Skip to content
Draft
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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,10 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper.
scratch buffer of at most `XCL_SPLIT_SCRATCH_MB` (default 256); the chains of one recording
share it, and `XCL_SPLIT_SCRATCH_TOTAL_MB` (default 384) bounds what all recordings not yet
reset hold together (past it a dispatch runs in smaller slabs).
- The pipeline (`xcl-pso*`) and shader compiler (`xcl-dxc*`) workers run below the normal
priority, so the game's own threads go first; the worker of a pipeline a game thread waits for,
and the compile it waits for, go up to normal for as long as it does.
`XCL_LOW_PRIORITY_WORKERS=0` keeps them all at normal priority.
- Huge pipelines (translated DXIL of `XCL_HUGE_PSO_BYTES` or more, default 262144) built on the
background `xcl-pso*` workers take turns in the driver's compiler: `XCL_HUGE_PSO_CONCURRENCY`
at once (default 1, maximum 64). Pipelines of 4 MiB or more use a separate one-wide lane so
Expand Down
122 changes: 120 additions & 2 deletions crates/xcl/src/gpu/recomp/dxc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,34 @@ mod queue_tests {
}
}

#[test]
fn a_running_compile_is_raised_when_a_title_thread_comes_to_want_it() {
use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL};
if !low_priority_workers() {
return;
}
let wanted = Arc::new(AtomicBool::new(false));
let check = wanted.clone();
std::thread::spawn(move || unsafe {
let priority = || GetThreadPriority(GetCurrentThread());
lower_this_worker();
assert_eq!(priority(), THREAD_PRIORITY_BELOW_NORMAL, "a worker starts below normal");
let running = RunningCompile::start(Box::new(move || check.load(Ordering::Acquire)));
raise_wanted();
assert_eq!(priority(), THREAD_PRIORITY_BELOW_NORMAL, "nobody waits for it yet");
wanted.store(true, Ordering::Release);
raise_wanted();
assert_eq!(priority(), THREAD_PRIORITY_NORMAL, "raised once wanted");
drop(running);
assert_eq!(priority(), THREAD_PRIORITY_BELOW_NORMAL, "back below normal for the next compile");
let wanted_at_start = RunningCompile::start(Box::new(|| true));
assert_eq!(priority(), THREAD_PRIORITY_NORMAL, "a compile wanted when it starts runs at normal");
drop(wanted_at_start);
})
.join()
.unwrap();
}

#[test]
fn wanted_dxc_jobs_overtake_background_fifo() {
let mut jobs = VecDeque::from([
Expand Down Expand Up @@ -752,8 +780,10 @@ const WANTED_AT_ONCE: usize = 6;
/// but one, `XCL_DXC_THREADS` to choose. Memory is what `wait_for_memory` watches: a retail
/// pack's biggest translations take ~0.7 GB in DXC (a typical one 0.1–0.3 GB). The cap used
/// to be 6, which left most of a 16-thread CPU idle while a title with ~24 000 shaders
/// compiled for half an hour. (Normal priority: a title thread can wait for a pipeline –
/// `resolve_wait`, a compute pipeline's first bind – and must not wait behind its own threads.)
/// compiled for half an hour. (Below the normal priority, `idle_priority`, but a title thread
/// can wait for a pipeline – `resolve_wait`, a compute pipeline's first bind – and must not wait
/// behind its own threads: the worker of a build it waits for, and the compile that worker
/// waits for, are raised to normal while it does – `pso_async::Build::want`, `raise_wanted`.)
pub fn compile_threads() -> usize {
static N: OnceLock<usize> = OnceLock::new();
*N.get_or_init(|| {
Expand Down Expand Up @@ -841,6 +871,92 @@ pub fn wait_for_memory(wanted: &Wanted) -> MemorySlot {
MemorySlot
}

/// Whether the compile workers (these and the pipeline workers that feed them) run below the
/// normal priority while no title thread waits for their work. They are a thread for every core
/// but one each, at the title's own priority: a world's shader stream took cores from the title's
/// threads that the frame waited for. `XCL_LOW_PRIORITY_WORKERS=0`: normal priority, as before.
pub fn low_priority_workers() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var("XCL_LOW_PRIORITY_WORKERS").map_or(true, |v| v.trim() != "0"))
}

/// A compile worker's priority while nobody waits for its work (`low_priority_workers`).
pub fn idle_priority() -> windows_sys::Win32::System::Threading::THREAD_PRIORITY {
use windows_sys::Win32::System::Threading::{THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL};
if low_priority_workers() { THREAD_PRIORITY_BELOW_NORMAL } else { THREAD_PRIORITY_NORMAL }
}

/// The calling compile worker starts at `idle_priority`.
pub fn lower_this_worker() {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority};
if low_priority_workers() {
unsafe { SetThreadPriority(GetCurrentThread(), idle_priority()) };
}
}

/// Thread `thread` (an id) at `priority`.
pub fn set_thread_priority(thread: u32, priority: windows_sys::Win32::System::Threading::THREAD_PRIORITY) {
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_SET_LIMITED_INFORMATION};
unsafe {
let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, thread);
if !h.is_null() {
SetThreadPriority(h, priority);
CloseHandle(h);
}
}
}

/// The compiles running below the normal priority: the worker's thread id and whether its job
/// is wanted (`raise_wanted`).
static RUNNING: Mutex<Vec<(u32, Wanted)>> = Mutex::new(Vec::new());

/// A title thread came to wait for a pipeline: the running compiles now wanted go on at the
/// normal priority (a compile started before anyone waited for it ran below it).
pub fn raise_wanted() {
use windows_sys::Win32::System::Threading::THREAD_PRIORITY_NORMAL;
let mut running = RUNNING.lock().unwrap_or_else(|e| e.into_inner());
running.retain(|(thread, wanted)| {
let now = wanted();
if now {
set_thread_priority(*thread, THREAD_PRIORITY_NORMAL);
}
!now
});
}

/// A compile on this worker, below the normal priority unless wanted now (`raise_wanted`
/// raises it later); back at `idle_priority` when it ends.
struct RunningCompile(Option<u32>);

impl RunningCompile {
fn start(wanted: Wanted) -> Self {
use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_NORMAL};
if !low_priority_workers() {
return Self(None);
}
let me = unsafe { GetCurrentThreadId() };
let mut running = RUNNING.lock().unwrap_or_else(|e| e.into_inner());
if wanted() {
unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) };
} else {
running.push((me, wanted));
}
Self(Some(me))
}
}

