diff --git a/crates/metal2vulkan-conformance/README.md b/crates/metal2vulkan-conformance/README.md index a3c73fbd6..33f81aea0 100644 --- a/crates/metal2vulkan-conformance/README.md +++ b/crates/metal2vulkan-conformance/README.md @@ -296,8 +296,7 @@ random on honest work. Each reason is written at its site in `cost.rs` with the - one whose readings **moved** between the measurement's own rounds, which the record keeps as the range it was seen in; -- one that says **which thread arrived first** — which thread replayed a deferred command buffer, - when one of our background threads ran, and everything on the asynchronous release path, whose +- one that says **which thread arrived first** — when one of our background threads ran, and everything on the asynchronous release path, whose counts may land in a later case's window; - one that is a reading of **what was alive at that instant** rather than work a case did; - one that says an object was **found already made** rather than made, or that a making was diff --git a/crates/metal2vulkan-conformance/src/cost.rs b/crates/metal2vulkan-conformance/src/cost.rs index 8e961957c..3500dbee4 100644 --- a/crates/metal2vulkan-conformance/src/cost.rs +++ b/crates/metal2vulkan-conformance/src/cost.rs @@ -442,7 +442,7 @@ const POOLED: &str = "an object made because no spare was free, where a spare co /// replays of a larger case set — which reads like a regression and is not one. See [`BORROWED`]. /// `slot_returns` beside it stays gated: it counts work items, one a command buffer, and has held /// still alone and in both case sets. -const RACY: [(&str, &str); 33] = [ +const RACY: [(&str, &str); 32] = [ ("fences_made", POOLED), // What is alive, parked or waiting at the instant the counts were read. ("memory_blocks_live", INSTANTANEOUS), @@ -493,11 +493,6 @@ const RACY: [(&str, &str); 33] = [ "whether a transition had to wake a thread or found one already running, which is a \ question about timing rather than about the case's work", ), - ( - "command_buffers_replayed", - "which thread replayed a deferred command buffer: the recorder's, or one that reached it \ - first. Their total is command_buffers_deferred, which is gated, so nothing is lost", - ), ( "object_churn.", "the release path, which runs on whichever thread drops the object. A release may land in \ diff --git a/crates/metal2vulkan-conformance/src/tests.rs b/crates/metal2vulkan-conformance/src/tests.rs index 7d17deb28..1933f0860 100644 --- a/crates/metal2vulkan-conformance/src/tests.rs +++ b/crates/metal2vulkan-conformance/src/tests.rs @@ -4708,8 +4708,6 @@ fn re_recording_a_metal_answer_keeps_the_cost_record() { fn a_count_that_says_which_thread_arrived_first_is_never_gated() { use crate::cost::racy; for count in [ - "command_buffers_replayed", - "command_buffers_replayed_inline", "object_churn.images_evicted", "object_churn.vk_images_destroyed", "object_churn.vk_images_made", @@ -4745,7 +4743,6 @@ fn a_count_that_says_which_thread_arrived_first_is_never_gated() { // selection is a question only the contrast run answers, and // `a_count_the_selection_decides_is_reported_and_not_gated` holds that half. for count in [ - "command_buffers_deferred", "command_buffers_submitted", "queue_submissions", "commands_replayed.cmd_draw", @@ -4840,8 +4837,8 @@ fn a_count_that_says_which_thread_arrived_first_is_never_gated() { contrasted: None, degraded: Vec::new(), bounds: [ - ("command_buffers_replayed_inline".to_owned(), 1), - ("command_buffers_deferred".to_owned(), 1), + ("wakes_spared".to_owned(), 1), + ("command_buffers_submitted".to_owned(), 1), ] .into_iter() .collect(), @@ -4866,20 +4863,20 @@ fn a_count_that_says_which_thread_arrived_first_is_never_gated() { // The race going over its bound is not a failure. assert_eq!( judge( - "WorkCounts {\n command_buffers_deferred: 1,\n \ - command_buffers_replayed_inline: 9,\n}" + "WorkCounts {\n command_buffers_submitted: 1,\n \ + wakes_spared: 9,\n}" ) .word(), "within" ); // The total going over it is. let over = judge( - "WorkCounts {\n command_buffers_deferred: 2,\n \ - command_buffers_replayed_inline: 1,\n}", + "WorkCounts {\n command_buffers_submitted: 2,\n \ + wakes_spared: 1,\n}", ); assert_eq!(over.word(), "over"); assert!( - over.to_string().contains("command_buffers_deferred"), + over.to_string().contains("command_buffers_submitted"), "{over}" ); // And a racy count the record never bounded at all is still not gated, which is the case that diff --git a/crates/metal2vulkan-runtime/examples/host_ab/main.rs b/crates/metal2vulkan-runtime/examples/host_ab/main.rs index 5d4fea1a8..84b9b57a0 100644 --- a/crates/metal2vulkan-runtime/examples/host_ab/main.rs +++ b/crates/metal2vulkan-runtime/examples/host_ab/main.rs @@ -442,12 +442,8 @@ fn child(side: &str, options: &Options) { c.batches_with_four_or_more_pending, ); eprintln!( - "runtime replays: command_buffers_replayed {} command_buffers_replayed_inline {} \ - scheduler_sleeps {} scheduler_wakes_commit {}", - c.command_buffers_replayed, - c.command_buffers_replayed_inline, - c.scheduler_sleeps, - c.scheduler_wakes_commit, + "runtime scheduler: scheduler_sleeps {} scheduler_wakes_commit {}", + c.scheduler_sleeps, c.scheduler_wakes_commit, ); eprintln!( "runtime submit stalls: idle_submits {} submit_stalls_idle {} \ @@ -459,7 +455,7 @@ fn child(side: &str, options: &Options) { c.submits_behind_idle_stalls, c.wait_behind_idle_stall_longest_nanos, ); - eprintln!("runtime commands replayed: {:?}", c.commands_replayed); + eprintln!("runtime commands recorded: {:?}", c.commands_replayed); eprintln!( "runtime notices: {} (bound notices made {}), other messages heard {}", runtime::NOTICES.load(std::sync::atomic::Ordering::Relaxed), diff --git a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs index fd68bc02d..77e31b7b1 100644 --- a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs +++ b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs @@ -1424,12 +1424,6 @@ impl Gpu for Runtime { "replayed_cmd_draw_mesh_tasks_indirect", replayed.cmd_draw_mesh_tasks_indirect, ), - ("command_buffers_deferred", c.command_buffers_deferred), - ("command_buffers_replayed", c.command_buffers_replayed), - ( - "command_buffers_replayed_inline", - c.command_buffers_replayed_inline, - ), ("copy_regions_split", c.copy_regions_split), ("spare_command_pools_taken", c.spare_command_pools_taken), ("spare_command_pools_reset", c.spare_command_pools_reset), diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 0ea099c9d..25cc20247 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -363,19 +363,6 @@ 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 { /// Whether the GPU's writes to the buffer are dropped (`read_only_view.rs`). pub(super) fn drops_writes(&self) -> bool { @@ -434,11 +421,6 @@ impl HostCell { HOST_CELLS_MOVED.fetch_add(1, Ordering::AcqRel); lay }; - // The replays that hold the pages it lay in go first, so the caller lets go of them last, - // as it would without them (`HostPages::let_go_by_buffer`). - if let Lying::In(pages) = &lay { - pages.let_go_by_buffer(); - } lay } @@ -653,13 +635,6 @@ 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, - /// Their buffer let go of them: its release, rebind or detach (pages lie in one buffer, - /// once) ([`let_go_by_buffer`](Self::let_go_by_buffer)). - let_go: AtomicBool, /// The caller's log of the writes to them, where it gave one with their memory /// (`HostMemory::with_dirty_pages`, `dirty_pages.rs`). dirty: OnceLock>, @@ -677,8 +652,6 @@ impl HostPages { import, release: OnceLock::new(), listed: AtomicUsize::new(0), - replay_holds: Arc::new(AtomicUsize::new(0)), - let_go: AtomicBool::new(false), dirty: OnceLock::new(), } } @@ -698,50 +671,6 @@ impl HostPages { self.dirty.get() } - /// 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)). - pub(super) fn let_go_by_replay(pages: Arc) -> Option { - let holds = Arc::clone(&pages.replay_holds); - 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 - /// at the call that lets go of them last, as it does with commands recorded as they are - /// encoded (`recorder`). Nothing where none holds them. - /// - /// Against a commit on another thread whose replays come to hold them, each marks its side - /// and then reads the other's, sequentially consistent, so at least one sees the other: - /// this finds the commit's hold, and its replays, queued before the commit read the mark, - /// and replays them here; or the commit finds the mark and replays them itself, letting go - /// of the pages where it lets go of them without a recorder (`Replays::commit`). - 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()); - } - } - /// Keep `objects`, over these pages, until they go. pub(super) fn park(&self, objects: impl Any + Send + Sync) { lock(&self.parked).push(Box::new(objects)); @@ -831,33 +760,6 @@ 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 @@ -1507,17 +1409,6 @@ 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 96c5ecd55..320c37598 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs @@ -69,7 +69,6 @@ use super::checks::metal_submissions; use super::rebound_use::{ReboundAt, ReboundUse, Recording}; use super::{write_fields, CommandBufferShared, Resident, State}; -use crate::buffer::HostPages; use crate::error::{internal, CommandBufferError, Error}; use crate::live_buffers::LiveTable; use crate::rebind::{SubmittedHolds, Submitting}; @@ -183,11 +182,9 @@ 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. - /// 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>) { + pub(super) fn wait_for_submission(&mut self, listing: Listing) { for record in &mut self.ended { - record.taken.wait(held); + record.taken.wait(); } let segments = self .recorded @@ -195,7 +192,7 @@ impl State { .flat_map(|part| part.segments.iter_mut()) .filter_map(|segment| segment.recorded.as_mut()); for done in segments { - done.taken.wait(held); + done.taken.wait(); } 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 035c7c3d1..409a9db63 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -89,7 +89,6 @@ use super::predication::{Event, Predication}; use super::program_objects; use super::queue::Slot; use super::rebind::{Holds, SubmittedHolds, Taken}; -use super::recorder::{self, Replays}; use super::render::EndInFlight; use super::replay::Replay; use super::residency::Residency; @@ -260,7 +259,7 @@ pub(super) struct CommandBufferShared { /// where they are every one the pool handed out and it completed, it gives the pool back /// with none recording (`spares.rs`). raws_ended: AtomicU64, - /// Its kernel times, apart from the state, which the scheduler holds while it replays and + /// Its kernel times, apart from the state, which the scheduler holds while it records and /// submits a batch: a read waits for neither (`gpu_time.rs`). kernel: KernelTimes, /// Its status as `status` answers it, apart from the state for the same reason: each @@ -534,9 +533,6 @@ 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 pool of a predicated loop's check while it records again the work its laying left /// apart (`rerun.rs`): every `VkCommandBuffer` the command buffer hands out meanwhile comes /// from it, and goes back to it for the next run again. @@ -1764,19 +1760,11 @@ 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, replays) = { - let mut state = lock(&self.state); - (state.pool.take(), state.replays.take()) - }; + let pool = lock(&self.state).pool.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); - } } } @@ -1810,7 +1798,6 @@ impl CommandBuffer { called_over_mutable_map: false, committing: false, pool: None, - replays: None, rerun_pool: None, recorded: Vec::new(), tail: None, @@ -2091,12 +2078,12 @@ impl CommandBuffer { Ok(residency.with_live(live)) } - /// 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 + /// An encoder's primary command buffer, from this command buffer's pool, made on first use: + /// the encoder records into it at each call, on the program's thread. 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) + .allocate_encoder(state, vk::CommandBufferLevel::PRIMARY) } /// An encoder's own primary `VkCommandBuffer` from this command buffer's pool, and whether it @@ -2129,29 +2116,22 @@ impl CommandBuffer { /// 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. + /// pass that changes nothing): it ends ([`end_raw`](Self::end_raw)), so its pool goes back + /// to the device's spares unreset (`spares.rs`). Nothing executes it, so the GPU does the + /// same work and every byte it writes is the same. /// /// # 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`. + /// A secondary command buffer (a render encoder's draws), 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_deferred(state, vk::CommandBufferLevel::SECONDARY) + .allocate_encoder(state, vk::CommandBufferLevel::SECONDARY) } /// `addScheduledHandler:`: call `handler` once the command buffer is scheduled, on one of the @@ -2881,18 +2861,10 @@ impl CommandBuffer { // 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`). - // 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()), - } + state.wait_for_submission(listing); // 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 - // (`steps_hold`). Only once its replays hold the pages, so a rebind finds them held. + // (`steps_hold`). if steps_hold { let held = &mut *state; let kept = held @@ -3893,8 +3865,7 @@ 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) }; - // A deferred one is none of its pool's: its replay ends its own (`recorder`). - if ended.is_ok() && !recorder::is_deferred(raw) { + if ended.is_ok() { self.raws_ended.fetch_add(1, Ordering::Relaxed); } ended @@ -3916,13 +3887,10 @@ 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)). One of a predicated loop's check's pool while it records - /// again (`rerun.rs`). - fn allocate_deferred( + /// An encoder's command buffer of `level`, a driver's the encoder records into at each call: + /// one from this command buffer's pool ([`allocate`](Self::allocate)), or one of a + /// predicated loop's check's pool while it records again (`rerun.rs`). + fn allocate_encoder( &self, state: &mut State, level: vk::CommandBufferLevel, @@ -3930,33 +3898,7 @@ impl CommandBufferShared { if let Some(pool) = &state.rerun_pool { return hand_out(&self.device, &mut lock(pool), level); } - 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) + self.allocate(state, level) } /// A `VkCommandBuffer` of `level` from this command buffer's pool, made on first use: a @@ -3972,12 +3914,8 @@ impl CommandBufferShared { hand_out(&self.device, self.pool(state)?, level) } - /// [`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`). + /// [`CommandBuffer::encoder_primary`]. 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)); } @@ -4611,17 +4549,6 @@ 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); - } - } state.unplaced(); parked = state.parked > 0; } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 6d46aaa1f..d5b36ba9f 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -54,9 +54,7 @@ use super::rebound_use::Unlogged; use super::{lock, CommandBuffer, CommandBufferShared, State}; -use crate::buffer::HostPages; use crate::deferred::{Deferred, StepInputs}; -use crate::device::functions::Vk; use crate::encoder::{RecordedSegment, Replayed, ReplayedPart, Segment}; use crate::pipeline::budget::Urgency; use crate::replay::Replay; @@ -175,10 +173,9 @@ impl CommandBufferShared { } }; // What a refused splice held goes after the lock. - let vk = device.shared().vk(); let spliced_now = { let mut state = lock(&self.state); - let spliced = state.splice_replay(vk, at, replayed, residency); + let spliced = state.splice_replay(at, replayed, residency); if let (Ok(()), Some(predication)) = (&spliced, predication) { state.predication.take_checks(predication); } @@ -264,8 +261,7 @@ impl CommandBufferShared { counts.reencode_refused(); continue; }; - let vk = device.shared().vk(); - let put = lock(&self.state).splice_segment(vk, place, recorded, inputs); + let put = lock(&self.state).splice_segment(place, recorded, inputs); match put { Ok(()) => counts.segment_recorded_again(), Err(unspliced) => { @@ -314,12 +310,9 @@ impl State { /// `replayed` back, where its place holds other parts than the encoding again's, or a segment /// but one whose pipelines are being made (which goes, the encoding again having left one of /// its own in its place) or work its commit recorded on the GPU alone, or its group was - /// submitted, or the - /// command buffer completed. Its replays hold what its commands took with `device`, the - /// device's functions (`Replays::hold`). + /// submitted, or the command buffer completed. pub(super) fn splice_replay( &mut self, - device: &Vk, at: usize, replayed: Replayed, residency: Option, @@ -358,21 +351,13 @@ impl State { heaps, } = replayed; // Held weakly until its group's submission, as the commit held what the first recording - // and its segments 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). - let mut wait = |pages: &mut Vec>| { - taken.wait(pages); - let segments = (replayed_parts.iter_mut()) - .flat_map(|part| part.segments.iter_mut()) - .filter_map(|segment| segment.recorded.as_mut()); - for done in segments { - done.taken.wait(pages); - } - }; - match self.replays.clone() { - Some(replays) => drop(replays.hold(device, wait)), - None => wait(&mut Vec::new()), + // and its segments took. + taken.wait(); + let segments = (replayed_parts.iter_mut()) + .flat_map(|part| part.segments.iter_mut()) + .filter_map(|segment| segment.recorded.as_mut()); + for done in segments { + done.taken.wait(); } let first = self.ended[at].executions.clone(); for (&part, replayed) in parts.iter().zip(replayed_parts) { @@ -436,15 +421,13 @@ impl State { /// Put `recorded`, segment `at` of part `part` recorded again on the GPU alone, in its place /// before the first submission, with `inputs`, what its host step needs now: what its - /// commands took held weakly until the first submission, as the commit holds them (by its - /// replays too, with `device`, the device's functions: `Replays::hold`). What the first + /// commands took held weakly until the first submission, as the commit holds them. What the first /// recording retained, its executions and its host step's inputs stay retained; its /// `VkCommandBuffer`s go with the pool unsubmitted, and what its commands took, held weakly, /// goes. Refused, changing nothing and giving `recorded` and `inputs` back, where the place /// holds no such segment, or the command buffer was submitted. pub(super) fn splice_segment( &mut self, - device: &Vk, (part, at): (usize, usize), mut recorded: RecordedSegment, inputs: StepInputs, @@ -456,10 +439,7 @@ impl State { if !fits { return Err(Box::new((recorded, inputs))); } - match self.replays.clone() { - Some(replays) => drop(replays.hold(device, |pages| recorded.taken.wait(pages))), - None => recorded.taken.wait(&mut Vec::new()), - } + recorded.taken.wait(); let segment = &mut self.recorded[part].segments[at]; let first = segment.recorded.replace(recorded); let before = segment.inputs.replace(inputs); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs index f11126a1c..32739ffd4 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs @@ -384,8 +384,7 @@ impl LoopCheck { } } - /// Submit `raws` (ended, in order; deferred ones resolved) on `buffer`'s `VkQueue` and wait - /// for them to complete. + /// Submit `raws` (ended, in order) on `buffer`'s `VkQueue` and wait for them to complete. fn submit(&self, buffer: &CommandBufferShared, raws: &[vk::CommandBuffer]) -> Result<(), Stop> { let device = &buffer.device; let Some(busy) = exit_guard::enter() else { @@ -393,24 +392,12 @@ impl LoopCheck { }; let shared = device.shared(); let raw = shared.vk(); - let mut reals = Vec::with_capacity(raws.len()); - for &handle in raws { - // SAFETY: each ended, its command buffer committed (the laying's, its batch submitted, - // which replayed it); inside a section. - match unsafe { crate::recorder::resolve(raw, handle) } { - Ok(real) => reals.push(real), - Err(error) => { - let error = recording_error(device, crate::error::vulkan(error)); - return Err(Stop::Failed(error)); - } - } - } // SAFETY: the device's fences, inside a section. let fence = unsafe { shared.fences.take(raw) } .map_err(|error| Stop::Failed(submission_error(device, error)))?; let queue = buffer.queue.vk_queue(); - let submits = [vk::SubmitInfo::default().command_buffers(&reals)]; - shared.counts.queue_submitted(1, reals.len()); + let submits = [vk::SubmitInfo::default().command_buffers(raws)]; + shared.counts.queue_submitted(1, raws.len()); // SAFETY: the `VkQueue` is used under its lock; each command buffer was begun to be // submitted again (the laying's) or recorded for this submission alone (a run again's), // ended, and is in no pending submission: the laying's batch completed before the check's diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index 6ab175dd2..3e0887d84 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -546,18 +546,6 @@ impl CommandBufferShared { exit_uses.push(image.transition_use()); } } - // Its encoders' deferred command buffers replayed now, where the recorder's thread has - // not yet (`recorder`), waiting for a replay in progress: before the first work's take, - // which holds the submissions' order until the submission is made, and which a new - // resource's registration waits for where registrations wait for their place - // (`texture/first_move.rs`). A texture made meanwhile so waits for no replay. Each keeps - // its handle as encoded until the submission (below), which finds it replayed. - for buffer in encoders.iter().flat_map(|recorded| &recorded.raws) { - // SAFETY: each ended, and its command buffer committed; inside the scheduler's - // section. - unsafe { crate::recorder::resolve(raw, *buffer) } - .map_err(|error| recording_error(device, crate::error::vulkan(error)))?; - } // The new resources' first work, before every command (`texture/first_move.rs`), given // back if the submission is not made. A batch's commands may reach every texture // unnamed, so it takes every move, those of images bound to host pages among them, whose @@ -891,16 +879,6 @@ impl CommandBufferShared { false => work.insert(0, lead), } } - // Its deferred command buffers go as their replays (`recorder`), after every check above - // that compares them as encoded: its encoders', replayed before the first work's take - // (above); the barriers recorded since, replayed here where the recorder's thread has - // not yet reached them. - 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); @@ -1174,8 +1152,10 @@ impl CommandBufferShared { Ok(buffer) } - /// Record the scrub segments of encoders `range` (`Deferred::SparseScrub`), which their batch's - /// submission records with the mappings it applied. + /// Record the segments of encoders `range` that their batch's submission records: the + /// scrubs (`Deferred::SparseScrub`), with the mappings it applied, and the gated copies in + /// (`Deferred::GatedCopyIn`), with the regions their logs say changed since the commit's + /// stamp, published by now. fn record_scrubs( &self, state: &mut State, @@ -1184,19 +1164,34 @@ impl CommandBufferShared { let mut scrubs = Vec::new(); for (encoder, recorded) in state.recorded[range.clone()].iter().enumerate() { for (at, segment) in recorded.segments.iter().enumerate() { - if let (Deferred::SparseScrub(scrub), None) = (&segment.work, &segment.recorded) { - scrubs.push((range.start + encoder, at, Arc::clone(scrub))); + let at_submission = matches!( + segment.work, + Deferred::SparseScrub(_) | Deferred::GatedCopyIn(_) + ); + if at_submission && segment.recorded.is_none() { + scrubs.push((range.start + encoder, at, segment.work.clone())); } } } let device = &self.device; - for (encoder, at, scrub) in scrubs { + for (encoder, at, work) in scrubs { let raw = self.record_raw(state, |state, buffer| { - // SAFETY: the command buffer is recording; the texture is live (its encoder's - // command buffer holds it), in `GENERAL`, and its batch's updates applied. - let held = unsafe { scrub.record(device, buffer) }?; - if !held.is_empty() { - state.retained.push(Box::new(held)); + match &work { + // SAFETY: the command buffer is recording; the texture is live (its encoder's + // command buffer holds it), in `GENERAL`, and its batch's updates applied. + Deferred::SparseScrub(scrub) => { + let held = unsafe { scrub.record(device, buffer) }?; + if !held.is_empty() { + state.retained.push(Box::new(held)); + } + } + // SAFETY: the command buffer is recording, outside a render pass; the + // shadowed texture is live (its encoder's command buffer holds it), its + // image in `GENERAL`. + Deferred::GatedCopyIn(copy) => unsafe { + copy.record(device.shared().vk(), buffer) + }, + _ => {} } Ok(()) })?; diff --git a/crates/metal2vulkan-runtime/src/deferred.rs b/crates/metal2vulkan-runtime/src/deferred.rs index 4874bb94f..79eb6255f 100644 --- a/crates/metal2vulkan-runtime/src/deferred.rs +++ b/crates/metal2vulkan-runtime/src/deferred.rs @@ -16,6 +16,7 @@ use super::pending_dispatch::PendingDispatch; use super::pipeline::ComputePipelineState; use super::render::DeferredPass; use super::resource::ResourceKey; +use super::shadow::GatedCopyIn; use super::sparse::emulated::Scrub; use super::tracker::Summary; use super::Device; @@ -34,6 +35,10 @@ pub(super) enum Deferred { /// (`sparse/emulated.rs`): neither `commit` nor a host step records it, but its batch's /// submission, with the mappings the batch applied. SparseScrub(Arc), + /// A shadow's copy in over host pages a consumer logs, whose regions the log decides: as with + /// a scrub, neither `commit` nor a host step records it, but its batch's submission, once the + /// commit's stamp is published (`shadow::GatedCopyIn`, `dirty_pages.rs`). + GatedCopyIn(Arc), /// A render pass that executes render commands (`render/executions.rs`). RenderPass(Arc), /// A compute encoder's dispatch whose pipelines were being made (`pending_dispatch.rs`). @@ -99,6 +104,7 @@ impl Deferred { (Deferred::Execute(a), Deferred::Execute(b)) => Arc::ptr_eq(a, b), (Deferred::Dispatch(a), Deferred::Dispatch(b)) => Arc::ptr_eq(a, b), (Deferred::SparseScrub(a), Deferred::SparseScrub(b)) => Arc::ptr_eq(a, b), + (Deferred::GatedCopyIn(a), Deferred::GatedCopyIn(b)) => Arc::ptr_eq(a, b), (Deferred::RenderPass(a), Deferred::RenderPass(b)) => Arc::ptr_eq(a, b), (Deferred::Pending(a), Deferred::Pending(b)) => Arc::ptr_eq(a, b), (Deferred::Loop(a), Deferred::Loop(b)) => Arc::ptr_eq(a, b), @@ -111,14 +117,15 @@ impl Deferred { /// executes render commands is not: its shadowed textures are its encoder's, copied in /// before it and back as the encoder ends (`render/shadows.rs`). /// Nor is a dispatch whose pipelines were being made: its shadowed textures were copied in - /// at the dispatch, and its writes are its encoder's to copy back. + /// at the dispatch, and its writes are its encoder's to copy back. Nor is a gated copy in, + /// which is one of the encoder's shadow copies. pub(super) fn leaves_shadows(&self) -> bool { match self { Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) | Deferred::Loop(_) => true, - Deferred::RenderPass(_) | Deferred::Pending(_) => false, + Deferred::RenderPass(_) | Deferred::Pending(_) | Deferred::GatedCopyIn(_) => false, } } @@ -136,7 +143,7 @@ impl Deferred { execute.icb.gpu_written() || execute.indirect() || execute.predicated() } Deferred::Dispatch(_) | Deferred::Loop(_) => true, - Deferred::SparseScrub(_) | Deferred::Pending(_) => false, + Deferred::SparseScrub(_) | Deferred::GatedCopyIn(_) | Deferred::Pending(_) => false, Deferred::RenderPass(pass) => pass.gpu_written(), } } @@ -221,7 +228,7 @@ impl Deferred { Deferred::Dispatch(_) => Err(internal( "an indirect dispatch recorded before the work it waits for completed", )), - Deferred::SparseScrub(_) => Ok(Prepared { + Deferred::SparseScrub(_) | Deferred::GatedCopyIn(_) => Ok(Prepared { recorded: None, for_good: false, inputs: StepInputs::None, @@ -336,6 +343,7 @@ impl Deferred { .map(|recorded| (recorded, StepInputs::RenderPass))), Deferred::Dispatch(_) | Deferred::SparseScrub(_) + | Deferred::GatedCopyIn(_) | Deferred::Pending(_) | Deferred::Loop(_) => Ok(None), } @@ -381,6 +389,7 @@ impl Deferred { } Deferred::Dispatch(dispatch) => dispatch.record(command_buffer), Deferred::SparseScrub(_) => Err(internal("a sparse scrub's host step")), + Deferred::GatedCopyIn(_) => Err(internal("a gated copy in's host step")), Deferred::RenderPass(pass) => pass.record(command_buffer, true), Deferred::Pending(dispatch) => dispatch.record(command_buffer), Deferred::Loop(check) => check.step(command_buffer), @@ -398,6 +407,7 @@ impl Deferred { Deferred::Execute(execute) => execute.outgrown(), Deferred::Dispatch(_) | Deferred::SparseScrub(_) + | Deferred::GatedCopyIn(_) | Deferred::Pending(_) | Deferred::Loop(_) => false, } @@ -413,6 +423,7 @@ impl Deferred { Deferred::RenderPass(pass) => pass.rewritten(), Deferred::Dispatch(_) | Deferred::SparseScrub(_) + | Deferred::GatedCopyIn(_) | Deferred::Pending(_) | Deferred::Loop(_) => false, } @@ -426,6 +437,7 @@ impl Deferred { Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) + | Deferred::GatedCopyIn(_) | Deferred::RenderPass(_) | Deferred::Pending(_) => false, } @@ -439,6 +451,7 @@ impl Deferred { Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) + | Deferred::GatedCopyIn(_) | Deferred::Loop(_) => false, } } @@ -460,6 +473,7 @@ impl Deferred { Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) + | Deferred::GatedCopyIn(_) | Deferred::Loop(_) => false, } } @@ -476,6 +490,7 @@ impl Deferred { Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) + | Deferred::GatedCopyIn(_) | Deferred::Loop(_) => false, } } @@ -492,6 +507,7 @@ impl Deferred { Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) + | Deferred::GatedCopyIn(_) | Deferred::Loop(_) => None, } } @@ -504,6 +520,7 @@ impl Deferred { Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) + | Deferred::GatedCopyIn(_) | Deferred::Loop(_) => {} } } @@ -517,6 +534,7 @@ impl Deferred { Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) + | Deferred::GatedCopyIn(_) | Deferred::Loop(_) => {} } } @@ -526,7 +544,10 @@ impl Deferred { match self { Deferred::Execute(execute) => indirect_execute::degrade_host_replay(device, execute), Deferred::Dispatch(dispatch) => dispatch.degrade(device), - Deferred::SparseScrub(_) | Deferred::Pending(_) | Deferred::Loop(_) => {} + Deferred::SparseScrub(_) + | Deferred::GatedCopyIn(_) + | Deferred::Pending(_) + | Deferred::Loop(_) => {} Deferred::RenderPass(pass) => pass.degrade(device), } } diff --git a/crates/metal2vulkan-runtime/src/device/functions.rs b/crates/metal2vulkan-runtime/src/device/functions.rs index be874eac6..3008d6604 100644 --- a/crates/metal2vulkan-runtime/src/device/functions.rs +++ b/crates/metal2vulkan-runtime/src/device/functions.rs @@ -20,7 +20,7 @@ //! every caller's stages and accesses hold as they are (`WorkCounts::copy_regions_split`). A //! driver's recording CPU for one region may grow with its size at some sizes and not at others: //! on ANV, Mesa 26.2.4, on the UHD 770 (`row_copies::span_copy_cost` in the validation crate's -//! runtime lane, the recorder thread's CPU time a frame of one blit of one region) 8,294,411 bytes +//! runtime lane, the recording thread's CPU time a frame of one blit of one region) 8,294,411 bytes //! (a prime) took 28-40 ms and 6.0 ms of GPU time, 8,294,576 (16 times a prime) 1.5-2.4 ms and //! 3,110,608 (16 times a prime) 0.74-0.91 ms, against 0.006-0.035 ms for 8,294,400 (2025 times //! 4 KiB); split so, 8,294,411 bytes took 0.018-0.060 ms and 0.64-0.76 ms of GPU time. RADV @@ -42,7 +42,7 @@ use std::sync::Arc; /// The bytes past which a `vkCmdCopyBuffer` region whose size is no multiple of [`SPLIT_UNIT`] is /// two (the module docs). Measured no slower up to it: on ANV, Mesa 26.2.4, on the UHD 770 one -/// region of 16,381 bytes (a prime) took 0.016-0.036 ms of the recorder's CPU, as 4,093 and 4,095 +/// region of 16,381 bytes (a prime) took 0.016-0.036 ms of the recording CPU, as 4,093 and 4,095 /// bytes did. const SPLIT_ABOVE: u64 = 16 * 1024; diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index a47d32ea7..fce021398 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -83,7 +83,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::recorder::{Command, MeshDraws, Slot}; use crate::release; use ash::vk::{self, Handle}; use functions::{Functions, Vk}; @@ -336,11 +336,9 @@ pub(super) struct DeviceShared { /// 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, + /// let go of after `vkDestroyDevice` (it drops after the teardown, `Drop`). Its counts are + /// `WorkCounts::commands_replayed`. + recording: 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>, @@ -597,10 +595,12 @@ impl DeviceShared { Arc::clone(&self.functions) } - /// 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) + /// The commands recorded through its slot so far, by kind (`recorder`); none where it took + /// no slot. + pub(crate) fn commands_recorded(&self) -> crate::CommandsReplayed { + self.recording + .as_ref() + .map_or_else(Default::default, Slot::counts) } /// `vkAllocateCommandBuffers` of `info`: the loader serves it and reads the device's loader @@ -1706,13 +1706,6 @@ impl Device { 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, @@ -1832,8 +1825,7 @@ impl Device { push_descriptor, pushes_after_pipeline_binds, color_write_masks, - _recording: recording, - recorder, + recording, snapshot_fallbacks: Mutex::new(Vec::new()), reader_sizes: Mutex::new(Default::default()), gpu_pools, @@ -1926,12 +1918,6 @@ impl Device { } } 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()); - // Woken by the scheduler's thread for what a commit queued (`recorder`). - (device.shared().scheduler).wake_recorder(Arc::clone(recorder)); - } // The verdicts of its check of textures over host pages, where a record holds them. device.recall_in_place_checks(); device.degrade_argument_buffers_unread(); diff --git a/crates/metal2vulkan-runtime/src/device/prime.rs b/crates/metal2vulkan-runtime/src/device/prime.rs index e953806ba..144a6e594 100644 --- a/crates/metal2vulkan-runtime/src/device/prime.rs +++ b/crates/metal2vulkan-runtime/src/device/prime.rs @@ -94,7 +94,7 @@ use super::QueueSlot; /// primes: the release of a device, an instance and a messenger, the commands of a mesh draw /// and of an execution of commands the GPU generates, which take pipelines of their own kinds, and /// the layout of a linear image, of which a device need make none of any format. The first -/// release of each in the process, the first replay of each command (`recorder`), and the first +/// release of each in the process, the first call of each command in a section, and the first /// layout read in a section, registers the hook again as its section ends /// (`exit_guard::called`). pub(crate) const UNPRIMED: [Call; 9] = [ @@ -379,8 +379,8 @@ pub(crate) struct Has { } /// 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`). +/// extension, which the priming's render host step makes (a host step records them inside a +/// section). #[derive(Clone, Copy, Default)] pub(crate) struct PrimedDraws { pub(crate) dynamic: Option, @@ -1334,8 +1334,8 @@ 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 + // What an encoder records that no host step does: 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); @@ -1496,7 +1496,7 @@ impl Primer<'_> { 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`). + // the bind too. let drawn = self.drawn; if let Some(dynamic) = drawn.dynamic { (dynamic.cull_mode)(draws, vk::CullModeFlags::NONE); diff --git a/crates/metal2vulkan-runtime/src/dirty_pages.rs b/crates/metal2vulkan-runtime/src/dirty_pages.rs index 6c7428e72..78381cc63 100644 --- a/crates/metal2vulkan-runtime/src/dirty_pages.rs +++ b/crates/metal2vulkan-runtime/src/dirty_pages.rs @@ -8,9 +8,10 @@ //! //! - **The stamps.** A [`DirtyStamp`] names one of the source's publications of its log. The //! runtime asks for a stamp at a command buffer's commit ([`DirtyPages::request`]) where one of -//! its copies takes the pages again, and waits for that publication before the command -//! buffer's commands are recorded for the GPU ([`DirtyPages::wait`]). A copy then syncs to -//! that stamp: every write made after it is stamped later. +//! its copies takes the pages again, and waits for that publication as the batch that holds +//! the copy is submitted, which records the copy then (`shadow::GatedCopyIn`, +//! [`DirtyPages::wait`]). A copy then syncs to that stamp: every write made after it is stamped +//! later. //! - **The pages changed** ([`DirtyPages::changed_except`]) since the stamp a copy synced to, by //! any writer but that copy's own, are the only bytes it may lack: they are copied in, the rest //! skipped. @@ -548,8 +549,8 @@ struct Decision { stamp: DirtyStamp, } -/// A copy in of a shadow over logged host pages, its regions decided as its command buffer's -/// commands are recorded for the GPU (`recorder`): every region where its commit found no hold +/// A copy in of a shadow over logged host pages, its regions decided as its batch is submitted +/// (`shadow::GatedCopyIn`): every region where its commit found no hold /// or its log cannot say, else the rows of the pages changed since the hold. pub(crate) struct CopyInGate { log: Arc, diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index d555c1541..23269d747 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -33,6 +33,7 @@ use super::churn_counts::KeepBy; use super::command_buffer::rebound_use::Unlogged; use super::command_buffer::{recording_error, CommandBuffer}; use super::deferred::{Deferred, StepInputs}; +use super::dirty_pages::CopyInGate; use super::error::{internal, invalid, vulkan, CommandBufferError, Error, Problem}; use super::execution::Execution; use super::fresh_unwritten::FreshRead; @@ -51,7 +52,7 @@ use super::residency::{Residency, Used}; use super::resource::ResourceKey; use super::retained::Retained; use super::row_copies::RowCopies; -use super::shadow::{CopyCause, ShadowCopy, ShadowSync, ShadowUse, Step, Within}; +use super::shadow::{CopyCause, GatedCopyIn, ShadowCopy, ShadowSync, ShadowUse, Step, Within}; use super::shadow_copy_in::CopyIn; use super::shadow_merge::ShadowMerge; use super::sparse::encoder::SparseUpdate; @@ -1622,8 +1623,8 @@ impl EncoderCore { copy.uses_with(rows.as_ref()), ), }; - // A copy in over host pages a consumer logs takes the regions its gate decides as the - // command buffer replays (`dirty_pages.rs`). + // A copy in over host pages a consumer logs takes the regions its gate decides as its + // batch is submitted (`dirty_pages.rs`, `shadow::GatedCopyIn`). let gate = match &dispatched { Some(_) => None, None => copy.gate_log(&device).map(|(log, texel)| { @@ -1637,6 +1638,19 @@ impl EncoderCore { staged.extend(staged_keep(copies, i)); } let from_staging = staged.contains(&i); + if let Some(gate) = gate { + // Tracked here as the copy, recorded at its batch's submission. + let named = std::cell::Cell::new(false); + let tracked = |_: &Vk, _: vk::CommandBuffer| named.set(true); + self.shadow_command(&mut run, (stages, &uses, copy.writes_truth()), tracked); + if named.get() { + self.defer_copy_in(copy, gate); + } + if let Some(sets) = rows.and_then(RowCopies::retained) { + self.retain(sets); + } + continue; + } let kept = std::cell::Cell::new(false); let record = |device: &Vk, raw: vk::CommandBuffer| match &dispatched { // SAFETY: the encoder's command buffer is recording outside a render pass; its @@ -1651,7 +1665,7 @@ impl EncoderCore { kept.set(true); } // SAFETY: as above; the rows are the copy's own, made just now. - None => unsafe { copy.record_gated(device, raw, rows.as_ref(), gate) }, + None => unsafe { copy.record_gated(device, raw, rows.as_ref(), None) }, }; self.shadow_command(&mut run, (stages, &uses, copy.writes_truth()), record); if kept.get() { @@ -1702,6 +1716,32 @@ impl EncoderCore { self.touch(uses); } + /// Leave `copy`, a shadow's copy in over host pages a consumer logs that the encoder tracked + /// already ([`shadow_command`](Self::shadow_command)), to its batch's submission, its regions + /// decided by `gate` then (`shadow::GatedCopyIn`), the encoder going on in a new + /// `VkCommandBuffer`. Recorded whole here instead inside a predicated loop's laying, which + /// its check may submit again, or where no new `VkCommandBuffer` can be made. + fn defer_copy_in(&mut self, copy: &ShadowCopy, gate: Arc) { + let laying = (self.open.command_buffer.state().predication_mut()).laying(); + let next = match laying { + true => None, + false => self.release_pass().and_then(|()| self.continuation()).ok(), + }; + let Some(next) = next else { + if let Some(raw) = self.recording() { + // SAFETY: the encoder's command buffer is recording outside a render pass; its + // commands retain the shadowed texture until it completes, and its image rests in + // the `GENERAL` layout. + unsafe { copy.record(self.device().shared().vk(), raw, None) }; + } + return; + }; + let work = Deferred::GatedCopyIn(Arc::new(GatedCopyIn::new(copy.clone(), gate))); + // Refused only where the current `VkCommandBuffer` does not end, which abandons the + // command buffer. + let _abandoned = self.defer_into(next, work); + } + /// The `VkCommandBuffer` a render pass holds ([`hold_pass`](Self::hold_pass)), until its /// release. pub(super) fn held_pass(&self) -> Option { @@ -2201,9 +2241,6 @@ 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 5fc02a92c..c1fe58744 100644 --- a/crates/metal2vulkan-runtime/src/exit_guard.rs +++ b/crates/metal2vulkan-runtime/src/exit_guard.rs @@ -459,8 +459,7 @@ 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. + // An encoder's commands that no host step records, primed with the rest. CmdBlitImage => c"vkCmdBlitImage", CmdUpdateBuffer => c"vkCmdUpdateBuffer", CmdFillBuffer => c"vkCmdFillBuffer", @@ -900,8 +899,7 @@ where /// with the utilization floor at its top on Linux, from its start ([`run_at_user_interactive`]): /// the scheduler's (`scheduler/`), each `VkQueue`'s waiter, which makes the completion turns /// (`command_buffer/completion.rs`), every thread of the handler -/// pool (`contexts/`), the device's recorder and lowering threads (`recorder`, -/// `render/lowering_worker.rs`), and a predicated loop's check's (`command_buffer/rerun.rs`), +/// pool (`contexts/`), the device's lowering thread (`render/lowering_worker.rs`), and a predicated loop's check's (`command_buffer/rerun.rs`), /// whose work the program's command buffers wait for. A thread one /// of them starts (the reaper a pipeline state's last release /// starts on a handler thread, a program's thread made in a handler) does not take either: it diff --git a/crates/metal2vulkan-runtime/src/gpu_time.rs b/crates/metal2vulkan-runtime/src/gpu_time.rs index fbe7cee41..e3157b7ed 100644 --- a/crates/metal2vulkan-runtime/src/gpu_time.rs +++ b/crates/metal2vulkan-runtime/src/gpu_time.rs @@ -107,8 +107,8 @@ //! no slot free. //! - **Kernel times** are the host times at which the scheduler began submitting the command //! buffer's first batch and finished submitting its last. They are kept apart from the command -//! buffer's state ([`KernelTimes`]), which the scheduler holds while it replays the batch's -//! deferred command buffers (`recorder`) and submits it: a read waits for no submission in +//! buffer's state ([`KernelTimes`]), which the scheduler holds while it records the batch's +//! own command buffers and submits it: a read waits for no submission in //! progress and for no GPU work, as Metal's reads wait for none. //! - **No encoder, no timestamps**. A command buffer that encoded nothing and waits for no event or //! semaphore takes no slot and writes no timestamps. Its GPU start and end are both where its diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index 3fe378274..6faf29100 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -831,16 +831,12 @@ impl Taken { self.dead } - /// Hold every pin weakly: its command buffer committed and waits for its first submission. - /// 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>) { + /// Hold every pin weakly: its command buffer committed and waits for its first submission, + /// its commands recorded already. + pub(super) fn wait(&mut self) { for (_, pinned) in &mut self.pins { if let Pinned::Held(pages) = pinned { - let waiting = Pinned::Waiting(Arc::downgrade(pages)); - if let Pinned::Held(pages) = std::mem::replace(pinned, waiting) { - held.push(pages); - } + *pinned = Pinned::Waiting(Arc::downgrade(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 deleted file mode 100644 index 487948490..000000000 --- a/crates/metal2vulkan-runtime/src/recorder/handles.rs +++ /dev/null @@ -1,169 +0,0 @@ -//! 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 deleted file mode 100644 index 860679cc5..000000000 --- a/crates/metal2vulkan-runtime/src/recorder/log.rs +++ /dev/null @@ -1,1817 +0,0 @@ -//! 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::dirty_pages::CopyInGate; -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 push_slice(&mut self, values: &[T]) -> Span { - // SAFETY: the slice's elements, as many as its length. - unsafe { self.push(values.as_ptr(), values.len() as u32) } - } - - 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, - }, - /// A shadow's copy in whose regions its gate decides at the replay (`dirty_pages.rs`): - /// `regions` are every region, `gate` the gate's place in [`Log::gates`]. - GatedCopyBufferToImage { - src: vk::Buffer, - dst: vk::Image, - layout: vk::ImageLayout, - regions: Span, - gate: u32, - }, - 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), - BindIndexBuffer2(vk::Buffer, vk::DeviceSize, vk::DeviceSize, vk::IndexType), - DrawMeshTasks(u32, u32, u32), - DrawMeshTasksIndirect(vk::Buffer, vk::DeviceSize, u32, u32), - /// The commands' buffer and offset, the count's, the most draws and the stride. - DrawMeshTasksIndirectCount( - vk::Buffer, - vk::DeviceSize, - 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, - /// The gates of its gated copies in, which decide their regions as it replays. - gates: Vec>, -} - -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(), - gates: Vec::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(); - self.gates.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, - }); - } - - /// Log a shadow's copy in of `regions` from `src` into `dst` whose gate decides, at the - /// replay, which of them it records (`dirty_pages.rs`). - pub(super) fn copy_buffer_to_image_gated( - &mut self, - gate: Arc, - (src, dst, layout): (vk::Buffer, vk::Image, vk::ImageLayout), - regions: &[vk::BufferImageCopy], - ) { - let regions = (self.buffer_images).push_slice(regions); - let gate_at = self.gates.len() as u32; - self.gates.push(gate); - self.op(Logged::GatedCopyBufferToImage { - src, - dst, - layout, - regions, - gate: gate_at, - }); - } - - 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_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)); - } - - pub(super) unsafe fn cmd_draw_mesh_tasks_indirect_count( - &mut self, - buffer: vk::Buffer, - offset: vk::DeviceSize, - count_buffer: vk::Buffer, - count_offset: vk::DeviceSize, - max_count: u32, - stride: u32, - ) { - self.op(Logged::DrawMeshTasksIndirectCount( - buffer, - offset, - count_buffer, - count_offset, - max_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::GatedCopyBufferToImage { - src, - dst, - layout, - regions, - gate, - } => { - let whole = self.buffer_images.get(regions); - let mut chosen = Vec::new(); - self.gates[gate as usize].regions(whole, &mut chosen); - if !chosen.is_empty() { - call!( - CmdCopyBufferToImage, - vk::PFN_vkCmdCopyBufferToImage, - src, - dst, - layout, - chosen.len() as u32, - chosen.as_ptr() - ) - } - } - 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::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::DrawMeshTasksIndirectCount( - buffer, - offset, - count_buffer, - count_offset, - max_count, - stride, - ) => call!( - CmdDrawMeshTasksIndirectCount, - vk::PFN_vkCmdDrawMeshTasksIndirectCountEXT, - buffer, - offset, - count_buffer, - count_offset, - max_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 23f52b030..ee48e9b15 100644 --- a/crates/metal2vulkan-runtime/src/recorder/mod.rs +++ b/crates/metal2vulkan-runtime/src/recorder/mod.rs @@ -1,6 +1,6 @@ -//! 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. +//! The door every command a `VkCommandBuffer` takes goes through, counted by kind as it is +//! recorded. The encoders record into the driver's command buffers at each call, on the program's +//! thread, as the scheduler's thread records its batches' own; this module only counts. //! //! - **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 @@ -10,65 +10,17 @@ //! 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, 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. The scheduler's thread wakes the recorder's once a pass took the -//! commit in, after the pass's submissions ([`RecorderShared::kick`]): a commit wakes one -//! thread, the scheduler's, so the program's thread makes one system call for it. 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. +//! - **Counted by kind.** Each command recorded through a slot counts once for its kind, one +//! relaxed increment into a fixed array of the slot's indexed by the command, whatever the +//! command buffer and the thread (`WorkCounts::commands_replayed`). A device past the slots +//! records with its driver's commands, uncounted. -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; -pub(crate) use replays::{resolve, take_leaving_room, RecorderShared, ReplayCounts, Replays}; pub(crate) use thunks::Command; pub use thunks::CommandsReplayed; @@ -146,6 +98,11 @@ impl Slot { unsafe { std::mem::transmute_copy::<*const c_void, F>(&thunk) } } + /// The commands recorded through the slot so far, by kind (the module docs). + pub(crate) fn counts(&self) -> CommandsReplayed { + thunks::counts(self.index) + } + /// 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> { @@ -154,49 +111,6 @@ impl Slot { } } -/// 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); @@ -220,6 +134,7 @@ pub(crate) unsafe fn route(device: ash::Device) -> (ash::Device, Option) { return (device, None); }; let slot = Slot { index }; + thunks::clear_counts(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)); @@ -247,43 +162,6 @@ pub(crate) unsafe fn through(slot: Option<&Slot>, command: Command, rea } } -/// Log a shadow's copy in into `raw`, where it is a deferred command buffer, its regions decided -/// by `gate` as it replays (`dirty_pages.rs`); `false` where `raw` is a driver's command buffer, -/// into which the caller records every region itself. -/// -/// # Safety -/// -/// The caller records `raw` alone, and `raw` is recording; the command is valid with every one -/// of `regions` (each region the gate keeps is one of them, or rows of one). -pub(crate) unsafe fn copy_buffer_to_image_gated( - raw: vk::CommandBuffer, - gate: Arc, - copy: (vk::Buffer, vk::Image, vk::ImageLayout), - regions: &[vk::BufferImageCopy], -) -> bool { - // SAFETY: the caller's. - unsafe { - handles::record(raw, |log| { - log.copy_buffer_to_image_gated(gate, copy, regions) - }) - } - .is_some() -} - -/// 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 { diff --git a/crates/metal2vulkan-runtime/src/recorder/replays.rs b/crates/metal2vulkan-runtime/src/recorder/replays.rs deleted file mode 100644 index 7e673d297..000000000 --- a/crates/metal2vulkan-runtime/src/recorder/replays.rs +++ /dev/null @@ -1,644 +0,0 @@ -//! 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 and `wake` says so; else - /// the scheduler's thread wakes it ([`kick`](Self::kick)). - fn enqueue(&self, replays: Arc, wake: bool) { - let mut queue = lock(&self.queue); - queue.replays.push_back(replays); - if wake && queue.parked { - self.wake.notify_one(); - } - } - - /// Wake the recorder thread where it waits while its queue holds replays: the scheduler's - /// thread, after a pass that took commits in, whose replays their commits queued without a - /// wake ([`Replays::commit`]). A submission replays what the recorder has yet to itself - /// ([`resolve`]), so no submission waits for this; the recorder replays what waits for a - /// later submission, and takes off its queue what a submission replayed. - pub(crate) fn kick(&self) { - let queue = lock(&self.queue); - if queue.parked && !queue.replays.is_empty() { - 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), true); - } - } - - /// 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 - /// recorder. `fill` runs under its lock, which it must not take again. - pub(crate) fn hold( - self: &Arc, - device: &Vk, - fill: impl FnOnce(&mut Vec>), - ) -> Vec { - let mut state = lock(&self.state); - Self::fill(&mut state, fill); - self.settle(device, &mut state, true) - } - - /// 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, which the - /// scheduler's wakes once it took the commit in ([`RecorderShared::kick`]), 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; - self.settle(device, &mut state, false) - } - - /// What `state` holds once its command buffer committed (nothing before), under its lock: - /// queued for the recorder where something ended waits, then each page's buffer's let-go - /// read, after its hold was counted and the replays queued, so a let-go after the read finds - /// both (`HostPages::let_go_by_buffer`). Where one came before, everything ended replays now, - /// 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, - wake: bool, - ) -> 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), wake); - } - if state.held.iter().any(|pages| pages.buffer_let_go()) { - let replayed = self.replay_ended(device, state); - self.recorder - .by_submitter - .fetch_add(replayed, Ordering::Relaxed); - } - } - 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 { - self.let_go(&mut state, None); - } - replayed - } - - /// Replay every ended command buffer of `state` not yet replayed, in the order they ended, - /// inside a section, with `device`, the device's functions: how many. Once the process - /// exits, outside a section, they are dropped unreplayed instead, and their submission fails - /// ([`resolve`]), as a submission does then. - fn replay_ended(&self, device: &Vk, state: &mut ReplayState) -> u64 { - let Some(_busy) = exit_guard::enter() else { - 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 - /// of pages held here replays first, and a commit after it replays itself - /// (`HostPages::let_go_by_buffer`). Were one held last, it would go on the device's handler - /// 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 index 3733606ea..43b2ffb57 100644 --- a/crates/metal2vulkan-runtime/src/recorder/thunks.rs +++ b/crates/metal2vulkan-runtime/src/recorder/thunks.rs @@ -1,6 +1,6 @@ //! 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. +//! device's driver gave them (`recorder`): each entry point counts its command for its slot and +//! calls the driver's. use super::SLOTS; use crate::generated_commands::GeneratedCommandsInfo; @@ -8,6 +8,22 @@ use ash::vk; use std::ffi::{c_void, CStr}; use std::sync::atomic::{AtomicPtr, AtomicU64, Ordering}; +/// Each slot's commands recorded so far, one count per command at its index. +static COUNTS: [[AtomicU64; Command::COUNT]; SLOTS] = + [const { [const { AtomicU64::new(0) }; Command::COUNT] }; SLOTS]; + +/// Slot `index`'s counts. +pub(super) fn counts(index: usize) -> CommandsReplayed { + CommandsReplayed::read(&COUNTS[index]) +} + +/// Zero slot `index`'s counts, as a device takes it. +pub(super) fn clear_counts(index: usize) { + for count in &COUNTS[index] { + count.store(0, Ordering::Relaxed); + } +} + /// 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. @@ -55,29 +71,28 @@ macro_rules! commands { } } - /// 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. + /// The commands a device recorded (`recorder`), by kind: each routed command's calls into + /// any of its `VkCommandBuffer`s, on whichever thread recorded them, counted at the call. + /// 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), "`.")] + #[doc = concat!("The calls of `", stringify!($v0), "`.")] pub $f0: u64, )* $( - #[doc = concat!("The replays' calls of `", stringify!($v3), "`.")] + #[doc = concat!("The calls of `", stringify!($v3), "`.")] pub $f3: u64, )* $( - #[doc = concat!("The replays' calls of `", stringify!($ve), "`.")] + #[doc = concat!("The 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 { + 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),)* @@ -99,9 +114,9 @@ macro_rules! commands { $($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)?;)*); + commands!(@thunks $($v0 $f0 $n0 ($($a0: $t0),*) $(-> $r0)?;)*); + commands!(@thunks $($v3 $f3 $n3 ($($a3: $t3),*) $(-> $r3)?;)*); + commands!(@thunks $($ve $fe $ne ($($ae: $te),*) $(-> $re)?;)*); /// Slot `S`'s entry point for `command`. pub(super) fn thunk(command: Command) -> *const c_void { @@ -122,24 +137,6 @@ macro_rules! commands { } } - /// 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);)* @@ -163,21 +160,14 @@ macro_rules! commands { )* } }; - (@thunks $($f:ident $n:literal ($($a:ident: $t:ty),*) $(-> $r:ty)?;)*) => { + (@thunks $($v:ident $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; - } + COUNTS[S][Command::$v as usize].fetch_add(1, Ordering::Relaxed); let real = REAL.$f[S].load(Ordering::Acquire); if real.is_null() { missing($n); diff --git a/crates/metal2vulkan-runtime/src/render/lowering_worker.rs b/crates/metal2vulkan-runtime/src/render/lowering_worker.rs index e39891d73..14d4cb1fd 100644 --- a/crates/metal2vulkan-runtime/src/render/lowering_worker.rs +++ b/crates/metal2vulkan-runtime/src/render/lowering_worker.rs @@ -33,7 +33,6 @@ use super::deferral::LoweringSlot; use super::queued_commits::QueuedCommits; use crate::device::lock; use crate::exit_guard; -use crate::recorder::take_leaving_room; use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Condvar, Mutex}; @@ -158,6 +157,17 @@ impl LoweringWorker { } } +/// The first of `queue`, taken off, and `queue` left room for twice as many as waited, made on +/// the thread that takes, so a push grows the queue, an allocation on the pushing thread, only +/// where more wait than twice as many as this thread ever found, as the scheduler's inbox leaves +/// its commits room (`scheduler/inbox.rs`). +fn take_leaving_room(queue: &mut VecDeque) -> Option { + let waited = queue.len(); + let first = queue.pop_front()?; + queue.reserve(waited + 1); + Some(first) +} + impl WorkerShared { /// The thread's loop: each slot handed lowered, until [`LoweringWorker::stop`]. fn run(&self) { diff --git a/crates/metal2vulkan-runtime/src/row_copies.rs b/crates/metal2vulkan-runtime/src/row_copies.rs index bd5918fbb..d251f51bd 100644 --- a/crates/metal2vulkan-runtime/src/row_copies.rs +++ b/crates/metal2vulkan-runtime/src/row_copies.rs @@ -12,7 +12,7 @@ //! - **Why.** A driver may record each region of a copy as an operation of its own: ANV records //! one blit operation per region, a full 3D-pipeline draw with its own state. On the Iris Xe //! the 1080 rows of a 1920-texel `BGRA8Unorm` texture took 3.1-3.3 ms of CPU, and one -//! `vkCmdCopyBuffer` a frame took about 15 of the recorder thread's 19 ms a frame of a +//! `vkCmdCopyBuffer` a frame took about 15 of the recording thread's 19 ms a frame of a //! program's frames. One dispatch records the same rows as one command. //! - **When.** On a device measured to run the dispatch faster //! (`DriverFact::RowCopiesDispatchFaster`: ANV, and NVIDIA's on the RTX 5080 Laptop GPU, from 2 diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs index eb0928b12..d8a3b7b36 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs @@ -10,10 +10,8 @@ //! thread stops looking at the inbox again at a pass that leaves it a check or a host step, and //! before each one it runs passes again for as long as the inbox holds commits, and looks at it //! before it sleeps ([`left`]): a commit waits for the pass under way, the submission handlers -//! that pass leaves, and the pass that takes it in, never for a check or a step. After a round -//! whose passes took commits in, and before its submission handlers, the thread wakes the -//! device's recorder where it waits with their replays queued (`recorder`), which the commits -//! queued without a wake: a commit wakes this thread alone. +//! that pass leaves, and the pass that takes it in, never for a check or a step. A commit +//! wakes this thread alone. //! //! - **A thread about to block submits for itself** ([`Scheduler::submit_before_waiting`]). //! Metal encodes and commits inline on the program's thread, and a thread that commits and then @@ -159,7 +157,6 @@ use super::event::EventShared; use super::event_timeline::WaitFor; use super::exit_guard; use super::gpu_time; -use super::recorder::RecorderShared; use super::replay::SpareLogs; use super::resource::ResourceKey; use super::tracker::{self, Footprint, Tracker}; @@ -381,9 +378,6 @@ struct SchedulerShared { /// The device's cleared encoder logs (`replay.rs`): an encoder takes one, and its log comes /// back as the encoder ends, or in its command buffer's release. spare_logs: SpareLogs, - /// The device's recorder, where it records off the encoding thread (`recorder`): woken after - /// a round that took commits in (the module docs). - recorder: OnceLock>, /// Where the device's driver stalls in one signalling submission of every 1024 to a queue, /// what the thread takes those stalls idle with (the module docs). stalls: OnceLock, @@ -632,7 +626,6 @@ impl Scheduler { passes: AtomicU64::new(0), nudge: OnceLock::new(), spare_logs: SpareLogs::default(), - recorder: OnceLock::new(), stalls: OnceLock::new(), }); let thread = { @@ -681,11 +674,6 @@ impl Scheduler { } } - /// Wake `recorder`, the device's, after each round that took commits in (the module docs). - pub(crate) fn wake_recorder(&self, recorder: Arc) { - let _ = self.shared.recorder.set(recorder); - } - /// Hold the batches of `buffer`, committed now on logical queue `queue`: what each batch /// waits for and signals, in order. They go to the thread's inbox, and `commit` returns at /// once, with nothing submitted: the thread takes them in at its next pass, woken for it @@ -735,9 +723,8 @@ impl Scheduler { pub(crate) fn submit_before_waiting(&self, device: &Device) { let shared = &*self.shared; let mut spent = Spent::new(); - let (mut took, mut submitted, mut left_over) = (false, 0, false); + let (mut submitted, mut left_over) = (0, false); let passed = shared.inbox.pass_once(|state, commits| { - took = !commits.is_empty(); take_in(state, commits, &mut spent); submitted = submit_plain_ready(state, &mut spent); left_over = !state.order.is_empty() || !state.grouped.is_empty(); @@ -754,13 +741,6 @@ impl Scheduler { device.let_go_elsewhere(Box::new(last)); } } - // The commits' replays, which they queued without waking the recorder (`recorder`): those - // of the batches submitted here replayed in their submission, the rest for its thread. - if took { - if let Some(recorder) = shared.recorder.get() { - recorder.kick(); - } - } // This pass never looks again (`inbox.rs`): what is left in the order, and anything // posted or nudged during it, goes to the thread that makes passes. if left_over || shared.inbox.passed_over() { @@ -1122,14 +1102,6 @@ fn round(shared: &SchedulerShared, left: &mut Left, passed: &mut Passed) - !passed.exiting && left.is_empty() && !passed.more }); passed.more = false; - // The commits' replays, which they queued without waking the recorder: after the passes' - // submissions, which replayed their own (`recorder`). - if passed.took && !passed.exiting { - if let Some(recorder) = shared.recorder.get() { - recorder.kick(); - } - } - passed.took = false; if passed.exiting { passed.settled.clear(); passed.handlers.clear(); @@ -1151,8 +1123,6 @@ struct Passed { handlers: Handlers, more: bool, exiting: bool, - /// A pass took commits in. - took: bool, } /// Take `commits` into the order, in commit order: each command buffer's batches, each with what @@ -1197,7 +1167,6 @@ fn pass( (passed, left): (&mut Passed, &mut Left), awaits: &Awaits, ) { - passed.took |= !commits.is_empty(); take_in(state, commits, &mut passed.spent); state.dirty = false; match submit_ready( diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs index b8f26c7f3..f859dd9cf 100644 --- a/crates/metal2vulkan-runtime/src/shadow.rs +++ b/crates/metal2vulkan-runtime/src/shadow.rs @@ -1023,6 +1023,40 @@ pub(super) enum Step { Merge(M), } +/// A shadow's copy in over host pages a consumer logs (`dirty_pages.rs`), left by its encoder +/// to its batch's submission (`Deferred::GatedCopyIn`): the commit asks the log for a stamp, and +/// the copy's regions are those the log says changed once that stamp is published, which only a +/// recording after the commit can know. Recorded in a command buffer of its own between the +/// encoder's, behind a barrier from everything before it and before one to everything after it, +/// so it keeps its place among the encoder's commands. +pub(super) struct GatedCopyIn { + copy: ShadowCopy, + gate: Arc, +} + +impl GatedCopyIn { + /// `copy`, its regions decided by `gate`. + pub(super) fn new(copy: ShadowCopy, gate: Arc) -> GatedCopyIn { + GatedCopyIn { copy, gate } + } + + /// Record it into `command_buffer`, its regions decided now. + /// + /// # Safety + /// + /// `command_buffer` is recording, outside a render pass; the copy's texture is live (its + /// encoder's command buffer holds it), its image in the `GENERAL` layout. + pub(super) unsafe fn record(&self, device: &Vk, command_buffer: vk::CommandBuffer) { + // SAFETY: the caller's. + unsafe { + Barrier::everything().record(device, command_buffer); + let gate = Some(Arc::clone(&self.gate)); + self.copy.record_gated(device, command_buffer, None, gate); + Barrier::everything().record(device, command_buffer); + } + } +} + /// One copy between a shadowed texture's buffer and its shadow. #[derive(Clone)] pub(super) struct ShadowCopy> { @@ -1184,7 +1218,8 @@ fn image_copy_texels(region: &vk::ImageCopy) -> u64 { impl ShadowCopy { /// The log of a copy in of every texel of a tracked 2D texture's image straight from a /// buffer over host pages a consumer logs (`dirty_pages.rs`), made or kept by `device`, and - /// the bytes of one texel: what may decide the copy's regions as its command buffer replays. + /// the bytes of one texel: what may decide the copy's regions as its batch is submitted + /// ([`GatedCopyIn`]). /// `None` for every other copy. pub(super) fn gate_log(&self, device: &Device) -> Option<(Arc, u64)> { let c = &self.copies; @@ -1557,8 +1592,8 @@ impl ShadowCopy { } /// [`record`](Self::record), a copy in of a 2D texture's image straight from the buffer - /// recorded under `gate` where given: its regions decided as the command buffer replays - /// (`dirty_pages.rs`), every region where it records into a driver's command buffer. + /// recorded under `gate` where given: its regions decided now, as its batch is submitted + /// ([`GatedCopyIn`], `dirty_pages.rs`). /// /// # Safety /// @@ -1813,16 +1848,18 @@ impl ShadowCopy { device.cmd_copy_buffer(command_buffer, buffer, texels, &[staging.into]); Barrier::everything().record(device, command_buffer); } - let gated = (gate.filter(|_| staging.is_none())).is_some_and(|gate| { - let copy = (texels, image, vk::ImageLayout::GENERAL); - super::recorder::copy_buffer_to_image_gated( - command_buffer, - gate, - copy, - ®ions, - ) - }); - if gated { + if let Some(gate) = gate.filter(|_| staging.is_none()) { + let mut chosen = Vec::new(); + gate.regions(®ions, &mut chosen); + if !chosen.is_empty() { + device.cmd_copy_buffer_to_image( + command_buffer, + texels, + image, + vk::ImageLayout::GENERAL, + &chosen, + ); + } return; } device.cmd_copy_buffer_to_image( diff --git a/crates/metal2vulkan-runtime/src/tests/exit_guard.rs b/crates/metal2vulkan-runtime/src/tests/exit_guard.rs index 65d20d68b..7eccaafc1 100644 --- a/crates/metal2vulkan-runtime/src/tests/exit_guard.rs +++ b/crates/metal2vulkan-runtime/src/tests/exit_guard.rs @@ -1649,7 +1649,7 @@ fn the_device_s_functions_are_reached_through_checked_accessors() { /// tuple field, a type argument or a by-value parameter) fails /// `only_the_listed_modules_keep_the_device_s_functions`; so does a listed module that keeps none /// any more. -const KEEPERS: [(&str, &str); 24] = [ +const KEEPERS: [(&str, &str); 23] = [ ( "binding.rs", "the push command (vkCmdPushDescriptorSet), a call's parameter (`push_set`) and the \ @@ -1719,11 +1719,6 @@ const KEEPERS: [(&str, &str); 24] = [ "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)", diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index d9d09f5ed..cbeec393c 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -216,6 +216,8 @@ mod rebind_descriptor_slip; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod rebind_making_wait; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod recorded_at_the_call; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod recycle; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod relay_facts; @@ -230,7 +232,6 @@ mod render_directory_trips; mod render_sibling_work; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod render_stage_digests; -mod replays; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod rerun_arenas; mod resource; diff --git a/crates/metal2vulkan-runtime/src/tests/pipeline_wait_order.rs b/crates/metal2vulkan-runtime/src/tests/pipeline_wait_order.rs index 25d361230..509de9b6a 100644 --- a/crates/metal2vulkan-runtime/src/tests/pipeline_wait_order.rs +++ b/crates/metal2vulkan-runtime/src/tests/pipeline_wait_order.rs @@ -176,6 +176,13 @@ fn a_hold_of_the_pool_lives_until_its_own_drop() { fn a_batch_waiting_for_a_pipeline_holds_only_the_batches_that_share_its_resources() { let scratch = Scratch::new(); let device = device(&scratch.0); + // The device's check of images over host pages (`in_place_check.rs`), which the texture over + // the no-copy buffer would start, runs to its verdicts first: its rounds' internal + // submissions, in flight as the buffer goes, would hold its memory and so its deallocator + // (`freed_memory.rs` waits for the device's own submissions), which is not what this test + // asks about. The texture then takes the path the verdict gives, as a program's does once + // the device's verdicts are known. + let _ = device.settle_in_place_checks(WAIT); let state = state(&device); let mut target = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); target.usage = TextureUsage::RENDER_TARGET; diff --git a/crates/metal2vulkan-runtime/src/tests/recorded_at_the_call.rs b/crates/metal2vulkan-runtime/src/tests/recorded_at_the_call.rs new file mode 100644 index 000000000..149bab137 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/recorded_at_the_call.rs @@ -0,0 +1,58 @@ +//! An encoder records each command into the driver's `VkCommandBuffer` at the call, on the +//! program's thread (`command_buffer`'s `allocate_raw`): the device's count of the commands +//! recorded (`WorkCounts::commands_replayed`, counted as each goes through its slot, `recorder`) +//! moves at the call itself, before the encoder ends and before the commit, where a command +//! logged for a later recording would move it only after the commit. +//! +//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`). + +use super::blit_holds::{device, Scratch, WAIT}; +use crate::{CommandBufferStatus, CommandsReplayed, ResourceOptions}; + +/// The fills recorded so far, as `vkCmdFillBuffer` or, where the runtime records fills as +/// transfers, `vkCmdUpdateBuffer` (`WorkCounts::fills_by_transfers`). +fn fills(counts: &CommandsReplayed) -> u64 { + counts.cmd_fill_buffer + counts.cmd_update_buffer +} + +/// A blit encoder's fill of a buffer's word is in the driver's command buffer as the call +/// returns: the count of fills recorded rose by one at the call, the encoder still open and the +/// command buffer uncommitted, and by no more at its end and commit. The bytes are the fill's. +#[test] +fn a_fill_is_recorded_at_its_call() { + let scratch = Scratch::new("recorded-at-the-call"); + let device = device(&scratch.0); + let queue = device.new_command_queue().unwrap(); + let buffer = (device.new_buffer(16, ResourceOptions::shared())).unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + let before = device.work_counts().commands_replayed; + blit.fill_buffer(&buffer, 4..8, 0x5a).unwrap(); + let at_call = device.work_counts().commands_replayed; + 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().commands_replayed; + println!( + "RECORDED-AT-THE-CALL {}: fills recorded at the call {}, after the commit {}", + device.name(), + fills(&at_call) - fills(&before), + fills(&after) - fills(&before), + ); + assert_eq!( + fills(&at_call) - fills(&before), + 1, + "the fill was recorded into the driver's command buffer at its call" + ); + assert_eq!( + fills(&after) - fills(&at_call), + 0, + "nothing recorded the fill again after its call" + ); + let bytes = buffer.contents().unwrap(); + // SAFETY: the buffer is shared, of 16 bytes, and its command buffer completed. + let words = unsafe { std::slice::from_raw_parts(bytes.as_ptr(), 16) }; + assert_eq!(&words[4..8], &[0x5a; 4], "the fill's bytes"); +} diff --git a/crates/metal2vulkan-runtime/src/tests/replays.rs b/crates/metal2vulkan-runtime/src/tests/replays.rs deleted file mode 100644 index 0f84c50e1..000000000 --- a/crates/metal2vulkan-runtime/src/tests/replays.rs +++ /dev/null @@ -1,74 +0,0 @@ -//! `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 d059e6ad6..1072ae303 100644 --- a/crates/metal2vulkan-runtime/src/texture/first_move.rs +++ b/crates/metal2vulkan-runtime/src/texture/first_move.rs @@ -91,8 +91,7 @@ //! command buffer that binds them is pending (no `descriptorBindingUpdateUnusedWhilePending`) //! holds no slots, as a write made after a command buffer committed misses the version it binds //! (`heap_sets.rs`): there each registration waits for its place ([`FirstMoves::ordered`]), so -//! for no replay and no GPU work (a batch replays its encoders' deferred command buffers, -//! `recorder`, before its take), only for the recording of a submission's own barriers and its +//! for no GPU work, only for the recording of a submission's own barriers and its //! `vkQueueSubmit`. 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 diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 764fabc06..73d7d7072 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -10,7 +10,7 @@ use super::command_buffer::GroupEnd; use super::degradation::Degradation; use super::device::lock; use super::memory::FreeCause; -use super::recorder::{CommandsReplayed, ReplayCounts}; +use super::recorder::CommandsReplayed; use super::scheduler::HeldFor; use super::shadow::{Backing, CarryTally, CopyCause, Lost, ShadowCopy, ShadowSource}; use super::Device; @@ -38,7 +38,6 @@ pub(crate) struct Counters { /// Released objects and shadow keeps by kind (`churn_counts.rs`). pub(crate) churn: super::churn_counts::ChurnCounters, command_pools_made: AtomicU64, - command_buffers_deferred: AtomicU64, spare_command_pools_taken: AtomicU64, spare_command_pools_reset: AtomicU64, live_tables_uploaded: AtomicU64, @@ -731,13 +730,6 @@ 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 @@ -1527,8 +1519,7 @@ impl Counters { } /// A render pass instance its pass replaced or gave up before running it had its draws - /// recording given up (`render.rs`, `RenderCommandEncoder::end_unrun`): never replayed where - /// deferred, else ended. + /// recording given up (`render.rs`, `RenderCommandEncoder::end_unrun`): ended. pub(crate) fn unrun_instance_ended(&self) { self.unrun_instances_ended.fetch_add(1, Ordering::Relaxed); } @@ -2855,28 +2846,20 @@ pub struct MemoryFrees { 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, /// Released objects MoltenVK commits its residency set for, by kind (`churn_counts.rs`). pub object_churn: super::churn_counts::ObjectChurn, /// Merged-back shadows' keeps by who planned them (`churn_counts.rs`). pub shadow_keeps: super::churn_counts::ShadowKeeps, + /// The commands recorded into the device's `VkCommandBuffer`s, by kind, as each was recorded + /// (`recorder`): one per call, the begins and ends among them, whatever the command buffer + /// (an encoder's, a batch's submission's, the device's own) and the thread; none on a device + /// past the slots. + pub commands_replayed: CommandsReplayed, /// The places in the runtime that recorded `vkCmdCopyBuffer`, `vkCmdCopyBufferToImage`, /// `vkCmdCopyImageToBuffer` and `vkCmdCopyImage` through the device's functions, as encoders - /// and the runtime's own work recorded them (whichever thread replays them later): the first - /// 32 places met, each with its calls, their regions and the most regions one had. What - /// names the copy behind a recorder's time on a driver that records each region as an - /// operation of its own (`row_copies.rs`). + /// and the runtime's own work recorded them: the first 32 places met, each with its calls, + /// their regions and the most regions one had. What names the copy behind a recording's time + /// on a driver that records each region as an operation of its own (`row_copies.rs`). pub copy_sites: [CopySite; 32], /// The `vkCmdCopyBuffer` regions over 16 KiB whose size is no multiple of 4 KiB that the /// device's functions recorded as two, the bytes up to the last whole multiple of 4 KiB and @@ -3530,8 +3513,7 @@ 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`). + /// the command buffer that takes the pool records into, begun no more on its thread. 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 @@ -3664,8 +3646,8 @@ pub struct WorkCounts { /// a submission holding its place in the submissions' order and waited until that submission /// was made: only on a device whose heap sets take no writes while a command buffer that binds /// them is pending (no `descriptorBindingUpdateUnusedWhilePending`), where a submission holds - /// the order from its take of the first work, after replaying its encoders' deferred command - /// buffers, to its `vkQueueSubmit` (`texture/first_move.rs`). Elsewhere a registration takes + /// the order from its take of the first work to its `vkQueueSubmit` + /// (`texture/first_move.rs`). Elsewhere a registration takes /// no place, and this stays 0. pub registrations_waited: u64, /// Submissions (a batch's, or one of the device's own) that found another holding its place in @@ -3791,8 +3773,7 @@ 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 first instance /// whose draws record inline instead), whose draws - /// recording the runtime gave up: never replayed where deferred (`recorder`), else ended, so - /// their command pool goes back to the device's spares unreset + /// recording the runtime gave up: 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. @@ -4604,7 +4585,7 @@ pub struct WorkCounts { /// either way (`shadow.rs`). pub shadow_keeps_from_staging: u64, /// The copies in of shadows over host pages a consumer logs whose regions the log decided as - /// their command buffer replayed (`dirty_pages.rs`). + /// their batch was submitted (`dirty_pages.rs`). pub dirty_copies_in_gated: u64, /// Of those, the ones that copied every region: no hold to count on, a wait the log answered /// `false`, or half the rows or more changed. @@ -4618,13 +4599,12 @@ pub struct WorkCounts { /// The stamps the commits of command buffers with a gated copy in asked of the logs: one per /// log and commit. pub dirty_stamps_asked: u64, - /// The waits the replays made for a log's publication (`DirtyPages::wait`): one per log + /// The waits the submissions made for a log's publication (`DirtyPages::wait`): one per log /// serves every stamp asked of it before the wait. pub dirty_waits: u64, /// Of the waits, those the log answered `false`. pub dirty_waits_unanswered: u64, - /// The nanoseconds the waits took, on the threads that replay command buffers before their - /// submission. + /// The nanoseconds the waits took, on the threads that submit command buffers. pub dirty_wait_nanos: u64, /// Of the keeps and merges among `shadow_copies`, those whose copy of the shadow's texels into /// the merge's scratch is the dispatch a copy back takes, where the device runs one faster @@ -4931,16 +4911,10 @@ impl Device { memory.frees(), ) }; - let replays = (self.shared().recorder()) - .map_or_else(ReplayCounts::default, |recorder| recorder.counts()); let dirty = self.shared().dirty.tally(); WorkCounts { - 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, + command_pools_made: counters.command_pools_made.load(Ordering::Relaxed), + commands_replayed: self.shared().commands_recorded(), object_churn: churn.0, shadow_keeps: churn.1, copy_sites: self.shared().vk().copy_sites(), @@ -5151,8 +5125,7 @@ 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, + .load(Ordering::Relaxed), 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/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index ee056c459..fb9de7157 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -a8324821f640fff12537547520eef63e0d455611ffe03c080d095768643721e8 +0534cba97de779bc527e7a767c1f69052a4d003e7fd44f2264eb4e9d1f8724b1 diff --git a/crates/metal2vulkan-validation/src/runtime_lane/clear_reach.rs b/crates/metal2vulkan-validation/src/runtime_lane/clear_reach.rs index 3af4fd251..685e211aa 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/clear_reach.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/clear_reach.rs @@ -18,7 +18,6 @@ use super::degrade_notices::shared_in_system_memory; use super::degrade_notices::{assert_made_once, forced, made_render_kinds}; -use super::hidden_depth::replayed_but_unrun; use super::{ buffer_with, layer_reported_nothing_at_all, read_buffer, validated_device, Messages, ScratchCache, WAIT, @@ -894,17 +893,10 @@ fn a_pass_that_changes_no_texel_records_nothing() { 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", + "a pass beside a depth that changes nothing on {}: {unrun} secondaries given up", lane.device.name() ); - assert_eq!( - replayed, - deferred - unrun, - "a depth beside: command buffers replayed of those begun deferred" - ); assert_eq!( lane.read(&texture, (0, 0), 4, BlitOption::None), old, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/commands_replayed.rs b/crates/metal2vulkan-validation/src/runtime_lane/commands_replayed.rs index b0b6be8ec..049150d99 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/commands_replayed.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/commands_replayed.rs @@ -1,6 +1,6 @@ -//! Device tests of the commands the recorder's replays call, by kind (the runtime's `recorder`, +//! Device tests of the commands recorded, 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 +//! command buffer of one blit encoder of fills and copies records 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). @@ -26,13 +26,12 @@ fn added(before: &CommandsReplayed, after: &CommandsReplayed) -> [u64; 4] { } /// 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 +/// words into another's, committed and completed: it recorded `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. +/// what the fills and copies wrote. A device past the runtime's slots counts nothing, printed. #[test] -fn a_replay_counts_each_command_it_calls_by_kind() { +fn each_command_recorded_counts_once_by_kind() { on_device(|device| { let name = device.name(); let queue = device.new_command_queue().unwrap(); @@ -61,8 +60,8 @@ fn a_replay_counts_each_command_it_calls_by_kind() { 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"); + if after.commands_replayed == before.commands_replayed { + eprintln!("COMMANDS-RECORDED {name}: took no slot, so counts nothing"); return; } let [fills, updates, copies, ends] = @@ -70,16 +69,16 @@ fn a_replay_counts_each_command_it_calls_by_kind() { 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 \ + "COMMANDS-RECORDED {name}: {fills} vkCmdFillBuffer, {updates} vkCmdUpdateBuffer, \ + {copies} vkCmdCopyBuffer, {ends} vkEndCommandBuffer recorded; {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}" + "the fills' and copies' calls recorded on {name}" ); - assert!(ends >= 1, "the replay ended no command buffer on {name}"); + assert!(ends >= 1, "no command buffer ended on {name}"); }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/detach.rs b/crates/metal2vulkan-validation/src/runtime_lane/detach.rs index e51cb9b88..86750b16e 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/detach.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/detach.rs @@ -35,9 +35,8 @@ //! command buffer completes over the new pages, as Metal's (`EncodedUseRebound` before). The //! layer reports nothing: no Vulkan command takes the detached buffer's stand-in. //! - **Racing a commit.** A detach on one thread while another commits a command buffer whose -//! command names the buffer runs the old pages' deallocator in neither call, wherever the -//! device's recorder replays the commands, and the buffer's release runs it, on the releasing -//! thread; nothing is announced. +//! command names the buffer runs the old pages' deallocator in neither call, and the buffer's +//! release runs it, on the releasing thread; nothing is announced. //! - **No memory.** A detach places no memory of the bytes it detaches: once the device's //! stand-in is made, detaching a large heap, and a large buffer, allocates no device memory. //! - **Textures**: `detach_textures.rs`. @@ -1256,8 +1255,7 @@ fn spin_until(at: Instant) { /// A detach on one thread racing the commit, on another, of a command buffer whose blit names the /// buffer: the old pages' deallocator runs in neither call (the detach or the commit, whichever -/// lets go of the pages last), wherever the device's recorder replays the command buffer's -/// commands, and runs once at the buffer's release, on the releasing thread, as Metal runs it +/// lets go of the pages last), and runs once at the buffer's release, on the releasing thread, as Metal runs it /// there; nothing is announced: with a keep-alive and without one. The command buffer, which an /// event holds back until both calls returned, then fails `DetachedBacking`. The races start the /// two calls up to 40 us apart, either first, swept in steps of 0.25 us, so that many land inside @@ -1273,7 +1271,6 @@ fn a_detach_racing_a_commit_leaves_the_deallocator_to_the_release() { false => member_over(device, A), }; let (mut early, mut elsewhere) = (0, 0); - let before = device.work_counts(); let span = RACE_SPAN.as_nanos() as i64; for round in 0..RACES { let Some((buffer, seen)) = made() else { @@ -1314,12 +1311,9 @@ fn a_detach_racing_a_commit_leaves_the_deallocator_to_the_release() { _ => elsewhere += 1, } } - let inline = device.work_counts().command_buffers_replayed_inline - - before.command_buffers_replayed_inline; eprintln!( "DETACH race {} ({form}): {RACES} races, the deallocator ran before the release \ - {early}, not once in the release on its thread {elsewhere}; {inline} command \ - buffers replayed off the recorder's thread", + {early}, not once in the release on its thread {elsewhere}", device.name() ); assert_eq!( diff --git a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs index 2298baf32..4afab104d 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs @@ -14,23 +14,6 @@ //! texture over it is rebound. The end mark reads 0 as each call returns. Afterwards every //! texture and buffer holds what Metal's holds: zero where new, the bytes it was made with, the //! bytes it lies over where it aliases, what a blit wrote. -//! - **Making waits for no submission's replay.** A command buffer whose deferred command buffers -//! take long to replay (`recorder`) and to submit is committed, and a `Private` texture made -//! while its submission replays and submits them waits for no submission's place -//! (`WorkCounts::registrations_waited` stays 0): a submission replays them before it takes the -//! new resources' first work, and from its take until its `vkQueueSubmit` returned (MoltenVK -//! encodes the Metal commands inside it) it holds the texture slots' writes, not the texture's -//! registration (`WorkCounts::heap_slot_writes_deferred`), or, on a device whose heap sets take -//! no writes while pending, the registrations, which then wait only for that span. The making's -//! time is printed, not bounded: it holds the host's and the driver's waits. On lavapipe under -//! the validation layer, beside 128 busy threads on 32 CPUs, its `vkCreateImage` slept up to -//! 6 ms on the layer's lock, which the replay's own Vulkan calls on the recorder's thread held -//! while the host ran another thread, and once waited 8 ms for a CPU. It makes a -//! `Private` texture: its move waits for a submission, so its making registers it, where a new -//! `Shared` texture's move is made on the host on a device with host image copies -//! (`texture/host_copy.rs`), registering nothing, whatever the order. One is made before, -//! untimed: a device's first texture making took 4 to 9 ms on RADV -//! and the Iris Xe, 32 ms on a loaded Iris Xe, waiting for nothing. //! - **The zeros come before every use, on every queue** (the coordinator's conditions). A new //! `Private` buffer whose memory held other bytes is read through its address unnamed, and //! through its heap made resident, by a command buffer on another queue, after a command @@ -887,89 +870,6 @@ fn new_resources_wait_for_no_gpu_work() { }); } -/// The fills the long replay's command buffer encodes at first -/// ([`a_new_texture_waits_for_no_submission_s_replay`]), doubled until its submission comes at -/// least [`LONG_REPLAY`] after its commit, up to [`MOST_REPLAY_FILLS`]. -const REPLAY_FILLS: usize = 1 << 12; -const MOST_REPLAY_FILLS: usize = 1 << 20; - -/// The least time from the long replay's commit until its command buffer is scheduled. -const LONG_REPLAY: Duration = Duration::from_millis(40); - -/// How long after that commit the texture is made: past the scheduler's first look at the -/// command buffer, well inside its replay. -const AFTER_COMMIT: Duration = Duration::from_millis(2); - -/// Making a texture waits for no submission's replay of deferred command buffers, nor for its -/// `vkQueueSubmit` (Metal's makes wait for no GPU work, nor for a submission). One blit encoder of -/// fills of distinct words, whose replay into a `VkCommandBuffer` (`recorder`) and submission take -/// at least [`LONG_REPLAY`] (its fills doubled until they do), is committed, and a `Private` -/// texture, whose making registers its move and writes its slot (the module docs), is made -/// [`AFTER_COMMIT`] later, after one made untimed before: its registration waits for no -/// submission's place (`WorkCounts::registrations_waited`), and its time is printed. A device that -/// records as it encodes (no recorder) replays nothing, printed. -#[test] -fn a_new_texture_waits_for_no_submission_s_replay() { - on_device(|device| { - let queue = device.new_command_queue().unwrap(); - let name = device.name(); - let first = device.new_texture(&descriptor(tracked_private())).unwrap(); - let mut fills = REPLAY_FILLS; - loop { - let target = (device.new_buffer(4 * fills as u64, ResourceOptions::private())).unwrap(); - let deferred = device.work_counts().command_buffers_deferred; - let command_buffer = queue.command_buffer().unwrap(); - let mut blit = command_buffer.blit_command_encoder().unwrap(); - for at in 0..fills as u64 { - blit.fill_buffer(&target, 4 * at..4 * at + 4, at as u8) - .unwrap(); - } - blit.end_encoding().unwrap(); - if device.work_counts().command_buffers_deferred == deferred { - eprintln!("FIRST-USE {name}: records as it encodes, so no submission replays"); - return; - } - let committed = Instant::now(); - command_buffer.commit().unwrap(); - std::thread::sleep(AFTER_COMMIT); - let waited = device.work_counts().registrations_waited; - let making = Instant::now(); - let texture = device.new_texture(&descriptor(tracked_private())).unwrap(); - let made = making.elapsed(); - let waited = device.work_counts().registrations_waited - waited; - scheduled(&command_buffer); - let submitted = committed.elapsed(); - command_buffer.wait_until_completed_for(WAIT).unwrap(); - assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); - drop(texture); - eprintln!( - "FIRST-USE {name}: a Private texture made {:.1} ms after the commit of {fills} \ - fills took {:.3} ms, its registration waiting {waited} times for a \ - submission's place; the command buffer was scheduled {:.1} ms after its commit", - AFTER_COMMIT.as_secs_f64() * 1e3, - made.as_secs_f64() * 1e3, - submitted.as_secs_f64() * 1e3, - ); - if submitted < LONG_REPLAY && fills < MOST_REPLAY_FILLS { - fills *= 2; - continue; - } - assert!( - submitted >= LONG_REPLAY, - "{MOST_REPLAY_FILLS} fills were scheduled {submitted:?} after their commit, \ - short of {LONG_REPLAY:?}" - ); - assert_eq!( - waited, 0, - "a texture made {AFTER_COMMIT:?} after the commit, {submitted:?} before its \ - command buffer was scheduled, waited for a submission's place" - ); - break; - } - drop(first); - }); -} - /// A `Private` buffer of `len` bytes made where a buffer that held `node(A)` was just released /// (most likely its memory): a fill that did not run would leave those bytes. Whether the /// memory was the released one's, printed. diff --git a/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs index 77194ea3b..4212c05ed 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs @@ -44,7 +44,7 @@ //! layouts of equal shapes (`WorkCounts::set_zero_equal_shape_switches` and kin), the passes whose //! first instance recorded inline and the others by the check that ruled it out //! (`WorkCounts::inline_passes`, `WorkCounts::passes_not_inline_actions` and kin) -//! with the render pass begins and secondary executions the recorder's replays called +//! with the render pass begins and secondary executions recorded //! (`WorkCounts::commands_replayed`), and the device's live //! `VkDeviceMemory` by kind after the timed frames (ANV on i915 lists each in every kernel //! submission). Then the CPU time of the @@ -1594,11 +1594,10 @@ 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); 4] = [ +const THREAD_GROUPS: [(&str, &str); 3] = [ ("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 @@ -1867,8 +1866,7 @@ fn measure(runs: &[Run]) { eprintln!( "FRAME-COST {name} {label}: a frame's command buffers begun by what for: {:.1} \ encoders' own, {:.1} segments, {:.1} continuations, {:.1} draws' secondaries, {:.1} \ - batches' work, {:.1} batches' barriers, {:.1} barriers kept, {:.1} internal; their \ - logs replayed: {:.1} by the recorder's thread, {:.1} by threads that submit", + batches' work, {:.1} batches' barriers, {:.1} barriers kept, {:.1} internal", per_frame(|c| c.command_buffers_begun_encoders), per_frame(|c| c.command_buffers_begun_segments), per_frame(|c| c.command_buffers_begun_continuations), @@ -1877,8 +1875,6 @@ fn measure(runs: &[Run]) { per_frame(|c| c.command_buffers_begun_batch_barriers), per_frame(|c| c.command_buffers_begun_kept_barriers), per_frame(|c| c.command_buffers_begun_internal), - per_frame(|c| c.command_buffers_replayed), - per_frame(|c| c.command_buffers_replayed_inline), ); eprintln!( "FRAME-COST {name} {label}: a frame's groups of batches by what sent them: {:.1} \ diff --git a/crates/metal2vulkan-validation/src/runtime_lane/guest_frame_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/guest_frame_costs.rs index 0d3f0fa8d..b195ed642 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/guest_frame_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/guest_frame_costs.rs @@ -6,8 +6,7 @@ //! the medians and 90th percentiles of the frame's commit to completion (from the first commit to //! the last command buffer's completion), its GPU time (each command buffer's `GPUEndTime` less //! `GPUStartTime`, summed) and the process's CPU time, each busy thread's CPU time per frame (the -//! encoding thread, the recorder that replays its Vulkan commands, the scheduler, the queue's -//! waiter), and the work counts per frame (the merges' kept images live at the end too). +//! encoding thread, which records its Vulkan commands, the scheduler, the queue's waiter), and the work counts per frame (the merges' kept images live at the end too). use super::host_memory::Mapping; use super::no_copy_textures::{blending, floats, staged}; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/hidden_depth.rs b/crates/metal2vulkan-validation/src/runtime_lane/hidden_depth.rs index eab4e191a..3055e56f1 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, WorkCounts}; +use metal2vulkan_runtime::{Buffer, Error, RenderCommandEncoder, RuntimeGap, Viewport}; /// 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,9 +207,7 @@ 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`). 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`]). +/// (`WorkCounts::spare_command_pools_reset`). #[test] fn a_first_draw_s_instance_ends_the_one_it_replaces() { const PASSES: u64 = 4; @@ -231,11 +229,9 @@ 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; {replayed} of {deferred} \ - deferred command buffers begun replayed", + instances; {taken} spare pools taken, {reset} of them reset", probe.device.name(), visibility.is_some(), ); @@ -244,35 +240,10 @@ 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/crates/metal2vulkan-validation/src/runtime_lane/property_reads.rs b/crates/metal2vulkan-validation/src/runtime_lane/property_reads.rs index a0dcac0c3..feef04f98 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/property_reads.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/property_reads.rs @@ -3,8 +3,8 @@ //! and `error` reads wait for no GPU work and for no submission in progress. //! //! GPU busy work is committed first (`first_use::Busy`, released by the test), then on the same -//! queue one blit encoder of fills of distinct words, whose submission replays its deferred command -//! buffer (`recorder`) between its kernel start and its kernel end; its fills are doubled until +//! queue one blit encoder of fills of distinct words, whose submission lies between its kernel +//! start and its kernel end; its fills are doubled until //! that span is at least [`LONG_SUBMISSION`]. One thread reads the two kernel times over and over, //! from the commit until [`BEHIND_BUSY`] after the submission, while the fills wait behind the busy //! work, and another reads `status` and `error` over the same time, each between a read of the diff --git a/crates/metal2vulkan-validation/src/runtime_lane/rate_mapped_passes.rs b/crates/metal2vulkan-validation/src/runtime_lane/rate_mapped_passes.rs index 260cb09d3..c474f490c 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/rate_mapped_passes.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/rate_mapped_passes.rs @@ -875,8 +875,7 @@ fn a_pass_of_no_draw_call_over_a_mutable_map_hangs_until_one_drew() { /// 27.0.1): a pass over a mutable map not yet reset, and over a map of no layers made while no map /// of layers was released, mutable or not, runs its clear and store and each draw's vertex /// function (Metal's counted 3 runs for a triangle), and shades nothing. The runtime records the -/// draw through an empty scissor: its replay calls `vkCmdDraw` once (`commands_replayed`, on a -/// device that records through its recorder). +/// draw through an empty scissor: it records `vkCmdDraw` once (`commands_replayed`). #[test] fn a_pass_over_a_map_of_no_compiled_layers_runs_its_vertex_function_alone() { let unset = |screen: u32, layers: &[(f32, f32)]| { @@ -897,10 +896,8 @@ fn a_pass_over_a_map_of_no_compiled_layers_runs_its_vertex_function_alone() { fixture.draw(&map, &target, |_| {}).unwrap(); let after = device.work_counts(); assert!(cleared(&target), "{name}"); - if after.command_buffers_deferred > before.command_buffers_deferred { - let draws = after.commands_replayed.cmd_draw - before.commands_replayed.cmd_draw; - assert_eq!(draws, 1, "{name}: the vertex function's draw"); - } + let draws = after.commands_replayed.cmd_draw - before.commands_replayed.cmd_draw; + assert_eq!(draws, 1, "{name}: the vertex function's draw"); assert!(!announced_after_release(messages), "{name}"); }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/row_copies.rs b/crates/metal2vulkan-validation/src/runtime_lane/row_copies.rs index 360b0457b..8164bb4e7 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/row_copies.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/row_copies.rs @@ -17,9 +17,9 @@ //! `row_copies_cost` (ignored; run it with `--ignored --nocapture`) prints `ROW-COPIES` lines: a //! frame of one blit of `rows` rows of 1920 `BGRA8Unorm` texels from a tight buffer into a texture //! over a buffer whose rows lie 8192 bytes apart, for 1080 rows down to 2, timed over -//! [`TIMED`] frames after [`WARM`]: the CPU time a frame of the threads that replay it (the -//! recorder's and the scheduler's, from each thread's `schedstat`), of the encoding thread, the -//! command buffer's GPU time (`GPUEndTime - GPUStartTime`), and the commands its replays called. +//! [`TIMED`] frames after [`WARM`]: the CPU time a frame of the scheduler's thread (from its +//! `schedstat`), of the encoding thread, which records it, the command buffer's GPU time +//! (`GPUEndTime - GPUStartTime`), and the commands recorded. //! //! `long_copies_of_any_size_copy_metals_bytes` checks every byte of blits between buffers of one //! region each, of sizes a driver may record slowly as one region, which the runtime records as @@ -567,8 +567,8 @@ fn thread_cpu() -> Duration { } /// The costs a frame of `frame` on `device`, timed over [`TIMED`] frames after [`WARM`]: the CPU -/// time of the threads that replay it (the recorder's and the scheduler's) and of the encoding -/// thread, and the command buffer's GPU time, as words; with `device`'s work counts before and +/// time of the scheduler's thread and of the encoding thread, which records it, and the command +/// buffer's GPU time, as words; with `device`'s work counts before and /// after the timed frames. fn frame_costs( device: &Device, @@ -578,10 +578,7 @@ fn frame_costs( frame().wait_until_completed_for(WAIT).unwrap(); } let counts = device.work_counts(); - let (recorder, scheduler) = ( - threads_cpu("metal2vulkan-re"), - threads_cpu("metal2vulkan-sc"), - ); + let scheduler = threads_cpu("metal2vulkan-sc"); let mut encoding = Duration::ZERO; let mut gpu = Vec::with_capacity(TIMED); for _ in 0..TIMED { @@ -600,9 +597,7 @@ fn frame_costs( let per = |d: Duration| d.as_secs_f64() * 1e3 / TIMED as f64; gpu.sort_by(f64::total_cmp); let costs = format!( - "recorder {:.3} ms, scheduler {:.3} ms, encoding {:.3} ms a frame; GPU {:.1} us (p90 \ - {:.1})", - per(threads_cpu("metal2vulkan-re") - recorder), + "scheduler {:.3} ms, encoding {:.3} ms a frame; GPU {:.1} us (p90 {:.1})", per(threads_cpu("metal2vulkan-sc") - scheduler), per(encoding), gpu[TIMED / 2], diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index ab244b923..0e5932f95 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 477; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1691; +pub const RUNTIME_VERSION: u32 = 1692; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index e91b9194f..a366fcc32 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2455,9 +2455,6 @@ field metal2vulkan-runtime::WorkCounts.command_buffers_begun_internal pub comman field metal2vulkan-runtime::WorkCounts.command_buffers_begun_kept_barriers pub command_buffers_begun_kept_barriers: u64 field metal2vulkan-runtime::WorkCounts.command_buffers_begun_secondaries pub command_buffers_begun_secondaries: u64 field metal2vulkan-runtime::WorkCounts.command_buffers_begun_segments pub command_buffers_begun_segments: u64 -field metal2vulkan-runtime::WorkCounts.command_buffers_deferred pub command_buffers_deferred: u64 -field metal2vulkan-runtime::WorkCounts.command_buffers_replayed pub command_buffers_replayed: u64 -field metal2vulkan-runtime::WorkCounts.command_buffers_replayed_inline pub command_buffers_replayed_inline: u64 field metal2vulkan-runtime::WorkCounts.command_buffers_submitted pub command_buffers_submitted: u64 field metal2vulkan-runtime::WorkCounts.command_pools_made pub command_pools_made: u64 field metal2vulkan-runtime::WorkCounts.commands_noted_as_before pub commands_noted_as_before: u64 @@ -7006,7 +7003,7 @@ macro-template metal2vulkan-air::metal_flags! ( $(#[$meta:meta])* $name:ident = macro-template metal2vulkan-air::vk_bit! ( $(#[$meta:meta])* $name:ident($raw:ty) = $vk:literal in $flags:ident { $($konst:ident = $value:literal, $vkname:literal;)* } aliases { $($alias:literal => $target:ident;)* } ) => { $(#[$meta])* #[repr(transparent)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", serde(try_from = "u32", into = "u32"))] pub struct $name($raw); impl $name { $( #[doc = concat!("`", $vkname, "`.")] pub const $konst: $name = $name($value); )* pub const VK_NAME: &'static str = $vk; pub const KNOWN: &'static [$name] = &[$($name::$konst),*]; const NAMES: &'static [($name, &'static str)] = &[$(($name::$konst, $vkname)),*]; const ALIASES: &'static [(&'static str, $name)] = &[$(($alias, $name::$target)),*]; pub const fn from_raw(raw: $raw) -> Option<$name> { let mut i = 0; while i < Self::KNOWN.len() { if Self::KNOWN[i].0 == raw { return Some(Self::KNOWN[i]); } i += 1; } None } pub const fn from_flags(flags: $flags) -> Option<$name> { Self::from_raw(flags.as_raw()) } pub const fn as_raw(self) -> $raw { self.0 } pub const fn flags(self) -> $flags { $flags::from_raw(self.0) } pub fn name(self) -> &'static str { Self::NAMES .iter() .find(|(v, _)| *v == self) .map(|(_, n)| *n) .expect("a single-bit value is always a named bit") } pub fn from_name(name: &str) -> Option<$name> { Self::NAMES .iter() .find(|(_, n)| *n == name) .map(|(v, _)| *v) .or_else(|| Self::ALIASES.iter().find(|(n, _)| *n == name).map(|(_, v)| *v)) } } impl ::std::convert::TryFrom<$raw> for $name { type Error = $raw; fn try_from(raw: $raw) -> Result<$name, $raw> { $name::from_raw(raw).ok_or(raw) } } impl From<$name> for $raw { fn from(bit: $name) -> $raw { bit.0 } } impl From<$name> for $flags { fn from(bit: $name) -> $flags { bit.flags() } } impl ::std::fmt::Debug for $name { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { f.write_str(self.name()) } } }; macro-template metal2vulkan-air::vk_enum! ( $(#[$meta:meta])* $name:ident($raw:ty) = $vk:literal { $($konst:ident = $value:literal, $vkname:literal;)* } aliases { $($alias:literal => $target:ident;)* } ) => { $(#[$meta])* #[repr(transparent)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", serde(transparent))] pub struct $name($raw); impl $name { $( #[doc = concat!("`", $vkname, "`.")] pub const $konst: $name = $name($value); )* pub const VK_NAME: &'static str = $vk; pub const KNOWN: &'static [$name] = &[$($name::$konst),*]; const NAMES: &'static [($name, &'static str)] = &[$(($name::$konst, $vkname)),*]; const ALIASES: &'static [(&'static str, $name)] = &[$(($alias, $name::$target)),*]; pub const fn from_raw(raw: $raw) -> $name { $name(raw) } pub const fn as_raw(self) -> $raw { self.0 } pub fn name(self) -> Option<&'static str> { Self::NAMES.iter().find(|(v, _)| *v == self).map(|(_, n)| *n) } pub fn is_known(self) -> bool { self.name().is_some() } pub fn from_name(name: &str) -> Option<$name> { Self::NAMES .iter() .find(|(_, n)| *n == name) .map(|(v, _)| *v) .or_else(|| Self::ALIASES.iter().find(|(n, _)| *n == name).map(|(_, v)| *v)) } } impl ::std::fmt::Debug for $name { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self.name() { Some(name) => f.write_str(name), None => write!(f, "{}({})", $vk, self.0), } } } }; macro-template metal2vulkan-air::vk_flags! ( $(#[$meta:meta])* $name:ident($raw:ty) = $vk:literal { $($konst:ident = $value:literal, $vkname:literal;)* } aliases { $($alias:literal => $target:ident;)* } ) => { $(#[$meta])* #[repr(transparent)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", serde(transparent))] pub struct $name($raw); impl $name { $( #[doc = concat!("`", $vkname, "`.")] pub const $konst: $name = $name($value); )* pub const VK_NAME: &'static str = $vk; pub const KNOWN: &'static [($name, &'static str)] = &[$(($name::$konst, $vkname)),*]; const ALIASES: &'static [(&'static str, $name)] = &[$(($alias, $name::$target)),*]; pub const fn empty() -> $name { $name(0) } pub const fn from_raw(raw: $raw) -> $name { $name(raw) } pub const fn as_raw(self) -> $raw { self.0 } pub const fn is_empty(self) -> bool { self.0 == 0 } pub const fn contains(self, other: $name) -> bool { self.0 & other.0 == other.0 } pub const fn intersects(self, other: $name) -> bool { self.0 & other.0 != 0 } pub const fn union(self, other: $name) -> $name { $name(self.0 | other.0) } pub const fn intersection(self, other: $name) -> $name { $name(self.0 & other.0) } pub const fn difference(self, other: $name) -> $name { $name(self.0 & !other.0) } pub const fn known_bits() -> $name { let mut bits: $raw = 0; let mut i = 0; while i < Self::KNOWN.len() { let v = Self::KNOWN[i].0 .0; if v.count_ones() == 1 { bits |= v; } i += 1; } $name(bits) } pub fn name(self) -> Option<&'static str> { Self::KNOWN.iter().find(|(v, _)| *v == self).map(|(_, n)| *n) } pub fn from_name(name: &str) -> Option<$name> { Self::KNOWN .iter() .find(|(_, n)| *n == name) .map(|(v, _)| *v) .or_else(|| Self::ALIASES.iter().find(|(n, _)| *n == name).map(|(_, v)| *v)) } } impl ::std::ops::BitOr for $name { type Output = $name; fn bitor(self, rhs: $name) -> $name { self.union(rhs) } } impl ::std::ops::BitOrAssign for $name { fn bitor_assign(&mut self, rhs: $name) { *self = self.union(rhs); } } impl ::std::ops::BitAnd for $name { type Output = $name; fn bitand(self, rhs: $name) -> $name { self.intersection(rhs) } } impl ::std::ops::BitAndAssign for $name { fn bitand_assign(&mut self, rhs: $name) { *self = self.intersection(rhs); } } impl ::std::fmt::Debug for $name { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { if let Some(name) = self.name() { return f.write_str(name); } let mut rest = self.0; let mut first = true; for (v, n) in Self::KNOWN { if v.0.count_ones() == 1 && rest & v.0 != 0 { if !first { f.write_str(" | ")?; } f.write_str(n)?; rest &= !v.0; first = false; } } if rest != 0 || first { if !first { f.write_str(" | ")?; } write!(f, "{:#x}", rest)?; } Ok(()) } } }; -macro-template metal2vulkan-runtime::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)?;)* } ) => { #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum Command { $($v0,)* $($v3,)* $($ve,)* } impl Command { pub(crate) const ALL: &'static [Command] = &[ $(Command::$v0,)* $(Command::$v3,)* $(Command::$ve,)* ]; pub(crate) const COUNT: usize = Command::ALL.len(); pub(crate) fn name(self) -> &'static CStr { match self { $(Command::$v0 => $n0,)* $(Command::$v3 => $n3,)* $(Command::$ve => $ne,)* } } } #[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 { 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),)* } } } 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)?;)*); 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,)* } } 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),)* } } 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()); } unsafe { std::mem::transmute_copy::<*mut c_void, F>(&real) } } 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);)* } 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)?;)*) => { $( unsafe extern "system" fn $f( command_buffer: vk::CommandBuffer, $($a: $t,)* ) $(-> $r)? { 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); } unsafe { let real = std::mem::transmute::< *mut c_void, unsafe extern "system" fn(vk::CommandBuffer, $($t,)*) $(-> $r)?, >(real); real(command_buffer, $($a,)*) } } )* }; +macro-template metal2vulkan-runtime::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)?;)* } ) => { #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum Command { $($v0,)* $($v3,)* $($ve,)* } impl Command { pub(crate) const ALL: &'static [Command] = &[ $(Command::$v0,)* $(Command::$v3,)* $(Command::$ve,)* ]; pub(crate) const COUNT: usize = Command::ALL.len(); pub(crate) fn name(self) -> &'static CStr { match self { $(Command::$v0 => $n0,)* $(Command::$v3 => $n3,)* $(Command::$ve => $ne,)* } } } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct CommandsReplayed { $( #[doc = concat!("The calls of `", stringify!($v0), "`.")] pub $f0: u64, )* $( #[doc = concat!("The calls of `", stringify!($v3), "`.")] pub $f3: u64, )* $( #[doc = concat!("The calls of `", stringify!($ve), "`.")] pub $fe: u64, )* } impl CommandsReplayed { 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),)* } } } 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 $($v0 $f0 $n0 ($($a0: $t0),*) $(-> $r0)?;)*); commands!(@thunks $($v3 $f3 $n3 ($($a3: $t3),*) $(-> $r3)?;)*); commands!(@thunks $($ve $fe $ne ($($ae: $te),*) $(-> $re)?;)*); 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,)* } } 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),)* } } 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);)* } 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 $($v:ident $f:ident $n:literal ($($a:ident: $t:ty),*) $(-> $r:ty)?;)*) => { $( unsafe extern "system" fn $f( command_buffer: vk::CommandBuffer, $($a: $t,)* ) $(-> $r)? { COUNTS[S][Command::$v as usize].fetch_add(1, Ordering::Relaxed); let real = REAL.$f[S].load(Ordering::Acquire); if real.is_null() { missing($n); } unsafe { let real = std::mem::transmute::< *mut c_void, unsafe extern "system" fn(vk::CommandBuffer, $($t,)*) $(-> $r)?, >(real); real(command_buffer, $($a,)*) } } )* }; macro-template metal2vulkan-runtime::degradations! ( runtime { $( $(#[doc = $doc:literal])* $kind:ident = $code:literal, $category:ident, $cost:literal; )* } notes { $( $(#[doc = $note_doc:literal])* $note:ident = $note_code:literal; )* } ) => { #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Degradation { $($(#[doc = $doc])* $kind,)* $( #[doc = concat!( "A pipeline stage records [`PrecisionNote::", stringify!($note), "`](metal2vulkan::pipeline::PrecisionNote::", stringify!($note), ")." )] $(#[doc = $note_doc])* $note, )* } impl Degradation { pub const ALL: &'static [Degradation] = &[$(Degradation::$kind,)* $(Degradation::$note,)*]; pub const fn code(self) -> &'static str { match self { $(Degradation::$kind => concat!("metal2vulkan-degrade-", $code),)* $(Degradation::$note => concat!("metal2vulkan-degrade-", $note_code),)* } } pub const fn category(self) -> DegradationCategory { match self { $(Degradation::$kind => DegradationCategory::$category,)* $(Degradation::$note => DegradationCategory::Precision,)* } } pub const fn cost(self) -> &'static str { match self { $(Degradation::$kind => $cost,)* $(Degradation::$note => NOTE_COST,)* } } pub const fn precision_note(self) -> Option { match self { $(Degradation::$kind => None,)* $(Degradation::$note => Some(PrecisionNote::$note),)* } } pub const fn from_precision_note(note: PrecisionNote) -> Degradation { match note { $(PrecisionNote::$note => Degradation::$note,)* } } } }; macro-template metal2vulkan-runtime::exposures! ($($exposure:expr => [$($feature:ident),* $(,)?];)*) => { impl VkFeature { pub const ALL: &'static [VkFeature] = &[$($(VkFeature::$feature),*),*]; pub fn exposure(self) -> Exposure { match self { $($(VkFeature::$feature)|* => $exposure,)* } } } }; macro-template metal2vulkan-runtime::flag_set! ( $(#[$doc:meta])* $name:ident { $($(#[$fdoc:meta])* $flag:ident = $bit:expr),* $(,)? } $(#[$all:meta])* ALL ) => { $(#[$doc])* #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct $name(u8); impl $name { pub const NONE: $name = $name(0); $($(#[$fdoc])* pub const $flag: $name = $name($bit);)* $(#[$all])* pub const ALL: &'static [($name, &'static str)] = &[$(($name::$flag, stringify!($flag))),*]; pub const fn union(self, other: $name) -> $name { $name(self.0 | other.0) } pub const fn contains(self, other: $name) -> bool { self.0 & other.0 == other.0 } #[cfg(test)] pub const fn bits(self) -> u8 { self.0 } } };