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"
3434 # writer's emulation-prevention fix that shares that code) are
3535 # applied here verbatim -- upstream work carried early, not a
3636 # local invention, and the H.265 half of what makes edith's
37-# HEVC export run on the GPU
37+# 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+
3850 # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per
3951 # term (the fast path in the same file serves the encoder only),
4052 # 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;
9898 const Y_TILE_HEIGHT: usize = Y_TILE_HEIGHT_IN_SUBTILES * Y_SUBTILE_HEIGHT;
9999 const Y_TILE_SIZE: usize = Y_TILE_WIDTH * Y_TILE_HEIGHT;
100100
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+
101107 fn detile_y_tile(dst: &mut [u8], src: &[u8], width: usize, height: usize) {
102108 let tiles_per_row = width / Y_TILE_WIDTH;
103109 for y in 0..height {
@@ -123,6 +129,11 @@ fn detile_y_tile(dst: &mut [u8], src: &[u8], width: usize, height: usize) {
123129 pub struct DmaMapping<'a> {
124130 dma_handles: Vec<BorrowedFd<'a>>,
125131 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)>,
126137 detiled_bufs: Vec<Vec<u8>>,
127138 lens: Vec<usize>,
128139 is_writable: bool,
@@ -171,12 +182,14 @@ impl<'a> DmaMapping<'a> {
171182 // Offsets aren't guaranteed to page aligned, so we have to map the entire FD and then
172183 // do pointer arithmetic to get the right buffer.
173184 let mut addrs: Vec<NonNull<libc::c_void>> = vec![];
185+ let mut maps: Vec<(NonNull<libc::c_void>, usize)> = vec![];
174186 if borrowed_dma_handles.len() > 1 {
175187 for i in 0..offsets.len() {
176188 // SAFETY: This assumes that fd is a valid DMA buffer and that our lens and offsets
177189 // are correct.
190+ let plane_size = lens[i] + offsets[i];
178191 addrs.push(unsafe {
179- mmap(
192+ let base = mmap(
180193 None,
181194 NonZeroUsize::new(lens[i] + offsets[i])
182195 .ok_or("Attempted to map plane of length 0!")?,
@@ -189,8 +202,9 @@ impl<'a> DmaMapping<'a> {
189202 borrowed_dma_handles[i].as_fd(),
190203 0,
191204 )
192- .map_err(|err| format!("Error mapping plane {err}"))?
193- .add(offsets[i])
205+ .map_err(|err| format!("Error mapping plane {err}"))?;
206+ maps.push((base, plane_size));
207+ base.add(offsets[i])
194208 });
195209 }
196210 } else {
@@ -212,6 +226,7 @@ impl<'a> DmaMapping<'a> {
212226 0,
213227 )
214228 .map_err(|err| format!("Error mapping plane {err}"))?;
229+ maps.push((base_addr, total_size.get()));
215230 for i in 0..offsets.len() {
216231 addrs.push(base_addr.add(offsets[i]));
217232 }
@@ -245,6 +260,7 @@ impl<'a> DmaMapping<'a> {
245260 Ok(DmaMapping {
246261 dma_handles: borrowed_dma_handles.clone(),
247262 addrs: addrs,
263+ maps: maps,
248264 detiled_bufs: detiled_bufs,
249265 lens: lens.clone(),
250266 is_writable: is_writable,
@@ -313,12 +329,22 @@ impl<'a> Drop for DmaMapping<'a> {
313329 _mm_mfence();
314330
315331 for (addr, len) in zip(self.addrs.iter(), self.lens.iter()) {
316- // TODO: We shouldn't actually have to flush every address, we should just
317- // flush the address at the beginning of each cache line. But, during testing
318- // this caused a race condition.
319- for offset in 0..*len {
320- _mm_clflush((addr.as_ptr() as *const u8).offset(offset as isize));
332+ // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): a cache
333+ // line at a time, which is the granularity CLFLUSH has --
334+ // flushing every byte issued 64 instructions per line and
335+ // cost 6.2 ms per 1080p picture on radeonsi (measured
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));
321344 }
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));
322348 }
323349
324350 _mm_mfence();
@@ -326,7 +352,13 @@ impl<'a> Drop for DmaMapping<'a> {
326352
327353 fence(Ordering::SeqCst);
328354
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+ }
330362 }
331363 }
332364 }