diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 07c1fa4b..26065392 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -19366,20 +19366,59 @@ fn deblock_plane_span( } }); } -thread_local! { - /// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a - /// pre-CDEF snapshot of all three planes, a post-deblock snapshot when - /// loop restoration is active, and a fresh LR destination per plane -- - /// freshly allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K, - /// so every sample written also takes a first-touch page fault. The - /// buffers are handed back here instead and refilled in place. - static PLANE_SCRATCH: std::cell::RefCell>> = - const { std::cell::RefCell::new(Vec::new()) }; +/// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a +/// pre-CDEF snapshot of all three planes, a post-deblock snapshot when loop +/// restoration is active, and a fresh LR destination per plane -- freshly +/// allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K, so every +/// sample written also takes a first-touch page fault. The buffers are handed +/// back here instead and refilled in place. +/// +/// lane-memfix: PROCESS-WIDE, not one stash per thread. These buffers do not +/// stay on one thread: the frame thread allocates the snapshots and a filter +/// worker returns them ([`pipe_run_lr`] swaps the picture's pre-LR planes +/// into the pool from whichever worker ran it), so a per-thread pool leaked +/// whole-plane buffers into every worker it touched -- 19 MB a set, times +/// every pool thread the decode ever created. One shared pool with a hard +/// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how +/// many threads cycle through it; anything over the cap is freed. +static PLANE_SCRATCH: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); + +/// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K +/// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in +/// flight cycle through far fewer. +const SCRATCH_CAP: usize = 32; + +/// Takes a pooled buffer for a caller that wants `n` samples, best-fit by +/// CAPACITY so a chroma-sized request does not permanently promote a +/// luma-sized allocation (every pooled buffer would drift to the largest +/// size otherwise). `None` when the pool is empty. +fn scratch_take(n: usize) -> Option> { + let mut p = PLANE_SCRATCH.lock().unwrap(); + if p.is_empty() { + return None; + } + let fit = p + .iter() + .enumerate() + .filter(|(_, v)| v.capacity() >= n) + .min_by_key(|(_, v)| v.capacity()) + .map(|(i, _)| i); + let i = match fit { + Some(i) => i, + // Nothing big enough: grow the largest rather than a small one. + None => p + .iter() + .enumerate() + .max_by_key(|(_, v)| v.capacity()) + .map(|(i, _)| i) + .expect("the pool is not empty"), + }; + Some(p.swap_remove(i)) } /// A pooled buffer holding a copy of `src`. fn scratch_from(src: &[u16]) -> Vec { - let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default(); + let mut v = scratch_take(src.len()).unwrap_or_default(); v.clear(); v.extend_from_slice(src); v @@ -19387,7 +19426,7 @@ fn scratch_from(src: &[u16]) -> Vec { /// An empty pooled buffer, for a caller that fills it itself. fn scratch_empty() -> Vec { - let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default(); + let mut v = scratch_take(0).unwrap_or_default(); v.clear(); v } @@ -19396,7 +19435,7 @@ fn scratch_empty() -> Vec { /// for a caller that writes every element it later reads (lane-copy: the /// post-deblock snapshot writes 4 rows in 64 and reads no other). fn scratch_sized(n: usize) -> Vec { - let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default(); + let mut v = scratch_take(n).unwrap_or_default(); if v.len() > n { v.truncate(n); } else if v.len() < n { @@ -19458,8 +19497,13 @@ fn crop_owned(plane: PlaneBuf<'_>, w: usize, h: usize) -> Vec { } /// Hands a buffer back to the pool; the capacity is what is worth keeping. +/// Over [`SCRATCH_CAP`] the buffer is dropped (freed) instead -- the cap is +/// what keeps a pool shared by every thread from being an unbounded stash. fn scratch_return(v: Vec) { - PLANE_SCRATCH.with(|p| p.borrow_mut().push(v)); + let mut p = PLANE_SCRATCH.lock().unwrap(); + if p.len() < SCRATCH_CAP { + p.push(v); + } } /// One CDEF mi-row band, as a real function rather than the body of the diff --git a/crates/ec-av1/src/par.rs b/crates/ec-av1/src/par.rs index b40a12f4..e16ac1d1 100644 --- a/crates/ec-av1/src/par.rs +++ b/crates/ec-av1/src/par.rs @@ -202,6 +202,11 @@ struct PoolQ { /// Jobs handed to a worker and not yet finished. busy: usize, closed: bool, + /// lane-memfix: the pool's threads live behind the same lock as its + /// queue, because the thread that has to GROW the pool is whichever one + /// submits -- including one of the pool's own workers (see + /// [`pool_push`]). Joined by [`Pool::drop`] on the owning thread. + handles: Vec>, } struct PoolInner { @@ -211,10 +216,13 @@ struct PoolInner { struct Pool { inner: std::sync::Arc, - handles: Vec>, } -fn pool_worker(inner: &PoolInner) { +fn pool_worker(inner: &std::sync::Arc) { + // lane-memfix: a job this worker runs submits its own sub-batches to THIS + // pool rather than opening a second one on the worker's thread-local -- + // see [`Batch::submit`]. + ON_POOL.with(|c| *c.borrow_mut() = Some(std::sync::Arc::clone(inner))); let mut q = inner.q.lock().unwrap(); loop { if let Some(job) = q.jobs.pop_front() { @@ -228,6 +236,7 @@ fn pool_worker(inner: &PoolInner) { continue; } if q.closed { + POOL_THREADS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); return; } q = inner.cv.wait(q).unwrap(); @@ -242,46 +251,66 @@ impl Pool { jobs: std::collections::VecDeque::new(), busy: 0, closed: false, + handles: Vec::new(), }), cv: std::sync::Condvar::new(), }), - handles: Vec::new(), } } +} - /// Queues `job` and makes sure a worker is free for it: the pool grows to - /// `busy + queued` threads and never shrinks, so a submitted job always - /// starts, even when every other running job is blocked waiting for it. - /// `class` names the submitting site of the job that grows the pool, so a - /// profiler attributes the thread to the work that created it - /// (`ec-av1-frame`, `ec-av1-recon`, `ec-av1-filter`). One pool serves - /// every class a thread submits, so later classes on the same pool reuse - /// the threads an earlier one named. - fn push(&mut self, job: Job, class: &'static str) { - let want = { - let mut q = self.inner.q.lock().unwrap(); - q.jobs.push_back(job); - q.busy + q.jobs.len() - }; - while self.handles.len() < want { - let inner = std::sync::Arc::clone(&self.inner); - let name = format!("{class}-{}", self.handles.len()); - self.handles.push( - std::thread::Builder::new() - .name(name) - .spawn(move || pool_worker(&inner)) - .expect("spawning an ec-av1 pool worker"), - ); - } - self.inner.cv.notify_one(); +/// Queues `job` on `inner` and makes sure a worker is free for it: the pool +/// grows to `busy + queued` threads, so a submitted job always starts, even +/// when every other running job is blocked waiting for it. +/// `class` names the submitting site of the job that grows the pool, so a +/// profiler attributes the thread to the work that created it +/// (`ec-av1-frame`, `ec-av1-recon`, `ec-av1-filter`). One pool serves every +/// class submitted to it, so later classes reuse the threads an earlier one +/// named. +/// +/// lane-memfix: the pool only grows for work that is queued and unserved AT +/// THAT MOMENT, and a pool worker submits back into its own pool, so the +/// process-wide thread count is the peak of `busy + queued` over the whole +/// job tree -- not the product of one pool per nesting level (a filter band +/// job used to open a third-level pool on the worker running it, and none of +/// those pools ever shrank: 1038 threads at (16,4,2)). +fn pool_push(inner: &std::sync::Arc, job: Job, class: &'static str) { + let mut q = inner.q.lock().unwrap(); + q.jobs.push_back(job); + let want = q.busy + q.jobs.len(); + while q.handles.len() < want { + let inner = std::sync::Arc::clone(inner); + let name = format!("{class}-{}", q.handles.len()); + q.handles.push( + std::thread::Builder::new() + .name(name) + .spawn(move || pool_worker(&inner)) + .expect("spawning an ec-av1 pool worker"), + ); + POOL_THREADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } + drop(q); + inner.cv.notify_one(); +} + +/// Live threads across every ec-av1 pool -- what the bounded-growth test +/// asserts on, and what a profiler counts as `ec-av1-*`. +static POOL_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +#[cfg(test)] +pub(crate) fn pool_threads() -> usize { + POOL_THREADS.load(std::sync::atomic::Ordering::Relaxed) } impl Drop for Pool { fn drop(&mut self) { - self.inner.q.lock().unwrap().closed = true; + let handles = { + let mut q = self.inner.q.lock().unwrap(); + q.closed = true; + std::mem::take(&mut q.handles) + }; self.inner.cv.notify_all(); - for h in self.handles.drain(..) { + for h in handles { let _ = h.join(); } } @@ -292,6 +321,12 @@ thread_local! { /// when the thread exits (the process's main thread may skip that /// destructor, in which case the idle workers die with the process). static POOL: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// lane-memfix: set on a pool WORKER for its whole life -- the pool it + /// serves. A job submitting a sub-batch (a pipeline stage banding itself + /// across the filter pool) then reuses that pool instead of opening a + /// nested one of its own. + static ON_POOL: std::cell::RefCell>> = + const { std::cell::RefCell::new(None) }; } struct BatchState { @@ -350,10 +385,26 @@ impl<'a> Batch<'a> { // for `left == 0`), and `Batch<'a>` cannot outlive `'a`, so the // laundered lifetime is never observed past the real one. let job: Job = unsafe { std::mem::transmute::, Job>(job) }; - POOL.with(|p| { - let mut p = p.borrow_mut(); - p.get_or_insert_with(Pool::new).push(job, self.class); - }); + // lane-memfix: on a pool worker, back into the pool it is serving; on + // any other thread, this thread's own pool. + // + // No deadlock: a job blocked in `Batch::drop` is counted in `busy`, + // so `pool_push` grows the pool by one thread for every queued job + // that has no idle worker -- the child of a blocked parent always + // gets a thread. The only waits inside a job are on its own sub-batch + // (same rule, one level deeper) and on wavefront row atomics / + // `PipeSync` counters, which are published by jobs that are already + // running, never by a job still in the queue. + let on = ON_POOL.with(|c| c.borrow().clone()); + match on { + Some(inner) => pool_push(&inner, job, self.class), + None => POOL.with(|p| { + let mut p = p.borrow_mut(); + let inner = std::sync::Arc::clone(&p.get_or_insert_with(Pool::new).inner); + drop(p); + pool_push(&inner, job, self.class); + }), + } } } diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index d2e9b4e9..31d523cc 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -6363,6 +6363,58 @@ mod tests { } } + /// lane-memfix: the pool grows to the peak of `busy + queued` over the + /// job tree and stops there. Before, a job running on a pool worker + /// opened a SECOND pool on that worker's own thread-local -- one level + /// per pipeline stage, none of them ever shrinking -- which is how a 4K + /// decode at `(16, 4, 2)` reached 1038 live threads. Two decodes of the + /// same stream: the count stays inside the composed setting and the + /// second decode adds nothing (the ratchet is what cost the memory). + #[test] + fn the_worker_pool_stays_bounded_across_repeated_threaded_decodes() { + const NAME: &str = "the_worker_pool_stays_bounded_across_repeated_threaded_decodes"; + let _gate_lock = lock_gate_counters(); + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join("superres_alltools_sb128_320x180.obu"); + let stream = std::fs::read(&path) + .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); + crate::par::set_filter_threads(4); + crate::par::set_recon_threads(2); + let mut counts = [0usize; 2]; + let mut frames = [0usize; 2]; + for (i, slot) in counts.iter_mut().enumerate() { + let mut n = 0usize; + let r = decode_stream_with_threads(&stream, 4, |_, _, _| { + n += 1; + Ok(()) + }); + if let Err(e) = r { + crate::par::set_filter_threads(1); + crate::par::set_recon_threads(1); + panic!("{NAME}: refused on decode {i}: {e}"); + } + frames[i] = n; + *slot = crate::par::pool_threads(); + } + crate::par::set_filter_threads(1); + crate::par::set_recon_threads(1); + assert!(frames[0] > 1, "{NAME}: the fixture decoded {} frames, so nothing was threaded", frames[0]); + // 4 frame workers x (recon 2 + filter 4) plus the two in-flight + // slots `stream.rs` allows over the thread count, with room for the + // show jobs -- 1038 was three orders past this. + assert!( + counts[1] <= 4 * (2 + 4) + 2 * 4, + "{NAME}: the pool grew to {} threads at 4 frame / 4 filter / 2 recon", + counts[1] + ); + assert_eq!( + counts[0], counts[1], + "{NAME}: a second decode of the same stream grew the pool from {} to {} threads", + counts[0], counts[1] + ); + } + #[test] fn a_real_stream_filters_identically_with_one_and_four_filter_threads() { const NAME: &str = "a_real_stream_filters_identically_with_one_and_four_filter_threads";