One pool per job tree and a shared capped plane-scratch pool
Browse files at this commit2636658db6a6628601937c3230053ce83bae1a09Parent: 36b27a7- perf
- one pool per job tree and a shared capped plane-scratch pool
2 changed files +141 -47
- crates/ec-av1/src/decode.rs +57 -13
- crates/ec-av1/src/par.rs +84 -34
crates/ec-av1/src/decode.rsmodified+57 -13
| @@ -19336,20 +19336,59 @@ fn deblock_plane_span( | |||
| 19336 | } }); | 19336 | } }); |
| 19337 | } | 19337 | } |
| 19338 | 19338 | ||
| 19339 | -thread_local! { | 19339 | +/// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a |
| 19340 | - /// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a | 19340 | +/// pre-CDEF snapshot of all three planes, a post-deblock snapshot when loop |
| 19341 | - /// pre-CDEF snapshot of all three planes, a post-deblock snapshot when | 19341 | +/// restoration is active, and a fresh LR destination per plane -- freshly |
| 19342 | - /// loop restoration is active, and a fresh LR destination per plane -- | 19342 | +/// allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K, so every |
| 19343 | - /// freshly allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K, | 19343 | +/// sample written also takes a first-touch page fault. The buffers are handed |
| 19344 | - /// so every sample written also takes a first-touch page fault. The | 19344 | +/// back here instead and refilled in place. |
| 19345 | - /// buffers are handed back here instead and refilled in place. | 19345 | +/// |
| 19346 | - static PLANE_SCRATCH: std::cell::RefCell<Vec<Vec<u16>>> = | 19346 | +/// lane-memfix: PROCESS-WIDE, not one stash per thread. These buffers do not |
| 19347 | - const { std::cell::RefCell::new(Vec::new()) }; | 19347 | +/// stay on one thread: the frame thread allocates the snapshots and a filter |
| 19348 | +/// worker returns them ([`pipe_run_lr`] swaps the picture's pre-LR planes | ||
| 19349 | +/// into the pool from whichever worker ran it), so a per-thread pool leaked | ||
| 19350 | +/// whole-plane buffers into every worker it touched -- 19 MB a set, times | ||
| 19351 | +/// every pool thread the decode ever created. One shared pool with a hard | ||
| 19352 | +/// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how | ||
| 19353 | +/// many threads cycle through it; anything over the cap is freed. | ||
| 19354 | +static PLANE_SCRATCH: std::sync::Mutex<Vec<Vec<u16>>> = std::sync::Mutex::new(Vec::new()); | ||
| 19355 | + | ||
| 19356 | +/// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K | ||
| 19357 | +/// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in | ||
| 19358 | +/// flight cycle through far fewer. | ||
| 19359 | +const SCRATCH_CAP: usize = 32; | ||
| 19360 | + | ||
| 19361 | +/// Takes a pooled buffer for a caller that wants `n` samples, best-fit by | ||
| 19362 | +/// CAPACITY so a chroma-sized request does not permanently promote a | ||
| 19363 | +/// luma-sized allocation (every pooled buffer would drift to the largest | ||
| 19364 | +/// size otherwise). `None` when the pool is empty. | ||
| 19365 | +fn scratch_take(n: usize) -> Option<Vec<u16>> { | ||
| 19366 | + let mut p = PLANE_SCRATCH.lock().unwrap(); | ||
| 19367 | + if p.is_empty() { | ||
| 19368 | + return None; | ||
| 19369 | + } | ||
| 19370 | + let fit = p | ||
| 19371 | + .iter() | ||
| 19372 | + .enumerate() | ||
| 19373 | + .filter(|(_, v)| v.capacity() >= n) | ||
| 19374 | + .min_by_key(|(_, v)| v.capacity()) | ||
| 19375 | + .map(|(i, _)| i); | ||
| 19376 | + let i = match fit { | ||
| 19377 | + Some(i) => i, | ||
| 19378 | + // Nothing big enough: grow the largest rather than a small one. | ||
| 19379 | + None => p | ||
| 19380 | + .iter() | ||
| 19381 | + .enumerate() | ||
| 19382 | + .max_by_key(|(_, v)| v.capacity()) | ||
| 19383 | + .map(|(i, _)| i) | ||
| 19384 | + .expect("the pool is not empty"), | ||
| 19385 | + }; | ||
| 19386 | + Some(p.swap_remove(i)) | ||
| 19348 | } | 19387 | } |
| 19349 | 19388 | ||
| 19350 | /// A pooled buffer holding a copy of `src`. | 19389 | /// A pooled buffer holding a copy of `src`. |
| 19351 | fn scratch_from(src: &[u16]) -> Vec<u16> { | 19390 | fn scratch_from(src: &[u16]) -> Vec<u16> { |
| 19352 | - let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default(); | 19391 | + let mut v = scratch_take(src.len()).unwrap_or_default(); |
| 19353 | v.clear(); | 19392 | v.clear(); |
| 19354 | v.extend_from_slice(src); | 19393 | v.extend_from_slice(src); |
| 19355 | v | 19394 | v |
| @@ -19357,7 +19396,7 @@ fn scratch_from(src: &[u16]) -> Vec<u16> { | |||
| 19357 | 19396 | ||
| 19358 | /// An empty pooled buffer, for a caller that fills it itself. | 19397 | /// An empty pooled buffer, for a caller that fills it itself. |
| 19359 | fn scratch_empty() -> Vec<u16> { | 19398 | fn scratch_empty() -> Vec<u16> { |
| 19360 | - let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default(); | 19399 | + let mut v = scratch_take(0).unwrap_or_default(); |
| 19361 | v.clear(); | 19400 | v.clear(); |
| 19362 | v | 19401 | v |
| 19363 | } | 19402 | } |
| @@ -19366,7 +19405,7 @@ fn scratch_empty() -> Vec<u16> { | |||
| 19366 | /// for a caller that writes every element it later reads (lane-copy: the | 19405 | /// for a caller that writes every element it later reads (lane-copy: the |
| 19367 | /// post-deblock snapshot writes 4 rows in 64 and reads no other). | 19406 | /// post-deblock snapshot writes 4 rows in 64 and reads no other). |
| 19368 | fn scratch_sized(n: usize) -> Vec<u16> { | 19407 | fn scratch_sized(n: usize) -> Vec<u16> { |
| 19369 | - let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default(); | 19408 | + let mut v = scratch_take(n).unwrap_or_default(); |
| 19370 | if v.len() > n { | 19409 | if v.len() > n { |
| 19371 | v.truncate(n); | 19410 | v.truncate(n); |
| 19372 | } else if v.len() < n { | 19411 | } else if v.len() < n { |
| @@ -19428,8 +19467,13 @@ fn crop_owned(plane: PlaneBuf<'_>, w: usize, h: usize) -> Vec<u16> { | |||
| 19428 | } | 19467 | } |
| 19429 | 19468 | ||
| 19430 | /// Hands a buffer back to the pool; the capacity is what is worth keeping. | 19469 | /// Hands a buffer back to the pool; the capacity is what is worth keeping. |
| 19470 | +/// Over [`SCRATCH_CAP`] the buffer is dropped (freed) instead -- the cap is | ||
| 19471 | +/// what keeps a pool shared by every thread from being an unbounded stash. | ||
| 19431 | fn scratch_return(v: Vec<u16>) { | 19472 | fn scratch_return(v: Vec<u16>) { |
| 19432 | - PLANE_SCRATCH.with(|p| p.borrow_mut().push(v)); | 19473 | + let mut p = PLANE_SCRATCH.lock().unwrap(); |
| 19474 | + if p.len() < SCRATCH_CAP { | ||
| 19475 | + p.push(v); | ||
| 19476 | + } | ||
| 19433 | } | 19477 | } |
| 19434 | 19478 | ||
| 19435 | /// One CDEF mi-row band, as a real function rather than the body of the | 19479 | /// One CDEF mi-row band, as a real function rather than the body of the |
crates/ec-av1/src/par.rsmodified+84 -34
| @@ -202,6 +202,11 @@ struct PoolQ { | |||
| 202 | /// Jobs handed to a worker and not yet finished. | 202 | /// Jobs handed to a worker and not yet finished. |
| 203 | busy: usize, | 203 | busy: usize, |
| 204 | closed: bool, | 204 | closed: bool, |
| 205 | + /// lane-memfix: the pool's threads live behind the same lock as its | ||
| 206 | + /// queue, because the thread that has to GROW the pool is whichever one | ||
| 207 | + /// submits -- including one of the pool's own workers (see | ||
| 208 | + /// [`pool_push`]). Joined by [`Pool::drop`] on the owning thread. | ||
| 209 | + handles: Vec<std::thread::JoinHandle<()>>, | ||
| 205 | } | 210 | } |
| 206 | 211 | ||
| 207 | struct PoolInner { | 212 | struct PoolInner { |
| @@ -211,10 +216,13 @@ struct PoolInner { | |||
| 211 | 216 | ||
| 212 | struct Pool { | 217 | struct Pool { |
| 213 | inner: std::sync::Arc<PoolInner>, | 218 | inner: std::sync::Arc<PoolInner>, |
| 214 | - handles: Vec<std::thread::JoinHandle<()>>, | ||
| 215 | } | 219 | } |
| 216 | 220 | ||
| 217 | -fn pool_worker(inner: &PoolInner) { | 221 | +fn pool_worker(inner: &std::sync::Arc<PoolInner>) { |
| 222 | + // lane-memfix: a job this worker runs submits its own sub-batches to THIS | ||
| 223 | + // pool rather than opening a second one on the worker's thread-local -- | ||
| 224 | + // see [`Batch::submit`]. | ||
| 225 | + ON_POOL.with(|c| *c.borrow_mut() = Some(std::sync::Arc::clone(inner))); | ||
| 218 | let mut q = inner.q.lock().unwrap(); | 226 | let mut q = inner.q.lock().unwrap(); |
| 219 | loop { | 227 | loop { |
| 220 | if let Some(job) = q.jobs.pop_front() { | 228 | if let Some(job) = q.jobs.pop_front() { |
| @@ -228,6 +236,7 @@ fn pool_worker(inner: &PoolInner) { | |||
| 228 | continue; | 236 | continue; |
| 229 | } | 237 | } |
| 230 | if q.closed { | 238 | if q.closed { |
| 239 | + POOL_THREADS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); | ||
| 231 | return; | 240 | return; |
| 232 | } | 241 | } |
| 233 | q = inner.cv.wait(q).unwrap(); | 242 | q = inner.cv.wait(q).unwrap(); |
| @@ -242,46 +251,65 @@ impl Pool { | |||
| 242 | jobs: std::collections::VecDeque::new(), | 251 | jobs: std::collections::VecDeque::new(), |
| 243 | busy: 0, | 252 | busy: 0, |
| 244 | closed: false, | 253 | closed: false, |
| 254 | + handles: Vec::new(), | ||
| 245 | }), | 255 | }), |
| 246 | cv: std::sync::Condvar::new(), | 256 | cv: std::sync::Condvar::new(), |
| 247 | }), | 257 | }), |
| 248 | - handles: Vec::new(), | ||
| 249 | } | 258 | } |
| 250 | } | 259 | } |
| 260 | +} | ||
| 251 | 261 | ||
| 252 | - /// Queues `job` and makes sure a worker is free for it: the pool grows to | 262 | +/// Queues `job` on `inner` and makes sure a worker is free for it: the pool |
| 253 | - /// `busy + queued` threads and never shrinks, so a submitted job always | 263 | +/// grows to `busy + queued` threads, so a submitted job always starts, even |
| 254 | - /// starts, even when every other running job is blocked waiting for it. | 264 | +/// when every other running job is blocked waiting for it. |
| 255 | - /// `class` names the submitting site of the job that grows the pool, so a | 265 | +/// `class` names the submitting site of the job that grows the pool, so a |
| 256 | - /// profiler attributes the thread to the work that created it | 266 | +/// profiler attributes the thread to the work that created it |
| 257 | - /// (`ec-av1-frame`, `ec-av1-recon`, `ec-av1-filter`). One pool serves | 267 | +/// (`ec-av1-frame`, `ec-av1-recon`, `ec-av1-filter`). One pool serves every |
| 258 | - /// every class a thread submits, so later classes on the same pool reuse | 268 | +/// class submitted to it, so later classes reuse the threads an earlier one |
| 259 | - /// the threads an earlier one named. | 269 | +/// named. |
| 260 | - fn push(&mut self, job: Job, class: &'static str) { | 270 | +/// |
| 261 | - let want = { | 271 | +/// lane-memfix: the pool only grows for work that is queued and unserved AT |
| 262 | - let mut q = self.inner.q.lock().unwrap(); | 272 | +/// THAT MOMENT, and a pool worker submits back into its own pool, so the |
| 263 | - q.jobs.push_back(job); | 273 | +/// process-wide thread count is the peak of `busy + queued` over the whole |
| 264 | - q.busy + q.jobs.len() | 274 | +/// job tree -- not the product of one pool per nesting level (a filter band |
| 265 | - }; | 275 | +/// job used to open a third-level pool on the worker running it, and none of |
| 266 | - while self.handles.len() < want { | 276 | +/// those pools ever shrank: 1038 threads at (16,4,2)). |
| 267 | - let inner = std::sync::Arc::clone(&self.inner); | 277 | +fn pool_push(inner: &std::sync::Arc<PoolInner>, job: Job, class: &'static str) { |
| 268 | - let name = format!("{class}-{}", self.handles.len()); | 278 | + let mut q = inner.q.lock().unwrap(); |
| 269 | - self.handles.push( | 279 | + q.jobs.push_back(job); |
| 270 | - std::thread::Builder::new() | 280 | + let want = q.busy + q.jobs.len(); |
| 271 | - .name(name) | 281 | + while q.handles.len() < want { |
| 272 | - .spawn(move || pool_worker(&inner)) | 282 | + let inner = std::sync::Arc::clone(inner); |
| 273 | - .expect("spawning an ec-av1 pool worker"), | 283 | + let name = format!("{class}-{}", q.handles.len()); |
| 274 | - ); | 284 | + q.handles.push( |
| 275 | - } | 285 | + std::thread::Builder::new() |
| 276 | - self.inner.cv.notify_one(); | 286 | + .name(name) |
| 287 | + .spawn(move || pool_worker(&inner)) | ||
| 288 | + .expect("spawning an ec-av1 pool worker"), | ||
| 289 | + ); | ||
| 290 | + POOL_THREADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 277 | } | 291 | } |
| 292 | + drop(q); | ||
| 293 | + inner.cv.notify_one(); | ||
| 294 | +} | ||
| 295 | + | ||
| 296 | +/// Live threads across every ec-av1 pool -- what the bounded-growth test | ||
| 297 | +/// asserts on, and what a profiler counts as `ec-av1-*`. | ||
| 298 | +static POOL_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); | ||
| 299 | + | ||
| 300 | +pub(crate) fn pool_threads() -> usize { | ||
| 301 | + POOL_THREADS.load(std::sync::atomic::Ordering::Relaxed) | ||
| 278 | } | 302 | } |
| 279 | 303 | ||
| 280 | impl Drop for Pool { | 304 | impl Drop for Pool { |
| 281 | fn drop(&mut self) { | 305 | fn drop(&mut self) { |
| 282 | - self.inner.q.lock().unwrap().closed = true; | 306 | + let handles = { |
| 307 | + let mut q = self.inner.q.lock().unwrap(); | ||
| 308 | + q.closed = true; | ||
| 309 | + std::mem::take(&mut q.handles) | ||
| 310 | + }; | ||
| 283 | self.inner.cv.notify_all(); | 311 | self.inner.cv.notify_all(); |
| 284 | - for h in self.handles.drain(..) { | 312 | + for h in handles { |
| 285 | let _ = h.join(); | 313 | let _ = h.join(); |
| 286 | } | 314 | } |
| 287 | } | 315 | } |
| @@ -292,6 +320,12 @@ thread_local! { | |||
| 292 | /// when the thread exits (the process's main thread may skip that | 320 | /// when the thread exits (the process's main thread may skip that |
| 293 | /// destructor, in which case the idle workers die with the process). | 321 | /// destructor, in which case the idle workers die with the process). |
| 294 | static POOL: std::cell::RefCell<Option<Pool>> = const { std::cell::RefCell::new(None) }; | 322 | static POOL: std::cell::RefCell<Option<Pool>> = const { std::cell::RefCell::new(None) }; |
| 323 | + /// lane-memfix: set on a pool WORKER for its whole life -- the pool it | ||
| 324 | + /// serves. A job submitting a sub-batch (a pipeline stage banding itself | ||
| 325 | + /// across the filter pool) then reuses that pool instead of opening a | ||
| 326 | + /// nested one of its own. | ||
| 327 | + static ON_POOL: std::cell::RefCell<Option<std::sync::Arc<PoolInner>>> = | ||
| 328 | + const { std::cell::RefCell::new(None) }; | ||
| 295 | } | 329 | } |
| 296 | 330 | ||
| 297 | struct BatchState { | 331 | struct BatchState { |
| @@ -350,10 +384,26 @@ impl<'a> Batch<'a> { | |||
| 350 | // for `left == 0`), and `Batch<'a>` cannot outlive `'a`, so the | 384 | // for `left == 0`), and `Batch<'a>` cannot outlive `'a`, so the |
| 351 | // laundered lifetime is never observed past the real one. | 385 | // laundered lifetime is never observed past the real one. |
| 352 | let job: Job = unsafe { std::mem::transmute::<Box<dyn FnOnce() + Send + 'a>, Job>(job) }; | 386 | let job: Job = unsafe { std::mem::transmute::<Box<dyn FnOnce() + Send + 'a>, Job>(job) }; |
| 353 | - POOL.with(|p| { | 387 | + // lane-memfix: on a pool worker, back into the pool it is serving; on |
| 354 | - let mut p = p.borrow_mut(); | 388 | + // any other thread, this thread's own pool. |
| 355 | - p.get_or_insert_with(Pool::new).push(job, self.class); | 389 | + // |
| 356 | - }); | 390 | + // No deadlock: a job blocked in `Batch::drop` is counted in `busy`, |
| 391 | + // so `pool_push` grows the pool by one thread for every queued job | ||
| 392 | + // that has no idle worker -- the child of a blocked parent always | ||
| 393 | + // gets a thread. The only waits inside a job are on its own sub-batch | ||
| 394 | + // (same rule, one level deeper) and on wavefront row atomics / | ||
| 395 | + // `PipeSync` counters, which are published by jobs that are already | ||
| 396 | + // running, never by a job still in the queue. | ||
| 397 | + let on = ON_POOL.with(|c| c.borrow().clone()); | ||
| 398 | + match on { | ||
| 399 | + Some(inner) => pool_push(&inner, job, self.class), | ||
| 400 | + None => POOL.with(|p| { | ||
| 401 | + let mut p = p.borrow_mut(); | ||
| 402 | + let inner = std::sync::Arc::clone(&p.get_or_insert_with(Pool::new).inner); | ||
| 403 | + drop(p); | ||
| 404 | + pool_push(&inner, job, self.class); | ||
| 405 | + }), | ||
| 406 | + } | ||
| 357 | } | 407 | } |
| 358 | } | 408 | } |
| 359 | 409 | ||