forge
Explore
Log in

Don't you dare go Hollow

A cache line is flushed once, not sixty-four times

Browse files at this commit

522e89ffa05fea1421d3b8919e7ce03df24ddff5Ahmet Kaan GümüşParent: 01fb8ce
  • perf
    • a cache line is flushed once, not sixty-four times
Show full message
⚡ perf(cros-codecs): a cache line is flushed once, not sixty-four times

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.tomlmodified+13 -1
@@ -34,7 +34,19 @@ edition = "2024"
34 # writer's emulation-prevention fix that shares that code) are34 # writer's emulation-prevention fix that shares that code) are
35 # applied here verbatim -- upstream work carried early, not a35 # applied here verbatim -- upstream work carried early, not a
36 # local invention, and the H.265 half of what makes edith's36 # local invention, and the H.265 half of what makes edith's
37-# HEVC export run on the GPU37+# HEVC export run on the GPU.
38+# And `video_frame/generic_dma_video_frame.rs` unmapped a DMA
39+# buffer by issuing one `CLFLUSH` per *byte* -- 64 per cache
40+# line, 3.1 million per 1080p picture, 6.2 ms of the 8.4 ms a
41+# hardware export spent per frame (measured on radeonsi
42+# 2026-08-13; upstream's own TODO asks for exactly this and
43+# reports a race that the mfence pair, not the redundancy, was
44+# always ordering). The same `drop` wrote its `munmap` as an
45+# unconsumed `.map()`, so no mapping was ever released and an
46+# encode session leaked 3 MB of address space per frame
47+# (2.2 GB over a 719-frame export). Both are fixed in place
48+# and marked LOCAL PATCH
49+
38 # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per50 # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per
39 # term (the fast path in the same file serves the encoder only),51 # term (the fast path in the same file serves the encoder only),
40 # which is 4x slower than real time for 5.1 and therefore not52 # which is 4x slower than real time for 5.1 and therefore not
vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rsmodified+41 -9
@@ -98,6 +98,12 @@ const Y_TILE_WIDTH: usize = Y_TILE_WIDTH_IN_SUBTILES * Y_SUBTILE_WIDTH;
98 const Y_TILE_HEIGHT: usize = Y_TILE_HEIGHT_IN_SUBTILES * Y_SUBTILE_HEIGHT;98 const Y_TILE_HEIGHT: usize = Y_TILE_HEIGHT_IN_SUBTILES * Y_SUBTILE_HEIGHT;
99 const Y_TILE_SIZE: usize = Y_TILE_WIDTH * Y_TILE_HEIGHT;99 const Y_TILE_SIZE: usize = Y_TILE_WIDTH * Y_TILE_HEIGHT;
100 100
101+/// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): what one `CLFLUSH` covers,
102+/// and therefore the stride the unmap below walks a buffer with. 64 bytes on
103+/// every x86-64 part this runs on.
104+#[cfg(target_arch = "x86_64")]
105+const CACHE_LINE: usize = 64;
106+
101 fn detile_y_tile(dst: &mut [u8], src: &[u8], width: usize, height: usize) {107 fn detile_y_tile(dst: &mut [u8], src: &[u8], width: usize, height: usize) {
102 let tiles_per_row = width / Y_TILE_WIDTH;108 let tiles_per_row = width / Y_TILE_WIDTH;
103 for y in 0..height {109 for y in 0..height {
@@ -123,6 +129,11 @@ fn detile_y_tile(dst: &mut [u8], src: &[u8], width: usize, height: usize) {
123 pub struct DmaMapping<'a> {129 pub struct DmaMapping<'a> {
124 dma_handles: Vec<BorrowedFd<'a>>,130 dma_handles: Vec<BorrowedFd<'a>>,
125 addrs: Vec<NonNull<libc::c_void>>,131 addrs: Vec<NonNull<libc::c_void>>,
132+ /// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): what `mmap` actually
133+ /// returned and how much of it, which is what `munmap` has to be handed --
134+ /// `addrs` above are those bases plus a plane offset that is not required
135+ /// to be page aligned, so unmapping *them* is EINVAL.
136+ maps: Vec<(NonNull<libc::c_void>, usize)>,
126 detiled_bufs: Vec<Vec<u8>>,137 detiled_bufs: Vec<Vec<u8>>,
127 lens: Vec<usize>,138 lens: Vec<usize>,
128 is_writable: bool,139 is_writable: bool,
@@ -171,12 +182,14 @@ impl<'a> DmaMapping<'a> {
171 // Offsets aren't guaranteed to page aligned, so we have to map the entire FD and then182 // Offsets aren't guaranteed to page aligned, so we have to map the entire FD and then
172 // do pointer arithmetic to get the right buffer.183 // do pointer arithmetic to get the right buffer.
173 let mut addrs: Vec<NonNull<libc::c_void>> = vec![];184 let mut addrs: Vec<NonNull<libc::c_void>> = vec![];
185+ let mut maps: Vec<(NonNull<libc::c_void>, usize)> = vec![];
174 if borrowed_dma_handles.len() > 1 {186 if borrowed_dma_handles.len() > 1 {
175 for i in 0..offsets.len() {187 for i in 0..offsets.len() {
176 // SAFETY: This assumes that fd is a valid DMA buffer and that our lens and offsets188 // SAFETY: This assumes that fd is a valid DMA buffer and that our lens and offsets
177 // are correct.189 // are correct.
190+ let plane_size = lens[i] + offsets[i];
178 addrs.push(unsafe {191 addrs.push(unsafe {
179- mmap(192+ let base = mmap(
180 None,193 None,
181 NonZeroUsize::new(lens[i] + offsets[i])194 NonZeroUsize::new(lens[i] + offsets[i])
182 .ok_or("Attempted to map plane of length 0!")?,195 .ok_or("Attempted to map plane of length 0!")?,
@@ -189,8 +202,9 @@ impl<'a> DmaMapping<'a> {
189 borrowed_dma_handles[i].as_fd(),202 borrowed_dma_handles[i].as_fd(),
190 0,203 0,
191 )204 )
192- .map_err(|err| format!("Error mapping plane {err}"))?205+ .map_err(|err| format!("Error mapping plane {err}"))?;
193- .add(offsets[i])206+ maps.push((base, plane_size));
207+ base.add(offsets[i])
194 });208 });
195 }209 }
196 } else {210 } else {
@@ -212,6 +226,7 @@ impl<'a> DmaMapping<'a> {
212 0,226 0,
213 )227 )
214 .map_err(|err| format!("Error mapping plane {err}"))?;228 .map_err(|err| format!("Error mapping plane {err}"))?;
229+ maps.push((base_addr, total_size.get()));
215 for i in 0..offsets.len() {230 for i in 0..offsets.len() {
216 addrs.push(base_addr.add(offsets[i]));231 addrs.push(base_addr.add(offsets[i]));
217 }232 }
@@ -245,6 +260,7 @@ impl<'a> DmaMapping<'a> {
245 Ok(DmaMapping {260 Ok(DmaMapping {
246 dma_handles: borrowed_dma_handles.clone(),261 dma_handles: borrowed_dma_handles.clone(),
247 addrs: addrs,262 addrs: addrs,
263+ maps: maps,
248 detiled_bufs: detiled_bufs,264 detiled_bufs: detiled_bufs,
249 lens: lens.clone(),265 lens: lens.clone(),
250 is_writable: is_writable,266 is_writable: is_writable,
@@ -313,12 +329,22 @@ impl<'a> Drop for DmaMapping<'a> {
313 _mm_mfence();329 _mm_mfence();
314 330
315 for (addr, len) in zip(self.addrs.iter(), self.lens.iter()) {331 for (addr, len) in zip(self.addrs.iter(), self.lens.iter()) {
316- // TODO: We shouldn't actually have to flush every address, we should just332+ // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): a cache
317- // flush the address at the beginning of each cache line. But, during testing333+ // line at a time, which is the granularity CLFLUSH has --
318- // this caused a race condition.334+ // flushing every byte issued 64 instructions per line and
319- for offset in 0..*len {335+ // cost 6.2 ms per 1080p picture on radeonsi (measured
320- _mm_clflush((addr.as_ptr() as *const u8).offset(offset as isize));336+ // 2026-08-13), four fifths of a hardware export's whole
337+ // per-frame budget. The upstream TODO says exactly this and
338+ // reports a race when it was tried; the mfence pair either
339+ // side is what orders the flushes, and the sixty-four
340+ // redundant flushes per line were never what did.
341+ let base = addr.as_ptr() as *const u8;
342+ for offset in (0..*len).step_by(CACHE_LINE) {
343+ _mm_clflush(base.offset(offset as isize));
321 }344 }
345+ // ...and the last line, where the length is not a multiple
346+ // of one.
347+ _mm_clflush(base.offset(len.saturating_sub(1) as isize));
322 }348 }
323 349
324 _mm_mfence();350 _mm_mfence();
@@ -326,7 +352,13 @@ impl<'a> Drop for DmaMapping<'a> {
326 352
327 fence(Ordering::SeqCst);353 fence(Ordering::SeqCst);
328 354
329- let _ = zip(self.addrs.iter(), self.lens.iter()).map(|x| munmap(*x.0, *x.1).unwrap());355+ // LOCAL PATCH: `map` on an iterator is lazy, so the unmap upstream
356+ // writes here never ran -- every mapping leaked its address space
357+ // (3 MB a picture through an encode session, 2.2 GB of VSZ over a
358+ // 719-frame export, measured 2026-08-13).
359+ for (addr, len) in self.maps.iter() {
360+ let _ = munmap(*addr, *len);
361+ }
330 }362 }
331 }363 }
332 }364 }