From 2636658db6a6628601937c3230053ce83bae1a09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 02:13:18 +0300 Subject: [PATCH] perf(av1): one pool per job tree and a shared capped plane-scratch pool A filter band job opened a sub-pool on the worker running it, one level per pipeline stage, and no pool ever shrank: 1038 threads at (16,4,2). A job now submits back into the pool it is running on (`ON_POOL`), so the thread count is the peak of `busy + queued` over the whole job tree. `Pool`'s handles moved behind the queue lock because the thread that grows the pool is now whichever one submits. The whole-plane scratch pool was per thread while its buffers are not: the frame thread allocates the snapshots and a filter worker returns them, so ~19 MB a set leaked into every worker the decode touched. One process-wide pool, best-fit by capacity, hard-capped at 32 buffers. 4K peak RSS 9.33 GB -> 4.07 GB, peak threads 1053 -> 59, instructions:u +0.10% and page faults -30% on seg4k at (16,4,2). --- crates/ec-av1/src/decode.rs | 70 +++++++++++++++++---- crates/ec-av1/src/par.rs | 118 +++++++++++++++++++++++++----------- 2 files changed, 141 insertions(+), 47 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 6f7d1daa..4fcc9022 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -19336,20 +19336,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 @@ -19357,7 +19396,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 } @@ -19366,7 +19405,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 { @@ -19428,8 +19467,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..e048e264 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,65 @@ 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); + +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 +320,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 +384,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); + }), + } } }