diff --git a/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs b/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs index 15e0c94bc..bc09303a2 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs @@ -14,7 +14,7 @@ pub(crate) enum Unlogged { /// (`predication.rs`), or one of a kind that logs none (a resource state encoder's). NoCalls, /// It left work for later that an encoding again does not record at once: a GPU-written - /// indirect dispatch's host step, or a scrub (`Segment::records_again`). + /// indirect dispatch's host step (`Segment::records_again`). Segments, /// The command buffer's failure fails it, or a fault of its own, as it commits. Fails, diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 704f51241..6badee03b 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -674,8 +674,9 @@ impl State { /// part (which goes, the encoding again leaving its own over the new pages, /// `shadow_splice.rs`), or a staged scatter's steps (which go, the encoding again staging it /// again, `host_ram/copy.rs`), or a shadow's gated copy in (which goes, the encoding again - /// copying in for itself, `shadow::GatedCopyIn`), or its group was submitted, or the command - /// buffer completed. + /// copying in for itself, `shadow::GatedCopyIn`), or a sparse texture's scrub (which goes, the + /// encoding again leaving its own, `sparse/emulated.rs`), or its group was submitted, or the + /// command buffer completed. pub(super) fn splice_replay( &mut self, at: usize, @@ -716,8 +717,8 @@ impl State { recorded.summary = summary; // Its first segments go: the encoding again left a segment of its own in each // pending dispatch's, each splice's or merge on the host's, each staged copy step's it - // staged again and each gated copy in's place, and its work on the GPU alone in - // segments of its own, and recorded each other staged gather's copy at once. + // staged again, each gated copy in's and each scrub's place, and its work on the GPU + // alone in segments of its own, and recorded each other staged gather's copy at once. // What the commit recorded of one stays retained, never submitted, as the first // recording does. for segment in recorded.segments.drain(..) { diff --git a/crates/metal2vulkan-runtime/src/deferred.rs b/crates/metal2vulkan-runtime/src/deferred.rs index 304189908..29d335f75 100644 --- a/crates/metal2vulkan-runtime/src/deferred.rs +++ b/crates/metal2vulkan-runtime/src/deferred.rs @@ -589,13 +589,16 @@ impl Deferred { /// (`shadow::GatedCopyIn`), which the encoding again's copy in leaves again, gated as it /// decides then (or records in place, where it decides to copy every texel): its gate of a /// log, made after the commit's decisions (`DirtyShadows::committed`), holds no stamp and - /// copies every region (`CopyInGate::regions`). The first's go unrun. + /// copies every region (`CopyInGate::regions`); and a sparse texture's scrub, left for its + /// batch's submission (`sparse::emulated::Scrub`), which the blit or the pass encoded again + /// leaves again over the same texture. The first's go unrun. pub(super) fn left_again_by_an_encoding_again(&self) -> bool { match self { Deferred::ShadowSplice(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) - | Deferred::GatedCopyIn(_) => true, + | Deferred::GatedCopyIn(_) + | Deferred::SparseScrub(_) => true, Deferred::GatherStage(gather) => !gather.encoded_again_through_imports(), _ => false, } @@ -826,10 +829,12 @@ impl Deferred { /// encoder again, the merge with it. So do a staged copy's steps, between the buffer its call /// resolved (`blit_at`) and the pages it named, and a splice's and a merge on the host's CPU /// part (`shadow_splice.rs`), which writes the pages the truth's buffer lay in at its - /// encoder's call, and a shadow's gated copy in, which copies from the truth's `VkBuffer` as - /// its encoder's call found it (`shadow::GatedCopyIn`): a rebind before the command buffer's - /// submission encodes that encoder again, its CPU part or its copy in over the new pages with - /// it, and one after it keeps the old pages until the command buffer completes (`rebind.rs`). + /// encoder's call, a shadow's gated copy in, which copies from the truth's `VkBuffer` as its + /// encoder's call found it (`shadow::GatedCopyIn`), and a sparse texture's scrub, which zeroes + /// tiles of its texture alone, as its batch mapped them, and reads no buffer + /// (`sparse::emulated::Scrub`): a rebind before the command buffer's submission encodes that + /// encoder again, its CPU part, its copy in or its scrub with it, and one after it keeps the + /// old pages until the command buffer completes (`rebind.rs`). /// Everything else its step resolves as it records: a rebind meanwhile is refused. pub(super) fn resolved_at_its_calls(&self, pipelines: bool) -> bool { match self { @@ -839,12 +844,10 @@ impl Deferred { | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) | Deferred::ShadowSplice(_) - | Deferred::GatedCopyIn(_) => true, + | Deferred::GatedCopyIn(_) + | Deferred::SparseScrub(_) => true, Deferred::RenderPass(pass) => pipelines && !pass.executes(), - Deferred::Execute(_) - | Deferred::Dispatch(_) - | Deferred::SparseScrub(_) - | Deferred::Loop(_) => false, + Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::Loop(_) => false, } } diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 535cb63fb..a803d320c 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -314,8 +314,9 @@ impl Segment { /// copies through the imports in its place (`Deferred::recorded_by_an_encoding_again`), or a /// splice's or a merge on the host's CPU part, a staged scatter's steps, a staged gather the /// imports would not copy, or a shadow's gated copy in, which the encoding again leaves again - /// over the new pages (`Deferred::left_again_by_an_encoding_again`). Its log is kept only - /// where every segment does. + /// over the new pages, or a sparse texture's scrub, which it leaves again over its texture + /// (`Deferred::left_again_by_an_encoding_again`). Its log is kept only where every segment + /// does. pub(super) fn records_again(&self) -> bool { self.pends() || self.work.may_run_on_gpu_alone() @@ -4165,7 +4166,8 @@ impl EncoderCore { /// GPU alone but one whose pipelines are being made or failed to make, left as the first /// encoding left it ([`Segment::keeps_pipelines`]), and a splice's or a merge on the host's /// CPU part and a staged copy's steps, left for their host steps, and a shadow's gated copy - /// in, left for its batch's submission (`Deferred::left_again_by_an_encoding_again`). Refused + /// in and a sparse texture's scrub, left for their batch's submission + /// (`Deferred::left_again_by_an_encoding_again`). Refused /// (internal) where the encoder, encoded again, failed or faulted its command buffer, or met a /// detached buffer, which its first encoding kept none of, or left work that no longer runs on /// the GPU alone: its place stays as it was. @@ -4229,7 +4231,7 @@ impl EncoderCore { // Its segments recorded at once on the GPU alone, as its commit recorded the first // encoding's (`command_buffer/reencode.rs`): work that no longer runs there refuses the // encoding again, but work whose pipelines are being made, a splice's CPU part, a - // staged copy's steps and a gated copy in, which keep their segments. + // staged copy's steps, a gated copy in and a scrub, which keep their segments. let mut parts = Vec::with_capacity(split.len()); for ((raws, mut segments), summary) in split.into_iter().zip(summaries) { for segment in &mut segments { @@ -4249,7 +4251,8 @@ impl EncoderCore { // A splice's or a merge on the host's CPU part, planned again over the pages the // buffer lies in now, and a staged copy's steps, staged again from there, are // left for their host steps as the commit left the first's, and a gated copy in - // for its batch's submission (`Deferred::left_again_by_an_encoding_again`). + // and a scrub for their batch's submission + // (`Deferred::left_again_by_an_encoding_again`). if segment.work.left_again_by_an_encoding_again() { let prepared = segment.work.prepare(&open.command_buffer, segment.host)?; segment.recorded = prepared.recorded; diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 470ac5299..1b6502b52 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -670,6 +670,8 @@ mod rebind_behind_a_wait; mod rebind_descriptor_slip; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod rebind_making_wait; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod rebind_sparse_scrub; mod recent_shape_keys; #[cfg(all(m2v_gpu, target_os = "linux"))] mod reclaim_submit_bench; diff --git a/crates/metal2vulkan-runtime/src/tests/rebind_sparse_scrub.rs b/crates/metal2vulkan-runtime/src/tests/rebind_sparse_scrub.rs new file mode 100644 index 000000000..5c8f9d32e --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/rebind_sparse_scrub.rs @@ -0,0 +1,186 @@ +//! A blit encoder that writes a sparse texture and fills a no-copy buffer, its command buffer +//! committed behind a shared-event wait only the host signals, and the buffer rebound before the +//! signal. The blit's write leaves a scrub of the unmapped tiles it wrote for its batch's +//! submission (`sparse::emulated::Scrub`, `Deferred::SparseScrub`), which reads no buffer: the +//! commit holds none of the buffer's pages until completion (`Deferred::resolved_at_its_calls`), +//! so the rebind encodes the encoder again (`command_buffer/reencode.rs`), the fill writing the +//! new pages, and the encoding again's scrub takes the first's place +//! (`Deferred::left_again_by_an_encoding_again`). +//! +//! A device test: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on the kind +//! of device the cfg selects. It prints `REBIND-SCRUB` lines, and returns where the device makes no +//! sparse texture or imports no host memory. + +use super::blit_holds::{device, Scratch, WAIT}; +use super::encoder_holds::words_of; +use super::rebind_behind_a_wait::{Page, BYTES}; +use crate::error::RuntimeGap; +use crate::{ + BlitOption, CommandBufferStatus, Error, EventRef, HeapDescriptor, HeapType, Origin, Region, + ResourceOptions, Size, TextureDescriptor, +}; +use metal2vulkan::bind::TileMapping; +use metal2vulkan::error::Feature; +use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; + +/// The sparse texture's side, in `R32Float` texels. +const SIDE: u64 = 256; + +/// The byte the fill writes. +const FILL: u8 = 0x5a; + +/// A rebind before the first submission of a buffer an encoder filled, the encoder's blit into a +/// sparse texture leaving a scrub, encodes the encoder again: the command buffer completes with no +/// error, the fill reaches the pages the buffer lies in and not those it left, and the texture's +/// mapped tiles hold what the blit encoded again wrote. +#[test] +fn a_rebind_before_the_first_submission_encodes_a_sparse_scrub_s_encoder_again() { + // Declared before the device, so dropped after it. + let pages = [Page::new(), Page::new()]; + let scratch = Scratch::new("rebind-scrub"); + let device = device(&scratch.0); + let lacks = |error: &Error| { + matches!(error, Error::Unsupported(u) if matches!(u.feature, Feature::SparseTextures { .. })) + || *error == Error::NotImplemented(RuntimeGap::SparseTileMaps) + }; + let descriptor = HeapDescriptor::new(HeapType::Sparse, 1 << 20, ResourceOptions::private()); + let heap = match device.new_heap(&descriptor) { + Ok(heap) => heap, + Err(error) if lacks(&error) => { + eprintln!("REBIND-SCRUB: no sparse heap: {error:?}"); + return; + } + Err(error) => panic!("a sparse heap: {error:?}"), + }; + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::R32Float, SIDE, SIDE, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::private(); + let texture = match heap.new_texture(&descriptor) { + Ok(texture) => texture, + Err(error) if lacks(&error) => { + eprintln!("REBIND-SCRUB: no sparse texture: {error:?}"); + return; + } + Err(error) => panic!("a sparse texture: {error:?}"), + }; + // SAFETY: each page outlives every buffer over it (dropped after the device), and only the + // buffer's commands use it while it lives. + let made = unsafe { + device.new_buffer_with_bytes_no_copy( + pages[0].memory(), + BYTES as u64, + ResourceOptions::shared(), + None, + ) + }; + let buffer = match made { + Ok(buffer) => buffer, + Err(Error::Unsupported(gap)) => { + eprintln!("REBIND-SCRUB: the device imports no host memory: {gap:?}"); + return; + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + }; + let queue = device.new_command_queue().unwrap(); + // The texture's left tiles mapped, in a command buffer of their own: the blit below writes + // them and the unmapped ones, which its scrub zeroes where the texture holds their memory. + let tile = device.sparse_tile_size(TextureType::Type2D, PixelFormat::R32Float, 1); + let (across, down) = (SIDE / tile.width, SIDE / tile.height); + let mapped = (across / 2).max(1); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.resource_state_command_encoder().unwrap(); + let region = Region::new_2d(0, 0, mapped, down); + (encoder.update_texture_mapping(&texture, TileMapping::Map, region, 0, 0)).unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None, "the mapping"); + let texels: Vec = (0..SIDE * SIDE) + .flat_map(|i| (i as f32).to_le_bytes()) + .collect(); + let source = device + .new_buffer_with_bytes(&texels, ResourceOptions::shared()) + .unwrap(); + // Its command buffer waits for an event only the host signals, below: the rebind comes before + // its first submission. + let gate = device.new_shared_event().unwrap(); + let encoding = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + (command_buffer.encode_wait_for_event(EventRef::Shared(&gate), 1)).unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_buffer_to_texture( + &source, + 0, + SIDE * 4, + SIDE * SIDE * 4, + Size::new(SIDE, SIDE, 1), + &texture, + 0, + 0, + Origin::new(0, 0, 0), + BlitOption::None, + ) + .unwrap(); + blit.fill_buffer(&buffer, 0..BYTES as u64, FILL).unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + assert_eq!(buffer.detach_backing(), Ok(true), "the detach"); + // SAFETY: as above. + let rebound = unsafe { buffer.rebind_bytes_no_copy(pages[1].memory(), None, None) }; + // Read before the submission: the rebind encodes again in its own call. + let counts = device.work_counts(); + gate.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + let (status, error) = (command_buffer.status(), command_buffer.error()); + let reencoded = counts.encoders_reencoded - encoding.encoders_reencoded; + let (old, new) = (pages[0].written(), pages[1].written()); + println!( + "REBIND-SCRUB {}: tile {}x{}, {mapped} of {across} columns mapped; rebind {rebound:?}; \ + {status:?} {error:?}; encoders encoded again {reencoded}, refused {}; old pages written \ + {old}, new {new}", + device.name(), + tile.width, + tile.height, + counts.reencodes_refused - encoding.reencodes_refused, + ); + rebound.unwrap(); + assert_eq!((status, error), (CommandBufferStatus::Completed, None)); + assert_eq!(reencoded, 1, "the rebind encoded the encoder again"); + let filled = u32::from_ne_bytes([FILL; 4]); + assert!( + pages[1].words().iter().all(|&word| word == filled), + "the fill wrote every byte of the pages the buffer lies in" + ); + assert!( + !old, + "the fill wrote the pages the buffer left before the submission" + ); + // The mapped tiles hold what the blit encoded again wrote. + let width = mapped * tile.width; + let read = device + .new_buffer(width * SIDE * 4, ResourceOptions::shared()) + .unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_texture_to_buffer( + &texture, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(width, SIDE, 1), + &read, + 0, + width * 4, + width * SIDE * 4, + 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, "the read"); + let wanted: Vec = (0..SIDE) + .flat_map(|row| (0..width).map(move |column| ((row * SIDE + column) as f32).to_bits())) + .collect(); + assert_eq!(words_of(&read), wanted, "the mapped tiles' texels"); +} diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index c43f33601..c64b0b0f1 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2451; +pub const RUNTIME_VERSION: u32 = 2452; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles