diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 170d7435b..ea75673eb 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -228,7 +228,13 @@ the runtime made. (`shadowed-texture`, naming why) for every other texture there (under `HostPageTexturePolicy::Shadow`, one that renders or writes, one made before the check answered or whose check did not pass), where the device's linear images cannot hold Metal's layout, and - where the rows lie with bytes between them. + where the rows lie with bytes between them. On a discrete GPU, a texture whose policy and usage + take the image in place, over a no-copy buffer whose memory carries a log of its writes + (`HostMemory::with_dirty_pages`), tracked and laid out as one copy, is instead such a copy in + the device's memory, announced nowhere, whatever the check answered: its copies in take only the + rows the log reports changed, so the GPU reads the surface from its own memory, where in place it + reads the pages across the bus at every sample (`WorkCounts::device_copy_textures`). Exact either + way; integrated GPUs, CPU devices and memory without a log keep the image in place. - **Two-plane YCbCr textures** (`YCBCR8_420_2P` and its kin over a surface's planes) hold an image of the texels Metal reads, converted from the planes before a command buffer's first use where they changed. Where `has_unified_memory`, a function that only samples a `YCBCR8_420_2P` diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index 0f564c090..49d26eb55 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -1363,6 +1363,23 @@ impl Texels { /// copied in place (`shadow_copy_back.rs`), and its merges read the texels through `unorm`, /// its image's view of its own 8-bit unsigned normalized format, where given so /// (`shadow_merge.rs`). Refused as `new_buffer` refuses the staging buffer. + /// Whether these texels take a device copy on `device` (`texture.rs`, `dirty_pages.rs`): on + /// a discrete GPU, tracked, over host pages whose memory carries a log, where the shadow's + /// copy in is one region straight from the texels' place in the buffer's `VkBuffer` (one + /// slice, rows that share no bytes, a first texel at a multiple of the texel's size there), + /// the copy in a log decides. + pub(super) fn device_copy(&self, device: &Device) -> bool { + let layout = &self.layout; + let (_, at) = self.buffer.at_for(layout.offset, ReadApart::Texture); + let logged = (self.buffer.host_pages()).is_some_and(|pages| pages.dirty().is_some()); + device.properties().kind == crate::DeviceKind::Discrete + && self.tracked() + && layout.slices == 1 + && layout.shared_bytes() == 0 + && at.is_multiple_of(self.texel_bytes) + && logged + } + pub(super) fn shadow_copies( &self, image: vk::Image, diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 85ab19f32..676cbedce 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -2176,7 +2176,21 @@ impl Device { None if texels.buffer.in_fresh_pages() => Some(PagesClass::Fresh), _ => None, }; + // On a discrete GPU, a texture whose policy and usage take the image in place, over pages + // whose memory carries a log, is a device copy instead: a shadow whose copies in take + // only the rows the log reports changed (`dirty_pages.rs`), so the GPU reads the texels + // from its own memory, where in place it reads the pages across the bus at every sample. + // It binds no image to the pages, so the in-place check's verdict is not asked. + let device_copy = match class { + Some(class) if !in_place::checking() && !texels.buffer.detached() => { + let policy = self.compile_device().policy().host_page_textures; + in_place::in_place(policy, usage, class, |_| Verdict::Passed).is_ok() + && texels.device_copy(self) + } + _ => false, + }; let why = match class { + Some(_) if device_copy => String::new(), Some(class) => { let checking = in_place::checking(); let cause = if texels.buffer.detached() { @@ -2359,6 +2373,15 @@ impl Device { let copies = texels.shadow_copies(image.raw.get(), image.identity, aspects, views)?; // Its copies keep its own image, which it presents again once the bytes lie in pages. self.stand_in_while_detached(&texels.buffer, &image)?; + // A device copy degrades nothing: it holds the bytes wherever a command reads them. + if device_copy { + self.shared().counts.device_copy_texture(); + return Ok(Storage::Shadow { + image: image.shared(), + texels, + copies: Arc::new(copies), + }); + } let (offset, bytes_per_row) = (texels.layout.offset, texels.layout.row_pitch); self.degrade(Degradation::ShadowedTexture, || { let format = descriptor.pixel_format; diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 60060a91e..8ddc1b9b2 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -294,6 +294,7 @@ pub(crate) struct Counters { shadows_zeroed: AtomicU64, shadows_over_fresh_pages: AtomicU64, host_textures_in_place: AtomicU64, + device_copy_textures: AtomicU64, dma_buf_textures_in_place: AtomicU64, fresh_page_textures_in_place: AtomicU64, pitched_host_images: AtomicU64, @@ -2030,6 +2031,11 @@ impl Counters { (self.shadows_over_fresh_pages).fetch_add(1, Ordering::Relaxed); } + /// A texture over host pages was made a device copy of them (`texture.rs`). + pub(crate) fn device_copy_texture(&self) { + self.device_copy_textures.fetch_add(1, Ordering::Relaxed); + } + /// A texture over host pages of `class` was made an image in place over them (`in_place.rs`), /// its rows at Metal's pitch in a `DRM_FORMAT_MOD_LINEAR` image made for host allocations /// where `pitched`. @@ -4207,6 +4213,12 @@ pub struct WorkCounts { /// place, where the device's check passed for their class (`HostPageTexturePolicy::InPlace`): /// no shadow, and no copy in or back. pub host_textures_in_place: u64, + /// Textures over host pages that `host_textures_in_place` would count (or a shadow made + /// before the check answered or where it failed), made instead a copy in the device's memory + /// on a discrete GPU, where their memory carries a log of its writes + /// (`HostMemory::with_dirty_pages`): a shadow whose copies in take only the rows the log + /// reports changed (`dirty_copies_in_gated` and kin), announced nowhere. + pub device_copy_textures: u64, /// Of `host_textures_in_place`, those over pages imported as dma-bufs: each a /// `DRM_FORMAT_MOD_LINEAR` image over a dma-buf of its own pages (also counted in /// `dma_buf_images`). @@ -5186,6 +5198,7 @@ impl Device { shadowed_textures: counters.shadowed_textures.load(Ordering::Relaxed), shadows_over_fresh_pages: counters.shadows_over_fresh_pages.load(Ordering::Relaxed), host_textures_in_place: counters.host_textures_in_place.load(Ordering::Relaxed), + device_copy_textures: counters.device_copy_textures.load(Ordering::Relaxed), dma_buf_textures_in_place: counters.dma_buf_textures_in_place.load(Ordering::Relaxed), fresh_page_textures_in_place: counters .fresh_page_textures_in_place diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index e61e94e70..8b4337fd9 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -4314cee1feecf90c6eb979277e8c801fe687124aec0c2018aa6910554264df1d +5444426c46744d1bdcdb9fa83307a75b6b7d8d8775c91df28b9b53b4b8668816 diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 2ff622022..19dc21b3b 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -363,6 +363,8 @@ mod detach_textures; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod device_commands; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod device_copies; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod device_lockstep; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod discard_counts; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/device_copies.rs b/crates/metal2vulkan-validation/src/runtime_lane/device_copies.rs new file mode 100644 index 000000000..a29bdf42a --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/device_copies.rs @@ -0,0 +1,473 @@ +//! Device tests of device copies on the device the cfg selects: on a discrete GPU, a texture that +//! would read host pages in place, over a no-copy buffer whose memory carries a log of its writes +//! (`HostMemory::with_dirty_pages`), is a shadow in the device's memory whose copies in take only +//! the rows the log reports changed (the runtime's `dirty_pages.rs`); on any other device, and +//! without a log, it is placed as before. +//! +//! - [`a_sampled_surface_over_logged_pages_follows_the_guest_s_writes`], under the validation +//! layer: a 1920x1080 `BGRA8Unorm` surface over logged pages, read whole each frame by a +//! fragment function into a private target, which then holds the pages' texels after each +//! frame's CPU write of a run of a row. On a discrete GPU it is a device copy +//! (`device_copy_textures`, no `vk_image`): its first copy in moves every row, each later one +//! only the rows the log reported (`dirty_copies_in_gated`, `dirty_copy_in_bytes_copied`), one +//! with no change nothing (`dirty_copies_in_skipped`), and one whose wait the log answers +//! `false` every row (`dirty_copies_in_whole`). Elsewhere none is made. +//! - [`a_gpu_write_of_the_pages_reaches_the_device_copy`], under the validation layer: a blit's +//! fill of rows of the surface's buffer in one command buffer is what the next one's read finds +//! (on a discrete GPU a whole copy in: the fill let go of the copy's hold). +//! - [`without_a_log_the_surface_is_placed_as_before`], under the validation layer: the same +//! surface over pages without a log is no device copy. +//! - [`device_copy_costs`], without the validation layer, report only (built in release for the +//! numbers): a 3840x2160 `BGRA8Unorm` surface read whole each frame, with a few CPU-written +//! runs a frame, in one pass and in three, over pages without a log (in place where the check +//! passed) and with one (a device copy on a discrete GPU): the median and fastest GPU time of a +//! frame's command buffer (`DEVICE-COPY-COST`). + +use super::first_use_writes::CHECK_WAIT; +use super::host_memory::{counting, Mapping, GUEST_PAGE}; +use super::in_place_textures::{in_place, sampled}; +use super::no_copy_textures::{floats, staged}; +use super::pitched_surfaces::reading; +use super::{layer_reported_nothing_at_all, validated_device_with, Messages, ScratchCache, WAIT}; +use crate::gpu::TEST_DEVICE; +use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; +use metal2vulkan_runtime::{ + BlitOption, Buffer, CommandQueue, Device, DeviceKind, DirtyPages, DirtyStamp, HostMemory, + LoadAction, Origin, RenderPassDescriptor, RenderPipelineState, ResourceOptions, ScissorRect, + Size, StoreAction, Texture, TextureDescriptor, WorkCounts, +}; +use std::ops::Range; +use std::sync::{Arc, Mutex}; + +/// The log's page. +const PAGE: u64 = 4096; + +/// A log of the writes to a mapping's pages, as a consumer keeps one: each write stamped with the +/// publication it falls in, and each stamp the runtime asks for a new publication. +#[derive(Default)] +struct Log { + state: Mutex, +} + +#[derive(Default)] +struct LogState { + /// The publication writes fall in now. + now: u64, + /// Each write's pages and stamp. + writes: Vec<(Range, u64)>, + /// Whether the next wait cannot say. + cannot_say: bool, +} + +impl Log { + /// Note the CPU's write of the bytes `range`, whole pages. + fn mark(&self, range: Range) { + let mut state = self.state.lock().unwrap(); + let pages = range.start / PAGE * PAGE..range.end.div_ceil(PAGE) * PAGE; + let now = state.now; + state.writes.push((pages, now)); + } + + /// Make the next wait answer `false`. + fn cannot_say(&self) { + self.state.lock().unwrap().cannot_say = true; + } +} + +impl DirtyPages for Log { + type Watch = (); + + fn watch(&self, _: Range) {} + + fn request(&self) -> DirtyStamp { + let mut state = self.state.lock().unwrap(); + let stamp = state.now; + state.now += 1; + DirtyStamp(stamp) + } + + fn wait(&self, _: DirtyStamp) -> bool { + let mut state = self.state.lock().unwrap(); + !std::mem::take(&mut state.cannot_say) + } + + fn changed(&self, since: DirtyStamp, out: &mut Vec>) { + let state = self.state.lock().unwrap(); + let later = state.writes.iter().filter(|(_, stamp)| *stamp > since.0); + out.extend(later.map(|(pages, _)| pages.clone())); + } + + fn wrote(&self, range: Range) { + let mut state = self.state.lock().unwrap(); + let now = state.now; + state.writes.push((range, now)); + } +} + +/// A no-copy buffer over `mapping`'s `len` bytes on `device`, its memory carrying `log` where +/// given. +fn over(device: &Device, mapping: &Mapping, len: usize, log: Option<&Arc>) -> Buffer { + // SAFETY: the mapping outlives the buffer (dropped first by every caller), and stays + // writable. + let memory = unsafe { HostMemory::new(mapping.pointer()) }; + let memory = match log { + Some(log) => memory.with_dirty_pages(Arc::clone(log)), + None => memory, + }; + // SAFETY: as above. + unsafe { + device.new_buffer_with_bytes_no_copy(memory, len as u64, ResourceOptions::default(), None) + } + .unwrap() +} + +/// One frame's command buffer on `queue`: `passes` passes, each reading the top `rows` rows of +/// `texture` into `target` through `reads`; its GPU time. +fn frame( + queue: &CommandQueue, + (reads, corners): (&RenderPipelineState, &Buffer), + (texture, target): (&Texture, &Texture), + (w, rows): (u64, u64), + passes: usize, +) -> f64 { + let command_buffer = queue.command_buffer().unwrap(); + for _ in 0..passes { + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(target.clone()); + color.load_action = LoadAction::DontCare; + color.store_action = StoreAction::Store; + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(reads).unwrap(); + encoder + .set_scissor_rect(ScissorRect::new(0, 0, w, rows)) + .unwrap(); + encoder.set_vertex_buffer(Some(corners), 0, 0).unwrap(); + encoder.set_fragment_texture(Some(texture), 0).unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + } + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + command_buffer.gpu_end_time().unwrap() - command_buffer.gpu_start_time().unwrap() +} + +/// `target`'s `w` by `h` texels of 4 bytes, as a blit reads them into tight rows. +fn texels(queue: &CommandQueue, target: &Texture, (w, h): (u64, u64)) -> Vec { + let row = w * 4; + let out = (queue.device()) + .new_buffer(row * h, ResourceOptions::shared()) + .unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + let size = Size::new(w, h, 1); + let origin = Origin::new(0, 0, 0); + blit.copy_from_texture_to_buffer( + target, + 0, + 0, + origin, + size, + &out, + 0, + row, + row * h, + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + let contents = out.contents().unwrap(); + // SAFETY: the buffer's `row * h` bytes, which no command writes any longer. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), (row * h) as usize) }.to_vec() +} + +/// The texels of `w` by `h` (4 bytes each) of `mapping`, laid out `bpr` apart, as tight rows. +fn guest_texels(mapping: &Mapping, (w, h, bpr): (u64, u64, u64)) -> Vec { + let bytes = mapping.read(0..(bpr * h) as usize); + (0..h) + .flat_map(|y| { + let at = (y * bpr) as usize; + bytes[at..at + (w * 4) as usize].to_vec() + }) + .collect() +} + +/// A private `BGRA8Unorm` render target of `w` by `h` on `device`. +fn target_of(device: &Device, (w, h): (u64, u64)) -> Texture { + let mut d = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, w, h, false); + d.usage = TextureUsage::RENDER_TARGET; + d.resource_options = ResourceOptions::private(); + device.new_texture(&d).unwrap() +} + +/// Whether `device` makes device copies: a discrete GPU. +fn copies_on(device: &Device) -> bool { + device.properties().kind == DeviceKind::Discrete +} + +/// The changes of the device copies' counters from `before` to `after`: textures made, copies in +/// gated, of every row, skipped, and the bytes they moved. +fn copied(before: &WorkCounts, after: &WorkCounts) -> [u64; 5] { + let of = |c: &WorkCounts| { + [ + c.device_copy_textures, + c.dirty_copies_in_gated, + c.dirty_copies_in_whole, + c.dirty_copies_in_skipped, + c.dirty_copy_in_bytes_copied, + ] + }; + let (a, b) = (of(before), of(after)); + std::array::from_fn(|i| b[i] - a[i]) +} + +#[test] +fn a_sampled_surface_over_logged_pages_follows_the_guest_s_writes() { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), in_place).unwrap(); + let queue = device.new_command_queue().unwrap(); + let reads = reading(&device, PixelFormat::BGRA8Unorm, "tob_read"); + let corners = staged(&device, &floats([-1.0, -1.0, 1.0, 1.0])); + let (w, h, bpr) = (1920u64, 1080u64, 7680u64); + let len = ((bpr * h) as usize).next_multiple_of(GUEST_PAGE); + let mapping = Mapping::anonymous(len); + mapping.write(0, &counting(len, 3)); + let log = Arc::new(Log::default()); + let before = device.work_counts(); + let buffer = over(&device, &mapping, len, Some(&log)); + let texture = sampled(&buffer, PixelFormat::BGRA8Unorm, (w, h, bpr)); + let made = copied(&before, &device.work_counts()); + let discrete = copies_on(&device); + // SAFETY: the handle is only compared. + let in_place = unsafe { texture.vk_image() }.is_some(); + eprintln!( + "DEVICE-COPY on {} ({:?}): device copy {}, in place {in_place}", + device.name(), + device.properties().kind, + made[0] == 1 + ); + assert_eq!( + made[0], + u64::from(discrete), + "a device copy exactly on a discrete GPU" + ); + if discrete { + assert!(!in_place, "a device copy reads no image in place"); + } + let target = target_of(&device, (w, h)); + let objects = (&reads, &corners); + let check = |what: &str| { + let read = texels(&queue, &target, (w, h)); + let guest = guest_texels(&mapping, (w, h, bpr)); + assert!(read == guest, "{what}: the target holds the guest's texels"); + }; + // The first frame copies every row. + let start = device.work_counts(); + frame(&queue, objects, (&texture, &target), (w, h), 1); + check("the first frame"); + // Each later frame's CPU write of a run of one row, logged. + for (at, row) in [(3u64, 17u64), (1, 500), (7, 1079)] { + let offset = row * bpr + at * 64; + mapping.write(offset as usize, &[0xa5 ^ row as u8; 64]); + log.mark(offset..offset + 64); + frame(&queue, objects, (&texture, &target), (w, h), 1); + check(&format!("after a write of row {row}")); + } + // A frame with no write copies nothing; one whose wait cannot say copies every row. + frame(&queue, objects, (&texture, &target), (w, h), 1); + check("after no write"); + let offset = 900 * bpr; + mapping.write(offset as usize, &[0x3c; 128]); + log.mark(offset..offset + 128); + log.cannot_say(); + frame(&queue, objects, (&texture, &target), (w, h), 1); + check("after a wait that could not say"); + let counted = copied(&start, &device.work_counts()); + eprintln!( + "DEVICE-COPY on {}: gated {}, whole {}, skipped {}, bytes copied {}", + device.name(), + counted[1], + counted[2], + counted[3], + counted[4] + ); + if discrete { + assert_eq!(counted[1], 6, "each frame's copy in, gated"); + assert_eq!( + counted[2], 2, + "the first and the one that could not say: every row" + ); + assert_eq!(counted[3], 1, "no write: nothing"); + // Every row twice; a 4 KiB page of a 7680-byte row touches at most two rows, three times. + let row = w * 4; + assert!( + counted[4] <= 2 * h * row + 3 * 2 * row, + "bytes {}", + counted[4] + ); + } + drop((texture, buffer, target)); + drop(mapping); + layer_reported_nothing_at_all(&messages); +} + +#[test] +fn a_gpu_write_of_the_pages_reaches_the_device_copy() { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), in_place).unwrap(); + let queue = device.new_command_queue().unwrap(); + let reads = reading(&device, PixelFormat::BGRA8Unorm, "tob_read"); + let corners = staged(&device, &floats([-1.0, -1.0, 1.0, 1.0])); + let (w, h, bpr) = (256u64, 256u64, 1024u64); + let len = ((bpr * h) as usize).next_multiple_of(GUEST_PAGE); + let mapping = Mapping::anonymous(len); + mapping.write(0, &counting(len, 11)); + let log = Arc::new(Log::default()); + let buffer = over(&device, &mapping, len, Some(&log)); + let texture = sampled(&buffer, PixelFormat::BGRA8Unorm, (w, h, bpr)); + let target = target_of(&device, (w, h)); + let objects = (&reads, &corners); + frame(&queue, objects, (&texture, &target), (w, h), 1); + let start = device.work_counts(); + // A blit fills rows 40 to 47 of the buffer: the GPU's write, no CPU write logged. + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(&buffer, 40 * bpr..48 * bpr, 0x5a).unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + frame(&queue, objects, (&texture, &target), (w, h), 1); + let read = texels(&queue, &target, (w, h)); + assert!( + read == guest_texels(&mapping, (w, h, bpr)), + "the fill reached the read" + ); + assert!(read[(40 * w * 4) as usize..(48 * w * 4) as usize] + .iter() + .all(|&byte| byte == 0x5a)); + let counted = copied(&start, &device.work_counts()); + eprintln!( + "DEVICE-COPY on {}: after the fill gated {}, whole {}", + device.name(), + counted[1], + counted[2] + ); + if copies_on(&device) { + assert_eq!( + counted[1..3], + [1, 1], + "the fill let go of the hold: every row" + ); + } + drop((texture, buffer, target)); + drop(mapping); + layer_reported_nothing_at_all(&messages); +} + +#[test] +fn without_a_log_the_surface_is_placed_as_before() { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), in_place).unwrap(); + let (w, h, bpr) = (256u64, 256u64, 1024u64); + let len = ((bpr * h) as usize).next_multiple_of(GUEST_PAGE); + let mapping = Mapping::anonymous(len); + let before = device.work_counts(); + let buffer = over(&device, &mapping, len, None); + let texture = sampled(&buffer, PixelFormat::BGRA8Unorm, (w, h, bpr)); + let after = device.work_counts(); + assert_eq!( + copied(&before, &after)[0], + 0, + "no device copy without a log" + ); + assert_eq!( + after.host_textures_in_place - before.host_textures_in_place + after.shadowed_textures + - before.shadowed_textures, + 1, + "in place or a shadow, as before" + ); + drop((texture, buffer)); + drop(mapping); + layer_reported_nothing_at_all(&messages); +} + +#[test] +fn device_copy_costs() { + const FRAMES: usize = 40; + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| { + in_place(options); + options.layers.clear(); + }) + .unwrap(); + let queue = device.new_command_queue().unwrap(); + let reads = reading(&device, PixelFormat::BGRA8Unorm, "tob_read"); + let corners = staged(&device, &floats([-1.0, -1.0, 1.0, 1.0])); + let (w, h, bpr) = (3840u64, 2160u64, 15360u64); + let len = ((bpr * h) as usize).next_multiple_of(GUEST_PAGE); + let target = target_of(&device, (w, h)); + // A texture over host pages starts the device's in-place check, which the texture without a + // log then follows. + { + let mapping = Mapping::anonymous(GUEST_PAGE); + let buffer = over(&device, &mapping, GUEST_PAGE, None); + drop(sampled(&buffer, PixelFormat::BGRA8Unorm, (16, 16, 64))); + let settled = device.settle_in_place_checks(CHECK_WAIT); + eprintln!( + "DEVICE-COPY-COST on {}: the in-place check answered: {settled}", + device.name() + ); + } + for logged in [false, true] { + for passes in [1usize, 3] { + let mapping = Mapping::anonymous(len); + mapping.write(0, &counting(len, 5)); + let log = Arc::new(Log::default()); + let buffer = over(&device, &mapping, len, logged.then_some(&log)); + let texture = sampled(&buffer, PixelFormat::BGRA8Unorm, (w, h, bpr)); + // SAFETY: the handle is only compared. + let form = match (unsafe { texture.vk_image() }, logged && copies_on(&device)) { + (_, true) => "device copy", + (Some(_), false) => "in place", + (None, false) => "shadow", + }; + let start = device.work_counts(); + let mut times = Vec::with_capacity(FRAMES); + for f in 0..FRAMES as u64 { + // A few runs a frame, as a guest's cursor and a clock change. + for run in 0..4u64 { + let offset = ((f * 37 + run * 541) % h) * bpr + run * 1024; + mapping.write(offset as usize, &[f as u8; 256]); + log.mark(offset..offset + 256); + } + let objects = (&reads, &corners); + times.push(frame(&queue, objects, (&texture, &target), (w, h), passes)); + } + let counted = copied(&start, &device.work_counts()); + times.sort_by(f64::total_cmp); + eprintln!( + "DEVICE-COPY-COST on {}: {form}: a frame's GPU time median {:.1} us, fastest \ + {:.1} us, over {FRAMES} frames of {passes} pass(es) each reading a {w}x{h} \ + surface whole, 4 runs written a frame; copied in {} bytes ({} a frame)", + device.name(), + times[FRAMES / 2] * 1e6, + times[0] * 1e6, + counted[4], + counted[4] / FRAMES as u64, + ); + drop((texture, buffer)); + drop(mapping); + } + } +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs index 2dc8d7407..d90138f91 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs @@ -62,7 +62,7 @@ const FRESH: u64 = 40 << 20; /// The lane's options with textures over host pages taken in place where the check passes: the /// lane's devices otherwise take the exact answers, under which every one is a shadow. -fn in_place(options: &mut DeviceOptions) { +pub(super) fn in_place(options: &mut DeviceOptions) { options.policy.host_page_textures = HostPageTexturePolicy::InPlace; } @@ -105,7 +105,11 @@ fn refused(before: &WorkCounts, after: &WorkCounts) -> u64 { } /// A texture of `format`, `w` by `h`, `ShaderRead` alone, over `buffer` with rows `bpr` apart. -fn sampled(buffer: &Buffer, format: PixelFormat, (w, h, bpr): (u64, u64, u64)) -> Texture { +pub(super) fn sampled( + buffer: &Buffer, + format: PixelFormat, + (w, h, bpr): (u64, u64, u64), +) -> Texture { let mut d = TextureDescriptor::texture_2d(format, w, h, false); d.usage = TextureUsage::SHADER_READ; d.resource_options = buffer.resource_options(); diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 2f90c9734..899b9601d 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2545,6 +2545,7 @@ field metal2vulkan-runtime::WorkCounts.depth_attachments_moved pub depth_attachm field metal2vulkan-runtime::WorkCounts.depth_instances_held pub depth_instances_held: u64 field metal2vulkan-runtime::WorkCounts.descriptor_keys_built pub descriptor_keys_built: u64 field metal2vulkan-runtime::WorkCounts.detached_storage_reaches pub detached_storage_reaches: u64 +field metal2vulkan-runtime::WorkCounts.device_copy_textures pub device_copy_textures: u64 field metal2vulkan-runtime::WorkCounts.device_memory_allocated pub device_memory_allocated: u64 field metal2vulkan-runtime::WorkCounts.dirty_copies_in_gated pub dirty_copies_in_gated: u64 field metal2vulkan-runtime::WorkCounts.dirty_copies_in_skipped pub dirty_copies_in_skipped: u64 diff --git a/docs/API.md b/docs/API.md index 3f3a0e698..ed23eb9ec 100644 --- a/docs/API.md +++ b/docs/API.md @@ -269,6 +269,12 @@ before a use and back (merged back: only the bytes the commands changed) after a is bound to the pages, and `Texture::vk_image` gives `None` for it. A texture in place renders and is written beyond its declared usage, as plain Metal allows, through its usage shadow and an attachment stand-in, whose copies touch its texels alone. +On a discrete GPU, a texture whose policy and usage take the image in place, over a no-copy +buffer whose memory carries a log of its writes (`HostMemory::with_dirty_pages`), tracked, one +slice laid out as one copy, is instead a device copy (`WorkCounts::device_copy_textures`, whatever +the check answered): a shadow whose copies in take only the bands of rows the log reports changed +(`dirty_copies_in_gated` and kin). Its notice is not announced: it holds the bytes wherever a +command reads it. A texture placed in a heap over dma-buf pages is an image over a dma-buf of its own pages, which its first submission acquires from `VK_QUEUE_FAMILY_FOREIGN_EXT`; a linear image over a buffer of the runtime's own memory starts `VK_IMAGE_LAYOUT_PREINITIALIZED`, and its move from there keeps its