From 522e89ffa05fea1421d3b8919e7ce03df24ddff5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 13 Aug 2026 14:02:45 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20perf(cros-codecs):=20a=20cache=20li?= =?UTF-8?q?ne=20is=20flushed=20once,=20not=20sixty-four=20times?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Unmapping a DMA buffer flushed the CPU's caches back to it a *byte* at a time -- one CLFLUSH per byte, where a CLFLUSH covers a whole 64-byte line. That is 3.1 million instructions per 1080p picture, and it was 6.2 ms of the 8.4 ms a hardware export was spending per frame: the encoder maps its input buffer to write the picture into, and every unmap paid it. The stride is the cache line now. Upstream's own TODO on those lines asks for this and reports a race when it was tried; what orders the flushes is the mfence either side, which is still there, and the sixty-three redundant flushes per line never were. The same `drop` also wrote its munmap as `let _ = zip(..).map(..)` -- a lazy iterator nobody consumes, so no mapping was ever released. An encode session leaked its 3 MB input mapping every frame, 2.2 GB of address space over a 719-frame export. It unmaps in a `for` loop now, and it unmaps what `mmap` actually returned: the plane addresses it used to pass are those bases plus an offset that is not required to be page aligned, which munmap refuses. Export throughput on the 1080p film, hardware H.264 seat, same 30 s span: 89.9 fps before, 239.6 fps after -- 10x realtime, and the file is the same file (a ten-second span exported through both builds is byte-identical, 6,379,699 bytes, ffmpeg -v error empty). tests/hw_decode.rs (10), tests/hw_encode.rs (3) and tests/decode_baseline.rs pass, the pixel oracle `hardware_matches_software_on_frame_30` among them. --- Cargo.toml | 14 +++++- .../video_frame/generic_dma_video_frame.rs | 50 +++++++++++++++---- 2 files changed, 54 insertions(+), 10 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 06e1089..574bf4e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,7 +34,19 @@ edition = "2024" # writer's emulation-prevention fix that shares that code) are # applied here verbatim -- upstream work carried early, not a # local invention, and the H.265 half of what makes edith's -# HEVC export run on the GPU +# HEVC export run on the GPU. +# And `video_frame/generic_dma_video_frame.rs` unmapped a DMA +# buffer by issuing one `CLFLUSH` per *byte* -- 64 per cache +# line, 3.1 million per 1080p picture, 6.2 ms of the 8.4 ms a +# hardware export spent per frame (measured on radeonsi +# 2026-08-13; upstream's own TODO asks for exactly this and +# reports a race that the mfence pair, not the redundancy, was +# always ordering). The same `drop` wrote its `munmap` as an +# unconsumed `.map()`, so no mapping was ever released and an +# encode session leaked 3 MB of address space per frame +# (2.2 GB over a 719-frame export). Both are fixed in place +# and marked LOCAL PATCH + # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per # term (the fast path in the same file serves the encoder only), # which is 4x slower than real time for 5.1 and therefore not diff --git a/vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rs b/vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rs index bdb788f..f3c851f 100644 --- a/vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rs +++ b/vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rs @@ -98,6 +98,12 @@ const Y_TILE_WIDTH: usize = Y_TILE_WIDTH_IN_SUBTILES * Y_SUBTILE_WIDTH; const Y_TILE_HEIGHT: usize = Y_TILE_HEIGHT_IN_SUBTILES * Y_SUBTILE_HEIGHT; const Y_TILE_SIZE: usize = Y_TILE_WIDTH * Y_TILE_HEIGHT; +/// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): what one `CLFLUSH` covers, +/// and therefore the stride the unmap below walks a buffer with. 64 bytes on +/// every x86-64 part this runs on. +#[cfg(target_arch = "x86_64")] +const CACHE_LINE: usize = 64; + fn detile_y_tile(dst: &mut [u8], src: &[u8], width: usize, height: usize) { let tiles_per_row = width / Y_TILE_WIDTH; for y in 0..height { @@ -123,6 +129,11 @@ fn detile_y_tile(dst: &mut [u8], src: &[u8], width: usize, height: usize) { pub struct DmaMapping<'a> { dma_handles: Vec>, addrs: Vec>, + /// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): what `mmap` actually + /// returned and how much of it, which is what `munmap` has to be handed -- + /// `addrs` above are those bases plus a plane offset that is not required + /// to be page aligned, so unmapping *them* is EINVAL. + maps: Vec<(NonNull, usize)>, detiled_bufs: Vec>, lens: Vec, is_writable: bool, @@ -171,12 +182,14 @@ impl<'a> DmaMapping<'a> { // Offsets aren't guaranteed to page aligned, so we have to map the entire FD and then // do pointer arithmetic to get the right buffer. let mut addrs: Vec> = vec![]; + let mut maps: Vec<(NonNull, usize)> = vec![]; if borrowed_dma_handles.len() > 1 { for i in 0..offsets.len() { // SAFETY: This assumes that fd is a valid DMA buffer and that our lens and offsets // are correct. + let plane_size = lens[i] + offsets[i]; addrs.push(unsafe { - mmap( + let base = mmap( None, NonZeroUsize::new(lens[i] + offsets[i]) .ok_or("Attempted to map plane of length 0!")?, @@ -189,8 +202,9 @@ impl<'a> DmaMapping<'a> { borrowed_dma_handles[i].as_fd(), 0, ) - .map_err(|err| format!("Error mapping plane {err}"))? - .add(offsets[i]) + .map_err(|err| format!("Error mapping plane {err}"))?; + maps.push((base, plane_size)); + base.add(offsets[i]) }); } } else { @@ -212,6 +226,7 @@ impl<'a> DmaMapping<'a> { 0, ) .map_err(|err| format!("Error mapping plane {err}"))?; + maps.push((base_addr, total_size.get())); for i in 0..offsets.len() { addrs.push(base_addr.add(offsets[i])); } @@ -245,6 +260,7 @@ impl<'a> DmaMapping<'a> { Ok(DmaMapping { dma_handles: borrowed_dma_handles.clone(), addrs: addrs, + maps: maps, detiled_bufs: detiled_bufs, lens: lens.clone(), is_writable: is_writable, @@ -313,12 +329,22 @@ impl<'a> Drop for DmaMapping<'a> { _mm_mfence(); for (addr, len) in zip(self.addrs.iter(), self.lens.iter()) { - // TODO: We shouldn't actually have to flush every address, we should just - // flush the address at the beginning of each cache line. But, during testing - // this caused a race condition. - for offset in 0..*len { - _mm_clflush((addr.as_ptr() as *const u8).offset(offset as isize)); + // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): a cache + // line at a time, which is the granularity CLFLUSH has -- + // flushing every byte issued 64 instructions per line and + // cost 6.2 ms per 1080p picture on radeonsi (measured + // 2026-08-13), four fifths of a hardware export's whole + // per-frame budget. The upstream TODO says exactly this and + // reports a race when it was tried; the mfence pair either + // side is what orders the flushes, and the sixty-four + // redundant flushes per line were never what did. + let base = addr.as_ptr() as *const u8; + for offset in (0..*len).step_by(CACHE_LINE) { + _mm_clflush(base.offset(offset as isize)); } + // ...and the last line, where the length is not a multiple + // of one. + _mm_clflush(base.offset(len.saturating_sub(1) as isize)); } _mm_mfence(); @@ -326,7 +352,13 @@ impl<'a> Drop for DmaMapping<'a> { fence(Ordering::SeqCst); - let _ = zip(self.addrs.iter(), self.lens.iter()).map(|x| munmap(*x.0, *x.1).unwrap()); + // LOCAL PATCH: `map` on an iterator is lazy, so the unmap upstream + // writes here never ran -- every mapping leaked its address space + // (3 MB a picture through an encode session, 2.2 GB of VSZ over a + // 719-frame export, measured 2026-08-13). + for (addr, len) in self.maps.iter() { + let _ = munmap(*addr, *len); + } } } }