diff --git a/crates/stela-driver-gpu/src/metal/command_buffer.rs b/crates/stela-driver-gpu/src/metal/command_buffer.rs index d3aeaecac8..59216413c3 100644 --- a/crates/stela-driver-gpu/src/metal/command_buffer.rs +++ b/crates/stela-driver-gpu/src/metal/command_buffer.rs @@ -792,6 +792,11 @@ pub struct CommandBuffer { /// The textures with aligned copies it writes, which its end copies /// back into their rows. pub(crate) aligned_writes: Vec, + /// Every texture it writes: an attachment, a blit destination, one + /// shaders may write. + pub(crate) written: Vec, + /// The IOSurface objects it uses, as the guest reported them. + pub(crate) surfaces: Vec, } impl CommandBuffer { @@ -805,6 +810,8 @@ impl CommandBuffer { workload: Workload::default(), planes: Default::default(), aligned_writes: Vec::new(), + written: Vec::new(), + surfaces: Vec::new(), } } diff --git a/crates/stela-driver-gpu/src/metal/device.rs b/crates/stela-driver-gpu/src/metal/device.rs index 677a039bcd..631da1380c 100644 --- a/crates/stela-driver-gpu/src/metal/device.rs +++ b/crates/stela-driver-gpu/src/metal/device.rs @@ -49,6 +49,7 @@ pub mod pins; pub mod pipelines; pub mod queue; pub mod resources; +pub use resources::SurfaceNote; /// A slab of objects addressed by index; freed slots are reused. #[derive(Debug)] diff --git a/crates/stela-driver-gpu/src/metal/device/queue.rs b/crates/stela-driver-gpu/src/metal/device/queue.rs index 2fcc6f1bc3..45ac13a38c 100644 --- a/crates/stela-driver-gpu/src/metal/device/queue.rs +++ b/crates/stela-driver-gpu/src/metal/device/queue.rs @@ -882,7 +882,9 @@ impl Device { // wrote copied back into them last. if finished.is_ok() { let written = core::mem::take(&mut commands.aligned_writes); - let (lead, tail) = self.aligned_copy_commands(&written); + let surfaces = core::mem::take(&mut commands.surfaces); + let writes = core::mem::take(&mut commands.written); + let (lead, tail) = self.aligned_copy_commands(&written, &surfaces, &writes); commands.surround(lead, tail); } // Applied once the recording reaches the queue. diff --git a/crates/stela-driver-gpu/src/metal/device/resources.rs b/crates/stela-driver-gpu/src/metal/device/resources.rs index 41dd2ff853..920e95696b 100644 --- a/crates/stela-driver-gpu/src/metal/device/resources.rs +++ b/crates/stela-driver-gpu/src/metal/device/resources.rs @@ -47,7 +47,7 @@ use stela_contracts::gate::MemoryRange; mod aligned_copies; mod extended_planes; mod read_back; -pub use aligned_copies::RowCopy; +pub use aligned_copies::{RowCopy, SurfaceNote}; pub(super) use extended_planes::PlaneActions; pub use extended_planes::PlaneChanges; pub use read_back::ReadBack; @@ -1002,7 +1002,7 @@ impl Device { }, texel_bytes: u64::from(descriptor.pixel_format.describe().block.bytes), }; - let (image, copy) = self.plane_image(&plan, rows)?; + let (image, copy) = self.plane_image(&plan, rows, false)?; let (id, views) = match self.shader_views(image, &plan.views) { Ok(created) => created, Err(error) => { @@ -1144,6 +1144,12 @@ impl Device { buffer.length, ); let plans = resource::two_plane_texture(&self.capabilities, descriptor, length, planes)?; + // A large surface the GPU only samples is read from device memory + // (`aligned_copies`): sampled from guest RAM, every texel cache miss + // crosses the bus. + let sampled = !renders + && descriptor.width.saturating_mul(descriptor.height) + >= aligned_copies::DEVICE_COPY_TEXELS; let formats = descriptor .pixel_format .plane_formats() @@ -1160,7 +1166,7 @@ impl Device { layout, texel_bytes: u64::from(format.describe().block.bytes), }; - let (image, copy) = self.plane_image(plan, rows)?; + let (image, copy) = self.plane_image(plan, rows, sampled)?; images.push(image); copies.extend(copy); let info = plan diff --git a/crates/stela-driver-gpu/src/metal/device/resources/aligned_copies.rs b/crates/stela-driver-gpu/src/metal/device/resources/aligned_copies.rs index d65ef86f0a..0b913c66c5 100644 --- a/crates/stela-driver-gpu/src/metal/device/resources/aligned_copies.rs +++ b/crates/stela-driver-gpu/src/metal/device/resources/aligned_copies.rs @@ -24,6 +24,22 @@ //! //! A texture whose rows fit keeps its linear image placed in the rows: no //! copy at all. +//! +//! A large IOSurface texture the GPU only samples, of a two-plane format it +//! cannot render (a video frame or a video wallpaper's 10-bit 4:2:0 +//! surface), is kept in device memory as well, though its rows fit: sampled +//! in place, every texel cache miss is a bus read of guest RAM with no L2 +//! caching, so one 3840x2160 surface cost a Mission Control frame 10-19 ms of +//! GPU time on the 5080. Its copy is refreshed only in a command buffer that +//! uses it, and only when the surface changed since it was last copied: +//! the guest reports each IOSurface object a command buffer uses with the +//! surface's ID and seed as committed (`SurfaceUse`); the CPU's writes +//! change the seed, and a command buffer that writes a surface (a pass +//! attachment, a blit destination, a texture shaders may write, any buffer +//! over it) marks its copies stale for later command buffers. A texture +//! reached only through an argument buffer and a residency set, which the +//! guest does not report, is not refreshed: its copy keeps what its last +//! reported use copied. use super::{Device, TextureId}; use crate::metal::{ abi::TextureUsage, @@ -49,6 +65,7 @@ pub(in crate::metal::device) struct AlignedCopy { memory: Memory, bytes: u64, rows: RowCopy, + refresh: Refresh, /// The rows' memory and where they start in it, for the CPU's copies. rows_memory: Memory, place: u64, @@ -56,6 +73,36 @@ pub(in crate::metal::device) struct AlignedCopy { texel_bytes: u64, } +/// When an aligned copy is refreshed from its rows. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Refresh { + /// By every command buffer: rows the GPU cannot address in place. + Always, + /// By a command buffer that uses it whose surface's seed differs from + /// `filled`, the seed it was last copied at (`None`: never copied, or + /// written by the GPU since); `surface` is the surface's ID once the + /// guest reported it. + Changed { + surface: Option, + filled: Option, + }, +} + +/// An IOSurface object a command buffer uses, as the guest reported it: +/// the texture (`None` for a buffer) and the surface's ID and seed at its +/// commit. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct SurfaceNote { + pub texture: Option, + pub surface: u32, + pub seed: u32, +} + +/// The fewest texels of a sampled-only two-plane surface's first plane kept +/// in device memory: a 1920x1080 frame's. Smaller ones cost less sampled in +/// place than their copies. +pub(in crate::metal::device) const DEVICE_COPY_TEXELS: u64 = 1920 * 1080; + /// A copy between a plane's rows in `buffer` and its aligned copy `image`, /// both ways: `region` names the rows by their offset and their pitch in /// texels. @@ -99,14 +146,17 @@ pub(in crate::metal::device) struct Rows { impl Device { /// The image of a linear plane `plan` over `rows`: its linear image - /// placed in the rows when the GPU addresses them in place, else its - /// aligned copy, which the caller keeps with the texture - /// ([`Self::keep_aligned_copies`]) or releases - /// ([`Self::release_aligned_copies`]) once it destroyed the image. + /// placed in the rows when the GPU addresses them in place and `sampled` + /// is false, else its aligned copy, which the caller keeps with the + /// texture ([`Self::keep_aligned_copies`]) or releases + /// ([`Self::release_aligned_copies`]) once it destroyed the image. With + /// `sampled`, a plane whose rows fit gets a copy refreshed only where + /// used and changed ([`Refresh::Changed`]). pub(in crate::metal::device) fn plane_image( &mut self, plan: &TexturePlan, rows: Rows, + sampled: bool, ) -> Result<(Image, Option)> { let Rows { buffer, @@ -118,12 +168,21 @@ impl Device { let place = memory_offset .checked_add(layout.offset) .ok_or(Error::Invalid("the rows lie past the memory"))?; - if resource::linear_layout_fits(&self.capabilities, place, layout.bytes_per_row) { + let fits = resource::linear_layout_fits(&self.capabilities, place, layout.bytes_per_row); + if fits && !sampled { let image = self .backend .create_placed_image(&plan.image, memory, place)?; return Ok((image, None)); } + let refresh = if fits { + Refresh::Changed { + surface: None, + filled: None, + } + } else { + Refresh::Always + }; let row_length = u32::try_from(layout.bytes_per_row / texel_bytes.max(1)) .map_err(|_| Error::Invalid("bytesPerRow exceeds the row pitch range"))?; let info = resource::aligned_copy(&plan.image); @@ -165,6 +224,7 @@ impl Device { image, region, }, + refresh, rows_memory: memory, place, bytes_per_row: layout.bytes_per_row, @@ -238,6 +298,9 @@ impl Device { /// back into the rows when it is an aligned copy. An extended-range /// IOSurface texture writes its rows itself. pub fn note_texture_write(&self, commands: &mut CommandBuffer, id: TextureId) { + if !commands.written.contains(&id) { + commands.written.push(id); + } let Some(root) = self.aligned_root(id) else { return; }; @@ -262,20 +325,64 @@ impl Device { } } - /// The copies a command buffer begins with, each aligned copy's rows - /// into it, and those it ends with, back into the rows of the textures - /// it wrote (`written`); each followed by a full barrier, and empty when - /// there are none. + /// The copies a command buffer begins with, and those it ends with, + /// back into the rows of the textures it wrote (`written`); each + /// followed by a full barrier, and empty when there are none. It begins + /// with every [`Refresh::Always`] copy, and each [`Refresh::Changed`] + /// copy of a texture it uses (`surfaces`) whose surface's seed differs + /// from the one last copied, which it then records. The surfaces it may + /// write (`writes`: the textures it writes; any buffer over a surface) + /// leave their copies stale for later command buffers. pub(in crate::metal::device) fn aligned_copy_commands( - &self, + &mut self, written: &[TextureId], + surfaces: &[SurfaceNote], + writes: &[TextureId], ) -> (Vec, Vec) { - let copies = &self.resources.aligned_copies; - let mut lead: Vec = copies + let mut lead: Vec = self + .resources + .aligned_copies .values() .flatten() + .filter(|copy| copy.refresh == Refresh::Always) .map(|copy| copy.rows.refresh()) .collect(); + let used: Vec<(TextureId, SurfaceNote)> = surfaces + .iter() + .filter_map(|note| Some((self.aligned_root(note.texture?)?, *note))) + .collect(); + for (root, note) in used { + let Some(copies) = self.resources.aligned_copies.get_mut(&root.0) else { + continue; + }; + for copy in copies { + if let Refresh::Changed { surface, filled } = &mut copy.refresh { + *surface = Some(note.surface); + if *filled != Some(note.seed) { + *filled = Some(note.seed); + lead.push(copy.rows.refresh()); + } + } + } + } + let dirty: Vec = surfaces + .iter() + .filter(|note| note.texture.is_none_or(|texture| writes.contains(&texture))) + .map(|note| note.surface) + .collect(); + if !dirty.is_empty() { + for copy in self.resources.aligned_copies.values_mut().flatten() { + if let Refresh::Changed { + surface: Some(surface), + filled, + } = &mut copy.refresh + && dirty.contains(surface) + { + *filled = None; + } + } + } + let copies = &self.resources.aligned_copies; let mut tail: Vec = written .iter() .filter_map(|id| copies.get(&id.0)) @@ -326,6 +433,18 @@ impl Device { for (offset, packed) in rows { self.backend.write_memory(memory, offset, &bytes[packed])?; } + // The next command buffer that uses it copies the rows again. + for copy in self + .resources + .aligned_copies + .get_mut(&id.0) + .into_iter() + .flatten() + { + if let Refresh::Changed { filled, .. } = &mut copy.refresh { + *filled = None; + } + } Ok(true) } diff --git a/crates/stela-driver-gpu/src/metal/device/resources/aligned_copies/tests.rs b/crates/stela-driver-gpu/src/metal/device/resources/aligned_copies/tests.rs index b75746663b..00fd0101cf 100644 --- a/crates/stela-driver-gpu/src/metal/device/resources/aligned_copies/tests.rs +++ b/crates/stela-driver-gpu/src/metal/device/resources/aligned_copies/tests.rs @@ -339,3 +339,112 @@ fn rows_another_connections_work_refreshes_from_outlive_it() { assert_eq!(device.poll(), Ok(other)); assert!(device.backend().destroyed.contains(&Object::Memory(memory))); } + +/// A video wallpaper's 10-bit 4:2:0 surface, whose rows the GPU could +/// address in place, is sampled from device memory: both planes' copies are +/// refreshed only by a command buffer that uses the texture, only when the +/// surface's seed changed since the last copy, and again after a command +/// buffer wrote the surface through another object. Before, it was sampled +/// from guest RAM: 10.6 ms for one 1280x896 quad over a 3840x2160 surface. +#[test] +fn a_large_sampled_surface_is_copied_only_where_used_and_changed() { + let mut device = device(); + let buffer = buffer(&mut device, 8 << 20); + let surface = descriptor( + PixelFormat::Ycbcr10_420_2p, + 1920, + 1080, + TextureUsage::SHADER_READ, + ); + let planes = [ + PlaneLayout { + offset: 0, + bytes_per_row: 3840, + }, + PlaneLayout { + offset: 4 << 20, + bytes_per_row: 3840, + }, + ]; + let texture = device + .new_two_plane_texture(buffer, &surface, planes, 0) + .unwrap(); + assert!(device.has_aligned_copy(texture)); + let both = [ + (true, 0, 1920, [1920, 1080, 1]), + (true, 4 << 20, 960, [960, 540, 1]), + ]; + let note = |texture, seed| SurfaceNote { + texture, + surface: 42, + seed, + }; + let commit = |device: &mut TestDevice, notes: &[SurfaceNote], written: &[TextureId]| { + let mut commands = device.new_command_buffer(); + commands.surfaces.extend_from_slice(notes); + commands.written.extend_from_slice(written); + device.commit(commands).unwrap(); + row_copies(device) + }; + // Not used: nothing is copied. + assert_eq!(commit(&mut device, &[], &[]), []); + // Used at seed 7: copied once, then not again while the seed holds. + assert_eq!(commit(&mut device, &[note(Some(texture), 7)], &[]), both); + assert_eq!(commit(&mut device, &[note(Some(texture), 7)], &[]), []); + // The CPU wrote it: a new seed. + assert_eq!(commit(&mut device, &[note(Some(texture), 8)], &[]), both); + // Another texture over the same surface (another connection's, as the + // surface's ID says) written by a command buffer: the next use copies. + let other = device + .new_texture_from_buffer( + buffer, + &descriptor( + PixelFormat::R16Unorm, + 1920, + 1080, + TextureUsage::RENDER_TARGET, + ), + 0, + 3840, + ) + .unwrap(); + assert_eq!(commit(&mut device, &[note(Some(other), 8)], &[other]), []); + assert_eq!(commit(&mut device, &[note(Some(texture), 8)], &[]), both); + // Read, not written, it changes nothing. + assert_eq!(commit(&mut device, &[note(Some(other), 8)], &[]), []); + assert_eq!(commit(&mut device, &[note(Some(texture), 8)], &[]), []); + // A buffer over the surface may be written by any shader. + assert_eq!(commit(&mut device, &[note(None, 8)], &[]), []); + assert_eq!(commit(&mut device, &[note(Some(texture), 8)], &[]), both); + device.destroy_texture(other).unwrap(); + device.destroy_texture(texture).unwrap(); +} + +/// A surface below a 1920x1080 frame keeps sampling its rows in +/// place: no copy at all. +#[test] +fn small_surfaces_stay_in_their_rows() { + let mut device = device(); + let buffer = buffer(&mut device, 8 << 20); + let planes = [ + PlaneLayout { + offset: 0, + bytes_per_row: 1280, + }, + PlaneLayout { + offset: 4 << 20, + bytes_per_row: 1280, + }, + ]; + let small = descriptor( + PixelFormat::Ycbcr10_420_2p, + 640, + 360, + TextureUsage::SHADER_READ, + ); + let texture = device + .new_two_plane_texture(buffer, &small, planes, 0) + .unwrap(); + assert!(!device.has_aligned_copy(texture)); + device.destroy_texture(texture).unwrap(); +} diff --git a/crates/stela-driver-gpu/src/metal/device/resources/extended_planes.rs b/crates/stela-driver-gpu/src/metal/device/resources/extended_planes.rs index 5c99da9bec..9733e27bc2 100644 --- a/crates/stela-driver-gpu/src/metal/device/resources/extended_planes.rs +++ b/crates/stela-driver-gpu/src/metal/device/resources/extended_planes.rs @@ -238,7 +238,7 @@ impl Device { layout, texel_bytes: u64::from(format.describe().block.bytes), }; - let (image, copy) = self.plane_image(plan, rows)?; + let (image, copy) = self.plane_image(plan, rows, false)?; images.push(image); copies.extend(copy); let info = plan diff --git a/crates/stela-driver-gpu/src/metal/service/commands.rs b/crates/stela-driver-gpu/src/metal/service/commands.rs index 6f8a4a79e0..5877ff9fd8 100644 --- a/crates/stela-driver-gpu/src/metal/service/commands.rs +++ b/crates/stela-driver-gpu/src/metal/service/commands.rs @@ -8,6 +8,7 @@ use super::{ commands::{ BufferLayoutRecord, CommandBufferCode, CommandCode, CommandHeader, CommitRequest, DepthStencilRecord, EventCommand, PatchSourceRecord, SampleCounters, StencilRecord, + SurfaceUse, }, }, }; @@ -21,7 +22,7 @@ use crate::metal::{ render::PatchSource, }, compiler::DEFERRED, - device::{BufferId, SamplerId, TextureId}, + device::{BufferId, SamplerId, SurfaceNote, TextureId}, pipeline::{DepthStencilDescriptor, DepthStencilState, StencilDescriptor, depth_stencil}, shader::Compiler, timing::{Detail, Phase, Timed}, @@ -259,6 +260,30 @@ impl Service { let Handle { handle } = payload.record()?; commands.set_log_buffer(self.buffer_ref(connection, handle)?); } + CommandBufferCode::SurfaceUse => { + let SurfaceUse { + object, + surface, + seed, + buffer, + reserved: _, + } = payload.record()?; + let texture = match buffer { + 0 => Some(self.object::(connection, object)?), + 1 => { + self.buffer_ref(connection, object)?; + None + } + kind => { + return Err(Fault::malformed("surface use kind").value(u64::from(kind))); + } + }; + commands.surfaces.push(SurfaceNote { + texture, + surface, + seed, + }); + } CommandBufferCode::SampleCounters => { let SampleCounters { buffer, diff --git a/crates/stela-driver-gpu/src/metal/service/wire/commands.rs b/crates/stela-driver-gpu/src/metal/service/wire/commands.rs index ca480a2aeb..c82441bef4 100644 --- a/crates/stela-driver-gpu/src/metal/service/wire/commands.rs +++ b/crates/stela-driver-gpu/src/metal/service/wire/commands.rs @@ -40,6 +40,21 @@ records! { pub reserved: u32, } + /// An IOSurface object the command buffer uses: a texture or buffer + /// handle over the surface (`buffer` 1 for a buffer, 0 for a texture), + /// the surface's ID and its seed as the command buffer was committed + /// (`IOSurfaceGetID`, `IOSurfaceGetSeed`). Sent once for each such + /// object, after the encoders: the service refreshes its device-memory + /// copies of sampled surfaces only when their seed changed, and takes a + /// surface written by the command buffer as changed for later ones. + pub struct SurfaceUse { + pub object: u64, + pub surface: u32, + pub seed: u32, + pub buffer: u32, + pub reserved: u32, + } + /// `computeCommandEncoderWithDispatchType:`. pub struct BeginCompute { pub dispatch_type: u64, @@ -662,6 +677,8 @@ raw_enum! { SampleCounters = 0x0004, /// `Handle`: the log state's buffer, before any encoder. LogBuffer = 0x0005, + /// `SurfaceUse`, outside any encoder. + SurfaceUse = 0x0006, } } diff --git a/guest/stela-gpu/bundle/Commands.m b/guest/stela-gpu/bundle/Commands.m index 02536c8e40..7a8e1f7582 100644 --- a/guest/stela-gpu/bundle/Commands.m +++ b/guest/stela-gpu/bundle/Commands.m @@ -309,12 +309,67 @@ static void name_functions(id object, NSMutableSet *seen, NSMutableString *names stela_report(what.UTF8String, failure); } +/* The IOSurface a texture or buffer lies in, a view's its parent's, or NULL. */ +static IOSurfaceRef surface_of(id object, BOOL *buffer) +{ + *buffer = NO; + if ([object isKindOfClass:[StelaGPUBuffer class]]) { + *buffer = YES; + return ((StelaGPUBuffer *)object)->_surface; + } + for (int depth = 0; depth < 8 && [object isKindOfClass:[StelaGPUTexture class]]; depth++) { + StelaGPUTexture *texture = object; + if (texture->_surface) { + return texture->_surface; + } + if ([texture->_buffer isKindOfClass:[StelaGPUBuffer class]] && ((StelaGPUBuffer *)texture->_buffer)->_surface) { + return ((StelaGPUBuffer *)texture->_buffer)->_surface; + } + object = texture->_parent; + } + return NULL; +} + +/* Each IOSurface object the command buffer used, once, with its surface's ID + * and seed now, at its commit: the service refreshes its device-memory copy of + * a sampled surface only when the seed changed, which the CPU's writes do. */ +- (void)reportSurfaces +{ + os_unfair_lock_lock(&_referencesLock); + NSMutableSet *seen = nil; + for (NSUInteger i = 0; i < _retained.count; i++) { + id object = [_retained objectAtIndex:i]; + BOOL buffer; + IOSurfaceRef surface = surface_of(object, &buffer); + if (!surface) { + continue; + } + if (!seen) { + seen = [NSMutableSet setWithCapacity:8]; + } + /* By identity: the driver's objects keep NSObject's equality. */ + if ([seen containsObject:object]) { + continue; + } + [seen addObject:object]; + StelaSurfaceUse use = { + .object = ((StelaGPUObject *)object)->_handle, + .surface = IOSurfaceGetID(surface), + .seed = IOSurfaceGetSeed(surface), + .buffer = buffer ? 1 : 0, + }; + stela_stream_entry(&_stream, StelaCommandBufferCodeSurfaceUse, &use, sizeof(use), NULL, 0); + } + os_unfair_lock_unlock(&_referencesLock); +} + /* Under the queue's lock, so serials follow the order of enqueue. */ - (void)submit { _kernelStart = host_time(); [_logState commandBufferStarted]; [_device flushIndirect]; + [self reportSurfaces]; StelaCommitRequest request = { .commands = stela_span(_stream.bytes, _stream.length), .queue = _queue->_identity, diff --git a/xtask/src/gpu/metal_suite/wire.rs b/xtask/src/gpu/metal_suite/wire.rs index 104e814f8f..d0498eabbb 100644 --- a/xtask/src/gpu/metal_suite/wire.rs +++ b/xtask/src/gpu/metal_suite/wire.rs @@ -172,6 +172,8 @@ const OPERATIONS: &[(&str, Reach)] = &[ Reach::Call("sampleCountersInBuffer:"), ), ("CommandBufferCode::LogBuffer", Reach::Call("logState")), + // Each commit of a command buffer that uses an IOSurface texture. + ("CommandBufferCode::SurfaceUse", Reach::Call("iosurface:")), ("ComputeCode::Begin", Reach::Call("computeCommandEncoder")), ( "ComputeCode::SetPipeline",