Stop a rebind's re-encoded tile dispatch making or waiting for its pipeline

The steps this packet landed as, in order:
- Let a rebind of a pending tile pass's buffer run, and place the pass it leaves
- Say in the rebind rule that a pipeline being made does not hold a rebind off
- Re-pin the runtime sources at the landing tip

Content: the tree of `development` at 7da33c898d, unchanged.
This commit is contained in:
Anees Iqbal committed 2026-10-26 13:19:21 +02:00
1 parent fdf3f414b6
commit a730cf1e96
16 files changed
+731 -62

No files matched your search

@@ -2641,12 +2641,16 @@ impl CommandBuffer {
// A host step may record commands after the commit (a segment not recorded for good).
let stepped = prepared.iter().any(|prepared| !prepared.for_good);
// Until the command buffer completes, the buffers its host steps' commands use keep their
// pages, where a step resolves what it records as it records it. A dispatch whose
// pipelines were being made records what its encoding resolved (`pending_dispatch.rs`),
// and an encoder encoded again at a rebind records it at once (`replay.rs`): it holds
// nothing past the commit.
// pages, where a step resolves what it records as it records it, and a rebind of one is
// refused meanwhile (`RebindProblem::EncodedUses`). Work whose step records only what its
// calls resolved holds nothing past the commit (`Deferred::resolved_at_its_calls`): a
// dispatch whose pipelines were being made (`pending_dispatch.rs`), and a render pass left
// for the pipelines its draws and tile dispatches record
// (`render/pending_tile.rs`). Metal's replace fails for neither, and a rebind encodes
// their encoder again instead (`command_buffer/reencode.rs`); where it cannot, their
// recording records nothing of the encoder (`DeferredPass::record_forms`).
let steps_hold = (segments.iter().zip(&prepared)).any(|((work, _), prepared)| {
!prepared.for_good && !matches!(work, Deferred::Pending(_))
!prepared.for_good && !work.resolved_at_its_calls(prepared.pipelines)
});
// The segments a host step records once the pipelines they record are made.
let made_later: Vec<Deferred> = segments
@@ -2775,11 +2779,21 @@ impl CommandBuffer {
waits: batch.waits.clone(),
binary_waits: batch.binary_waits.clone(),
binary_signals: batch.binary_signals.clone(),
// A batch holds segments, or may come to: a rebind before its submission
// encodes an encoder of it again from its log, and the encoding again leaves
// a segment of its own where a pipeline it records is being made, though the
// first encoding left none (`command_buffer/reencode.rs`,
// `render/pending_tile.rs`). The scheduler reads this as a gate alone and
// asks the command buffer itself whether a step is due
// ([`needs_host_step`](Self::needs_host_step)), so a batch that gains none
// waits for nothing.
segments: state.recorded[state.batch_range(index)]
.iter()
.any(|encoder| {
!encoder.segments.is_empty()
|| encoder.sparse.iter().any(SparseUpdate::needs_step)
|| (state.ended.get(encoder.encoder))
.is_some_and(|record| record.replay.is_some())
}),
checked: state.checks.is_some(),
})
@@ -19,8 +19,9 @@
//! 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
//! waited for, and no pipeline's making: a dispatch whose pipelines are being made leaves a
//! segment of its own, as the first encoding left one (`pending_dispatch.rs`), which the
//! submission or the host step records once they are made, so no Metal compile runs or is
//! segment of its own, as the first encoding left one (`pending_dispatch.rs`), and so does a
//! render pass of a draw's or a tile dispatch's being made (`render/pending_tile.rs`), which
//! the submission or the host step records once they are made, so no Metal compile runs or is
//! waited for on the program's thread inside the rebind's call.
//! Rebinds on two threads take turns (`reencoding`); a rebind during another's
//! turn marks the command buffer again, and its own turn encodes what moved since. A host step
@@ -203,7 +204,7 @@ impl CommandBufferShared {
}
}
}
// Each making a spliced dispatch's segment now waits for wakes the scheduler as it
// Each making a spliced segment now waits for wakes the scheduler as it
// finishes, with no lock held, registered before the scheduler looks at the batches again
// (the wake at the end of this turn): a making that finished between that look and a
// later registration would leave the batch held with nothing to wake the scheduler. Its
@@ -311,8 +312,9 @@ impl State {
/// 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 left one of its own in its
/// place) or work its commit recorded on the GPU alone, or its group was submitted, or the
/// but one whose pipelines are being made (which goes, the encoding again having left one of
/// its own in its place) or work its commit recorded on the GPU alone, or its group was
/// submitted, or the
/// command buffer completed. Its replays hold what its commands took with `device`, the
/// device's functions (`Replays::hold`).
pub(super) fn splice_replay(
@@ -329,7 +331,8 @@ impl State {
let replaces = |part: &usize| {
let recorded = &self.recorded[*part];
recorded.sparse.is_empty()
&& (recorded.segments.iter()).all(|segment| segment.pends() || segment.gpu_alone)
&& (recorded.segments.iter())
.all(|segment| segment.keeps_pipelines() || segment.gpu_alone)
};
let unjudged = self.unjudged_parts();
let fits = !self.finished()
@@ -443,6 +443,41 @@ impl Deferred {
}
}
/// Whether a host step records it from what its calls resolved alone, nothing of the buffers
/// it names read again then: the buffers over host pages its commands used let their pages go
/// at the commit instead of keeping them until it completes (`CommandBuffer::commit`'s
/// `steps_hold`, `rebind.rs`), so a rebind of one is not refused but encodes its encoder
/// again (`command_buffer/reencode.rs`). A dispatch whose pipelines were being made records
/// what its encoding resolved (`pending_dispatch.rs`), and so does a render pass `commit`
/// left for the pipelines its draws and tile dispatches record (`pipelines`) that executes no
/// render commands, whose instances' commands its calls recorded
/// (`render/pending_tile.rs`). Everything else its step resolves as it records: a rebind
/// meanwhile is refused.
pub(super) fn resolved_at_its_calls(&self, pipelines: bool) -> bool {
match self {
Deferred::Pending(_) => true,
Deferred::RenderPass(pass) => pipelines && !pass.executes(),
Deferred::Execute(_)
| Deferred::Dispatch(_)
| Deferred::SparseScrub(_)
| Deferred::Loop(_) => false,
}
}
/// Whether the making of a pipeline the work records failed, which its recording makes again,
/// on the thread that records it (`DeferredPass::failed`, `PendingDispatch::failed`): where
/// that fails too the command buffer completes with `CommandBufferError::PipelineCreation`.
pub(super) fn failed(&self) -> bool {
match self {
Deferred::RenderPass(pass) => pass.failed(),
Deferred::Pending(dispatch) => dispatch.failed(),
Deferred::Execute(_)
| Deferred::Dispatch(_)
| Deferred::SparseScrub(_)
| Deferred::Loop(_) => false,
}
}
/// What its recording uses, on `device`, where that is known before it records
/// (`DeferredPass::known_summary`): a render pass's that executes no render commands. `None`
/// for the rest, whose uses their recording finds: an execution's or an indirect dispatch's
+20 -15
View File
@@ -168,6 +168,17 @@ impl Segment {
matches!(self.work, Deferred::Pending(_))
}
/// Whether an encoder encoded again (`replay.rs`) leaves it as a segment of its own, prepared
/// as the commit prepared the first encoding's ([`Deferred::prepare`]), rather than recording
/// it on the GPU alone: a dispatch whose pipelines were being made ([`pends`](Self::pends)),
/// and a render pass of a draw's or a tile dispatch's pipeline still being made, or whose
/// making failed (`render/pending.rs`, `render/pending_tile.rs`), which recording on the GPU
/// alone would wait for, and make itself, on the program's thread
/// (`DeferredPass::record_on_gpu`).
pub(super) fn keeps_pipelines(&self) -> bool {
self.pends() || self.work.making() || self.work.failed()
}
/// Whether an encoder encoded again (`replay.rs`) records its place: a dispatch whose
/// pipelines were being made ([`pends`](Self::pends)), left as a segment again, or work a
/// commit may record on the GPU alone, recorded there again (`Deferred::record_on_gpu`). Its
@@ -1680,14 +1691,6 @@ impl EncoderCore {
}
}
/// Whether it encodes an ended encoder's calls again ([`replaying`](Self::replaying)): its
/// tile dispatches wait for their pipelines, leaving no segment (`render/pending_tile.rs`).
/// Its compute dispatches wait for none, and leave the segment the first encoding left
/// (`pending_dispatch.rs`).
pub(super) fn encodes_again(&self) -> bool {
self.replaying
}
/// The encoder's uses, for its fence waits and updates.
pub(super) fn uses(&mut self) -> &mut EncoderUses<ResourceKey> {
&mut self.uses
@@ -2134,7 +2137,8 @@ impl EncoderCore {
/// End a core made by [`replaying`](Self::replaying): its shadowed textures written since
/// their last copy back are copied back, and what it recorded comes back for its encoder's
/// place (`State::splice_replay`), in its parts, each segment it left recorded at once on the
/// GPU alone. Refused (internal) where the encoder, encoded again, failed or faulted its
/// GPU alone but one whose pipelines are being made or failed to make, left as the first
/// encoding left it ([`Segment::keeps_pipelines`]). Refused (internal) where the encoder, encoded again, failed or faulted its
/// command buffer, or met a detached buffer, which its first encoding kept none of, or left
/// work that no longer runs on the GPU alone: its place stays as it was.
pub(super) fn finish_replay(mut self) -> Result<Replayed, Error> {
@@ -2177,15 +2181,16 @@ impl EncoderCore {
}
// Its segments recorded at once on the GPU alone, as its commit recorded the first
// encoding's (`command_buffer/reencode.rs`): work that no longer runs there refuses the
// encoding again.
// encoding again, but work whose pipelines are being made, which keeps its segment.
let mut parts = Vec::with_capacity(split.len());
for ((raws, mut segments), summary) in split.into_iter().zip(summaries) {
for segment in &mut segments {
// A dispatch whose pipelines are being made is left as the first encoding left
// it, prepared as its commit prepared that one (`Deferred::prepare`): recorded
// here where they are made, else by the host step once they are
// (`pending_dispatch.rs`). The rebind's call waits for no making.
if segment.pends() {
// Work whose pipelines are being made, or whose making failed, is left as the
// first encoding left it, prepared as its commit prepared that one
// (`Deferred::prepare`): recorded here where they are made, else by the host step
// once they are (`pending_dispatch.rs`, `render/pending_tile.rs`). The rebind's
// call waits for no making, and makes none itself.
if segment.keeps_pipelines() {
let prepared = segment.work.prepare(&open.command_buffer, false)?;
segment.recorded = prepared.recorded;
segment.inputs = Some(prepared.inputs);
+5 -1
View File
@@ -32,7 +32,11 @@
//! (`Invalid`, [`RebindProblem::EncodedUses`]): its commands took the old pages, and committing
//! them after the rebind would be neither order. A command buffer committed with commands the
//! runtime records only once earlier work completed (executions of an indirect command buffer
//! the GPU writes) counts as uncommitted until it completed.
//! the GPU writes) counts as uncommitted until it completed. One committed with commands left
//! for a `VkPipeline` still being made does not: a dispatch whose pipelines were being made
//! (`pending_dispatch.rs`) and a render pass left for its draws' and tile dispatches'
//! (`render/pending_tile.rs`) record what their calls resolved, so the rebind encodes their
//! encoder again as it does any other, and Metal's replace fails for neither.
//! - **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
@@ -5536,6 +5536,7 @@ impl RenderLowering {
},
(layout.clone(), bare.clone()),
pass_shadows,
core.command_buffer().state().open_encoder_place(),
));
// The steps' objects, held with the pass until the command buffer completes.
deferred = Some(Arc::clone(&pass));
@@ -2626,6 +2626,10 @@ pub(crate) struct DeferredPass {
/// Its draws whose pipelines were being made as they were encoded, each recorded once made
/// (`render/pending.rs`).
pending: Vec<PendingDraw>,
/// Its encoder's place among the command buffer's ended encoders: whether a rebind since the
/// commit moved a buffer one of its commands named, which its recording must not then record
/// ([`record_forms`](Self::record_forms), as `pending_dispatch.rs` has it).
encoder: usize,
/// The pass's storage where the encoder's draws or tile dispatches made it: its buffer of
/// every tile's threadgroup memory (`render/tile_memory.rs`), its fragment imageblock storage
/// (`fragment_imageblock.rs`) and its shader-side stencil's shadow (`shadow_stencil.rs`);
@@ -2696,7 +2700,8 @@ impl DeferredPass {
/// where the encoder made it, and its `layout` as the encoder ended it with that layout
/// without its hidden depth and stencil (`bare`); `held` the command buffer of its leading
/// instances where the encoder recorded those inline, and their count, and `instances` the
/// later ones (the field's docs).
/// later ones (the field's docs); `encoder` its encoder's place among the command buffer's
/// ended encoders.
pub(super) fn new(
(instances, held): (Vec<PassInstance>, Option<(vk::CommandBuffer, usize)>),
steps: PassSteps,
@@ -2705,6 +2710,7 @@ impl DeferredPass {
storage: PassStorage,
(layout, bare): (PassLayout, Option<PassLayout>),
shadows: Vec<Arc<ShadowCopies>>,
encoder: usize,
) -> DeferredPass {
DeferredPass {
instances,
@@ -2714,6 +2720,7 @@ impl DeferredPass {
uses,
executions,
pending,
encoder,
storage,
layout,
bare,
@@ -2759,6 +2766,12 @@ impl DeferredPass {
|| self.steps.tile_pipelines().any(TilePipelines::failed)
}
/// Whether it executes render commands, whose records its recording reads: everything else it
/// records its calls resolved (`Deferred::resolved_at_its_calls`).
pub(crate) fn executes(&self) -> bool {
!self.executions.is_empty()
}
/// Whether it executes render commands whose records the CPU writes, which its recording
/// reads as they stand at commit (the module docs).
pub(crate) fn reads_at_commit(&self) -> bool {
@@ -2940,6 +2953,19 @@ impl DeferredPass {
step: bool,
forms: &[Option<GpuForm>],
) -> Result<RecordedSegment, Error> {
// A rebind since the commit moved a buffer one of its commands named, and no encoding
// again reached this encoder (`CommandBuffer::encoder_rebound`): its instances'
// secondaries and its pending draws' and tile dispatches' recordings resolved that buffer
// where it lay as they were encoded, so recording them now would bind a `VkBuffer` the
// rebind freed. The Vulkan specification has a descriptor's contents consumed as its
// command is recorded, and the pages stay mapped, so a driver that reads one writes into
// pages the program handed back with nothing said. Its submission then runs nothing and
// the command buffer fails `CommandBufferError::EncodedUseRebound`
// (`first_submission.rs`), as for a dispatch whose pipelines were being made
// (`pending_dispatch.rs`).
if command_buffer.encoder_rebound(self.encoder) {
return Ok(EncoderCore::unrecorded_segment());
}
if step {
// The host step records what a GPU form left to it, for good: a route outgrew the
// decision where one was made.
@@ -23,7 +23,11 @@
//! encoder's tile dispatch calls, the tile state, its variant and specialization, and the
//! driver's error.
//! - **Encoded again** (`replay.rs`): an encoder encoded again waits for its tile dispatches'
//! makings in the rebind's call, as a compute encoder waits for its dispatches'.
//! makings no more than its first encoding did, and leaves its pass to record later in the
//! first encoding's place (`command_buffer/reencode.rs`), prepared as the commit prepared that
//! one: the submission or the host step records it once the makings land, so no Metal compile
//! runs or is waited for on the program's thread inside the rebind's call. Its makings get the
//! scheduler's waker there, as the commit gives the first encoding's.
use super::pass_steps::PassSteps;
use crate::command_buffer::CommandBuffer;
@@ -1134,37 +1134,30 @@ impl RenderLowering {
regions.push((push, region.group_count));
}
// Each region's `VkPipeline`: made, or handed to the device's pool while the dispatch goes
// on, its pass recording once it is made (`render/pending_tile.rs`); an encoder encoded
// again waits for it (`replay.rs`), as a compute encoder does.
// on, its pass recording once it is made (`render/pending_tile.rs`). An encoder encoded
// again (`replay.rs`) waits for no making either, and leaves the same pass to record
// later: the making is its submission's to wait for, as the first encoding left it, never
// the rebind's call on the program's thread, as for a compute dispatch.
let formats: BoundFormats<'_> = &|slot| tables.bound_format(slot);
let creation = self
.core
.records_executions()
.then(|| Arc::new(OnceLock::new()));
let pipelines = match self.core.encodes_again() {
true => {
let mut made = Vec::with_capacity(commands.regions.len());
for region in &commands.regions {
made.push(variant.region_pipeline(region, formats)?);
}
TilePipelines::Made(made)
}
false => {
let call = TileCall {
state: (self.pipeline.clone())
.ok_or_else(|| internal("a tile dispatch without its pipeline state"))?,
encoder: self.core.command_buffer().state().open_encoder_place(),
dispatch: self.tile_dispatch_calls,
};
let regions = &commands.regions;
TilePipelines::begin(
(&kernel, &variant),
regions,
formats,
call,
creation.clone(),
)
}
let pipelines = {
let call = TileCall {
state: (self.pipeline.clone())
.ok_or_else(|| internal("a tile dispatch without its pipeline state"))?,
encoder: self.core.command_buffer().state().open_encoder_place(),
dispatch: self.tile_dispatch_calls,
};
let regions = &commands.regions;
TilePipelines::begin(
(&kernel, &variant),
regions,
formats,
call,
creation.clone(),
)
};
let objects = Arc::clone(variant.objects());
// Set 0 per dispatch; set 1 the device's (written below, once nothing refuses).
@@ -261,6 +261,8 @@ mod texture_facts;
mod texture_resource_options;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod tile_pending;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod tile_rebind_making_wait;
mod tracker;
mod trails;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
@@ -48,7 +48,7 @@ const SCALE: f32 = 2.0;
/// The device the cfg selects, its shader cache in `cache`, asking for the validation layer and
/// reporting to `watched`.
fn device(watched: &Watched, cache: &Path) -> Device {
pub(super) fn device(watched: &Watched, cache: &Path) -> Device {
let options = DeviceOptions {
kinds: match cfg!(m2v_cpu_icd) {
true => vec![DeviceKind::Cpu],
@@ -64,10 +64,14 @@ impl Page {
/// Whether the kernel wrote it: its words are zero until it does.
pub(super) fn written(&self) -> bool {
self.words().iter().any(|&word| word != 0)
}
/// Its words, for a leg that reads back what a shader recorded in it.
pub(super) fn words(&self) -> &[u32] {
// SAFETY: `BYTES` bytes, allocated in `new` aligned past a word, which no command writes
// any more (its command buffer completed).
let words = unsafe { std::slice::from_raw_parts(self.0.as_ptr().cast::<u32>(), BYTES / 4) };
words.iter().any(|&word| word != 0)
unsafe { std::slice::from_raw_parts(self.0.as_ptr().cast::<u32>(), BYTES / 4) }
}
/// Its pages, for a no-copy buffer or a rebind.
@@ -27,7 +27,7 @@ use std::time::{Duration, Instant};
const WATCHED: Duration = Duration::from_millis(500);
/// The attachments' formats: the fixture's implicit imageblock.
const FORMATS: [PixelFormat; 3] = [
pub(super) const FORMATS: [PixelFormat; 3] = [
PixelFormat::R32Float,
PixelFormat::R32Uint,
PixelFormat::R32Uint,
@@ -40,7 +40,7 @@ const AREA: [u64; 2] = [40, 24];
const RECORDS: u64 = 512 * 12 * 4;
/// A state of the fixture's tile function.
fn tile_state(device: &Device) -> RenderPipelineState {
pub(super) fn tile_state(device: &Device) -> RenderPipelineState {
let ll = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/fixtures/public/engine/k10ts_tile_grid.ll");
let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap();
@@ -0,0 +1,578 @@
//! A rebind of a no-copy buffer a committed command buffer's *tile* dispatch was encoded over,
//! whose region `VkPipeline` its variant's memo no longer holds: the rebind encodes that render
//! encoder again in its own call (`command_buffer/reencode.rs`), and what the encoding again does
//! for a pipeline it must have is what this watches. The twin of `rebind_making_wait.rs`, which
//! watches a compute encoder's dispatch.
//!
//! Metal makes a tile state's pipeline at `newRenderPipelineStateWithTileDescriptor`, so no Metal
//! call of the program's blocks on a shader compile afterwards: a tile dispatch waits for none
//! (`tile_pending.rs`), and neither does a replace of a buffer's bytes. The runtime makes a
//! region's `VkPipeline` on demand instead, in the device's pool, and keeps at most 32 of a
//! variant's (`pipeline::PIPELINES`): a rebind's encoding again of a dispatch whose region key
//! the memo let go of must answer as the first encoding did -- hand the making to the pool and
//! leave the pass to record later -- and never make the pipeline on the program's thread, nor
//! wait for a making another encoder began.
//!
//! Each leg differs only in what the encoding again finds for its region key ([`Memo`]), which
//! the legs drive by making 32 further keys of the variant, each a tile dispatch of threads per
//! tile of its own, so the key the rebind needs is the one the memo let go of. Nothing here rests
//! on how long anything took:
//!
//! - **Kept** is the control: the key is in the memo, so the encoding again finds it made. Nothing
//! is made and nothing is pooled in the rebind's call, and a leg that read something there would
//! mean the counters read something other than the making.
//! - **Let go** has the memo without the key and no making of it anywhere. The device's pool's
//! test hold (`pool::held`) starts no piece, so a making handed to it stays in flight: the
//! rebind that pools one makes nothing (`variant_pipelines_made`), and one that makes the
//! pipeline itself on the program's thread shows as a make and no pooling. The pass the encoding
//! again leaves is then awaited end to end: its command buffer cannot complete while the hold
//! lives, and completes with the dispatch's records in the pages the buffer lies in once it
//! goes.
//! - **In flight** has the memo without the key and its making in the held pool, begun by another
//! command buffer's dispatch. A rebind that asks the memo for the pipeline waits for that making
//! with no deadline; so the hold is let go of only after a thread sets a flag, and a rebind that
//! returns with the flag unset waited for no making.
//!
//! The work must land where the buffer lies now in every leg: the records go into the pages of the
//! rebind, byte for byte what the same dispatch writes into a buffer of the runtime's own, and the
//! pages the dispatch was encoded over stay untouched.
//!
//! 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. The tile function is the owned fixture
//! `validation/fixtures/public/engine/k10ts_tile_grid.ll`, as `tile_pending.rs` runs it, over one
//! 16x16 tile so that its records fit in one page ([`Page`]).
use super::blit_holds::{device, over_host, Host, Scratch, WAIT};
use super::layer_claim::Watched;
use super::pending_rebind::device as watched_device;
use super::rebind_behind_a_wait::{Page, BYTES};
use super::tile_pending::{tile_state, FORMATS};
use crate::pipeline::pool::held;
use crate::{
Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, CommandQueue, Device, Error,
EventRef, LoadAction, Region, RenderPassDescriptor, RenderPipelineState, ResourceOptions,
SharedEvent, Size, StoreAction, Texture, TextureDescriptor,
};
use metal2vulkan::metal::TextureUsage;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
/// How long the rebind is given to return while the pool's hold keeps a making waiting.
const WATCHED: Duration = Duration::from_millis(500);
/// How long the command buffer is watched not to complete while its pass's making is held.
const WATCHED_COMPLETION: Duration = Duration::from_millis(500);
/// The safety net: the pool's hold goes after this whatever the leg is doing, so a regression that
/// makes the rebind block again ends the leg on its assertions instead of wedging it while it holds
/// the Mac's GPU lock. The leg's own release comes long before.
const NET: Duration = Duration::from_secs(20);
/// The pass's tile and render area: one whole 16x16 tile, so the fixture's slot
/// `(tg.y * 4 + tg.x) * 64 + tidx` is `tidx` alone and its records end well inside a page.
const SIDE: u64 = 16;
/// The threads per tile the leg's own dispatch runs: 8x8, each thread owning the 2x2 cells at
/// twice its position.
const THREADS: u64 = 8;
/// The further region keys of the variant a leg makes to push its own out of the memo: one more
/// than the 32 `VkPipeline`s a variant keeps (`pipeline::PIPELINES`), each a dispatch of threads
/// per tile of its own, none of them 8x8.
const CROWD: u64 = 33;
/// What the encoding again finds in the variant's memo for the region key its tile dispatch needs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Memo {
/// The key, made: the encoding again finds it and asks for nothing.
Kept,
/// Not the key, and no making of it: the encoding again must begin one.
LetGo,
/// Not the key, its making in the held pool, begun by another command buffer's dispatch.
InFlight,
}
/// The threads per tile a crowding dispatch may take, in order: every shape up to the tile,
/// without the leg's own. A shape the translator refuses for this tile function is skipped, so the
/// leg takes the first `CROWD` it accepts.
fn crowd_threads() -> impl Iterator<Item = Size> {
(1..=SIDE)
.flat_map(|y| (1..=SIDE).map(move |x| (x, y)))
.filter(|&(x, y)| (x, y) != (THREADS, THREADS))
.map(|(x, y)| Size::new(x, y, 1))
}
/// The pass's three attachments, zeroed: the fixture's implicit imageblock. What they hold is not
/// what a leg reads -- the records in the no-copy buffer are -- so they are left at zero.
fn attachments(device: &Device) -> [Texture; 3] {
FORMATS.map(|format| {
let mut descriptor = TextureDescriptor::texture_2d(format, SIDE, SIDE, false);
descriptor.usage = TextureUsage::RENDER_TARGET;
descriptor.resource_options = ResourceOptions::shared();
let texture = device.new_texture(&descriptor).unwrap();
let bytes = vec![0u8; (SIDE * SIDE * 4) as usize];
let region = Region::new_2d(0, 0, SIDE, SIDE);
texture
.replace_region(region, 0, 0, &bytes, SIDE * 4, 0)
.unwrap();
texture
})
}
/// A command buffer of `queue` whose one pass over `colors`, of one 16x16 tile, dispatches `state`
/// over it with `out` as its tile buffer and `threads` threads per tile: encoded, uncommitted.
/// `gate` holds its first submission until the host signals it, so a rebind of `out` comes before
/// that submission (`rebind_behind_a_wait.rs`).
fn pass(
queue: &CommandQueue,
state: &RenderPipelineState,
colors: &[Texture; 3],
(out, threads): (&Buffer, Size),
gate: Option<&SharedEvent>,
) -> CommandBuffer {
let command_buffer = queue.command_buffer().unwrap();
assert!(
encode(&command_buffer, state, colors, (out, threads), gate),
"the tile function takes {threads:?} threads per tile"
);
command_buffer
}
/// [`pass`] into `command_buffer`, `false` where the translator refuses the dispatch's shape,
/// which leaves the encoder ended and the command buffer uncommitted.
fn encode(
command_buffer: &CommandBuffer,
state: &RenderPipelineState,
colors: &[Texture; 3],
(out, threads): (&Buffer, Size),
gate: Option<&SharedEvent>,
) -> bool {
let mut descriptor = RenderPassDescriptor::new();
for (attachment, target) in descriptor.color_attachments.iter_mut().zip(colors) {
attachment.texture = Some(target.clone());
attachment.load_action = LoadAction::Load;
attachment.store_action = StoreAction::Store;
}
descriptor.tile_width = SIDE;
descriptor.tile_height = SIDE;
if let Some(gate) = gate {
command_buffer
.encode_wait_for_event(EventRef::Shared(gate), 1)
.unwrap();
}
let mut encoder = command_buffer.render_command_encoder(&descriptor).unwrap();
encoder.set_render_pipeline_state(state).unwrap();
encoder.set_tile_buffer(Some(out), 0, 0).unwrap();
let dispatched = encoder.dispatch_threads_per_tile(threads).is_ok();
encoder.end_encoding().unwrap();
dispatched
}
/// Run the pass of `threads` to completion and check it completed.
fn completed(
queue: &CommandQueue,
state: &RenderPipelineState,
colors: &[Texture; 3],
(out, threads): (&Buffer, Size),
) {
let command_buffer = pass(queue, state, colors, (out, threads), None);
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(
command_buffer.status(),
CommandBufferStatus::Completed,
"{threads:?}: {:?} {:?}",
command_buffer.error(),
command_buffer.failed_pipeline(),
);
}
/// The no-copy buffer of `device` over `page`, `None` where the device imports no host memory.
///
/// # Safety
///
/// `page` outlives every buffer over it, and only that buffer's commands use it while it lives.
unsafe fn out_buffer(device: &Device, page: &Page, leg: &str) -> Option<Buffer> {
// SAFETY: the caller's contract.
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!("{leg}: the device imports no host memory: {gap:?}");
None
}
Err(error) => panic!("{leg}: new_buffer_with_bytes_no_copy: {error:?}"),
}
}
/// The leg of `memo`: a tile dispatch over a no-copy buffer committed behind a shared event only
/// the host signals, so its first submission comes after the rebind; the variant's memo then
/// brought to `memo`, and the buffer detached and rebound. Asserts that the rebind made no
/// `VkPipeline` on the program's thread and waited for no making, that the pass the encoding again
/// left is the command buffer's to await, and that the dispatch's records landed in the pages the
/// buffer lies in.
fn leg(memo: Memo) {
// Declared before the device, so dropped after it.
let pages = [Page::new(), Page::new()];
let scratch = Scratch::new(match memo {
Memo::Kept => "tile-rebind-memo-kept",
Memo::LetGo => "tile-rebind-memo-let-go",
Memo::InFlight => "tile-rebind-memo-in-flight",
});
let device: Device = device(&scratch.0);
let state = tile_state(&device);
let colors = attachments(&device);
let crowd_colors = attachments(&device);
let queue = device.new_command_queue().unwrap();
// The crowding passes run on a queue of their own: the leg's own command buffer waits for an
// event only the host signals, and a queue runs its command buffers in order.
let crowd_queue = device.new_command_queue().unwrap();
let threads = Size::new(THREADS, THREADS, 1);
let own = device
.new_buffer(BYTES as u64, ResourceOptions::shared())
.unwrap();
// What the same dispatch writes into a buffer of the runtime's own: what the leg's rebound
// pages must hold, byte for byte. It also makes the leg's region key, so the dispatch below
// finds it and the pass records at the encoder's end, leaving no segment -- which is what lets
// the rebind encode the encoder again at all.
completed(&queue, &state, &colors, (&own, threads));
let reference: Vec<u32> = {
let contents = own.contents().unwrap();
// SAFETY: `BYTES` bytes of shared storage, which the runtime maps for the program and no
// command writes any more (the command buffer above completed).
let words =
unsafe { std::slice::from_raw_parts(contents.as_ptr().cast::<u32>(), BYTES / 4) };
words.to_vec()
};
assert!(
reference.iter().any(|&word| word != 0),
"the reference run recorded something"
);
// SAFETY: each page outlives every buffer over it (dropped after the device), and only the
// buffer's commands use it while it lives.
let output = unsafe { out_buffer(&device, &pages[0], "TILE-REBIND-MEMO") };
let Some(output) = output else { return };
let before = device.work_counts();
let gate = device.new_shared_event().unwrap();
let command_buffer = pass(&queue, &state, &colors, (&output, threads), Some(&gate));
command_buffer.commit().unwrap();
let counts = device.work_counts();
assert_eq!(
counts.tile_pipelines_pooled, before.tile_pipelines_pooled,
"the dispatch found its region pipeline made, so its pass records at the encoder's end"
);
// The memo brought to what the encoding again must meet: 33 further region keys of the
// variant, one more than the 32 a variant keeps, so the leg's own key is the one let go of.
if memo != Memo::Kept {
let made = device.work_counts().variant_pipelines_made;
// Committed together and awaited once: each pass's making goes to the device's pool, and
// the last one completing has them all recorded, so every key is in the memo by then.
let mut crowding: Vec<CommandBuffer> = Vec::with_capacity(CROWD as usize);
for threads in crowd_threads() {
if crowding.len() as u64 == CROWD {
break;
}
let command_buffer = crowd_queue.command_buffer().unwrap();
if !encode(
&command_buffer,
&state,
&crowd_colors,
(&own, threads),
None,
) {
continue;
}
command_buffer.commit().unwrap();
crowding.push(command_buffer);
}
assert_eq!(
crowding.len() as u64,
CROWD,
"the tile function takes {CROWD} further shapes of its own"
);
for (n, command_buffer) in crowding.iter().enumerate() {
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(
command_buffer.status(),
CommandBufferStatus::Completed,
"the crowding pass {n}: {:?} {:?}",
command_buffer.error(),
command_buffer.failed_pipeline(),
);
}
let crowded = device.work_counts().variant_pipelines_made - made;
assert_eq!(
crowded, CROWD,
"each crowding dispatch is a region key of its own, so the memo let the leg's go"
);
}
// From now on the pool starts no piece: a making handed to it stays in flight. The one hold is
// a thread's, which drops it when the leg says so or after `NET`, whichever comes first: a leg
// that blocks in the rebind cannot keep it and wedge the Mac's GPU lock.
let hold = held::hold();
let (release, released_at) = std::sync::mpsc::channel::<()>();
let watchdog = std::thread::spawn(move || {
let _ = released_at.recv_timeout(NET);
drop(hold);
});
// Another command buffer's dispatch of the same region, whose making the held pool keeps in
// flight: what a rebind that asks the memo for the pipeline would wait for.
let in_flight = (memo == Memo::InFlight).then(|| {
let pooled = device.work_counts().tile_pipelines_pooled;
let other = pass(&queue, &state, &crowd_colors, (&own, threads), Some(&gate));
other.commit().unwrap();
assert_eq!(
device.work_counts().tile_pipelines_pooled,
pooled + 1,
"the other dispatch handed the leg's region key to the held pool"
);
other
});
// The hold is let go of only after the flag is set, on a thread of its own: a rebind that
// returns with the flag unset waited for no making. The flag is read before the thread is
// joined, so nothing of the release is in it.
let released = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&released);
let releaser = (memo == Memo::InFlight).then(|| {
std::thread::spawn(move || {
std::thread::sleep(WATCHED);
flag.store(true, Ordering::SeqCst);
})
});
assert!(WATCHED < NET, "the flag is set while the hold still lives");
let before = device.work_counts();
assert_eq!(
output.detach_backing(),
Ok(true),
"{memo:?}: the detach of a buffer whose only use waits for an event"
);
// SAFETY: as above.
unsafe { output.rebind_bytes_no_copy(pages[1].memory(), None, None) }.unwrap();
let waited = released.load(Ordering::SeqCst);
let counts = device.work_counts();
if let Some(releaser) = releaser {
releaser.join().unwrap();
}
let (made, pooled) = (
counts.variant_pipelines_made - before.variant_pipelines_made,
counts.tile_pipelines_pooled - before.tile_pipelines_pooled,
);
println!(
"tile-rebind-memo {memo:?}: made {made} pooled {pooled} waited {waited} \
reencoded {} refused {}",
counts.encoders_reencoded, counts.reencodes_refused,
);
assert_eq!(
made, 0,
"{memo:?}: the rebind made a `VkPipeline` on the program's thread: a Metal shader \
compile inside `rebind_bytes_no_copy`"
);
assert!(
!waited,
"{memo:?}: `rebind_bytes_no_copy` returned only once the flag was set, so it waited for \
the making in the held pool"
);
assert_eq!(
(counts.encoders_reencoded, counts.reencodes_refused),
(1, 0),
"{memo:?}: the rebind encoded the tile dispatch's encoder again, and the splice took it"
);
match memo {
Memo::Kept => assert_eq!(pooled, 0, "Kept: the encoding again found the key made"),
Memo::LetGo => assert_eq!(
pooled, 1,
"LetGo: the encoding again pooled the key's making"
),
// The other command buffer's making is the one in flight; the encoding again took it as
// it stood and handed nothing over.
Memo::InFlight => assert_eq!(pooled, 0, "InFlight: it took the making in flight"),
}
// Nothing of the GPU's holds the command buffer now. A leg whose pass the encoding again left
// for a making cannot complete while the pool holds that making: the end-to-end witness that
// the pass survives `State::splice_replay`, which would otherwise show as `EncodedUseRebound`.
gate.set_signaled_value(1);
if memo != Memo::Kept {
assert!(
command_buffer
.wait_until_completed_for(WATCHED_COMPLETION)
.is_err(),
"{memo:?}: the command buffer completed though the making its pass records is held"
);
assert_ne!(
command_buffer.status(),
CommandBufferStatus::Completed,
"{memo:?}: the pass the encoding again left awaits its making"
);
assert!(
!pages[0].written() && !pages[1].written(),
"{memo:?}: nothing ran while the making was held"
);
}
drop(release);
watchdog.join().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
if let Some(other) = in_flight {
other.wait_until_completed_for(WAIT).unwrap();
}
let (status, error) = (command_buffer.status(), command_buffer.error());
let (old, new) = (pages[0].written(), pages[1].written());
println!("tile-rebind-memo {memo:?}: {status:?} {error:?} old {old} new {new}");
assert!(
!old,
"{memo:?}: the dispatch recorded into the pages it was encoded over, which the buffer \
left before the submission ({status:?}, {error:?})"
);
assert_eq!(
error,
None,
"{memo:?}: the pass recorded and ran over the new pages ({:?})",
command_buffer.failed_pipeline()
);
assert_eq!(status, CommandBufferStatus::Completed, "{memo:?}");
assert!(
new,
"{memo:?}: the command buffer completed with no error, so the dispatch ran over the pages \
the buffer lies in"
);
assert_eq!(
pages[1].words(),
&reference[..],
"{memo:?}: the pages the buffer lies in hold what the same dispatch writes into a buffer \
of the runtime's own"
);
}
/// The control: a rebind whose encoding again finds the region key in the variant's memo makes
/// nothing and pools nothing, so a make or a wait read in the other legs reads the making and not
/// the rebind itself.
#[test]
fn a_rebind_whose_encoding_again_finds_its_tile_region_made_asks_for_nothing() {
leg(Memo::Kept);
}
/// A rebind whose encoding again needs a region `VkPipeline` the memo let go of hands the making
/// to the device's pool and leaves the pass to record later, as the first encoding would, instead
/// of running the Metal compile on the program's thread.
#[test]
fn a_rebind_does_not_make_a_tile_region_pipeline_on_the_programs_thread() {
leg(Memo::LetGo);
}
/// A rebind whose encoding again needs a region `VkPipeline` whose making another encoder began
/// takes that making as it stands and returns, instead of waiting for it with no deadline.
#[test]
fn a_rebind_does_not_wait_for_a_tile_making_another_encoder_began() {
leg(Memo::InFlight);
}
/// The guard on the other side of the rebind rule, with the validation layer watching.
///
/// A pass left for the pipelines its tile dispatch records holds no buffer's pages past its
/// command buffer's commit (`CommandBuffer::commit`'s `steps_hold`), so a rebind of one is not
/// refused -- Metal's replace never fails for that -- and encodes its encoder again instead. Where
/// that encoding again cannot happen, the pass must record nothing: its instances' secondaries and
/// its tile dispatch's recording resolved the buffer where it lay as they were encoded, and the
/// pages a rebind freed stay mapped, so a recording that bound that `VkBuffer` would have the GPU
/// write into pages the program handed back, with no fault and nothing said. That is the class of
/// bug this guard exists for, so it is watched by the layer and not by a page's contents alone.
///
/// The encoding again is made impossible as `pending_rebind.rs` makes it: the render encoder is
/// opened while the device has no buffer over host pages, so it logs no call (`Unlogged::NoCalls`)
/// and no rebind can replay it. The device's pool is held, so only a host step records the pass,
/// and only once the hold is gone -- after the rebind, in every run.
///
/// Without `DeferredPass::record_forms`' `encoder_rebound` guard the host step records the pass and
/// the layer reports the freed `VkBuffer` in a bound descriptor
/// (`VUID-vkCmdDrawIndexed-None-08114` and its kin), which fails this test.
#[test]
fn a_tile_pass_records_nothing_where_a_rebind_freed_what_its_descriptors_name() {
// Declared before the device, so dropped after it.
let hosts = [Host::new(), Host::new()];
let watched = Watched::default();
let scratch = Scratch::new("tile-rebind-unlogged");
let device = watched_device(&watched, &scratch.0);
let state = tile_state(&device);
let colors = attachments(&device);
let queue = device.new_command_queue().unwrap();
// Every making the pool starts waits from here: only a host step records the pass, and only
// once this hold is gone.
let hold = held::hold();
let mut descriptor = RenderPassDescriptor::new();
for (attachment, target) in descriptor.color_attachments.iter_mut().zip(&colors) {
attachment.texture = Some(target.clone());
attachment.load_action = LoadAction::Load;
attachment.store_action = StoreAction::Store;
}
descriptor.tile_width = SIDE;
descriptor.tile_height = SIDE;
let command_buffer = queue.command_buffer().unwrap();
// Opened while the device has no buffer over host pages, so the encoder logs no call and no
// rebind encodes it again (`Unlogged::NoCalls`).
let mut encoder = command_buffer.render_command_encoder(&descriptor).unwrap();
let runs = Arc::new(AtomicUsize::new(0));
let Some(output) = over_host(&device, &hosts[0], &runs) else {
return;
};
encoder.set_render_pipeline_state(&state).unwrap();
encoder.set_tile_buffer(Some(&output), 0, 0).unwrap();
let pooled = device.work_counts().tile_pipelines_pooled;
encoder
.dispatch_threads_per_tile(Size::new(THREADS, THREADS, 1))
.unwrap();
encoder.end_encoding().unwrap();
assert_eq!(
device.work_counts().tile_pipelines_pooled,
pooled + 1,
"the dispatch handed a making to the pool, so a host step records its pass"
);
command_buffer.commit().unwrap();
// The buffer lies elsewhere from here, and the pages it lay in go: nothing submitted holds
// them, and the committed command buffer holds them weakly. The rebind is allowed at all only
// because the pass holds nothing past the commit.
//
// SAFETY: the pages outlive every buffer over them, and only its commands use them while it
// lives.
unsafe { output.rebind_bytes_no_copy(hosts[1].memory(), None, None) }.unwrap();
assert_eq!(
device.work_counts().encoders_reencoded,
0,
"the encoder kept no log, so nothing was encoded again"
);
// The makings may finish now, so the host step records the pass after the rebind.
drop(hold);
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Error);
assert_eq!(
command_buffer.error(),
Some(CommandBufferError::EncodedUseRebound),
"the submission holding the pass ran nothing"
);
assert!(hosts[0].holds(0), "the pages the dispatch took");
assert!(hosts[1].holds(0), "the pages the buffer lies in now");
watched.layer_reported_nothing(
"a tile pass recorded after a rebind of a buffer it named bound no freed VkBuffer",
);
}
@@ -1 +1 @@
4a225dd40b17c9141505490b955fee25d80f7e444d0158194e16b323408cdccb
4026573ae5081d870a623825f3acfb2916cebf7e783fd0ef0700eb4b954ea37b
+1 -1
View File
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 450;
/// 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 = 1640;
pub const RUNTIME_VERSION: u32 = 1641;
/// 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