diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index c14709bc3..e1102ff5d 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -32,7 +32,7 @@ use super::fresh_pages; use super::generated_commands::PREPROCESS_BUFFER; use super::heap::{Heap, HeapType}; use super::host_aliases::Alias; -use super::host_memory::{KeepAlive, Release}; +use super::host_memory::{HeldBack, KeepAlive, Release}; #[cfg(unix)] use super::host_residency::{Again, Residency}; use super::memory::{Mapped, MemoryClass, Placement, BLOCK_BYTES}; @@ -164,6 +164,9 @@ pub(super) struct HostCell { /// its pages are imported through a read-only view of them (`read_only_view.rs`), which a /// rebind's are too. drops_writes: bool, + /// The deallocator of the pages its last detach let go of (`detach.rs`), held back until its + /// next rebind or its release, as Metal runs it then ([`Release::hold_back`]). + held_back: Mutex>>, } /// The textures over a buffer's host pages ([`HostCell`]): their images, which a detach makes @@ -417,6 +420,51 @@ impl HostCell { lay } + /// A detach let go of `pages`: their deallocator is held back until the buffer's next rebind + /// or its release ([`HostCell::release_held_back`]), as Metal never runs it at a detach. + pub(super) fn hold_back(&self, pages: &HostPages) { + let Some(held) = pages.release.get().and_then(Release::hold_back) else { + return; + }; + let earlier = lock(&self.held_back).replace(held); + // Never so: a detached buffer is detached again by no detach, and a rebind runs what + // was held back first. Were it to be, the earlier one is due now. + if let Some(earlier) = earlier { + self.held_back_due(&earlier); + } + } + + /// The buffer's next rebind (inside the call, once its new pages are in place) or its release + /// came: the deallocator its last detach held back runs now, on this thread, as Metal runs it + /// there, or, where the pages it let go of are still imported (a texture's image over them + /// waits for a command buffer that may read it) and no keep-alive keeps them mapped, once + /// their import is freed, announced (`host-deallocator-delayed`). + pub(super) fn release_held_back(&self) { + let held = lock(&self.held_back).take(); + if let Some(held) = held { + self.held_back_due(&held); + } + } + + /// `held` is due ([`HostCell::release_held_back`]). + fn held_back_due(&self, held: &HeldBack) { + if !held.due() { + return; + } + let device = &self.device; + device.shared().counts.host_deallocator_delayed(); + device.degrade_once(Degradation::HostDeallocatorDelayed, || { + ( + "a detached no-copy buffer".to_owned(), + "the pages its detach let go of are still imported as it is rebound or released \ + (a texture's image over them may still be read through its resource ID by a \ + command buffer), and the caller gave no keep-alive: its deallocator runs once \ + their import is freed" + .to_owned(), + ) + }); + } + /// Note `noted`, a texture over the buffer's bytes (`TexturesOver`), forgetting those /// gone. fn watch_texture(&self, noted: NotedTexture) { @@ -1655,6 +1703,8 @@ impl Drop for BufferShared { if let Lying::In(pages) = cell.lying() { pages.released_listed(&self.device); } + // A detached buffer's deallocator runs at its release, as Metal's does. + cell.release_held_back(); } } } @@ -2355,6 +2405,7 @@ impl Device { exposed: AtomicU8::new(0), device: self.clone(), drops_writes, + held_back: Mutex::new(None), }); self.shared().rebinds.register(key, &cell); Lie::Host(cell) diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index 758a285ab..ac734bd7f 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -770,8 +770,11 @@ impl Device { if !stood_in.is_empty() { super::heap_sets::retire(self, Box::new(stood_in)); } - // The old pages go now where no command buffer holds them, their deallocator with them. + // The old pages go now where no command buffer holds them, their deallocator with them; + // the deallocator a detach held back runs now, inside the call, as Metal runs it at the + // replace (`HostCell::release_held_back`). drop(old); + cell.release_held_back(); // The command buffers committed before the rebind and not yet first submitted whose // encoders named the buffer are encoded again over the new pages, in this call, before // their first submission (`command_buffer/reencode.rs`), as Metal resolves them then. diff --git a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs index 632c7c75b..d9dc31ba5 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs @@ -121,6 +121,7 @@ use crate::error::{CommandBufferError, Error, MemoryKind, VkResultCode}; use crate::event::EventShared; use crate::exit_guard::{self, Call}; use crate::gpu_time; +use crate::rebind::SubmittedHolds; use crate::release; use crate::Device; use ash::vk; @@ -212,6 +213,10 @@ pub(crate) struct Submitted { pub(crate) fence: Option, /// The events it signals, with their signal indices. pub(crate) signals: Vec<(Arc, u64)>, + /// The holds of what its event group's commands took that its completion lets go + /// (`State::holds_until`): at once, or, where it ends its command buffer, once the command + /// buffer's completed handlers ran. + pub(crate) holds: Vec, } impl Completion { @@ -378,7 +383,7 @@ fn turns(watch: &Watch, lists: &mut FenceLists) -> bool { /// reached, the scheduler told, their fences settled, then, for each that ends its command buffer, /// its timestamps read and its GPU times placed, and its transition posted. False once the /// process is exiting. -fn finish(watch: &Watch, lists: &mut FenceLists, finished: Vec<(usize, Submitted)>) -> bool { +fn finish(watch: &Watch, lists: &mut FenceLists, mut finished: Vec<(usize, Submitted)>) -> bool { // The host time the batches were seen complete: an uncalibrated command buffer's GPU end // (`gpu_time.rs`). let seen = gpu_time::host_nanos(); @@ -389,6 +394,13 @@ fn finish(watch: &Watch, lists: &mut FenceLists, finished: Vec<(usize, Submitted else { return true; }; + // The holds of the batches that end no command buffer go first, their work completed: a + // detach that sees one of their signals detaches what only they held (`detach.rs`). + for (_, batch) in &mut finished { + if !batch.last { + batch.holds.clear(); + } + } // Their event signals are seen before the scheduler looks again: a batch whose submission // checks wait for a GPU signal to land may now go. for (_, batch) in &finished { @@ -407,11 +419,15 @@ fn finish(watch: &Watch, lists: &mut FenceLists, finished: Vec<(usize, Submitted buffer, last, fence, + holds, .. } = batch; lists.gathered.extend(fence.map(|fence| (queue, fence))); if last { - lock(&buffer.state).times.completed = seen; + let mut state = lock(&buffer.state); + state.times.completed = seen; + state.keep_holds(holds); + drop(state); ending.push(buffer); } } @@ -465,11 +481,15 @@ fn fail(watch: &Watch, ending: Vec>, error: CommandBuf buffer, last, fence, + holds, .. } = batch; if let Some(fence) = fence { let_go(buffer.device(), queue, fence); } + if last { + lock(&buffer.state).keep_holds(holds); + } last.then_some(buffer) }); for buffer in ending.into_iter().chain(failed) { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs index e946e2851..96c5ecd55 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs @@ -7,9 +7,12 @@ //! holds the pages its commands took of buffers over host pages (`rebind::Taken`) and the live //! buffers' table its resident set was made of (`Live`) weakly: a rebind or a release meanwhile //! lets the pages go, their deallocator run, where no submitted command buffer holds them -//! (the question, answered without revoking anything). From the first submission on it holds them -//! until it completes, so a submitted command buffer keeps the pages it took, as Metal's does -//! (table 3: a submitted command buffer never sees the new pages). A root table recorded +//! (the question, answered without revoking anything). The pages an event group's commands took +//! (its batches between event waits and signals, `State::event_group`) are held from that +//! group's first batch's submission until the command buffer completes, so submitted work keeps +//! the pages it took, as Metal's does (table 3: a submitted command buffer never sees the new +//! pages); a detach waits for, or refuses on, that group only until its work completed +//! (`rebind::SubmittedHolds`), as Metal holds a submission's uses. A root table recorded //! before then, by a rebind's encoding again (`reencode.rs`) or a host step, holds the table //! (`State::hold_live`) until the first submission, which lets go of it where the list changed //! meanwhile: at once, as Metal lets a released buffer go, but on a handler thread @@ -46,8 +49,16 @@ //! release meanwhile takes effect in its commands, which are recorded once. What its commands //! named is encoded or recorded again as an encoder's commands are (`reencode.rs`). //! - **Each submission at its own batch**. The first submission finds which of Metal's submissions -//! are rebound, against the pages and the table it fixes for every later batch; each fails only -//! as its own batch is submitted, after that batch's submission checks (`checks.rs`). One its +//! of the first event group are rebound or hold a detached buffer, and each later group's first +//! batch those of its group, against where the buffers lie then, as Metal decides each +//! submission as it submits it (a detach between two submissions fails the later one, code 8, +//! the earlier one having run: the M3 Max under macOS 27.0.1). A rebind before a later group's +//! submission encodes its encoders that named the buffer again, as before the first +//! (`reencode.rs`): Metal's later submission runs over the new pages. The table its first +//! submission fixes serves every later batch: a later group reaches a buffer detached or +//! rebound since then through an address (made resident, or unnamed) through the pages it took, +//! where Metal's reads the new pages or zeros. Each fails only as its own batch is submitted, +//! after that batch's submission checks (`checks.rs`). One its //! check failed already keeps the check's code (8 for the consumer's detach) and announces //! nothing, and so does one whose every encoder the commit's failure failed (`commit_failed`'s); //! the submissions before it run as Metal runs them, and the command buffer fails with the first @@ -61,10 +72,11 @@ 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; +use crate::rebind::{SubmittedHolds, Submitting}; use crate::residency::Residency; use crate::upload::Upload; use crate::used_resources::UsedResources; +use crate::values::CommandBufferStatus; use crate::Device; use metal2vulkan::bind::{ResidentRange, ResidentSet, RootTable}; use std::collections::{BTreeMap, BTreeSet}; @@ -318,17 +330,20 @@ impl State { } /// As its first batch is submitted (the module docs), on the thread that submits it, under - /// the scheduler's lock and its own, after that batch's checks: Metal's submissions found - /// rebound, or holding a detached buffer, go to `failing`, each to fail as its own batch is - /// submitted (`State::failing_at`). What its commands took is judged and held under one lock of - /// the device's buffers over host pages (`Submitting`), so a detach comes either before (and - /// fails the submission) or after (and waits for the command buffer). Nothing here lets pages - /// go: the weak holds become strong, and what it held strongly it retains. + /// the scheduler's lock and its own, after that batch's checks: Metal's submissions of its first + /// event group ([`State::event_group`]) found rebound, or holding a detached buffer, go to + /// `failing`, each to fail as its own batch is submitted (`State::failing_at`). What the + /// group's commands took is judged and held under one lock of the device's buffers over host + /// pages (`Submitting`), so a detach comes either before (and fails the submission) or after + /// (and waits for the group's work); a later group's is judged and held as its own first + /// batch is submitted (`State::failing_at`). Nothing here lets pages go: the weak holds become + /// strong, and what it held strongly it retains. /// `Ok(false)`, changing nothing, while a rebind since its commit has encoders of it, which /// `buffer`'s rebinds mark, to encode again (`reencode.rs`): read under the lock its rebinds /// mark them under, so a rebind comes either before this submission (which waits for them) - /// or after it (which keeps the old pages). From here it waits for no rebind's replay; its - /// encoders' logs stay until its release (`CommandBufferShared::complete`). + /// or after it (which keeps the old pages for this group). From here it waits for no + /// rebind's replay; its encoders' logs stay until its release + /// (`CommandBufferShared::complete`). pub(super) fn first_submission( &mut self, device: &Device, @@ -336,67 +351,30 @@ impl State { ) -> Result { let shared = device.shared(); let mut verdicts = BTreeMap::new(); - let mut moved = false; let mut holds = SubmittedHolds::new(device); - { + let group = self.event_group(0); + let parts = self.group_parts(&group); + let encoders = self.first_parts(parts.clone()); + let moved = { let mut submitting = shared.rebinds.submitting(); if buffer.reencode_pending() { return Ok(false); } self.submitted = true; - submitting.submitted_now(&shared.rebinds, buffer); - let State { - ended, - recorded, - retained, - rebound_use, - .. - } = self; - for (at, record) in ended.iter_mut().enumerate() { - let found = submitting.submit(&mut record.taken, retained, &mut holds); - moved |= found.moved; - judge(&mut verdicts, at, found.failure()); - if found.failure() == Some(CommandBufferError::EncodedUseRebound) { - let at_commands = match (&record.replay, &record.refused) { - (None, _) => ReboundAt::Unlogged(record.unlogged), - (Some(_), Some(refusal)) => ReboundAt::Refused(refusal.clone()), - (Some(_), None) => ReboundAt::NotEncodedAgain, - }; - rebound_use.get_or_insert(ReboundUse { - encoder: at, - kind: record.kind, - at: at_commands, - }); - } + self.judged_to = group.end; + if group.end == self.batches.all().len() { + submitting.submitted_now(&shared.rebinds, buffer); } - for part in recorded.iter_mut() { - let kind = ended.get(part.encoder).map(|record| record.kind); - for segment in &mut part.segments { - let recording = match (segment.gpu_alone, segment.stepped) { - (true, _) => Recording::GpuAlone, - (false, true) => Recording::HostStep, - (false, false) => Recording::Commit, - }; - let Some(done) = segment.recorded.as_mut() else { - continue; - }; - let found = submitting.submit(&mut done.taken, retained, &mut holds); - moved |= found.moved; - judge(&mut verdicts, part.encoder, found.failure()); - if let (Some(CommandBufferError::EncodedUseRebound), Some(kind)) = - (found.failure(), kind) - { - rebound_use.get_or_insert(ReboundUse { - encoder: part.encoder, - kind, - at: ReboundAt::Segment(recording), - }); - } - } - } - } + self.judge_group( + &mut submitting, + &encoders, + parts.clone(), + &mut verdicts, + &mut holds, + ) + }; if !holds.is_empty() { - self.submitted_holds.push(holds); + self.submitted_holds.push((group.end - 1, holds)); } // The list changed since the commit: what it listed is listed again, a rebind having // ended its use, and its resident set made of the list as it stands. @@ -425,23 +403,10 @@ impl State { // at its own batch, after its check. self.failing = self.failing_submissions(&verdicts); // Their names let go; the listing released without the lock. + self.judged(&encoders, parts); let State { - ended, - recorded, - retained, - listing, - .. + retained, listing, .. } = self; - for record in ended.iter_mut() { - record.taken.judged(); - } - let segments = recorded - .iter_mut() - .flat_map(|part| part.segments.iter_mut()) - .filter_map(|segment| segment.recorded.as_mut()); - for done in segments { - done.taken.judged(); - } // An empty listing (a command buffer that used no no-copy buffer and no heap) holds // nothing to let go of. if let Some(Listing { used, .. }) = listing.take() { @@ -485,6 +450,72 @@ impl State { .collect() } + /// As batch `index` is submitted, after the first submission, where it begins a later event + /// group ([`State::event_group`]): that group's commands are judged and held as the first + /// submission judged the first group's, as Metal decides each submission as it submits it, + /// those found rebound or holding a detached buffer going to `failing`. `false`, changing + /// nothing, while a rebind since the last group's submission has encoders of this one, which + /// `buffer`'s rebinds mark, to encode again (`reencode.rs`): read under the lock its rebinds + /// mark them under, so a rebind comes either before this group's submission (which waits for + /// them) or after it. From the last group on it waits for no rebind's replay. + pub(super) fn later_group( + &mut self, + device: &Device, + buffer: &CommandBufferShared, + index: usize, + ) -> bool { + let group = self.event_group(index); + if index == 0 || group.start != index { + return true; + } + let shared = device.shared(); + let parts = self.group_parts(&group); + let encoders = self.first_parts(parts.clone()); + let mut verdicts = BTreeMap::new(); + let mut holds = SubmittedHolds::new(device); + { + let mut submitting = shared.rebinds.submitting(); + if buffer.reencode_pending() { + return false; + } + self.judged_to = group.end; + if group.end == self.batches.all().len() { + submitting.submitted_now(&shared.rebinds, buffer); + } + self.judge_group( + &mut submitting, + &encoders, + parts.clone(), + &mut verdicts, + &mut holds, + ); + } + self.judged(&encoders, parts); + let failing = self.failing_submissions(&verdicts); + self.failing.extend(failing); + if !holds.is_empty() { + self.submitted_holds.push((group.end - 1, holds)); + } + true + } + + /// Whether it completed or failed: no rebind encodes it again. + pub(super) fn finished(&self) -> bool { + matches!( + self.status, + CommandBufferStatus::Completed | CommandBufferStatus::Error + ) + } + + /// The first part of the event groups not judged yet ([`State::later_group`]): the parts from + /// it on are what a rebind may encode again (`reencode.rs`). + pub(super) fn unjudged_parts(&self) -> usize { + match self.batches.all().len() { + len if self.judged_to >= len => self.recorded.len(), + _ => self.batch_range(self.judged_to).start, + } + } + /// As batch `index` is submitted, after its checks ran: the segments a host step recorded /// for it since the first submission are judged and held as the first submission judged the /// rest (`State::first_submission`); then each of Metal's submissions found failing that @@ -497,6 +528,7 @@ impl State { /// Metal's runs, whatever the command buffer failed with before. pub(super) fn failing_at(&mut self, device: &Device, index: usize) -> bool { let range = self.batch_range(index); + let group = self.event_group(index); let mut later = BTreeMap::new(); let mut holds = SubmittedHolds::new(device); let mut found_later = None; @@ -528,7 +560,7 @@ impl State { } } if !holds.is_empty() { - self.submitted_holds.push(holds); + self.submitted_holds.push((group.end - 1, holds)); } if self.failing.is_empty() && later.is_empty() { return false; @@ -570,6 +602,129 @@ impl State { .any(|(_, failure)| *failure == CommandBufferError::EncodedUseRebound) } + /// The batches of the event group batch `index` lies in: the run of batches around it that + /// no event (or binary semaphore) wait or signal splits. Metal holds what a group's + /// submissions use from the group's submission until its work completed (a buffer's detach + /// waits for that work, and one with its later work behind a wait detaches at once, measured + /// on the M3 Max), and the runtime judges and holds a group's commands as its first batch is + /// submitted ([`State::first_submission`], [`State::failing_at`]), letting go as its last + /// batch's work completed (`CommandBufferShared::holds_until`). + pub(super) fn event_group(&self, index: usize) -> Range { + let batches = self.batches.all(); + let splits = |at: usize| { + at == 0 + || at >= batches.len() + || !batches[at].waits.is_empty() + || !batches[at].binary_waits.is_empty() + || !batches[at - 1].signals.is_empty() + || !batches[at - 1].binary_signals.is_empty() + }; + let start = (0..=index).rev().find(|&at| splits(at)).unwrap_or(0); + let end = (index + 1..=batches.len()) + .find(|&at| splits(at)) + .unwrap_or(batches.len()); + start..end + } + + /// The parts of the ended encoders the batches of `group` hold. + fn group_parts(&self, group: &Range) -> Range { + let start = self.batch_range(group.start).start; + let end = self.batch_range(group.end - 1).end; + start..end + } + + /// The ended encoders whose first part lies among `parts`, in order. + fn first_parts(&self, parts: Range) -> Vec { + parts + .filter(|&at| at == 0 || self.recorded[at - 1].encoder != self.recorded[at].encoder) + .map(|at| self.recorded[at].encoder) + .collect() + } + + /// Judge and hold what `encoders` took, and the segments of `parts` recorded so far, against + /// where their buffers lie now (`Submitting::submit`): their failures go to `verdicts`, their + /// holds to `holds`, their pages to what the command buffer retains. Whether a buffer one took + /// lies elsewhere now. + fn judge_group( + &mut self, + submitting: &mut Submitting<'_>, + encoders: &[usize], + parts: Range, + verdicts: &mut BTreeMap, + holds: &mut SubmittedHolds, + ) -> bool { + let mut moved = false; + let State { + ended, + recorded, + retained, + rebound_use, + .. + } = self; + for &at in encoders { + let Some(record) = ended.get_mut(at) else { + continue; + }; + let found = submitting.submit(&mut record.taken, retained, holds); + moved |= found.moved; + judge(verdicts, at, found.failure()); + if found.failure() == Some(CommandBufferError::EncodedUseRebound) { + let at_commands = match (&record.replay, &record.refused) { + (None, _) => ReboundAt::Unlogged(record.unlogged), + (Some(_), Some(refusal)) => ReboundAt::Refused(refusal.clone()), + (Some(_), None) => ReboundAt::NotEncodedAgain, + }; + rebound_use.get_or_insert(ReboundUse { + encoder: at, + kind: record.kind, + at: at_commands, + }); + } + } + for part in &mut recorded[parts] { + let kind = ended.get(part.encoder).map(|record| record.kind); + for segment in &mut part.segments { + let recording = match (segment.gpu_alone, segment.stepped) { + (true, _) => Recording::GpuAlone, + (false, true) => Recording::HostStep, + (false, false) => Recording::Commit, + }; + let Some(done) = segment.recorded.as_mut() else { + continue; + }; + let found = submitting.submit(&mut done.taken, retained, holds); + moved |= found.moved; + judge(verdicts, part.encoder, found.failure()); + if let (Some(CommandBufferError::EncodedUseRebound), Some(kind)) = + (found.failure(), kind) + { + rebound_use.get_or_insert(ReboundUse { + encoder: part.encoder, + kind, + at: ReboundAt::Segment(recording), + }); + } + } + } + moved + } + + /// Let go of the names of what `encoders` and the segments of `parts` took, once judged. + fn judged(&mut self, encoders: &[usize], parts: Range) { + for &at in encoders { + if let Some(record) = self.ended.get_mut(at) { + record.taken.judged(); + } + } + let segments = self.recorded[parts] + .iter_mut() + .flat_map(|part| part.segments.iter_mut()) + .filter_map(|segment| segment.recorded.as_mut()); + for done in segments { + done.taken.judged(); + } + } + /// Whether the commit's failure failed every encoder of Metal's submission of `encoders`. fn commit_failed(&self, encoders: &Range) -> bool { self.failed_at_commit diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 8cd4fdc44..2b13a5267 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -668,6 +668,10 @@ pub(super) struct State { /// Its first batch was submitted: from then on it holds what its commands took and the /// live buffers' table its resident set was made of until it completes. submitted: bool, + /// The batches before this one lie in event groups judged as they were submitted + /// (`State::first_submission`, `State::later_group`): a rebind encodes again only encoders + /// of the groups from here (`reencode.rs`). + judged_to: usize, /// Metal's submissions (`checks::metal_submissions`, by their ended encoders) its first /// submission found to name a buffer rebound since, or to hold a detached one, each with /// its failure: each fails as its own batch is submitted, after its check @@ -683,10 +687,12 @@ pub(super) struct State { /// The ended encoders whose submissions failed so: no part of one goes to a queue with work /// (`submit.rs` holds it to that). unrunnable: BTreeSet, - /// What its batches' commands took of buffers over host pages, held from its first - /// submission (`rebind::SubmittedHolds`): let go as its work completes, before its - /// completed handlers, so a detach waiting for it goes on once its GPU work ended. - submitted_holds: Vec, + /// What its batches' commands took of buffers over host pages, held from the submission of + /// their event group's first batch (`rebind::SubmittedHolds`, `State::event_group`), each with + /// the batch whose submission takes it ([`State::holds_until`]): let go as that batch's work + /// completed, or, for its last batch's, noted complete there and let go once its completed + /// handlers ran, as Metal answers a detach `NO` until then (measured on the M3 Max). + submitted_holds: Vec<(usize, SubmittedHolds)>, /// The encoders its commit's failure failed (`commit_failed`'s, Metal's own from a render /// pass, or a faulted encoder's: [`State::fail`]): a submission none of whose encoders /// runs so is spared its rebound verdict (`first_submission.rs`). @@ -1286,6 +1292,29 @@ impl State { Ok(()) } + /// The holds of what its commands took that batch `index`'s work lets go as it completes + /// (`State::submitted_holds`), for its submission to carry (`completion::Submitted`). + pub(super) fn holds_until(&mut self, index: usize) -> Vec { + if self.submitted_holds.is_empty() { + return Vec::new(); + } + let (now, later): (Vec<_>, Vec<_>) = self + .submitted_holds + .drain(..) + .partition(|(until, _)| *until <= index); + self.submitted_holds = later; + now.into_iter().map(|(_, holds)| holds).collect() + } + + /// The holds of its last batch, whose work completed: kept until its completed handlers ran + /// (`State::submitted_holds`). + pub(super) fn keep_holds(&mut self, holds: Vec) { + for mut held in holds { + held.ran(); + self.submitted_holds.push((usize::MAX, held)); + } + } + /// The encoders (or parts of them) of batch `index`. pub(super) fn batch_range(&self, index: usize) -> Range { let batches = self.batches.all(); @@ -1716,6 +1745,7 @@ impl CommandBuffer { stepped_tables: Vec::new(), listing: None, submitted: false, + judged_to: 0, failing: Vec::new(), rebound_use: None, replay_tables: Vec::new(), @@ -3834,6 +3864,7 @@ impl CommandBufferShared { last: true, fence, signals: Vec::new(), + holds: Vec::new(), }, ); } @@ -3957,6 +3988,8 @@ impl CommandBufferShared { let mut settled_pool = None; // The heap versions its commands bound, let go of once its completed handlers ran. let released_versions; + // No rebind encodes it again from here: a group that was never submitted runs nothing. + self.device.shared().rebinds.no_replays(self); { let mut state = lock(&self.state); // Every trail of the work it waited for (a pipeline's making, a twin's decode) was @@ -4073,8 +4106,11 @@ impl CommandBufferShared { // Its heap versions, uploads, pools and descriptor pools go once its completed // handlers ran (below). released_versions = state.heaps.clear(); - // Its work ended: a detach waiting for it goes on (`detach.rs`). - state.submitted_holds.clear(); + // Its work ended: a buffer's detach waiting for it answers `false` (`detach.rs`), and + // a detach answers so until its completed handlers ran (below), as Metal's does. + for (_, held) in &mut state.submitted_holds { + held.ran(); + } // Its work ended (its fences were signaled, or its queues drained after a failed // wait), so nothing of its pools is pending: its command pool goes to the device's // spares whatever its status, never released on this thread (`spares.rs`); its @@ -4128,6 +4164,10 @@ impl CommandBufferShared { exit_guard::program(|| handler(&buffer)); } } + // Its holds of what its commands took go once its completed handlers ran: a detach + // detaches from now on (`detach.rs`). Let go without the lock. + let holds = lock(&self.state).holds_until(usize::MAX); + drop(holds); let handled = Instant::now(); drop(buffer); // Its queue's slot comes back as its last completed handler returns, as Metal's does: a diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index aa42612fb..c711cf278 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -1,16 +1,20 @@ -//! A committed command buffer's encoders encoded again at a rebind, before its first submission -//! (the logs are `replay.rs`'s). +//! A committed command buffer's encoders encoded again at a rebind, before the submission of their +//! event group (the logs are `replay.rs`'s). //! //! - **Marked under the rebind's lock.** Its commit notes the command buffer, with the keys of //! the buffers over host pages its replayable encoders named, while its encoders' holds still -//! refuse a rebind of them (`Rebinds::wait_for_replay`). A rebind of one of them marks it -//! (`reencode`) under the device's lock of those buffers, the lock its first submission reads -//! the mark under (`State::first_submission`): that submission came before the rebind, and -//! keeps the old pages (Metal's table 3), or it waits, held at its place in the scheduler's -//! order, until the mark is gone. +//! refuse a rebind of them (`Rebinds::wait_for_replay`), until its last event group is +//! submitted or it completes. A rebind of one of them marks it (`reencode`) under the device's +//! lock of those buffers, the lock each group's submission reads the mark under +//! (`State::first_submission`, `State::later_group`): that submission came before the rebind, +//! and keeps the old pages (Metal's table 3), or it waits, held at its place in the +//! scheduler's order, until the mark is gone. A later group's encoders are encoded again as +//! the first's are: Metal's later submission of a command buffer whose earlier one ran reaches +//! the new pages (the M3 Max under macOS 27.0.1). //! - **Encoded again in the rebind's call.** The rebind then encodes again, on its own thread -//! (the program's call, under no lock of the runtime's), each encoder of the command buffer a -//! command of which named a buffer that lies elsewhere now than it took it, from its log, into +//! (the program's call, under no lock of the runtime's), each encoder of the command buffer's +//! groups not yet submitted a command of which named a buffer that lies elsewhere now than it +//! took it, from its log, into //! new `VkCommandBuffer`s of the command buffer's pool, and puts what it recorded in the //! encoder's place: its recordings, uses, executions, keys and what its commands took (held //! weakly, as the commit holds them). The first recording is never submitted. No GPU work is @@ -29,8 +33,8 @@ //! (`EncoderCore::finish_replay`), its own commands (a render pass's shadowed textures' //! copies and its other steps among them) recorded again around them. Its commit notes the //! keys that work named too (`State::keep_replays`): a rebind of one of them before the first -//! submission records the work of the encoders it does not encode again in its place, as the -//! commit did, over where the buffers lie now: its recording, what its commands took and what +//! submission (which alone points those tables) records the work of the encoders it does not +//! encode again in its place, as the commit did, over where the buffers lie now: its recording, what its commands took and what //! its host step needs. Work a host step recorded again since (with the barriers between its //! commands, `gpu_execute::Rerecord`, or as a route outgrew it, `DeferredPass::outgrown`) //! keeps that step's recording. @@ -51,28 +55,33 @@ use crate::replay::Replay; use crate::residency::Residency; use crate::resource::ResourceKey; use crate::used_resources::EncoderKind; +use std::collections::BTreeSet; use std::sync::atomic::Ordering; use std::sync::Arc; impl CommandBufferShared { /// A rebind since its commit, of a buffer one of its replayable encoders named, has them - /// to encode again ([`reencode`](Self::reencode)) before its first submission: marked under + /// to encode again ([`reencode`](Self::reencode)) before the submission of their event group: + /// marked under /// the device's lock of its buffers over host pages (`Rebinds::replace`). pub(crate) fn mark_reencode(&self) { self.reencode.fetch_add(1, Ordering::AcqRel); } - /// Whether its first submission waits for its encoders encoded again (the module docs). + /// Whether the submission of its next event group waits for its encoders encoded again (the + /// module docs). pub(crate) fn reencode_pending(&self) -> bool { self.reencode.load(Ordering::Acquire) > 0 } - /// Encode again each of its encoders that a command of named a buffer over host pages that - /// lies elsewhere now than the command took it, and record again the work its commit - /// recorded on the GPU alone (the module docs), on the rebind's thread, with no lock of the - /// runtime's held; then its first submission may go, and the scheduler looks again. Nothing - /// here fails the rebind: an encoder it cannot encode again, or work it cannot record on the - /// GPU alone again, keeps its first recording, which its first submission fails. + /// Encode again each encoder of its event groups not yet submitted that a command of named a + /// buffer over host pages that lies elsewhere now than the command took it, and record again + /// the work its commit recorded on the GPU alone before the first submission (the module + /// docs), on the rebind's thread, with no lock of the runtime's held; then the submission of + /// its next group may go, and the scheduler looks again. Nothing here fails the rebind: an + /// encoder it cannot encode again, or work it cannot record on the GPU alone again, keeps its + /// first recording, which its group's submission fails. A command buffer that completed + /// encodes nothing again. pub(crate) fn reencode(self: &Arc) { let turn = lock(&self.reencoding); let marked = self.reencode.load(Ordering::Acquire); @@ -80,16 +89,19 @@ impl CommandBufferShared { return; } let device = &self.device; + // The encoders of its event groups not submitted yet: those before were judged, and run + // over the pages they took. let moved: Vec<(usize, Arc)> = { let state = lock(&self.state); - match state.submitted { + match state.finished() { true => Vec::new(), false => { + let open: BTreeSet = (state.recorded[state.unjudged_parts()..].iter()) + .map(|part| part.encoder) + .collect(); let submitting = device.shared().rebinds.submitting(); - state - .ended - .iter() - .enumerate() + (state.ended.iter().enumerate()) + .filter(|(at, _)| open.contains(at)) .filter_map(|(at, record)| { let replay = record.replay.as_ref()?; submitting @@ -132,8 +144,9 @@ impl CommandBufferShared { } } // Its work recorded on the GPU alone in encoders not encoded again that named a buffer - // over host pages that lies elsewhere now, each segment by its part and its place - // there, which hold through this turn: only the first submission places segments, and + // over host pages that lies elsewhere now, before its first submission (which alone + // points their resident tables), each segment by its part and its place there, which + // hold through this turn: only the first submission places segments, and // it waits for the turn; a host step, which records one, takes the turn too. What it // reaches through its resident set its first submission points it at as it lies then. let alone: Vec<((usize, usize), Deferred)> = { @@ -179,8 +192,8 @@ impl CommandBufferShared { } } drop(handle); - // Its first submission may go, unless a rebind marked it meanwhile: that rebind's turn - // comes next and encodes what moved since. + // Its next group's submission may go, unless a rebind marked it meanwhile: that rebind's + // turn comes next and encodes what moved since. let _ = self .reencode .compare_exchange(marked, 0, Ordering::AcqRel, Ordering::Acquire); @@ -209,17 +222,17 @@ impl State { } /// Put `replayed`, ended encoder `at` encoded again, and what it made resident in its place, - /// before the first submission: each of its parts' recordings, uses and segments (recorded - /// on the GPU alone), its executions (the later encoders' and segments' places among them - /// moved by the difference), its keys, and what its commands and its segments' took (held - /// weakly until the first submission). What its first recording retained stays retained, + /// before the submission of its event group: each of its parts' recordings, uses and segments + /// (recorded on the GPU alone), its executions (the later encoders' and segments' places + /// among them moved by the difference), its keys, and what its commands and its segments' + /// took (held weakly until that submission). What its first recording retained stays retained, /// and so does what its first segments recorded and what their host steps needed; its /// `VkCommandBuffer`s go with the pool unsubmitted. Refused, changing nothing and giving /// `replayed` back, where its place holds other parts than the encoding again's, or a segment /// but a pending dispatch's (which goes, the encoding again having recorded it at once) or - /// work its commit recorded on the GPU alone, or the command buffer was submitted. Its - /// replays hold what its commands took with `device`, the device's functions - /// (`Replays::hold`). + /// 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`). pub(super) fn splice_replay( &mut self, device: &Vk, @@ -236,8 +249,10 @@ impl State { recorded.sparse.is_empty() && (recorded.segments.iter()).all(|segment| segment.pends() || segment.gpu_alone) }; - let fits = !self.submitted + let unjudged = self.unjudged_parts(); + let fits = !self.finished() && !parts.is_empty() + && parts.iter().all(|&part| part >= unjudged) && parts.len() == replayed.parts.len() && parts.iter().all(replaces) && !self.unrunnable.contains(&at) @@ -257,7 +272,7 @@ impl State { mut taken, heaps, } = replayed; - // Held weakly until the first submission, as the commit held what the first recording + // 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). diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index d1186f43f..e023228eb 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -256,8 +256,8 @@ pub(crate) enum Submitting { /// buffer's transition to `Scheduled` as it is held, where it ends it /// ([`Submission::schedule_held`]), the rest published once the group is submitted. Grouped, - /// Nothing submitted or changed: its first submission waits for encoders of it a rebind - /// encodes again (`reencode.rs`). + /// Nothing submitted or changed: the submission of its event group waits for encoders of it a + /// rebind encodes again (`reencode.rs`). Later, /// Nothing submitted or changed: the group held goes first, sent by what this says. AfterGroup(GroupEnd), @@ -331,9 +331,9 @@ impl CommandBufferShared { /// batch is for the caller to [`publish`](Self::publish) once its section ended /// ([`Submitting::Submitted`]), or waits in the scheduler's group for one kernel submission /// with the batches after it, its submission's changes made ([`Submitting::Grouped`], - /// `group.rs`). Nothing submitted or changed while its first submission waits for encoders - /// of it a rebind encodes again (`reencode.rs`, [`Submitting::Later`]), or while the group - /// held must go first ([`Submitting::AfterGroup`]): the caller holds the batch back at its + /// `group.rs`). Nothing submitted or changed while the submission of its event group waits for + /// encoders of it a rebind encodes again (`reencode.rs`, [`Submitting::Later`]), or while the + /// group held must go first ([`Submitting::AfterGroup`]): the caller holds the batch back at its /// place. Where the group went in this batch's submission, its outcome is the group's /// (`Group::take_outcome`). pub(crate) fn submit_batch( @@ -389,6 +389,11 @@ impl CommandBufferShared { return Ok(Submitting::Later); } } + // A later event group's, as its first batch is submitted, unless a rebind encodes + // encoders of it again. + if !state.later_group(device, self, index) { + return Ok(Submitting::Later); + } // Each of Metal's submissions it found rebound, or holding a detached buffer, fails as // its own batch is submitted, after the batch's checks: one a check failed keeps the // check's code. @@ -1044,6 +1049,8 @@ impl CommandBufferShared { // set: the stale-reach degrade's trigger decides (`detach.rs`). let reaches = state.heaps.bound(); let rebound_use = state.rebound_use.clone(); + // The holds its completion lets go (`State::holds_until`). + let holds = state.holds_until(index); drop(state); if rebound { device.degrade_encoded_use_rebound(rebound_use); @@ -1063,6 +1070,7 @@ impl CommandBufferShared { .into_iter() .map(|(event, signal, _)| (event, signal)) .collect(), + holds, }, handlers, forms, diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index d5bb5b1bb..cb2951997 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -1006,7 +1006,7 @@ impl ComputeCommandEncoder { .residency .use_resource(resource, usage, RenderStages::empty()); if let Some(used) = used { - self.core.retain(used); + self.core.made_resident(used); } if let ResourceRef::IndirectCommandBuffer(icb) = resource { if usage.contains(ResourceUsage::WRITE) { @@ -1047,7 +1047,7 @@ impl ComputeCommandEncoder { } for heap in heaps { for used in self.residency.use_heap(heap, RenderStages::empty()) { - self.core.retain(used); + self.core.made_resident(used); } } Ok(()) diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index d90be9aad..8f9ec91a0 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1777,7 +1777,10 @@ degradations! { /// - with no keep-alive, on a device whose driver fails pending work where memory a /// device-address buffer lay in is freed /// (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`: MoltenVK), while the - /// batches submitted before the import's memory went are in flight (`freed_memory.rs`). + /// batches submitted before the import's memory went are in flight (`freed_memory.rs`); + /// - with no keep-alive, a detached buffer's or heap's rebind or release while the pages + /// its detach let go of are still imported, as above: the deallocator its detach held + /// back (Metal runs it at the replace or the release) runs once they go (`detach.rs`). /// /// With a keep-alive the deallocator runs at the release, as Metal's, and the import keeps /// the keep-alive, which keeps the pages mapped, until it is freed: not announced. diff --git a/crates/metal2vulkan-runtime/src/detach.rs b/crates/metal2vulkan-runtime/src/detach.rs index f6a8af985..e3a41e2e0 100644 --- a/crates/metal2vulkan-runtime/src/detach.rs +++ b/crates/metal2vulkan-runtime/src/detach.rs @@ -4,22 +4,39 @@ //! //! A consumer that moves its pages lets go of the old ones before it has the new: the buffer or //! heap lies in no pages until a rebind gives it some. Metal's answers (the consumer's rebind -//! probe on the M3 Max, tables 1 to 3), which the runtime keeps: +//! probe on the M3 Max, tables 1 to 3, and the M3 Max under macOS 27.0.1), which the runtime +//! keeps: //! -//! - **The call.** It detaches at once, and answers `true`, unless a command buffer submitted -//! and not yet complete took the buffer or heap: through a command that named it (one of a -//! heap's buffers included), or through what it made resident (`use_resource`, `use_heap`). -//! Then a buffer's call blocks until each such command buffer completed and answers `false`, -//! detaching nothing; a heap's answers `false` at once. A lost device ends the wait -//! (`Err(DeviceLost)`). The wait holds no lock of the runtime's: a completion turn lets go -//! of each command buffer's holds without one (`rebind::SubmittedHolds`). -//! - **Pending work.** A command buffer whose first submission comes after the detach and whose -//! commands named the buffer or made it resident (a render pass whose attachment lies in the -//! bytes names them from its open), encoded before the detach or after it, fails at that -//! submission with `CommandBufferError::DetachedBacking` (Metal's code 8) and runs nothing of it; -//! one that only reaches the bytes unnamed reads zeros there (`live_buffers.rs` no longer lists -//! them) and runs. A rebind before that submission gives a command encoded while detached -//! `EncodedUseRebound` instead, the gap until encoded uses resolve at submission. +//! - **The call.** It detaches at once, and answers `true`, unless submitted work holds the +//! buffer or heap: a submission whose command named it (one of a heap's buffers included), or +//! whose encoder made it resident (`use_resource`, `use_heap`), holds it from its submission +//! until its work completed, and the command buffer's last submissions hold it until its +//! completed handlers ran (`rebind::SubmittedHolds`; an event wait or signal splits the +//! submissions, `State::event_group`). Then a buffer's call blocks until the work of each such +//! submission completed and answers `false`, detaching nothing; a heap's answers `false` at +//! once. So a detach in a completed handler of the command buffer that used the buffer answers +//! `false` (Metal's: 37 of 40 such detaches, the other 3 a race of its kernel's retire), and one +//! once its `wait_until_completed` returned detaches (36 of 40 on Metal, always 2 ms later). A +//! later submission of a command buffer, behind an event wait, holds nothing until it is +//! submitted: a detach while it waits detaches at once, whatever the command buffer's earlier +//! submissions held, which keep their pages until they complete. A lost device ends the wait +//! (`Err(DeviceLost)`). The wait holds no lock of the runtime's: a completion turn notes each +//! submission's work complete without one. +//! - **Pending work.** A submission that comes after the detach, the command buffer's first or a +//! later one, whose commands named the buffer or made it resident (a render pass whose +//! attachment lies in the bytes names them from its open), encoded before the detach or after +//! it, fails with `CommandBufferError::DetachedBacking` (Metal's code 8) and runs nothing of it, +//! its other submissions running; one that only reaches the bytes unnamed reads zeros there +//! (`live_buffers.rs` no longer lists them) and runs, where its command buffer's first +//! submission came after the detach. A rebind before the first submission gives a command +//! encoded while detached `EncodedUseRebound` instead, the gap until encoded uses resolve at +//! submission; so does a rebind before a later submission whose commands named the buffer, +//! which the rebind does not encode again. +//! - **The deallocator** of the pages a detach lets go of runs at the buffer's (or heap's) next +//! rebind, inside the call, on its thread, or at its release, on the releasing thread, never at +//! the detach, as Metal's (`HostCell::hold_back`): their import goes at the detach, once nothing +//! holds it; a keep-alive goes once both the deallocator ran and the import is freed, so the +//! deallocator may read the bytes. //! - **No memory.** A detached buffer takes the device's stand-in, a small buffer of the //! runtime's own shared by every detached buffer (`buffer::Detached`), never memory of its //! size. No command that takes the stand-in runs: an encoder whose command names a detached @@ -55,20 +72,23 @@ use std::sync::{Arc, Weak}; const STAND_IN_BYTES: u64 = 256; impl Buffer { - /// `detachBacking` (a runtime extension; the module docs of `detach.rs` state the rule): let - /// the no-copy buffer lie in no host pages until + /// `detachBacking` (Metal's private `MTLBuffer` method; the module docs of `detach.rs` state + /// the rule): let the no-copy buffer lie in no host pages until /// [`rebind_bytes_no_copy`](Buffer::rebind_bytes_no_copy) gives it some. `true` once it is - /// detached (at once, or it was already). Where a command buffer submitted and not yet - /// complete took the buffer, the call blocks until each such command buffer completed and - /// answers `false`, detaching nothing. The old memory's deallocator runs once every command - /// buffer submitted before the call that used it completed, and every open encoder that named - /// it was committed or dropped (in the call, where none holds it). The buffer, its - /// `gpu_address` and its options stay; `contents` answers `None` while it is detached. + /// detached (at once, or it was already). Where submitted work holds the buffer (a submission + /// that named it or made it resident, from its submission until its work completed, and the + /// command buffer's last submissions until its completed handlers ran), the call blocks until + /// that work completed and answers `false`, detaching nothing, as Metal's does. The old + /// memory's import goes once nothing holds it; its deallocator runs at the buffer's next + /// rebind, inside the call, or at its release, never at the detach, as Metal's. The buffer, its + /// `gpu_address` and its options stay; `contents` answers `None` while it is detached, where + /// Metal's answers the old pointer. /// - /// A command buffer first submitted after the call whose commands named the buffer or made - /// it resident (a render pass whose attachment lies over it names it from its open) fails - /// there, `CommandBufferError::DetachedBacking`, and runs nothing of it; one that reaches the - /// buffer only by its address reads zeros there. + /// A submission after the call, the command buffer's first or a later one behind an event + /// wait, whose commands named the buffer or made it resident (a render pass whose attachment + /// lies over it names it from its open) fails there, `CommandBufferError::DetachedBacking`, and + /// runs nothing of it; one whose command buffer reaches the buffer only by its address reads + /// zeros there, where its first submission came after the call. /// /// A texture over the buffer's bytes stays, and presents a stand-in until the buffer lies in /// pages again: its queries answer its own descriptor, an unnamed read reads zeros, and a @@ -90,11 +110,12 @@ impl Buffer { impl Heap { /// `detachBacking` of a heap over the caller's host memory - /// (`Device::new_heap_with_bytes_no_copy`; a runtime extension), as [`Buffer::detach_backing`] - /// detaches a no-copy buffer: every buffer placed in it stays, at its offset, and lies in no - /// pages until [`rebind_bytes_no_copy`](Heap::rebind_bytes_no_copy) gives the heap some. Where - /// a command buffer submitted and not yet complete took the heap or a buffer placed in it, the - /// call answers `false` at once, detaching nothing. + /// (`Device::new_heap_with_bytes_no_copy`; Metal's private `MTLHeap` method), as + /// [`Buffer::detach_backing`] detaches a no-copy buffer: every buffer placed in it stays, at + /// its offset, and lies in no pages until [`rebind_bytes_no_copy`](Heap::rebind_bytes_no_copy) + /// gives the heap some. Where submitted work holds the heap or a buffer placed in it, the call + /// answers `false` at once, detaching nothing, as Metal's does. The deallocator of the heap's + /// memory runs at its next rebind or its release, as a buffer's. /// /// Its textures, and those over its buffers, stay and present stand-ins as a buffer's do. /// @@ -116,9 +137,8 @@ impl Heap { impl Device { /// Detach `buffer`, a no-copy buffer whose hold on its pages is `cell` (`heap`'s own buffer - /// where given), as the module docs say: `true` once detached; `false` where a command - /// buffer submitted and not yet complete took it, after waiting for each such command buffer - /// to complete unless it is a heap's. + /// where given), as the module docs say: `true` once detached; `false` where submitted work + /// holds it, after waiting for that work to complete unless it is a heap's. fn detach_host_pages( &self, buffer: &Buffer, @@ -134,10 +154,10 @@ impl Device { shared.deferred.lower_all(); let rebinds = &shared.rebinds; let key = buffer.identity().key; - // A submitted command buffer took it: a buffer's call waits for each, a heap's not. + // Submitted work holds it: a buffer's call waits for that work, a heap's not. let refuse = || { if heap.is_none() { - rebinds.wait_unsubmitted(self, key)?; + rebinds.wait_ran(self, key)?; } Ok(false) }; @@ -211,7 +231,11 @@ impl Device { Lying::Detached(_) => super::heap_sets::retire(self, Box::new(gone)), } } - // The old pages go now where no command buffer holds them, their deallocator with them. + // The old pages go now where no command buffer holds them, their import freed; their + // deallocator waits for the next rebind or the release (`HostCell::hold_back`). + if let Lying::In(pages) = &old { + cell.hold_back(pages); + } drop(old); Ok(true) } diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index bb35a3ae8..b040a3044 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -43,7 +43,7 @@ use super::pending_dispatch::PendingDispatch; use super::pipeline::VariantObjects; use super::rebind::{Holds, Taken}; use super::replay::Replay; -use super::residency::Residency; +use super::residency::{Residency, Used}; use super::resource::ResourceKey; use super::retained::Retained; use super::row_copies::RowCopies; @@ -247,6 +247,9 @@ pub(super) struct EncoderCore { /// open, so a use at that place of the same key, named only where that one was, is kept and /// named already. touched: Vec<(ResourceKey, bool)>, + /// The buffers the encoder made resident since its last command (`made_resident`), which its + /// next command holds. + resident_unheld: Vec, /// The shadowed textures its pass took as attachments (`render/shadows.rs`): `end` notes them /// in the command buffer (`WorkCounts::shadow_attachment_passes`). attachment_shadows: Vec, @@ -435,6 +438,7 @@ impl EncoderCore { shadows: ShadowSync::default(), keys: BTreeSet::new(), touched: Vec::new(), + resident_unheld: Vec::new(), attachment_shadows: Vec::new(), first_copies: Vec::new(), kept_leases: Vec::new(), @@ -516,6 +520,7 @@ impl EncoderCore { shadows: ShadowSync::default(), keys: BTreeSet::new(), touched: Vec::new(), + resident_unheld: Vec::new(), attachment_shadows: Vec::new(), first_copies: Vec::new(), kept_leases: Vec::new(), @@ -1034,6 +1039,7 @@ impl EncoderCore { /// through the resident set alone: every other key is named (`Taken`), where the device has /// a buffer over host pages. fn touch_reaching(&mut self, uses: &[Use], resident: &BTreeSet) { + self.hold_resident(); let rebinds = self.device().shared().rebinds.any(); for (at, used) in uses.iter().enumerate() { let key = used.key; @@ -1064,6 +1070,31 @@ impl EncoderCore { } } + /// Retain `used`, a resource the encoder first made resident (`use_resource`, `use_heap`), + /// until the command buffer completes; and, where it is a buffer over host pages or a heap + /// whose bytes are, hold it from the encoder's next command on, whether or not a command + /// reaches it, as Metal holds every buffer an encoder made resident from the submission of a + /// command it encoded after, and fails that submission where the buffer is detached by then + /// (code 8). An encoder that encodes no command after it holds nothing of it, as Metal's. + pub(super) fn made_resident(&mut self, used: Used) { + if let Some(key) = used.bytes_key() { + if self.device().shared().rebinds.any() { + self.resident_unheld.push(key); + } + } + self.retain(used); + } + + /// Hold the buffers the encoder made resident since its last command (`made_resident`), as + /// its commands' uses are held: once each, the keys kept. + fn hold_resident(&mut self) { + while let Some(key) = self.resident_unheld.pop() { + if self.keys.insert(key) { + self.hold(key); + } + } + } + /// Hold each buffer over host pages among `keys` from now on, as a command that names it /// does (`touch_keys`), without keeping the keys: the bytes a render pass's attachments lie /// in, which it holds from its open (`render.rs`). Free while the device has no buffer over @@ -1170,6 +1201,7 @@ impl EncoderCore { )); } self.observe_fresh(uses, &[]); + self.hold_resident(); let Some(noted) = noted else { self.record_aliased(stages, uses); self.touch_reaching(uses, resident); diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index 0212fcd42..8bc0e916b 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -113,7 +113,7 @@ use metal2vulkan::device::{EnableSet, VkExtension}; use metal2vulkan::error::{Feature, Unsupported}; use std::ffi::c_void; use std::ptr::NonNull; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; /// Host memory a buffer or heap wraps without a copy: a pointer whose bytes the caller vouches for /// (the `pointer` of `newBufferWithBytesNoCopy:length:options:deallocator:`), and, as a runtime @@ -317,6 +317,7 @@ impl HostRelease { length, deallocator: Mutex::new(deallocator), keep_alive: Mutex::new(keep_alive), + held_back: Mutex::new(None), }) } } @@ -809,6 +810,9 @@ pub(super) struct Release { length: u64, deallocator: Mutex>>, keep_alive: Mutex>>, + /// Where a detach held both back ([`Release::hold_back`]): told as the release would have run + /// the deallocator. + held_back: Mutex>>, } // SAFETY: the pointer is only handed to the deallocator, which is `Send`; the deallocator and @@ -850,8 +854,13 @@ impl Release { self.length } - /// Run the deallocator, once; a panic inside it is caught. + /// Run the deallocator, once; a panic inside it is caught. Where a detach held it back, the + /// [`HeldBack`] is told instead: the pages may be unmapped from now on. pub(super) fn run(&self) { + if let Some(held) = lock(&self.held_back).take() { + held.unmappable(); + return; + } let deallocator = lock(&self.deallocator).take(); if let Some(deallocator) = deallocator { let (pointer, length) = (self.pointer, self.length); @@ -860,4 +869,132 @@ impl Release { }); } } + + /// Hold back its deallocator and its keep-alive for a detach (`detach.rs`): Metal runs a + /// no-copy buffer's deallocator at its next replace, inside the call, or at its release, never + /// at a detach (measured on the M3 Max, macOS 27.0.1). Both go to a [`HeldBack`], which this + /// release tells, in the deallocator's place, once the pages may be unmapped (their import + /// freed, or another buffer lying in it: [`HeldBack::unmappable`]); the keep-alive goes once + /// the deallocator ran and the pages may be unmapped, so the deallocator may read the bytes, as + /// with a release. `None` where it has no deallocator left to run. + pub(super) fn hold_back(&self) -> Option> { + let deallocator = lock(&self.deallocator).take()?; + let keep_alive = lock(&self.keep_alive).take(); + let held = Arc::new(HeldBack { + state: Mutex::new(Back { + deallocator: Some(deallocator), + keep_alive, + unmappable: false, + due: false, + }), + pointer: self.pointer, + length: self.length, + }); + *lock(&self.held_back) = Some(Arc::clone(&held)); + Some(held) + } +} + +/// A no-copy buffer's deallocator and keep-alive a detach held back ([`Release::hold_back`]). The +/// deallocator runs once the buffer's next rebind or its release came ([`HeldBack::due`]) and the +/// pages are kept mapped or may be unmapped: at once where the caller gave a keep-alive, which +/// keeps them mapped, as Metal runs it then; else once the pages' release reached it +/// ([`HeldBack::unmappable`]), at once where nothing still holds the import. The keep-alive goes +/// once both the deallocator ran and the pages may be unmapped, on the thread whose call came last. +pub(super) struct HeldBack { + state: Mutex, + pointer: NonNull, + length: u64, +} + +/// What a [`HeldBack`] holds, and what came. +struct Back { + deallocator: Option>, + keep_alive: Option>, + unmappable: bool, + due: bool, +} + +// SAFETY: the pointer is only handed to the deallocator, which is `Send`; the deallocator and +// the keep-alive are reached only through their lock. +unsafe impl Send for HeldBack {} +// SAFETY: as above. +unsafe impl Sync for HeldBack {} + +/// What a [`HeldBack`] runs and drops now, taken under its lock. +type Ready = ( + Option>, + Option>, +); + +impl HeldBack { + /// What runs and goes now: the deallocator once due and the pages are mapped (a keep-alive) + /// or may be unmapped; the keep-alive once the deallocator ran and they may be unmapped. + fn ready(back: &mut Back) -> Ready { + let deallocator = match back.due && (back.unmappable || back.keep_alive.is_some()) { + true => back.deallocator.take(), + false => None, + }; + let keep_alive = match back.unmappable && back.deallocator.is_none() { + true => back.keep_alive.take(), + false => None, + }; + (deallocator, keep_alive) + } + + /// Run the deallocator and drop the keep-alive of `ready`, in that order; the process + /// exiting runs and drops neither: the pages stay imported to its end. + fn run(&self, (deallocator, keep_alive): Ready) { + let Some(busy) = exit_guard::enter() else { + std::mem::forget(deallocator); + std::mem::forget(keep_alive); + return; + }; + drop(busy); + let (pointer, length) = (self.pointer, self.length); + exit_guard::program_release(move || { + if let Some(deallocator) = deallocator { + deallocator.run(|deallocator| deallocator(pointer, length)); + } + drop(keep_alive); + }); + } + + /// The pages' release reached the deallocator ([`Release::run`]): they may be unmapped from + /// now on. + fn unmappable(&self) { + let ready = { + let mut back = lock(&self.state); + back.unmappable = true; + HeldBack::ready(&mut back) + }; + self.run(ready); + } + + /// The buffer's next rebind, or its release, came: the deallocator runs now, but where no + /// keep-alive keeps the pages mapped and they are still imported; `true` where it waits so. + pub(super) fn due(&self) -> bool { + let (ready, waits) = { + let mut back = lock(&self.state); + back.due = true; + let ready = HeldBack::ready(&mut back); + (ready, back.deallocator.is_some()) + }; + self.run(ready); + waits + } +} + +impl Drop for HeldBack { + /// The process exiting leaves what it still holds unrun and undropped (`exit_guard`). + fn drop(&mut self) { + let back = self + .state + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if exit_guard::enter().is_none() { + std::mem::forget(back.deallocator.take()); + std::mem::forget(back.keep_alive.take()); + } + } } diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index 6f3c3d419..0dfc59feb 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -12,17 +12,19 @@ //! (the device's own Metal address space, `address.rs`: the resident table maps each address //! to the `VkBuffer` behind it at encode time), their resource IDs, labels, offsets and //! options. `contents` answers the new pointer at once. -//! - **The ordering rule, by first submission** (by commit before). Metal resolves a command -//! buffer's uses as it submits it (the consumer's rebind probe, tables 2 and 3, the M3 Max): one -//! first submitted before the rebind keeps the old pages until it completes; one committed before -//! it and first submitted after reaches the new pages through what it uses or made resident, and -//! none through what it only reaches unnamed (the rebind ends the use). The runtime resolves both -//! at the first submission (`command_buffer/first_submission.rs`); a command it encoded that -//! names the buffer took the pages as it was encoded (`Taken`), so the rebind encodes its +//! - **The ordering rule, by submission** (by commit before). Metal resolves a command buffer's +//! uses as it submits each of its submissions (the consumer's rebind probe, tables 2 and 3, the +//! M3 Max; and a rebind between two submissions of one command buffer, the M3 Max under macOS +//! 27.0.1): one submitted before the rebind keeps the old pages until its work completed; one +//! committed before it and submitted after reaches the new pages through what it names or made +//! resident (a later submission of a command buffer whose earlier one ran included), and none +//! through what it only reaches unnamed (the rebind ends the use). The runtime resolves both as +//! each event group is submitted (`command_buffer/first_submission.rs`); a command it encoded +//! that names the buffer took the pages as it was encoded (`Taken`), so the rebind encodes its //! compute, blit and render encoders that named the buffer again, in the rebind's call, before -//! the command buffer's first submission (`replay.rs`, `command_buffer/reencode.rs`); an encoder -//! it cannot encode again (one of a command buffer that used command predication, among others) -//! fails `CommandBufferError::EncodedUseRebound` there, as all did before. Commands encoded after +//! their group's submission (`replay.rs`, `command_buffer/reencode.rs`); an encoder it cannot +//! encode again (one of a command buffer that used command predication, among others) fails +//! `CommandBufferError::EncodedUseRebound` there, as all did before. Commands encoded after //! the rebind use the new pages. A rebind while a command buffer that is not yet committed has //! encoded a use of the buffer or heap (one of its resources included), or has an encoder open //! that used one (a render encoder uses its attachments' bytes from its open), is refused @@ -38,7 +40,8 @@ //! - **The deallocators.** The old range's runs once every command buffer first submitted //! before the rebind that used it completed (at the rebind where none holds it: a command //! buffer not yet submitted holds its pages weakly); the new range's at the next rebind's turn, -//! or when the buffer or heap goes. +//! or when the buffer or heap goes. A detached buffer's or heap's rebind runs, inside the call, +//! the deallocator of the range its detach let go of (`detach.rs`), as Metal's replace does. //! - **Textures.** Nothing of the old contents is copied. A heap texture bound to the heap's //! bytes (a no-copy heap's linear image), and a texture over a no-copy buffer (or over a //! buffer of a no-copy heap) whose linear image aliases its bytes, has its image made again over @@ -97,8 +100,8 @@ pub(super) struct Rebinds { buffers: Mutex>, /// How many of them are detached (`detach.rs`): else no command names a detached one. detached: AtomicUsize, - /// Signaled as a submitted command buffer that took one of them completes - /// (`SubmittedHolds`): a detach of it waits for none to hold it. + /// Signaled as the work of a submitted batch that took one of them completes, and as its hold + /// goes (`SubmittedHolds`): a buffer's detach waits for no such work to run. completed: Condvar, /// The device's stand-in a detached buffer's commands take (`buffer::Detached`), while one /// is detached: made again once every one let go of it. @@ -111,15 +114,17 @@ pub(super) struct Rebinds { pub(super) stale: Mutex>, /// How many there are: the check at each submission costs one load while none is. pub(super) stale_count: AtomicUsize, - /// The command buffers committed and not yet first submitted that an encoder of theirs can - /// encode again (`replay.rs`), or work of theirs on the GPU alone can be recorded again, with - /// the keys of the buffers over host pages those encoders and that work named: a rebind of - /// one of them has them encoded or recorded again before their first submission. Taken under - /// `buffers`' lock, after it. + /// The command buffers committed whose last event group is not yet submitted that an encoder + /// of theirs can encode again (`replay.rs`), or work of theirs on the GPU alone can be + /// recorded again, with the keys of the buffers over host pages those encoders and that work + /// named: a rebind of one of them has the encoders of the groups not yet submitted encoded + /// again, and that work recorded again before the first submission. Taken under `buffers`' + /// lock, after it. waiting: Mutex, } -/// The command buffers waiting for their first submission whose encoders a rebind encodes again, +/// The command buffers waiting for the submission of an event group whose encoders a rebind +/// encodes again, /// or whose work on the GPU alone it records again ([`Rebinds::wait_for_replay`]), each with the /// keys they named, sorted. #[derive(Default)] @@ -171,9 +176,12 @@ struct Entry { cell: Weak, /// The holds of encoders and of command buffers not yet committed on it ([`Holds`]). pending: u32, - /// The submitted command buffers not yet complete whose commands took it - /// (`SubmittedHolds`): a detach waits for none, or refuses. + /// The holds of submitted work that took it (`SubmittedHolds`), each from the submission of + /// its batches until their work completed, or, for a command buffer's last batches, until its + /// completed handlers ran: a detach refuses while one is. submitted: u32, + /// Those of them whose work has not yet completed: a buffer's detach waits for none. + running: u32, /// It is detached (`detach.rs`), as its cell says. detached: bool, /// A submitted command buffer took the pages it lies in now and found them its own: Metal @@ -201,6 +209,7 @@ impl Rebinds { cell: Arc::downgrade(cell), pending: 0, submitted: 0, + running: 0, detached: false, resident: false, }; @@ -248,9 +257,10 @@ impl Rebinds { } /// Note `buffer`, committed now and not yet first submitted, whose encoders that can be - /// encoded again named the buffers of `keys` (sorted): a rebind of one of them before its - /// first submission has them encoded again ([`Rebinds::replace`]). Its first submission - /// lets go of it ([`Submitting::submitted_now`]). + /// encoded again named the buffers of `keys` (sorted): a rebind of one of them before the + /// submission of their event group has them encoded again ([`Rebinds::replace`]). The + /// submission of its last group lets go of it ([`Submitting::submitted_now`]), and so does + /// its completion. pub(super) fn wait_for_replay( &self, buffer: &Arc, @@ -261,6 +271,15 @@ impl Rebinds { waiting.buffers.push((Arc::downgrade(buffer), keys)); } + /// `buffer` waits for no rebind's replay from here: its last event group was submitted, or + /// it completed. + pub(super) fn no_replays(&self, buffer: &CommandBufferShared) { + let mut waiting = lock(&self.waiting); + waiting + .buffers + .retain(|(waiting, _)| !std::ptr::eq(Weak::as_ptr(waiting), buffer)); + } + /// Whether a buffer of the device is detached now (`detach.rs`): a render encoder logs no call /// while one is (`render/deferral.rs`). pub(super) fn any_detached_now(&self) -> bool { @@ -277,8 +296,8 @@ impl Rebinds { .any(|key| buffers.get(&key).is_some_and(|entry| entry.detached)) } - /// Detach the buffer of `key`, whose hold on its pages is `cell`, to `detached`, unless a - /// submitted command buffer not yet complete took it (`SubmittedHolds`): where it lay, and + /// Detach the buffer of `key`, whose hold on its pages is `cell`, to `detached`, unless + /// submitted work holds it (`SubmittedHolds`): where it lay, and /// whether a submitted command buffer made those pages resident, or `None` where such a command /// buffer refuses it. Already detached, it stays so. pub(super) fn detach( @@ -301,13 +320,13 @@ impl Rebinds { Some((cell.replace(Lying::Detached(detached)), resident)) } - /// Wait until no submitted command buffer not yet complete holds the buffer of `key` - /// (`SubmittedHolds`), with no other lock of the runtime's held: the completion path lets - /// go of each without this one's caller. Settles on a lost device (`Err(DeviceLost)`), - /// whose command buffers may never complete. - pub(super) fn wait_unsubmitted(&self, device: &Device, key: ResourceKey) -> Result<(), Error> { + /// Wait until no submitted work that holds the buffer of `key` still runs + /// (`SubmittedHolds::ran`), with no other lock of the runtime's held: the completion path + /// notes each without this one's caller. Settles on a lost device (`Err(DeviceLost)`), whose + /// command buffers may never complete. + pub(super) fn wait_ran(&self, device: &Device, key: ResourceKey) -> Result<(), Error> { let mut buffers = lock(&self.buffers); - while buffers.get(&key).is_some_and(|entry| entry.submitted > 0) { + while buffers.get(&key).is_some_and(|entry| entry.running > 0) { if device.is_lost() { return Err(Error::DeviceLost); } @@ -319,7 +338,7 @@ impl Rebinds { Ok(()) } - /// Whether a submitted command buffer not yet complete holds the buffer of `key`. + /// Whether submitted work holds the buffer of `key` (`SubmittedHolds`). pub(super) fn submitted(&self, key: ResourceKey) -> bool { lock(&self.buffers) .get(&key) @@ -334,12 +353,29 @@ impl Rebinds { } } - /// Submitted command buffers that took `keys` completed: a detach may go on. - fn completed(&self, keys: &[ResourceKey]) { + /// The holds of submitted work on `keys` go, the work having completed unless `ran` noted it + /// already: a detach may go on. + fn let_go(&self, keys: &[ResourceKey], ran: bool) { let mut buffers = lock(&self.buffers); for key in keys { if let Some(entry) = buffers.get_mut(key) { entry.submitted = entry.submitted.saturating_sub(1); + if !ran { + entry.running = entry.running.saturating_sub(1); + } + } + } + drop(buffers); + self.completed.notify_all(); + } + + /// The submitted work holding `keys` completed, its holds staying: a buffer's detach waiting + /// for it answers. + fn ran(&self, keys: &[ResourceKey]) { + let mut buffers = lock(&self.buffers); + for key in keys { + if let Some(entry) = buffers.get_mut(key) { + entry.running = entry.running.saturating_sub(1); } } drop(buffers); @@ -362,10 +398,10 @@ impl Rebinds { /// Give the buffer of `key`, whose hold on its pages is `cell`, `pages` from now on, unless /// a hold refuses it: where it lay (a detached one is attached again), and the command - /// buffers waiting for their first submission whose replayable encoders or work on the GPU - /// alone named it ([`Rebinds::wait_for_replay`]), each marked under this lock to encode or - /// record them again before that submission (`CommandBufferShared::reencode`), which the - /// caller runs; `Err` gives `pages` back. + /// buffers waiting for the submission of an event group whose replayable encoders or work on + /// the GPU alone named it ([`Rebinds::wait_for_replay`]), each marked under this lock to + /// encode or record them again before that submission (`CommandBufferShared::reencode`), which + /// the caller runs; `Err` gives `pages` back. pub(super) fn replace( &self, key: ResourceKey, @@ -386,7 +422,7 @@ impl Rebinds { // No command buffer made the new pages resident yet. entry.resident = false; let lying = cell.replace(Lying::In(pages)); - // Marked before this lock goes, so a first submission either came before the rebind + // Marked before this lock goes, so a group's submission either came before the rebind // (and keeps the old pages) or waits for the encoders encoded again. // Each upgraded one goes to the caller, which lets go of it without this lock. let mut again: Vec> = Vec::new(); @@ -465,13 +501,10 @@ impl Submitting<'_> { }) } - /// `buffer` is first submitted now (or holds back for its encoders encoded again): it waits - /// for no rebind's replay from here ([`Rebinds::wait_for_replay`]). + /// `buffer`'s last event group is submitted now: it waits for no rebind's replay from here + /// ([`Rebinds::wait_for_replay`]). pub(super) fn submitted_now(&self, rebinds: &Rebinds, buffer: &CommandBufferShared) { - let mut waiting = lock(&rebinds.waiting); - waiting - .buffers - .retain(|(waiting, _)| !std::ptr::eq(Weak::as_ptr(waiting), buffer)); + rebinds.no_replays(buffer); } /// Judge `taken`, and hold every pin whose pages still live in `retained` until the command @@ -515,6 +548,7 @@ impl Submitting<'_> { // Pages the command buffer finds its own, Metal makes resident. entry.resident |= !moved && !detached; entry.submitted += 1; + entry.running += 1; holds.keys.push(key); retained.push(Box::new(pages)); } @@ -533,12 +567,17 @@ impl Submitting<'_> { } } -/// The holds a submitted command buffer's commands took on buffers over host pages -/// (`Submitting::submit`), counted per buffer until it completes: dropped with what it -/// retained, it lets a detach waiting for them go on. +/// The holds the commands of a command buffer's submitted batches took on buffers over host +/// pages (`Submitting::submit`), counted per buffer, as Metal holds what a submission uses +/// (`command_buffer/first_submission.rs`): from the submission of the batches' event group until +/// their work completed, where a buffer's detach waiting for them answers (`ran`), and, for the +/// command buffer's last group, until its completed handlers ran, where it is dropped. Until +/// then a detach answers `false`. pub(super) struct SubmittedHolds { device: Device, keys: Vec, + /// Their work completed, noted already ([`SubmittedHolds::ran`]). + ran: bool, } impl SubmittedHolds { @@ -547,6 +586,7 @@ impl SubmittedHolds { SubmittedHolds { device: device.clone(), keys: Vec::new(), + ran: false, } } @@ -554,12 +594,24 @@ impl SubmittedHolds { pub(super) fn is_empty(&self) -> bool { self.keys.is_empty() } + + /// The work holding them completed, the holds staying until they are dropped: a buffer's + /// detach waiting for that work answers `false`. Once. + pub(super) fn ran(&mut self) { + if self.ran { + return; + } + self.ran = true; + if !self.keys.is_empty() { + self.device.shared().rebinds.ran(&self.keys); + } + } } impl Drop for SubmittedHolds { fn drop(&mut self) { if !self.keys.is_empty() { - self.device.shared().rebinds.completed(&self.keys); + self.device.shared().rebinds.let_go(&self.keys, self.ran); } } } @@ -781,8 +833,9 @@ impl Buffer { /// this call cannot encode again named the buffer (one of a command buffer that used command /// predication, among others); commands encoded after it use the new. The old memory's /// deallocator runs once every command buffer submitted before the call that used it completed - /// (in the call, where none holds it); `deallocator` runs for the new memory at the next - /// rebind's turn, or when the buffer goes. A refused call runs neither and changes nothing. + /// (in the call, where none holds it), and that of the memory a detach let go of in the call, + /// as Metal's replace runs it; `deallocator` runs for the new memory at the next rebind's + /// turn, or when the buffer goes. A refused call runs neither and changes nothing. /// `keep_alive` ([`KeepAlive`]) is dropped once the device's import of the new memory is freed: /// with one, `deallocator` runs at that turn though something still holds the import (a command /// buffer submitted before a texture over the bytes was released); with none, `deallocator` diff --git a/crates/metal2vulkan-runtime/src/render/arguments.rs b/crates/metal2vulkan-runtime/src/render/arguments.rs index bc4e833a8..8b73a717f 100644 --- a/crates/metal2vulkan-runtime/src/render/arguments.rs +++ b/crates/metal2vulkan-runtime/src/render/arguments.rs @@ -70,7 +70,7 @@ impl RenderLowering { } for &resource in resources { if let Some(used) = self.residency.use_resource(resource, usage, stages) { - self.core.retain(used); + self.core.made_resident(used); } if let ResourceRef::IndirectCommandBuffer(icb) = resource { if usage.contains(ResourceUsage::WRITE) { @@ -107,7 +107,7 @@ impl RenderLowering { } for heap in heaps { for used in self.residency.use_heap(heap, stages) { - self.core.retain(used); + self.core.made_resident(used); } } Ok(()) diff --git a/crates/metal2vulkan-runtime/src/residency.rs b/crates/metal2vulkan-runtime/src/residency.rs index ed2676f9e..363322672 100644 --- a/crates/metal2vulkan-runtime/src/residency.rs +++ b/crates/metal2vulkan-runtime/src/residency.rs @@ -82,7 +82,7 @@ use super::heap::Heap; use super::indirect_command_buffer::IndirectCommandBuffer; use super::key_hash::KeyMap; use super::live_buffers::LiveTable; -use super::resource::ResourceRef; +use super::resource::{ResourceKey, ResourceRef}; use super::texture::Texture; use metal2vulkan::bind::{ResidentRange, ResourceClass, UsedResource}; use metal2vulkan::metal::{RenderStages, ResourceUsage}; @@ -145,6 +145,18 @@ struct HeapUse { next: u64, } +impl Used { + /// The key of the buffer whose bytes it is: a buffer's, a heap's own buffer's; `None` for a + /// texture and an indirect command buffer. + pub(super) fn bytes_key(&self) -> Option { + match self { + Used::Buffer(buffer) => Some(buffer.identity().key), + Used::Heap { bytes, .. } => Some(bytes.identity().key), + Used::Texture(_) | Used::IndirectCommandBuffer(_) => None, + } + } +} + impl Residency { /// Whether it holds nothing: no resource, heap or live table. pub(super) fn is_empty(&self) -> bool { diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs index f10c2d5c3..ec980a7f4 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs @@ -1047,8 +1047,9 @@ fn submit_ready( if !binary.ready(&held.binary_needs) { return None; } - // Its first submission waits while a rebind encodes encoders of it again. - if held.index == 0 && held.buffer.reencode_pending() { + // The submission of its event group waits while a rebind encodes encoders of it again + // (`command_buffer/reencode.rs`). + if held.buffer.reencode_pending() { return None; } // Held for a decoded twin's CPU decode it may read: any batch, while an untracked diff --git a/crates/metal2vulkan-runtime/src/tests/detach_lost.rs b/crates/metal2vulkan-runtime/src/tests/detach_lost.rs index 4ffa98703..4f8d83572 100644 --- a/crates/metal2vulkan-runtime/src/tests/detach_lost.rs +++ b/crates/metal2vulkan-runtime/src/tests/detach_lost.rs @@ -1,15 +1,15 @@ -//! A detach waiting for a submitted command buffer settles when the device is lost (`detach.rs`): a -//! no-copy buffer named by a command buffer whose first batch was submitted and whose next batch -//! waits for an event is detached on another thread, which blocks; the device is then marked lost -//! (as `device/relay.rs` marks it), the event never signaled, and the detach answers -//! `Err(DeviceLost)` within its poll. +//! A detach waiting for submitted work settles when the device is lost (`detach.rs`): a no-copy +//! buffer a submitted kernel names, spinning until the host raises a word, is detached on another +//! thread, which blocks; the device is then marked lost (as `device/relay.rs` marks it), the word +//! not yet raised, and the detach answers `Err(DeviceLost)` within its poll. //! //! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. use crate::error::Error; use crate::{ - Device, DeviceKind, DeviceOptions, EventRef, HostMemory, ResourceOptions, ShaderCacheOptions, + ComputePipelineState, Device, DeviceKind, DeviceOptions, HostMemory, PipelineOptions, + ResourceOptions, ShaderCacheOptions, Size, }; use std::alloc::Layout; use std::path::{Path, PathBuf}; @@ -83,10 +83,27 @@ fn device(cache: &Path) -> Device { Device::system_default_with(&options).unwrap() } -/// A buffer's detach blocked on a submitted command buffer that took it answers -/// `Err(DeviceLost)` once the device is lost, the command buffer never completing. +/// The owned fixture's kernel that loads a word no one raises until its cap +/// (`kernel_spin_on_an_unraised_word`). +fn spin(device: &Device) -> ComputePipelineState { + let ll = Path::new(env!("CARGO_MANIFEST_DIR")).join( + "../metal2vulkan-validation/fixtures/public/engine/kernel_spin_on_an_unraised_word.ll", + ); + let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap(); + let library = metal2vulkan::library::Library::from_air(&bitcode).unwrap(); + let library = device.new_library_with_compile_library(library); + let function = library + .new_function_with_name("spin_on_an_unraised_word") + .unwrap(); + device + .new_compute_pipeline_state_with_function(&function, &PipelineOptions::default()) + .unwrap() +} + +/// A buffer's detach blocked on submitted work that took it answers `Err(DeviceLost)` once the +/// device is lost, the work not yet complete. #[test] -fn a_detach_waiting_for_a_submitted_command_buffer_settles_on_a_lost_device() { +fn a_detach_waiting_for_submitted_work_settles_on_a_lost_device() { let host = Host::new(); let scratch = Scratch::new(); let device = device(&scratch.0); @@ -108,19 +125,18 @@ fn a_detach_waiting_for_a_submitted_command_buffer_settles_on_a_lost_device() { } }; let queue = device.new_command_queue().unwrap(); - let copied = device.new_buffer(16, ResourceOptions::shared()).unwrap(); - let event = device.new_shared_event().unwrap(); + let state = spin(&device); + let flag = device.new_buffer(16, ResourceOptions::shared()).unwrap(); let command_buffer = queue.command_buffer().unwrap(); - let mut blit = command_buffer.blit_command_encoder().unwrap(); - blit.copy_from_buffer_to_buffer(&buffer, 0, &copied, 0, 16) + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&state).unwrap(); + encoder.set_buffer(Some(&flag), 0, 0).unwrap(); + encoder.set_buffer(Some(&buffer), 0, 1).unwrap(); + encoder.set_bytes(&(1u32 << 25).to_le_bytes(), 2).unwrap(); + encoder + .dispatch_threadgroups(Size::new(1, 1, 1), Size::new(1, 1, 1)) .unwrap(); - blit.end_encoding().unwrap(); - command_buffer - .encode_wait_for_event(EventRef::from(&event), 1) - .unwrap(); - let mut blit = command_buffer.blit_command_encoder().unwrap(); - blit.fill_buffer(&copied, 0..16, 0x3c).unwrap(); - blit.end_encoding().unwrap(); + encoder.end_encoding().unwrap(); command_buffer.commit().unwrap(); let deadline = Instant::now() + WAIT; while command_buffer.kernel_start_time() == 0.0 { @@ -130,14 +146,21 @@ fn a_detach_waiting_for_a_submitted_command_buffer_settles_on_a_lost_device() { ); std::thread::sleep(Duration::from_millis(1)); } + let raise = || { + let word = flag.contents().unwrap().as_ptr().cast::(); + // SAFETY: the flag's `Shared` bytes are mapped for its life, aligned for a word, and the + // GPU only loads them. + unsafe { word.write_volatile(1) }; + }; std::thread::scope(|scope| { let detaching = scope.spawn(|| buffer.detach_backing()); std::thread::sleep(Duration::from_millis(100)); - assert!( - !detaching.is_finished(), - "the detach did not wait for the submitted command buffer" - ); + let waited = !detaching.is_finished(); device.mark_lost(); - assert_eq!(detaching.join().unwrap(), Err(Error::DeviceLost)); + let answer = detaching.join().unwrap(); + // The GPU is never left spinning. + raise(); + assert!(waited, "the detach did not wait for the submitted work"); + assert_eq!(answer, Err(Error::DeviceLost)); }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/detach.rs b/crates/metal2vulkan-validation/src/runtime_lane/detach.rs index 85f9129aa..21f25e899 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/detach.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/detach.rs @@ -6,13 +6,24 @@ //! buffer whose command names the buffer (bound and read, case 1; bound and walked, case 2; a //! blit's operand, case 5) or whose encoder made it resident (`use_resources`, case 3; //! `use_heap`, case 3h) fails `CommandBufferError::DetachedBacking`, Metal's code 8, and runs -//! nothing; its signal fires, its completed handler runs, and the queue runs on. One that +//! nothing; its signal fires, its completed handler runs, and the queue runs on. A resident +//! buffer counts whether or not a command reaches it, once the encoder encoded a command after +//! making it resident (the M3 Max under macOS 27.0.1). One that //! reaches the buffer unnamed alone (case 4) reads 0 there and completes. No degradation is //! announced: the failure is Metal's. -//! - **Submitted work** (table 3: a command buffer submitted and not yet complete). A buffer's -//! detach blocks until each such command buffer that took it completed, then answers `false` -//! and detaches nothing; a heap's answers `false` at once; a buffer such a command buffer does -//! not take is detached at once. +//! - **Submitted work** (table 3, and the M3 Max under macOS 27.0.1). Metal holds what a +//! submission uses from its submission until its work completed, and the last submission's +//! until the command buffer's completed handlers ran: a buffer's detach meanwhile blocks until +//! that work completed, then answers `false` and detaches nothing; a heap's answers `false` at +//! once; a detach in a completed handler answers `false`, and one once `wait_until_completed` +//! returned detaches. A command buffer's later submission behind an event wait holds nothing +//! until it is submitted: a detach while it waits detaches at once, though the command buffer's +//! earlier work ran or still runs, and that submission then fails with code 8. +//! - **The deallocator** of the pages a detach lets go of runs at the buffer's next rebind, +//! inside the call, on its thread, or at its release, never at the detach (the M3 Max under +//! macOS 27.0.1, a `newBufferWithBytesNoCopy:` buffer and one of `newBufferWithDescriptor:`, +//! each with and without GPU use before the detach). A keep-alive goes after the deallocator, +//! once the import is freed. //! - **Encoded while detached.** A command that names a detached buffer records nothing, nor does //! any after it in its encoder (blit, dispatch, draw), and its command buffer fails //! `DetachedBacking` and runs nothing; where a rebind gave the buffer pages again before its @@ -20,8 +31,9 @@ //! 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 one of the two calls, wherever -//! the device's recorder replays the commands, and announces nothing. +//! 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. //! - **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`. @@ -32,25 +44,24 @@ use super::degrade_notices::{ use super::host_memory::{gpu_read, on_device, recording, Mapping, Seen}; use super::no_copy_heaps::shared; use super::rebind_reach::{ - buffer_len, buffer_over, deallocated, heap_member, kept_member_over, member_over, node, pages, + buffer_len, buffer_over, heap_member, kept_member_over, member_over, node, pages, rebind_heap_to, rebind_to, walk, Outputs, Uses, Walked, A, B, POINTER_WALKER, }; use super::shared_kinds; -use super::{ - bound_buffers, buffer_with, encode_case, pipeline_state, public_case, read_buffer, - CaseResources, WAIT, -}; +use super::{buffer_with, public_case, read_buffer, WAIT}; use crate::air_library::AirLibrary; -use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; -use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; +use metal2vulkan::metal::{PixelFormat, PrimitiveType, ResourceUsage, TextureUsage}; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, +}; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ Buffer, ClearColor, CommandBuffer, CommandBufferError, CommandBufferStatus, CommandQueue, - Degradation, Device, Error, EventRef, Heap, HeapDescriptor, HeapType, HostMemory, Invalid, - LoadAction, PipelineOptions, Problem, RebindProblem, Region, RenderPassDescriptor, - ResourceOptions, SharedEvent, StoreAction, TextureDescriptor, + ComputePipelineState, Degradation, Device, Error, EventRef, Heap, HeapDescriptor, HeapType, + HostMemory, Invalid, LoadAction, PipelineOptions, Problem, RebindProblem, Region, + RenderPassDescriptor, ResourceOptions, SharedEvent, Size, StoreAction, TextureDescriptor, }; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -121,8 +132,10 @@ fn table_1_a_pending_command_buffer_holding_a_detached_buffer_fails_with_code_8( }; let blit = held(&member, Uses::Blit, &|| detach(&member)); failed(device, &queue, blit, "5: a blit's operand"); - deallocated(&old); + // The old pages' deallocator waits for the rebind, which runs it inside the call. + assert_eq!(old.runs.load(Ordering::SeqCst), 0, "ran at the detach"); rebind_to(&member, A); + ran_here(&old, "the rebind after a detach"); let resident = held(&member, Uses::Resident, &|| detach(&member)); failed(device, &queue, resident, "3: resident"); rebind_to(&member, A); @@ -220,7 +233,7 @@ fn a_command_naming_a_detached_buffer_records_nothing_and_its_command_buffer_run gpu_read(&queue, &member, 0..16); assert!(member.contents().is_some()); detach(&member); - deallocated(&old); + assert_eq!(old.runs.load(Ordering::SeqCst), 0, "ran at the detach"); assert_eq!(member.contents(), None, "a detached buffer's contents"); detach(&member); @@ -277,6 +290,7 @@ fn a_command_naming_a_detached_buffer_records_nothing_and_its_command_buffer_run assert!(!notices.contains_key(&Degradation::EncodedUseRebound)); let reencoded = device.work_counts().encoders_reencoded; rebind_to(&member, B); + ran_here(&old, "the rebind after the detach"); // The rebind encodes the blit encoder again over the new pages before its first // submission: the copy reads them, as Metal's does. assert!( @@ -391,21 +405,106 @@ fn a_render_pass_drawing_from_a_detached_buffer_runs_nothing() { }); } -/// A command buffer whose first batch was submitted (an event wait after its first encoder -/// splits it), held by that wait. -struct Running { - command_buffer: CommandBuffer, - event: SharedEvent, +/// `seen`'s deallocator ran once, on this thread, before the call that should run it returned. +fn ran_here(seen: &Seen, call: &str) { + assert_eq!( + seen.runs.load(Ordering::SeqCst), + 1, + "{call}: ran once, in the call" + ); + assert_eq!( + *seen.thread.lock().unwrap(), + Some(std::thread::current().id()), + "{call}: on the calling thread" + ); } -impl Running { - /// `encode` encodes its first encoder; a blit after the wait fills a buffer of its own. - fn new(device: &Device, queue: &CommandQueue, encode: impl FnOnce(&CommandBuffer)) -> Running { - let event = device.new_shared_event().unwrap(); +/// The most loads a spin makes: seconds on the M3 Max (about 135 ns a load there), so a spin whose +/// word is never seen raised still ends. +const SPIN_CAP: u32 = 1 << 25; + +/// The owned fixture's kernel that loads a word no one raises until its cap +/// (`kernel_spin_on_an_unraised_word`): its GPU work runs until the host raises the word. Run +/// once on `queue`, its word raised from the start, so its `VkPipeline` is made: a dispatch whose +/// pipeline is still being made records at a host step, which its submission waits for. +fn spin_state(device: &Device, queue: &CommandQueue) -> ComputePipelineState { + let ll = engine_dir().join("kernel_spin_on_an_unraised_word.ll"); + let library = device + .new_library_with_air(&llvm_assemble(&ll).unwrap()) + .unwrap(); + let function = library + .new_function_with_name("spin_on_an_unraised_word") + .unwrap(); + let state = device + .new_compute_pipeline_state( + &ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())), + &PipelineOptions::default(), + ) + .unwrap(); + let raised = buffer_with(device, &1u32.to_le_bytes()).unwrap(); + let loads = buffer_with(device, &[0; 4]).unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&state).unwrap(); + encoder.set_buffer(Some(&raised), 0, 0).unwrap(); + encoder.set_buffer(Some(&loads), 0, 1).unwrap(); + encoder.set_bytes(&SPIN_CAP.to_le_bytes(), 2).unwrap(); + encoder + .dispatch_threadgroups(Size::new(1, 1, 1), Size::new(1, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None, "the spin, raised"); + assert_eq!( + read_buffer(&loads, 0, 4).unwrap(), + [0; 4], + "the spin, raised" + ); + state +} + +/// A command buffer whose first batch spins over a buffer until [`Spinning::release`] (the +/// buffer bound as the kernel's output, or made resident), and whose next batch, behind an event +/// wait, fills a buffer of its own; committed, its first batch submitted. +struct Spinning { + command_buffer: CommandBuffer, + flag: Buffer, + output: Buffer, + gate: SharedEvent, +} + +impl Spinning { + fn new( + device: &Device, + queue: &CommandQueue, + state: &ComputePipelineState, + held: &Buffer, + resident: bool, + ) -> Spinning { + let flag = buffer_with(device, &[0; 16]).unwrap(); + let output = match resident { + true => buffer_with(device, &[0; 16]).unwrap(), + false => held.clone(), + }; + let gate = device.new_shared_event().unwrap(); let command_buffer = queue.command_buffer().unwrap(); - encode(&command_buffer); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(state).unwrap(); + encoder.set_buffer(Some(&flag), 0, 0).unwrap(); + encoder.set_buffer(Some(&output), 0, 1).unwrap(); + encoder.set_bytes(&SPIN_CAP.to_le_bytes(), 2).unwrap(); + if resident { + encoder + .use_resource(held.as_resource(), ResourceUsage::READ) + .unwrap(); + } + encoder + .dispatch_threadgroups(Size::new(1, 1, 1), Size::new(1, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); command_buffer - .encode_wait_for_event(EventRef::from(&event), 1) + .encode_wait_for_event(EventRef::from(&gate), 1) .unwrap(); let filled = device.new_buffer(16, ResourceOptions::shared()).unwrap(); let mut blit = command_buffer.blit_command_encoder().unwrap(); @@ -420,23 +519,45 @@ impl Running { ); std::thread::sleep(Duration::from_millis(1)); } - Running { + Spinning { command_buffer, - event, + flag, + output, + gate, } } + /// Raise the word: an atomic store into the buffer the kernel's atomic loads read. The spin + /// ends. + fn release(&self) { + let contents = self.flag.contents().unwrap(); + // SAFETY: the buffer's first word, `Shared` and 4-aligned, which the host and the + // kernel's atomics alone touch while the kernel runs. + let flag = unsafe { AtomicU32::from_ptr(contents.as_ptr().cast::()) }; + flag.store(1, Ordering::SeqCst); + } + /// Let it run to its end. fn finish(&self) { - self.event.set_signaled_value(1); + self.release(); + self.gate.set_signaled_value(1); self.command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(self.command_buffer.error(), None); } } -/// `detach`, called on another thread while `running` waits: it must not return before the -/// command buffer is let run, and answers `false` once it completed. -fn waits_then_refuses(running: &Running, detach: impl FnOnce() -> Result + Send) { +impl Drop for Spinning { + /// The GPU is never left spinning, whatever failed. + fn drop(&mut self) { + self.release(); + self.gate.set_signaled_value(1); + } +} + +/// `detach`, called on another thread while `spinning`'s first batch spins: it must not return +/// before the spin ends, and answers `false` once it ended, the command buffer still waiting for +/// its event: the hold is the submission's, not the command buffer's. +fn waits_then_refuses(spinning: &Spinning, detach: impl FnOnce() -> Result + Send) { let returned = AtomicBool::new(false); std::thread::scope(|scope| { let detaching = scope.spawn(|| { @@ -445,89 +566,374 @@ fn waits_then_refuses(running: &Running, detach: impl FnOnce() -> Result>()[..] else { - panic!("{POINTER_WALKER}: one argument-buffer buffer"); - }; - holding.argument_buffers.insert(field, member.clone()); - let buffers = bound_buffers(device, &walker.compute, &holding).unwrap(); - let resident = Running::new(device, &queue, |command_buffer| { - let mut encoder = command_buffer.compute_command_encoder().unwrap(); - encode_case(&mut encoder, &state, &walker.compute, &buffers, &holding).unwrap(); - encoder.end_encoding().unwrap(); - }); + // Resident: its encoder made the buffer resident. + let resident = Spinning::new(device, &queue, &state, &member, true); waits_then_refuses(&resident, || member.detach_backing()); - drop(holding); + resident.finish(); detach(&member); // A heap: at once. let Some((heap, placed)) = heap_member(device) else { return; }; - let in_heap = Running::new(device, &queue, |command_buffer| { - let mut blit = command_buffer.blit_command_encoder().unwrap(); - blit.copy_from_buffer_to_buffer(&placed, 0, &copied, 0, 16) - .unwrap(); - blit.end_encoding().unwrap(); - }); + let in_heap = Spinning::new(device, &queue, &state, &placed, false); assert_eq!(heap.detach_backing(), Ok(false)); - assert_eq!( + assert_ne!( in_heap.command_buffer.status(), - CommandBufferStatus::Committed, + CommandBufferStatus::Completed, "the heap's detach waited" ); in_heap.finish(); - assert_eq!(read_buffer(&copied, 0, 16).unwrap(), node(A)); detach_heap(&heap); - eprintln!("DETACH table 3: a buffer waits then refuses, a heap refuses at once"); + eprintln!( + "DETACH table 3: a buffer waits for the running submission then refuses, a heap \ + refuses at once" + ); + }); +} + +/// A command buffer of `queue`, behind a wait for `gate` where it is given, whose compute encoder +/// makes `resident` resident and runs the spin over a raised word, which reaches no buffer through +/// an address: committed. Its spin writes 0 loads into the returned buffer, which holds `0xff` +/// bytes until then. +fn resident_unreached( + device: &Device, + queue: &CommandQueue, + state: &ComputePipelineState, + resident: &Buffer, + gate: Option<&SharedEvent>, +) -> (CommandBuffer, Buffer) { + let raised = buffer_with(device, &1u32.to_le_bytes()).unwrap(); + let loads = buffer_with(device, &[0xff; 4]).unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + if let Some(gate) = gate { + command_buffer + .encode_wait_for_event(EventRef::from(gate), 1) + .unwrap(); + } + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder + .use_resource(resident.as_resource(), ResourceUsage::READ) + .unwrap(); + encoder.set_compute_pipeline_state(state).unwrap(); + encoder.set_buffer(Some(&raised), 0, 0).unwrap(); + encoder.set_buffer(Some(&loads), 0, 1).unwrap(); + encoder.set_bytes(&SPIN_CAP.to_le_bytes(), 2).unwrap(); + encoder + .dispatch_threadgroups(Size::new(1, 1, 1), Size::new(1, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + (command_buffer, loads) +} + +/// An encoder's resident buffer that no command reaches, as Metal answers it on the M3 Max (macOS +/// 27.0.1): held and judged as a reached one. Detached before the command buffer is encoded, or +/// after its commit and before its first submission (the detach answering `true` at once), its +/// submission fails `DetachedBacking` (code 8) and runs nothing. +#[test] +fn a_resident_buffer_no_command_reaches_fails_its_submission_once_detached() { + on_device(|device| { + let queue = device.new_command_queue().unwrap(); + let state = spin_state(device, &queue); + let Some((member, _)) = member_over(device, A) else { + return; + }; + detach(&member); + let (encoded, loads) = resident_unreached(device, &queue, &state, &member, None); + encoded.wait_until_completed_for(WAIT).unwrap(); + detached_backing(&encoded, "encoded detached"); + assert_eq!( + read_buffer(&loads, 0, 4).unwrap(), + [0xff; 4], + "the spin ran" + ); + rebind_to(&member, A); + + let gate = device.new_shared_event().unwrap(); + let (pending, loads) = resident_unreached(device, &queue, &state, &member, Some(&gate)); + detach(&member); + gate.set_signaled_value(1); + pending.wait_until_completed_for(WAIT).unwrap(); + detached_backing(&pending, "detached before its submission"); + assert_eq!( + read_buffer(&loads, 0, 4).unwrap(), + [0xff; 4], + "the spin ran" + ); + eprintln!("DETACH resident unreached: held and failed with code 8 as a reached one"); + }); +} + +/// A command buffer of `queue` whose first submission runs `first` and signals an event, and +/// whose second, behind a wait for another event, runs `second`; committed, and returned once its +/// first submission's work completed (its signal seen), with the event that lets the second go. +fn split( + device: &Device, + queue: &CommandQueue, + first: impl FnOnce(&CommandBuffer), + second: impl FnOnce(&CommandBuffer), +) -> (CommandBuffer, SharedEvent) { + let done = device.new_shared_event().unwrap(); + let gate = device.new_shared_event().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + first(&command_buffer); + command_buffer + .encode_signal_event(EventRef::from(&done), 1) + .unwrap(); + command_buffer + .encode_wait_for_event(EventRef::from(&gate), 1) + .unwrap(); + second(&command_buffer); + command_buffer.commit().unwrap(); + let deadline = Instant::now() + WAIT; + while done.signaled_value() < 1 { + assert!(Instant::now() < deadline, "the first submission never ran"); + std::thread::sleep(Duration::from_millis(1)); + } + (command_buffer, gate) +} + +/// A blit of `command_buffer` that fills the first 16 bytes of `buffer` with `value`. +fn fill(command_buffer: &CommandBuffer, buffer: &Buffer, value: u8) { + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(buffer, 0..16, value).unwrap(); + blit.end_encoding().unwrap(); +} + +/// A detach between two of a command buffer's submissions, as Metal answers it on the M3 Max +/// (macOS 27.0.1): Metal holds what a submission uses only from its submission until its work +/// completed, so a detach while the command buffer waits for an event after a submission that used +/// the buffer, its work done, detaches at once, and the command buffer completes; one before a +/// later submission that uses it detaches at once too, and that submission fails with code 8, the +/// earlier one having run. Buffer and heap forms. +#[test] +fn a_detach_between_submissions_detaches_at_once_and_fails_only_the_later_submission() { + on_device(|device| { + let queue = device.new_command_queue().unwrap(); + let Some((member, _)) = member_over(device, A) else { + return; + }; + let Some((heap, placed)) = heap_member(device) else { + return; + }; + type Forms<'a> = [( + &'a str, + &'a Buffer, + &'a dyn Fn() -> Result, + &'a dyn Fn(), + ); 2]; + let forms: Forms<'_> = [ + ("buffer", &member, &|| member.detach_backing(), &|| { + rebind_to(&member, A); + }), + ("heap", &placed, &|| heap.detach_backing(), &|| { + rebind_heap_to(&heap, A) + }), + ]; + for (form, used, detach, reattach) in forms { + // The use before the wait: its work done, the detach detaches at once. + let other = buffer_with(device, &[0; 16]).unwrap(); + let (command_buffer, gate) = split( + device, + &queue, + |cb| fill(cb, used, 0x5c), + |cb| fill(cb, &other, 0x5d), + ); + let started = Instant::now(); + assert_eq!(detach(), Ok(true), "{form}: used before the wait"); + assert!(started.elapsed() < EARLY, "{form}: the detach waited"); + gate.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None, "{form}: used before the wait"); + assert_eq!(read_buffer(&other, 0, 16).unwrap(), [0x5d; 16]); + reattach(); + + // The use behind the wait: detached at once, and that submission fails. + let other = buffer_with(device, &[0; 16]).unwrap(); + let (command_buffer, gate) = split( + device, + &queue, + |cb| fill(cb, &other, 0x5c), + |cb| fill(cb, used, 0x5d), + ); + let started = Instant::now(); + assert_eq!(detach(), Ok(true), "{form}: used behind the wait"); + assert!(started.elapsed() < EARLY, "{form}: the detach waited"); + gate.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + detached_backing(&command_buffer, form); + assert_eq!( + read_buffer(&other, 0, 16).unwrap(), + [0x5c; 16], + "{form}: the earlier submission ran" + ); + reattach(); + } + eprintln!( + "DETACH split: a detach between submissions detaches at once; the later submission \ + fails with code 8" + ); + }); +} + +/// A detach a completed handler calls: a buffer's or a heap's. +type Detaching = Arc Result + Send + Sync>; + +/// A detach in a completed handler of the command buffer that used the buffer answers `false`, as +/// Metal's does (37 of 40 on the M3 Max, macOS 27.0.1; the consumer measured 197 of 200 and 39 of +/// 40), and one once its `wait_until_completed` returned detaches (36 of 40 there; always 2 ms +/// later). Buffer and heap forms. +#[test] +fn a_detach_in_a_completed_handler_answers_false() { + on_device(|device| { + let queue = device.new_command_queue().unwrap(); + let Some((member, _)) = member_over(device, A) else { + return; + }; + let Some((heap, placed)) = heap_member(device) else { + return; + }; + let (buffer_answer, heap_answer) = (member.clone(), heap.clone()); + let forms: [(&str, &Buffer, Detaching); 2] = [ + ( + "buffer", + &member, + Arc::new(move || buffer_answer.detach_backing()), + ), + ( + "heap", + &placed, + Arc::new(move || heap_answer.detach_backing()), + ), + ]; + for (form, used, detach) in forms { + let answered = Arc::new(std::sync::Mutex::new(None)); + let command_buffer = queue.command_buffer().unwrap(); + let (in_handler, seen) = (Arc::clone(&detach), Arc::clone(&answered)); + command_buffer + .add_completed_handler(Box::new(move |_| { + *seen.lock().unwrap() = Some(in_handler()); + })) + .unwrap(); + fill(&command_buffer, used, 0x5a); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None, "{form}"); + assert_eq!( + *answered.lock().unwrap(), + Some(Ok(false)), + "{form}: in its completed handler" + ); + assert_eq!(detach(), Ok(true), "{form}: once the wait returned"); + } + drop(heap); + eprintln!("DETACH handler: false in the completed handler, true once the wait returned"); + }); +} + +/// The deallocator of the pages a detach lets go of runs at the buffer's next rebind, inside the +/// call, on its thread, and, where the buffer is released detached, at the release, on the +/// releasing thread; never at the detach, as Metal runs it (the M3 Max, macOS 27.0.1). A +/// keep-alive goes after the deallocator, which may read the bytes, once the import is freed. With +/// GPU use before the detach and without. +#[test] +fn a_detach_holds_the_deallocator_until_the_rebind_or_the_release() { + on_device(|device| { + let queue = device.new_command_queue().unwrap(); + for used in [false, true] { + let Some((member, old)) = member_over(device, A) else { + return; + }; + if used { + gpu_read(&queue, &member, 0..16); + } + detach(&member); + std::thread::sleep(Duration::from_millis(20)); + assert_eq!( + old.runs.load(Ordering::SeqCst), + 0, + "used {used}: at the detach" + ); + let new = rebind_to(&member, B); + ran_here(&old, "the rebind"); + if used { + gpu_read(&queue, &member, 0..16); + } + detach(&member); + std::thread::sleep(Duration::from_millis(20)); + assert_eq!( + new.runs.load(Ordering::SeqCst), + 0, + "used {used}: the second detach" + ); + drop(member); + ran_here(&new, "the release of a detached buffer"); + } + let Some((member, old, dropped)) = kept_member_over(device, A) else { + return; + }; + gpu_read(&queue, &member, 0..16); + detach(&member); + assert_eq!(old.runs.load(Ordering::SeqCst), 0, "kept: at the detach"); + // The keep-alive waits for the deallocator, which may read the bytes. + assert!( + !dropped.load(Ordering::SeqCst), + "kept: the keep-alive went first" + ); + drop(member); + ran_here(&old, "kept: the release of a detached buffer"); + let deadline = Instant::now() + WAIT; + while !dropped.load(Ordering::SeqCst) { + assert!(Instant::now() < deadline, "kept: the keep-alive never went"); + std::thread::sleep(Duration::from_millis(5)); + } + eprintln!("DETACH deallocator: at the rebind or the release, never at the detach"); }); } @@ -600,7 +1006,7 @@ fn a_detach_of_a_large_heap_allocates_no_device_memory() { detach_heap(&heap); detach(&large); assert_eq!(allocated(), made, "a detach allocated device memory"); - deallocated(&seen); + assert_eq!(seen.runs.load(Ordering::SeqCst), 0, "ran at the detach"); for (name, buffer) in [("the heap's buffer", &placed), ("the buffer", &large)] { let command_buffer = queue.command_buffer().unwrap(); let mut blit = command_buffer.blit_command_encoder().unwrap(); @@ -616,6 +1022,8 @@ fn a_detach_of_a_large_heap_allocates_no_device_memory() { made, "a command buffer naming a detached buffer allocated device memory" ); + drop(large); + ran_here(&seen, "the release of a detached buffer"); eprintln!( "DETACH memory: 0 bytes allocated detaching {} MiB twice", LARGE >> 20 @@ -623,8 +1031,8 @@ fn a_detach_of_a_large_heap_allocates_no_device_memory() { }); } -/// The rounds of [`a_detach_racing_a_commit_runs_the_deallocator_in_one_of_the_two_calls`], for -/// each form: two sweeps of the offsets. +/// The rounds of [`a_detach_racing_a_commit_leaves_the_deallocator_to_the_release`], for each +/// form: two sweeps of the offsets. const RACES: u32 = 640; /// How far apart the detach and the commit of a race start, at most, either first. @@ -644,14 +1052,15 @@ 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 once, in one of the two calls (the detach where it lets -/// go of the pages last, the commit where its encoder held them last), wherever the device's -/// recorder replays the command buffer's commands, and 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 each other. +/// 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 +/// 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 +/// each other. #[test] -fn a_detach_racing_a_commit_runs_the_deallocator_in_one_of_the_two_calls() { +fn a_detach_racing_a_commit_leaves_the_deallocator_to_the_release() { for (form, kept) in [("no keep-alive", false), ("keep-alive", true)] { on_device_noticed(|device, messages| { let queue = device.new_command_queue().unwrap(); @@ -660,8 +1069,7 @@ fn a_detach_racing_a_commit_runs_the_deallocator_in_one_of_the_two_calls() { true => kept_member_over(device, A).map(|(buffer, seen, _)| (buffer, seen)), false => member_over(device, A), }; - let detacher = std::thread::current().id(); - let (mut in_detach, mut in_commit, mut late, mut elsewhere) = (0, 0, 0, 0); + 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 { @@ -682,41 +1090,39 @@ fn a_detach_racing_a_commit_runs_the_deallocator_in_one_of_the_two_calls() { let start = Instant::now() + RACE_LEAD; let late_by = |ns: i64| Duration::from_nanos(ns.max(0) as u64); let (commit_at, detach_at) = (start + late_by(offset), start + late_by(-offset)); - let committer = std::thread::scope(|scope| { - let committing = scope.spawn(|| { + std::thread::scope(|scope| { + scope.spawn(|| { spin_until(commit_at); command_buffer.commit().unwrap(); - std::thread::current().id() }); spin_until(detach_at); detach(&buffer); - committing.join().unwrap() }); - let ran = *seen.thread.lock().unwrap(); - match (seen.runs.load(Ordering::SeqCst), ran) { - (1, Some(thread)) if thread == detacher => in_detach += 1, - (1, Some(thread)) if thread == committer => in_commit += 1, - (0, _) => late += 1, - _ => elsewhere += 1, - } + early += seen.runs.load(Ordering::SeqCst); event.set_signaled_value(value); command_buffer.wait_until_completed_for(WAIT).unwrap(); detached_backing(&command_buffer, form); - deallocated(&seen); - assert_eq!(seen.runs.load(Ordering::SeqCst), 1, "{form}: ran once"); + early += seen.runs.load(Ordering::SeqCst); + drop(command_buffer); + drop(buffer); + let here = *seen.thread.lock().unwrap() == Some(std::thread::current().id()); + match (seen.runs.load(Ordering::SeqCst), here) { + (1, true) => {} + _ => 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 in the detach {in_detach}, \ - in the commit {in_commit}, after both returned {late}, on another thread \ - {elsewhere}; {inline} command buffers replayed off the recorder's thread", + "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", device.name() ); assert_eq!( - (late, elsewhere), + (early, elsewhere), (0, 0), - "{form}: the deallocator ran outside the detach and the commit" + "{form}: the deallocator ran outside the buffer's release" ); assert_once_allowing(&messages.take_notices(), &[], &shared_kinds(device)); }); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs b/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs index 98387ac0e..297c393e8 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs @@ -1244,14 +1244,16 @@ fn a_rebound_submission_before_commit_faileds_encoders_runs_over_the_new_pages() ); } -/// A command buffer whose first batch was submitted before a rebind (its wait for an event after -/// the walker's encoder splits it) keeps the table and pages that submission took for its later -/// batch, which runs after the rebind: its blit, which names the buffer, copies the old node, and -/// its walker, which made the buffer resident, reads it, as the first batch's did (table 3: a -/// running command buffer reads the old pages). The old pages' deallocator waits for the command -/// buffer; a command buffer encoded after the rebind reads the new pages. +/// A rebind between two submissions of one command buffer (its wait for an event after the +/// walker's encoder splits it), as Metal answers it on the M3 Max (macOS 27.0.1): the later +/// submission, behind the wait, runs over the new pages with no error. Its blit, which names the +/// buffer, is encoded again by the rebind and copies the new node. Its walker, which made the +/// buffer resident, reaches it through the table the first submission fixed, and reads the old +/// node where Metal's reads the new one (`docs/FAST-PATHS.md`, known gaps), the old pages' import +/// held, and their deallocator waiting, until the command buffer completed. A command buffer +/// encoded after the rebind reads the new pages. #[test] -fn a_command_buffer_first_submitted_before_a_rebind_keeps_its_pages_in_every_later_batch() { +fn a_rebind_between_submissions_reaches_the_new_pages_in_the_later_named_use() { on_device(|device| { let queue = device.new_command_queue().unwrap(); let walker = public_case(POINTER_WALKER).unwrap(); @@ -1310,8 +1312,9 @@ fn a_command_buffer_first_submitted_before_a_rebind_keeps_its_pages_in_every_lat read_buffer(&buffers[&binding], offset, length).unwrap() }; assert!(read(&first) == outputs.a, "the first batch's walk"); + // The known gap: Metal's later walk reads the new node. assert!(read(&later) == outputs.a, "the later batch's walk"); - assert_eq!(read_buffer(&copied, 0, 16).unwrap(), node(A), "its blit"); + assert_eq!(read_buffer(&copied, 0, 16).unwrap(), node(B), "its blit"); deallocated(&old); drop(holding); let after = walk( @@ -1328,7 +1331,9 @@ fn a_command_buffer_first_submitted_before_a_rebind_keeps_its_pages_in_every_lat after.produced == outputs.b, "a command buffer encoded after" ); - eprintln!("REBIND-REACH submitted: the later batch kept the first submission's pages"); + eprintln!( + "REBIND-REACH between submissions: the later blit encoded again over the new pages" + ); }); } diff --git a/docs/API.md b/docs/API.md index db92fe22b..7ec402bf4 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2188,9 +2188,11 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. with no keep-alive on MoltenVK (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`), while the batches submitted before the import's memory went, and the program's own submissions through `CommandQueue::with_vk_queue` before it, are in flight, as MoltenVK fails pending work that reads - device addresses where such memory is freed. With a keep-alive the deallocator runs at - the release, as Metal's, and the import keeps the keep-alive, which keeps the pages mapped, until - it is freed: not announced. + device addresses where such memory is freed; with no keep-alive, a detached buffer's or heap's + rebind or release while the pages its detach let go of are still so held (the deallocator its + detach held back, which Metal runs at the replace or the release). With a keep-alive the + deallocator runs at the release, as Metal's, and the import keeps the keep-alive, which keeps + the pages mapped, until it is freed: not announced. Cost: the deallocator runs once every such command buffer lets go of the pages, or those batches complete, where Metal's runs at the release; the pages stay mapped until then. - `metal2vulkan-degrade-read-only-pages-written` (precision). `ReadOnlyPagesWritten`: A no-copy diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index efd8845ac..3175a9b22 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -311,6 +311,15 @@ driver's. Each is open work. 780M and the RX 7900 XTX under Mesa 26.2.4), but one whose Metal address was handed out, or any on a device not measured with the fact, stays live. 275 kept dma-buf imports of 512 KiB each cost 54-56 us per command buffer there (no other size measured). +- **A detach or rebind between a command buffer's submissions.** A command buffer's later + submission, behind an event wait, reaches a no-copy buffer detached or rebound after its first + submission through an address (made resident, or unnamed) through the pages its first + submission found, where Metal's reads the new pages or zeros; those pages stay imported, and + their deallocator waits (announced), until the command buffer completes. Its commands that + named the buffer are encoded again over the new pages, as Metal runs them, and fail with code 8 + where it is detached by then, as Metal's; those of an encoder that cannot be encoded again (a + command predication's command buffer, work on the GPU alone) fail `EncodedUseRebound` + (announced). - **A runtime sampler's nearest sample of an 8-bit sRGB texture under native sampling.** On a device that samples the format, the sample keeps the device's sRGB decode (announced as `SrgbTexelDecode`), where the table's exact decode of the one texel it reads would cost little: