diff --git a/crates/automation/src/gpu.rs b/crates/automation/src/gpu.rs index a0451ea765..b257fccdd7 100644 --- a/crates/automation/src/gpu.rs +++ b/crates/automation/src/gpu.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use photocraft_doc::{DocId, Document, Rect}; -use photocraft_gpu::context::{NativeContext, NativeContextOptions}; +use photocraft_gpu::context::{AbandonedRequest, GpuContextError, NativeContext, NativeContextOptions}; use photocraft_gpu::{Compositor, readback}; use photocraft_io::{BandRenderer, IoError, RenderBand, RenderError}; @@ -22,6 +22,8 @@ pub struct GpuRenderer { init_error: Option, diagnostics: Vec, adapter_reported: bool, + /// This renderer's GPU request that timed out, still running inside the driver. + abandoned: Option, } impl GpuRenderer { @@ -43,6 +45,7 @@ impl GpuRenderer { init_error: None, diagnostics: Vec::new(), adapter_reported: false, + abandoned: None, } } @@ -57,6 +60,7 @@ impl GpuRenderer { init_error: None, diagnostics: Vec::new(), adapter_reported: false, + abandoned: None, } } @@ -99,6 +103,9 @@ impl GpuRenderer { } }, Err(e) => { + if let GpuContextError::TimedOut { pending, .. } = &e { + self.abandoned = Some(pending.clone()); + } let msg = format!("no GPU adapter available: {e}"); self.push_diag(msg.clone()); self.init_error = Some(msg.clone()); @@ -149,15 +156,14 @@ impl GpuRenderer { } impl Drop for GpuRenderer { - /// A request that timed out left its thread inside the driver. Give it time to finish, so the - /// process does not exit under it: Lavapipe then crashes the process. A driver that really - /// hangs costs this wait once, after its request already failed. + /// This renderer's request that timed out left its thread inside the driver. Give it time to + /// finish, so the process does not exit under it: Lavapipe then crashes the process. A driver + /// that really hangs costs this wait once, after its request already failed. Past the limit the + /// drop returns anyway and accepts that risk rather than hanging. fn drop(&mut self) { - if self.context.is_none() - && self.init_error.is_some() - && let Some(timeout) = self.options.timeout - { - NativeContext::wait_for_abandoned_requests(timeout.max(ABANDONED_REQUEST_WAIT)); + if let Some(pending) = self.abandoned.take() { + let timeout = self.options.timeout.unwrap_or_default(); + pending.wait(timeout.max(ABANDONED_REQUEST_WAIT)); } } } diff --git a/crates/automation/tests/it/gpu_backend.rs b/crates/automation/tests/it/gpu_backend.rs index 5d2d07ff7d..43769e51e0 100644 --- a/crates/automation/tests/it/gpu_backend.rs +++ b/crates/automation/tests/it/gpu_backend.rs @@ -293,7 +293,10 @@ mod tests { let mut gpu_renderer = GpuRenderer::with_options(options); let doc = make_test_doc(16, 16, SampleType::U8); let res = gpu_renderer.render_bands(&doc, doc.bounds(), 16, &photocraft_raster::Interrupt::NONE, &mut |_| Ok::<(), photocraft_io::IoError>(())); - assert!(matches!(res, Err(photocraft_io::RenderError::Unavailable(_))), "a zero timeout must leave the renderer unavailable: {res:?}"); + assert!( + matches!(&res, Err(photocraft_io::RenderError::Unavailable(msg)) if msg.contains("timed out")), + "a zero timeout must time the request out: {res:?}" + ); drop(gpu_renderer); assert!(NativeContext::wait_for_abandoned_requests(std::time::Duration::ZERO), "the drop returned with the request still inside the driver"); diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs index b5452cc3bf..d6083fbfe2 100644 --- a/crates/gpu/src/context.rs +++ b/crates/gpu/src/context.rs @@ -18,6 +18,10 @@ pub enum GpuContextError { Compositor(String), #[error("GPU device was lost: {0}")] DeviceLost(String), + /// Initialization did not finish within [`NativeContextOptions::timeout`]. Its thread is + /// still running inside wgpu and the driver; `pending` tells when it has finished. + #[error("no suitable GPU adapter found: timed out after {timeout:?} requesting GPU adapter/device")] + TimedOut { timeout: Duration, pending: AbandonedRequest }, } impl From for GpuContextError { @@ -43,8 +47,11 @@ pub struct NativeContextOptions { /// If initialization times out, the background initialization thread cannot be forcibly terminated /// in standard Rust and continues detached until wgpu completes or fails. Callers should avoid /// repeatedly requesting initialization in tight loops when timeouts occur to prevent thread and - /// resource leaks. Before the process exits, call [`NativeContext::wait_for_abandoned_requests`]: - /// exiting while that thread is still inside the driver can crash the process. + /// resource leaks. Exiting while that thread is still inside the driver can crash the process, + /// so wait for it first: [`AbandonedRequest::wait`] on the one in + /// [`GpuContextError::TimedOut`], or [`NativeContext::wait_for_abandoned_requests`] for all. + /// Either returns `false` when the thread is still running at the limit; the process then + /// either waits longer or exits accepting that risk. pub timeout: Option, } @@ -135,26 +142,11 @@ impl NativeContext { }; if let Some(timeout) = options.timeout { - let (tx, rx) = std::sync::mpsc::channel(); - let request = Arc::new(InitThread::default()); - let thread_request = Arc::clone(&request); - let thread_res = std::thread::Builder::new().name("pc_gpu_init".into()).spawn(move || { - // Declared first so it is dropped last: an abandoned request counts as running - // until the context nobody waits for any more has been dropped too. - let _finish = FinishOnDrop(thread_request); - let res = init_work(); - let _ = tx.send(res); - }); - match thread_res { - Ok(_handle) => match rx.recv_timeout(timeout) { - Ok(res) => res, - Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { - request.abandon(); - Err(GpuContextError::NoAdapter(format!("timed out after {timeout:?} requesting GPU adapter/device"))) - } - Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(GpuContextError::NoAdapter("GPU initialization thread disconnected".into())), - }, - Err(e) => Err(GpuContextError::NoAdapter(format!("failed to spawn GPU initialization thread: {e}"))), + match run_with_timeout("pc_gpu_init", timeout, init_work) { + Ok(res) => res, + Err(InitWait::TimedOut(pending)) => Err(GpuContextError::TimedOut { timeout, pending }), + Err(InitWait::Disconnected) => Err(GpuContextError::NoAdapter("GPU initialization thread disconnected".into())), + Err(InitWait::Spawn(e)) => Err(GpuContextError::NoAdapter(format!("failed to spawn GPU initialization thread: {e}"))), } } else { init_work() @@ -167,24 +159,12 @@ impl NativeContext { /// A request that timed out leaves its thread inside wgpu and the driver. If the process /// exits meanwhile, the driver's state is torn down under that thread, and software drivers /// such as Lavapipe crash the whole process (a SIGSEGV or heap corruption after every test - /// already passed). Call this before exiting after a timed-out request. + /// already passed). Call this before exiting after a timed-out request. To wait for one + /// request only, use the [`AbandonedRequest`] in its [`GpuContextError::TimedOut`]. + /// + /// Returns `false` when one is still running at `limit`; see [`NativeContextOptions::timeout`]. pub fn wait_for_abandoned_requests(limit: Duration) -> bool { - // A limit too far ahead to represent waits as long as it takes. - let deadline = Instant::now().checked_add(limit); - let mut running = ABANDONED.running.lock().unwrap_or_else(PoisonError::into_inner); - while *running > 0 { - running = match deadline { - Some(deadline) => { - let left = deadline.saturating_duration_since(Instant::now()); - if left.is_zero() { - return false; - } - ABANDONED.done.wait_timeout(running, left).unwrap_or_else(PoisonError::into_inner).0 - } - None => ABANDONED.done.wait(running).unwrap_or_else(PoisonError::into_inner), - }; - } - true + wait_until(&ABANDONED.running, &ABANDONED.done, limit, |running| *running == 0) } /// Build a new [`Compositor`] wired to this context's device and health flag. @@ -259,6 +239,90 @@ impl NativeContext { } } +/// Why [`run_with_timeout`] returned without the work's result. +enum InitWait { + TimedOut(AbandonedRequest), + Disconnected, + Spawn(std::io::Error), +} + +/// Run `work` on a thread named `name` and wait up to `timeout` for its result. On a timeout the +/// thread keeps running, and the returned [`AbandonedRequest`] tells when it has finished. +fn run_with_timeout(name: &str, timeout: Duration, work: F) -> Result +where + T: Send + 'static, + F: FnOnce() -> T + Send + 'static, +{ + // A rendezvous channel: a result is either handed to this thread or, once it stopped + // waiting, dropped on the worker before the worker counts as finished. + let (tx, rx) = std::sync::mpsc::sync_channel(0); + let request = AbandonedRequest(Arc::new(InitThread::default())); + let thread_request = request.clone(); + let spawned = std::thread::Builder::new().name(name.into()).spawn(move || { + // Declared first so it is dropped last, after an unclaimed result. + let _finish = FinishOnDrop(thread_request); + let res = work(); + let _ = tx.send(res); + }); + if let Err(e) = spawned { + return Err(InitWait::Spawn(e)); + } + match rx.recv_timeout(timeout) { + Ok(res) => Ok(res), + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + request.0.abandon(); + // Stop taking the result, so the worker drops it itself. + drop(rx); + Err(InitWait::TimedOut(request)) + } + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(InitWait::Disconnected), + } +} + +/// Wait up to `limit` until `done` holds for the state behind `lock`, re-checking whenever `cv` +/// is notified. A limit too far ahead to represent waits as long as it takes. +fn wait_until(lock: &Mutex, cv: &Condvar, limit: Duration, done: impl Fn(&S) -> bool) -> bool { + let deadline = Instant::now().checked_add(limit); + let mut state = lock.lock().unwrap_or_else(PoisonError::into_inner); + while !done(&state) { + state = match deadline { + Some(deadline) => { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return false; + } + cv.wait_timeout(state, left).unwrap_or_else(PoisonError::into_inner).0 + } + None => cv.wait(state).unwrap_or_else(PoisonError::into_inner), + }; + } + true +} + +/// An initialization thread that [`NativeContext::request`] stopped waiting for after its +/// timeout, still running inside wgpu and the driver until it finishes. +#[derive(Clone)] +pub struct AbandonedRequest(Arc); + +impl AbandonedRequest { + /// Wait up to `limit` for this thread to finish. Returns `false` when it is still running; + /// see [`NativeContextOptions::timeout`]. + pub fn wait(&self, limit: Duration) -> bool { + wait_until(&self.0.state, &self.0.done, limit, |state| state.finished) + } + + /// Whether the thread has finished, including dropping a context nobody claimed. + pub fn is_finished(&self) -> bool { + self.0.state.lock().unwrap_or_else(PoisonError::into_inner).finished + } +} + +impl fmt::Debug for AbandonedRequest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("AbandonedRequest").field("finished", &self.is_finished()).finish() + } +} + /// How many initialization threads [`NativeContext::request`] gave up on are still running. struct Abandoned { running: Mutex, @@ -267,28 +331,36 @@ struct Abandoned { static ABANDONED: Abandoned = Abandoned { running: Mutex::new(0), done: Condvar::new() }; -/// One initialization thread: whether its request gave up on it, and whether it has finished. +#[derive(Default)] +struct ThreadState { + /// The request stopped waiting for the thread. + abandoned: bool, + /// The thread has finished. + finished: bool, +} + +/// One initialization thread and a condition variable notified when it finishes. #[derive(Default)] struct InitThread { - state: Mutex<(bool, bool)>, + state: Mutex, + done: Condvar, } impl InitThread { /// The request stopped waiting: count the thread in [`ABANDONED`] unless it already finished. fn abandon(&self) { let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); - let (abandoned, finished) = &mut *state; - if !*finished && !*abandoned { - *abandoned = true; + if !state.finished && !state.abandoned { + state.abandoned = true; *ABANDONED.running.lock().unwrap_or_else(PoisonError::into_inner) += 1; } } fn finish(&self) { let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); - let (abandoned, finished) = &mut *state; - *finished = true; - if *abandoned { + state.finished = true; + self.done.notify_all(); + if state.abandoned { let mut running = ABANDONED.running.lock().unwrap_or_else(PoisonError::into_inner); *running = running.saturating_sub(1); ABANDONED.done.notify_all(); @@ -297,10 +369,13 @@ impl InitThread { } /// Marks the initialization thread finished when it ends, also when it panics. -struct FinishOnDrop(Arc); +struct FinishOnDrop(AbandonedRequest); impl Drop for FinishOnDrop { fn drop(&mut self) { - self.0.finish(); + self.0.0.finish(); } } + +#[cfg(test)] +mod tests; diff --git a/crates/gpu/src/context/tests.rs b/crates/gpu/src/context/tests.rs new file mode 100644 index 0000000000..c945f94ba5 --- /dev/null +++ b/crates/gpu/src/context/tests.rs @@ -0,0 +1,53 @@ +//! The timeout around GPU initialization, with test-controlled work instead of a driver. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, mpsc}; +use std::time::Duration; + +use super::{InitWait, run_with_timeout}; + +const LONG: Duration = Duration::from_secs(60); + +#[test] +fn work_that_finishes_in_time_returns_its_result() { + assert!(matches!(run_with_timeout("t_in_time", LONG, || 7), Ok(7))); +} + +#[test] +fn a_timed_out_request_counts_as_running_until_its_work_finishes() { + let (release, released) = mpsc::channel::<()>(); + let res = run_with_timeout("t_abandoned", Duration::from_millis(10), move || released.recv().is_ok()); + let Err(InitWait::TimedOut(pending)) = res else { panic!("held work must time out") }; + assert!(!pending.is_finished()); + assert!(!pending.wait(Duration::from_millis(50)), "the wait returned while the work was still held"); + + release.send(()).unwrap(); + assert!(pending.wait(LONG), "the work finished but the wait never saw it"); + assert!(pending.is_finished()); +} + +/// A result that arrives after the timeout is dropped on the worker before it counts as +/// finished: a context's device must be gone before a waiter lets the process exit. +#[test] +fn an_unclaimed_result_is_dropped_before_the_request_finishes() { + struct SlowDrop(Arc); + impl Drop for SlowDrop { + fn drop(&mut self) { + std::thread::sleep(Duration::from_millis(50)); + self.0.store(true, Ordering::SeqCst); + } + } + + let dropped = Arc::new(AtomicBool::new(false)); + let (release, released) = mpsc::channel::<()>(); + let result_dropped = Arc::clone(&dropped); + let res = run_with_timeout("t_unclaimed", Duration::from_millis(10), move || { + let _ = released.recv(); + SlowDrop(result_dropped) + }); + let Err(InitWait::TimedOut(pending)) = res else { panic!("held work must time out") }; + + release.send(()).unwrap(); + assert!(pending.wait(LONG)); + assert!(dropped.load(Ordering::SeqCst), "the request finished before its unclaimed result was dropped"); +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 2beaedc233..730ff6b49b 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -153,7 +153,7 @@ use batch::{BATCH, batch_kernel, batch_op_words, batch_runs, op_words, run_start use consts::OP_UNIFORM; pub use consts::{ACC_FORMAT, CHUNK, FX_BUDGET, PAGE, PATTERN_BUDGET, PATTERN_IDLE_FRAMES, RESIDENT_BUDGET}; #[cfg(not(target_arch = "wasm32"))] -pub use context::{GpuContextError, NativeContext, NativeContextOptions}; +pub use context::{AbandonedRequest, GpuContextError, NativeContext, NativeContextOptions}; use convert::W; #[cfg(test)] use convert::{CONVERT_BATCH, colour_managed, convert_tile, convert_tiles, rgb_gray16_to_f16, rgb_gray32_to_f16}; diff --git a/crates/gpu/tests/it/init_timeout.rs b/crates/gpu/tests/it/init_timeout.rs index f22cca8814..13f93df8d7 100644 --- a/crates/gpu/tests/it/init_timeout.rs +++ b/crates/gpu/tests/it/init_timeout.rs @@ -14,10 +14,8 @@ fn a_timed_out_request_can_be_waited_for_before_exit() { let _gpu = GPU_LOCK.lock().unwrap_or_else(PoisonError::into_inner); let opts = NativeContextOptions { timeout: Some(Duration::ZERO), ..Default::default() }; let res = NativeContext::request(&opts); - assert!( - matches!(&res, Err(GpuContextError::NoAdapter(msg)) if msg.contains("timed out")), - "a zero timeout must give up before the adapter is ready: {res:?}" - ); - assert!(NativeContext::wait_for_abandoned_requests(Duration::from_secs(120)), "the abandoned initialization thread never finished"); + let Err(GpuContextError::TimedOut { pending, .. }) = &res else { panic!("a zero timeout must give up before the adapter is ready: {res:?}") }; + assert!(pending.wait(Duration::from_secs(120)), "the abandoned initialization thread never finished"); + assert!(pending.is_finished()); assert!(NativeContext::wait_for_abandoned_requests(Duration::ZERO), "a finished thread must not count as running"); }