impl Drop for RunningCompile {
fn drop(&mut self) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority};
let Some(me) = self.0 else { return };
// (under the lock: `raise_wanted` does not raise this thread after it)
let mut running = RUNNING.lock().unwrap_or_else(|e| e.into_inner());
running.retain(|(thread, _)| *thread != me);
unsafe { SetThreadPriority(GetCurrentThread(), idle_priority()) };
}
}

/// DXC workers (`compile_threads`, each with its own compiler and a `DXC_STACK` stack), started
/// on first use; callers wait for their job.
fn pool() -> &'static Arc<CompileQueue> {
Expand All @@ -852,11 +968,13 @@ fn pool() -> &'static Arc<CompileQueue> {
queue.workers.fetch_add(1, Ordering::Release);
if std::thread::Builder::new().name(format!("xcl-dxc-{k}")).stack_size(DXC_STACK).spawn(move || {
let _worker = CompileWorker(worker_queue.clone());
lower_this_worker();
loop {
let job = worker_queue.take();
let Job { src, entry, profile, extra, reply, wanted, queue_stall } = job;
let _slot = wait_for_memory(&wanted);
drop(queue_stall);
let _running = RunningCompile::start(wanted);
let extra: Vec<&str> = extra.iter().map(|s| s.as_str()).collect();
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _stall = crate::stall::span(crate::stall::StallKind::DxcCompile);
Expand Down
92 changes: 54 additions & 38 deletions crates/xcl/src/hle/d3d12x/pso_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,9 @@ struct Demand {
ahead: bool,
/// thread id of the preload worker (lowest priority) building it, 0 = none
preload_thread: u32,
/// thread id of the normal worker (below-normal priority: `dxc::idle_priority`) building
/// it, 0 = none
normal_thread: u32,
}

thread_local! {
Expand Down Expand Up @@ -411,25 +414,54 @@ pub(super) fn build_parks() {
struct RunningBuild<'a> {
build: &'a Build,
preload: bool,
/// a normal worker below the normal priority (`note_worker`)
normal: bool,
}

impl Drop for RunningBuild<'_> {
fn drop(&mut self) {
if self.preload {
if self.preload || self.normal {
// (under the lock: `want` does not raise this thread after it)
let mut demand = self.build.demand.lock().unwrap();
demand.preload_thread = 0;
if self.preload {
demand.preload_thread = 0;
} else {
demand.normal_thread = 0;
}
if self.build.wanted.load(Ordering::Acquire) {
unsafe {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST};
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
let idle = if self.preload { THREAD_PRIORITY_LOWEST } else { crate::gpu::recomp::dxc::idle_priority() };
SetThreadPriority(GetCurrentThread(), idle);
}
}
}
BUILDING.with(|b| *b.borrow_mut() = None);
}
}

/// This worker starts `build`: it is noted on the build (`Demand`), so that a title thread that
/// comes to wait for it raises it (`Build::want`), and raised now if one already waits. Whether
/// it is a preload worker, and whether a normal worker below the normal priority.
fn note_worker(build: &Build) -> (bool, bool) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_NORMAL};
let preload = PRELOAD_WORKER.get();
let normal = !preload && NORMAL_WORKER.get() && crate::gpu::recomp::dxc::low_priority_workers();
if preload || normal {
let mut d = build.demand.lock().unwrap();
let me = unsafe { GetCurrentThreadId() };
if preload {
d.preload_thread = me;
} else {
d.normal_thread = me;
}
if build.wanted.load(Ordering::Acquire) {
unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) };
}
}
(preload, normal)
}

struct RestoreBuilding(Option<Arc<Build>>);

impl Drop for RestoreBuilding {
Expand Down Expand Up @@ -461,18 +493,10 @@ fn run_job(job: Job) -> usize {

/// A worker's pipeline build (`preload`: by one of the lowest-priority workers).
fn run_build(build: &Arc<Build>, job: Job) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_NORMAL};
let preload = PRELOAD_WORKER.get();
BUILDING.with(|b| *b.borrow_mut() = Some(build.clone()));
if preload {
let mut d = build.demand.lock().unwrap();
d.preload_thread = unsafe { GetCurrentThreadId() };
if build.wanted.load(Ordering::Acquire) {
unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) };
}
}
let (preload, normal) = note_worker(build);
let real = {
let _running = RunningBuild { build, preload };
let _running = RunningBuild { build, preload, normal };
run_timed_job(build, job)
};
complete(build, real);
Expand Down Expand Up @@ -617,7 +641,9 @@ impl Build {
d.waiters += 1;
if d.waiters == 1 {
self.wanted.store(true, Ordering::Release);
Self::set_priority(d, windows_sys::Win32::System::Threading::THREAD_PRIORITY_NORMAL);
Self::set_priority(d, true);
// and the compile its worker waits for, if one runs
crate::gpu::recomp::dxc::raise_wanted();
}
}

Expand All @@ -632,7 +658,7 @@ impl Build {
d.waiters = d.waiters.saturating_sub(1);
if d.waiters == 0 {
self.wanted.store(false, Ordering::Release);
Self::set_priority(&d, windows_sys::Win32::System::Threading::THREAD_PRIORITY_LOWEST);
Self::set_priority(&d, false);
}
}

Expand All @@ -645,19 +671,15 @@ impl Build {
}
}

/// The preload worker building it, if one does, at `priority` (under the `demand` lock: the
/// worker does not end its build meanwhile).
fn set_priority(d: &Demand, priority: windows_sys::Win32::System::Threading::THREAD_PRIORITY) {
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_SET_LIMITED_INFORMATION};
if d.preload_thread == 0 {
return;
}
unsafe {
let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, d.preload_thread);
if !h.is_null() {
SetThreadPriority(h, priority);
CloseHandle(h);
/// The worker building it, if one does, at the normal priority when `wanted`, else back at
/// its own (a preload worker's lowest, a normal worker's `dxc::idle_priority`) (under the
/// `demand` lock: the worker does not end its build meanwhile).
fn set_priority(d: &Demand, wanted: bool) {
use windows_sys::Win32::System::Threading::{THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL};
let idle = crate::gpu::recomp::dxc::idle_priority();
for (thread, own) in [(d.preload_thread, THREAD_PRIORITY_LOWEST), (d.normal_thread, idle)] {
if thread != 0 {
crate::gpu::recomp::dxc::set_thread_priority(thread, if wanted { THREAD_PRIORITY_NORMAL } else { own });
}
}
}
Expand Down Expand Up @@ -4007,6 +4029,7 @@ fn start_normal_workers() -> bool {
let worker = q.worker_between(Priority::BoundSoon, Priority::Foreground);
if std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || {
NORMAL_WORKER.set(true);
crate::gpu::recomp::dxc::lower_this_worker();
worker.run();
}).is_ok() {
started += 1;
Expand Down Expand Up @@ -4061,6 +4084,7 @@ fn spawn_normal_helper(k: usize) {
}
let spawned = std::thread::Builder::new().name(format!("xcl-pso-h{k}")).stack_size(64 << 20).spawn(move || {
NORMAL_WORKER.set(true);
crate::gpu::recomp::dxc::lower_this_worker();
let mut retired = false;
worker.run_while(|| {
retired = retire_normal_helper();
Expand Down Expand Up @@ -4111,17 +4135,9 @@ fn start_preload_workers() -> bool {
}

fn run_reserved_rebuild(build: Arc<Build>, recipe: Recipe) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_NORMAL};
let preload = PRELOAD_WORKER.get();
BUILDING.with(|b| *b.borrow_mut() = Some(build.clone()));
if preload {
let mut demand = build.demand.lock().unwrap();
demand.preload_thread = unsafe { GetCurrentThreadId() };
if build.wanted.load(Ordering::Acquire) {
unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) };
}
}
let _running = RunningBuild { build: &build, preload };
let (preload, normal) = note_worker(&build);
let _running = RunningBuild { build: &build, preload, normal };
let _ = rebuild_reserved(&build, &recipe);
}

Expand Down
Loading