diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 77dbd3c83..24bd6374b 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -482,8 +482,13 @@ after it, and 0 of 80 with the device dropped first that used them, with commands the runtime records once earlier work completed (an indirect command buffer's executions the GPU writes, a dispatch left to its host step, a predicated loop's run again of such work or of work on the GPU alone), has not completed; a render - encoder whose attachment lies in them uses them from its open. Where a - driver refuses the pointer (RADV refuses shared mappings, a `memfd`'s among them), memory made + encoder whose attachment lies in them uses them from its open. Other threads may encode and + commit command buffers that use the bytes during a rebind: an encoder whose call raced it is + encoded again over the new pages before its first submission, and one the runtime cannot encode + again fails `CommandBufferError::EncodedUseRebound` (`WorkCounts::encoders_raced_rebind` counts + the encoders that raced); another rebind or a detach of the same buffer or heap, a texture made + over its bytes and a resource placed in the heap during the call are the caller's to exclude. + Where a driver refuses the pointer (RADV refuses shared mappings, a `memfd`'s among them), memory made with `HostMemory::with_dma_buf` is imported from dma-bufs of its pages instead ([HOWTO](../../docs/HOWTO.md#6-host-memory-a-driver-refuses)), and a no-copy buffer or heap over memory made without a source is a copy of its pages, as below. A device that enables no diff --git a/crates/metal2vulkan-runtime/src/argument_table.rs b/crates/metal2vulkan-runtime/src/argument_table.rs index 16478241f..590f5a131 100644 --- a/crates/metal2vulkan-runtime/src/argument_table.rs +++ b/crates/metal2vulkan-runtime/src/argument_table.rs @@ -1941,6 +1941,12 @@ impl ArgumentTable { read: (Stage, &PipelineInterface), (maps, views): (&SamplerMaps, &AtBindViews), ) { + // A call that raced a rebind on another thread may have kept what a reading now no longer + // finds; its hold tells it apart, and its encoder runs only encoded again + // (`rebind::call_may_have_raced`). + if crate::rebind::call_may_have_raced() { + return; + } let (stage, _) = read; const DIFFERS: &str = "a stage table brought in place that is not the table read whole"; // The slots that tell the view base alignment apart, and those that tell offset 0 apart, diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index 366925c6f..6a4b2997b 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -271,6 +271,7 @@ impl BlitCommandEncoder { call: impl FnOnce(&mut CallLog) -> BlitCall, run: impl FnOnce(&mut Self) -> Result, ) -> Result { + self.core.begin_call(); let _for = self.core.notices_for(); self.refuse_aborted()?; if flush { @@ -812,6 +813,7 @@ impl BlitCommandEncoder { fill_tiles: _, mut run, } = self; + core.begin_call(); core.flush_copies(&mut run); if let Some(pattern) = pattern { core.retain(pattern); diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 64524b055..a5cab819d 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -373,7 +373,8 @@ impl TexturesOver { } /// How many times a no-copy buffer of the process (or a no-copy heap's own buffer) came to lie -/// elsewhere ([`HostCell::replace`]: rebound or detached). +/// elsewhere ([`HostCell::replace`]: rebound or detached), and a rebind settled what lies over +/// its bytes ([`host_cells_settled`]). static HOST_CELLS_MOVED: AtomicU64 = AtomicU64::new(0); /// The count of the times a no-copy buffer of the process came to lie elsewhere (rebound or @@ -383,6 +384,14 @@ pub(super) fn host_cells_moved() -> u64 { HOST_CELLS_MOVED.load(Ordering::Acquire) } +/// A rebind closed its publish (`Rebinds::published`): the images, views and texel views over the +/// moved buffer's bytes are made over its new pages, so a binding read since its move, while they +/// were being made, may hold the old pages' ones. Counted in [`host_cells_moved`] as a move: no +/// binding read before it is kept after it (`rebind.rs`, **Other threads**). +pub(super) fn host_cells_settled() { + HOST_CELLS_MOVED.fetch_add(1, Ordering::AcqRel); +} + /// The most buffers over host pages a [`KeptSpaces`] keeps where they lie. const KEPT_SPACES: usize = 4; @@ -420,12 +429,18 @@ impl KeptSpaces { let at = Arc::as_ptr(cell); let found = (self.kept.iter()).find(|kept| kept.moved == moved && kept.cell.as_ptr() == at); if let Some(kept) = found { + // Unless it moved since `moved` was read, on another thread (`rebind.rs`, **Other + // threads**): the move is counted under the cell's lock, before a reading of it can + // see where it lies now, and the call's hold tells the race apart. #[cfg(debug_assertions)] - assert_eq!( - kept.pages, - cell.binding_pages(), - "a buffer kept where it no longer lies" - ); + { + let now = cell.binding_pages(); + assert!( + kept.pages == now || host_cells_moved() != moved, + "a buffer kept where it no longer lies: {:?}, lying in {now:?}", + kept.pages + ); + } return kept.pages; } cell.device.shared().counts.thread().bind_space_read(); diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index a94aa8d84..ceda258df 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -1694,8 +1694,11 @@ impl Device { .rebinds .replace(key, cell, Arc::clone(&pages)) .map_err(|_| encoded())?; - // Its read twins over the old pages go, the rebinds' lock let go of (`LeftTwins`). - drop(twins); + // The publish is open from here to its close below, and as short as it can be: what lies + // over the bytes is made over the new pages, and nothing goes, nor any deallocator runs, + // until it closes (`rebind.rs`, **Other threads**). + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + crate::rebind::pause::at(crate::rebind::pause::Point::Publishing, key); // The buffer, or the heap's buffers, are reached unnamed again only once a command buffer // uses it after the rebind, over the new pages. shared.live_buffers.rebound(buffer, heap); @@ -1755,9 +1758,19 @@ impl Device { if rebound || !stood_in.is_empty() { super::heap_sets::renew_over(self, key); } + // Everything over the bytes is made over the new pages: the publish closes, marking the + // command buffers committed while it was open whose encoders named the buffer too. + let mut again = again; + for buffer in shared.rebinds.published(key) { + if !again.iter().any(|had| Arc::ptr_eq(had, &buffer)) { + again.push(buffer); + } + } if !stood_in.is_empty() { super::heap_sets::retire(self, Box::new(stood_in)); } + // Its read twins over the old pages go, the rebinds' lock let go of (`LeftTwins`). + drop(twins); // 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`). diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index db9b2ff06..485b79dd7 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -4705,7 +4705,7 @@ impl CommandBuffer { } copies_again = CopiesAgain::new(unreached, (used, written)); } - let (waits, away, reaches, unreplayable, (reset, splits)) = { + let (waits, away, reaches, unreplayable, (reset, splits, raced)) = { let mut state = self.state(); state.committing = false; state.copies_again = copies_again; @@ -4797,6 +4797,13 @@ impl CommandBuffer { state.split_units = split; self.0.mark_reencode(); } + // So are its encoders a call of which raced a rebind on another thread of a buffer + // it took (`rebind.rs`, **Other threads**), over where the buffer lies now; one that + // kept no log fails `EncodedUseRebound` at its submission. + let raced = state.raced_again(); + if raced { + self.0.mark_reencode(); + } if let Some(slot) = lock(&self.0.slot).as_mut() { slot.committed(); } @@ -4875,7 +4882,7 @@ impl CommandBuffer { away, state.heaps.bound(), unreplayable, - (reset, splits), + (reset, splits, raced), ) }; // Each making the batches wait for wakes the scheduler as it finishes, with no lock @@ -4922,10 +4929,10 @@ impl CommandBuffer { slot.handed(); } // Its passes that took a rasterization-rate map since reset, encoded again in this call - // as a reset's are; its first submission waits for them (marked above). Those it cannot - // encode again are announced. + // as a reset's are, and its encoders that raced a rebind; its first submission waits for + // them (marked above). Those it cannot encode again are announced. let (again, unencoded) = reset; - if again || splits { + if again || splits || raced { self.0.reencode(); } for unlogged in unencoded { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 6badee03b..b41cb36bc 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -127,7 +127,9 @@ impl CommandBufferShared { /// 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. + /// encodes nothing again. An encoder whose encoding again raced a rebind of a buffer it took + /// (`Taken::raced`, `rebind.rs`'s **Other threads**) is encoded again once no rebind's + /// publish is open (`Rebinds::wait_published`), until one does not race. pub(crate) fn reencode(self: &Arc) { let _for = self.notices_for(); let turn = lock(&self.reencoding); @@ -135,6 +137,22 @@ impl CommandBufferShared { if marked == 0 { return; } + while self.encode_moved() { + self.device.shared().rebinds.wait_published(); + } + // 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); + drop(turn); + self.device.shared().scheduler.wake(); + } + + /// One turn of [`reencode`](Self::reencode), its caller holding the turn: each encoder that + /// moved encoded again and put in place, and the work on the GPU alone recorded again. + /// Whether an encoder it put in place raced a rebind as it was encoded again. + fn encode_moved(self: &Arc) -> bool { let device = &self.device; // The encoders of its event groups not submitted yet: those before were judged, and run // over the pages they took. @@ -392,13 +410,8 @@ impl CommandBufferShared { } } drop(handle); - // 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); - drop(turn); - device.shared().scheduler.wake(); + let state = lock(&self.state); + (spliced.iter()).any(|&at| state.ended[at].taken.raced()) } /// Encode ended encoder `at` again from `replay`, its log, on the rebind's thread (the module @@ -863,6 +876,14 @@ impl State { } } + /// As it commits, once its replays are kept ([`State::keep_replays`]): whether an encoder a + /// call of which raced a rebind of a buffer it took (`Taken::raced`) is to be encoded again, + /// in the commit's call, before its first submission, its log kept. One that kept none keeps + /// its first recording, which that submission fails (`EncodedUseRebound`). + pub(super) fn raced_again(&self) -> bool { + (self.ended.iter()).any(|record| record.taken.raced() && record.replay.is_some()) + } + /// As it commits, once its replays are kept ([`State::keep_replays`]): whether an encoder /// whose pass took a rasterization-rate map since reset, before the commit, is to be encoded /// again before its first submission, its log kept (`rate_mapped_pass.rs`); and why each that diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 8d78a9258..f02ae6202 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -400,6 +400,7 @@ impl ComputeCommandEncoder { call: impl FnOnce(&mut CallLog) -> ComputeCall, run: impl FnOnce(&mut Self) -> Result, ) -> Result { + self.core.begin_call(); let _for = self.core.notices_for(); let at = self.log(call); let ran = run(self); @@ -1706,6 +1707,7 @@ impl ComputeCommandEncoder { /// `endEncoding`. What it binds is held until the command buffer completes, as Metal holds /// what an encoder was handed. pub fn end_encoding(mut self) -> Result<(), Error> { + self.core.begin_call(); let _for = self.core.notices_for(); // Its unit of command predication takes what it encoded (`predication.rs`): as its core // ends, under the one lock that takes, where its command buffer has no record. diff --git a/crates/metal2vulkan-runtime/src/compute/live.rs b/crates/metal2vulkan-runtime/src/compute/live.rs index 17bf368c8..c3d8d0936 100644 --- a/crates/metal2vulkan-runtime/src/compute/live.rs +++ b/crates/metal2vulkan-runtime/src/compute/live.rs @@ -442,6 +442,10 @@ impl LiveDispatch { samplers: Option<&[crate::sampler::SamplerState]>, function_tables: &[VisibleFunctionTable], ) { + // As `ArgumentTable::check_reading`: not in a call that raced a rebind on another thread. + if crate::rebind::call_may_have_raced() { + return; + } let mut whole = tables.bind_state(samplers.unwrap_or_default(), function_tables); maps.apply(&mut whole); let state = &self.state; diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index c59f9564f..2a63daa5d 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1710,9 +1710,12 @@ degradations! { /// A command buffer's command named a buffer over the caller's host pages (a binding, a /// blit's operand, an attachment, a texture over the pages, an indirect command's /// resolved buffer) that was rebound (`rebind_bytes_no_copy`) after the command was - /// encoded and before the command buffer was first submitted + /// encoded and before the command buffer was first submitted, or that a rebind on another + /// thread raced the command's encoding of (its call held the buffer while the rebind was + /// making what lies over its bytes again, or after, having begun before: `rebind.rs`'s + /// **Other threads**, `WorkCounts::encoders_raced_rebind`) /// (`CommandBufferError::EncodedUseRebound`, `command_buffer/first_submission.rs`), in an - /// encoder the rebind could not encode again (a compute encoder its unit of command + /// encoder the runtime could not encode again (a compute encoder its unit of command /// predication reaches past: one whose unit laid a step before it opened, or one of its /// own that the unit's later encoders read, or whose unit holds a loop or leaves work /// out; a render pass a host step records; work diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 5333a66f3..5dd9291dc 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -1286,6 +1286,10 @@ impl EncoderCore { buffer: &Buffer, offset: u64, ) -> Result<(vk::Buffer, u64), Error> { + // Held before its `VkBuffer` is read, as the command's uses hold it: a copy that joins a + // run records later, in another call (`copy_run.rs`), where a rebind between would go + // unseen by the call's hold (`rebind.rs`, **Other threads**). + self.touch_keys([buffer.identity().key]); let (at, hold) = buffer.blit_at(offset)?; if let Some(hold) = hold { self.taken.hold_import(hold); @@ -2323,18 +2327,37 @@ impl EncoderCore { } } - /// Hold `key` where it names a buffer over host pages (`rebind.rs`). + /// Hold `key` where it names a buffer over host pages (`rebind.rs`). Where the call under + /// way raced a rebind of it (`Rebinds::hold`), what the call read of it before may be the + /// old pages': the encoder's commands run only encoded again (`Taken::race`). fn hold(&mut self, key: ResourceKey) { // Encoded again after the commit: nothing refuses a rebind for it. - if self.replaying { - if let Some(pinned) = self.holds.pin(key) { - self.taken.pin(key, pinned); - } + let taken = match self.replaying { + true => self.holds.pin(key), + false => self.holds.hold(key), + }; + let Some((pinned, raced)) = taken else { return; + }; + self.taken.pin(key, pinned); + if raced && !self.taken.raced() { + self.taken.race(); + self.device().shared().counts.encoder_raced_rebind(); } - if let Some(pinned) = self.holds.hold(key) { - self.taken.pin(key, pinned); - } + } + + /// The encoder's next call begins (a logged call, a render encoder's lowered call, an end), + /// before it reads anything of a buffer over host pages: a hold in it of a buffer whose + /// rebind's publish closed since, or is open, finds the call raced that rebind + /// (`Holds::begin_call`). One load. + pub(super) fn begin_call(&mut self) { + self.holds.begin_call(); + } + + /// The encoder's call begins as one began at `call` (`Rebinds::call_begins`): a render + /// encoder's open, which read the pass's attachments before its core was made. + pub(super) fn begun_at(&mut self, call: u64) { + self.holds.begun_at(call); } /// Whether the commands it records from now on were called while no buffer of the device was diff --git a/crates/metal2vulkan-runtime/src/heap_sets.rs b/crates/metal2vulkan-runtime/src/heap_sets.rs index 652fa770f..3b6663489 100644 --- a/crates/metal2vulkan-runtime/src/heap_sets.rs +++ b/crates/metal2vulkan-runtime/src/heap_sets.rs @@ -2472,9 +2472,11 @@ pub(super) fn renew(device: &Device) { /// of the buffer of `key` (`Texture::bytes_key`; a heap's own buffer for its textures and those /// over its buffers), and no other's: a rebind or a detach of those bytes remade their images or /// views, or made them present stand-ins or their own images again (`buffer_descriptor.rs`, -/// `detach.rs`); its caller commits no command that uses the bytes meanwhile, so no pending -/// command buffer reads the elements rewritten. Every other texture's images and views stay -/// what its elements were written with. +/// `detach.rs`). A detach's caller commits no command that uses the bytes meanwhile, and a +/// command that uses them encoded on another thread during a rebind raced it and runs only +/// encoded again once the rebind closed its publish (`rebind.rs`, **Other threads**), so no +/// pending command buffer reads the elements rewritten. Every other texture's +/// images and views stay what its elements were written with. pub(super) fn renew_over(device: &Device, key: ResourceKey) { sync(device, Slots::Over(key)); } diff --git a/crates/metal2vulkan-runtime/src/predication.rs b/crates/metal2vulkan-runtime/src/predication.rs index 73cb757ae..12988cb18 100644 --- a/crates/metal2vulkan-runtime/src/predication.rs +++ b/crates/metal2vulkan-runtime/src/predication.rs @@ -2010,6 +2010,7 @@ impl ComputeCommandEncoder { /// for the End that closes that block; with no block open it is an unbalanced record, /// answering `NO` (the module docs). pub fn encode_end_if(&mut self) -> Result { + self.core().begin_call(); let _for = self.core().notices_for(); let at = self.log(|_| ComputeCall::EndIf(false)); let result = self.encode_end_if_uncounted(); @@ -2051,6 +2052,7 @@ impl ComputeCommandEncoder { comparison: u64, reference_value: u32, ) -> Result<(), Error> { + self.core().begin_call(); let _for = self.core().notices_for(); self.stop_logging(); let result = self.encode_start_while_uncounted(buffer, offset, comparison, reference_value); @@ -2088,6 +2090,7 @@ impl ComputeCommandEncoder { /// run, and again while that End's condition holds after each run, as /// [`encode_start_while`](Self::encode_start_while)'s run, laid down as there. pub fn encode_start_do_while(&mut self) -> Result<(), Error> { + self.core().begin_call(); let _for = self.core().notices_for(); self.stop_logging(); let result = self.encode_start_do_while_uncounted(); @@ -2104,6 +2107,7 @@ impl ComputeCommandEncoder { /// block it kills the outermost open block and answers `NO`; with no block open it is an /// unbalanced record, answering `NO` (the module docs). pub fn encode_end_while(&mut self) -> Result { + self.core().begin_call(); let _for = self.core().notices_for(); self.stop_logging(); let result = self.encode_end_while_uncounted(); @@ -2133,6 +2137,7 @@ impl ComputeCommandEncoder { comparison: u64, reference_value: u32, ) -> Result { + self.core().begin_call(); let _for = self.core().notices_for(); self.stop_logging(); let result = diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index a5f722387..a8635315c 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -48,6 +48,32 @@ //! encoded: a rebind after its submission keeps the old pages for every run again, as Metal's //! loop runs on over them, and one before it fails that submission (`EncodedUseRebound`), as //! the laying's encoders cannot be encoded again. +//! - **Other threads.** A rebind may run while other threads encode and commit command buffers that +//! use the buffer or heap. Its publish runs from the moment the buffer lies in the new pages +//! ([`Rebinds::replace`]) to the moment everything over its bytes (aliasing images and their +//! views, texel views, the heap sets' elements) is made over them ([`Rebinds::published`]); the +//! old pages, their twins and their deallocator go only after it closes, and the close counts as +//! a move (`buffer::host_cells_moved`), so no binding an encoder read while it was open is kept +//! past it. Each encoder call reads, as it begins, how many publishes closed (one atomic load, +//! [`Rebinds::call_begins`]), and its holds compare it: a call that holds or takes the buffer +//! while its publish is open, or after it closed having begun before, raced the rebind, and what +//! it read of the buffer before its hold may be the old pages' (`Taken::raced`, counted by +//! `WorkCounts::encoders_raced_rebind`). Such an encoder runs only encoded again over the new +//! pages, after the publish closed: by its commit, in the commit's call, or by the rebind's call +//! where it committed while the publish was open. An encoder the runtime cannot encode again +//! whose call raced a rebind fails `CommandBufferError::EncodedUseRebound` at its submission, +//! announced (`encoded-use-rebound`): a compute encoder its unit of command predication reaches +//! past, one that left a GPU-written indirect dispatch to its host step, a blit or render encoder +//! opened while the device had no buffer over host pages, an encoder whose command buffer's +//! commit fails it, and one with a call that answers otherwise than at its encoding +//! (`command_buffer/rebound_use.rs`; a resource state encoder takes no pages, so races none). A +//! rebind no encode of the buffer overlaps changes nothing for them: every call either held the +//! buffer before the rebind, which refuses it (`EncodedUses`), or began after its publish closed +//! and reads the new pages. A commit and a submission order against the rebind under `buffers`' +//! lock as above. Another rebind of the same buffer or heap whose publish is open is refused +//! (`EncodedUses`); a rebind or detach of it on another thread, a texture made over its bytes and +//! a resource placed in the heap during the call stay the caller's to exclude +//! (`Buffer::rebind_bytes_no_copy`'s **Safety**). //! - **The new pages' import.** New memory that is the bytes a live no-copy buffer was made over, //! of its memory class, lies in that buffer's import, as a buffer made over them does //! (`host_aliases.rs`): the rebind imports nothing, pins no page and asks the kernel about no @@ -145,6 +171,16 @@ pub(super) struct Rebinds { /// again, and that work recorded again before the first submission. Taken under `buffers`' /// lock, after it. waiting: Mutex, + /// How many rebinds closed their publish ([`Rebinds::published`]): an encoder's call reads it + /// as it begins ([`Rebinds::call_begins`]), and a hold or pin in the call of a buffer whose + /// publish closed past that, or is open, finds the call raced it (the module docs, **Other + /// threads**). + published: AtomicU64, + /// How many rebinds' publishes are open ([`Rebinds::replace`] to [`Rebinds::published`]). + open: AtomicUsize, + /// Signaled as a rebind closes its publish: an encoding again that raced one waits for none + /// to be open before it encodes again (`CommandBufferShared::reencode`). + closed: Condvar, } /// The command buffers waiting for the submission of an event group whose encoders a rebind @@ -216,6 +252,30 @@ struct Entry { /// made them resident, so a detach leaves their textures' unnamed reads reading those pages /// (`Device::reach_stale_detached`). resident: bool, + /// A rebind gave it new pages and has not closed its publish yet ([`Rebinds::published`]): + /// the images, views and heap elements over its bytes may still be the old pages'. + publishing: bool, + /// [`Rebinds::published`]'s count as its last rebind's publish closed (0 before any). + published: u64, +} + +impl Entry { + /// Whether an encoder's call begun at `call` ([`Rebinds::call_begins`]) that holds or pins the + /// buffer now raced a rebind of it: the rebind's publish is open, or closed after the call + /// began, so what the call read of the buffer before this hold may be the old pages', or + /// half made (the module docs, **Other threads**). + fn raced(&self, call: u64) -> bool { + self.publishing || self.published > call + } +} + +/// What a command takes of a buffer over host pages that lies as `cell` says: the pages it lies +/// in, or none while it is detached. +fn pinned(cell: &HostCell) -> Pinned { + match cell.lying() { + Lying::In(pages) => Pinned::Held(pages), + Lying::Detached(_) | Lying::Gone(_) => Pinned::Detached, + } } /// The keys a device registered buffers over host pages under ([`Rebinds::register`]), as a filter @@ -278,6 +338,8 @@ impl Rebinds { submitted: 0, detached: false, resident: false, + publishing: false, + published: 0, }; self.hosted.insert(key); if lock(&self.buffers).insert(key, entry).is_none() { @@ -298,29 +360,97 @@ impl Rebinds { /// Hold `key` for an encoder's commands, which used it: the pages they took, which their /// command buffer retains until it completed, or `Pinned::Detached` while it is detached; /// `None` where `key` names no buffer over host pages. The hold refuses a rebind until - /// [`Rebinds::release`]. - fn hold(&self, key: ResourceKey) -> Option { + /// [`Rebinds::release`]. With whether the encoder's call that takes it, begun at `call` + /// ([`Rebinds::call_begins`]), raced a rebind of it ([`Entry::raced`]). + fn hold(&self, key: ResourceKey, call: u64) -> Option<(Pinned, bool)> { let mut buffers = lock(&self.buffers); let entry = buffers.get_mut(&key)?; let cell = entry.cell.upgrade()?; entry.pending += 1; - Some(match cell.lying() { - Lying::In(pages) => Pinned::Held(pages), - Lying::Detached(_) | Lying::Gone(_) => Pinned::Detached, - }) + Some((pinned(&cell), entry.raced(call))) } /// What a command an encoder encodes again took of the buffer of `key` (`replay.rs`), as /// [`Rebinds::hold`] answers it, without the hold: its command buffer is committed, so /// nothing it encodes refuses a rebind. - fn pin(&self, key: ResourceKey) -> Option { + fn pin(&self, key: ResourceKey, call: u64) -> Option<(Pinned, bool)> { let buffers = lock(&self.buffers); - let cell = buffers.get(&key)?.cell.upgrade()?; - let pinned = match cell.lying() { - Lying::In(pages) => Pinned::Held(pages), - Lying::Detached(_) | Lying::Gone(_) => Pinned::Detached, + let entry = buffers.get(&key)?; + let cell = entry.cell.upgrade()?; + Some((pinned(&cell), entry.raced(call))) + } + + /// The count an encoder's call reads as it begins, before it reads anything of a buffer over + /// host pages (`Holds::begin_call`): a hold or pin in the call of a buffer whose rebind's + /// publish closed past that count, or is open, finds the call raced the rebind + /// ([`Entry::raced`]). + pub(super) fn call_begins(&self) -> u64 { + self.published.load(Ordering::Acquire) + } + + /// The rebind that gave the buffer of `key` new pages ([`Rebinds::replace`]) closes its + /// publish: everything over its bytes is made over the new pages (images swapped in, texel + /// views let go of, heap elements written again). An encoder's call begun before now that + /// holds or pins the buffer finds it raced the rebind ([`Entry::raced`]). The command buffers + /// waiting for the submission of an event group whose replayable encoders named it, marked + /// under this lock to encode them again as `replace` marks them, for the caller to run: those + /// committed while the publish was open among them, whose raced encoders their commit encoded + /// again then (`State::raced_again`) over what may not yet have been the new pages'. + pub(super) fn published(&self, key: ResourceKey) -> Vec> { + let mut buffers = lock(&self.buffers); + let Some(entry) = buffers.get_mut(&key).filter(|entry| entry.publishing) else { + return Vec::new(); }; - Some(pinned) + entry.publishing = false; + // What a binding read of the buffers over host pages while the publish was open may be of + // the old pages' images and views: a move, for every binding kept since + // (`buffer::host_cells_moved`), before a call that begins after the close can read the + // count. + super::buffer::host_cells_settled(); + entry.published = self.published.fetch_add(1, Ordering::AcqRel) + 1; + self.open.fetch_sub(1, Ordering::AcqRel); + #[cfg(debug_assertions)] + PUBLISHES_OPEN.fetch_sub(1, Ordering::AcqRel); + let again = self.mark_waiting(key); + drop(buffers); + self.closed.notify_all(); + again + } + + /// Wait until no rebind's publish is open, with no other lock of the runtime's held: an + /// encoding again that raced one encodes again after (`CommandBufferShared::reencode`), and a + /// publish waits for nothing an encoder holds. + pub(super) fn wait_published(&self) { + let mut buffers = lock(&self.buffers); + while self.open.load(Ordering::Acquire) > 0 { + buffers = match self.closed.wait(buffers) { + Ok(buffers) => buffers, + Err(poisoned) => poisoned.into_inner(), + }; + } + } + + /// Mark each command buffer waiting for the submission of an event group whose replayable + /// encoders or work on the GPU alone named the buffer of `key` to encode or record them again + /// before that submission (`CommandBufferShared::reencode`), each once, for the caller to run + /// and let go of without this lock. The caller holds `buffers`' lock. + fn mark_waiting(&self, key: ResourceKey) -> Vec> { + let mut again: Vec> = Vec::new(); + let waiting = lock(&self.waiting); + let named = (waiting.buffers.iter()) + .filter(|(_, keys)| keys.binary_search(&key).is_ok()) + .map(|(buffer, _)| buffer); + for buffer in named { + let Some(buffer) = buffer.upgrade() else { + continue; + }; + if again.iter().any(|had| Arc::ptr_eq(had, &buffer)) { + continue; + } + buffer.mark_reencode(); + again.push(buffer); + } + again } /// Note `buffer`, committed now and not yet first submitted, whose encoders that can be @@ -504,7 +634,8 @@ impl Rebinds { /// 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. + /// the caller runs; `Err` gives `pages` back. Its publish is open from here until the caller + /// closes it ([`Rebinds::published`]). pub(super) fn replace( &self, key: ResourceKey, @@ -516,7 +647,9 @@ impl Rebinds { let (lying, twins) = cell.replace(Lying::In(pages)); return Ok((lying, twins, Vec::new())); }; - if entry.pending > 0 { + // A rebind of it on another thread whose publish is open refuses this one as a hold does, + // where the caller's contract has none (`Buffer::rebind_bytes_no_copy`). + if entry.pending > 0 || entry.publishing { return Err(pages); } if entry.detached { @@ -525,25 +658,16 @@ impl Rebinds { } // No command buffer made the new pages resident yet. entry.resident = false; + // What lies over the bytes is the old pages' until the publish closes. + entry.publishing = true; + self.open.fetch_add(1, Ordering::AcqRel); + #[cfg(debug_assertions)] + PUBLISHES_OPEN.fetch_add(1, Ordering::AcqRel); let (lying, twins) = cell.replace(Lying::In(pages)); // 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(); - let waiting = lock(&self.waiting); - let named = (waiting.buffers.iter()) - .filter(|(_, keys)| keys.binary_search(&key).is_ok()) - .map(|(buffer, _)| buffer); - for buffer in named { - let Some(buffer) = buffer.upgrade() else { - continue; - }; - if again.iter().any(|had| Arc::ptr_eq(had, &buffer)) { - continue; - } - buffer.mark_reencode(); - again.push(buffer); - } + let again = self.mark_waiting(key); Ok((lying, twins, again)) } } @@ -586,23 +710,27 @@ impl Found { impl Submitting<'_> { /// Whether a buffer a command of `taken` named lies elsewhere than the command took it, not - /// detached: what [`Submitting::submit`] finds `rebound`, judged without taking anything. + /// detached, or a command of it raced a rebind ([`Taken::raced`]): what + /// [`Submitting::submit`] finds `rebound`, judged without taking anything. pub(super) fn rebound(&self, taken: &Taken) -> bool { - taken.pins.iter().any(|(key, pinned)| { - if !taken.named.contains(key) { - return false; - } - let entry = self.buffers.get(key); - let cell = entry.and_then(|entry| entry.cell.upgrade()); - match (pinned, cell.as_ref().map(|cell| cell.lying())) { - (_, None) | (_, Some(Lying::Detached(_) | Lying::Gone(_))) => false, - (Pinned::Detached, Some(Lying::In(_))) => true, - (Pinned::Held(pages), Some(Lying::In(current))) => !Arc::ptr_eq(pages, ¤t), - (Pinned::Waiting(pages), Some(Lying::In(current))) => { - !std::ptr::eq(Weak::as_ptr(pages), Arc::as_ptr(¤t)) + taken.raced + || taken.pins.iter().any(|(key, pinned)| { + if !taken.named.contains(key) { + return false; } - } - }) + let entry = self.buffers.get(key); + let cell = entry.and_then(|entry| entry.cell.upgrade()); + match (pinned, cell.as_ref().map(|cell| cell.lying())) { + (_, None) | (_, Some(Lying::Detached(_) | Lying::Gone(_))) => false, + (Pinned::Detached, Some(Lying::In(_))) => true, + (Pinned::Held(pages), Some(Lying::In(current))) => { + !Arc::ptr_eq(pages, ¤t) + } + (Pinned::Waiting(pages), Some(Lying::In(current))) => { + !std::ptr::eq(Weak::as_ptr(pages), Arc::as_ptr(¤t)) + } + } + }) } /// `buffer`'s last event group is submitted now: it waits for no rebind's replay from here @@ -665,6 +793,12 @@ impl Submitting<'_> { None => found.moved = true, } } + // A command that raced a rebind of a buffer it took may have read the old pages before + // its hold (`Taken::raced`): its recording runs nothing, as one whose buffer moved. + if taken.raced { + found.moved = true; + found.rebound |= !found.detached; + } // `cell` and `now` drop here, under the lock: never the last hold of anything (above). found } @@ -711,30 +845,54 @@ impl Drop for SubmittedHolds { pub(super) struct Holds { device: Device, keys: Vec, + /// [`Rebinds::call_begins`] as the encoder's call under way began ([`begin_call`]( + /// Self::begin_call)), or as the holds were made: a hold or pin in the call finds whether + /// the call raced a rebind of what it takes against it. + call: u64, } impl Holds { - /// No holds yet, on `device`. + /// No holds yet, on `device`, its encoder's first call begun now. pub(super) fn new(device: &Device) -> Holds { + #[cfg(debug_assertions)] + CALL_MOVED.set(super::buffer::host_cells_moved()); Holds { device: device.clone(), keys: Vec::new(), + call: device.shared().rebinds.call_begins(), } } + /// The encoder's next call begins, before it reads anything of a buffer over host pages (an + /// encoder's logged call, a render encoder's lowered one, an end): one load. + pub(super) fn begin_call(&mut self) { + #[cfg(debug_assertions)] + CALL_MOVED.set(super::buffer::host_cells_moved()); + self.call = self.device.shared().rebinds.call_begins(); + } + + /// The encoder's call begins as one began at `call` ([`Rebinds::call_begins`]): a render + /// encoder's open, read before the pass's attachments were. + pub(super) fn begun_at(&mut self, call: u64) { + self.call = call; + } + /// Hold `key` where it names a buffer over host pages: the pages the commands took, to - /// retain until the command buffer completes (none while it is detached). + /// retain until the command buffer completes (none while it is detached), with whether the + /// call under way raced a rebind of it ([`Rebinds::hold`]). /// A key whose bit the device's filter of such keys never set names none, told without the /// lock (`HostedKeys`). - pub(super) fn hold(&mut self, key: ResourceKey) -> Option { + pub(super) fn hold(&mut self, key: ResourceKey) -> Option<(Pinned, bool)> { let shared = self.device.shared(); if !shared.rebinds.hosted.may_hold(key) { return None; } shared.counts.thread().host_hold_looked_up(); - let pinned = shared.rebinds.hold(key)?; + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pause::at(pause::Point::Holding, key); + let taken = shared.rebinds.hold(key, self.call)?; self.keys.push(key); - Some(pinned) + Some(taken) } /// Whether it holds nothing. @@ -748,9 +906,81 @@ impl Holds { } /// What a command an encoder encodes again took of `key` ([`Rebinds::pin`]), held by - /// nothing here. - pub(super) fn pin(&self, key: ResourceKey) -> Option { - self.device.shared().rebinds.pin(key) + /// nothing here, with whether the call under way raced a rebind of it. + pub(super) fn pin(&self, key: ResourceKey) -> Option<(Pinned, bool)> { + self.device.shared().rebinds.pin(key, self.call) + } +} + +/// How many rebinds of the process have their publish open ([`Rebinds::replace`] to +/// [`Rebinds::published`]), for [`call_may_have_raced`]. Debug builds. +#[cfg(debug_assertions)] +static PUBLISHES_OPEN: AtomicUsize = AtomicUsize::new(0); + +#[cfg(debug_assertions)] +thread_local! { + /// `buffer::host_cells_moved` as the encoder call under way on this thread began + /// ([`Holds::begin_call`]), for [`call_may_have_raced`]. Debug builds. + static CALL_MOVED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Whether what the encoder call under way on this thread read of buffers over host pages may +/// differ from a reading of them now, as a call that raced a rebind on another thread reads (the +/// module docs, **Other threads**): a no-copy buffer moved since the call began, or a rebind's +/// publish is open. A debug check that compares what the call kept with a reading now +/// (`ArgumentTable::check_reading`) holds only where neither, the call's hold telling a race apart +/// (`Taken::raced`). Debug builds. +#[cfg(debug_assertions)] +pub(super) fn call_may_have_raced() -> bool { + CALL_MOVED.get() != super::buffer::host_cells_moved() + || PUBLISHES_OPEN.load(Ordering::Acquire) > 0 +} + +/// Points a device test holds a thread at, to order an encoder's call against a rebind's +/// publish (`tests::rebind_races`): armed for a buffer's key, each holds the first thread that +/// meets it there, once, until the test lets it go. +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +pub(crate) mod pause { + use super::ResourceKey; + use std::sync::mpsc::{channel, Receiver, Sender}; + use std::sync::Mutex; + + /// Where a thread is held. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) enum Point { + /// An encoder about to hold the buffer (`Holds::hold`), after what its call read before. + Holding, + /// A rebind whose publish is open: the buffer lies in its new pages, and what lies over + /// its bytes is not made over them yet (`Device::rebind_host_pages`). + Publishing, + } + + /// An armed point: its key, the sender that says a thread reached it, and the receiver it + /// waits on. + type Armed = (Point, ResourceKey, Sender<()>, Receiver<()>); + + static ARMED: Mutex> = Mutex::new(Vec::new()); + + /// Arm `point` for the buffer of `key`: the receiver hears a thread reach it, and the sender + /// lets it go. + pub(crate) fn arm(point: Point, key: ResourceKey) -> (Receiver<()>, Sender<()>) { + let (reached, hears) = channel(); + let (go, waits) = channel(); + ARMED.lock().unwrap().push((point, key, reached, waits)); + (hears, go) + } + + /// Hold this thread at `point` for `key`, where a test armed it, until the test lets it go. + pub(crate) fn at(point: Point, key: ResourceKey) { + let armed = { + let mut armed = ARMED.lock().unwrap(); + let at = armed.iter().position(|(p, k, ..)| *p == point && *k == key); + at.map(|at| armed.remove(at)) + }; + if let Some((_, _, reached, waits)) = armed { + let _ = reached.send(()); + let _ = waits.recv(); + } } } @@ -786,6 +1016,10 @@ pub(super) struct Taken { /// which its draws were planned by: a reset of the map before the submission of its event /// group has the encoder encoded again (`rate_mapped_pass.rs`). rate_map: Option<(RasterizationRateMap, Arc)>, + /// A command of it raced a rebind of a buffer it took ([`Taken::race`]): what its call read of + /// the buffer before its hold may be the old pages', so its submission runs it only encoded + /// again, as one whose buffer moved. + raced: bool, } /// The objects of a releasable import a blit's command took (`Buffer::blit_at`, @@ -887,20 +1121,32 @@ impl Taken { self.pins.extend(other.pins); self.named.extend(other.named); self.dead |= other.dead; + self.raced |= other.raced; if self.rate_map.is_none() { self.rate_map = other.rate_map; } } + /// A command of it raced a rebind of a buffer it took: the call that encoded it began before + /// the rebind's publish closed ([`Rebinds::hold`]). + pub(super) fn race(&mut self) { + self.raced = true; + } + + /// Whether a command of it raced a rebind ([`race`](Self::race)). + pub(super) fn raced(&self) -> bool { + self.raced + } + /// Note that the encoder's render pass is over `map`, which it took as `state`. pub(super) fn take_rate_map(&mut self, map: RasterizationRateMap, state: Arc) { self.rate_map = Some((map, state)); } /// Whether a rebind or a reset may have the encoder encoded again: a command named a buffer - /// over host pages, or its pass is over a rasterization-rate map. + /// over host pages, its pass is over a rasterization-rate map, or a command raced a rebind. pub(super) fn encodes_again(&self) -> bool { - self.names_a_pin() || self.rate_map.is_some() + self.names_a_pin() || self.rate_map.is_some() || self.raced } /// The identity of the rasterization-rate map its pass is over (`Rebinds::reset_map`). @@ -1035,9 +1281,20 @@ impl Buffer { /// `memory` meets the contract of the [`HostMemory`] constructor that made it /// ([`HostMemory::new`], [`HostMemory::with_dma_buf`]) for the buffer's length. The old memory /// stays mapped until its keep-alive is dropped, else until its deallocator runs, or with - /// neither until every command buffer first submitted before the call completed. No command - /// that uses the buffer is encoded, and no command buffer that uses it committed, on another - /// thread during the call. + /// neither until every command buffer first submitted before the call completed. No other + /// thread rebinds or detaches the buffer, or makes a texture over its bytes, during the call. + /// + /// Other threads may encode and commit command buffers that use the buffer during the call. + /// An encoder whose call raced it (held the buffer while the call was making what lies over + /// its bytes again, or after, having begun before) is encoded again over the new memory before + /// its first submission, where the runtime can encode it again (the module docs of `rebind.rs`, + /// **Other threads**, counted by `WorkCounts::encoders_raced_rebind`); one it cannot fails + /// `CommandBufferError::EncodedUseRebound` at that submission: a compute encoder its unit of + /// command predication reaches past, one that left a GPU-written indirect dispatch to its host + /// step, a blit or render encoder opened while the device had no buffer over host pages, an + /// encoder whose command buffer's commit fails it, and one with a call that answers otherwise + /// than at its encoding. A call with no concurrent encode of the buffer changes nothing for + /// them. pub unsafe fn rebind_bytes_no_copy( &self, memory: HostMemory, @@ -1099,7 +1356,12 @@ impl Heap { /// # Safety /// /// As [`Buffer::rebind_bytes_no_copy`]'s, for the heap's [`size`](Heap::size) and the uses - /// of the heap and its resources. + /// of the heap and its resources: no other thread rebinds the heap, detaches one of its + /// resources' bytes, or places a resource in it, during the call. Other threads may encode and + /// commit command buffers that use the heap or its resources during the call, with the outcomes + /// [`Buffer::rebind_bytes_no_copy`]'s **Safety** names, `EncodedUseRebound` for an encoder the + /// runtime cannot encode again whose call raced it, and none of them where no encode overlaps + /// the call. pub unsafe fn rebind_bytes_no_copy( &self, memory: HostMemory, diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 800b896ef..e6a551ea2 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -2233,7 +2233,8 @@ impl Lowering { /// The lowering of [`RenderCommandEncoder::end_encoding`] (`RenderLowering::end_encoding`), /// its kept draw carried into its command buffer's next render encoder where it carries /// (`render/carried.rs`). - pub(crate) fn end_encoding(self) -> Result<(), Error> { + pub(crate) fn end_encoding(mut self) -> Result<(), Error> { + self.core.begin_call(); let _for = self.core.notices_for(); self.ending_carried().end_encoding() } @@ -2295,6 +2296,9 @@ impl CommandBuffer { ) -> Result { const CALL: &str = "render_command_encoder"; let device = self.device(); + // The call begins before it reads the pass's attachments, some of which may lie over host + // pages, which its core holds once made (`rebind.rs`, **Other threads**). + let begun = device.shared().rebinds.call_begins(); let screen = screen.or_else(|| { (given.rasterization_rate_map.as_ref()).map(|map| map.state().screen_size()) }); @@ -2377,6 +2381,7 @@ impl CommandBuffer { Some(_) => EncoderCore::replaying(self, false)?, } .boxed(); + core.begun_at(begun); // A color's texture with faces that the pass renders whole without loading it turns to // its other face here, before anything of the pass names its image; the kept draw the // last render encoder carried bound the face presented before (`render/face_swap.rs`). diff --git a/crates/metal2vulkan-runtime/src/render/deferral.rs b/crates/metal2vulkan-runtime/src/render/deferral.rs index e61209b2c..81f6d6fb8 100644 --- a/crates/metal2vulkan-runtime/src/render/deferral.rs +++ b/crates/metal2vulkan-runtime/src/render/deferral.rs @@ -793,6 +793,7 @@ impl RenderCommandEncoder { pub(crate) fn at_call_unit(&mut self, f: impl FnOnce(&mut Lowering)) { self.next += 1; let lowered = |lowering: &mut Lowering| { + lowering.core.begin_call(); let _for = lowering.core.notices_for(); f(lowering); }; diff --git a/crates/metal2vulkan-runtime/src/render/replay.rs b/crates/metal2vulkan-runtime/src/render/replay.rs index 37df8a5b5..8d7c5239f 100644 --- a/crates/metal2vulkan-runtime/src/render/replay.rs +++ b/crates/metal2vulkan-runtime/src/render/replay.rs @@ -731,6 +731,7 @@ impl Lowering { &mut self, run: impl FnOnce(&mut Lowering) -> Result, ) -> Result { + self.core.begin_call(); let _for = self.core.notices_for(); let at = self.log.as_ref().map(|log| log.calls.calls.len()); let ran = run(self); @@ -773,6 +774,9 @@ pub(super) fn render( ) -> Result<(), Error> { use RenderCall as C; use Table as T; + // Each call begins before it reads anything of a buffer over host pages (`rebind.rs`, **Other + // threads**). + encoder.core.begin_call(); match call { C::PipelineState(state) => encoder.set_render_pipeline_state(log.render_state(*state)), C::Buffer(table, buffer, offset, index) => { diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 7c3b31b98..20625bdb3 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -681,6 +681,8 @@ mod rebind_loop_check; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod rebind_making_wait; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod rebind_races; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod rebind_sparse_scrub; mod recent_shape_keys; #[cfg(all(m2v_gpu, target_os = "linux"))] diff --git a/crates/metal2vulkan-runtime/src/tests/rebind_races.rs b/crates/metal2vulkan-runtime/src/tests/rebind_races.rs new file mode 100644 index 000000000..04fbb8a85 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/rebind_races.rs @@ -0,0 +1,605 @@ +//! Rebinds of a no-copy buffer racing encoders on other threads (`rebind.rs`, **Other threads**). +//! +//! - **A read before the hold.** A dispatch reads the bound buffer's pages (its bind state) +//! before its encoder holds the buffer. Held at the hold (`rebind::pause`, `Point::Holding`) +//! while another thread rebinds the buffer whole, the hold then finds the new pages, where the +//! dispatch's commands named the old ones. The call raced the rebind +//! (`WorkCounts::encoders_raced_rebind`): the commit encodes the encoder again, and the dispatch +//! reads the new pages. A second buffer over the old pages keeps their import, so a tree without +//! the check reads the old pages' values, not a freed `VkBuffer`, and fails the assertion. +//! - **A read during the publish.** A rebind held after the buffer took its new pages, before +//! the texture over its bytes has its image made over them (`Point::Publishing`), while a +//! dispatch on another thread reads the texture: the dispatch's hold finds the publish open, +//! and the commit, after the publish closed, encodes the encoder again over the new image. +//! - **Threads.** Four threads encode and commit command buffers whose commands read the buffer, +//! one family each: a dispatch reading a texture over it, a draw reading it as a vertex buffer, +//! a blit copying from it, and a dispatch it was bound to a call before (the dispatch's bind +//! state reuses nothing a move changed, `buffer::host_cells_moved`). A fifth thread rebinds it +//! to fresh pages meanwhile, as often as it is let. Every page holds one value in every word, so +//! each command buffer's output is wholly one page's, of a page the buffer lay in between the +//! start of the encoding and the completion, or the command buffer failed `EncodedUseRebound`. +//! It prints the rebinds made and refused, the encoders that raced and the failures. +//! +//! Device tests: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`). The functions +//! are `scale_and_offset`, `invert_texels` and `colored_vertex` of the owned fixture +//! `validation/fixtures/public/examples/runtime_examples.ll`. + +use super::blit_holds::{device, Scratch, WAIT}; +use super::dispatch_pending::state as scale_state; +use super::encoder_holds::{bits, bytes_of, library, pass, render_state, words_of}; +use crate::error::{invalid, Problem}; +use crate::rebind::pause::{self, Point}; +use crate::{ + BlitOption, Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, + ComputePipelineState, Device, Error, HostMemory, Origin, PipelineOptions, RebindProblem, + Region, RenderPipelineState, ResourceOptions, Size, Texture, TextureDescriptor, +}; +use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; +use std::alloc::Layout; +use std::ptr::NonNull; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +/// The buffer's bytes: whole pages of any host. +const BYTES: usize = 64 << 10; + +/// The texture over the buffer's bytes: `RGBA8Unorm`, `SIDE` texels square, rows tight. +const SIDE: u64 = 64; + +/// The threads of `scale_and_offset`, one threadgroup, and the scale it multiplies by. +const COUNT: u64 = 64; +const SCALE: f32 = 2.0; + +/// The side of a draw's target, and the bytes a blit copies. +const TARGET: u64 = 16; +const COPIED: u64 = 4096; + +/// The command buffers each encoding thread commits, and the pages the rebinding thread takes +/// (fewer than 255, so each page's value has its own `RGBA8Unorm` code). +const ROUNDS: usize = 25; +const PAGES: usize = 64; + +/// The value page `tag` holds in every word: `(tag + 1) / 255`, whose `RGBA8Unorm` code is +/// `tag + 1`. +fn value(tag: usize) -> f32 { + (tag + 1) as f32 / 255.0 +} + +/// Host memory of [`BYTES`], every word [`value`]`(tag)`'s bits, freed when dropped. +struct Page(NonNull); + +// SAFETY: its bytes are written in `new` alone, before any other thread is handed it; only the +// GPU reads them after. +unsafe impl Send for Page {} +// SAFETY: as above. +unsafe impl Sync for Page {} + +impl Page { + fn layout() -> Layout { + Layout::from_size_align(BYTES, BYTES).unwrap() + } + + fn new(tag: usize) -> Page { + // SAFETY: the layout's size is not zero. + let pointer = NonNull::new(unsafe { std::alloc::alloc(Page::layout()) }).unwrap(); + // SAFETY: `BYTES` bytes, allocated just now aligned past a word. + let words = unsafe { std::slice::from_raw_parts_mut(pointer.as_ptr().cast(), BYTES / 4) }; + words.fill(value(tag).to_bits()); + Page(pointer) + } + + /// Its memory, for a no-copy buffer or a rebind. + /// + /// # Safety + /// + /// It outlives every buffer over it, and nothing writes it. + unsafe fn memory(&self) -> HostMemory { + // SAFETY: the caller's contract; `BYTES` bytes, allocated in `new` page-aligned. + unsafe { HostMemory::new(self.0) } + } +} + +impl Drop for Page { + fn drop(&mut self) { + // SAFETY: allocated with this layout in `Page::new`. + unsafe { std::alloc::dealloc(self.0.as_ptr(), Page::layout()) }; + } +} + +/// A no-copy buffer over `page`; `None`, printed, where the device imports no host memory. +fn over(device: &Device, page: &Page) -> Option { + // SAFETY: each page outlives the device (dropped after it), and nothing writes it. + let made = unsafe { + device.new_buffer_with_bytes_no_copy( + page.memory(), + BYTES as u64, + ResourceOptions::shared(), + None, + ) + }; + match made { + Ok(buffer) => Some(buffer), + Err(Error::Unsupported(gap)) => { + eprintln!("REBIND-RACES: the device imports no host memory: {gap:?}"); + None + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + } +} + +/// Rebind `buffer` to `page`. +fn rebind(buffer: &Buffer, page: &Page) -> Result<(), Error> { + // SAFETY: as in `over`; no other thread rebinds or detaches the buffer, or makes a texture + // over it, during the call. + unsafe { buffer.rebind_bytes_no_copy(page.memory(), None, None) } +} + +/// What a command buffer's commands do with the buffer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Family { + /// `invert_texels` reads the texture over its bytes. + TextureRead, + /// `colored_vertex` reads its colors from it, bound at vertex buffer 1. + VertexBuffer, + /// A blit copies from it. + BlitCopy, + /// `scale_and_offset` reads it, bound a call before the dispatch. + BoundBefore, +} + +const FAMILIES: [Family; 4] = [ + Family::TextureRead, + Family::VertexBuffer, + Family::BlitCopy, + Family::BoundBefore, +]; + +/// The states, and the objects of the device's own, the families' commands use. +struct Fixtures { + scale: ComputePipelineState, + invert: ComputePipelineState, + draw: RenderPipelineState, + scale_bytes: Buffer, + positions: Buffer, +} + +impl Fixtures { + fn new(device: &Device) -> Fixtures { + let invert = library(device, "examples/runtime_examples.ll") + .new_function_with_name("invert_texels") + .unwrap(); + // A triangle over the whole target. + let triangle = bits(&[-1.0, -1.0, 3.0, -1.0, -1.0, 3.0]); + Fixtures { + scale: scale_state(device), + invert: device + .new_compute_pipeline_state_with_function(&invert, &PipelineOptions::default()) + .unwrap(), + draw: render_state( + device, + "examples/runtime_examples.ll", + "colored_vertex", + "colored_fragment", + ), + scale_bytes: device + .new_buffer_with_bytes(&SCALE.to_le_bytes(), ResourceOptions::shared()) + .unwrap(), + positions: device + .new_buffer_with_bytes( + &bytes_of(&triangle, u32::to_le_bytes), + ResourceOptions::shared(), + ) + .unwrap(), + } + } +} + +/// The texture over `buffer`'s first bytes that `invert_texels` reads. +fn texture_over(buffer: &Buffer) -> Texture { + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::shared(); + buffer.new_texture(&descriptor, 0, SIDE * 4).unwrap() +} + +/// Where a family's command buffer leaves its output. +enum Output { + Texture(Texture), + Buffer(Buffer), +} + +impl Output { + /// Its words, once its command buffer completed. + fn words(&self) -> Vec { + match self { + Output::Buffer(buffer) => words_of(buffer), + Output::Texture(texture) => { + let mut bytes = vec![0; (SIDE * SIDE * 4) as usize]; + let region = Region::new_2d(0, 0, SIDE, SIDE); + texture + .get_bytes(&mut bytes, SIDE * 4, 0, region, 0, 0) + .unwrap(); + let (words, _) = bytes.as_chunks::<4>(); + words.iter().map(|word| u32::from_le_bytes(*word)).collect() + } + } + } +} + +/// The output `family`'s commands leave over a buffer whose bytes are page `tag`'s. +fn expected(family: Family, tag: usize) -> Vec { + let word = value(tag).to_bits(); + match family { + Family::TextureRead => { + let [r, g, b, a] = word.to_le_bytes(); + let inverted = u32::from_le_bytes([255 - r, 255 - g, 255 - b, a]); + vec![inverted; (SIDE * SIDE) as usize] + } + Family::VertexBuffer => { + let code = (tag + 1) as u8; + vec![u32::from_le_bytes([code; 4]); (TARGET * TARGET) as usize] + } + Family::BlitCopy => vec![word; (COPIED / 4) as usize], + Family::BoundBefore => (0..COUNT) + .map(|i| (value(tag) * SCALE + i as f32).to_bits()) + .collect(), + } +} + +/// Encode `family`'s commands over `buffer` (and `over`, the texture over its bytes) into +/// `command_buffer`, not committed. +fn encode( + family: Family, + device: &Device, + fixtures: &Fixtures, + command_buffer: &CommandBuffer, + (buffer, over): (&Buffer, &Texture), +) -> Output { + match family { + Family::TextureRead => { + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + descriptor.usage = TextureUsage::SHADER_WRITE; + descriptor.resource_options = ResourceOptions::shared(); + let out = device.new_texture(&descriptor).unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder + .set_compute_pipeline_state(&fixtures.invert) + .unwrap(); + encoder.set_texture(Some(over), 0).unwrap(); + encoder.set_texture(Some(&out), 1).unwrap(); + encoder + .dispatch_threads(Size::new(SIDE, SIDE, 1), Size::new(8, 8, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + Output::Texture(out) + } + Family::VertexBuffer => { + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, TARGET, TARGET, false); + descriptor.usage = TextureUsage::RENDER_TARGET; + descriptor.resource_options = ResourceOptions::private(); + let target = device.new_texture(&descriptor).unwrap(); + let back = device + .new_buffer(TARGET * TARGET * 4, ResourceOptions::shared()) + .unwrap(); + let mut encoder = command_buffer + .render_command_encoder(&pass(&target)) + .unwrap(); + encoder.set_render_pipeline_state(&fixtures.draw).unwrap(); + encoder + .set_vertex_buffer(Some(&fixtures.positions), 0, 0) + .unwrap(); + encoder.set_vertex_buffer(Some(buffer), 0, 1).unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_texture_to_buffer( + &target, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(TARGET, TARGET, 1), + &back, + 0, + TARGET * 4, + TARGET * TARGET * 4, + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + Output::Buffer(back) + } + Family::BlitCopy => { + let out = device + .new_buffer(COPIED, ResourceOptions::shared()) + .unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_buffer_to_buffer(buffer, 0, &out, 0, COPIED) + .unwrap(); + blit.end_encoding().unwrap(); + Output::Buffer(out) + } + Family::BoundBefore => { + let out = device + .new_buffer(COUNT * 4, ResourceOptions::shared()) + .unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + // Bound in its own call, before the state and the dispatch. + encoder.set_buffer(Some(buffer), 0, 0).unwrap(); + encoder.set_compute_pipeline_state(&fixtures.scale).unwrap(); + encoder.set_buffer(Some(&out), 0, 1).unwrap(); + encoder + .set_buffer(Some(&fixtures.scale_bytes), 0, 2) + .unwrap(); + encoder + .dispatch_threads(Size::new(COUNT, 1, 1), Size::new(COUNT, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + Output::Buffer(out) + } + } +} + +/// The encoders that raced a rebind, over the device's life. +fn raced(device: &Device) -> u64 { + device.work_counts().encoders_raced_rebind +} + +/// A dispatch held at its hold of the buffer, after it read the buffer's pages, while the main +/// thread rebinds the buffer: it raced the rebind, and its commit encodes it again over the new +/// pages. +#[test] +fn a_dispatch_that_read_the_buffer_before_its_hold_runs_over_the_new_pages() { + let scratch = Scratch::new("rebind-races-hold"); + let device = device(&scratch.0); + let fixtures = Fixtures::new(&device); + let pages = [Page::new(0), Page::new(1)]; + let Some(buffer) = over(&device, &pages[0]) else { + return; + }; + // Over the same bytes: it lies in the buffer's import, which it keeps after the rebind. + let keeper = over(&device, &pages[0]).unwrap(); + let over_texture = texture_over(&buffer); + let queue = device.new_command_queue().unwrap(); + let before = raced(&device); + let (reached, go) = pause::arm(Point::Holding, buffer.identity().key); + let (output, command_buffer) = std::thread::scope(|scope| { + let encoding = scope.spawn(|| { + let command_buffer = queue.command_buffer().unwrap(); + let family = Family::BoundBefore; + let output = encode( + family, + &device, + &fixtures, + &command_buffer, + (&buffer, &over_texture), + ); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + (output, command_buffer) + }); + reached + .recv_timeout(WAIT) + .expect("the dispatch reached its hold"); + rebind(&buffer, &pages[1]).expect("the rebind before the hold"); + go.send(()).unwrap(); + encoding.join().unwrap() + }); + let raced = raced(&device) - before; + println!( + "REBIND-RACES hold: {:?} {:?}, raced {raced}", + command_buffer.status(), + command_buffer.error() + ); + assert_eq!( + (command_buffer.status(), command_buffer.error()), + (CommandBufferStatus::Completed, None) + ); + let words = output.words(); + assert_ne!( + words, + expected(Family::BoundBefore, 0), + "the dispatch read the pages the buffer left before its submission" + ); + assert_eq!( + words, + expected(Family::BoundBefore, 1), + "the dispatch read the pages the buffer lies in" + ); + assert_eq!(raced, 1, "the encoder that raced the rebind"); + drop(keeper); +} + +/// A dispatch reading the texture over the buffer while a rebind of it is held in its publish, +/// the texture's image still the old pages': its hold finds the publish open, and its commit, +/// after the publish closed, encodes it again over the new image. +#[test] +fn a_dispatch_that_read_a_texture_over_the_buffer_during_its_publish_runs_over_the_new_pages() { + let scratch = Scratch::new("rebind-races-publish"); + let device = device(&scratch.0); + let fixtures = Fixtures::new(&device); + let pages = [Page::new(0), Page::new(1)]; + let Some(buffer) = over(&device, &pages[0]) else { + return; + }; + let over_texture = texture_over(&buffer); + let queue = device.new_command_queue().unwrap(); + let before = raced(&device); + let (reached, go) = pause::arm(Point::Publishing, buffer.identity().key); + let command_buffer = queue.command_buffer().unwrap(); + let output = std::thread::scope(|scope| { + let rebinding = scope.spawn(|| rebind(&buffer, &pages[1])); + reached + .recv_timeout(WAIT) + .expect("the rebind reached its publish"); + let output = encode( + Family::TextureRead, + &device, + &fixtures, + &command_buffer, + (&buffer, &over_texture), + ); + go.send(()).unwrap(); + rebinding.join().unwrap().expect("the rebind"); + output + }); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + let raced = raced(&device) - before; + println!( + "REBIND-RACES publish: {:?} {:?}, raced {raced}", + command_buffer.status(), + command_buffer.error() + ); + assert_eq!( + (command_buffer.status(), command_buffer.error()), + (CommandBufferStatus::Completed, None) + ); + assert_eq!( + output.words(), + expected(Family::TextureRead, 1), + "the dispatch read the texture over the pages the buffer lies in" + ); + assert_eq!(raced, 1, "the encoder that raced the rebind"); +} + +/// What one command buffer of the threaded run came to. +#[derive(Debug)] +enum Seen { + /// Its output is wholly page `tag`'s. + Page(usize), + /// It failed `EncodedUseRebound`. + Rebound, + /// Anything else: a wrong answer. + Wrong(String), +} + +/// Four threads encoding and committing command buffers that read the buffer, a family each, +/// while a fifth rebinds it to fresh pages: every output is wholly one page's, of a page the +/// buffer lay in meanwhile, or its command buffer failed `EncodedUseRebound`. +#[test] +fn encoders_on_other_threads_read_wholly_one_page_of_a_buffer_rebound_meanwhile() { + let scratch = Scratch::new("rebind-races-threads"); + let device = device(&scratch.0); + let fixtures = Fixtures::new(&device); + let pages: Vec = (0..PAGES).map(Page::new).collect(); + let Some(buffer) = over(&device, &pages[0]) else { + return; + }; + let over_texture = texture_over(&buffer); + // One queue for every thread: a test's device takes two `VkQueue`s at most. + let queue = device.new_command_queue().unwrap(); + let before = device.work_counts(); + // The page the buffer lies in, stored after each rebind returns. + let current = AtomicUsize::new(0); + let seen: Mutex> = Mutex::new(Vec::new()); + let encoded_uses = invalid( + "rebind_bytes_no_copy", + Problem::Rebind(RebindProblem::EncodedUses), + ); + let (made, refused) = std::thread::scope(|scope| { + for family in FAMILIES { + let (device, fixtures, buffer, over_texture) = + (&device, &fixtures, &buffer, &over_texture); + let (current, seen, queue) = (¤t, &seen, &queue); + scope.spawn(move || { + for _ in 0..ROUNDS { + let low = current.load(Ordering::Acquire); + let command_buffer = queue.command_buffer().unwrap(); + let output = encode( + family, + device, + fixtures, + &command_buffer, + (buffer, over_texture), + ); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + // A rebind's replace comes before its call returns and the page is stored. + let high = current.load(Ordering::Acquire) + 1; + let outcome = match (command_buffer.status(), command_buffer.error()) { + (CommandBufferStatus::Completed, None) => { + let words = output.words(); + match (low..=high.min(PAGES - 1)) + .find(|&tag| words == expected(family, tag)) + { + Some(tag) => Seen::Page(tag), + None => Seen::Wrong(format!( + "no page {low}..={high}'s output: first words {:x?}", + &words[..4] + )), + } + } + ( + CommandBufferStatus::Error, + Some(CommandBufferError::EncodedUseRebound), + ) => Seen::Rebound, + other => Seen::Wrong(format!("{other:?}")), + }; + seen.lock().unwrap().push((family, outcome)); + } + }); + } + let rebinding = scope.spawn(|| { + let (mut made, mut refused) = (0, 0); + let mut next = 1; + while next < PAGES && seen.lock().unwrap().len() < FAMILIES.len() * ROUNDS { + match rebind(&buffer, &pages[next]) { + Ok(()) => { + current.store(next, Ordering::Release); + made += 1; + next += 1; + } + Err(error) if error == encoded_uses => refused += 1, + Err(error) => panic!("the rebind: {error:?}"), + } + std::thread::yield_now(); + } + (made, refused) + }); + rebinding.join().unwrap() + }); + let after = device.work_counts(); + let seen = seen.into_inner().unwrap(); + let count = |family: Family, which: fn(&Seen) -> bool| { + (seen.iter()) + .filter(|(of, outcome)| *of == family && which(outcome)) + .count() + }; + for family in FAMILIES { + let pages: std::collections::BTreeSet = (seen.iter()) + .filter_map(|(of, outcome)| match outcome { + Seen::Page(tag) if *of == family => Some(*tag), + _ => None, + }) + .collect(); + println!( + "REBIND-RACES threads {family:?}: {} wholly one page ({} pages apart), {} \ + EncodedUseRebound, {} wrong", + count(family, |seen| matches!(seen, Seen::Page(_))), + pages.len(), + count(family, |seen| matches!(seen, Seen::Rebound)), + count(family, |seen| matches!(seen, Seen::Wrong(_))), + ); + } + let grew = |of: fn(&crate::WorkCounts) -> u64| of(&after) - of(&before); + println!( + "REBIND-RACES threads: {made} rebinds made, {refused} refused (EncodedUses); {} encoders \ + raced a rebind, {} encoded again, {} refused encoding again", + grew(|counts| counts.encoders_raced_rebind), + grew(|counts| counts.encoders_reencoded), + grew(|counts| counts.reencodes_refused), + ); + let wrong: Vec<(Family, &str)> = (seen.iter()) + .filter_map(|(family, outcome)| match outcome { + Seen::Wrong(why) => Some((*family, why.as_str())), + _ => None, + }) + .collect(); + assert_eq!(seen.len(), FAMILIES.len() * ROUNDS); + assert!(wrong.is_empty(), "wrong outputs: {wrong:?}"); + assert!(made > 0, "no rebind was made"); +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index b3b513fd8..d541688b4 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -786,6 +786,7 @@ pub(crate) struct Counters { segments_recorded_again: AtomicU64, replay_tables_pointed: AtomicU64, reencodes_refused: AtomicU64, + encoders_raced_rebind: AtomicU64, pipeline_libraries_made: AtomicU64, fragment_shader_libraries_made: AtomicU64, pipelines_linked: AtomicU64, @@ -6150,6 +6151,12 @@ impl Counters { self.reencodes_refused.fetch_add(1, Ordering::Relaxed); } + /// An encoder's call raced a rebind of a buffer over host pages it held or pinned + /// (`rebind.rs`, **Other threads**): its commands run only encoded again. + pub(crate) fn encoder_raced_rebind(&self) { + self.encoders_raced_rebind.fetch_add(1, Ordering::Relaxed); + } + /// A new image was moved to `GENERAL` and zeroed on the host (`texture/host_copy.rs`). pub(crate) fn image_started_on_the_host(&self) { self.images_started_on_the_host @@ -11816,6 +11823,13 @@ pub struct WorkCounts { /// recording unlike the first), and work recorded on the GPU alone it could not record there /// again, which keep their first recording and fail `EncodedUseRebound`. pub reencodes_refused: u64, + /// Encoders a call of which, on another thread than a rebind of a buffer over host pages + /// (`rebind_bytes_no_copy`), held or took the buffer while the rebind was making what lies + /// over its bytes again, or after, having begun before (`rebind.rs`, **Other threads**): what + /// the call read of the buffer may be the old pages', so the commit, or a rebind's turn, + /// encodes the encoder again over the new pages, and one that cannot be encoded again fails + /// `EncodedUseRebound`. Zero where no encoder races a rebind. + pub encoders_raced_rebind: u64, /// Fences made to end command buffers, where none was idle (`command_buffer/fences.rs`): /// none on a driver that reads no command buffer's objects after its value, whose queues' /// failures are not relayed. @@ -13636,6 +13650,7 @@ impl Device { segments_recorded_again: counters.segments_recorded_again.load(Ordering::Relaxed), replay_tables_pointed: counters.replay_tables_pointed.load(Ordering::Relaxed), reencodes_refused: counters.reencodes_refused.load(Ordering::Relaxed), + encoders_raced_rebind: counters.encoders_raced_rebind.load(Ordering::Relaxed), fences_made: self.shared().fences.made(), pipeline_libraries_made: counters.pipeline_libraries_made.load(Ordering::Relaxed), fragment_shader_libraries_made: counters diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 5da60c7ed..7d657f3d9 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 524; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2464; +pub const RUNTIME_VERSION: u32 = 2465; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 19f6a2d0e..f889e6a34 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3068,6 +3068,7 @@ field metal2vulkan-runtime::WorkCounts.encoders_none_kept_next_last pub encoders field metal2vulkan-runtime::WorkCounts.encoders_none_kept_next_layout pub encoders_none_kept_next_layout: u64 field metal2vulkan-runtime::WorkCounts.encoders_none_kept_next_split pub encoders_none_kept_next_split: u64 field metal2vulkan-runtime::WorkCounts.encoders_none_kept_next_under pub encoders_none_kept_next_under: u64 +field metal2vulkan-runtime::WorkCounts.encoders_raced_rebind pub encoders_raced_rebind: u64 field metal2vulkan-runtime::WorkCounts.encoders_reencoded pub encoders_reencoded: u64 field metal2vulkan-runtime::WorkCounts.encoders_uncarried_commands pub encoders_uncarried_commands: u64 field metal2vulkan-runtime::WorkCounts.encoders_uncarried_drawless pub encoders_uncarried_drawless: u64 diff --git a/docs/API.md b/docs/API.md index 21d195bfa..7316153ca 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3622,12 +3622,15 @@ bound. command named a buffer over the caller's host pages (a binding, a blit's operand, an attachment, a texture over the pages, an indirect command's resolved buffer) that was rebound (`rebind_bytes_no_copy`) after the command was encoded and before the command buffer was first - submitted, in an encoder the rebind could not encode again. Cost: each of Metal's submissions of - the command buffer holding such a command runs nothing and the command buffer fails - (EncodedUseRebound), where Metal resolves the use as it submits the command buffer and reaches the - pages the buffer lies in then; the rebind encodes compute, blit and render encoders again, but not - this one. The reason names where the first such submission found the use (the encoder; its own - commands or work it left for later) and why no rebind encoded or recorded it again. + submitted, or whose encoding a rebind on another thread raced (the call held the buffer while the + rebind was making what lies over its bytes again, or after, having begun before; counted by + `WorkCounts::encoders_raced_rebind`), in an encoder the runtime could not encode again. Cost: each + of Metal's submissions of the command buffer holding such a command runs nothing and the command + buffer fails (EncodedUseRebound), where Metal resolves the use as it submits the command buffer + and reaches the pages the buffer lies in then; the rebind encodes compute, blit and render + encoders again, but not this one. The reason names where the first such submission found the use + (the encoder; its own commands or work it left for later) and why no rebind encoded or recorded it + again. - `metal2vulkan-degrade-stale-detached-reach` (precision). `StaleDetachedReach`: A command buffer that bound a heap set, whose commands may reach any texture through its resource ID without naming it, was submitted while a texture's bytes (a no-copy buffer's or heap's, the texture over them or