diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index e2f05e186..7585e9145 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -3963,7 +3963,10 @@ impl CommandBuffer { /// `commit`: hand the batches to the device's scheduler, which submits them in the queue's /// commit order, each once the events it waits for are reached. It returns at once, as /// Metal's does: the scheduler's thread makes every submission, so no driver call holds it - /// (`scheduler/inbox.rs`). + /// (`scheduler/inbox.rs`), but the build of a decode kernel of the runtime's own that a + /// carried texture made, viewed or written since the last submission needs, once per device + /// for each decode, before the scheduler's section (`texture/decoded_twin.rs`), which no + /// texture's making builds. /// /// The indirect command buffers' commands the encoders execute are recorded first, from /// their records as they are now: each through the plan path, as a dispatch of the encoder @@ -3972,7 +3975,8 @@ impl CommandBuffer { /// oversized threadgroup) is left out. /// /// Refused (and nothing submitted) when the command buffer was committed already, an - /// encoder is open, or an encoder was abandoned (`Invalid`). A submission the device fails + /// encoder is open, or an encoder was abandoned (`Invalid`), and as that decode kernel's + /// making is (out of memory, a pipeline the device refuses). A submission the device fails /// completes the command buffer with that error ([`CommandBuffer::error`]), as Metal reports /// it on the command buffer. A command buffer that encoded a render pass without attachments /// past 16384 a side fails from that pass on, as Metal's does @@ -4112,6 +4116,10 @@ impl CommandBuffer { hand: Hand, ) -> Result<(), Error> { let shared = self.0.device.shared(); + // The kernels of the decode passes staged or queued for the device's next submissions, + // made here, on the committing thread, before the scheduler's section, where no other + // queue's submission waits for the compile (`texture/decoded_twin.rs`). + self.0.device.make_pending_decodes()?; // An unshared queue's commit holds other queues' batches back from its `VkQueue` for a // while (`unshared_hold.rs`), from before its own batches reach the scheduler. if self.0.queue.unshared() { diff --git a/crates/metal2vulkan-runtime/src/device/submit.rs b/crates/metal2vulkan-runtime/src/device/submit.rs index f88f32209..0b5b956db 100644 --- a/crates/metal2vulkan-runtime/src/device/submit.rs +++ b/crates/metal2vulkan-runtime/src/device/submit.rs @@ -255,6 +255,10 @@ impl Device { if self.is_lost() { return Err(self.lost_refusal()); } + // The kernels of the decode passes staged or queued for the device's next submissions, + // made before the internal lock, which every internal submission waits for + // (`texture/decoded_twin.rs`). + self.make_pending_decodes()?; let shared = self.shared(); let raw = shared.vk(); let firsts = &shared.textures.first_moves; diff --git a/crates/metal2vulkan-runtime/src/owned_kernel.rs b/crates/metal2vulkan-runtime/src/owned_kernel.rs index 406e774c9..d941b7789 100644 --- a/crates/metal2vulkan-runtime/src/owned_kernel.rs +++ b/crates/metal2vulkan-runtime/src/owned_kernel.rs @@ -1427,6 +1427,11 @@ impl FirstUse { Ok(()) } + /// Whether the kernel and the sets were made ([`make`](Self::make)). + pub(super) fn is_made(&self) -> bool { + self.made.get().is_some() + } + /// The kernel and the sets, for a record: every command that records a dispatch of them used /// the resource first, which made them ([`make`](Self::make)). `None` where none did, and a /// debug build panics: the record then records nothing. diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 9c431b214..ea3e1a598 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -280,6 +280,9 @@ pub(super) struct TextureState { /// The decodes queued for ASTC carriers' second decoded twins, which the device's next batch /// with work records (`texture/decoded_twin.rs`). pub(super) second_decodes: decoded_twin::SecondDecodes, + /// Whether a decode pass whose kernel is not made was staged or queued since the last walk + /// that makes them (`Device::make_pending_decodes`). + pub(super) decodes_unmade: AtomicBool, /// The multisampled depth textures held in the attachment layout between passes /// (`texture/held_depth.rs`). pub(crate) held: held_depth::HeldImages, @@ -326,6 +329,7 @@ impl TextureState { ), twin_decodes: twin_decode::TwinDecodes::default(), second_decodes: Mutex::new(Vec::new()), + decodes_unmade: AtomicBool::new(false), held: held_depth::HeldImages::default(), } } @@ -7726,8 +7730,12 @@ impl Texture { }; let keeper: Weak = Arc::downgrade(truth); let firsts = &device.shared().textures.first_moves; - // Past the bound, the copies staged so far are made now, by a submission waited for. - if firsts.register_texels(keeper, staged) { + // Its decode's kernel made before the submission that takes it takes its lock + // (`Device::make_pending_decodes`). Past the bound, the copies staged so far are made + // now, by a submission waited for. + let past = firsts.register_texels(keeper, staged); + device.note_unmade_decode(); + if past { truth.submit_copy(|_, _| {})?; } // An ASTC carrier's second twin's decode, for the next batch, after the copy. @@ -7740,7 +7748,11 @@ impl Texture { truth.shadow_written(&image_region, &unit, packed); let (buffer, image) = (staging.raw, truth.raw.get()); // The decoded twin's texels of the region, after the copy; the submission is waited for. + // Its kernel made now, before the submission takes its lock. let decode = truth.decode_pass(std::slice::from_ref(&image_region), PassScratch::Own)?; + if let Some(decode) = &decode { + decode.make(device)?; + } truth.submit_copy(|raw, command_buffer| { transfer_barrier(raw, command_buffer, true); // SAFETY: the internal command buffer is recording; the staging buffer and the images diff --git a/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs b/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs index ab4886880..03d77002d 100644 --- a/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs +++ b/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs @@ -104,6 +104,21 @@ //! submissions there (no host or staging copies), each followed by its pass, so no texel of the //! twin is the CPU's (Metal's) decode. //! +//! **Kernels at first use.** A decode pass keeps, as it is made, what its sets bind; its kernel +//! (once per device for each decode) and its sets are made by the first thing that records it +//! or before ([`DecodePass::make`], `owned_kernel::FirstUse`): a blit's decode, and a decode its +//! write makes for a second twin, as the blit is encoded; a host call's own submission before +//! it is made; and every pass staged for the device's next submission (a heap texture's whole +//! decode, a host call's staged copy's) or queued for a second twin (its whole decode, a host +//! write's) on the submitting thread, before the submission takes its lock: a commit before the +//! scheduler's section, an internal submission before the device's internal lock +//! ([`Device::make_pending_decodes`]). So no texture's making (a heap's texture, a view of +//! its other colour space, a 4:2:2 texture whose twin samples the pairs, whose making makes the +//! device's conversion alone) compiles a pipeline, and no submission compiles inside a lock +//! other submissions wait for. A pass staged after a submission's walk began, its texture made +//! meanwhile, waits for a later submission, with every staged copy after it, so the copies keep +//! their order: none of that submission's commands reads such a texture. +//! //! **Cost**, announced once per device (`carried-decoded-twin`, performance): the carrier and the //! twin's memory, and a decode pass after each write. A `VkImage` handed out (`Texture::vk_image`) //! is the carrier: what the caller writes into it outside the runtime's calls leaves the twin as @@ -135,7 +150,7 @@ use super::super::error::{internal, Error}; use super::super::etc; use super::super::exit_guard::{self, Call}; use super::super::image_plan::ImagePlan; -use super::super::owned_kernel::{OwnedModule, OwnedSet, OwnedSets}; +use super::super::owned_kernel::{FirstUse, OwnedModule, OwnedSet}; use super::super::pvrtc; use super::super::resource::Identity; use super::super::resource::ResourceKey; @@ -164,6 +179,7 @@ use metal2vulkan::metal::PixelFormat; use metal2vulkan::vk::{ Format, FormatFeatureFlags2, ImageAspectFlags, ImageCreateFlags, ImageType, ImageUsageFlags, }; +use std::sync::atomic::Ordering; use std::sync::{Arc, Mutex, Weak}; /// What a decoded twin's format must take on the device: sampling, its linear filter and copies @@ -936,8 +952,10 @@ impl Image { /// Stage the decode of `regions` of the image into its decoded twin for the device's next /// submission (`TexelCopy::decode_only`), what the image holds there already: a heap's - /// bytes. Past the bound, made now. Nothing for an image without a twin. (no longer a host - /// call's copy's, which the CPU decodes, [`decode_written`](Self::decode_written).) + /// bytes; its kernel made before the submission that takes it takes its lock + /// ([`Device::make_pending_decodes`]), not now. Past the bound, made now. Nothing for an + /// image without a twin. (no longer a host call's copy's, which the CPU decodes, + /// [`decode_written`](Self::decode_written).) pub(super) fn stage_decode(self: &Arc, regions: &[ImageRegion]) -> Result<(), Error> { let firsts = &self.device.shared().textures.first_moves; let Some(pass) = self.decode_pass(regions, PassScratch::Device)? else { @@ -945,7 +963,9 @@ impl Image { }; let staged = TexelCopy::decode_only(pass); let keeper: Weak = Arc::downgrade(self); - if firsts.register_texels(keeper, staged) { + let past = firsts.register_texels(keeper, staged); + self.device.note_unmade_decode(); + if past { self.submit_copy(|_, _| {})?; } Ok(()) @@ -1357,9 +1377,10 @@ impl Image { std::ptr::copy_nonoverlapping(plan.shape.as_ptr(), to, plan.shape.len()); } } - let (kernel, sets) = match &decoded.pairs { + // The kernel and a set a step, made where the pass is first recorded or before + // (`DecodePass::make`), never as the pass is made. + let kernel = match &decoded.pairs { None => { - let kernel = device.owned_kernel(OwnedModule::TwinDecode(decode))?; let ranges: Vec<[(vk::Buffer, u64, u64); 3]> = (layouts.iter()) .zip(0u64..) .map(|(&(blocks, texels_at, texels), at)| { @@ -1370,7 +1391,7 @@ impl Image { ] }) .collect(); - (kernel, OwnedSets::write(device, &kernel, &ranges)?) + FirstUse::of_buffers(OwnedModule::TwinDecode(decode), &ranges) } // The pairs' image, then the shape and the texels (`bind::ChromaSampleModule`). Some(pairs) => { @@ -1385,20 +1406,15 @@ impl Image { ], }) .collect(); - let kernels = vec![pairs.kernel; owned.len()]; device.shared().counts.chroma_device_decode(); - ( - pairs.kernel, - OwnedSets::write_each(device, &kernels, &owned)?, - ) + FirstUse::new(pairs.module(), owned) } }; let steps = steps .iter() .zip(&plans) .zip(&layouts) - .zip(&sets.sets) - .map(|(((region, plan), &(_, texels_at, _)), &set)| Step { + .map(|((region, plan), &(_, texels_at, _))| Step { blocks: vk::BufferImageCopy { buffer_offset: base, ..buffer_image_copy(&plan.blocks) @@ -1413,7 +1429,6 @@ impl Image { buffer_offset: base + texels_at, ..buffer_image_copy(region) }, - set, groups: plan.groups, }) .collect(); @@ -1426,14 +1441,12 @@ impl Image { .as_ref() .map_or(vk::Image::null(), |pairs| pairs.image), scratch: raw_scratch, - pipeline: kernel.pipeline, - layout: kernel.layout, steps, bytes, held: Held { _scratch: scratch, _shapes: shapes, - _sets: sets, + kernel: Arc::new(kernel), }, })) } @@ -1470,8 +1483,6 @@ impl Image { Feature::TextureView, ))); } - // The kernel that keeps it in step, made now rather than by a submission. - device.owned_kernel(OwnedModule::TwinDecode(decode))?; // Its uses are the image's, as the first twin's; it takes no CPU copy, so only the GPU // writes it, in submission order. let mut own = descriptor; @@ -1525,6 +1536,7 @@ impl Image { uses, }; lock(&self.device.shared().textures.second_decodes).push(queued); + self.device.note_unmade_decode(); Ok(()) } @@ -1684,16 +1696,16 @@ struct Step { blocks: vk::BufferImageCopy, pairs: Option, texels: vk::BufferImageCopy, - set: vk::DescriptorSet, groups: [u32; 3], } /// What a decode pass holds until the command that records it completed: its own scratch -/// (`None` in the device's, which the device keeps), its shapes and its sets. +/// (`None` in the device's, which the device keeps), its shapes, and its kernel and sets, a set +/// a step ([`DecodePass::make`]). struct Held { _scratch: Option, _shapes: Buffer, - _sets: OwnedSets, + kernel: Arc, } /// A decode into an ASTC carrier's second decoded twin (the module docs) that a batch records @@ -1761,10 +1773,50 @@ pub(crate) struct QueuedDecode { pub(crate) type SecondDecodes = Mutex>; impl Device { + /// Note that a decode pass whose kernel is not made was staged or queued, for the next walk + /// ([`make_pending_decodes`](Self::make_pending_decodes)): after its registration, so a + /// walk that reads the note finds the pass. + pub(super) fn note_unmade_decode(&self) { + (self.shared().textures.decodes_unmade).store(true, Ordering::Release); + } + + /// Make the kernels and sets of the decode passes staged for the device's next submission + /// (a heap texture's whole decode, a host call's staged copy's) and queued for second + /// decoded twins that are not made yet ([`DecodePass::make`]), on the submitting thread + /// before a submission takes its lock: a commit before the scheduler's section, an internal + /// submission before the device's internal lock. So no submission compiles while it holds + /// a lock other queues' submissions wait for, and no texture's making compiles. The passes + /// are listed under their registries' locks and made once those are free, so a making that + /// stages one never waits behind a compile. A pass staged after the walk began (its texture + /// made meanwhile) is left to a later submission, which takes none unmade. One atomic swap + /// where no unmade pass was staged since the last walk. Refused as a kernel's or its sets' + /// making is; the next walk tries again. + pub(crate) fn make_pending_decodes(&self) -> Result<(), Error> { + let textures = &self.shared().textures; + if !textures.decodes_unmade.swap(false, Ordering::AcqRel) { + return Ok(()); + } + let mut unmade = textures.first_moves.unmade_decodes(); + let queued = lock(&textures.second_decodes); + unmade.extend(queued.iter().filter_map(|decode| decode.pass.unmade())); + drop(queued); + for kernel in unmade { + if let Err(error) = kernel.make(self) { + self.note_unmade_decode(); + return Err(error); + } + } + Ok(()) + } + /// The decodes queued for second decoded twins (the module docs), taken for the batch now /// submitted to record before its work, in the order they were queued, but those of an image - /// for which `held` answers true (a write of the batch's made no decode), which stay queued - /// for a later batch, and those of an image gone, dropped. + /// for which `held` answers true (a write of the batch's made no decode) and those whose + /// kernel is not made (queued after the batch's walk, [`make_pending_decodes`]: of a view + /// made after its commit began, which none of its commands reads), which stay queued for a + /// later batch, and those of an image gone, dropped. + /// + /// [`make_pending_decodes`]: Self::make_pending_decodes pub(crate) fn take_second_decodes( &self, held: impl Fn(ResourceKey) -> bool, @@ -1774,7 +1826,7 @@ impl Device { return Vec::new(); } let (kept, taken): (Vec, Vec) = - queued.drain(..).partition(|decode| held(decode.key)); + (queued.drain(..)).partition(|decode| held(decode.key) || !decode.pass.is_made()); queued.extend(kept); drop(queued); taken @@ -1815,8 +1867,6 @@ pub(crate) struct DecodePass { /// A 4:2:2 twin's pairs' image, where it holds the device's conversion; null elsewhere. pairs: vk::Image, scratch: vk::Buffer, - pipeline: vk::Pipeline, - layout: vk::PipelineLayout, steps: Vec, /// The bytes of its own scratch (none in the device's). pub(super) bytes: u64, @@ -1824,6 +1874,27 @@ pub(crate) struct DecodePass { } impl DecodePass { + /// Make its kernel (`OwnedModule::TwinDecode`, or a 4:2:2 twin's `ChromaSample`; once per + /// device) and its sets, once: by its maker, where it records the pass at once (a blit's + /// decode, a replace's own submission), else before the submission that records it takes its + /// lock ([`Device::make_pending_decodes`]); never as a texture is made. Refused as the + /// kernel's or the sets' making is; a later attempt tries again. + pub(crate) fn make(&self, device: &Device) -> Result<(), Error> { + self.held.kernel.make(device) + } + + /// Whether its kernel and sets were made ([`make`](Self::make)): a submission takes no pass + /// that is not. + pub(crate) fn is_made(&self) -> bool { + self.held.kernel.is_made() + } + + /// Its kernel and sets, where they are not made yet, for a making outside every lock + /// ([`Device::make_pending_decodes`]). + pub(crate) fn unmade(&self) -> Option> { + (!self.is_made()).then(|| Arc::clone(&self.held.kernel)) + } + /// Record the pass: after every write before it, each band's blocks copied into the /// scratch, decoded, and its texels copied into the twin, each step past a barrier, then a /// barrier to everything after. Only entry points of the exit guard's table (a staged @@ -1834,14 +1905,20 @@ impl DecodePass { /// `raw` is recording, outside a render pass, on a queue family with compute; the image, the /// twin and the pass live until it completes; both images are in the `GENERAL` layout. pub(crate) unsafe fn record(&self, device: &Vk, raw: vk::CommandBuffer) { + // Made before any record ([`make`](Self::make)): where it is recorded at once, by its + // maker; where staged or queued, before the submission that records it took its lock + // (`Device::make_pending_decodes`), which takes none unmade. + let Some((kernel, sets)) = self.held.kernel.made() else { + return; + }; let general = vk::ImageLayout::GENERAL; let compute = vk::PipelineBindPoint::COMPUTE; // SAFETY: the caller's contract; each copy lies in its image and in the scratch, and // each dispatch reads and writes within its set's ranges (`decode_pass`). unsafe { Barrier::everything().record(device, raw); - device.cmd_bind_pipeline(raw, compute, self.pipeline); - for step in &self.steps { + device.cmd_bind_pipeline(raw, compute, kernel.pipeline); + for (step, set) in self.steps.iter().zip(&sets.sets) { let blocks = std::slice::from_ref(&step.blocks); device.cmd_copy_image_to_buffer(raw, self.image, general, self.scratch, blocks); Barrier::everything().record(device, raw); @@ -1877,8 +1954,8 @@ impl DecodePass { device.cmd_copy_buffer_to_image(raw, self.scratch, self.pairs, general, pairs); Barrier::everything().record(device, raw); } - let set = std::slice::from_ref(&step.set); - device.cmd_bind_descriptor_sets(raw, compute, self.layout, 0, set, &[]); + let set = std::slice::from_ref(set); + device.cmd_bind_descriptor_sets(raw, compute, kernel.layout, 0, set, &[]); let [x, y, z] = step.groups; device.cmd_dispatch(raw, x, y, z); Barrier::everything().record(device, raw); @@ -1920,6 +1997,9 @@ impl BlitCommandEncoder { let Some(pass) = image.decode_pass(®ions, PassScratch::Own)? else { return Ok(()); }; + // Its kernel made now, as the blit is encoded (`DecodePass::make`). + let device = image.device.clone(); + pass.make(&device)?; let uses = image.decode_uses(®ions); let stages = TRANSFER | vk::PipelineStageFlags2::COMPUTE_SHADER; self.command_in(stages, &uses, |device, raw| { @@ -1933,6 +2013,10 @@ impl BlitCommandEncoder { // twin, by the decode made now where it has one (the module docs). if matches!(image.decoded.as_deref(), Some(d) if matches!(d.decode, TwinDecode::Astc(..))) { let decode = image.second_decode(®ions)?; + // Made now, as the blit is encoded: its batch's submission records it in its section. + if let Some(decode) = &decode { + decode.pass.make(&device)?; + } let key = image.identity.key; self.core().wrote_twin(TwinWrite { key, decode }); } diff --git a/crates/metal2vulkan-runtime/src/texture/first_move.rs b/crates/metal2vulkan-runtime/src/texture/first_move.rs index 6e169f8bc..f6650785a 100644 --- a/crates/metal2vulkan-runtime/src/texture/first_move.rs +++ b/crates/metal2vulkan-runtime/src/texture/first_move.rs @@ -81,7 +81,11 @@ //! device's makes before its own: `texture/staging_copy.rs`) stages the bytes //! ([`TexelCopy`], [`FirstMoves::register_texels`]): the next submission copies them in at //! the start of its work, after the first work's `VkSubmitInfo`, each copy after the writes before -//! it, and holds the image and the staging buffer until it completed. +//! it, and holds the image and the staging buffer until it completed. A copy's decode into its +//! texture's decoded twin (`texture/decoded_twin.rs`, a heap texture's whole decode alone) +//! has its kernel made before the submission takes its lock (`Device::make_pending_decodes`); +//! one staged after that walk began is left, with every staged copy after it, for a later +//! submission, so the copies keep their order ([`FirstMoves::unmade_decodes`]). //! - **Bounded**. Past [`STAGED_BYTES`] bytes, or [`STAGED_COPIES`] copies, staged for the next //! submission (copies into buffers from staging buffers of their own, and staged texel copies), //! the call that staged the last makes a submission for them and waits @@ -172,6 +176,7 @@ use super::super::exit_guard::{self, Call}; use super::super::heap_sets::HeldSlots; use super::super::image_barrier::{image_barrier, ImageDst}; use super::super::memory::{Memory, MemoryClass, Placement}; +use super::super::owned_kernel::FirstUse; use super::super::release; use super::super::render_target::{FramebufferObject, RenderPassObject}; use super::super::resource::{ObjectId, ResourceKey}; @@ -1528,6 +1533,19 @@ impl FirstMoves { past_bound(&waiting) } + /// The kernels and sets of the staged copies' decode passes not made yet + /// ([`DecodePass::unmade`]), for `Device::make_pending_decodes` to make once this lock is + /// free. + pub(crate) fn unmade_decodes(&self) -> Vec> { + let waiting = lock(&self.waiting); + (waiting.iter()) + .filter_map(|entry| match entry { + Waiting::Texels(_, copy) => copy.decode.as_ref().and_then(DecodePass::unmade), + Waiting::Moves(_) | Waiting::Fill(..) => None, + }) + .collect() + } + /// Take the work a submission does: all of it, but the moves of images bound to host pages /// whose key `named` does not name (an internal submission's; a batch names every key, the /// module docs). What goes is dropped once the lock is free. @@ -1637,6 +1655,11 @@ impl FirstMoves { } // Each entry in its order: kept, taken, or a fill whose turn waits for the moves. let mut sorted = Vec::with_capacity(waiting.len()); + // Whether a staged copy waits for a later submission: its decode's kernel is not + // made, staged after this submission's walk (`Device::make_pending_decodes`), which + // its maker's texture, made after that walk began, no command of this submission + // reads. Every staged copy after it waits too, so the copies keep their order. + let mut texels_kept = false; for entry in waiting.drain(..) { if !wanted(&entry) { sorted.push(Sorted::Kept(entry)); @@ -1679,6 +1702,11 @@ impl FirstMoves { } // An image gone takes its copy and staging buffer with it. Waiting::Texels(weak, copy) => { + texels_kept |= copy.decode.as_ref().is_some_and(|pass| !pass.is_made()); + if texels_kept { + sorted.push(Sorted::Kept(Waiting::Texels(weak, copy))); + continue; + } if let Some(image) = weak.upgrade() { every_fill = true; let owner = diff --git a/crates/metal2vulkan-runtime/src/texture/surface_pairs.rs b/crates/metal2vulkan-runtime/src/texture/surface_pairs.rs index 3a921a23b..26acb55f4 100644 --- a/crates/metal2vulkan-runtime/src/texture/surface_pairs.rs +++ b/crates/metal2vulkan-runtime/src/texture/surface_pairs.rs @@ -153,6 +153,8 @@ enum PairsMade { /// texels out, and the workgroups. struct DeviceMade { pairs: PairsSampling, + /// The pairs' sample kernel ([`PairsSampling::module`]). + kernel: OwnedKernel, _scratch: Buffer, scratch_raw: vk::Buffer, scratch_use: (ResourceKey, Range), @@ -482,6 +484,7 @@ impl PairsConversion { let device = &self.device; let [width, height] = self.size; let pairs = PairsSampling::new(device, sampler, self.size)?; + let kernel = device.owned_kernel(pairs.module())?; let texels = u64::from(width) * u64::from(height) * 4; let scratch = device.own_buffer(texels, ResourceOptions::private())?; let (scratch_raw, scratch_at) = scratch.at(0); @@ -496,7 +499,7 @@ impl PairsConversion { (scratch_raw, scratch_at, texels), ], }; - let sets = OwnedSets::write_each(device, &[pairs.kernel], &[set])?; + let sets = OwnedSets::write_each(device, &[kernel], &[set])?; let layers = vk::ImageSubresourceLayers { aspect_mask: vk::ImageAspectFlags::COLOR, mip_level: 0, @@ -513,6 +516,7 @@ impl PairsConversion { .map_err(|_| internal("a 4:2:2 texture's rows past a word"))?; Ok(PairsMade::Device(Box::new(DeviceMade { pairs, + kernel, _scratch: scratch, scratch_raw, scratch_use: (identity.key, range), @@ -691,7 +695,7 @@ impl PairsConversion { pairs_in, ); Barrier::everything().record(device, command_buffer); - let kernel = &made.pairs.kernel; + let kernel = &made.kernel; device.cmd_bind_pipeline(command_buffer, point, kernel.pipeline); device.cmd_bind_descriptor_sets( command_buffer, diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 527f2d100..1e916b162 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -10697,10 +10697,11 @@ pub struct WorkCounts { /// a driver that compiles a pipeline as it is created is a shader compile. A kernel is built /// **by the Metal call that first needs it** and then kept for the device, so the count /// attributes the build to that call: encoding a command where the command is, a resource's - /// own moves included at its first use (`owned_kernel::FirstUse`), and making a carried - /// texture's decoded twin where its decode is made with it (`texture/decoded_twin.rs`: a 4:2:2 - /// texture's on a device that converts its pairs, a heap texture's whole decode, a view's - /// second twin). A later call that takes a kernel already built adds + /// own moves included at its first use (`owned_kernel::FirstUse`), and a commit or an + /// internal submission where a decoded twin's decode staged or queued since the last needs + /// it (`texture/decoded_twin.rs`: a heap texture's whole decode, a view's second twin, a + /// host call's staged copy's), before the submission's lock. No making builds one. A later + /// call that takes a kernel already built adds /// nothing, so a reading of 0 beside a kernel's dispatch says the build landed in an earlier /// call. Metal builds none of these: they are what the emulation costs, and the count is /// where that cost fell. A render execution's draw replay's are begun ahead, on the device's diff --git a/crates/metal2vulkan-runtime/src/ycbcr_device.rs b/crates/metal2vulkan-runtime/src/ycbcr_device.rs index 69688e6ac..77ad32301 100644 --- a/crates/metal2vulkan-runtime/src/ycbcr_device.rs +++ b/crates/metal2vulkan-runtime/src/ycbcr_device.rs @@ -936,14 +936,18 @@ pub(crate) struct PairsSampling { pub(crate) image: vk::Image, placement: Placement, pub(crate) view: vk::ImageView, - pub(crate) kernel: OwnedKernel, + /// The device's conversion it is sampled through, whose kernel (`OwnedModule::ChromaSample`) + /// a use makes ([`module`](Self::module)), not its making. + sampler: YCbCrSampler, pub(crate) extent: [u32; 2], } impl PairsSampling { /// The pairs' image of a texture of `extent` (an even width) through `sampler` - /// ([`YCbCrSampler::pairs`]), on `device`. Refused as the image, its memory, the kernel and - /// the view are refused. + /// ([`YCbCrSampler::pairs`]), on `device`: its view made with the device's conversion of + /// `sampler`, which its sample kernel's layout bakes; the kernel made by a use + /// ([`module`](Self::module)). Refused as the image, its memory, the conversion and the view + /// are refused. pub(crate) fn new( device: &Device, sampler: YCbCrSampler, @@ -999,19 +1003,13 @@ impl PairsSampling { unwind(); return Err(vulkan(error)); } - let kernel = match device.owned_kernel(OwnedModule::ChromaSample(sampler)) { - Ok(kernel) => kernel, + let conversion = match device.made_ycbcr_conversion(sampler) { + Ok(conversion) => conversion, Err(error) => { unwind(); return Err(error); } }; - let Some(conversion) = device.ycbcr_conversion(sampler) else { - unwind(); - return Err(super::error::internal( - "a 4:2:2 sample kernel without its conversion", - )); - }; let mut chained = vk::SamplerYcbcrConversionInfo::default().conversion(conversion); let info = vk::ImageViewCreateInfo::default() .image(image) @@ -1039,11 +1037,17 @@ impl PairsSampling { image, placement, view, - kernel, + sampler, extent, }) } + /// Its sample kernel (`bind::chroma_sample_module`), which bakes the conversion its view was + /// made with: made by a use (`texture/surface_pairs.rs`, `DecodePass::make`). + pub(crate) fn module(&self) -> OwnedModule { + OwnedModule::ChromaSample(self.sampler) + } + /// The shape of a step that samples `rows` rows from row `first` of the image /// (`ChromaSampleModule::shape`), and its workgroups. pub(crate) fn step( diff --git a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs index feb7009db..2d14d8416 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs @@ -10,8 +10,10 @@ //! `Shared`; over a buffer; over a no-copy buffer; in a heap, and a two-plane `RGB10A8_2P_XR10` //! one there; over detached bytes, a stand-in; a 4:4:4 two-plane YCbCr texture over a surface's //! plane, which a heap element holds the write shadow of as it is made, where the device holds -//! textures in argument buffers and a kernel writing through one ran before), a heap's buffer -//! and new buffers are made (a `Private` one with bytes among them, and a `Managed` +//! textures in argument buffers and a kernel writing through one ran before; a 4:2:2 +//! `GBGR422` texture, which every device holds in a carrier with a decoded twin, of its own and +//! in a heap; and a view of an `ASTC_4x4_LDR` texture as `ASTC_4x4_sRGB`, its second decoded +//! twin where the device lacks ASTC), a heap's buffer and new buffers are made (a `Private` one with bytes among them, and a `Managed` //! one), a `Managed` buffer's `did_modify_range` is called (on a device without unified memory //! each copies to the buffer's own bytes by the next submission), and a no-copy buffer with a //! texture over it is rebound. The end mark reads 0 as each call returns. Afterwards every @@ -20,7 +22,15 @@ //! runtime's own (`WorkCounts::owned_kernels_made`), a pipeline's compile: a tiled heap //! texture's moves', a heap two-plane texture's and a YCbCr write shadow's write-back's are //! built at their first use (`runtime/src/owned_kernel.rs`, `FirstUse`), which the test makes -//! after, a blit out of the two-plane texture and a write through the YCbCr texture's handle. +//! after, a blit out of the two-plane texture and a write through the YCbCr texture's handle; +//! a decoded twin's decode kernels (a 4:2:2 texture's on a device that converts its pairs, the +//! heap texture's whole decode, the view's second twin's) by the next commit, before the +//! scheduler's section (`runtime/src/texture/decoded_twin.rs`). +//! - **A carried heap texture read with no commit.** A `GBGR422` texture made in a `Shared` +//! heap, its whole decode staged by its making, then written by `replace_region` and read by +//! `get_bytes` with no commit between: its making builds no kernel, and `get_bytes` reads the +//! bytes written, any internal submission among the calls making the staged decode's kernel +//! before its lock. //! - **The zeros come before every use, on every queue** (the coordinator's conditions). A new //! `Private` buffer whose memory held other bytes is read through its address unnamed, and //! through its heap made resident, by a command buffer on another queue, after a command @@ -63,6 +73,7 @@ //! Such textures are made, started neither on the host nor on the staging queue, and resolve to //! zero through a pass that loads them. +use super::astc_textures::decodes_astc; use super::commit_work::relay_marks; use super::degrade_notices::{ assert_once_allowing, forced, made_compute_kinds, shared_in_system_memory, @@ -418,6 +429,14 @@ fn two_planes(options: ResourceOptions) -> TextureDescriptor { d } +/// A `SIDE`² 4:2:2 texture descriptor (`GBGR422`) of `options`: on every device a carrier of +/// its pairs with a decoded twin (`runtime/src/texture/decoded_twin.rs`). +fn pairs(options: ResourceOptions) -> TextureDescriptor { + let mut d = descriptor(options); + d.pixel_format = PixelFormat::GBGR422; + d +} + /// The kernel that writes the texture an argument buffer holds (`ycbcr_argument_writes`), run /// once over an `RGBA32Float` texture so the device's heap set of its layout lives /// (`runtime/src/heap_sets.rs`): a texture made after takes its elements there as it is made. @@ -759,6 +778,12 @@ fn new_resources_wait_for_no_gpu_work() { // over, whose write shadow a heap element holds as it is made (`heap_sets.rs`). let held = held_writes(device, &queue); let surface = buffer_with(device, &surface_bytes(0x5400)).unwrap(); + // An ASTC texture, a carrier with a decoded twin where the device lacks ASTC, whose view + // in its other colour space makes a second twin (`decoded_twin.rs`). + let mut astc_descriptor = descriptor(ResourceOptions::shared()); + astc_descriptor.pixel_format = PixelFormat::ASTC4x4LDR; + let astc = device.new_texture(&astc_descriptor).unwrap(); + let carried = !decodes_astc(device, PixelFormat::ASTC4x4LDR); let (busy_work, mark) = busy.commit(device, &queue); busy_work.scheduled(); @@ -812,6 +837,21 @@ fn new_resources_wait_for_no_gpu_work() { twin_texture(&surface, PixelFormat::YCBCR84442P, "444v", usage).unwrap() }) }); + let carried_pairs = calls.time("new_texture (GBGR422)", || { + device + .new_texture(&pairs(ResourceOptions::private())) + .unwrap() + }); + let pairs_in_heap = calls.time("new_texture in a heap (GBGR422)", || { + heap.new_texture(&pairs(ResourceOptions::private())) + .unwrap() + }); + let twins = device.work_counts().second_twins; + let other_space = calls.time( + "new_texture_view of an ASTC_4x4_LDR texture as sRGB", + || astc.new_texture_view(PixelFormat::ASTC4x4SRGB).unwrap(), + ); + let second_twins = device.work_counts().second_twins - twins; let stand_in = detached.as_ref().map(|buffer| { calls.time("new_texture over detached bytes", || { buffer @@ -931,6 +971,10 @@ fn new_resources_wait_for_no_gpu_work() { // Its first use, which makes its moves' kernel; its bytes are checked elsewhere // (`two_plane_heap_blits`). copy_out(&command_buffer, &planes_in_heap); + // The 4:2:2 textures' pairs; the commit takes the heap texture's whole decode and the + // view's second twin's, whose kernels it makes first. + copy_out_sized(&command_buffer, &carried_pairs, SIDE, SIDE, 2); + copy_out_sized(&command_buffer, &pairs_in_heap, SIDE, SIDE, 2); let rebound_out = (rebound.as_ref()).map(|(_, texture)| copy_out(&command_buffer, texture)); command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); @@ -943,9 +987,11 @@ fn new_resources_wait_for_no_gpu_work() { let counts = device.work_counts(); println!( "FIRST-USE on {name}: heap textures tiled {}; a YCbCr texture written through a heap \ - {}; the makings built no kernel, the uses built {}", + {}; 4:2:2 twins of the device's conversion {}; ASTC carried {carried}, second twins \ + made {second_twins}; the makings built no kernel, the uses built {}", counts.heap_textures_tiled, written_through_heap.is_some(), + counts.chroma_device_twins, counts.owned_kernels_made - kernels ); for (what, out, expected) in outs { @@ -978,12 +1024,72 @@ fn new_resources_wait_for_no_gpu_work() { in_heap, planes_in_heap, written_through_heap, + carried_pairs, + pairs_in_heap, + other_space, + astc, heap, )); drop((rebound, detached, pages)); }); } +/// A carried 4:2:2 texture (`GBGR422`) made in a `Shared` heap, its decoded twin's whole decode +/// staged by its making, then written by `replace_region` and read by `get_bytes`, with no commit +/// between (the module docs): its making builds no kernel of the runtime's own +/// (`WorkCounts::owned_kernels_made`), and `get_bytes` reads the bytes `replace_region` wrote, as +/// Metal's does. Any internal submission the calls make takes the staged decode with its kernel +/// made before its lock (`Device::make_pending_decodes`); the kernels each call built are +/// printed (`CARRIED-HEAP`). +#[test] +fn a_carried_heap_texture_reads_its_bytes_with_no_commit() { + on_device(|device| { + let name = device.name(); + let d = pairs(ResourceOptions::shared()); + let heap = device + .new_heap(&HeapDescriptor::new( + HeapType::Automatic, + 1 << 20, + ResourceOptions::shared(), + )) + .unwrap(); + let built = || device.work_counts().owned_kernels_made; + let (kernels, submissions) = (built(), device.work_counts().internal_submissions); + let texture = heap.new_texture(&d).unwrap(); + let making = built() - kernels; + // Two bytes a texel: a pair of texels a word. + let row = 2 * SIDE; + let written: Vec = (0..(row * SIDE) as usize) + .map(|i| ((i * 13 + 5) % 251) as u8) + .collect(); + let region = Region::new_2d(0, 0, SIDE, SIDE); + let kernels = built(); + texture + .replace_region(region, 0, 0, &written, row, 0) + .unwrap(); + let replaced = built() - kernels; + let mut read = vec![0; written.len()]; + let kernels = built(); + texture.get_bytes(&mut read, row, 0, region, 0, 0).unwrap(); + let reading = built() - kernels; + println!( + "CARRIED-HEAP {name}: kernels built by the making {making}, replace_region {replaced}, \ + get_bytes {reading}; internal submissions {}", + device.work_counts().internal_submissions - submissions + ); + assert_eq!( + making, 0, + "a GBGR422 texture's making in a heap on {name} built kernels of the runtime's own" + ); + assert!( + read == written, + "get_bytes of a GBGR422 heap texture on {name}, with no commit after its making, reads \ + other bytes than replace_region wrote" + ); + drop((texture, heap)); + }); +} + /// A `Private` buffer of `len` bytes made where a buffer that held `node(A)` was just released /// (most likely its memory): a fill that did not run would leave those bytes. Whether the /// memory was the released one's, printed. diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index dd510926a..5ffeaa1c9 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 = 2377; +pub const RUNTIME_VERSION: u32 = 2378; /// 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