diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 04f6ceea1..2ffc2b56f 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -330,7 +330,19 @@ impl Detached { } } +impl Drop for HostCell { + fn drop(&mut self) { + // As in `replace`: the buffer's release lets go of its pages last. + let lying = self + .pages + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Lying::In(pages) = lying { pages.let_go_by_buffer(); + } + } +} + impl HostCell { /// The pages the buffer lies in now; `None` while it is detached. pub(super) fn current(&self) -> Option> { @@ -388,6 +400,7 @@ impl HostCell { // as it would without them (`HostPages::let_go_by_buffer`). if let Lying::In(pages) = &lay { pages.let_go_by_buffer(); + } lay } @@ -542,6 +555,7 @@ pub(super) struct HostPages { release: OnceLock, /// The live buffers' tables' holds on them ([`ListedPages`]). listed: AtomicUsize, + /// The holds on them of command buffers' replays (`recorder`): what a command buffer's /// commands took, held from its commit until they are replayed, each counted until it is /// gone ([`let_go_by_replay`](Self::let_go_by_replay)), so the count outlives them. replay_holds: Arc, @@ -564,9 +578,15 @@ impl HostPages { listed: AtomicUsize::new(0), replay_holds: Arc::new(AtomicUsize::new(0)), let_go: AtomicBool::new(false), + } + } + /// A command buffer's replays hold them from now on (`recorder`): counted before its commit /// reads whether their buffer let go of them ([`let_go_by_buffer`](Self::let_go_by_buffer)). + pub(super) fn held_for_replay(&self) { self.replay_holds.fetch_add(1, Ordering::SeqCst); + } + /// A command buffer's replays let go of `pages`: the pages, where that hold was their last. /// Counted out only once the hold is gone, so their buffer's let-go that finds no hold /// finds no replay letting go of one either ([`let_go_by_buffer`](Self::let_go_by_buffer)). @@ -575,10 +595,14 @@ impl HostPages { let last = Arc::into_inner(pages); holds.fetch_sub(1, Ordering::AcqRel); last + } + /// Whether their buffer let go of them ([`let_go_by_buffer`](Self::let_go_by_buffer)): read /// by a commit after its replays' holds on them are counted and its replays queued. pub(super) fn buffer_let_go(&self) -> bool { self.let_go.load(Ordering::SeqCst) + } + /// Their buffer lets go of them (its release, rebind or detach), the caller still holding /// them: where command buffers' replays hold them, every replay waiting runs first, on this /// thread, so the replays let go of them before the caller does, and their deallocator runs @@ -593,6 +617,10 @@ impl HostPages { fn let_go_by_buffer(&self) { self.let_go.store(true, Ordering::SeqCst); if self.replay_holds.load(Ordering::SeqCst) == 0 { + return; + } + let shared = self.import.device.shared(); + if let Some(recorder) = shared.recorder() { recorder.settle_all(shared.vk()); } } @@ -689,12 +717,33 @@ impl HostPages { }); } + /// The replay of a command buffer's deferred command buffers held these pages last /// (`recorder`, [`HeldByReplay`]): never as a rule, as their buffer's let-go and each commit /// whose replays hold them agree on which replays them first /// ([`let_go_by_buffer`](Self::let_go_by_buffer)). Were it to, they would have gone at that /// let-go or at the commit, where their deallocator or keep-alive ran; they go now, after /// the replay, announced once per device (`Degradation::HostDeallocatorDelayed`). Nothing /// where neither is left to run. + fn held_by_replay(&self) { + let Some(release) = self.release.get() else { + return; + }; + if !release.deallocates() && !release.keeps_alive() { + return; + } + let device = &self.import.device; + device.shared().counts.host_deallocator_delayed(); + let length = release.length(); + device.degrade_once(Degradation::HostDeallocatorDelayed, || { + ( + format!("a no-copy buffer of {length} bytes"), + "a command buffer committed before its release or rebind names its pages, and \ + they stayed until its commands were recorded on the device's recorder thread" + .to_owned(), + ) + }); + } + /// Run `release`'s deallocator now, at Metal's moment, the caller's `keep_alive` keeping the /// pages mapped until the import is freed: the import keeps it, unless it keeps another's /// already, or `others` (another buffer lies in the import, whose own contract keeps the same @@ -1223,6 +1272,17 @@ impl Drop for AfterFree { } } +/// Host pages the replay of a command buffer's deferred command buffers held last (`recorder`), +/// let go of on one of the device's handler threads: announced as they go +/// ([`HostPages::held_by_replay`]), then dropped, which runs their deallocator. +pub(super) struct HeldByReplay(pub(super) HostPages); + +impl Drop for HeldByReplay { + fn drop(&mut self) { + self.0.held_by_replay(); + } +} + impl Drop for HostPages { fn drop(&mut self) { // The images and views a rebind or a detach parked go first: they may hold the import. diff --git a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs index 10a6a14f6..cd66d09bc 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs @@ -52,6 +52,7 @@ use super::checks::metal_submissions; use super::{write_fields, CommandBufferShared, Resident, State}; +use crate::buffer::HostPages; use crate::error::{CommandBufferError, Error}; use crate::live_buffers::LiveTable; use crate::rebind::SubmittedHolds; @@ -154,9 +155,11 @@ impl Covered { impl State { /// As the command buffer commits (its segments recorded): what its commands took is held /// weakly until its first submission, which lists `listing` again where the list changed. - pub(super) fn wait_for_submission(&mut self, listing: Listing) { + /// The pages its commands held go to `held`, which its deferred command buffers' replays + /// hold until they are replayed (`recorder`). + pub(super) fn wait_for_submission(&mut self, listing: Listing, held: &mut Vec>) { for record in &mut self.ended { - record.taken.wait(); + record.taken.wait(held); } let segments = self .recorded @@ -164,7 +167,7 @@ impl State { .flat_map(|part| part.segments.iter_mut()) .filter_map(|segment| segment.recorded.as_mut()); for done in segments { - done.taken.wait(); + done.taken.wait(held); } self.listing = Some(listing); } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index acaf58859..6a2e46418 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -72,6 +72,7 @@ use super::predication::Predication; use super::program_objects; use super::queue::Slot; use super::rebind::{Holds, SubmittedHolds, Taken}; +use super::recorder::{self, Replays}; use super::replay::Replay; use super::residency::Residency; use super::resource::ResourceKey; @@ -414,6 +415,9 @@ pub(super) struct State { /// The pool every `VkCommandBuffer` of this command buffer comes from, with those made from /// it; `None` until the first, and once given back to the device's spares. pool: Option, + /// Its encoders' deferred command buffers and their replays, where the device records them + /// so (`recorder`): `None` until the first, and once let go of. + pub(super) replays: Option>, /// The ended encoders' recordings, in encoding order. recorded: Vec, /// The last ended encoder's last `VkCommandBuffer`, still recording: its batch's end goes @@ -1316,11 +1320,19 @@ impl Drop for CommandBufferShared { // nothing of its pool is pending. The device's spares keep it (`spares.rs`), which // release it only with the device. A timestamp slot it still holds goes back with its // state. - let pool = lock(&self.state).pool.take(); + let (pool, replays) = { + let mut state = lock(&self.state); + (state.pool.take(), state.replays.take()) + }; if let Some(pool) = pool { let shared = self.device.shared(); shared.spares.give_command_pool(shared, pool, false); } + // Its replays end likewise. + if let Some((pool, _)) = replays.and_then(|replays| replays.release(false)) { + let shared = self.device.shared(); + shared.spares.give_command_pool(shared, pool, false); + } } } @@ -1346,6 +1358,7 @@ impl CommandBuffer { abandoned: false, committing: false, pool: None, + replays: None, recorded: Vec::new(), tail: None, folds: Vec::new(), @@ -1467,9 +1480,13 @@ impl CommandBuffer { Ok(residency.with_live(live)) } - /// A primary `VkCommandBuffer` from this command buffer's pool, made on first use. The - /// caller holds `state` (the pool is externally synchronized). + /// An encoder's primary command buffer: a deferred one where the device records them so + /// (`recorder`), else one from this command buffer's pool, made on first use. The caller holds + /// `state` (the pool is externally synchronized). pub(super) fn allocate_raw(&self, state: &mut State) -> Result { + self.0 + .allocate_deferred(state, vk::CommandBufferLevel::PRIMARY) + } /// An encoder's own primary `VkCommandBuffer` from this command buffer's pool, and whether it /// is begun: the pool's primary begun ahead where it holds one (`spares.rs`), else as @@ -1499,10 +1516,31 @@ impl CommandBuffer { unsafe { self.0.end_raw(raw) } } - /// A secondary `VkCommandBuffer` from this command buffer's pool (a render encoder's draws), - /// freed with the pool. The caller holds `state`. + /// Give up `raw`, a secondary command buffer recording that nothing will execute (a render + /// pass instance its pass replaced or gave up before running it, or the one instance of a + /// pass that changes nothing): a deferred one (`recorder`) is left unended, so its log is + /// never replayed, and goes with the command buffer's release, as one never ended goes; one + /// of this command buffer's pool ends ([`end_raw`](Self::end_raw)), so the pool goes back to + /// the device's spares unreset (`spares.rs`). Nothing executes either, so the GPU does the + /// same work and every byte it writes is the same; a deferred one's replay only cost the + /// recorder's thread a `vkBeginCommandBuffer`, which ANV makes reset the command buffer's + /// whole state, and the commands' recording. + /// + /// # Safety + /// As [`end_raw`](Self::end_raw)'s, and no command buffer executes `raw`. + pub(super) unsafe fn give_up_raw(&self, raw: vk::CommandBuffer) -> Result<(), vk::Result> { + if recorder::is_deferred(raw) { + return Ok(()); + } + // SAFETY: the caller's. + unsafe { self.end_raw(raw) } + } + + /// A secondary command buffer (a render encoder's draws), deferred or from this command + /// buffer's pool as [`allocate_raw`](Self::allocate_raw)'s. The caller holds `state`. pub(super) fn allocate_secondary(&self, state: &mut State) -> Result { - self.0.allocate(state, vk::CommandBufferLevel::SECONDARY) + self.0 + .allocate_deferred(state, vk::CommandBufferLevel::SECONDARY) } /// `addScheduledHandler:`: call `handler` once the command buffer is scheduled, on one of the @@ -1894,15 +1932,36 @@ impl CommandBuffer { // The last encoder's last command buffer ends, with its batch's end where it may // (`submit.rs`), the slot taken. self.0.close_tail(&mut state, None); + // Its submissions record their barriers from its pool, inside sections, where no + // spare is taken: one that encoded nothing takes a spare now, if one is free. + self.0.take_spare_pool(&mut state); // Until its first submission it holds what its commands took weakly: a rebind or a // release meanwhile lets the pages go, and the submission finds them moved. Only once // its last command buffer ended: what lay in pages a detach replaced while an encoder // held them goes with them (`detach.rs`), and its tail's commands recorded above // name the views of an attachment recorded inline (`render/inline_first.rs`). - state.wait_for_submission(listing); - // Its submissions record their barriers from its pool, inside sections, where no - // spare is taken: one that encoded nothing takes a spare now, if one is free. - self.0.take_spare_pool(&mut state); + // Its deferred command buffers replay from now on, on the device's recorder thread, + // and hold the pages their commands name until they are replayed; such pages go here + // all the same, replayed first (`Replays::commit`). + match state.replays.clone() { + Some(replays) => drop(replays.commit(device.shared().vk(), |held| { + state.wait_for_submission(listing, held) + })), + None => state.wait_for_submission(listing, &mut Vec::new()), + } + // Committed, its commands recorded for good: a rebind of what they used takes + // effect after them (`rebind.rs`); one a host step records holds until completion. + // Only once its replays hold the pages, so a rebind finds them held. + if stepped { + let held = &mut *state; + let kept = held + .holds + .drain(..) + .map(|holds| Box::new(holds) as Box); + held.retained.extend(kept); + } else { + state.holds.clear(); + } let waits = state .batches .all() @@ -2645,7 +2704,8 @@ impl CommandBufferShared { unsafe fn end_raw(&self, raw: vk::CommandBuffer) -> Result<(), vk::Result> { // SAFETY: the caller's. let ended = unsafe { self.device.shared().vk().end_command_buffer(raw) }; - if ended.is_ok() { + // A deferred one is none of its pool's: its replay ends its own (`recorder`). + if ended.is_ok() && !recorder::is_deferred(raw) { self.raws_ended.fetch_add(1, Ordering::Relaxed); } ended @@ -2667,6 +2727,45 @@ impl CommandBufferShared { } } + /// An encoder's command buffer of `level`: where the device records them so, a deferred one + /// of its replays, which take a spare pool of the device's for their replays as the first is + /// made (outside a section, where a spare is taken; else the first replay makes one); + /// elsewhere, or once every deferred handle is live, one from this command buffer's pool + /// ([`allocate`](Self::allocate)). + fn allocate_deferred( + &self, + state: &mut State, + level: vk::CommandBufferLevel, + ) -> Result { + match self.deferred(state, level)? { + Some(raw) => Ok(raw), + None => self.allocate(state, level), + } + } + + /// A deferred command buffer of `level` of its replays, where the device records them so and + /// a handle is free (`recorder`); `None` elsewhere. + fn deferred( + &self, + state: &mut State, + level: vk::CommandBufferLevel, + ) -> Result, Error> { + let shared = self.device.shared(); + let Some(recorder) = shared.recorder() else { + return Ok(None); + }; + if state.replays.is_none() { + let family = shared.queue_family_of(self.queue.vk_queue()); + let spare = shared.spares.command_pool(shared, family)?; + state.replays = Some(recorder.replays(family, spare)); + } + let raw = (state.replays.as_ref()).and_then(|replays| replays.make(level)); + if raw.is_some() { + shared.counts.command_buffer_deferred(); + } + Ok(raw) + } + /// A `VkCommandBuffer` of `level` from this command buffer's pool, made on first use: a /// spare of the device's, or a new one. A command buffer the pool made before this command /// buffer took it is handed out again before a new one is made; its begin resets it (the @@ -2690,7 +2789,12 @@ impl CommandBufferShared { Ok(buffer) } + /// [`CommandBuffer::encoder_primary`]: a deferred one where the device records them so, to + /// begin, whose replay takes the primary its replays' pool holds begun ahead (`recorder`). fn encoder_primary(&self, state: &mut State) -> Result<(vk::CommandBuffer, bool), Error> { + if let Some(raw) = self.deferred(state, vk::CommandBufferLevel::PRIMARY)? { + return Ok((raw, false)); + } if let Some(buffer) = self.pool(state)?.take_begun() { return Ok((buffer, true)); } @@ -3279,6 +3383,17 @@ impl CommandBufferShared { let shared = self.device.shared(); shared.spares.give_command_pool(shared, pool, settled); } + // Its replays end, any in progress first, and replay nothing more; their pool goes + // back as its own does, and holds the primary begun ahead in its place: its encoders' + // primaries came from it, and only their replays take that primary (`recorder`). + if let Some(replays) = state.replays.take() { + let completed = state.status == CommandBufferStatus::Completed; + if let Some((pool, settled)) = replays.release(completed) { + settled_pool = settled.then_some(pool.raw); + let shared = self.device.shared(); + shared.spares.give_command_pool(shared, pool, settled); + } + } if state.status == CommandBufferStatus::Completed { state.descriptors.give_back(); } else { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 4680e2900..53b8eaf86 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -179,7 +179,10 @@ impl State { // Held weakly until the first submission, as the commit held what the first recording // took, and by its replays until they are replayed: what they held last goes here, as // it does without them (`Replays::hold`, with `device`, the device's functions). + match self.replays.clone() { Some(replays) => drop(replays.hold(device, |pages| taken.wait(pages))), + None => taken.wait(&mut Vec::new()), + } let recorded = &mut self.recorded[part]; recorded.raws = raws; recorded.summary = summary; diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index 0a9ec594f..f764b7246 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -843,6 +843,12 @@ impl CommandBufferShared { true => (&signal_semaphores[..], &signal_values[..]), false => (&[][..], &[][..]), }; + for buffer in work.iter_mut() { + // SAFETY: each ended, and its command buffer committed; inside the scheduler's + // section. + *buffer = unsafe { crate::recorder::resolve(raw, *buffer) } + .map_err(|error| recording_error(device, crate::error::vulkan(error)))?; + } let mut work_timeline = vk::TimelineSemaphoreSubmitInfo::default() .wait_semaphore_values(wait_values) .signal_semaphore_values(work_signal_values); diff --git a/crates/metal2vulkan-runtime/src/device/functions.rs b/crates/metal2vulkan-runtime/src/device/functions.rs index 82faa98da..7872a247a 100644 --- a/crates/metal2vulkan-runtime/src/device/functions.rs +++ b/crates/metal2vulkan-runtime/src/device/functions.rs @@ -15,6 +15,7 @@ use crate::exit_guard::{self, Call}; use crate::image_barrier::MemoryReads; +use crate::recorder::Slot; use ash::vk; use std::ffi::{c_void, CStr}; use std::ops::Deref; @@ -91,14 +92,16 @@ impl Functions { /// /// # Safety /// - /// `all` is a live device of `instance`, routed (`compiles::route`), and the loader serves - /// `vkGetDeviceProcAddr` for it (its loader word is in place). + /// `all` is a live device of `instance`, routed (`compiles::route`, and through `recording` + /// where it is set, `recorder::route`), and the loader serves `vkGetDeviceProcAddr` for it + /// (its loader word is in place). pub(super) unsafe fn new( instance: &ash::Instance, all: ash::Device, reads: MemoryReads, push_descriptor: Option, object_name: Option, + recording: Option<&Slot>, ) -> Functions { let handle = all.handle(); let get = instance.fp_v1_0().get_device_proc_addr; @@ -115,8 +118,11 @@ impl Functions { Some(at) => { let pointer = address(name); entry_points[at] = pointer as usize as u64; - // The pipeline makings come through `compiles.rs`, as `all`'s do. - super::compiles::entry(name).unwrap_or(pointer) + // The pipeline makings come through `compiles.rs`, and the commands through + // the device's slot, as `all`'s do. + super::compiles::entry(name) + .or_else(|| recording.and_then(|slot| slot.entry(name))) + .unwrap_or(pointer) } None => std::ptr::null(), } diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index cec7a7efa..4e03acb7e 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -79,6 +79,7 @@ use super::stencil_copy::StencilCopyObjects; use super::texture::TextureState; use super::unique_identifier::UniqueIdentifiers; use crate::image_barrier::MemoryReads; +use crate::recorder::{Command, MeshDraws, Recorder, RecorderShared, Slot}; use crate::release; use ash::vk::{self, Handle}; use functions::{Functions, Vk}; @@ -284,6 +285,7 @@ pub(super) struct DeviceShared { /// `VK_EXT_depth_bias_control` (`render_state.rs`). pub(super) depth_bias_command: Option, /// The mesh draw commands, where the device enabled `meshShader` (`render/mesh.rs`). + pub(super) mesh_draws: Option, /// `vkCmdPushDescriptorSet`, from Vulkan 1.4 or `VK_KHR_push_descriptor` /// (`binding::push_set`); none where the driver has /// `RuntimeDriverDefect::PushedBufferSizesUnset`. @@ -295,6 +297,12 @@ pub(super) struct DeviceShared { /// The command that sets a draw's color write masks, where the device enabled everything a /// draw that reads its own pass's texture through a snapshot takes (`render/snapshot.rs`). pub(super) color_write_masks: Option, + /// The device's slot among those its commands go through (`recorder`), where it took one: + /// let go of after `vkDestroyDevice` (it drops after the teardown, `Drop`). Held, not read. + _recording: Option, + /// The thread that replays its encoders' deferred command buffers, where it has a slot + /// (`recorder`). + recorder: Option, /// The reasons a draw that reads its pass's texture took the split that the device said /// already, where `METAL2VULKAN_LOG_PIPELINES` is set (`render/snapshot.rs`). pub(super) snapshot_fallbacks: Mutex>, @@ -459,6 +467,12 @@ impl DeviceShared { self.functions.get() } + /// What its encoders' deferred command buffers' replays share, where it records them so + /// (`recorder`). + pub(crate) fn recorder(&self) -> Option<&Arc> { + self.recorder.as_ref().map(Recorder::shared) + } + /// `vkAllocateCommandBuffers` of `info`: the loader serves it and reads the device's loader /// word first ([`LoaderWord`]). pub(super) fn allocate_command_buffers( @@ -995,6 +1009,10 @@ impl Device { // Every pipeline made on the device from here on is made at the user-initiated class. // SAFETY: the device is live (the caller's contract), and its functions are its own. let raw = unsafe { compiles::route(raw) }; + // Every command recorded with the device's functions goes through a slot of its own + // (`recorder`), dropped with the device after `vkDestroyDevice`. + // SAFETY: as above; its functions were routed for its pipeline makings alone. + let (raw, recording) = unsafe { crate::recorder::route(raw) }; // What the runtime made from the device, destroyed with it when a later step fails. let undo = |timelines: &[vk::Semaphore]| { // The record of pipeline makings first, as in the teardown (`compiles.rs`). @@ -1123,6 +1141,7 @@ impl Device { .get_device_proc_addr(raw.handle(), name.as_ptr()) }) } + .map(|commands| commands.routed(recording.as_ref())) } else { None }; @@ -1147,6 +1166,13 @@ impl Device { &enabled, ) } + .filter(|_| pushes_whole_sets) + .map(|push| { + // SAFETY: the device's own command of that name. + unsafe { + crate::recorder::through(recording.as_ref(), Command::CmdPushDescriptorSet, push) + } + }); // Its naming of an object, where its instance reports messages: a graphics pipeline that // reads its input attachments in rasterization order is named for the layers' messages // (`pipeline/graphics.rs`). @@ -1179,6 +1205,55 @@ impl Device { gpu_time::calibrated(&instance.entry, &instance.raw, physical, &raw, calibration) } .filter(|_| timestamp_bits > 0); + // The render encoder's commands of extensions and of Vulkan 1.3, which priming makes too. + // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. + let extended_dynamic_state = unsafe { + loader_word.restore(); + ExtendedDynamicState::load( + &instance.raw, + &raw, + description.api_version, + &enabled, + recording.as_ref(), + ) + }; + // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. + let sized_index_bind = unsafe { + loader_word.restore(); + sized_index_bind(&instance.raw, &raw, &enabled) + } + .map(|bind| { + // SAFETY: the device's own command of that name. + unsafe { + crate::recorder::through(recording.as_ref(), Command::CmdBindIndexBuffer2, bind) + } + }); + // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. + let depth_bias_command = unsafe { + loader_word.restore(); + depth_bias_command(&instance.raw, &raw, &enabled) + } + .map(|bias| { + // SAFETY: the device's own command of that name. + unsafe { crate::recorder::through(recording.as_ref(), Command::CmdSetDepthBias2, bias) } + }); + // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. + let color_write_masks = unsafe { + loader_word.restore(); + ColorWriteMasks::load(&instance.raw, &raw, &enabled) + } + .map(|ColorWriteMasks(masks)| { + // SAFETY: the device's own command of that name. + ColorWriteMasks(unsafe { + crate::recorder::through(recording.as_ref(), Command::CmdSetColorWriteMask, masks) + }) + }); + let drawn = prime::PrimedDraws { + dynamic: extended_dynamic_state, + color_write_masks, + depth_bias: depth_bias_command, + sized_index_bind, + }; // Before the exit hook is registered for this device (below): the first call of each // entry point of the exit guard's table (`prime.rs`). // SAFETY: the device is live, of `physical`, and enables timeline semaphores, and @@ -1193,7 +1268,7 @@ impl Device { queue_family, &queues, Sharing::new(&queue_families), - prime::Has { + drawn.has(prime::Has { timestamps: timestamp_bits > 0, // A device the runtime created enables it (`enables.rs`). host_query_reset: owned, @@ -1203,9 +1278,16 @@ impl Device { push_descriptor: push_descriptor.is_some(), calibration: calibrated.is_some(), object_names: object_name.is_some(), + extended_dynamic_state: false, + primitive_restart: false, + color_write_masks: false, + depth_bias: false, + sized_index_bind: false, + }), generated_commands.as_ref(), push_descriptor, calibrated, + drawn, ) } { scheduler.stop(); @@ -1269,26 +1351,6 @@ impl Device { dma_buf_images, ) }; - // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. - let extended_dynamic_state = unsafe { - loader_word.restore(); - ExtendedDynamicState::load( - &instance.raw, - &raw, - properties.description.api_version, - &enabled, - ) - }; - // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. - let sized_index_bind = unsafe { - loader_word.restore(); - sized_index_bind(&instance.raw, &raw, &enabled) - }; - // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. - let depth_bias_command = unsafe { - loader_word.restore(); - depth_bias_command(&instance.raw, &raw, &enabled) - }; // The host image copy functions, where the device enabled `hostImageCopy` and copies to // and from `GENERAL` on the host: by their core names from Vulkan 1.4, else by the // extension's, which the device then enabled. @@ -1314,11 +1376,6 @@ impl Device { }) }) }); - // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. - let color_write_masks = unsafe { - loader_word.restore(); - ColorWriteMasks::load(&instance.raw, &raw, &enabled) - }; // The mesh draw commands, which exist where `meshShader` is enabled (it needs // `VK_EXT_mesh_shader`). let mesh_draws = if enabled @@ -1328,7 +1385,8 @@ impl Device { // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put // back. unsafe { loader_word.restore() }; - Some(ash::ext::mesh_shader::Device::new(&instance.raw, &raw)) + let loaded = ash::ext::mesh_shader::Device::new(&instance.raw, &raw); + Some(MeshDraws::new(&loaded, recording.as_ref())) } else { None }; @@ -1384,8 +1442,22 @@ impl Device { // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. let functions = unsafe { loader_word.restore(); + Functions::new( + &instance.raw, + raw.clone(), + memory_reads, + push_descriptor, object_name, + recording.as_ref(), + ) }; + // Its encoders' commands replay on a thread of its own where it has a slot (`recorder`). + // SAFETY: the device's handle, live, its word the loader's (put back just now). + let recorder = recording.as_ref().and_then(|slot| { + Recorder::start(slot, &functions, unsafe { + LoaderWord::of_device(raw.handle()) + }) + }); let shader_cache = match ShaderCache::start( cache, &physical_properties, @@ -1491,6 +1563,8 @@ impl Device { push_descriptor, pushes_after_pipeline_binds, color_write_masks, + _recording: recording, + recorder, snapshot_fallbacks: Mutex::new(Vec::new()), reader_sizes: Mutex::new(Default::default()), gpu_pools, @@ -1557,6 +1631,10 @@ impl Device { if !moltenvk { } let device = Device(shared); + // The pages its replays held last go on its handler threads (`recorder`). + if let Some(recorder) = device.shared().recorder() { + recorder.set_elsewhere(device.elsewhere()); + } device.say_unmeasured_driver(); device.degrade_argument_buffers_unread(); device.degrade_float_tininess(); diff --git a/crates/metal2vulkan-runtime/src/device/prime.rs b/crates/metal2vulkan-runtime/src/device/prime.rs index a7ba1424d..155128095 100644 --- a/crates/metal2vulkan-runtime/src/device/prime.rs +++ b/crates/metal2vulkan-runtime/src/device/prime.rs @@ -68,6 +68,8 @@ //! first call of each entry point, and every section whose count reaches a power of two, //! register the hook again for those (`exit_guard`). +use crate::draw_source::SizedIndexBind; +use crate::dynamic_state::{ColorWriteMasks, ExtendedDynamicState}; use crate::error::{vulkan, Error}; use crate::exit_guard::Call; use crate::generated_commands::{ @@ -79,6 +81,7 @@ use crate::gpu_time::Calibration; use crate::loader_word::LoaderWord; use crate::memory; use crate::release::{self, Generated, Released}; +use crate::render_state::DepthBiasCommand; use crate::sharing::Sharing; use crate::tracker::Barrier; use ash::vk; @@ -88,12 +91,18 @@ use super::functions::Vk; use super::QueueSlot; /// The table's entry points priming cannot make before the hook is registered for the device it -/// primes: the release of a device, an instance and a messenger. The first release of each in -/// the process registers the hook again as its section ends (`exit_guard::called`). -pub(crate) const UNPRIMED: [Call; 3] = [ +/// primes: the release of a device, an instance and a messenger, and the commands of a mesh draw +/// and of an execution of commands the GPU generates, which take pipelines of their own kinds. +/// The first release of each in the process, and the first replay of each command +/// (`recorder`), registers the hook again as its section ends (`exit_guard::called`). +pub(crate) const UNPRIMED: [Call; 7] = [ Call::DestroyDevice, Call::DestroyDebugUtilsMessenger, Call::DestroyInstance, + Call::CmdDrawMeshTasks, + Call::CmdDrawMeshTasksIndirect, + Call::CmdExecuteGeneratedCommands, + Call::CmdPreprocessGeneratedCommands, ]; /// The table's entry points a queue family that writes no timestamps (`timestampValidBits` 0) @@ -137,6 +146,37 @@ pub(crate) const CALIBRATION_CALLS: [Call; 1] = [Call::GetCalibratedTimestamps]; /// a graphics pipeline's debug name (`pipeline/graphics.rs`). pub(crate) const NAMING_CALLS: [Call; 1] = [Call::SetDebugUtilsObjectName]; +/// The table's entry points a device without extended dynamic state (Vulkan 1.3, or +/// `VK_EXT_extended_dynamic_state`) never calls, nor primes: a render encoder's dynamic states +/// (`dynamic_state.rs`). +pub(crate) const EXTENDED_DYNAMIC_STATE_CALLS: [Call; 9] = [ + Call::CmdSetCullMode, + Call::CmdSetFrontFace, + Call::CmdSetPrimitiveTopology, + Call::CmdBindVertexBuffers2, + Call::CmdSetDepthTestEnable, + Call::CmdSetDepthWriteEnable, + Call::CmdSetDepthCompareOp, + Call::CmdSetStencilTestEnable, + Call::CmdSetStencilOp, +]; + +/// The table's entry points a device without a dynamic primitive restart (Vulkan 1.3, or +/// `VK_EXT_extended_dynamic_state2`) never calls, nor primes (`dynamic_state.rs`). +pub(crate) const PRIMITIVE_RESTART_CALLS: [Call; 1] = [Call::CmdSetPrimitiveRestartEnable]; + +/// The table's entry points a device without the dynamic color write mask never calls, nor +/// primes: a snapshot draw's masks (`dynamic_state.rs`, `render/snapshot.rs`). +pub(crate) const COLOR_WRITE_MASK_CALLS: [Call; 1] = [Call::CmdSetColorWriteMask]; + +/// The table's entry points a device without `VK_EXT_depth_bias_control` never calls, nor +/// primes: a depth bias in a unit of its own (`render_state.rs`). +pub(crate) const DEPTH_BIAS_CALLS: [Call; 1] = [Call::CmdSetDepthBias2]; + +/// The table's entry points a device without `maintenance5` never calls, nor primes: an index +/// buffer bound with its size (`draw_source.rs`). +pub(crate) const SIZED_INDEX_BIND_CALLS: [Call; 1] = [Call::CmdBindIndexBuffer2]; + /// The debug name of a render host step's pipeline that priming makes, where the instance reports /// messages ([`NAMING_CALLS`]). const PRIMING_PIPELINE: &std::ffi::CStr = @@ -316,6 +356,7 @@ fn specialization() -> vk::SpecializationInfo<'static> { /// What the device primed has: a queue family that writes timestamps, `hostQueryReset`, device /// addresses, `VK_EXT_device_generated_commands`, sparse binding on its queues, the push command, +/// calibrated timestamps, and the render encoder's commands of [`PrimedDraws`]. #[derive(Clone, Copy)] pub(crate) struct Has { pub(crate) timestamps: bool, @@ -326,12 +367,45 @@ pub(crate) struct Has { pub(crate) push_descriptor: bool, pub(crate) calibration: bool, pub(crate) object_names: bool, + pub(crate) extended_dynamic_state: bool, + pub(crate) primitive_restart: bool, + pub(crate) color_write_masks: bool, + pub(crate) depth_bias: bool, + pub(crate) sized_index_bind: bool, +} + +/// The commands a render encoder records that the device has where it has their feature or +/// extension, which the priming's render host step makes (a deferred command buffer's replay +/// records them inside a section, `recorder`). +#[derive(Clone, Copy, Default)] +pub(crate) struct PrimedDraws { + pub(crate) dynamic: Option, + pub(crate) color_write_masks: Option, + pub(crate) depth_bias: Option, + pub(crate) sized_index_bind: Option, +} + +impl PrimedDraws { + /// `has`, with what it says of these commands set from them. + pub(crate) fn has(&self, has: Has) -> Has { + Has { + extended_dynamic_state: self.dynamic.is_some(), + primitive_restart: self + .dynamic + .is_some_and(|dynamic| dynamic.primitive_restart_enable.is_some()), + color_write_masks: self.color_write_masks.is_some(), + depth_bias: self.depth_bias.is_some(), + sized_index_bind: self.sized_index_bind.is_some(), + ..has + } + } } /// Prime `device` of `physical`, made from `instance`, whose queues are `queues`, the first of /// its primary family `queue_family`, its buffers and images shared as `sharing` says, on this -/// thread; `has` says what the device has, and `generated` holds the commands of -/// `VK_EXT_device_generated_commands` where it has them. +/// thread; `has` says what the device has, `generated` holds the commands of +/// `VK_EXT_device_generated_commands` where it has them, and `drawn` the render encoder's +/// commands it has. /// /// # Safety /// @@ -351,6 +425,7 @@ pub(super) unsafe fn prime( generated: Option<&Commands>, push: Option, calibration: Option, + drawn: PrimedDraws, ) -> Result<(), Error> { let mut primer = Primer { device, @@ -358,6 +433,7 @@ pub(super) unsafe fn prime( sharing, push, calibration, + drawn, // SAFETY: the caller's. memory: unsafe { instance.get_physical_device_memory_properties(physical) }, calls: 0, @@ -402,6 +478,8 @@ pub(super) unsafe fn prime( /// has no push command, those of [`CALIBRATION_CALLS`] where it calibrates no timestamps, those /// of [`NAMING_CALLS`] where its instance reports no messages, and those of /// [`EXTENDED_DYNAMIC_STATE_CALLS`], [`PRIMITIVE_RESTART_CALLS`], +/// [`COLOR_WRITE_MASK_CALLS`], [`DEPTH_BIAS_CALLS`] and [`SIZED_INDEX_BIND_CALLS`] where it has +/// not their commands, that `calls` (one bit each) does not hold. pub(crate) fn missing(calls: u128, has: Has) -> Vec { Call::ALL .iter() @@ -418,6 +496,11 @@ pub(crate) fn missing(calls: u128, has: Has) -> Vec { && (has.push_descriptor || !PUSH_DESCRIPTOR_CALLS.contains(&call)) && (has.calibration || !CALIBRATION_CALLS.contains(&call)) && (has.object_names || !NAMING_CALLS.contains(&call)) + && (has.extended_dynamic_state || !EXTENDED_DYNAMIC_STATE_CALLS.contains(&call)) + && (has.primitive_restart || !PRIMITIVE_RESTART_CALLS.contains(&call)) + && (has.color_write_masks || !COLOR_WRITE_MASK_CALLS.contains(&call)) + && (has.depth_bias || !DEPTH_BIAS_CALLS.contains(&call)) + && (has.sized_index_bind || !SIZED_INDEX_BIND_CALLS.contains(&call)) }) .collect() } @@ -451,6 +534,8 @@ struct Primer<'a> { push: Option, /// The device's calibrated timestamps, where its queue family writes timestamps. calibration: Option, + /// The render encoder's commands the device has. + drawn: PrimedDraws, memory: vk::PhysicalDeviceMemoryProperties, /// The table's entry points called, one bit each. calls: u128, @@ -1185,6 +1270,36 @@ impl Primer<'_> { let zero = vk::ClearDepthStencilValue::default(); device.cmd_clear_depth_stencil_image(recorded, depth, general, &zero, &[depth_whole]); self.made(Call::CmdClearDepthStencilImage); + // What an encoder records that no host step does, which a deferred command buffer's + // replay records (`recorder`): a buffer's fill and its inline update, each at bytes + // of its own, a copy of the query's result, and a blit of the image's first texel to + // its second after the clear. + device.cmd_fill_buffer(recorded, buffer, 192, 4, 0); + self.made(Call::CmdFillBuffer); + device.cmd_update_buffer(recorded, buffer, 208, &[0; 4]); + self.made(Call::CmdUpdateBuffer); + let results = vk::QueryResultFlags::empty(); + device.cmd_copy_query_pool_results(recorded, queries, 0, 1, buffer, 224, 4, results); + self.made(Call::CmdCopyQueryPoolResults); + Barrier::everything().record(device, recorded); + let corner = |x| vk::Offset3D { x, y: 0, z: 0 }; + let far = |x| vk::Offset3D { x, y: 1, z: 1 }; + let blit = [vk::ImageBlit { + src_subresource: texel, + src_offsets: [corner(0), far(1)], + dst_subresource: texel, + dst_offsets: [corner(1), far(2)], + }]; + device.cmd_blit_image( + recorded, + image, + general, + image, + general, + &blit, + vk::Filter::NEAREST, + ); + self.made(Call::CmdBlitImage); // The image's read before the pass's layout transition of it. Barrier::everything().record(device, recorded); self.render_step(RenderStep { @@ -1316,9 +1431,72 @@ impl Primer<'_> { self.made(Call::CmdSetStencilWriteMask); device.cmd_set_stencil_reference(draws, faces, 0); self.made(Call::CmdSetStencilReference); + // The extended dynamic states and the extension states the device has, set before + // the bind too (a deferred command buffer's replay records them, `recorder`). + let drawn = self.drawn; + if let Some(dynamic) = drawn.dynamic { + (dynamic.cull_mode)(draws, vk::CullModeFlags::NONE); + self.made(Call::CmdSetCullMode); + (dynamic.front_face)(draws, vk::FrontFace::COUNTER_CLOCKWISE); + self.made(Call::CmdSetFrontFace); + (dynamic.primitive_topology)(draws, vk::PrimitiveTopology::TRIANGLE_LIST); + self.made(Call::CmdSetPrimitiveTopology); + (dynamic.depth_test_enable)(draws, vk::FALSE); + self.made(Call::CmdSetDepthTestEnable); + (dynamic.depth_write_enable)(draws, vk::FALSE); + self.made(Call::CmdSetDepthWriteEnable); + (dynamic.depth_compare_op)(draws, vk::CompareOp::ALWAYS); + self.made(Call::CmdSetDepthCompareOp); + (dynamic.stencil_test_enable)(draws, vk::FALSE); + self.made(Call::CmdSetStencilTestEnable); + let keep = vk::StencilOp::KEEP; + (dynamic.stencil_op)(draws, faces, keep, keep, keep, vk::CompareOp::ALWAYS); + self.made(Call::CmdSetStencilOp); + if let Some(restart) = dynamic.primitive_restart_enable { + restart(draws, vk::FALSE); + self.made(Call::CmdSetPrimitiveRestartEnable); + } + } + if let Some(ColorWriteMasks(masks)) = drawn.color_write_masks { + let all = [vk::ColorComponentFlags::RGBA]; + masks(draws, 0, all.len() as u32, all.as_ptr()); + self.made(Call::CmdSetColorWriteMask); + } + if let Some(bias) = drawn.depth_bias { + bias(draws, &vk::DepthBiasInfoEXT::default()); + self.made(Call::CmdSetDepthBias2); + } + // A clear of the attachment inside the pass, as a render encoder's clear of a stand-in + // records it. + let clear = [vk::ClearAttachment { + aspect_mask: vk::ImageAspectFlags::COLOR, + color_attachment: 0, + clear_value: vk::ClearValue::default(), + }]; + let rect = [vk::ClearRect { + rect: area, + base_array_layer: 0, + layer_count: 1, + }]; + device.cmd_clear_attachments(draws, &clear, &rect); + self.made(Call::CmdClearAttachments); device.cmd_bind_pipeline(draws, vk::PipelineBindPoint::GRAPHICS, pipeline); device.cmd_bind_vertex_buffers(draws, 0, &[buffer], &[0]); self.made(Call::CmdBindVertexBuffers); + if let Some(dynamic) = drawn.dynamic { + let (buffers, offsets) = ([buffer], [0]); + let none = std::ptr::null(); + (dynamic.bind_vertex_buffers2)( + draws, + 0, + 1, + buffers.as_ptr(), + offsets.as_ptr(), + none, + none, + ); + self.made(Call::CmdBindVertexBuffers2); + } // An execution under a visibility result mode counts its draws in a query begun and // ended in its secondary. device.cmd_begin_query(draws, queries, 0, vk::QueryControlFlags::empty()); @@ -1332,6 +1510,10 @@ impl Primer<'_> { // and from its arguments. device.cmd_bind_index_buffer(draws, buffer, 0, vk::IndexType::UINT32); self.made(Call::CmdBindIndexBuffer); + if let Some(bind) = drawn.sized_index_bind { + bind(draws, buffer, 0, 256, vk::IndexType::UINT32); + self.made(Call::CmdBindIndexBuffer2); + } device.cmd_draw_indexed(draws, 3, 1, 0, 0, 0); self.made(Call::CmdDrawIndexed); device.cmd_draw_indexed_indirect(draws, buffer, 0, 1, 20); diff --git a/crates/metal2vulkan-runtime/src/dynamic_state.rs b/crates/metal2vulkan-runtime/src/dynamic_state.rs index 5007b0c58..8cc09cf42 100644 --- a/crates/metal2vulkan-runtime/src/dynamic_state.rs +++ b/crates/metal2vulkan-runtime/src/dynamic_state.rs @@ -9,6 +9,7 @@ //! when one of the two sources is present (`device::enables`, `Implied`); a draw of such a //! pipeline on a device without the commands is an internal error, never a guess. +use crate::recorder::{through, Command, Slot}; use ash::vk; use metal2vulkan::device::{EnableSet, VkExtension, VkFeature}; use metal2vulkan::vk::ApiVersion; @@ -34,17 +35,20 @@ pub(super) struct ExtendedDynamicState { impl ExtendedDynamicState { /// The commands of a device of effective version `api` (the instance's, at most the /// device's) with `enabled` enabled: the core ones from 1.3, else the extensions', else - /// none. + /// none. The core ones are `device`'s functions', routed through `slot` where the device has + /// one (`recorder`); the extensions' are routed through it here. /// /// # Safety /// - /// `device` was made from `instance` with `enabled` enabled, and the loader serves - /// `vkGetDeviceProcAddr` for it (its loader word is in place). + /// `device` was made from `instance` with `enabled` enabled, its functions routed through + /// `slot` where it is set, and the loader serves `vkGetDeviceProcAddr` for it (its loader + /// word is in place). pub(super) unsafe fn load( instance: &ash::Instance, device: &ash::Device, api: ApiVersion, enabled: &EnableSet, + slot: Option<&Slot>, ) -> Option { if api >= ApiVersion::V1_3 { let f = device.fp_v1_3(); @@ -69,25 +73,55 @@ impl ExtendedDynamicState { } let extension = ash::ext::extended_dynamic_state::Device::new(instance, device); let f = extension.fp(); - Some(ExtendedDynamicState { - cull_mode: f.cmd_set_cull_mode_ext, - front_face: f.cmd_set_front_face_ext, - primitive_topology: f.cmd_set_primitive_topology_ext, - depth_test_enable: f.cmd_set_depth_test_enable_ext, - depth_write_enable: f.cmd_set_depth_write_enable_ext, - depth_compare_op: f.cmd_set_depth_compare_op_ext, - stencil_test_enable: f.cmd_set_stencil_test_enable_ext, - stencil_op: f.cmd_set_stencil_op_ext, - bind_vertex_buffers2: f.cmd_bind_vertex_buffers2_ext, - primitive_restart_enable: enabled - .extensions - .contains(&VkExtension::ExtExtendedDynamicState2) - .then(|| { - ash::ext::extended_dynamic_state2::Device::new(instance, device) - .fp() - .cmd_set_primitive_restart_enable_ext - }), - }) + let restart = enabled + .extensions + .contains(&VkExtension::ExtExtendedDynamicState2) + .then(|| { + ash::ext::extended_dynamic_state2::Device::new(instance, device) + .fp() + .cmd_set_primitive_restart_enable_ext + }); + // SAFETY: each is the device's command of the routed command's signature (vk.xml aliases + // each to the core one), as its driver gave it. + unsafe { + Some(ExtendedDynamicState { + cull_mode: through(slot, Command::CmdSetCullMode, f.cmd_set_cull_mode_ext), + front_face: through(slot, Command::CmdSetFrontFace, f.cmd_set_front_face_ext), + primitive_topology: through( + slot, + Command::CmdSetPrimitiveTopology, + f.cmd_set_primitive_topology_ext, + ), + depth_test_enable: through( + slot, + Command::CmdSetDepthTestEnable, + f.cmd_set_depth_test_enable_ext, + ), + depth_write_enable: through( + slot, + Command::CmdSetDepthWriteEnable, + f.cmd_set_depth_write_enable_ext, + ), + depth_compare_op: through( + slot, + Command::CmdSetDepthCompareOp, + f.cmd_set_depth_compare_op_ext, + ), + stencil_test_enable: through( + slot, + Command::CmdSetStencilTestEnable, + f.cmd_set_stencil_test_enable_ext, + ), + stencil_op: through(slot, Command::CmdSetStencilOp, f.cmd_set_stencil_op_ext), + bind_vertex_buffers2: through( + slot, + Command::CmdBindVertexBuffers2, + f.cmd_bind_vertex_buffers2_ext, + ), + primitive_restart_enable: restart + .map(|restart| through(slot, Command::CmdSetPrimitiveRestartEnable, restart)), + }) + } } } diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index b62db5037..1ad8d88dd 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -1435,6 +1435,9 @@ impl EncoderCore { }, ); } + // SAFETY: only this call records `raw`, under the state lock, and it records until the + // tail ends (at the next part's end or the commit, `close_tail`). + unsafe { crate::recorder::reserve_end(raw) }; state.tail = Some(raw); state.retained.extend(retained.into_entry()); state.executions.extend(executions); diff --git a/crates/metal2vulkan-runtime/src/exit_guard.rs b/crates/metal2vulkan-runtime/src/exit_guard.rs index 261cc42e4..f4e4d8afd 100644 --- a/crates/metal2vulkan-runtime/src/exit_guard.rs +++ b/crates/metal2vulkan-runtime/src/exit_guard.rs @@ -442,6 +442,41 @@ calls! { // A batch's first work: the clear of a neutral depth image, which may be multisampled // (`texture/first_move.rs`, `neutral.rs`). CmdClearDepthStencilImage => c"vkCmdClearDepthStencilImage", + // An encoder's commands, which a deferred command buffer's replay records (`recorder`): those + // no host step records. + CmdBlitImage => c"vkCmdBlitImage", + CmdUpdateBuffer => c"vkCmdUpdateBuffer", + CmdFillBuffer => c"vkCmdFillBuffer", + CmdClearAttachments => c"vkCmdClearAttachments", + CmdCopyQueryPoolResults => c"vkCmdCopyQueryPoolResults", + // A render encoder's extended dynamic states, on a device that has them + // ([`EXTENDED_DYNAMIC_STATE_CALLS`](crate::device::prime::EXTENDED_DYNAMIC_STATE_CALLS), + // [`PRIMITIVE_RESTART_CALLS`](crate::device::prime::PRIMITIVE_RESTART_CALLS)), through the + // entry points the device gave (`dynamic_state.rs`: Vulkan 1.3's, else the extensions'). + CmdSetCullMode => c"vkCmdSetCullMode", + CmdSetFrontFace => c"vkCmdSetFrontFace", + CmdSetPrimitiveTopology => c"vkCmdSetPrimitiveTopology", + CmdBindVertexBuffers2 => c"vkCmdBindVertexBuffers2", + CmdSetDepthTestEnable => c"vkCmdSetDepthTestEnable", + CmdSetDepthWriteEnable => c"vkCmdSetDepthWriteEnable", + CmdSetDepthCompareOp => c"vkCmdSetDepthCompareOp", + CmdSetStencilTestEnable => c"vkCmdSetStencilTestEnable", + CmdSetStencilOp => c"vkCmdSetStencilOp", + CmdSetPrimitiveRestartEnable => c"vkCmdSetPrimitiveRestartEnable", + // A render encoder's extension commands, each on a device that has it + // ([`COLOR_WRITE_MASK_CALLS`](crate::device::prime::COLOR_WRITE_MASK_CALLS), + // [`DEPTH_BIAS_CALLS`](crate::device::prime::DEPTH_BIAS_CALLS), + // [`SIZED_INDEX_BIND_CALLS`](crate::device::prime::SIZED_INDEX_BIND_CALLS)), through the + // entry point the device gave (`vkCmdBindIndexBuffer2KHR` where it enables that form). + CmdSetColorWriteMask => c"vkCmdSetColorWriteMaskEXT", + CmdSetDepthBias2 => c"vkCmdSetDepthBias2EXT", + CmdBindIndexBuffer2 => c"vkCmdBindIndexBuffer2", + // A mesh draw's, and an execution of commands the GPU generates: never primed + // ([`UNPRIMED`](crate::device::prime::UNPRIMED)). + CmdDrawMeshTasks => c"vkCmdDrawMeshTasksEXT", + CmdDrawMeshTasksIndirect => c"vkCmdDrawMeshTasksIndirectEXT", + CmdExecuteGeneratedCommands => c"vkCmdExecuteGeneratedCommandsEXT", + CmdPreprocessGeneratedCommands => c"vkCmdPreprocessGeneratedCommandsEXT", } /// The entry points a host step may call (`CommandBufferShared::host_step`): what a dispatch @@ -528,7 +563,7 @@ pub(crate) const HOST_STEP: &[Call] = &[ ]; impl Call { - /// Its bit. The table fills 88 of the word's 128 (widened from 64): when it next outgrows the + /// Its bit. The table fills 113 of the word's 128 (widened from 64): when it next outgrows the /// word, widen the word (here, [`CALLED`], `PENDING` and the priming's calls); do not add a /// second table. pub(crate) fn bit(self) -> u128 { diff --git a/crates/metal2vulkan-runtime/src/generated_commands.rs b/crates/metal2vulkan-runtime/src/generated_commands.rs index 02eac999d..154631be7 100644 --- a/crates/metal2vulkan-runtime/src/generated_commands.rs +++ b/crates/metal2vulkan-runtime/src/generated_commands.rs @@ -216,6 +216,7 @@ impl MemoryRequirementsInfo { /// `VkGeneratedCommandsInfoEXT`. #[repr(C)] +#[derive(Clone, Copy)] pub struct GeneratedCommandsInfo { pub s_type: vk::StructureType, pub p_next: *const c_void, @@ -337,6 +338,23 @@ impl Commands { }) } + /// The commands, those that record through `slot` where the device has one (`recorder`). + pub(crate) fn routed(self, slot: Option<&crate::recorder::Slot>) -> Commands { + use crate::recorder::{through, Command}; + // SAFETY: each is the device's command of the routed command's signature. + unsafe { + Commands { + execute: through(slot, Command::CmdExecuteGeneratedCommands, self.execute), + preprocess: through( + slot, + Command::CmdPreprocessGeneratedCommands, + self.preprocess, + ), + ..self + } + } + } + /// `vkCreateIndirectExecutionSetEXT`. /// /// # Safety diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index 6abdca81e..3b01627ee 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -858,6 +858,11 @@ impl Release { lock(&self.deallocator).is_some() } + /// Whether it still holds the caller's keep-alive. + pub(super) fn keeps_alive(&self) -> bool { + lock(&self.keep_alive).is_some() + } + /// The length of the caller's range. pub(super) fn length(&self) -> u64 { self.length diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index f1e5243e2..c3fe9bace 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -159,6 +159,7 @@ mod rate_map; mod rate_mapped_pass; mod reader_sizes; mod rebind; +mod recorder; mod release; mod render; mod render_pass; @@ -296,6 +297,8 @@ pub use queue::CommandQueue; pub use rate_map::{RasterizationRateMap, RateMapProblem}; pub use rate_mapped_pass::RegionRefusal; pub use rebind::RebindProblem; +#[doc(hidden)] +pub use recorder::CommandsReplayed; pub use render::{DrawProblem, RenderCommandEncoder, ResolveTarget}; pub use render_pass::{ Attachment, RenderPassColorAttachmentDescriptor, RenderPassDepthAttachmentDescriptor, diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index 77be3520b..5ef52bbfc 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -720,10 +720,15 @@ impl Taken { } /// Hold every pin weakly: its command buffer committed and waits for its first submission. - pub(super) fn wait(&mut self) { + /// The pages it held go to `held`, which its deferred command buffers' replays hold until + /// they are replayed (`recorder`). + pub(super) fn wait(&mut self, held: &mut Vec>) { for (_, pinned) in &mut self.pins { if let Pinned::Held(pages) = pinned { - *pinned = Pinned::Waiting(Arc::downgrade(pages)); + let waiting = Pinned::Waiting(Arc::downgrade(pages)); + if let Pinned::Held(pages) = std::mem::replace(pinned, waiting) { + held.push(pages); + } } } for hold in &mut self.imports { diff --git a/crates/metal2vulkan-runtime/src/recorder/handles.rs b/crates/metal2vulkan-runtime/src/recorder/handles.rs new file mode 100644 index 000000000..487948490 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/recorder/handles.rs @@ -0,0 +1,169 @@ +//! Deferred command buffers' handles: each is the address of one entry of a table of this +//! process's, so it never equals a driver's command buffer (a dispatchable handle is a pointer to +//! the driver's or the loader's own memory), and the entry holds its log (`recorder`). +//! +//! - **Made** by an encoder's command buffer from its pool's place ([`make`]), for the command +//! buffer's [`Replays`]; none once [`HANDLES`] are live together, where the command buffer takes +//! a driver's command buffer instead, recorded as before. +//! - **Found** by each routed entry point with one subtraction and one load ([`log`]); a +//! driver's command buffer is outside the table. +//! - **Let go of** with their command buffer's replays (`Replays::release`): the logs keep their +//! room for the next ones. + +use super::log::{Log, Stage}; +use super::replays::Replays; +use crate::device::lock; +use ash::vk::{self, Handle}; +use std::sync::atomic::{AtomicPtr, Ordering}; +use std::sync::{Arc, Mutex}; + +/// How many deferred command buffers may be live together in the process. +pub(super) const HANDLES: usize = 1 << 16; + +/// Each handle's log; null while it is free. +static LOGS: [AtomicPtr; HANDLES] = [const { AtomicPtr::new(std::ptr::null_mut()) }; HANDLES]; + +/// The free handles and the logs kept for reuse. +struct Free { + /// Freed handles, reused first. + indices: Vec, + /// The next handle never made. + next: u32, + /// Logs let go of, emptied, their room kept. + logs: Vec, +} + +/// A log kept for reuse in the box a handle's entry points to: a handle made takes it with no +/// allocation. +struct Kept(Box); + +static FREE: Mutex = Mutex::new(Free { + indices: Vec::new(), + next: 0, + logs: Vec::new(), +}); + +/// The most logs [`FREE`] keeps for reuse. +const KEPT_LOGS: usize = 1024; + +/// The handle of entry `index`. +pub(super) fn handle(index: u32) -> vk::CommandBuffer { + vk::CommandBuffer::from_raw(std::ptr::from_ref(&LOGS[index as usize]) as u64) +} + +/// The entry `raw` names, where it is a deferred command buffer's handle. +pub(super) fn index(raw: vk::CommandBuffer) -> Option { + let base = LOGS.as_ptr() as u64; + let offset = raw.as_raw().wrapping_sub(base); + let size = std::mem::size_of::>() as u64; + (offset < HANDLES as u64 * size && offset.is_multiple_of(size)) + .then_some((offset / size) as u32) +} + +/// Whether `raw` is a deferred command buffer's handle. +pub(crate) fn is_deferred(raw: vk::CommandBuffer) -> bool { + index(raw).is_some() +} + +/// Log a command into `raw`'s log with `log`, where `raw` is a live deferred command buffer: its +/// answer. Where the command ended the log, its replays take it once `log`'s borrow of it ended, +/// so a replay, which may start at once, reads it with no other borrow of it live. +/// +/// # Safety +/// +/// The caller records `raw` alone, as Vulkan's external synchronization of a command buffer asks. +pub(super) unsafe fn record( + raw: vk::CommandBuffer, + log: impl FnOnce(&mut Log) -> R, +) -> Option { + let index = index(raw)?; + let entry = LOGS[index as usize].load(Ordering::Acquire); + if entry.is_null() { + return None; + } + // SAFETY: a live entry's log lives until its handle is let go of, which its command buffer + // does only once nothing records it; only the caller records it, and no replay reads it + // before it ended (below). + let answer = log(unsafe { &mut *entry }); + // SAFETY: as above; read only, the borrow above having ended. + let logged = unsafe { &*entry }; + if logged.stage == Stage::Ended { + if let Some(replays) = logged.replays() { + replays.ended(logged.index()); + } + } + Some(answer) +} + +/// The log of `raw`, where it is a live deferred command buffer, to read. +/// +/// # Safety +/// +/// The log ended (only replays read it from then on, and only its release writes it). +pub(super) unsafe fn log<'a>(raw: vk::CommandBuffer) -> Option<&'a Log> { + let index = index(raw)?; + let log = LOGS[index as usize].load(Ordering::Acquire); + // SAFETY: the caller's; a live entry's log lives until its handle is let go of. + unsafe { log.as_ref() } +} + +/// The log at `index`, live and ended, to read. +/// +/// # Safety +/// +/// As [`log`]. +pub(super) unsafe fn log_at<'a>(index: u32) -> &'a Log { + let log = LOGS[index as usize].load(Ordering::Acquire); + // SAFETY: the caller's: the entry is live. + unsafe { &*log } +} + +/// A new deferred command buffer of `level` for `replays`, its index; `None` where every handle +/// is live. +pub(super) fn make(level: vk::CommandBufferLevel, replays: &Arc) -> Option { + let (index, kept) = { + let mut free = lock(&FREE); + let index = match free.indices.pop() { + Some(index) => index, + None if (free.next as usize) < HANDLES => { + free.next += 1; + free.next - 1 + } + None => return None, + }; + (index, free.logs.pop()) + }; + let mut log = match kept { + Some(Kept(mut log)) => { + log.clear(level); + log + } + None => Box::new(Log::new(level)), + }; + log.own(index, Arc::clone(replays)); + LOGS[index as usize].store(Box::into_raw(log), Ordering::Release); + Some(index) +} + +/// Let go of the handles `indices`: their logs go back for reuse. +/// +/// # Safety +/// +/// Nothing records or reads any of them, nor will: their command buffer let go of them. +pub(super) unsafe fn free(indices: &[u32]) { + let mut free = lock(&FREE); + for &index in indices { + let log = LOGS[index as usize].swap(std::ptr::null_mut(), Ordering::AcqRel); + if log.is_null() { + continue; + } + // SAFETY: made by `Box::into_raw` in `make`, taken out of the table just now. + let mut log = unsafe { Box::from_raw(log) }; + // Its hold on its replays goes: never their last, which their command buffer holds. + log.disown(); + if free.logs.len() < KEPT_LOGS { + free.logs.push(Kept(log)); + } + } + free.indices.extend_from_slice(indices); +} diff --git a/crates/metal2vulkan-runtime/src/recorder/log.rs b/crates/metal2vulkan-runtime/src/recorder/log.rs new file mode 100644 index 000000000..08c2e9bb0 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/recorder/log.rs @@ -0,0 +1,1760 @@ +//! A deferred command buffer's log: each command its recording made, with its arguments copied at +//! the call, and the replay of them into a `VkCommandBuffer` (`recorder`). +//! +//! - **Copied at the call.** Every argument a command reads through a pointer (regions, barriers, +//! viewports, clear values, push constants, an update's bytes, a pushed set's descriptors, a +//! begin's inheritance) is copied into one of the log's arenas as the command is called, as a +//! driver reads them at the call: the program's and the runtime's memory may change at once. +//! Handles are copied as they are; every object a command names stays live until its command +//! buffer completes (the runtime's contract for a recording), so past the replay. +//! - **Extension structures.** A structure's chain holds only what the runtime chains there (a +//! depth bias's representation); a chain of anything else is a defect of the runtime's, which +//! ends the process at the call: the command would otherwise be replayed without it. +//! - **Its memory** is kept for the next log ([`Log::clear`]): the arenas keep their room. What a +//! replay builds of them to call with (a pushed set's writes, an execution's secondaries) is +//! built in its thread's room ([`SCRATCH`]), so a replay allocates nothing once that holds +//! enough. + +use super::handles; +use super::replays::{real_of, Replays}; +use super::thunks::{real, Command}; +use crate::exit_guard::{self, Call}; +use crate::generated_commands::GeneratedCommandsInfo; +use ash::vk::{self, Handle}; +use std::cell::RefCell; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; + +/// What a replay builds of its log's arenas to call with. +struct Scratch { + /// A pushed set's writes, pointing into the log's arenas while their call lasts. + writes: Vec>, + /// An execution's secondaries, replayed. + secondaries: Vec, +} + +thread_local! { + /// The room replays on this thread build in ([`Scratch`]), kept for the next. + static SCRATCH: RefCell = const { + RefCell::new(Scratch { + writes: Vec::new(), + secondaries: Vec::new(), + }) + }; +} + +/// A run of elements in one of a log's arenas. +#[derive(Clone, Copy, Default)] +struct Span { + start: u32, + len: u32, +} + +/// An arena of `T`s that crosses threads: its elements' pointers (an `ash` structure's `p_next`) +/// are null, checked as each goes in. +struct Arena(Vec); + +// SAFETY: every element's pointers are null (the type's docs): the elements are plain values. +unsafe impl Send for Arena {} +// SAFETY: as above. +unsafe impl Sync for Arena {} + +impl Arena { + const fn new() -> Arena { + Arena(Vec::new()) + } + + /// `count` elements from `from`, copied in. + /// + /// # Safety + /// + /// `from` points at `count` readable elements, or `count` is 0. + unsafe fn push(&mut self, from: *const T, count: u32) -> Span { + let start = self.0.len() as u32; + if count > 0 && !from.is_null() { + // SAFETY: the caller's. + self.0 + .extend_from_slice(unsafe { std::slice::from_raw_parts(from, count as usize) }); + } + Span { + start, + len: self.0.len() as u32 - start, + } + } + + fn one(&mut self, value: T) -> Span { + let start = self.0.len() as u32; + self.0.push(value); + Span { start, len: 1 } + } + + fn get(&self, span: Span) -> &[T] { + &self.0[span.start as usize..(span.start + span.len) as usize] + } + + fn get_ptr(&self, span: Span) -> *const T { + match span.len { + 0 => std::ptr::null(), + _ => self.get(span).as_ptr(), + } + } +} + +/// End the process for a structure chain the log does not copy (the module docs). +#[cold] +fn unchained(what: &str) -> ! { + panic!("a deferred command's {what} chains a structure the recorder does not copy"); +} + +/// A pushed set's write, its descriptors in the log's arenas. +#[derive(Clone, Copy)] +struct Write { + binding: u32, + element: u32, + count: u32, + kind: vk::DescriptorType, + images: Span, + buffers: Span, + views: Span, +} + +/// A secondary command buffer's inheritance, copied. +#[derive(Clone, Copy)] +struct Inheritance { + render_pass: vk::RenderPass, + subpass: u32, + framebuffer: vk::Framebuffer, + occlusion: vk::Bool32, + query_flags: vk::QueryControlFlags, + statistics: vk::QueryPipelineStatisticFlags, +} + +/// One command, its arrays in the log's arenas. +#[derive(Clone, Copy)] +enum Logged { + BindPipeline(vk::PipelineBindPoint, vk::Pipeline), + SetViewport(u32, Span), + SetScissor(u32, Span), + SetDepthBias(f32, f32, f32), + SetBlendConstants([f32; 4]), + SetStencilCompareMask(vk::StencilFaceFlags, u32), + SetStencilWriteMask(vk::StencilFaceFlags, u32), + SetStencilReference(vk::StencilFaceFlags, u32), + BindDescriptorSets { + point: vk::PipelineBindPoint, + layout: vk::PipelineLayout, + first: u32, + sets: Span, + offsets: Span, + }, + BindIndexBuffer(vk::Buffer, vk::DeviceSize, vk::IndexType), + BindVertexBuffers { + first: u32, + buffers: Span, + offsets: Span, + }, + Draw(u32, u32, u32, u32), + DrawIndexed(u32, u32, u32, i32, u32), + DrawIndirect(vk::Buffer, vk::DeviceSize, u32, u32), + DrawIndexedIndirect(vk::Buffer, vk::DeviceSize, u32, u32), + Dispatch(u32, u32, u32), + DispatchIndirect(vk::Buffer, vk::DeviceSize), + CopyBuffer(vk::Buffer, vk::Buffer, Span), + CopyImage { + src: vk::Image, + src_layout: vk::ImageLayout, + dst: vk::Image, + dst_layout: vk::ImageLayout, + regions: Span, + }, + BlitImage { + src: vk::Image, + src_layout: vk::ImageLayout, + dst: vk::Image, + dst_layout: vk::ImageLayout, + regions: Span, + filter: vk::Filter, + }, + CopyBufferToImage { + src: vk::Buffer, + dst: vk::Image, + layout: vk::ImageLayout, + regions: Span, + }, + CopyImageToBuffer { + src: vk::Image, + layout: vk::ImageLayout, + dst: vk::Buffer, + regions: Span, + }, + UpdateBuffer(vk::Buffer, vk::DeviceSize, Span), + FillBuffer(vk::Buffer, vk::DeviceSize, vk::DeviceSize, u32), + ClearColorImage(vk::Image, vk::ImageLayout, vk::ClearColorValue, Span), + ClearDepthStencilImage(vk::Image, vk::ImageLayout, vk::ClearDepthStencilValue, Span), + ClearAttachments(Span, Span), + PipelineBarrier { + src: vk::PipelineStageFlags, + dst: vk::PipelineStageFlags, + flags: vk::DependencyFlags, + memory: Span, + buffers: Span, + images: Span, + }, + BeginQuery(vk::QueryPool, u32, vk::QueryControlFlags), + EndQuery(vk::QueryPool, u32), + ResetQueryPool(vk::QueryPool, u32, u32), + WriteTimestamp(vk::PipelineStageFlags, vk::QueryPool, u32), + CopyQueryPoolResults { + pool: vk::QueryPool, + first: u32, + count: u32, + dst: vk::Buffer, + offset: vk::DeviceSize, + stride: vk::DeviceSize, + flags: vk::QueryResultFlags, + }, + PushConstants { + layout: vk::PipelineLayout, + stages: vk::ShaderStageFlags, + offset: u32, + bytes: Span, + }, + BeginRenderPass { + render_pass: vk::RenderPass, + framebuffer: vk::Framebuffer, + area: vk::Rect2D, + clears: Span, + contents: vk::SubpassContents, + }, + EndRenderPass, + ExecuteCommands(Span), + SetCullMode(vk::CullModeFlags), + SetFrontFace(vk::FrontFace), + SetPrimitiveTopology(vk::PrimitiveTopology), + BindVertexBuffers2 { + first: u32, + buffers: Span, + offsets: Span, + sizes: Option, + strides: Option, + }, + SetDepthTestEnable(vk::Bool32), + SetDepthWriteEnable(vk::Bool32), + SetDepthCompareOp(vk::CompareOp), + SetStencilTestEnable(vk::Bool32), + SetStencilOp( + vk::StencilFaceFlags, + vk::StencilOp, + vk::StencilOp, + vk::StencilOp, + vk::CompareOp, + ), + SetPrimitiveRestartEnable(vk::Bool32), + PushDescriptorSet { + point: vk::PipelineBindPoint, + layout: vk::PipelineLayout, + set: u32, + writes: Span, + }, + SetColorWriteMask(u32, Span), + SetDepthBias2 { + factors: [f32; 3], + representation: Option<(vk::DepthBiasRepresentationEXT, vk::Bool32)>, + }, + BindIndexBuffer2(vk::Buffer, vk::DeviceSize, vk::DeviceSize, vk::IndexType), + DrawMeshTasks(u32, u32, u32), + DrawMeshTasksIndirect(vk::Buffer, vk::DeviceSize, u32, u32), + /// Preprocessed, and the info's place in its arena. + ExecuteGeneratedCommands(vk::Bool32, Span), + /// The info's place, and the state command buffer where it is another than this one. + PreprocessGeneratedCommands(Span, Option), +} + +/// Where a log stands. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Stage { + /// Made, not begun. + Initial, + Recording, + Ended, +} + +/// One deferred command buffer's log (the module docs). +pub(super) struct Log { + /// Its handle's entry, and its command buffer's replays, while its handle is live. + index: u32, + replays: Option>, + /// The command buffer its replay recorded, once replayed (0 before). + real: AtomicU64, + pub(super) stage: Stage, + pub(super) level: vk::CommandBufferLevel, + /// The begin's usage flags and a secondary's inheritance. + flags: vk::CommandBufferUsageFlags, + inheritance: Option, + ops: Vec, + bytes: Arena, + words: Arena, + u32s: Arena, + buffers: Arena, + sets: Arena, + viewports: Arena, + rects: Arena, + buffer_copies: Arena, + image_copies: Arena, + blits: Arena, + buffer_images: Arena, + ranges: Arena, + clear_attachments: Arena, + clear_rects: Arena, + clear_values: Arena, + memory_barriers: Arena>, + buffer_barriers: Arena>, + image_barriers: Arena>, + command_buffers: Arena, + writes: Arena, + image_infos: Arena, + buffer_infos: Arena, + views: Arena, + masks: Arena, + generated: Arena, +} + +impl Log { + /// An empty log of `level`. + pub(super) fn new(level: vk::CommandBufferLevel) -> Log { + Log { + index: 0, + replays: None, + real: AtomicU64::new(0), + stage: Stage::Initial, + level, + flags: vk::CommandBufferUsageFlags::empty(), + inheritance: None, + ops: Vec::new(), + bytes: Arena::new(), + words: Arena::new(), + u32s: Arena::new(), + buffers: Arena::new(), + sets: Arena::new(), + viewports: Arena::new(), + rects: Arena::new(), + buffer_copies: Arena::new(), + image_copies: Arena::new(), + blits: Arena::new(), + buffer_images: Arena::new(), + ranges: Arena::new(), + clear_attachments: Arena::new(), + clear_rects: Arena::new(), + clear_values: Arena::new(), + memory_barriers: Arena::new(), + buffer_barriers: Arena::new(), + image_barriers: Arena::new(), + command_buffers: Arena::new(), + writes: Arena::new(), + image_infos: Arena::new(), + buffer_infos: Arena::new(), + views: Arena::new(), + masks: Arena::new(), + generated: Arena::new(), + } + } + + /// Empty it for a new command buffer of `level`, keeping its arenas' room. + pub(super) fn clear(&mut self, level: vk::CommandBufferLevel) { + self.stage = Stage::Initial; + self.level = level; + self.flags = vk::CommandBufferUsageFlags::empty(); + self.inheritance = None; + self.ops.clear(); + self.bytes.0.clear(); + self.words.0.clear(); + self.u32s.0.clear(); + self.buffers.0.clear(); + self.sets.0.clear(); + self.viewports.0.clear(); + self.rects.0.clear(); + self.buffer_copies.0.clear(); + self.image_copies.0.clear(); + self.blits.0.clear(); + self.buffer_images.0.clear(); + self.ranges.0.clear(); + self.clear_attachments.0.clear(); + self.clear_rects.0.clear(); + self.clear_values.0.clear(); + self.memory_barriers.0.clear(); + self.buffer_barriers.0.clear(); + self.image_barriers.0.clear(); + self.command_buffers.0.clear(); + self.writes.0.clear(); + self.image_infos.0.clear(); + self.buffer_infos.0.clear(); + self.views.0.clear(); + self.masks.0.clear(); + self.generated.0.clear(); + } + + /// It is handle `index`'s, of a command buffer's `replays`. + pub(super) fn own(&mut self, index: u32, replays: Arc) { + self.index = index; + self.replays = Some(replays); + self.real.store(0, Ordering::Relaxed); + } + + /// Its handle was let go of. + pub(super) fn disown(&mut self) { + self.replays = None; + } + + /// Its handle's entry. + pub(super) fn index(&self) -> u32 { + self.index + } + + /// Whether its replay may record into a primary begun ahead (`spares.rs`): a primary begun as + /// that one is, `ONE_TIME_SUBMIT` alone. + pub(super) fn takes_begun(&self) -> bool { + self.level == vk::CommandBufferLevel::PRIMARY + && self.flags == vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT + && self.inheritance.is_none() + } + + /// Its command buffer's replays, while its handle is live. + pub(super) fn replays(&self) -> Option<&Arc> { + self.replays.as_ref() + } + + /// The command buffer its replay recorded, once replayed. + pub(super) fn real(&self) -> Option { + real_of(&self.real) + } + + /// Its replay recorded `real`, ended. + pub(super) fn replayed(&self, real: vk::CommandBuffer) { + self.real.store(real.as_raw(), Ordering::Release); + } + + /// Room for the end a commit may fold into this log, its command buffer's tail + /// ([`reserve_end`](super::reserve_end)): two commands and one memory barrier. + pub(super) fn reserve_end(&mut self) { + self.ops.reserve(2); + self.memory_barriers.0.reserve(1); + } + + fn op(&mut self, op: Logged) { + debug_assert_eq!( + self.stage, + Stage::Recording, + "a command outside a recording" + ); + self.ops.push(op); + } +} + +/// The logging of each routed command: the same parameters as its entry point's after the +/// command buffer (`thunks.rs`), each copying what it reads through a pointer. +/// +/// # Safety (each) +/// +/// The command's valid usage: its pointers point at as many elements as its counts say. +impl Log { + pub(super) unsafe fn begin_command_buffer( + &mut self, + info: *const vk::CommandBufferBeginInfo<'_>, + ) -> vk::Result { + // SAFETY: the caller's. + let info = unsafe { &*info }; + if !info.p_next.is_null() { + unchained("begin"); + } + let level = self.level; + self.clear(level); + self.flags = info.flags; + if level == vk::CommandBufferLevel::SECONDARY && !info.p_inheritance_info.is_null() { + // SAFETY: the caller's. + let inherited = unsafe { &*info.p_inheritance_info }; + if !inherited.p_next.is_null() { + unchained("inheritance"); + } + self.inheritance = Some(Inheritance { + render_pass: inherited.render_pass, + subpass: inherited.subpass, + framebuffer: inherited.framebuffer, + occlusion: inherited.occlusion_query_enable, + query_flags: inherited.query_flags, + statistics: inherited.pipeline_statistics, + }); + } + self.stage = Stage::Recording; + vk::Result::SUCCESS + } + + /// Its end: its replays take it once the call's borrow of it ended (`handles::record`). + pub(super) unsafe fn end_command_buffer(&mut self) -> vk::Result { + debug_assert_eq!(self.stage, Stage::Recording, "an end outside a recording"); + self.stage = Stage::Ended; + vk::Result::SUCCESS + } + + pub(super) unsafe fn cmd_bind_pipeline( + &mut self, + point: vk::PipelineBindPoint, + pipeline: vk::Pipeline, + ) { + self.op(Logged::BindPipeline(point, pipeline)); + } + + pub(super) unsafe fn cmd_set_viewport( + &mut self, + first: u32, + count: u32, + viewports: *const vk::Viewport, + ) { + // SAFETY: the caller's. + let span = unsafe { self.viewports.push(viewports, count) }; + self.op(Logged::SetViewport(first, span)); + } + + pub(super) unsafe fn cmd_set_scissor( + &mut self, + first: u32, + count: u32, + rects: *const vk::Rect2D, + ) { + // SAFETY: the caller's. + let span = unsafe { self.rects.push(rects, count) }; + self.op(Logged::SetScissor(first, span)); + } + + pub(super) unsafe fn cmd_set_depth_bias(&mut self, constant: f32, clamp: f32, slope: f32) { + self.op(Logged::SetDepthBias(constant, clamp, slope)); + } + + pub(super) unsafe fn cmd_set_blend_constants(&mut self, constants: *const [f32; 4]) { + // SAFETY: the caller's. + self.op(Logged::SetBlendConstants(unsafe { *constants })); + } + + pub(super) unsafe fn cmd_set_stencil_compare_mask( + &mut self, + faces: vk::StencilFaceFlags, + mask: u32, + ) { + self.op(Logged::SetStencilCompareMask(faces, mask)); + } + + pub(super) unsafe fn cmd_set_stencil_write_mask( + &mut self, + faces: vk::StencilFaceFlags, + mask: u32, + ) { + self.op(Logged::SetStencilWriteMask(faces, mask)); + } + + pub(super) unsafe fn cmd_set_stencil_reference( + &mut self, + faces: vk::StencilFaceFlags, + reference: u32, + ) { + self.op(Logged::SetStencilReference(faces, reference)); + } + + pub(super) unsafe fn cmd_bind_descriptor_sets( + &mut self, + point: vk::PipelineBindPoint, + layout: vk::PipelineLayout, + first: u32, + count: u32, + sets: *const vk::DescriptorSet, + offset_count: u32, + offsets: *const u32, + ) { + // SAFETY: the caller's. + let (sets, offsets) = unsafe { + ( + self.sets.push(sets, count), + self.u32s.push(offsets, offset_count), + ) + }; + self.op(Logged::BindDescriptorSets { + point, + layout, + first, + sets, + offsets, + }); + } + + pub(super) unsafe fn cmd_bind_index_buffer( + &mut self, + buffer: vk::Buffer, + offset: vk::DeviceSize, + index_type: vk::IndexType, + ) { + self.op(Logged::BindIndexBuffer(buffer, offset, index_type)); + } + + pub(super) unsafe fn cmd_bind_vertex_buffers( + &mut self, + first: u32, + count: u32, + buffers: *const vk::Buffer, + offsets: *const vk::DeviceSize, + ) { + // SAFETY: the caller's. + let (buffers, offsets) = unsafe { + ( + self.buffers.push(buffers, count), + self.words.push(offsets, count), + ) + }; + self.op(Logged::BindVertexBuffers { + first, + buffers, + offsets, + }); + } + + pub(super) unsafe fn cmd_draw(&mut self, vertices: u32, instances: u32, first: u32, base: u32) { + self.op(Logged::Draw(vertices, instances, first, base)); + } + + pub(super) unsafe fn cmd_draw_indexed( + &mut self, + indices: u32, + instances: u32, + first: u32, + offset: i32, + base: u32, + ) { + self.op(Logged::DrawIndexed(indices, instances, first, offset, base)); + } + + pub(super) unsafe fn cmd_draw_indirect( + &mut self, + buffer: vk::Buffer, + offset: vk::DeviceSize, + count: u32, + stride: u32, + ) { + self.op(Logged::DrawIndirect(buffer, offset, count, stride)); + } + + pub(super) unsafe fn cmd_draw_indexed_indirect( + &mut self, + buffer: vk::Buffer, + offset: vk::DeviceSize, + count: u32, + stride: u32, + ) { + self.op(Logged::DrawIndexedIndirect(buffer, offset, count, stride)); + } + + pub(super) unsafe fn cmd_dispatch(&mut self, x: u32, y: u32, z: u32) { + self.op(Logged::Dispatch(x, y, z)); + } + + pub(super) unsafe fn cmd_dispatch_indirect( + &mut self, + buffer: vk::Buffer, + offset: vk::DeviceSize, + ) { + self.op(Logged::DispatchIndirect(buffer, offset)); + } + + pub(super) unsafe fn cmd_copy_buffer( + &mut self, + src: vk::Buffer, + dst: vk::Buffer, + count: u32, + regions: *const vk::BufferCopy, + ) { + // SAFETY: the caller's. + let regions = unsafe { self.buffer_copies.push(regions, count) }; + self.op(Logged::CopyBuffer(src, dst, regions)); + } + + pub(super) unsafe fn cmd_copy_image( + &mut self, + src: vk::Image, + src_layout: vk::ImageLayout, + dst: vk::Image, + dst_layout: vk::ImageLayout, + count: u32, + regions: *const vk::ImageCopy, + ) { + // SAFETY: the caller's. + let regions = unsafe { self.image_copies.push(regions, count) }; + self.op(Logged::CopyImage { + src, + src_layout, + dst, + dst_layout, + regions, + }); + } + + pub(super) unsafe fn cmd_blit_image( + &mut self, + src: vk::Image, + src_layout: vk::ImageLayout, + dst: vk::Image, + dst_layout: vk::ImageLayout, + count: u32, + regions: *const vk::ImageBlit, + filter: vk::Filter, + ) { + // SAFETY: the caller's. + let regions = unsafe { self.blits.push(regions, count) }; + self.op(Logged::BlitImage { + src, + src_layout, + dst, + dst_layout, + regions, + filter, + }); + } + + pub(super) unsafe fn cmd_copy_buffer_to_image( + &mut self, + src: vk::Buffer, + dst: vk::Image, + layout: vk::ImageLayout, + count: u32, + regions: *const vk::BufferImageCopy, + ) { + // SAFETY: the caller's. + let regions = unsafe { self.buffer_images.push(regions, count) }; + self.op(Logged::CopyBufferToImage { + src, + dst, + layout, + regions, + }); + } + + pub(super) unsafe fn cmd_copy_image_to_buffer( + &mut self, + src: vk::Image, + layout: vk::ImageLayout, + dst: vk::Buffer, + count: u32, + regions: *const vk::BufferImageCopy, + ) { + // SAFETY: the caller's. + let regions = unsafe { self.buffer_images.push(regions, count) }; + self.op(Logged::CopyImageToBuffer { + src, + layout, + dst, + regions, + }); + } + + pub(super) unsafe fn cmd_update_buffer( + &mut self, + dst: vk::Buffer, + offset: vk::DeviceSize, + size: vk::DeviceSize, + data: *const c_void, + ) { + // SAFETY: the caller's: `size` bytes at `data` (at most 65536, Vulkan's bound). + let bytes = unsafe { self.bytes.push(data.cast(), size as u32) }; + self.op(Logged::UpdateBuffer(dst, offset, bytes)); + } + + pub(super) unsafe fn cmd_fill_buffer( + &mut self, + dst: vk::Buffer, + offset: vk::DeviceSize, + size: vk::DeviceSize, + data: u32, + ) { + self.op(Logged::FillBuffer(dst, offset, size, data)); + } + + pub(super) unsafe fn cmd_clear_color_image( + &mut self, + image: vk::Image, + layout: vk::ImageLayout, + color: *const vk::ClearColorValue, + count: u32, + ranges: *const vk::ImageSubresourceRange, + ) { + // SAFETY: the caller's. + let (color, ranges) = unsafe { (*color, self.ranges.push(ranges, count)) }; + self.op(Logged::ClearColorImage(image, layout, color, ranges)); + } + + pub(super) unsafe fn cmd_clear_depth_stencil_image( + &mut self, + image: vk::Image, + layout: vk::ImageLayout, + value: *const vk::ClearDepthStencilValue, + count: u32, + ranges: *const vk::ImageSubresourceRange, + ) { + // SAFETY: the caller's. + let (value, ranges) = unsafe { (*value, self.ranges.push(ranges, count)) }; + self.op(Logged::ClearDepthStencilImage(image, layout, value, ranges)); + } + + pub(super) unsafe fn cmd_clear_attachments( + &mut self, + count: u32, + attachments: *const vk::ClearAttachment, + rect_count: u32, + rects: *const vk::ClearRect, + ) { + // SAFETY: the caller's. + let (attachments, rects) = unsafe { + ( + self.clear_attachments.push(attachments, count), + self.clear_rects.push(rects, rect_count), + ) + }; + self.op(Logged::ClearAttachments(attachments, rects)); + } + + pub(super) unsafe fn cmd_pipeline_barrier( + &mut self, + src: vk::PipelineStageFlags, + dst: vk::PipelineStageFlags, + flags: vk::DependencyFlags, + memory_count: u32, + memory: *const vk::MemoryBarrier<'_>, + buffer_count: u32, + buffers: *const vk::BufferMemoryBarrier<'_>, + image_count: u32, + images: *const vk::ImageMemoryBarrier<'_>, + ) { + // SAFETY: the caller's; each structure is copied whole, its chain checked empty. + let (memory, buffers, images) = unsafe { + ( + self.memory_barriers.push(memory.cast(), memory_count), + self.buffer_barriers.push(buffers.cast(), buffer_count), + self.image_barriers.push(images.cast(), image_count), + ) + }; + let chained = self + .memory_barriers + .get(memory) + .iter() + .any(|b| !b.p_next.is_null()) + || self + .buffer_barriers + .get(buffers) + .iter() + .any(|b| !b.p_next.is_null()) + || self + .image_barriers + .get(images) + .iter() + .any(|b| !b.p_next.is_null()); + if chained { + unchained("barrier"); + } + self.op(Logged::PipelineBarrier { + src, + dst, + flags, + memory, + buffers, + images, + }); + } + + pub(super) unsafe fn cmd_begin_query( + &mut self, + pool: vk::QueryPool, + query: u32, + flags: vk::QueryControlFlags, + ) { + self.op(Logged::BeginQuery(pool, query, flags)); + } + + pub(super) unsafe fn cmd_end_query(&mut self, pool: vk::QueryPool, query: u32) { + self.op(Logged::EndQuery(pool, query)); + } + + pub(super) unsafe fn cmd_reset_query_pool( + &mut self, + pool: vk::QueryPool, + first: u32, + count: u32, + ) { + self.op(Logged::ResetQueryPool(pool, first, count)); + } + + pub(super) unsafe fn cmd_write_timestamp( + &mut self, + stage: vk::PipelineStageFlags, + pool: vk::QueryPool, + query: u32, + ) { + self.op(Logged::WriteTimestamp(stage, pool, query)); + } + + pub(super) unsafe fn cmd_copy_query_pool_results( + &mut self, + pool: vk::QueryPool, + first: u32, + count: u32, + dst: vk::Buffer, + offset: vk::DeviceSize, + stride: vk::DeviceSize, + flags: vk::QueryResultFlags, + ) { + self.op(Logged::CopyQueryPoolResults { + pool, + first, + count, + dst, + offset, + stride, + flags, + }); + } + + pub(super) unsafe fn cmd_push_constants( + &mut self, + layout: vk::PipelineLayout, + stages: vk::ShaderStageFlags, + offset: u32, + size: u32, + values: *const c_void, + ) { + // SAFETY: the caller's. + let bytes = unsafe { self.bytes.push(values.cast(), size) }; + self.op(Logged::PushConstants { + layout, + stages, + offset, + bytes, + }); + } + + pub(super) unsafe fn cmd_begin_render_pass( + &mut self, + begin: *const vk::RenderPassBeginInfo<'_>, + contents: vk::SubpassContents, + ) { + // SAFETY: the caller's. + let begin = unsafe { &*begin }; + if !begin.p_next.is_null() { + unchained("render pass begin"); + } + // SAFETY: the caller's. + let clears = unsafe { + self.clear_values + .push(begin.p_clear_values, begin.clear_value_count) + }; + self.op(Logged::BeginRenderPass { + render_pass: begin.render_pass, + framebuffer: begin.framebuffer, + area: begin.render_area, + clears, + contents, + }); + } + + pub(super) unsafe fn cmd_end_render_pass(&mut self) { + self.op(Logged::EndRenderPass); + } + + pub(super) unsafe fn cmd_execute_commands( + &mut self, + count: u32, + buffers: *const vk::CommandBuffer, + ) { + // SAFETY: the caller's. + let buffers = unsafe { self.command_buffers.push(buffers, count) }; + self.op(Logged::ExecuteCommands(buffers)); + } + + pub(super) unsafe fn cmd_set_cull_mode(&mut self, mode: vk::CullModeFlags) { + self.op(Logged::SetCullMode(mode)); + } + + pub(super) unsafe fn cmd_set_front_face(&mut self, face: vk::FrontFace) { + self.op(Logged::SetFrontFace(face)); + } + + pub(super) unsafe fn cmd_set_primitive_topology(&mut self, topology: vk::PrimitiveTopology) { + self.op(Logged::SetPrimitiveTopology(topology)); + } + + pub(super) unsafe fn cmd_bind_vertex_buffers2( + &mut self, + first: u32, + count: u32, + buffers: *const vk::Buffer, + offsets: *const vk::DeviceSize, + sizes: *const vk::DeviceSize, + strides: *const vk::DeviceSize, + ) { + // SAFETY: the caller's; a null array is none. + let op = unsafe { + Logged::BindVertexBuffers2 { + first, + buffers: self.buffers.push(buffers, count), + offsets: self.words.push(offsets, count), + sizes: (!sizes.is_null()).then(|| self.words.push(sizes, count)), + strides: (!strides.is_null()).then(|| self.words.push(strides, count)), + } + }; + self.op(op); + } + + pub(super) unsafe fn cmd_set_depth_test_enable(&mut self, enable: vk::Bool32) { + self.op(Logged::SetDepthTestEnable(enable)); + } + + pub(super) unsafe fn cmd_set_depth_write_enable(&mut self, enable: vk::Bool32) { + self.op(Logged::SetDepthWriteEnable(enable)); + } + + pub(super) unsafe fn cmd_set_depth_compare_op(&mut self, op: vk::CompareOp) { + self.op(Logged::SetDepthCompareOp(op)); + } + + pub(super) unsafe fn cmd_set_stencil_test_enable(&mut self, enable: vk::Bool32) { + self.op(Logged::SetStencilTestEnable(enable)); + } + + pub(super) unsafe fn cmd_set_stencil_op( + &mut self, + faces: vk::StencilFaceFlags, + fail: vk::StencilOp, + pass: vk::StencilOp, + depth_fail: vk::StencilOp, + compare: vk::CompareOp, + ) { + self.op(Logged::SetStencilOp(faces, fail, pass, depth_fail, compare)); + } + + pub(super) unsafe fn cmd_set_primitive_restart_enable(&mut self, enable: vk::Bool32) { + self.op(Logged::SetPrimitiveRestartEnable(enable)); + } + + pub(super) unsafe fn cmd_push_descriptor_set( + &mut self, + point: vk::PipelineBindPoint, + layout: vk::PipelineLayout, + set: u32, + count: u32, + writes: *const vk::WriteDescriptorSet<'_>, + ) { + let start = self.writes.0.len() as u32; + for at in 0..count as usize { + // SAFETY: the caller's: `count` writes, each with as many descriptors of its kind as + // it counts. + let write = unsafe { &*writes.add(at) }; + if !write.p_next.is_null() { + unchained("pushed write"); + } + let n = write.descriptor_count; + // SAFETY: as above; the arrays a kind does not read may be anything, so only the + // kind's own is read. + let (images, buffers, views) = unsafe { + match write.descriptor_type { + vk::DescriptorType::SAMPLER + | vk::DescriptorType::COMBINED_IMAGE_SAMPLER + | vk::DescriptorType::SAMPLED_IMAGE + | vk::DescriptorType::STORAGE_IMAGE + | vk::DescriptorType::INPUT_ATTACHMENT => ( + self.image_infos.push(write.p_image_info, n), + Span::default(), + Span::default(), + ), + vk::DescriptorType::UNIFORM_TEXEL_BUFFER + | vk::DescriptorType::STORAGE_TEXEL_BUFFER => ( + Span::default(), + Span::default(), + self.views.push(write.p_texel_buffer_view, n), + ), + vk::DescriptorType::UNIFORM_BUFFER + | vk::DescriptorType::STORAGE_BUFFER + | vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC + | vk::DescriptorType::STORAGE_BUFFER_DYNAMIC => ( + Span::default(), + self.buffer_infos.push(write.p_buffer_info, n), + Span::default(), + ), + _ => unchained("pushed write of another descriptor type"), + } + }; + self.writes.one(Write { + binding: write.dst_binding, + element: write.dst_array_element, + count: n, + kind: write.descriptor_type, + images, + buffers, + views, + }); + } + let writes = Span { start, len: count }; + self.op(Logged::PushDescriptorSet { + point, + layout, + set, + writes, + }); + } + + pub(super) unsafe fn cmd_set_color_write_mask( + &mut self, + first: u32, + count: u32, + masks: *const vk::ColorComponentFlags, + ) { + // SAFETY: the caller's. + let masks = unsafe { self.masks.push(masks, count) }; + self.op(Logged::SetColorWriteMask(first, masks)); + } + + pub(super) unsafe fn cmd_set_depth_bias2(&mut self, info: *const vk::DepthBiasInfoEXT<'_>) { + // SAFETY: the caller's. + let info = unsafe { &*info }; + let representation = match info.p_next.is_null() { + true => None, + false => { + // SAFETY: the caller's: a chained structure starts with its type. + let chained = + unsafe { &*info.p_next.cast::>() }; + if chained.s_type != vk::StructureType::DEPTH_BIAS_REPRESENTATION_INFO_EXT + || !chained.p_next.is_null() + { + unchained("depth bias"); + } + Some((chained.depth_bias_representation, chained.depth_bias_exact)) + } + }; + self.op(Logged::SetDepthBias2 { + factors: [ + info.depth_bias_constant_factor, + info.depth_bias_clamp, + info.depth_bias_slope_factor, + ], + representation, + }); + } + + pub(super) unsafe fn cmd_bind_index_buffer2( + &mut self, + buffer: vk::Buffer, + offset: vk::DeviceSize, + size: vk::DeviceSize, + index_type: vk::IndexType, + ) { + self.op(Logged::BindIndexBuffer2(buffer, offset, size, index_type)); + } + + pub(super) unsafe fn cmd_draw_mesh_tasks(&mut self, x: u32, y: u32, z: u32) { + self.op(Logged::DrawMeshTasks(x, y, z)); + } + + pub(super) unsafe fn cmd_draw_mesh_tasks_indirect( + &mut self, + buffer: vk::Buffer, + offset: vk::DeviceSize, + count: u32, + stride: u32, + ) { + self.op(Logged::DrawMeshTasksIndirect(buffer, offset, count, stride)); + } + + /// The info, copied, its chain checked empty. + /// + /// # Safety + /// + /// `info` points at a valid info. + unsafe fn generated_info(&mut self, info: *const GeneratedCommandsInfo) -> Span { + // SAFETY: the caller's. + let span = unsafe { self.generated.push(info, 1) }; + if self.generated.get(span).iter().any(|i| !i.p_next.is_null()) { + unchained("generated commands"); + } + span + } + + pub(super) unsafe fn cmd_execute_generated_commands( + &mut self, + preprocessed: vk::Bool32, + info: *const GeneratedCommandsInfo, + ) { + // SAFETY: the caller's. + let info = unsafe { self.generated_info(info) }; + self.op(Logged::ExecuteGeneratedCommands(preprocessed, info)); + } + + pub(super) unsafe fn cmd_preprocess_generated_commands( + &mut self, + info: *const GeneratedCommandsInfo, + state: vk::CommandBuffer, + ) { + // SAFETY: the caller's. + let info = unsafe { self.generated_info(info) }; + let state = (state != handles::handle(self.index)).then_some(state); + self.op(Logged::PreprocessGeneratedCommands(info, state)); + } +} + +/// What a replay names in place of each deferred command buffer it executes: its real one, once +/// replayed; `None` where it was not. +pub(super) type Resolve<'a> = &'a dyn Fn(vk::CommandBuffer) -> Option; + +impl Log { + /// The begin of its replay into `real`, of slot `slot`'s device, with its secondaries' real + /// command buffers from `resolve`, each command it calls counted in `counts` at its index + /// (`CommandsReplayed`). + /// + /// # Safety + /// + /// `real` is a command buffer of the slot's device in the initial or executable state, only + /// this call records it or any command buffer of its pool, and every object the log names is + /// live. + pub(super) unsafe fn replay( + &self, + slot: usize, + real_cb: vk::CommandBuffer, + begun: bool, + resolve: Resolve<'_>, + counts: &[AtomicU64; Command::COUNT], + ) -> Result<(), vk::Result> { + let inheritance = self.inheritance.map(|i| { + vk::CommandBufferInheritanceInfo::default() + .render_pass(i.render_pass) + .subpass(i.subpass) + .framebuffer(i.framebuffer) + .occlusion_query_enable(i.occlusion != vk::FALSE) + .query_flags(i.query_flags) + .pipeline_statistics(i.statistics) + }); + let mut begin = vk::CommandBufferBeginInfo::default().flags(self.flags); + if let Some(inheritance) = &inheritance { + begin = begin.inheritance_info(inheritance); + } + let cb = real_cb; + macro_rules! call { + ($command:ident, $pfn:ty, $($arg:expr),*) => {{ + // SAFETY: the slot's device's command of this name, of this signature + // (`thunks::real`); the arguments are the logged call's, their arrays in the + // log's arenas. + let f: $pfn = unsafe { real(slot, Command::$command) }; + exit_guard::called(Call::$command); + counts[Command::$command as usize].fetch_add(1, Ordering::Relaxed); + unsafe { f(cb, $($arg),*) } + }}; + } + if !begun { + let began = call!(BeginCommandBuffer, vk::PFN_vkBeginCommandBuffer, &begin); + if began != vk::Result::SUCCESS { + return Err(began); + } + } + let recorded = SCRATCH.with_borrow_mut(|scratch| -> Result<(), vk::Result> { + for op in &self.ops { + match *op { + Logged::BindPipeline(point, pipeline) => { + call!(CmdBindPipeline, vk::PFN_vkCmdBindPipeline, point, pipeline) + } + Logged::SetViewport(first, span) => call!( + CmdSetViewport, + vk::PFN_vkCmdSetViewport, + first, + span.len, + self.viewports.get_ptr(span) + ), + Logged::SetScissor(first, span) => call!( + CmdSetScissor, + vk::PFN_vkCmdSetScissor, + first, + span.len, + self.rects.get_ptr(span) + ), + Logged::SetDepthBias(a, b, c) => { + call!(CmdSetDepthBias, vk::PFN_vkCmdSetDepthBias, a, b, c) + } + Logged::SetBlendConstants(constants) => call!( + CmdSetBlendConstants, + vk::PFN_vkCmdSetBlendConstants, + &constants + ), + Logged::SetStencilCompareMask(faces, mask) => call!( + CmdSetStencilCompareMask, + vk::PFN_vkCmdSetStencilCompareMask, + faces, + mask + ), + Logged::SetStencilWriteMask(faces, mask) => call!( + CmdSetStencilWriteMask, + vk::PFN_vkCmdSetStencilWriteMask, + faces, + mask + ), + Logged::SetStencilReference(faces, reference) => call!( + CmdSetStencilReference, + vk::PFN_vkCmdSetStencilReference, + faces, + reference + ), + Logged::BindDescriptorSets { + point, + layout, + first, + sets, + offsets, + } => call!( + CmdBindDescriptorSets, + vk::PFN_vkCmdBindDescriptorSets, + point, + layout, + first, + sets.len, + self.sets.get_ptr(sets), + offsets.len, + self.u32s.get_ptr(offsets) + ), + Logged::BindIndexBuffer(buffer, offset, index_type) => call!( + CmdBindIndexBuffer, + vk::PFN_vkCmdBindIndexBuffer, + buffer, + offset, + index_type + ), + Logged::BindVertexBuffers { + first, + buffers, + offsets, + } => call!( + CmdBindVertexBuffers, + vk::PFN_vkCmdBindVertexBuffers, + first, + buffers.len, + self.buffers.get_ptr(buffers), + self.words.get_ptr(offsets) + ), + Logged::Draw(a, b, c, d) => call!(CmdDraw, vk::PFN_vkCmdDraw, a, b, c, d), + Logged::DrawIndexed(a, b, c, d, e) => { + call!(CmdDrawIndexed, vk::PFN_vkCmdDrawIndexed, a, b, c, d, e) + } + Logged::DrawIndirect(buffer, offset, count, stride) => call!( + CmdDrawIndirect, + vk::PFN_vkCmdDrawIndirect, + buffer, + offset, + count, + stride + ), + Logged::DrawIndexedIndirect(buffer, offset, count, stride) => call!( + CmdDrawIndexedIndirect, + vk::PFN_vkCmdDrawIndexedIndirect, + buffer, + offset, + count, + stride + ), + Logged::Dispatch(x, y, z) => call!(CmdDispatch, vk::PFN_vkCmdDispatch, x, y, z), + Logged::DispatchIndirect(buffer, offset) => call!( + CmdDispatchIndirect, + vk::PFN_vkCmdDispatchIndirect, + buffer, + offset + ), + Logged::CopyBuffer(src, dst, regions) => call!( + CmdCopyBuffer, + vk::PFN_vkCmdCopyBuffer, + src, + dst, + regions.len, + self.buffer_copies.get_ptr(regions) + ), + Logged::CopyImage { + src, + src_layout, + dst, + dst_layout, + regions, + } => call!( + CmdCopyImage, + vk::PFN_vkCmdCopyImage, + src, + src_layout, + dst, + dst_layout, + regions.len, + self.image_copies.get_ptr(regions) + ), + Logged::BlitImage { + src, + src_layout, + dst, + dst_layout, + regions, + filter, + } => call!( + CmdBlitImage, + vk::PFN_vkCmdBlitImage, + src, + src_layout, + dst, + dst_layout, + regions.len, + self.blits.get_ptr(regions), + filter + ), + Logged::CopyBufferToImage { + src, + dst, + layout, + regions, + } => call!( + CmdCopyBufferToImage, + vk::PFN_vkCmdCopyBufferToImage, + src, + dst, + layout, + regions.len, + self.buffer_images.get_ptr(regions) + ), + Logged::CopyImageToBuffer { + src, + layout, + dst, + regions, + } => call!( + CmdCopyImageToBuffer, + vk::PFN_vkCmdCopyImageToBuffer, + src, + layout, + dst, + regions.len, + self.buffer_images.get_ptr(regions) + ), + Logged::UpdateBuffer(dst, offset, bytes) => call!( + CmdUpdateBuffer, + vk::PFN_vkCmdUpdateBuffer, + dst, + offset, + u64::from(bytes.len), + self.bytes.get_ptr(bytes).cast() + ), + Logged::FillBuffer(dst, offset, size, data) => call!( + CmdFillBuffer, + vk::PFN_vkCmdFillBuffer, + dst, + offset, + size, + data + ), + Logged::ClearColorImage(image, layout, color, ranges) => call!( + CmdClearColorImage, + vk::PFN_vkCmdClearColorImage, + image, + layout, + &color, + ranges.len, + self.ranges.get_ptr(ranges) + ), + Logged::ClearDepthStencilImage(image, layout, value, ranges) => call!( + CmdClearDepthStencilImage, + vk::PFN_vkCmdClearDepthStencilImage, + image, + layout, + &value, + ranges.len, + self.ranges.get_ptr(ranges) + ), + Logged::ClearAttachments(attachments, rects) => call!( + CmdClearAttachments, + vk::PFN_vkCmdClearAttachments, + attachments.len, + self.clear_attachments.get_ptr(attachments), + rects.len, + self.clear_rects.get_ptr(rects) + ), + Logged::PipelineBarrier { + src, + dst, + flags, + memory, + buffers, + images, + } => call!( + CmdPipelineBarrier, + vk::PFN_vkCmdPipelineBarrier, + src, + dst, + flags, + memory.len, + self.memory_barriers.get_ptr(memory), + buffers.len, + self.buffer_barriers.get_ptr(buffers), + images.len, + self.image_barriers.get_ptr(images) + ), + Logged::BeginQuery(pool, query, flags) => { + call!(CmdBeginQuery, vk::PFN_vkCmdBeginQuery, pool, query, flags) + } + Logged::EndQuery(pool, query) => { + call!(CmdEndQuery, vk::PFN_vkCmdEndQuery, pool, query) + } + Logged::ResetQueryPool(pool, first, count) => call!( + CmdResetQueryPool, + vk::PFN_vkCmdResetQueryPool, + pool, + first, + count + ), + Logged::WriteTimestamp(stage, pool, query) => call!( + CmdWriteTimestamp, + vk::PFN_vkCmdWriteTimestamp, + stage, + pool, + query + ), + Logged::CopyQueryPoolResults { + pool, + first, + count, + dst, + offset, + stride, + flags, + } => call!( + CmdCopyQueryPoolResults, + vk::PFN_vkCmdCopyQueryPoolResults, + pool, + first, + count, + dst, + offset, + stride, + flags + ), + Logged::PushConstants { + layout, + stages, + offset, + bytes, + } => call!( + CmdPushConstants, + vk::PFN_vkCmdPushConstants, + layout, + stages, + offset, + bytes.len, + self.bytes.get_ptr(bytes).cast() + ), + Logged::BeginRenderPass { + render_pass, + framebuffer, + area, + clears, + contents, + } => { + let begin = vk::RenderPassBeginInfo { + render_pass, + framebuffer, + render_area: area, + clear_value_count: clears.len, + p_clear_values: self.clear_values.get_ptr(clears), + ..Default::default() + }; + call!( + CmdBeginRenderPass, + vk::PFN_vkCmdBeginRenderPass, + &begin, + contents + ) + } + Logged::EndRenderPass => call!(CmdEndRenderPass, vk::PFN_vkCmdEndRenderPass,), + Logged::ExecuteCommands(buffers) => { + let resolved = &mut scratch.secondaries; + resolved.clear(); + for &secondary in self.command_buffers.get(buffers) { + resolved.push(resolve(secondary).ok_or(vk::Result::ERROR_UNKNOWN)?); + } + call!( + CmdExecuteCommands, + vk::PFN_vkCmdExecuteCommands, + resolved.len() as u32, + resolved.as_ptr() + ) + } + Logged::SetCullMode(mode) => { + call!(CmdSetCullMode, vk::PFN_vkCmdSetCullMode, mode) + } + Logged::SetFrontFace(face) => { + call!(CmdSetFrontFace, vk::PFN_vkCmdSetFrontFace, face) + } + Logged::SetPrimitiveTopology(topology) => call!( + CmdSetPrimitiveTopology, + vk::PFN_vkCmdSetPrimitiveTopology, + topology + ), + Logged::BindVertexBuffers2 { + first, + buffers, + offsets, + sizes, + strides, + } => call!( + CmdBindVertexBuffers2, + vk::PFN_vkCmdBindVertexBuffers2, + first, + buffers.len, + self.buffers.get_ptr(buffers), + self.words.get_ptr(offsets), + sizes.map_or(std::ptr::null(), |s| self.words.get_ptr(s)), + strides.map_or(std::ptr::null(), |s| self.words.get_ptr(s)) + ), + Logged::SetDepthTestEnable(enable) => call!( + CmdSetDepthTestEnable, + vk::PFN_vkCmdSetDepthTestEnable, + enable + ), + Logged::SetDepthWriteEnable(enable) => call!( + CmdSetDepthWriteEnable, + vk::PFN_vkCmdSetDepthWriteEnable, + enable + ), + Logged::SetDepthCompareOp(op) => { + call!(CmdSetDepthCompareOp, vk::PFN_vkCmdSetDepthCompareOp, op) + } + Logged::SetStencilTestEnable(enable) => call!( + CmdSetStencilTestEnable, + vk::PFN_vkCmdSetStencilTestEnable, + enable + ), + Logged::SetStencilOp(faces, fail, pass, depth_fail, compare) => call!( + CmdSetStencilOp, + vk::PFN_vkCmdSetStencilOp, + faces, + fail, + pass, + depth_fail, + compare + ), + Logged::SetPrimitiveRestartEnable(enable) => call!( + CmdSetPrimitiveRestartEnable, + vk::PFN_vkCmdSetPrimitiveRestartEnable, + enable + ), + Logged::PushDescriptorSet { + point, + layout, + set, + writes, + } => { + let built = &mut scratch.writes; + built.clear(); + built.extend(self.writes.get(writes).iter().map(|w| { + vk::WriteDescriptorSet { + dst_binding: w.binding, + dst_array_element: w.element, + descriptor_count: w.count, + descriptor_type: w.kind, + p_image_info: self.image_infos.get_ptr(w.images), + p_buffer_info: self.buffer_infos.get_ptr(w.buffers), + p_texel_buffer_view: self.views.get_ptr(w.views), + ..Default::default() + } + })); + call!( + CmdPushDescriptorSet, + vk::PFN_vkCmdPushDescriptorSetKHR, + point, + layout, + set, + built.len() as u32, + built.as_ptr() + ); + // No pointer into the log outlives its call. + built.clear(); + } + Logged::SetColorWriteMask(first, masks) => call!( + CmdSetColorWriteMask, + vk::PFN_vkCmdSetColorWriteMaskEXT, + first, + masks.len, + self.masks.get_ptr(masks) + ), + Logged::SetDepthBias2 { + factors, + representation, + } => { + let mut chained = representation.map(|(representation, exact)| { + vk::DepthBiasRepresentationInfoEXT::default() + .depth_bias_representation(representation) + .depth_bias_exact(exact != vk::FALSE) + }); + let mut info = vk::DepthBiasInfoEXT::default() + .depth_bias_constant_factor(factors[0]) + .depth_bias_clamp(factors[1]) + .depth_bias_slope_factor(factors[2]); + if let Some(chained) = &mut chained { + info = info.push_next(chained); + } + call!(CmdSetDepthBias2, vk::PFN_vkCmdSetDepthBias2EXT, &info) + } + Logged::BindIndexBuffer2(buffer, offset, size, index_type) => call!( + CmdBindIndexBuffer2, + vk::PFN_vkCmdBindIndexBuffer2KHR, + buffer, + offset, + size, + index_type + ), + Logged::DrawMeshTasks(x, y, z) => { + call!(CmdDrawMeshTasks, vk::PFN_vkCmdDrawMeshTasksEXT, x, y, z) + } + Logged::DrawMeshTasksIndirect(buffer, offset, count, stride) => call!( + CmdDrawMeshTasksIndirect, + vk::PFN_vkCmdDrawMeshTasksIndirectEXT, + buffer, + offset, + count, + stride + ), + Logged::ExecuteGeneratedCommands(preprocessed, info) => call!( + CmdExecuteGeneratedCommands, + unsafe extern "system" fn( + vk::CommandBuffer, + vk::Bool32, + *const GeneratedCommandsInfo, + ), + preprocessed, + self.generated.get_ptr(info) + ), + Logged::PreprocessGeneratedCommands(info, state) => { + let state = match state { + None => cb, + Some(other) => resolve(other).unwrap_or(other), + }; + call!( + CmdPreprocessGeneratedCommands, + unsafe extern "system" fn( + vk::CommandBuffer, + *const GeneratedCommandsInfo, + vk::CommandBuffer, + ), + self.generated.get_ptr(info), + state + ) + } + } + } + Ok(()) + }); + recorded?; + let ended = call!(EndCommandBuffer, vk::PFN_vkEndCommandBuffer,); + match ended { + vk::Result::SUCCESS => Ok(()), + error => Err(error), + } + } +} diff --git a/crates/metal2vulkan-runtime/src/recorder/mod.rs b/crates/metal2vulkan-runtime/src/recorder/mod.rs index 2531cc586..495eafe7d 100644 --- a/crates/metal2vulkan-runtime/src/recorder/mod.rs +++ b/crates/metal2vulkan-runtime/src/recorder/mod.rs @@ -1,6 +1,320 @@ +//! Vulkan command recording off the program's encoding thread: the encoders record into deferred +//! command buffers, whose commands a log keeps, and the device's recorder thread replays each log +//! into a `VkCommandBuffer` once its command buffer committed, before its submission. +//! +//! - **One door.** The device's functions hold this module's entry point in place of the driver's +//! for each command a `VkCommandBuffer` takes ([`Command`]), its begin and its end among them. A +//! device the runtime makes or adopts takes one of [`SLOTS`] slots ([`route`]): its functions +//! (`device/functions.rs`, the exit guard's table among them) and the extension commands it loads +//! ([`Slot::route`]) hold the slot's entry points. Each is generic over its slot, so it finds its +//! device's command with one load, without a lock or a lookup by handle; a slot is let go of +//! with its device, after `vkDestroyDevice`. A source test fails when a file outside this module +//! names a command that is not routed. +//! - **Deferred command buffers.** An encoder's command buffers (`CommandBuffer::allocate_raw` +//! and `allocate_secondary`) are handles of this module's (`handles.rs`), never a driver's: an +//! entry point called with one logs the command, its arguments copied at the call (`log.rs`), and +//! calls the driver's with any other. So everything Metal makes observable at encode time stays +//! at the call, on the program's thread: the checks, refusals and their errors, the copies of +//! inline bytes and of the commands' arguments, descriptor writes, object and pipeline making, +//! retention, notices, the tracker's uses. Only the driver's recording moves, and Metal reads +//! buffer contents as the GPU runs the commands, not as they are encoded, so what the commands +//! do is the same. A device without a slot, or once every handle is live, records into the +//! driver's command buffers as they are encoded. +//! - **Replayed once committed** (`replays.rs`). A command buffer's ended logs replay, in the order +//! they ended (a secondary before the primary that executes it, Vulkan's executable state), into +//! command buffers of a pool of its own (a spare, `spares.rs`), never shared with the scheduler's +//! barrier command buffers: on the recorder thread, which its commit wakes, or on the thread +//! that submits it where the recorder has not yet reached it, which then replays it itself +//! ([`resolve`]), so a submission never waits for a wake. A log of a command buffer never +//! committed is never replayed, nor one never ended: a render pass instance's secondary that +//! nothing will execute is left unended (`CommandBuffer::give_up_raw`). +//! - **What the logs name lives through the replay.** Every object a command names stays live +//! until its command buffer completes, but for the host pages a command buffer holds only weakly +//! from its commit to its first submission (`rebind.rs`): its commit hands their holds to its +//! replays, which let go of them once every ended log replayed. A release, rebind or detach of +//! pages the replays hold replays first, on its own thread, what the recorder has yet to //! ([`RecorderShared::settle_all`]), and a commit whose pages' buffer let go of them (released //! or detached while an encoder took them, on any thread) replays its command buffer itself, //! so the pages' deallocator runs in the call it runs in without a recorder. Each marks its //! side, then reads the other's, so a let-go and a commit that race agree on which replays //! (`HostPages::let_go_by_buffer`). Its release (completion, failure, drop) lets go of the //! rest, after any replay in progress, replaying nothing more. +//! - **Counted by kind.** Each command a replay calls counts once for its kind, one relaxed +//! increment into a fixed array of the device's indexed by the command +//! (`WorkCounts::commands_replayed`). +//! - **A replay's failure** (`vkBeginCommandBuffer` or `vkEndCommandBuffer` out of memory) fails +//! the submission of what it replayed, as a recording error. +//! - **In sections.** The recorder thread is one of the runtime's: each replay runs inside a +//! section of the exit guard, and every entry point it calls is the guard's table's, marked as +//! called as it is ([`exit_guard::called`]), so the first replay of a command the device's +//! priming could not make registers the exit hook again. + +mod handles; +mod log; +mod replays; +mod thunks; + +use crate::device::functions::Functions; +use crate::exit_guard; +use crate::loader_word::LoaderWord; +use ash::vk; +use std::ffi::{c_void, CStr}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +pub(crate) use handles::is_deferred; +#[cfg(test)] +pub(crate) use replays::{queue_room, take_leaving_room}; +pub(crate) use replays::{resolve, RecorderShared, ReplayCounts, Replays}; +pub(crate) use thunks::Command; +pub use thunks::CommandsReplayed; + +/// How many devices route their commands here at once; one made past them keeps its driver's. +pub(crate) const SLOTS: usize = 8; + +/// The slots taken. +static TAKEN: [AtomicBool; SLOTS] = [const { AtomicBool::new(false) }; SLOTS]; + +/// Run `$body` with `$s` the const slot index `$index` names. +macro_rules! per_slot { + ($index:expr, $s:ident => $body:expr) => { + match $index { + 0 => { + const $s: usize = 0; + $body + } + 1 => { + const $s: usize = 1; + $body + } + 2 => { + const $s: usize = 2; + $body + } + 3 => { + const $s: usize = 3; + $body + } + 4 => { + const $s: usize = 4; + $body + } + 5 => { + const $s: usize = 5; + $body + } + 6 => { + const $s: usize = 6; + $body + } + _ => { + const $s: usize = 7; + $body + } + } + }; +} + +/// One device's slot (the module docs): its commands, until it is dropped, after the device is +/// destroyed. +pub(crate) struct Slot { + index: usize, +} + +impl Slot { + /// `real`, the device's command `command` as its driver gave it, routed through the slot: + /// the slot's entry point, which calls `real`. + /// + /// # Safety + /// + /// `real` is a function pointer of `command`'s signature, the slot's device's, and not one + /// of the slot's entry points (a function's address is no identity to compare against, so + /// the caller knows which it holds: a command of the device's routed functions is routed). + pub(crate) unsafe fn route(&self, command: Command, real: F) -> F { + assert_eq!( + std::mem::size_of::(), + std::mem::size_of::<*const c_void>() + ); + // SAFETY: `F` is a function pointer (the caller's), of a pointer's size. + let pointer = unsafe { std::mem::transmute_copy::(&real) }; + thunks::store(self.index, command, pointer); + let thunk = per_slot!(self.index, S => thunks::thunk::(command)); + // SAFETY: the entry point has `command`'s signature, `F`'s (the caller's). + unsafe { std::mem::transmute_copy::<*const c_void, F>(&thunk) } + } + + /// The slot's entry point in place of the driver's `name`, if it routes that command: the exit + /// guard's table (`device/functions.rs`) holds it too. + pub(crate) fn entry(&self, name: &CStr) -> Option<*const c_void> { + let command = Command::ALL.iter().find(|command| command.name() == name)?; + Some(per_slot!(self.index, S => thunks::thunk::(*command))) + } +} + +/// A device's recorder thread and what its replays share (the module docs). +pub(crate) struct Recorder { + shared: Arc, + thread: Option>, +} + +impl Recorder { + /// Start the recorder of the device of `slot`, whose functions are `functions` and loader + /// word `loader_word`; `None` where the host starts no thread (the device records as its + /// encoders encode). The thread holds the functions, which it ends before the device's + /// teardown goes on (its drop joins it); its replays borrow them. + pub(crate) fn start( + slot: &Slot, + functions: &Functions, + loader_word: LoaderWord, + ) -> Option { + let shared = RecorderShared::new(slot.index, loader_word); + let running = Arc::clone(&shared); + let functions = functions.clone(); + let builder = std::thread::Builder::new().name("metal2vulkan-recorder".to_owned()); + let thread = + exit_guard::spawn_user_interactive(builder, move || running.run(&functions)).ok()?; + Some(Recorder { + shared, + thread: Some(thread), + }) + } + + /// What its replays share. + pub(crate) fn shared(&self) -> &Arc { + &self.shared + } +} + +impl Drop for Recorder { + fn drop(&mut self) { + self.shared.stop(); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +impl Drop for Slot { + fn drop(&mut self) { + thunks::clear(self.index); + TAKEN[self.index].store(false, Ordering::Release); + } +} + +/// `device`'s functions with the entry points of a slot of its own in place of its driver's +/// commands, and the slot; the functions as they are, and no slot, where every slot is taken. +/// +/// # Safety +/// +/// `device` is live, and its functions are its driver's (or its topmost layer's, or routed for +/// its pipeline makings, `compiles.rs`), not already routed here. +pub(crate) unsafe fn route(device: ash::Device) -> (ash::Device, Option) { + let Some(index) = TAKEN.iter().position(|taken| { + taken + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed) + .is_ok() + }) else { + return (device, None); + }; + let slot = Slot { index }; + let mut v1_0 = device.fp_v1_0().clone(); + let mut v1_3 = device.fp_v1_3().clone(); + per_slot!(index, S => thunks::route_tables::(&mut v1_0, &mut v1_3)); + let routed = ash::Device::from_parts_1_3( + device.handle(), + v1_0, + device.fp_v1_1().clone(), + device.fp_v1_2().clone(), + v1_3, + ); + (routed, Some(slot)) +} + +/// `real`, a device's command `command`, through `slot` where the device has one +/// ([`Slot::route`]), else as it is. +/// +/// # Safety +/// +/// As [`Slot::route`]. +pub(crate) unsafe fn through(slot: Option<&Slot>, command: Command, real: F) -> F { + match slot { + // SAFETY: the caller's. + Some(slot) => unsafe { slot.route(command, real) }, + None => real, + } +} + +/// Room in `raw`'s log, where it is a deferred command buffer, for the end a commit may fold into +/// it as its command buffer's tail (`CommandBufferShared::close_tail`): a barrier of one memory +/// barrier, then a timestamp. A log made while no spare one was kept (its earlier replays' +/// completions still to come) has no room in its lists until it takes it here, on the encoding +/// thread as its encoder ends, so the commit's logging grows no list whenever completions come. +/// +/// # Safety +/// +/// The caller records `raw` alone, and `raw` is recording. +pub(crate) unsafe fn reserve_end(raw: vk::CommandBuffer) { + // SAFETY: the caller's. + unsafe { handles::record(raw, |log| log.reserve_end()) }; +} + +/// The extension commands of `VK_EXT_mesh_shader` a draw records, routed (`render.rs`). +#[derive(Clone, Copy)] +pub(crate) struct MeshDraws { + draw: vk::PFN_vkCmdDrawMeshTasksEXT, + indirect: vk::PFN_vkCmdDrawMeshTasksIndirectEXT, +} + +impl MeshDraws { + /// The commands of `loaded`, through `slot` where the device has one. + pub(crate) fn new(loaded: &ash::ext::mesh_shader::Device, slot: Option<&Slot>) -> MeshDraws { + let functions = loaded.fp(); + let (draw, indirect) = ( + functions.cmd_draw_mesh_tasks_ext, + functions.cmd_draw_mesh_tasks_indirect_ext, + ); + match slot { + // SAFETY: each is the device's command of that name. + Some(slot) => unsafe { + MeshDraws { + draw: slot.route(Command::CmdDrawMeshTasks, draw), + indirect: slot.route(Command::CmdDrawMeshTasksIndirect, indirect), + } + }, + None => MeshDraws { draw, indirect }, + } + } + + /// `vkCmdDrawMeshTasksEXT`. + /// + /// # Safety + /// + /// As the command's. + pub(crate) unsafe fn cmd_draw_mesh_tasks( + &self, + command_buffer: vk::CommandBuffer, + group_count_x: u32, + group_count_y: u32, + group_count_z: u32, + ) { + // SAFETY: the caller's. + unsafe { (self.draw)(command_buffer, group_count_x, group_count_y, group_count_z) } + } + + /// `vkCmdDrawMeshTasksIndirectEXT`. + /// + /// # Safety + /// + /// As the command's. + pub(crate) unsafe fn cmd_draw_mesh_tasks_indirect( + &self, + command_buffer: vk::CommandBuffer, + buffer: vk::Buffer, + offset: vk::DeviceSize, + draw_count: u32, + stride: u32, + ) { + // SAFETY: the caller's. + unsafe { (self.indirect)(command_buffer, buffer, offset, draw_count, stride) } + } +} diff --git a/crates/metal2vulkan-runtime/src/recorder/replays.rs b/crates/metal2vulkan-runtime/src/recorder/replays.rs index 9e87e47e1..196077943 100644 --- a/crates/metal2vulkan-runtime/src/recorder/replays.rs +++ b/crates/metal2vulkan-runtime/src/recorder/replays.rs @@ -1,16 +1,322 @@ +//! A command buffer's deferred command buffers and their replay, and the device's recorder thread +//! (`recorder`). + +use super::handles; +use super::log::Log; +use super::thunks::{Command, CommandsReplayed}; +use crate::buffer::{HeldByReplay, HostPages}; +use crate::command_buffer::Item; +use crate::contexts::Contexts; +use crate::device::functions::{Functions, Vk}; +use crate::device::lock; +use crate::exit_guard::{self, Call}; +use crate::loader_word::LoaderWord; +use crate::spares::CommandPool; +use ash::vk::{self, Handle}; +use std::collections::VecDeque; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; + +/// What a device's replays share: its slot's commands, its loader word for the command buffers +/// they make, and the recorder thread's queue. The device's functions are each replay's caller's +/// to lend. +pub(crate) struct RecorderShared { + slot: usize, + loader_word: LoaderWord, + queue: Mutex, + wake: Condvar, + /// Where pages the replays held last go (`Device::elsewhere`), set once the device is. + elsewhere: OnceLock<(Contexts, u64)>, + /// Replays let go of, emptied, their room kept: a command buffer takes one with no + /// allocation. Emptied as the recorder stops (each holds this). + kept: Mutex>>, /// Held through each [`settle_all`](Self::settle_all), so one finds the replays another /// took off the queue replayed. settling: Mutex<()>, + /// Command buffers replayed by the recorder's thread, and by a thread that submits. + pub(super) by_recorder: AtomicU64, + pub(super) by_submitter: AtomicU64, + /// Command pools the replays made, where their command buffer took no spare. + pools_made: AtomicU64, + /// Replays that recorded into their pool's primary begun ahead (`spares.rs`). + begun_ahead_taken: AtomicU64, + /// The commands the replays called, one count per command at its index + /// ([`CommandsReplayed`]). + commands: [AtomicU64; Command::COUNT], +} + +/// What a device's replays did so far: the command buffers replayed by the recorder's thread and +/// by threads that submit, the command pools they made, those replays that recorded into their +/// pool's primary begun ahead, and the commands they called, by kind. +#[derive(Clone, Copy, Default)] +pub(crate) struct ReplayCounts { + pub(crate) by_recorder: u64, + pub(crate) by_submitter: u64, + pub(crate) pools_made: u64, + pub(crate) begun_ahead_taken: u64, + pub(crate) commands: CommandsReplayed, +} + +/// The replays the recorder's queue holds from its making without growing: more than a frame +/// commits, as the scheduler's inbox holds (`scheduler::inbox::ROOM`). +const QUEUE_ROOM: usize = crate::scheduler::inbox::ROOM; + +/// The recorder thread's queue. +#[derive(Default)] +struct Queue { + /// Committed command buffers' replays, in commit order. It starts with room for + /// [`QUEUE_ROOM`], keeps its room, and the recorder's thread grows it ahead of the commits + /// ([`take_leaving_room`]). + replays: VecDeque>, + /// The replays the thread replays now, taken off `replays`. + current: Option>, + /// The thread waits for a replay. + parked: bool, + stop: bool, +} + +impl Queue { + /// An empty queue, with room for [`QUEUE_ROOM`] replays. + fn new() -> Queue { + Queue { + replays: VecDeque::with_capacity(QUEUE_ROOM), + ..Queue::default() + } + } +} + +/// How many replays a new recorder's queue holds without growing. +#[cfg(test)] +pub(crate) fn queue_room() -> usize { + Queue::new().replays.capacity() +} + +/// The most replays [`RecorderShared`] keeps for reuse. +const KEPT_REPLAYS: usize = 1024; + +/// The first of `queue`, taken off, and `queue` left room for twice as many as waited, made on +/// the thread that takes: the recorder's, for its queue, so a commit's push +/// ([`RecorderShared::enqueue`]) grows the queue, an allocation on the committing thread, only +/// where more wait than [`QUEUE_ROOM`] and twice as many as the recorder's thread ever found, as +/// the scheduler's inbox leaves its commits room (`scheduler/inbox.rs`). +pub(crate) fn take_leaving_room(queue: &mut VecDeque) -> Option { + let waited = queue.len(); + let first = queue.pop_front()?; + queue.reserve(waited + 1); + Some(first) +} + +/// One command buffer's deferred command buffers (the module docs of `recorder`). +pub(crate) struct Replays { + state: Mutex, + recorder: Arc, +} + +struct ReplayState { + /// The queue family its command buffer runs on: its pool's. + family: u32, + /// Every handle made for it, let go of in its release. + handles: Vec, + /// Those ended and not yet replayed, in the order they ended. It has room for every handle + /// made ([`Replays::make`]), so an end, the commit's included, never grows it. + ended: VecDeque, + /// Its command buffer committed: its ended command buffers may be replayed. + open: bool, + /// It waits in the recorder thread's queue. + queued: bool, + /// The pool its replays allocate from: a spare its command buffer took, or one made at the + /// first replay. + pool: Option, + /// The command buffers of the pool that replays ended. + ended_real: u64, + /// A replay's failure (`vkBeginCommandBuffer` or `vkEndCommandBuffer`): the submission of + /// what it replayed fails with it. + failure: Option, + /// The host pages what ended names, which its command buffer held only weakly from its + /// commit (`rebind.rs`): held here until nothing ended waits for its replay. + held: Vec>, +} + +impl RecorderShared { + /// A device's, through slot `slot`, with its `loader_word`. + pub(crate) fn new(slot: usize, loader_word: LoaderWord) -> Arc { + Arc::new(RecorderShared { + slot, + loader_word, + queue: Mutex::new(Queue::new()), + wake: Condvar::new(), + elsewhere: OnceLock::new(), + kept: Mutex::default(), settling: Mutex::default(), + by_recorder: AtomicU64::new(0), + by_submitter: AtomicU64::new(0), + pools_made: AtomicU64::new(0), + begun_ahead_taken: AtomicU64::new(0), + commands: [const { AtomicU64::new(0) }; Command::COUNT], + }) + } + + /// Where the pages the replays held last go from now on: `elsewhere`, the device's + /// (`Device::elsewhere`). + pub(crate) fn set_elsewhere(&self, elsewhere: (Contexts, u64)) { + let _ = self.elsewhere.set(elsewhere); + } + + /// Hand `replays` to the recorder thread, waking it where it waits. + fn enqueue(&self, replays: Arc) { + let mut queue = lock(&self.queue); + queue.replays.push_back(replays); + if queue.parked { + self.wake.notify_one(); + } + } + + /// The recorder thread's loop: each queued command buffer's ended deferred command buffers + /// replayed, inside a section, with the device's `functions`, until [`stop`](Self::stop). + pub(crate) fn run(&self, functions: &Functions) { + loop { + let replays = { + let mut queue = lock(&self.queue); + loop { + if let Some(replays) = take_leaving_room(&mut queue.replays) { + queue.current = Some(Arc::clone(&replays)); + break replays; + } + if queue.stop { + return; + } + queue.parked = true; + queue = self + .wake + .wait(queue) + .unwrap_or_else(std::sync::PoisonError::into_inner); + queue.parked = false; + } + }; + // Once the process exits, nothing is replayed here: a submission replays what it + // submits itself, in its own section, or fails. + if let Some(_busy) = exit_guard::enter() { let replayed = replays.drain(functions.get(), true); + self.by_recorder.fetch_add(replayed, Ordering::Relaxed); + } + lock(&self.queue).current = None; + // Released while it waited here (a submission replayed it first), it is kept now. + replays.keep(); + } + } + + /// Replay, on this thread, with `device`, the device's functions, everything ended in a + /// committed command buffer the recorder's thread has yet to replay, waiting for the replay /// it is in, and for another thread's settle: what the release, rebind or detach of host /// pages that replays hold does first, so the replays let go of them before it /// (`HostPages::let_go_by_buffer`). Once the process exits, what ended is dropped /// unreplayed instead ([`Replays::replay_ended`]). pub(crate) fn settle_all(&self, device: &Vk) { let _settling = lock(&self.settling); + let (queued, current) = { + let mut queue = lock(&self.queue); + let queued: Vec<_> = queue.replays.drain(..).collect(); + (queued, queue.current.clone()) + }; + let mut replayed = 0; + for replays in queued { replayed += replays.drain(device, true); + } + // The thread's replay ended once this takes its lock: what it left, nothing as a rule. + if let Some(replays) = current { replayed += replays.drain(device, false); + } + self.by_submitter.fetch_add(replayed, Ordering::Relaxed); + } + + /// End the thread's loop once its queue is empty, and let go of the replays kept. + pub(crate) fn stop(&self) { + lock(&self.queue).stop = true; + self.wake.notify_one(); + lock(&self.kept).clear(); + } + + /// A command buffer's replays, on queue family `family`, allocating from `pool` (a spare it + /// took) or a pool the first replay makes: a kept one where there is one. + pub(crate) fn replays( + self: &Arc, + family: u32, + pool: Option, + ) -> Arc { + let kept = lock(&self.kept).pop(); + let Some(replays) = kept else { + return Arc::new(Replays { + state: Mutex::new(ReplayState { + family, + handles: Vec::new(), + ended: VecDeque::new(), + open: false, + queued: false, + pool, + ended_real: 0, + failure: None, + held: Vec::new(), + }), + recorder: Arc::clone(self), + }); + }; + { + let mut state = lock(&replays.state); + state.family = family; + state.pool = pool; + } + replays + } + + /// What the replays did so far ([`ReplayCounts`]). + pub(crate) fn counts(&self) -> ReplayCounts { + ReplayCounts { + by_recorder: self.by_recorder.load(Ordering::Relaxed), + by_submitter: self.by_submitter.load(Ordering::Relaxed), + pools_made: self.pools_made.load(Ordering::Relaxed), + begun_ahead_taken: self.begun_ahead_taken.load(Ordering::Relaxed), + commands: CommandsReplayed::read(&self.commands), + } + } +} + +impl Replays { + /// A new deferred command buffer of `level`; `None` where every handle is live. `ended` is + /// given room for it here, as `handles` is: each handle ends once, so its end, which may be + /// the commit's (`CommandBufferShared::close_tail`), allocates nothing. A kept replays' room + /// stays from its last command buffer, so this grows nothing that one did not need. + pub(crate) fn make( + self: &Arc, + level: vk::CommandBufferLevel, + ) -> Option { + let index = handles::make(level, self)?; + let mut state = lock(&self.state); + state.handles.push(index); + let unended = state.handles.len().saturating_sub(state.ended.len()); + state.ended.reserve(unended); + Some(handles::handle(index)) + } + + /// How many deferred command buffers were made for it, and how many may end without + /// growing `ended`. + #[cfg(test)] + pub(crate) fn room_to_end(&self) -> (usize, usize) { + let state = lock(&self.state); + (state.handles.len(), state.ended.capacity()) + } + + /// Deferred command buffer `index` ended: replayed once its command buffer committed. + pub(super) fn ended(self: &Arc, index: u32) { + let mut state = lock(&self.state); + state.ended.push_back(index); + if state.open && !state.queued { + state.queued = true; + drop(state); + self.recorder.enqueue(Arc::clone(self)); + } + } + + /// Hold the host pages what ended names, which `fill` adds to what it holds, until nothing /// ended waits for its replay: an encoder encoded again before its command buffer's first /// submission (`reencode.rs`). As at the commit ([`commit`](Self::commit)), the pages it held /// last are the answer, for the caller to let go of where it lets go of them without a @@ -20,13 +326,26 @@ device: &Vk, fill: impl FnOnce(&mut Vec>), ) -> Vec { + let mut state = lock(&self.state); + Self::fill(&mut state, fill); self.settle(device, &mut state) + } + + /// Its command buffer commits, its commands' holds on host pages `fill` adds to what it holds + /// ([`hold`](Self::hold)): what ended is replayed, on the recorder thread, and what ends from + /// now on; where nothing ended waits, what it holds goes now. `fill` runs under its lock, /// which it must not take again. + /// /// Where the buffer of some of those pages let go of them (released, rebound or detached /// while an encoder took them, on any thread), the commit would let go of them last without /// a recorder: what ended replays now, on this thread, with `device`, the device's /// functions. The pages it held last are the answer, for the caller to let go of where the /// commit lets go of them without a recorder. Nothing as a rule. + pub(crate) fn commit( + self: &Arc, + device: &Vk, + fill: impl FnOnce(&mut Vec>), + ) -> Vec { let mut state = lock(&self.state); Self::fill(&mut state, fill); state.open = true; @@ -40,11 +359,15 @@ /// on this thread, with `device`; where nothing ended waits, what it holds goes now. The /// pages it held last are the answer. fn settle(self: &Arc, device: &Vk, state: &mut ReplayState) -> Vec { + let mut last = Vec::new(); if !state.open { return last; } if !state.ended.is_empty() { if !state.queued { + state.queued = true; + self.recorder.enqueue(Arc::clone(self)); + } if state.held.iter().any(|pages| pages.buffer_let_go()) { let replayed = self.replay_ended(device, state); self.recorder @@ -54,10 +377,28 @@ } if state.ended.is_empty() { self.let_go(state, Some(&mut last)); + } + last + } + /// Add what `fill` adds to what `state` holds, counted in each page's holds. fn fill(state: &mut ReplayState, fill: impl FnOnce(&mut Vec>)) { + let before = state.held.len(); + fill(&mut state.held); + for pages in &state.held[before..] { + pages.held_for_replay(); + } + } + + /// Replay every ended command buffer not yet replayed, in the order they ended, waiting for + /// a replay in progress on another thread: how many this call replayed. On the recorder's /// thread (`queued`, which it takes off), a submitting one, or one that settles, with + /// `device`, the device's functions. fn drain(&self, device: &Vk, queued: bool) -> u64 { + let mut state = lock(&self.state); + if queued { + state.queued = false; + } let replayed = self.replay_ended(device, &mut state); // Nothing ended waits now: what it held for the replays goes. if state.open { @@ -75,7 +416,14 @@ state.ended.clear(); return 0; }; + let mut replayed = 0; + while let Some(index) = state.ended.pop_front() { self.replay(device, state, index); + replayed += 1; + } + replayed + } + /// Let go of what `state` holds, under its lock, running nothing of the program's. Where /// `last` is given (a commit's, [`settle`](Self::settle)), the pages held last go to it, /// for the caller to let go of. Elsewhere none is held last: the release, rebind or detach @@ -84,5 +432,194 @@ /// threads (`Device::elsewhere`), as its deallocator may run the program's code, which may /// not run on the recorder's thread nor under a submission's locks: announced there /// (`HeldByReplay`). + fn let_go(&self, state: &mut ReplayState, mut last: Option<&mut Vec>) { + for pages in state.held.drain(..) { let Some(pages) = HostPages::let_go_by_replay(pages) else { + continue; + }; + if let Some(last) = last.as_deref_mut() { + last.push(pages); + continue; + } + let last = Box::new(HeldByReplay(pages)); + match self.recorder.elsewhere.get() { + Some((contexts, context)) => contexts.post(*context, Item::Release(last)), + // Only before the device is made, which no command buffer is. + None => drop(last), + } + } + } + + /// Replay deferred command buffer `index` into a command buffer of the pool. + fn replay(&self, device: &Vk, state: &mut ReplayState, index: u32) { + // SAFETY: an ended log, which only replays read, under the replays' lock. + let log = unsafe { handles::log_at(index) }; + let recorder = &self.recorder; + let (real, begun) = match self.allocate(device, state, log) { + Ok(real) => real, + Err(error) => { + state.failure.get_or_insert(error); + return; + } + }; + let resolve = |raw: vk::CommandBuffer| -> Option { + match handles::index(raw) { + None => Some(raw), + // SAFETY: a secondary the log executes ended before it (Vulkan's executable + // state), so was replayed before it, published under this lock. + Some(at) => unsafe { handles::log_at(at) }.real(), + } + }; + // SAFETY: `real` was just taken from the pool, which only replays record, under the + // replays' lock; every object the log names is live until its command buffer completes, + // which is after the replay (its submission waits for it) or after its release, which + // takes this lock and replays nothing after. + match unsafe { log.replay(recorder.slot, real, begun, &resolve, &recorder.commands) } { + Ok(()) => { + state.ended_real += 1; + log.replayed(real); + } + Err(error) => { + state.failure.get_or_insert(error); + } + } + } + + /// A command buffer of `log`'s level from the pool, made on first use, and whether it is + /// begun: the pool's primary begun ahead where `log` may take it (`Log::takes_begun`; the + /// first encoder's, which an encoder of the command buffer that took the pool would take + /// without a recorder, `spares.rs`). + fn allocate( + &self, + raw: &Vk, + state: &mut ReplayState, + log: &Log, + ) -> Result<(vk::CommandBuffer, bool), vk::Result> { + let level = log.level; + if state.pool.is_none() { + let info = vk::CommandPoolCreateInfo::default() + .flags( + vk::CommandPoolCreateFlags::TRANSIENT + | vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER, + ) + .queue_family_index(state.family); + // SAFETY: the device is live and `info` valid. + let pool = unsafe { raw.create_command_pool(&info, None) }?; + exit_guard::called(Call::CreateCommandPool); + self.recorder.pools_made.fetch_add(1, Ordering::Relaxed); + state.pool = Some(CommandPool::new(pool, state.family)); + } + let Some(pool) = &mut state.pool else { + return Err(vk::Result::ERROR_UNKNOWN); + }; + if log.takes_begun() { + if let Some(buffer) = pool.take_begun() { + self.recorder + .begun_ahead_taken + .fetch_add(1, Ordering::Relaxed); + return Ok((buffer, true)); + } + } + if let Some(buffer) = pool.reuse(level) { + return Ok((buffer, false)); + } + let info = vk::CommandBufferAllocateInfo::default() + .command_pool(pool.raw) + .level(level) + .command_buffer_count(1); + // SAFETY: the pool is this command buffer's, held under the replays' lock; the loader + // reads the device's word first (`loader_word.rs`). + let buffer = unsafe { + self.recorder.loader_word.restore(); + raw.allocate_command_buffers(&info) + }?[0]; + exit_guard::called(Call::AllocateCommandBuffers); + pool.made(level, buffer); + Ok((buffer, false)) + } + + /// Let go of everything: nothing ended is replayed after, a replay in progress ended first, + /// every handle is free, and what it held goes; kept for another command buffer where + /// nothing else holds it. The pool, with whether it is settled (every command buffer it + /// handed out ended, `completed` where its command buffer completed), to give back to the + /// device's spares. + pub(crate) fn release(self: Arc, completed: bool) -> Option<(CommandPool, bool)> { + let pool = { + let mut state = lock(&self.state); + state.ended.clear(); + state.open = false; + self.let_go(&mut state, None); + // SAFETY: nothing records these any more (their command buffer completed or is + // dropped), and no replay reads them after this lock (`ended` is empty, `open` + // false). + unsafe { handles::free(&state.handles) }; + state.handles.clear(); + let settled = completed + && state.failure.is_none() + && state + .pool + .as_ref() + .is_some_and(|pool| pool.handed_out() as u64 == state.ended_real); + state.ended_real = 0; + state.failure = None; + state.pool.take().map(|pool| (pool, settled)) + }; + self.keep(); + pool + } + + /// Keep it for another command buffer where nothing else holds it, released + /// ([`release`](Self::release)): where the recorder's queue holds it still, the recorder + /// keeps it as it takes it. + fn keep(self: Arc) { + if Arc::strong_count(&self) == 1 { + let recorder = Arc::clone(&self.recorder); + let mut kept = lock(&recorder.kept); + if kept.len() < KEPT_REPLAYS { + kept.push(self); + } + } + } +} + +/// The command buffer to submit in place of `raw`: `raw` where it is a driver's; a deferred one's +/// replay, replayed now by this thread with `device`, the device's functions, where the +/// recorder's has not yet, waiting for a replay in progress. A replay's failure is the result. +/// +/// # Safety +/// +/// `raw` ended, and its command buffer committed; the caller is inside a section. +pub(crate) unsafe fn resolve( + device: &Vk, + raw: vk::CommandBuffer, +) -> Result { + // SAFETY: an ended log (the caller's), read for what its replay published. + let Some(log) = (unsafe { handles::log(raw) }) else { + return Ok(raw); + }; + if let Some(real) = log.real() { + return Ok(real); + } + let Some(replays) = log.replays() else { + return Err(vk::Result::ERROR_UNKNOWN); + }; let replayed = replays.drain(device, false); + replays + .recorder + .by_submitter + .fetch_add(replayed, Ordering::Relaxed); + if let Some(real) = log.real() { + return Ok(real); + } + Err(lock(&replays.state) + .failure + .unwrap_or(vk::Result::ERROR_UNKNOWN)) +} + +/// The real command buffer of a raw handle stored in a log's `real`. +pub(super) fn real_of(raw: &AtomicU64) -> Option { + match raw.load(Ordering::Acquire) { + 0 => None, + raw => Some(vk::CommandBuffer::from_raw(raw)), + } +} diff --git a/crates/metal2vulkan-runtime/src/recorder/thunks.rs b/crates/metal2vulkan-runtime/src/recorder/thunks.rs new file mode 100644 index 000000000..89d7a262f --- /dev/null +++ b/crates/metal2vulkan-runtime/src/recorder/thunks.rs @@ -0,0 +1,415 @@ +//! The routed commands' entry points, one per command and slot, and each slot's commands as its +//! device's driver gave them (`recorder`): each entry point logs a deferred command buffer's +//! command (`log.rs`), and calls the driver's with any other. + +use super::SLOTS; +use crate::generated_commands::GeneratedCommandsInfo; +use ash::vk; +use std::ffi::{c_void, CStr}; +use std::sync::atomic::{AtomicPtr, AtomicU64, Ordering}; + +/// A command whose driver's entry point was not stored for the slot whose entry point was called: +/// a device's functions routed before its commands were (a defect of the runtime's). It ends the +/// process: a command recorded otherwise would be lost. +#[cold] +fn missing(name: &CStr) -> ! { + panic!("the routed command {name:?} has no driver's entry point"); +} + +/// Declare the routed commands: those of `ash`'s 1.0 table (`v1_0`), of its 1.3 table (`v1_3`), +/// and the extension commands the runtime loads itself (`extension`), each with its variant of +/// [`Command`], its field in its table (or a name of its own), its Vulkan name and its parameters +/// after the command buffer. +macro_rules! commands { + ( + v1_0 { $($v0:ident $f0:ident $n0:literal ($($a0:ident: $t0:ty),*) $(-> $r0:ty)?;)* } + v1_3 { $($v3:ident $f3:ident $n3:literal ($($a3:ident: $t3:ty),*) $(-> $r3:ty)?;)* } + extension { $($ve:ident $fe:ident $ne:literal ($($ae:ident: $te:ty),*) $(-> $re:ty)?;)* } + ) => { + /// A command routed through the slots (`recorder`). + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + pub(crate) enum Command { + $($v0,)* + $($v3,)* + $($ve,)* + } + + impl Command { + /// Every routed command. + pub(crate) const ALL: &'static [Command] = &[ + $(Command::$v0,)* + $(Command::$v3,)* + $(Command::$ve,)* + ]; + + /// How many commands are routed: each one's index (`command as usize`) is below it. + pub(crate) const COUNT: usize = Command::ALL.len(); + + /// Its Vulkan name. + pub(crate) fn name(self) -> &'static CStr { + match self { + $(Command::$v0 => $n0,)* + $(Command::$v3 => $n3,)* + $(Command::$ve => $ne,)* + } + } + } + + /// The commands a device's replays called (`recorder`), by kind: each routed command's + /// calls made into the `VkCommandBuffer`s the deferred command buffers replay into, on + /// whichever thread replayed them. A field of `WorkCounts`, for the lanes: not part of + /// the API. + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] + pub struct CommandsReplayed { + $( + #[doc = concat!("The replays' calls of `", stringify!($v0), "`.")] + pub $f0: u64, + )* + $( + #[doc = concat!("The replays' calls of `", stringify!($v3), "`.")] + pub $f3: u64, + )* + $( + #[doc = concat!("The replays' calls of `", stringify!($ve), "`.")] + pub $fe: u64, + )* + } + + impl CommandsReplayed { + /// The counts `counts` holds, one per command at its index. + pub(crate) fn read(counts: &[AtomicU64; Command::COUNT]) -> CommandsReplayed { + CommandsReplayed { + $($f0: counts[Command::$v0 as usize].load(Ordering::Relaxed),)* + $($f3: counts[Command::$v3 as usize].load(Ordering::Relaxed),)* + $($fe: counts[Command::$ve as usize].load(Ordering::Relaxed),)* + } + } + } + + /// Each slot's commands, as their devices' drivers gave them; null where none is stored. + struct Real { + $($f0: [AtomicPtr; SLOTS],)* + $($f3: [AtomicPtr; SLOTS],)* + $($fe: [AtomicPtr; SLOTS],)* + } + + static REAL: Real = Real { + $($f0: [const { AtomicPtr::new(std::ptr::null_mut()) }; SLOTS],)* + $($f3: [const { AtomicPtr::new(std::ptr::null_mut()) }; SLOTS],)* + $($fe: [const { AtomicPtr::new(std::ptr::null_mut()) }; SLOTS],)* + }; + + commands!(@thunks $($f0 $n0 ($($a0: $t0),*) $(-> $r0)?;)*); + commands!(@thunks $($f3 $n3 ($($a3: $t3),*) $(-> $r3)?;)*); + commands!(@thunks $($fe $ne ($($ae: $te),*) $(-> $re)?;)*); + + /// Slot `S`'s entry point for `command`. + pub(super) fn thunk(command: Command) -> *const c_void { + match command { + $(Command::$v0 => $f0:: as *const c_void,)* + $(Command::$v3 => $f3:: as *const c_void,)* + $(Command::$ve => $fe:: as *const c_void,)* + } + } + + /// Store `real` as slot `index`'s `command`. + pub(super) fn store(index: usize, command: Command, real: *const c_void) { + let real = real.cast_mut(); + match command { + $(Command::$v0 => REAL.$f0[index].store(real, Ordering::Release),)* + $(Command::$v3 => REAL.$f3[index].store(real, Ordering::Release),)* + $(Command::$ve => REAL.$fe[index].store(real, Ordering::Release),)* + } + } + + /// Slot `index`'s `command` as its device's driver gave it. + /// + /// # Safety + /// + /// `F` is the function pointer type of `command`'s signature. + pub(super) unsafe fn real(index: usize, command: Command) -> F { + let real = match command { + $(Command::$v0 => REAL.$f0[index].load(Ordering::Acquire),)* + $(Command::$v3 => REAL.$f3[index].load(Ordering::Acquire),)* + $(Command::$ve => REAL.$fe[index].load(Ordering::Acquire),)* + }; + if real.is_null() { + missing(command.name()); + } + // SAFETY: a function pointer of `F`'s signature (the caller's), not null. + unsafe { std::mem::transmute_copy::<*mut c_void, F>(&real) } + } + + /// Forget slot `index`'s commands. + pub(super) fn clear(index: usize) { + $(REAL.$f0[index].store(std::ptr::null_mut(), Ordering::Release);)* + $(REAL.$f3[index].store(std::ptr::null_mut(), Ordering::Release);)* + $(REAL.$fe[index].store(std::ptr::null_mut(), Ordering::Release);)* + } + + /// Route the tables' commands through slot `S`: each one's driver's entry point stored, + /// the slot's in its place. + pub(super) fn route_tables( + v1_0: &mut ash::DeviceFnV1_0, + v1_3: &mut ash::DeviceFnV1_3, + ) { + $( + store(S, Command::$v0, v1_0.$f0 as *const c_void); + v1_0.$f0 = $f0::; + )* + $( + store(S, Command::$v3, v1_3.$f3 as *const c_void); + v1_3.$f3 = $f3::; + )* + } + }; + (@thunks $($f:ident $n:literal ($($a:ident: $t:ty),*) $(-> $r:ty)?;)*) => { + $( + /// The command through slot `S` (the module docs). + unsafe extern "system" fn $f( + command_buffer: vk::CommandBuffer, + $($a: $t,)* + ) $(-> $r)? { + // A deferred command buffer's command goes into its log (`recorder`). + // SAFETY: the caller records `command_buffer` alone (Vulkan's external + // synchronization); its arguments are as the command takes them. + let logged = + unsafe { super::handles::record(command_buffer, |log| log.$f($($a,)*)) }; + if let Some(logged) = logged { + return logged; + } + let real = REAL.$f[S].load(Ordering::Acquire); + if real.is_null() { + missing($n); + } + // SAFETY: the slot's device's driver gave this command (`store`), of this + // signature; the caller's arguments are as the command takes them. + unsafe { + let real = std::mem::transmute::< + *mut c_void, + unsafe extern "system" fn(vk::CommandBuffer, $($t,)*) $(-> $r)?, + >(real); + real(command_buffer, $($a,)*) + } + } + )* + }; +} + +commands! { + v1_0 { + BeginCommandBuffer begin_command_buffer c"vkBeginCommandBuffer" + (info: *const vk::CommandBufferBeginInfo<'_>) -> vk::Result; + EndCommandBuffer end_command_buffer c"vkEndCommandBuffer" () -> vk::Result; + CmdBindPipeline cmd_bind_pipeline c"vkCmdBindPipeline" + (bind_point: vk::PipelineBindPoint, pipeline: vk::Pipeline); + CmdSetViewport cmd_set_viewport c"vkCmdSetViewport" + (first: u32, count: u32, viewports: *const vk::Viewport); + CmdSetScissor cmd_set_scissor c"vkCmdSetScissor" + (first: u32, count: u32, scissors: *const vk::Rect2D); + CmdSetDepthBias cmd_set_depth_bias c"vkCmdSetDepthBias" + (constant: f32, clamp: f32, slope: f32); + CmdSetBlendConstants cmd_set_blend_constants c"vkCmdSetBlendConstants" + (constants: *const [f32; 4]); + CmdSetStencilCompareMask cmd_set_stencil_compare_mask c"vkCmdSetStencilCompareMask" + (faces: vk::StencilFaceFlags, mask: u32); + CmdSetStencilWriteMask cmd_set_stencil_write_mask c"vkCmdSetStencilWriteMask" + (faces: vk::StencilFaceFlags, mask: u32); + CmdSetStencilReference cmd_set_stencil_reference c"vkCmdSetStencilReference" + (faces: vk::StencilFaceFlags, reference: u32); + CmdBindDescriptorSets cmd_bind_descriptor_sets c"vkCmdBindDescriptorSets" + ( + bind_point: vk::PipelineBindPoint, + layout: vk::PipelineLayout, + first: u32, + count: u32, + sets: *const vk::DescriptorSet, + offset_count: u32, + offsets: *const u32 + ); + CmdBindIndexBuffer cmd_bind_index_buffer c"vkCmdBindIndexBuffer" + (buffer: vk::Buffer, offset: vk::DeviceSize, index_type: vk::IndexType); + CmdBindVertexBuffers cmd_bind_vertex_buffers c"vkCmdBindVertexBuffers" + (first: u32, count: u32, buffers: *const vk::Buffer, offsets: *const vk::DeviceSize); + CmdDraw cmd_draw c"vkCmdDraw" + (vertices: u32, instances: u32, first_vertex: u32, first_instance: u32); + CmdDrawIndexed cmd_draw_indexed c"vkCmdDrawIndexed" + (indices: u32, instances: u32, first_index: u32, vertex_offset: i32, first_instance: u32); + CmdDrawIndirect cmd_draw_indirect c"vkCmdDrawIndirect" + (buffer: vk::Buffer, offset: vk::DeviceSize, count: u32, stride: u32); + CmdDrawIndexedIndirect cmd_draw_indexed_indirect c"vkCmdDrawIndexedIndirect" + (buffer: vk::Buffer, offset: vk::DeviceSize, count: u32, stride: u32); + CmdDispatch cmd_dispatch c"vkCmdDispatch" (x: u32, y: u32, z: u32); + CmdDispatchIndirect cmd_dispatch_indirect c"vkCmdDispatchIndirect" + (buffer: vk::Buffer, offset: vk::DeviceSize); + CmdCopyBuffer cmd_copy_buffer c"vkCmdCopyBuffer" + (src: vk::Buffer, dst: vk::Buffer, count: u32, regions: *const vk::BufferCopy); + CmdCopyImage cmd_copy_image c"vkCmdCopyImage" + ( + src: vk::Image, + src_layout: vk::ImageLayout, + dst: vk::Image, + dst_layout: vk::ImageLayout, + count: u32, + regions: *const vk::ImageCopy + ); + CmdBlitImage cmd_blit_image c"vkCmdBlitImage" + ( + src: vk::Image, + src_layout: vk::ImageLayout, + dst: vk::Image, + dst_layout: vk::ImageLayout, + count: u32, + regions: *const vk::ImageBlit, + filter: vk::Filter + ); + CmdCopyBufferToImage cmd_copy_buffer_to_image c"vkCmdCopyBufferToImage" + ( + src: vk::Buffer, + dst: vk::Image, + dst_layout: vk::ImageLayout, + count: u32, + regions: *const vk::BufferImageCopy + ); + CmdCopyImageToBuffer cmd_copy_image_to_buffer c"vkCmdCopyImageToBuffer" + ( + src: vk::Image, + src_layout: vk::ImageLayout, + dst: vk::Buffer, + count: u32, + regions: *const vk::BufferImageCopy + ); + CmdUpdateBuffer cmd_update_buffer c"vkCmdUpdateBuffer" + (dst: vk::Buffer, offset: vk::DeviceSize, size: vk::DeviceSize, data: *const c_void); + CmdFillBuffer cmd_fill_buffer c"vkCmdFillBuffer" + (dst: vk::Buffer, offset: vk::DeviceSize, size: vk::DeviceSize, data: u32); + CmdClearColorImage cmd_clear_color_image c"vkCmdClearColorImage" + ( + image: vk::Image, + layout: vk::ImageLayout, + color: *const vk::ClearColorValue, + count: u32, + ranges: *const vk::ImageSubresourceRange + ); + CmdClearDepthStencilImage cmd_clear_depth_stencil_image c"vkCmdClearDepthStencilImage" + ( + image: vk::Image, + layout: vk::ImageLayout, + value: *const vk::ClearDepthStencilValue, + count: u32, + ranges: *const vk::ImageSubresourceRange + ); + CmdClearAttachments cmd_clear_attachments c"vkCmdClearAttachments" + ( + count: u32, + attachments: *const vk::ClearAttachment, + rect_count: u32, + rects: *const vk::ClearRect + ); + CmdPipelineBarrier cmd_pipeline_barrier c"vkCmdPipelineBarrier" + ( + src: vk::PipelineStageFlags, + dst: vk::PipelineStageFlags, + flags: vk::DependencyFlags, + memory_count: u32, + memory: *const vk::MemoryBarrier<'_>, + buffer_count: u32, + buffers: *const vk::BufferMemoryBarrier<'_>, + image_count: u32, + images: *const vk::ImageMemoryBarrier<'_> + ); + CmdBeginQuery cmd_begin_query c"vkCmdBeginQuery" + (pool: vk::QueryPool, query: u32, flags: vk::QueryControlFlags); + CmdEndQuery cmd_end_query c"vkCmdEndQuery" (pool: vk::QueryPool, query: u32); + CmdResetQueryPool cmd_reset_query_pool c"vkCmdResetQueryPool" + (pool: vk::QueryPool, first: u32, count: u32); + CmdWriteTimestamp cmd_write_timestamp c"vkCmdWriteTimestamp" + (stage: vk::PipelineStageFlags, pool: vk::QueryPool, query: u32); + CmdCopyQueryPoolResults cmd_copy_query_pool_results c"vkCmdCopyQueryPoolResults" + ( + pool: vk::QueryPool, + first: u32, + count: u32, + dst: vk::Buffer, + offset: vk::DeviceSize, + stride: vk::DeviceSize, + flags: vk::QueryResultFlags + ); + CmdPushConstants cmd_push_constants c"vkCmdPushConstants" + ( + layout: vk::PipelineLayout, + stages: vk::ShaderStageFlags, + offset: u32, + size: u32, + values: *const c_void + ); + CmdBeginRenderPass cmd_begin_render_pass c"vkCmdBeginRenderPass" + (begin: *const vk::RenderPassBeginInfo<'_>, contents: vk::SubpassContents); + CmdEndRenderPass cmd_end_render_pass c"vkCmdEndRenderPass" (); + CmdExecuteCommands cmd_execute_commands c"vkCmdExecuteCommands" + (count: u32, buffers: *const vk::CommandBuffer); + } + v1_3 { + CmdSetCullMode cmd_set_cull_mode c"vkCmdSetCullMode" (mode: vk::CullModeFlags); + CmdSetFrontFace cmd_set_front_face c"vkCmdSetFrontFace" (face: vk::FrontFace); + CmdSetPrimitiveTopology cmd_set_primitive_topology c"vkCmdSetPrimitiveTopology" + (topology: vk::PrimitiveTopology); + CmdBindVertexBuffers2 cmd_bind_vertex_buffers2 c"vkCmdBindVertexBuffers2" + ( + first: u32, + count: u32, + buffers: *const vk::Buffer, + offsets: *const vk::DeviceSize, + sizes: *const vk::DeviceSize, + strides: *const vk::DeviceSize + ); + CmdSetDepthTestEnable cmd_set_depth_test_enable c"vkCmdSetDepthTestEnable" + (enable: vk::Bool32); + CmdSetDepthWriteEnable cmd_set_depth_write_enable c"vkCmdSetDepthWriteEnable" + (enable: vk::Bool32); + CmdSetDepthCompareOp cmd_set_depth_compare_op c"vkCmdSetDepthCompareOp" + (op: vk::CompareOp); + CmdSetStencilTestEnable cmd_set_stencil_test_enable c"vkCmdSetStencilTestEnable" + (enable: vk::Bool32); + CmdSetStencilOp cmd_set_stencil_op c"vkCmdSetStencilOp" + ( + faces: vk::StencilFaceFlags, + fail: vk::StencilOp, + pass: vk::StencilOp, + depth_fail: vk::StencilOp, + compare: vk::CompareOp + ); + CmdSetPrimitiveRestartEnable cmd_set_primitive_restart_enable + c"vkCmdSetPrimitiveRestartEnable" (enable: vk::Bool32); + } + extension { + CmdPushDescriptorSet cmd_push_descriptor_set c"vkCmdPushDescriptorSetKHR" + ( + bind_point: vk::PipelineBindPoint, + layout: vk::PipelineLayout, + set: u32, + count: u32, + writes: *const vk::WriteDescriptorSet<'_> + ); + CmdSetColorWriteMask cmd_set_color_write_mask c"vkCmdSetColorWriteMaskEXT" + (first: u32, count: u32, masks: *const vk::ColorComponentFlags); + CmdSetDepthBias2 cmd_set_depth_bias2 c"vkCmdSetDepthBias2EXT" + (info: *const vk::DepthBiasInfoEXT<'_>); + CmdBindIndexBuffer2 cmd_bind_index_buffer2 c"vkCmdBindIndexBuffer2" + ( + buffer: vk::Buffer, + offset: vk::DeviceSize, + size: vk::DeviceSize, + index_type: vk::IndexType + ); + CmdDrawMeshTasks cmd_draw_mesh_tasks c"vkCmdDrawMeshTasksEXT" (x: u32, y: u32, z: u32); + CmdDrawMeshTasksIndirect cmd_draw_mesh_tasks_indirect c"vkCmdDrawMeshTasksIndirectEXT" + (buffer: vk::Buffer, offset: vk::DeviceSize, count: u32, stride: u32); + CmdExecuteGeneratedCommands cmd_execute_generated_commands + c"vkCmdExecuteGeneratedCommandsEXT" + (preprocessed: vk::Bool32, info: *const GeneratedCommandsInfo); + CmdPreprocessGeneratedCommands cmd_preprocess_generated_commands + c"vkCmdPreprocessGeneratedCommandsEXT" + (info: *const GeneratedCommandsInfo, state: vk::CommandBuffer); + } +} diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 164e82e4d..67e9c812c 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -3581,6 +3581,11 @@ impl RenderCommandEncoder { { sample_positions::check_options(CALL, Attachment::Stencil, s.options, s.store, None)?; } + // The instance's secondary, where the pass began one as it opened, is given up + // unrun (`end_unrun`). + // records it, nothing recorded into it (`untouched::changes_nothing`), and + // nothing executes it. + let ended = unsafe { core.command_buffer().give_up_raw(only.draws) }; // An extended-range attachment's clear takes Metal's straight route where Metal keeps its // level compressed and the pass has no draw call, where a `half` NaN clear keeps its sign // (`nan_clear::keeps_nan_sign`), and goes through `half` elsewhere (bfloat: EVs @@ -5774,11 +5779,12 @@ impl RenderCommandEncoder { } } - /// End the draws recording of `instance`, one the pass replaced or gave up before running + /// Give up the draws recording of `instance`, one the pass replaced or gave up before running /// it ([`install`](Self::install), `render/reroute.rs`, `render/capture.rs`): never submitted, - /// it ends so its command buffer's pool goes back to the device's spares unreset (`spares.rs`). - /// One with pieces (the secondaries of draws whose pipelines were being made) is left to the - /// pool's reset; one whose secondary never began has none to end. + /// a deferred one is never replayed, and one of the pool's ends so the pool goes back to the + /// device's spares unreset (`CommandBuffer::give_up_raw`). One with pieces (the secondaries + /// of draws whose pipelines were being made) is left to the pool's reset; one whose secondary + /// never began has none to give up. fn end_unrun(&self, instance: Instance) { // Nor one recorded inline, in the pass's command buffer or kept (`render/inline_first.rs`, // `render/inline_splits.rs`). @@ -5788,11 +5794,11 @@ impl RenderCommandEncoder { { return; } - // SAFETY: the secondary command buffer is recording, and only this encoder records it; - // no query is active in it: a query begins or continues only in an instance none of - // whose draws record again (`rerecord` `None`, which `recorded` marks too), never one a - // pass replaces, a reroute leaves, or a capture's. - let ended = unsafe { self.core.command_buffer().end_raw(instance.draws) }; + // SAFETY: the secondary command buffer is recording, only this encoder records it, and + // nothing executes it; no query is active in it: a query begins or continues only in an + // instance none of whose draws record again (`rerecord` `None`, which `recorded` marks + // too), never one a pass replaces, a reroute leaves, or a capture's. + let ended = unsafe { self.core.command_buffer().give_up_raw(instance.draws) }; if ended.is_ok() { self.core.device().shared().counts.unrun_instance_ended(); } @@ -9563,7 +9569,7 @@ struct Recording<'a> { state: &'a DrawState, extended: Option, /// The device's mesh draw commands, where it enabled `meshShader`. - mesh: Option<&'a ash::ext::mesh_shader::Device>, + mesh: Option<&'a crate::recorder::MeshDraws>, draw: metal2vulkan::vk::DrawCommand, /// Its part in a draw read through snapshots (`render/snapshot.rs`): the barrier, write /// masks and phase it records before its draw. diff --git a/crates/metal2vulkan-runtime/src/scheduler/inbox.rs b/crates/metal2vulkan-runtime/src/scheduler/inbox.rs index 20de3379d..d02692af0 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/inbox.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/inbox.rs @@ -41,11 +41,16 @@ use crate::device::lock; use std::sync::atomic::{fence, AtomicBool, AtomicUsize, Ordering}; use std::sync::{Mutex, TryLockError}; +/// The commits the inbox holds from its making without growing: more than a frame commits (the +/// consumer's guest commits about 45 command buffers a frame, the `frame_costs` lanes 41 to 108 +/// and wait for each frame's last), so a commit's push allocates only past a backlog that deep. +pub(crate) const ROOM: usize = 128; + /// A state `S` that passes work on under its lock, and the commits `C` waiting to be taken in. pub(crate) struct Inbox { state: Mutex, - /// Commits not yet taken in, in commit order. It keeps its room, and the thread making passes - /// grows it ahead of the commits ([`take`](Self::take)). + /// Commits not yet taken in, in commit order. It starts with room for [`ROOM`], keeps its room, + /// and the thread making passes grows it ahead of the commits ([`take`](Self::take)). commits: Mutex>, /// The commits a pass takes in. Filled and drained by the thread making the pass, under the /// state's lock, so it keeps its room from pass to pass and a pass allocates no list of them @@ -63,7 +68,7 @@ impl Inbox { pub(crate) fn new(state: S) -> Inbox { Inbox { state: Mutex::new(state), - commits: Mutex::new(Vec::new()), + commits: Mutex::new(Vec::with_capacity(ROOM)), taking: Mutex::new(Vec::new()), posted: AtomicBool::new(false), nudged: AtomicBool::new(false), @@ -197,7 +202,7 @@ impl Inbox { /// /// The inbox is left room for twice the commits taken in, made here, on the thread making /// passes: a commit's push then grows it, an allocation on the committing thread, only where - /// more than twice as many commits wait as a pass ever took in. + /// more commits wait than [`ROOM`] and twice as many as a pass ever took in. fn take(&self, taking: &mut Vec) { self.nudged.swap(false, Ordering::SeqCst); if !self.posted.load(Ordering::SeqCst) { diff --git a/crates/metal2vulkan-runtime/src/tests/exit_guard.rs b/crates/metal2vulkan-runtime/src/tests/exit_guard.rs index f5fe318cf..9077a32f3 100644 --- a/crates/metal2vulkan-runtime/src/tests/exit_guard.rs +++ b/crates/metal2vulkan-runtime/src/tests/exit_guard.rs @@ -1470,6 +1470,64 @@ fn every_image_render_pass_and_framebuffer_goes_through_the_creation_door() { ); } +/// Every command a `VkCommandBuffer` takes that the runtime names, through `ash`'s tables or a +/// function pointer it loads, goes through the devices' slots (`recorder`), which route it +/// (`recorder::Command::ALL`): no file outside `recorder/` names one that is not routed. +#[test] +fn every_command_the_runtime_records_is_routed() { + /// `name` lowercase, without `vk` and underscores, nor an `ext` or `khr` suffix: an + /// extension's command and the core one it became compare equal. + fn plain(name: &str) -> String { + let lower: String = name.chars().filter(|c| *c != '_').collect::(); + let lower = lower.to_lowercase(); + let lower = lower.strip_prefix("vk").unwrap_or(&lower).to_owned(); + let lower = lower.strip_prefix("pfnvk").unwrap_or(&lower).to_owned(); + ["ext", "khr"] + .iter() + .find_map(|suffix| lower.strip_suffix(suffix)) + .unwrap_or(&lower) + .to_owned() + } + let routed: Vec = crate::recorder::Command::ALL + .iter() + .map(|command| plain(command.name().to_str().unwrap())) + .collect(); + let mut unrouted = Vec::new(); + for (path, code) in runtime_sources() { + if path.starts_with("recorder") { + continue; + } + let mut rest = code.as_str(); + while let Some(at) = rest.find(['.', 'P']) { + let after = &rest[at + 1..]; + let word: String = after + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect(); + let named = match &rest[at..=at] { + "." if word.starts_with("cmd_") + || word == "begin_command_buffer" + || word == "end_command_buffer" => + { + Some(word.clone()) + } + "P" if word.starts_with("FN_vkCmd") => Some(format!("P{word}")), + _ => None, + }; + if let Some(named) = named { + if !routed.contains(&plain(&named)) { + unrouted.push(format!("{path}: {named}")); + } + } + rest = after; + } + } + assert!( + unrouted.is_empty(), + "commands named outside recorder/ that it does not route: {unrouted:#?}" + ); +} + /// The creation door refuses each kind of object in a host step, typed, and lets it through /// outside one. #[test] @@ -1580,6 +1638,19 @@ fn the_device_s_functions_are_reached_through_checked_accessors() { "pipeline/creation_log.rs", "MoltenVK's statistics call, inside a call that borrows the device", ), + ( + "recorder/log.rs", + "the generated-command entry points' types, a replay's call through its slot's entry \ + points", + ), + ( + "recorder/mod.rs", + "the device's mesh draw commands, routed through its slot (DeviceShared)", + ), + ( + "recorder/thunks.rs", + "a slot's driver entry points, called by its thunks and cleared at the slot's release", + ), ( "render.rs", "a draw's recording (vkCmd*), held by what holds its command buffer", @@ -1931,12 +2002,15 @@ fn the_table_names_each_entry_point_once() { /// Priming's check misses nothing but the entry points it cannot make (and, on a queue family /// that writes no timestamps, the timestamp commands, on a device without device addresses, a /// buffer's address, on one without generated commands, the release of their objects, on one +/// without the push command, a host step's push, on one that calibrates no timestamps, a /// completion turn's calibration reading, on one whose instance reports no messages, a pipeline's /// debug name, and on one without a render encoder's command of an extension or of Vulkan 1.3, /// that command), and names an entry point of the table it did not make. #[test] fn the_priming_check_names_what_was_not_made() { use crate::device::prime::{ + missing, Has, CALIBRATION_CALLS, COLOR_WRITE_MASK_CALLS, DEPTH_BIAS_CALLS, + DEVICE_ADDRESS_CALLS, EXTENDED_DYNAMIC_STATE_CALLS, GENERATED_COMMANDS_CALLS, HOST_QUERY_RESET_CALLS, NAMING_CALLS, PRIMITIVE_RESTART_CALLS, PUSH_DESCRIPTOR_CALLS, SIZED_INDEX_BIND_CALLS, SPARSE_CALLS, TIMESTAMP_CALLS, UNPRIMED, }; @@ -1949,6 +2023,11 @@ fn the_priming_check_names_what_was_not_made() { push_descriptor: true, calibration: true, object_names: true, + extended_dynamic_state: true, + primitive_restart: true, + color_write_masks: true, + depth_bias: true, + sized_index_bind: true, }; let all = Call::ALL.iter().fold(0, |bits, call| bits | call.bit()); assert!(missing(all, has(true, true)).is_empty()); @@ -2044,6 +2123,34 @@ fn the_priming_check_names_what_was_not_made() { }; assert!(missing(unnamed, without).is_empty()); assert_eq!(missing(unnamed, has(true, true)), NAMING_CALLS); + // Without a render encoder's command of an extension or of Vulkan 1.3, nor is that command. + let groups: [(&[Call], fn(Has) -> Has); 5] = [ + (&EXTENDED_DYNAMIC_STATE_CALLS, |has| Has { + extended_dynamic_state: false, + ..has + }), + (&PRIMITIVE_RESTART_CALLS, |has| Has { + primitive_restart: false, + ..has + }), + (&COLOR_WRITE_MASK_CALLS, |has| Has { + color_write_masks: false, + ..has + }), + (&DEPTH_BIAS_CALLS, |has| Has { + depth_bias: false, + ..has + }), + (&SIZED_INDEX_BIND_CALLS, |has| Has { + sized_index_bind: false, + ..has + }), + ]; + for (calls, without) in groups { + let unmade = calls.iter().fold(made, |bits, call| bits & !call.bit()); + assert!(missing(unmade, without(has(true, true))).is_empty()); + assert_eq!(missing(unmade, has(true, true)), calls); + } } /// A thread is in a section, so that the device's functions are the table's alone, while its diff --git a/crates/metal2vulkan-runtime/src/tests/inbox.rs b/crates/metal2vulkan-runtime/src/tests/inbox.rs index a9ea42088..0367e3ba1 100644 --- a/crates/metal2vulkan-runtime/src/tests/inbox.rs +++ b/crates/metal2vulkan-runtime/src/tests/inbox.rs @@ -8,7 +8,7 @@ //! they made read by a pass; and a pass leaves the inbox room for twice the commits it took in. use crate::device::lock; -use crate::scheduler::inbox::Inbox; +use crate::scheduler::inbox::{Inbox, ROOM}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc; use std::sync::{Arc, Condvar}; @@ -131,6 +131,20 @@ fn a_commit_finding_no_pass_marks_the_state_for_the_thread_s_wake() { assert!(!inbox.holds_commits()); } +/// A new inbox holds [`ROOM`] commits without growing: so a frame's commits, which wait at most +/// that many, push theirs with no allocation on their own thread, in `commit`, however far the +/// thread making passes falls behind them before its first pass took in as many. +#[test] +fn a_new_inbox_holds_room_commits_without_growing() { + let inbox = Log::new(Vec::new()); + let room = inbox.room(); + assert!(room >= ROOM, "a new inbox has room for {room}"); + for commit in 0..ROOM as u32 { + inbox.post(commit, |_| {}); + } + assert_eq!(inbox.room(), room, "{ROOM} commits grew the inbox"); +} + /// A pass leaves the inbox room for twice the commits it took in, made on the passing thread: so /// the commits after it grow the inbox on their own thread, an allocation in `commit`, only where /// more than twice as many wait. Grown by the pushes alone, it had room for 8 after 5 (Rust diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index dc8adf32e..0028ceffc 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -129,6 +129,7 @@ mod range; mod rate_map; mod reader_sizes; mod render; +mod replays; mod resource; mod resource_ids; mod rotated; diff --git a/crates/metal2vulkan-runtime/src/tests/replays.rs b/crates/metal2vulkan-runtime/src/tests/replays.rs new file mode 100644 index 000000000..0f84c50e1 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/replays.rs @@ -0,0 +1,74 @@ +//! `recorder/replays.rs`: a new recorder's queue has room for a frame's commits, and the recorder's +//! thread, taking the first replays queued, leaves the queue room for twice as many as waited, so +//! the commits after it queue theirs without growing it; a command buffer's replays, made new, +//! have room to end each deferred command buffer made for them. + +use crate::loader_word::LoaderWord; +use crate::recorder::{queue_room, take_leaving_room, RecorderShared}; +use crate::scheduler::inbox::ROOM; +use ash::vk; +use std::collections::VecDeque; + +/// A new recorder's queue holds as many replays as the scheduler's inbox holds commits ([`ROOM`]) +/// without growing: so a frame's commits, which wait at most that many, queue theirs with no +/// allocation on their own thread, in `commit`, however far the recorder's thread falls behind +/// before it first took one. +#[test] +fn a_new_recorder_queue_holds_room_replays_without_growing() { + let room = queue_room(); + assert!(room >= ROOM, "a new recorder's queue has room for {room}"); +} + +/// Taking the first of 5 queued leaves the queue room for 10, made on the taking thread: so the +/// commits after it push theirs with no allocation on their own thread, in `commit`, until more +/// than twice as many wait. Grown by the pushes alone, it had room for 8 after 5 (Rust 1.98.1's +/// growth), and a commit's push past 8 allocated in `commit`. +#[test] +fn taking_the_first_queued_leaves_room_for_twice_as_many_as_waited() { + let mut queue: VecDeque = (0..5).collect(); + assert_eq!(take_leaving_room(&mut queue), Some(0)); + let room = queue.capacity(); + assert!( + room >= 10, + "taking the first of 5 left the queue room for {room}" + ); + queue.extend(5..11); + assert_eq!(queue.len(), 10); + assert_eq!( + queue.capacity(), + room, + "the pushes up to twice as many as waited grew the queue" + ); + assert_eq!(take_leaving_room(&mut VecDeque::::new()), None); +} + +/// A command buffer's replays made new (none kept to take, as where the command buffers before it +/// have yet to complete) have room to end every deferred command buffer made for them, as each is +/// made: so the end of the last, which the commit makes (`CommandBufferShared::close_tail`), +/// allocates nothing in `commit`. Grown by the ends alone, the first end grew it, and a commit +/// whose command buffer ended nothing before it allocated once more than one taking kept replays +/// (`runtime_lane::frame_costs`, `a_frame_s_commits_allocate_within_their_bound`, on lavapipe +/// under load). +#[test] +fn new_replays_have_room_to_end_every_command_buffer_made_for_them() { + let word = Box::leak(Box::new(0usize)); + // SAFETY: a word that lives as long as the process; no device's, and nothing restores it. + let loader_word = + unsafe { LoaderWord::of_handle(std::ptr::from_mut(word).expose_provenance() as u64) }; + let recorder = RecorderShared::new(0, loader_word); + let replays = recorder.replays(0, None); + for level in [ + vk::CommandBufferLevel::PRIMARY, + vk::CommandBufferLevel::SECONDARY, + ] + .repeat(5) + { + replays.make(level).unwrap(); + let (made, room) = replays.room_to_end(); + assert!( + room >= made, + "room to end {room} of the {made} deferred command buffers made" + ); + } + assert_eq!(replays.release(false).map(|(_, settled)| settled), None); +} diff --git a/crates/metal2vulkan-runtime/src/texture/first_move.rs b/crates/metal2vulkan-runtime/src/texture/first_move.rs index 25e5e31a6..eb90bab5b 100644 --- a/crates/metal2vulkan-runtime/src/texture/first_move.rs +++ b/crates/metal2vulkan-runtime/src/texture/first_move.rs @@ -92,15 +92,18 @@ //! one waits for the batch that did it until that batch completed ([`FirstMoves::waits`]): any //! of its commands may reach the resource unnamed. //! - **Order**. Each submission holds its place in the order from its take until its submission was -//! made, whether or not it took anything, and each registration waits for its place: so no -//! submission is made between another's take and its submission (one that found nothing to take -//! would otherwise run before the moves another took, on the same `VkQueue`), and no resource -//! registers between a take and its submission (its texture table element, written after it -//! registered, then reaches no batch submitted without its move). An internal submission signals -//! a timeline of its own, which a batch on another `VkQueue` waits for while one that did first -//! work may not have completed ([`FirstMoves::internal_wait`]). Seen without it on RADV: a batch -//! submitted with images in `UNDEFINED` in its texture table, under the validation layer (EV -//! STL-ps4-radv). +//! made, whether or not it took anything: so no submission is made between another's take and its +//! submission (one that found nothing to take would otherwise run before the moves another took, +//! on the same `VkQueue`). No texture's elements are written between a batch's take and its +//! submission: a texture registered after the take, whose move the batch did not take, would be +//! in the batch's texture table in `UNDEFINED`. So a batch holds the texture slots' writes over +//! that span ([`FirstMoves::take_holding`], `heap_sets::hold`): elements asked meanwhile are +//! written once its submission was made, before the next submission takes its place, and a +//! registration waits for nothing, as Metal's makes wait for nothing. Where registrations waited +//! for the place instead, a texture made while a batch of 4096 to 32768 fills was submitted on +//! the M3 Max waited up to 13 ms, in 20 of 60 makings: MoltenVK encodes a command buffer's Metal +//! commands inside `vkQueueSubmit`, on the calling thread (4.5 to 17 ms for those batches); with +//! the hold, no making of 60 took past 0.16 ms. A device whose heap sets take no writes while a //! - **Failure.** A submission that fails gives its work back, still to be done. //! - **Out of reach of a submission.** A texture's `VkImage` handed out (`Texture::vk_image`) //! rests in `GENERAL` as its contract says: handing it out does its work first, by an internal diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 28239f499..7e0825662 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -9,6 +9,7 @@ use super::buffer::{KeptBecause, ReadApart}; use super::command_buffer::GroupEnd; use super::degradation::Degradation; use super::device::lock; +use super::recorder::{CommandsReplayed, ReplayCounts}; use super::shadow::{Backing, CopyCause, Lost, ShadowCopy, ShadowSource}; use super::Device; use ash::vk; @@ -22,6 +23,7 @@ const LARGE_SURFACE_TEXELS: u64 = 1 << 20; #[derive(Default)] pub(crate) struct Counters { command_pools_made: AtomicU64, + command_buffers_deferred: AtomicU64, spare_command_pools_taken: AtomicU64, spare_command_pools_reset: AtomicU64, live_tables_uploaded: AtomicU64, @@ -363,6 +365,13 @@ impl Counters { self.command_pools_made.fetch_add(1, Ordering::Relaxed); } + /// An encoder took a deferred command buffer, which the device's recorder replays + /// (`recorder`). + pub(crate) fn command_buffer_deferred(&self) { + self.command_buffers_deferred + .fetch_add(1, Ordering::Relaxed); + } + /// A command buffer took one of the device's spare command pools (`spares.rs`). pub(crate) fn spare_command_pool_taken(&self) { self.spare_command_pools_taken @@ -828,7 +837,8 @@ impl Counters { } /// A render pass instance its pass replaced or gave up before running it had its draws - /// recording ended (`render.rs`, `RenderCommandEncoder::end_unrun`). + /// recording given up (`render.rs`, `RenderCommandEncoder::end_unrun`): never replayed where + /// deferred, else ended. pub(crate) fn unrun_instance_ended(&self) { self.unrun_instances_ended.fetch_add(1, Ordering::Relaxed); } @@ -1694,6 +1704,18 @@ impl Counters { pub struct WorkCounts { /// `VkCommandPool`s made for command buffers, where no spare one was free. pub command_pools_made: u64, + /// The command buffers encoders took that the program's thread logged and the device's + /// recorder replays into `VkCommandBuffer`s once their command buffer is committed + /// (`recorder`): every encoder's, on a device with a recorder. + pub command_buffers_deferred: u64, + /// Those the recorder's thread replayed. + pub command_buffers_replayed: u64, + /// Those another thread replayed itself where the recorder's had not yet reached them: one + /// that submits them, or that releases, rebinds or detaches host pages their commands name. + pub command_buffers_replayed_inline: u64, + /// The commands their replays called, by kind, on whichever thread replayed them + /// (`recorder`): one per call made into a `VkCommandBuffer`, the begins and ends among them. + pub commands_replayed: CommandsReplayed, /// Spare `VkCommandPool`s command buffers took, made by earlier ones. The pool is not reset /// where the command buffer that gave it back completed and ended every command buffer of it /// it was handed: each is reset as it is begun again. @@ -2000,6 +2022,8 @@ pub struct WorkCounts { /// Of `encoder_command_buffers_begun`, the encoders' own `VkCommandBuffer`s begun ahead: a /// settled spare command pool's primary, begun by the thread that completed the command /// buffer that gave it back where no thread waited for that one, which the first encoder of + /// the command buffer that takes the pool records into, begun no more on its thread (on a + /// device with a recorder, the first encoder's replay, `recorder`). pub encoder_primaries_begun_ahead: u64, /// The spare command pools' primaries begun ahead (`encoder_primaries_begun_ahead`), taken /// by an encoder or not yet: not among `command_buffers_begun` until one is taken. Each is @@ -2148,7 +2172,8 @@ pub struct WorkCounts { /// Render pass instances a pass replaced or gave up before running them (a draw that needed /// another shape before any draw recorded, a reroute's instance left behind, a capture that /// recorded nothing, a first instance whose draws record inline instead), whose draws - /// recording the runtime ended: their command pool goes back to the device's spares unreset + /// recording the runtime gave up: never replayed where deferred (`recorder`), else ended, so + /// their command pool goes back to the device's spares unreset /// (`WorkCounts::spare_command_pools_reset` counts the others). A pass's first instance that /// may record inline begins its draws' secondary only where a command records into it, so /// one replaced or recording inline before then began none, ended none, and is not counted. @@ -2821,8 +2846,15 @@ impl Device { turnover, ) }; + let replays = (self.shared().recorder()) + .map_or_else(ReplayCounts::default, |recorder| recorder.counts()); WorkCounts { - command_pools_made: counters.command_pools_made.load(Ordering::Relaxed), + command_pools_made: counters.command_pools_made.load(Ordering::Relaxed) + + replays.pools_made, + command_buffers_deferred: counters.command_buffers_deferred.load(Ordering::Relaxed), + command_buffers_replayed: replays.by_recorder, + command_buffers_replayed_inline: replays.by_submitter, + commands_replayed: replays.commands, spare_command_pools_taken: counters.spare_command_pools_taken.load(Ordering::Relaxed), spare_command_pools_reset: counters.spare_command_pools_reset.load(Ordering::Relaxed), live_tables_uploaded: counters.live_tables_uploaded.load(Ordering::Relaxed), @@ -2931,6 +2963,8 @@ impl Device { encoder_command_buffers_begun: (counters.encoder_command_buffers_begun) .load(Ordering::Relaxed), encoder_primaries_begun_ahead: (counters.encoder_primaries_begun_ahead) + .load(Ordering::Relaxed) + + replays.begun_ahead_taken, primaries_begun_ahead: counters.primaries_begun_ahead.load(Ordering::Relaxed), barrier_buffers_kept: counters.barrier_buffers_kept.load(Ordering::Relaxed), stamped_buffers_kept: counters.stamped_buffers_kept.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index c09453629..4cbcbf5a8 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -277,6 +277,8 @@ mod command_queues; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod command_render_states; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod commands_replayed; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod commit_costs; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod commit_latency; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/clear_reach.rs b/crates/metal2vulkan-validation/src/runtime_lane/clear_reach.rs index 5a439ca29..31e5e1773 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/clear_reach.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/clear_reach.rs @@ -17,6 +17,7 @@ use super::degrade_notices::{assert_made_once, forced, made_render_kinds}; use super::degrade_notices::{shared_in_system_memory, twins_depth}; +use super::hidden_depth::replayed_but_unrun; use super::{buffer_with, read_buffer, validated_device, Messages, ScratchCache, WAIT}; use crate::air_library::AirLibrary; use crate::gpu::TEST_DEVICE; @@ -724,8 +725,25 @@ fn depth_stencil_and_multisampled_clears_reach_past_the_render_area_as_metal_s() quiet(lane, &messages); } -/// A `DontCare` load of an attachment the pass stores (EV RRS-probe-5's `dl_rgba8_emptydraw`, -/// `dl_rgba8_full`, `dl_rgba8_nodraw`, `dl_rgba8_nothing` and `dl_d32_touch00`): kept in a pass +/// vertex keeps the texels, and a pass with a visibility result buffer keeps them: each records its +/// pass as before. The pass beside a depth, whose first instance never records inline, began its +/// draws' secondary as it opened: given up unused (`WorkCounts::unrun_instances_ended`), it is +/// never replayed (`CommandBuffer::give_up_raw`). + let counted = lane.device.work_counts(); + let after = lane.device.work_counts(); + let unrun = after.unrun_instances_ended - counted.unrun_instances_ended; + assert_eq!(unrun, 1, "a depth beside: secondaries given up"); + let (replayed, deferred) = replayed_but_unrun(&counted, &after); + eprintln!( + "a pass beside a depth that changes nothing on {}: {unrun} secondaries given up, \ + {replayed} of {deferred} deferred command buffers begun replayed", + lane.device.name() + ); + assert_eq!( + replayed, + deferred - unrun, + "a depth beside: command buffers replayed of those begun deferred" + ); /// that does not draw (a draw call of no vertex, or through a pipeline that rasterizes nothing, /// included), as Metal keeps it, with no notice; cleared to zero over every tile, Metal's answer /// with no notice, where such a pass clears and stores its depth (the clear rule); in one that diff --git a/crates/metal2vulkan-validation/src/runtime_lane/commands_replayed.rs b/crates/metal2vulkan-validation/src/runtime_lane/commands_replayed.rs new file mode 100644 index 000000000..b0b6be8ec --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/commands_replayed.rs @@ -0,0 +1,85 @@ +//! Device tests of the commands the recorder's replays call, by kind (the runtime's `recorder`, +//! `WorkCounts::commands_replayed`), on the device the cfg selects, under the validation layer: a +//! command buffer of one blit encoder of fills and copies replays each as one call of its own +//! kind, counted exactly: a fill of one word as `vkCmdFillBuffer`, or as `vkCmdUpdateBuffer` where +//! the runtime records fills as transfers (`WorkCounts::fills_by_transfers`, MoltenVK 1.4.1). + +use super::host_memory::on_device; +use super::{read_buffer, WAIT}; +use metal2vulkan_runtime::{CommandBufferStatus, CommandsReplayed, ResourceOptions}; + +/// The fills and the copies the command buffer encodes, each of [`WORD`] bytes at a word of its +/// own. +const FILLS: u64 = 5; +const COPIES: u64 = 2; +const WORD: u64 = 4; + +/// The counts `after` holds past `before`, of the fills', the updates', the copies' and the +/// ends' kinds. +fn added(before: &CommandsReplayed, after: &CommandsReplayed) -> [u64; 4] { + [ + after.cmd_fill_buffer - before.cmd_fill_buffer, + after.cmd_update_buffer - before.cmd_update_buffer, + after.cmd_copy_buffer - before.cmd_copy_buffer, + after.end_command_buffer - before.end_command_buffer, + ] +} + +/// One blit encoder of [`FILLS`] fills of a buffer's words, then [`COPIES`] copies of its first +/// words into another's, committed and completed: its replay called `vkCmdFillBuffer` once a fill +/// recorded so and `vkCmdUpdateBuffer` once a fill recorded as transfers (one word: no copy), +/// `vkCmdCopyBuffer` once a copy, and ended at least its encoder's command buffer. The bytes are +/// what the fills and copies wrote. A device that records as it encodes (no recorder) +/// replays nothing, printed. +#[test] +fn a_replay_counts_each_command_it_calls_by_kind() { + on_device(|device| { + let name = device.name(); + let queue = device.new_command_queue().unwrap(); + let filled = (device.new_buffer(WORD * FILLS, ResourceOptions::shared())).unwrap(); + let copied = (device.new_buffer(WORD * COPIES, ResourceOptions::shared())).unwrap(); + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + for at in 0..FILLS { + (blit.fill_buffer(&filled, WORD * at..WORD * (at + 1), at as u8 + 1)).unwrap(); + } + for at in 0..COPIES { + (blit.copy_from_buffer_to_buffer(&filled, WORD * at, &copied, WORD * at, WORD)) + .unwrap(); + } + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + let after = device.work_counts(); + let expected: Vec = (0..FILLS as u8) + .flat_map(|at| [at + 1; WORD as usize]) + .collect(); + assert_eq!(read_buffer(&filled, 0, WORD * FILLS).unwrap(), expected); + assert_eq!( + read_buffer(&copied, 0, WORD * COPIES).unwrap(), + expected[..(WORD * COPIES) as usize] + ); + if after.command_buffers_deferred == before.command_buffers_deferred { + eprintln!("COMMANDS-REPLAYED {name}: records as it encodes, so replays nothing"); + return; + } + let [fills, updates, copies, ends] = + added(&before.commands_replayed, &after.commands_replayed); + let recorded = after.fills_recorded - before.fills_recorded; + let by_transfers = after.fills_by_transfers - before.fills_by_transfers; + eprintln!( + "COMMANDS-REPLAYED {name}: {fills} vkCmdFillBuffer, {updates} vkCmdUpdateBuffer, \ + {copies} vkCmdCopyBuffer, {ends} vkEndCommandBuffer replayed; {recorded} fills \ + recorded so, {by_transfers} as transfers" + ); + assert_eq!(recorded + by_transfers, FILLS, "the fills on {name}"); + assert_eq!( + [fills, updates, copies], + [recorded, by_transfers, COPIES], + "the fills' and copies' calls replayed on {name}" + ); + assert!(ends >= 1, "the replay ended no command buffer on {name}"); + }); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs index 7ad540921..23f1a7454 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs @@ -1145,10 +1145,11 @@ fn other_threads_cpu() -> Option> { /// The groups of the process's other threads [`other_threads_cpu`] reports: the runtime's by the /// prefix of their names, and the rest. -const THREAD_GROUPS: [(&str, &str); 3] = [ +const THREAD_GROUPS: [(&str, &str); 4] = [ ("scheduler", "metal2vulkan-sc"), ("queue waits", "metal2vulkan-qu"), ("handlers", "metal2vulkan-ha"), + ("recorder", "metal2vulkan-re"), ]; /// What the other threads spent between `before` and `after` ([`other_threads_cpu`]), by diff --git a/crates/metal2vulkan-validation/src/runtime_lane/hidden_depth.rs b/crates/metal2vulkan-validation/src/runtime_lane/hidden_depth.rs index cfba10013..587c1145e 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/hidden_depth.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/hidden_depth.rs @@ -50,7 +50,7 @@ use super::render_state::{rows, stencil, validated, Pipe, Probe, EMPTY, FULL, PASS, WHITE}; use metal2vulkan::metal::{CompareFunction, PixelFormat, PrimitiveType, StencilOperation}; -use metal2vulkan_runtime::{Buffer, Error, RenderCommandEncoder, RuntimeGap, Viewport}; +use metal2vulkan_runtime::{Buffer, Error, RenderCommandEncoder, RuntimeGap, Viewport, WorkCounts}; /// A body of draws: the probe, the encoder, the depth buffers it keeps, and what makes a pipe /// fit the pass (the formats of the attachments the comparing pass has). @@ -207,7 +207,9 @@ fn a_draw_without_its_depth_or_stencil_attachment_tests_metal_s_hidden_ones() { /// probe's color-only pass), it began none and none ends (`render/inline_first.rs`). Either way /// every command buffer the pass's pool handed out ended, the pool goes back to the device's /// spares unreset, and no spare is reset as it is taken again -/// (`WorkCounts::spare_command_pools_reset`). +/// (`WorkCounts::spare_command_pools_reset`). The recorder replays every command buffer the +/// passes' command buffers began but those unused ones, which nothing executes +/// (`CommandBuffer::give_up_raw`, [`replayed_but_unrun`]). #[test] fn a_first_draw_s_instance_ends_the_one_it_replaces() { const PASSES: u64 = 4; @@ -229,9 +231,11 @@ fn a_first_draw_s_instance_ends_the_one_it_replaces() { let ended = after.unrun_instances_ended - before.unrun_instances_ended; let taken = after.spare_command_pools_taken - before.spare_command_pools_taken; let reset = after.spare_command_pools_reset - before.spare_command_pools_reset; + let (replayed, deferred) = replayed_but_unrun(&before, &after); eprintln!( "unrun instances on {}, visibility buffer {}: {PASSES} passes ended {ended} replaced \ - instances; {taken} spare pools taken, {reset} of them reset", + instances; {taken} spare pools taken, {reset} of them reset; {replayed} of {deferred} \ + deferred command buffers begun replayed", probe.device.name(), visibility.is_some(), ); @@ -240,10 +244,35 @@ fn a_first_draw_s_instance_ends_the_one_it_replaces() { "a replaced instance a pass whose first began its secondary" ); assert_eq!(reset, 0, "spare pools reset as taken"); + assert_eq!( + replayed, + deferred - ended, + "command buffers replayed of those begun deferred, the replaced instances' not" + ); } super::render_state::quiet(probe, &messages); } +/// The command buffers the recorder replayed between `before` and `after`, by its thread or by +/// threads that submit, and those begun that record deferred where the device routes its commands +/// to the recorder (`recorder`): every one an encoder began (its own, a segment's, one it went on +/// in, a draws' secondary), not those a batch's submission records as it is submitted, the +/// barrier command buffers kept, or the device's own submissions', which record straight into +/// the driver's. +pub(super) fn replayed_but_unrun(before: &WorkCounts, after: &WorkCounts) -> (u64, u64) { + let replayed = |c: &WorkCounts| c.command_buffers_replayed + c.command_buffers_replayed_inline; + let deferred = |c: &WorkCounts| { + c.command_buffers_begun_encoders + + c.command_buffers_begun_segments + + c.command_buffers_begun_continuations + + c.command_buffers_begun_secondaries + }; + ( + replayed(after) - replayed(before), + deferred(after) - deferred(before), + ) +} + /// A pass with a depth attachment of its own whose draw uses the stencil it lacks, and one with a /// stencil attachment whose draw uses depth, are refused: the hidden aspect beside an attachment /// of the other is not built. diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 48f1e9828..2293e905c 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -330,6 +330,12 @@ driver's. Each is open work. each timed command buffer writes: on an M4 a bare barrier took 14.7 µs alone and 167.8 µs with them. `DeviceOptions::gpu_times_from_host` (off by default, announced) answers GPU times from the host clock and spares them. +- **A texture made while a batch is submitted waits for that submission on a device without + `descriptorBindingUpdateUnusedWhilePending`** (the `vk12-floor` profile), where its making + registers a first move (a `Private` texture's): the registration takes the first-move order, + which the batch holds from its take until its `vkQueueSubmit` returns. Metal's making waits for + nothing. Elsewhere the batch holds the texture slots' writes instead + (`WorkCounts::heap_slot_writes_deferred`, which stays 0 on such a device). - **A shadow's copy back covers every texel it moves, where no merge serves it**: an image's shadow (a view of a layout the device's views do not reinterpret), a turned texture's and a two-plane one's. After a pass that draws, that is every texel inside the draws' scissors, where