From e7b9c5bfdc44deab2463611c81f47a712d88ecfc Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 14 Nov 2026 19:20:14 -0800 Subject: [PATCH] RUNTIME 2329: A GPU route's commands are drawn one draw per command in the replay variant, indexed The GPU route of a rate-mapped pass's host step drew each command's corners in its merged variant: a non-indexed draw of every index, which loses the indexed draw's vertex reuse and looks its command up per vertex. On the Iris Xe the wide frame's pieces took 74.2 ms against 48.0 ms when the host read the records (job 30850). Now the step reads back each command's VkDrawIndirectCommand and its index entry (the device address of its first index and its index size, bind::DRAW_INDEX_ENTRY_BYTES, now public), resolves the index address to its Metal address through the resident set's ranges and the live table's, and draws each command as the host draws a record it read: indexed where it is, with its instances, base vertex and base instance, in the state's replay variant (BufferForms::Replay), each draw pushing the command's own slot tables at its PushHole::RootTableAddress holes (CommandTables). The commit's settle begins the replay variants for the routed executions. The corner cutting in the piece loop goes: an indexed routed draw is cut into index ranges as any. Tests: the pixel and depth test asserts indexed draws are recorded on a routed frame; the count test runs three frames, the host step making no pipeline on any and nothing made at all on the second and third. Public: bind::DRAW_INDEX_ENTRY_BYTES (api_signatures, api_surface). Verified: job 30942 at the branch tip: clippy for metal2vulkan and the runtime, the runtime under --cfg m2v_cpu_icd, the runtime and validation under --cfg m2v_gpu; the two route tests on lavapipe. Job 30922: lavapipe suites 78/78, API tests 15/15, rustdoc -D warnings; a negative control (the change reverted but its tests) fails the pixel test with 0 indexed draws recorded. The Iris and 3090 GPU-time A/Bs are pending. --- .../metal2vulkan-runtime/src/degradation.rs | 6 +- .../src/rate_mapped_pass.rs | 7 +- crates/metal2vulkan-runtime/src/render.rs | 21 +- .../src/render/executions.rs | 205 +++++--------- .../src/render/executions/gpu.rs | 163 ++++++++---- .../src/render/executions/gpu_route.rs | 249 ++++++++++++------ .../src/render/fan_out.rs | 8 +- .../src/tests/rate_mapped_gpu_route.rs | 42 ++- .../metal2vulkan-runtime/src/work_counts.rs | 5 +- crates/metal2vulkan/src/bind/mod.rs | 4 +- crates/metal2vulkan/src/bind/replay.rs | 4 +- crates/metal2vulkan/src/bind/replay/merged.rs | 9 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 2 + crates/metal2vulkan/tests/api_surface.rs | 1 + docs/API.md | 6 +- 16 files changed, 424 insertions(+), 310 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index f0c46eeb9..0b32ccf71 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -732,9 +732,9 @@ degradations! { the CPU set on none of the commands. In a rate-mapped pass whose host step fans \ its triangles out, a render execution kept from the GPU alone by the rate map alone \ has its records decoded on the GPU at the step, which reads back each command's \ - corners and none of its records, and its commands run in their merged variant \ - (WorkCounts::rate_map_gpu_routes): a second round trip, for the decode, comes \ - before the probe's. Other commands run in the large-buffer form \ + draw arguments and index buffer and none of its records, and each command is drawn \ + in its replay variant, indexed where it is (WorkCounts::rate_map_gpu_routes): a \ + second round trip, for the decode, comes before the probe's. Other commands run in the large-buffer form \ (their range-limited buffer slots at device addresses, with in-shader bounds \ checks), whose variants the commit compiles for every pipeline state a record may \ name (for a render execution, every state the CPU set on its commands; or, for an \ diff --git a/crates/metal2vulkan-runtime/src/rate_mapped_pass.rs b/crates/metal2vulkan-runtime/src/rate_mapped_pass.rs index c5fadb447..8402ed80e 100644 --- a/crates/metal2vulkan-runtime/src/rate_mapped_pass.rs +++ b/crates/metal2vulkan-runtime/src/rate_mapped_pass.rs @@ -176,9 +176,8 @@ //! several would put an instance's later primitives before the next instance's earlier ones), //! whose pipeline reads no `[[primitive_id]]` (each range counts its primitives from 0) and //! writes no memory. Each range's vertices, instance and base vertex are the draw's -//! (`WorkCounts::rate_map_index_ranges`). A GPU route's draw of a command's corners -//! (`render/executions/gpu_route.rs`), such a list in one instance whatever its command's -//! instances, is cut so too, as ranges of its corners. Any other draw rides whole in the piece it begins in, +//! (`WorkCounts::rate_map_index_ranges`), a GPU route's command's draw +//! (`render/executions/gpu_route.rs`) as any other. Any other draw rides whole in the piece it begins in, //! however much work it holds: a strip, an instanced draw, a draw without indices, a mesh or //! patch draw, one of such a pipeline; and the encoder's own draws are not cut at all //! (`docs/FAST-PATHS.md`, known gaps). So a piece of draws cut so holds less than twice @@ -244,7 +243,7 @@ //! attachments are memoryless or that uses a shadowed texture is not probed, nor an execution //! whose commands record as several runs. `commit`'s settle of the pass //! (`RenderExecution::settle`) begins the probe's and the fanned-out draws' variants and -//! `VkPipeline`s on the device's pool beside the draws' own, in the merged form for an +//! `VkPipeline`s on the device's pool beside the draws' own, in the replay form for an //! execution the step's GPU route takes (`render/executions/gpu_route.rs`), so the step takes them made, or //! waits for them (`WorkCounts::rate_map_fan_out_pipelines_ready`, //! `rate_map_fan_out_pipelines_waited`), and makes none itself for the states the settle foresaw, diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 4e71ba474..07b85db88 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -1786,10 +1786,11 @@ pub(crate) struct RenderLowering { /// Where it records an execution's GPU form, the replay's draws, which its draw records in /// place of its own (`render/executions/gpu.rs`). replayed: Option, - /// Where it records an execution's GPU route at a host step, the device address of its - /// merged replay's header, which each draw's `PushHole::MergedDrawAddress` takes: its draws - /// are direct draws of the commands' corners (`render/executions/gpu_route.rs`). - merged_header: Option, + /// Where it records a command of an execution's GPU route at a host step, where the route's + /// slot tables lie and the command's place among them: each of the command's draws pushes the + /// command's own tables at its `PushHole::RootTableAddress` holes, its replay variant's + /// (`render/executions/gpu_route.rs`). + command_tables: Option<(executions::CommandTables, u32)>, /// Where the encoder records an execution's commands, the tracked uses of the pass's draws /// before the execution, in the stages a draw runs in inside its pass (`PASS_DRAW_STAGES`): /// which an emulated mesh command's dispatches, recorded before the pass, must not touch but @@ -2584,7 +2585,7 @@ impl RenderLowering { rerouting: false, forms: BufferForms::Bound, replayed: None, - merged_header: None, + command_tables: None, drawn_before: Vec::new(), run_barrier: false, piece_split: false, @@ -9816,8 +9817,7 @@ impl RenderLowering { .ok_or_else(|| internal("a heap's draw without its argument samplers"))?; tables = tables.with_heap(states, heap); } - let replayed = self.replayed.as_ref().and_then(|r| r.merged_header()); - if let Some(header) = replayed.or(self.merged_header) { + if let Some(header) = self.replayed.as_ref().and_then(|r| r.merged_header()) { tables = tables.with_merged_header(header); } // A list in the private list form is read at its address, which the device gives the @@ -10472,6 +10472,11 @@ impl RenderLowering { Some(replayed) => replayed.first_tables(&commands.push_holes, &mut live.pushes)?, None => Vec::new(), }; + // A GPU route's command's draws read its own slot tables, at every recording + // (`render/executions/gpu_route.rs`). + if let Some((tables, command)) = &self.command_tables { + tables.fill(*command, &commands.push_holes, &mut live.pushes)?; + } let push = &live.pushes; // A plan that draws one amplification at a time records the draw once per amplification, // in order, each after that amplification's push writes. @@ -11744,7 +11749,7 @@ impl RenderLowering { && !culled && !self.rerouting && self.replayed.is_none() - && self.merged_header.is_none() + && self.command_tables.is_none() && self.grouped.is_none() && self.rate_map.is_none() && matches!(draw_pipeline, DrawPipeline::Made(_)) diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index 68cd82c91..27669c441 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -30,8 +30,8 @@ //! the work before it completed, which the device announces once //! (`Degradation::HostReplayedIndirectCommands`). At a host step that fans a rate-mapped pass's //! triangles out, an execution kept from the GPU alone by the rate map alone has its records -//! decoded on the GPU there, and the host reads its commands' corners and none of its records -//! (`executions/gpu_route.rs`). The step draws in the large-buffer form, whose +//! decoded on the GPU there, and the host reads its commands' draw arguments and none of its +//! records, drawing each command in its replay variant (`executions/gpu_route.rs`). The step draws in the large-buffer form, whose //! variant no command's buffer lengths change (`BufferForms::Large`), and the commit settles what //! it will draw (the step compiled each draw's variant and `VkPipeline` as it met them, after the //! commit returned): for each state the records name as the CPU wrote them (the inherited one, @@ -347,7 +347,8 @@ use ahead::Ahead; use ash::vk; use cause::{HostStepCause, Passed}; use gpu::GpuForm; -pub(super) use gpu::ReplayedDraws; +pub(super) use gpu::{CommandTables, ReplayedDraws}; +use gpu_route::RoutedDraw; use metal2vulkan::bind::indirect_commands::{Action, BufferStage, CommandRecord}; use metal2vulkan::bind::{ draw_replay_merges, fan_out::PROBE_DRAW_WORDS, DrawCall, RateMapRegions, ReplayFaults, @@ -1053,11 +1054,11 @@ pub(super) type Command = (CommandRecord, Option); /// The commands of an execution a host step's probe and routes record (`render/fan_out.rs`): /// those the host read, `None` where a record runs nothing for a fault; or those of its GPU route -/// that draw, each its corners in its merged draw, and the type they draw -/// (`executions/gpu_route.rs`). +/// that draw, each its draw as the GPU decoded it, the type they draw and where their slot tables +/// lie (`executions/gpu_route.rs`). pub(super) enum StepDraws { Read(Vec>), - Corners(Vec>, PrimitiveType), + Routed(Vec, PrimitiveType, CommandTables), } impl StepDraws { @@ -1065,32 +1066,34 @@ impl StepDraws { pub(super) fn len(&self) -> usize { match self { StepDraws::Read(commands) => commands.len(), - StepDraws::Corners(corners, _) => corners.len(), + StepDraws::Routed(draws, ..) => draws.len(), } } + /// Whether they are a GPU route's, whose draws run in the replay variant. + pub(super) fn routed(&self) -> bool { + matches!(self, StepDraws::Routed(..)) + } + /// Of the commands `range`, those that run, as the replay loop records them. fn replayed(&self, range: Range) -> Vec> { match self { StepDraws::Read(commands) => (commands[range].iter().flatten()) .map(Replayed::Record) .collect(), - StepDraws::Corners(corners, primitive_type) => (corners[range].iter()) - .map(|corners| { - let count = corners.end - corners.start; - Replayed::Corners(corners.start, count, *primitive_type) - }) + StepDraws::Routed(draws, primitive_type, tables) => (draws[range].iter()) + .map(|draw| Replayed::Routed(draw, *primitive_type, tables)) .collect(), } } } /// A command the replay loop records ([`RenderExecution::replay`]): a record and the state it -/// names, or a GPU route's command, its first corner, its corners and the type they draw. +/// names, or a GPU route's command, its draw, the type it draws and where its slot tables lie. #[derive(Clone, Copy)] pub(super) enum Replayed<'c> { Record(&'c Command), - Corners(u32, u32, PrimitiveType), + Routed(&'c RoutedDraw, PrimitiveType, &'c CommandTables), } impl<'c> From<&'c Command> for Replayed<'c> { @@ -1122,17 +1125,17 @@ type SubmittedPart = ( /// The host step's commands of an execution, read once for its probe and its recording /// ([`RenderExecution::step_commands`]), or its GPU route's (`executions/gpu_route.rs`): the -/// commands, `None` where a record runs nothing for a fault, the command they start at, the -/// faults the range and the records hold, and a GPU route's merged header's device address. -type StepCommands = (StepDraws, u32, ReplayFaults, Option); +/// commands, `None` where a record runs nothing for a fault, the command they start at, and the +/// faults the range and the records hold. +type StepCommands = (StepDraws, u32, ReplayFaults); -/// The buffer forms of a host step's draws of an execution's commands: the large-buffer form, -/// whose variants `commit` settled (`RenderExecution::settle`); the merged one for its GPU -/// route's, whose merged replay's header lies at `header` (`executions/gpu_route.rs`). -fn step_forms(header: Option) -> BufferForms { - match header { - Some(_) => BufferForms::Merged, - None => BufferForms::Large, +/// The buffer forms of a host step's draws of an execution's commands, whose variants `commit` +/// settled (`RenderExecution::settle`): the large-buffer form; the replay form for its GPU +/// route's (`routed`, `executions/gpu_route.rs`). +fn step_forms(routed: bool) -> BufferForms { + match routed { + true => BufferForms::Replay, + false => BufferForms::Large, } } @@ -1259,24 +1262,6 @@ fn index_ranges_of(pipeline: &RenderPipelineState, draw: &IndexedDraw) -> Option list_vertices(pipeline, draw.primitive_type, draw.instance_count) } -/// The vertices of each primitive of `call` of `pipeline` as `assembly`, a GPU route's draw of a -/// command's corners (`executions/gpu_route.rs`), where they may be drawn as consecutive ranges as -/// a command's indices are ([`list_vertices`]'s): its corners are its command's whole primitives, -/// each instance's in turn, in one instance of the draw. -fn corner_ranges_of( - pipeline: &RenderPipelineState, - assembly: Assembly, - call: &DrawCall, -) -> Option { - match (assembly, call) { - (Assembly::Primitives(primitive_type), DrawCall::Primitives { instance_count, .. }) => { - let primitive_type = DrawPrimitiveType::Public(primitive_type); - list_vertices(pipeline, primitive_type, *instance_count) - } - _ => None, - } -} - /// The triangles of `draw` of `pipeline`, and whether its parts begin at even ones, where a draw /// the probe flagged is drawn in parts (`render/fan_out.rs`, **Parts**): a list of triangles whose /// vertices or indices may be drawn as consecutive ranges ([`list_vertices`]), its parts of a @@ -2182,9 +2167,10 @@ impl RenderLowering { }; // The encoder's pipeline state, which its bind state reads, as a command's draw sets it. self.pipeline = Some(pipeline.clone()); - // In the merged form a GPU route draws lists alone (`gpu_route.rs`). - let merged = self.forms == BufferForms::Merged; - for &primitive_type in types.iter().filter(|&&t| !merged || draw_replay_merges(t)) { + // A GPU route, whose draws the replay form's are at a host step, draws lists alone + // (`gpu_route.rs`). + let routed = self.forms == BufferForms::Replay; + for &primitive_type in types.iter().filter(|&&t| !routed || draw_replay_merges(t)) { if let Ok(Some(settled)) = self.settle_draw_of(live, state, primitive_type) { made.push(settled); } @@ -2549,12 +2535,12 @@ impl RenderExecution { let start = range.start; let (commands, written) = self.written_commands(device, range, check)?; let commands = StepDraws::Read(commands); - Ok((commands, start, ReplayFaults(faults.0 | written.0), None)) + Ok((commands, start, ReplayFaults(faults.0 | written.0))) } /// Record the probe of `commands`, a part of the host step's - /// ([`step_commands`](Self::step_commands)), or of its GPU route's, whose merged replay's - /// header lies at `header` (`executions/gpu_route.rs`), through an encoder of `core` into a + /// ([`step_commands`](Self::step_commands)), or of its GPU route's (`routed`, + /// `executions/gpu_route.rs`), through an encoder of `core` into a /// secondary begun against the execution's instance, over the pass's `storage`, with /// `residency`, the command buffer's, its draws taking indices of `flags` from `from` /// (`render/fan_out.rs`): the core back, and what it recorded ([`ProbedPart`]): where its @@ -2564,15 +2550,14 @@ impl RenderExecution { &self, core: EncoderCore, (command_buffer, residency): (&CommandBuffer, &Residency), - (commands, header): (&[Replayed<'_>], Option), + (commands, routed): (&[Replayed<'_>], bool), (flags, from, storage): (vk::DescriptorBufferInfo, u32, PassStorage), ) -> Result<(EncoderCore, ProbedPart), Error> { let snapshot = &self.snapshot; let layout = snapshot.layout.clone(); let lent = (command_buffer, None); - let forms = step_forms(header); + let forms = step_forms(routed); let mut encoder = self.begin_replay(core, lent, (storage, layout, residency), forms)?; - encoder.merged_header = header; encoder.fan_run = Some(FanOutRun::Probe(Probe::new(flags, from))); let mut found = Found::default(); let mut live = LiveBind::default(); @@ -2637,29 +2622,29 @@ impl RenderExecution { ) -> Result { let device = command_buffer.device().clone(); found.faults = ReplayFaults(found.faults.0 | routes.faults.0); - match (routes.header, &self.pipeline) { + let routed = routes.commands.routed(); + match (routed, &self.pipeline) { // The GPU reads the records: the handlers learn the state their commands run, as of // the GPU form's (`gpu.rs`). - (Some(_), Some(pipeline)) => { + (true, Some(pipeline)) => { command_buffer.report_executed(&self.icb, RecordsRead::Gpu, residency, || { (Vec::new(), pipeline.can_encode_indirect_commands()) }) } - (Some(_), None) => return Err(internal("a GPU route without its pipeline state")), - (None, _) if command_buffer.reports_executed() => { + (true, None) => return Err(internal("a GPU route without its pipeline state")), + (false, _) if command_buffer.reports_executed() => { if let StepDraws::Read(commands) = &routes.commands { let executed = commands.iter().map(Option::as_ref); let read = (RecordsRead::HostStep, residency); self.report(command_buffer, read, routes.start, executed); } } - (None, _) => {} + (false, _) => {} } let layout = rendered.backing(&self.snapshot.layout)?; let lent = (command_buffer, self.lent.clone()); - let forms = step_forms(routes.header); + let forms = step_forms(routed); let mut encoder = self.begin_replay(core, lent, (storage, layout, residency), forms)?; - encoder.merged_header = routes.header; encoder.fan_run = Some(FanOutRun::Route(Arc::clone(&routes))); let mut live = LiveBind::default(); let commands = routes.commands.replayed(0..routes.commands.len()); @@ -2698,9 +2683,9 @@ impl RenderExecution { /// Replay `commands` through `encoder` (`record`'s), resolving against `residency`, the /// command buffer's, what their draws found noted into `found`. A mesh or patch draw is no - /// plain draw (`RenderLowering::replay_plain`). A GPU route's command draws its corners - /// directly, with the encoder's tables at the call as the GPU form's draw has them - /// (`executions/gpu_route.rs`). + /// plain draw (`RenderLowering::replay_plain`). A GPU route's command draws as the GPU decoded + /// it, with the encoder's tables at the call as the GPU form's draw has them, its draws + /// pushing its own slot tables (`executions/gpu_route.rs`). fn replay<'c, C: Into>>( &self, (encoder, live): (&mut RenderLowering, &mut LiveBind), @@ -2733,7 +2718,12 @@ impl RenderExecution { let command: Replayed<'c> = command.into(); let (record, own) = match command { Replayed::Record((record, own)) => (Some(record), own.as_ref()), - Replayed::Corners(..) => (None, None), + Replayed::Routed(..) => (None, None), + }; + // A GPU route's command's draws read its own slot tables. + encoder.command_tables = match command { + Replayed::Routed(routed, _, tables) => Some((*tables, routed.command)), + Replayed::Record(_) => None, }; if let (Some((notes, last)), Some(own)) = (&mut trail, own) { if *last != Some(own) { @@ -2772,14 +2762,8 @@ impl RenderExecution { encoder.fanned = (false, false); encoder.boxed = false; let asked = match (command, record) { - (Replayed::Corners(first, count, primitive_type), _) => { - let draw = DrawCall::Primitives { - vertex_start: first, - vertex_count: count, - instance_count: 1, - base_instance: 0, - }; - Asked::Draw(Draw::Primitives(Assembly::Primitives(primitive_type), draw)) + (Replayed::Routed(routed, primitive_type, _), _) => { + Asked::Draw(routed.draw(primitive_type)) } (_, Some(record)) => Asked::of(&record.action, &self.icb), (_, None) => continue, @@ -2808,8 +2792,9 @@ impl RenderExecution { }; if let (Some((notes, _)), false) = (&mut trail, probing) { let drew = match (command, record) { - (Replayed::Corners(_, count, primitive_type), _) => { - Some((false, primitive_type.as_raw(), count, 1)) + (Replayed::Routed(routed, primitive_type, _), _) => { + let (indexed, count, instances) = routed.traced(); + Some((indexed, primitive_type.as_raw(), count, instances)) } (_, Some(record)) => trail_draw(&record.action), (_, None) => None, @@ -2936,62 +2921,13 @@ impl RenderExecution { }) .collect(), }; - for (at, (fan_out, mut draw, triangles, bounds)) in - draws.into_iter().enumerate() - { + for (at, (fan_out, draw, triangles, bounds)) in draws.into_iter().enumerate() { if at > 0 { regions = note(found.piece_after(encoder)); found.piece_before(encoder); } encoder.fan_out = fan_out; encoder.run_bounds = bounds; - // A GPU route's command's corners, a list of one instance, drawn as - // consecutive ranges where they would hold more than a piece's work, as a - // command's indices are (below); a fanned-out draw, and a probe, whole. - let corners = matches!(command, Replayed::Corners(..)); - let cut = corners - && encoder.rate_map.is_some() - && !probing - && encoder.fan_out.is_none(); - let per_primitive = cut - .then(|| corner_ranges_of(encoder.pipeline.as_ref()?, assembly, &draw)) - .flatten(); - if let Some(per_primitive) = per_primitive { - let mut ranges = 0u64; - while let DrawCall::Primitives { - vertex_start, - vertex_count, - instance_count, - base_instance, - } = draw - { - let most = rate_mapped_pass::index_range(regions, per_primitive); - if vertex_count <= most { - break; - } - let range = DrawCall::Primitives { - vertex_start, - vertex_count: most, - instance_count, - base_instance, - }; - let none = DrawBuffers::default(); - encoder.draw(live, CALL, assembly, range, none, false)?; - regions = note(found.piece_after(encoder)); - found.piece_before(encoder); - draw = DrawCall::Primitives { - vertex_start: vertex_start + most, - vertex_count: vertex_count - most, - instance_count, - base_instance, - }; - ranges += 1; - } - if ranges > 0 { - let counts = &encoder.core.device().shared().counts; - counts.rate_map_index_ranges(ranges); - } - } encoder.draw(live, CALL, assembly, draw, DrawBuffers::default(), false)?; encoder.run_bounds = None; drawn.push((triangles, encoder.fanned.0, encoder.boxed)); @@ -3138,6 +3074,7 @@ impl RenderExecution { } } } + encoder.command_tables = None; if let Some((notes, _)) = trail { encoder.core.command_buffer().trail_step(notes); } @@ -3363,7 +3300,7 @@ impl RenderExecution { rerouting: false, forms, replayed: None, - merged_header: None, + command_tables: None, drawn_before: snapshot.drawn.clone(), run_barrier: false, piece_split: false, @@ -3433,7 +3370,7 @@ impl RenderExecution { /// read from a buffer); over the pass's `storage`, with `residency`, the command buffer's. /// A state a record the GPU wrote names, the step meets as it is then. Nothing where the /// buffer holds no draw of primitives. In `forms`, the buffer forms the step's draws take: - /// the large-buffer form of the commands it reads, or the merged form of those its GPU route + /// the large-buffer form of the commands it reads, or the replay form of those its GPU route /// takes (`gpu_route.rs`), whose lists alone it draws. Returns the core. fn settle( &self, @@ -4083,7 +4020,7 @@ impl DeferredPass { continue; } let storage = self.storage.clone(); - let (back, form) = execution.gpu_form(core, (storage, residency), passed); + let (back, form) = execution.gpu_form(core, (storage, residency), (passed, false)); core = back; match form { Ok(form) => forms.push(Some(form)), @@ -4733,13 +4670,12 @@ impl DeferredPass { } let routes = (reads.into_iter().enumerate()) .map(|(at, read)| { - let (commands, start, faults, header) = read?; + let (commands, start, faults) = read?; let slots = probes.get(at).cloned().flatten().unwrap_or_default(); Some(Arc::new(FanOutRoutes { commands, start, faults, - header, slots, probed: Arc::clone(&found_draws), })) @@ -4769,7 +4705,7 @@ impl DeferredPass { let mut draws: Vec<(usize, vk::CommandBuffer)> = Vec::new(); let mut held = 0; for ((execution, read), home) in self.executions.iter().zip(reads).zip(homes) { - let (Some((commands, _, _, header)), Some(home)) = (read, home) else { + let (Some((commands, _, _)), Some(home)) = (read, home) else { probes.push(None); continue; }; @@ -4782,7 +4718,8 @@ impl DeferredPass { let these = commands.replayed(at..at + take); let probing = (flags, next, self.storage.clone()); let at_step = (command_buffer, residency); - let (back, probed) = execution.probe(core, at_step, (&these, *header), probing)?; + let routed = (&these[..], commands.routed()); + let (back, probed) = execution.probe(core, at_step, routed, probing)?; core = back; if probed.apart { apart = true; @@ -4907,7 +4844,7 @@ impl DeferredPass { /// ([`RenderExecution::settle`]): for each execution, the variants and `VkPipeline`s of the /// draws of each state its records name as the CPU wrote them, the encoder's where its buffer /// inherits it, else the live states the CPU set on the commands it may run, in the forms the - /// step draws them in: the merged form for an execution the step's GPU route takes, which the + /// step draws them in: the replay form for an execution the step's GPU route takes, which the /// decision finds again here (`gpu_route.rs`), else the large-buffer form. Each such state's /// creation compiled its variant in the large-buffer form, which the commit looks up, and the /// commit begins the `VkPipeline`s: under `PipelineWaitPolicy::Bounded` (the default) each @@ -4933,7 +4870,7 @@ impl DeferredPass { let mut fanned = Vec::new(); let fans = self.fans_out(command_buffer.device()); // Where the step fans the pass out, the executions its GPU route takes draw in their - // merged forms (`gpu_route.rs`); the others in the large-buffer form, from their records. + // replay forms (`gpu_route.rs`); the others in the large-buffer form, from their records. let routed: Vec = match fans { true => { let (back, forms) = self.route_forms(core, &residency); @@ -4945,11 +4882,7 @@ impl DeferredPass { for (execution, routed) in self.executions.iter().zip(routed) { let inputs = (self.storage.clone(), &residency); let into = (&mut made, fans.then_some(&mut fanned)); - let forms = match routed { - true => BufferForms::Merged, - false => BufferForms::Large, - }; - core = execution.settle(core, inputs, into, forms); + core = execution.settle(core, inputs, into, step_forms(routed)); } let makings = |made: &[SettledDraw]| -> Vec> { (made.iter()) diff --git a/crates/metal2vulkan-runtime/src/render/executions/gpu.rs b/crates/metal2vulkan-runtime/src/render/executions/gpu.rs index 6c315a03d..a34351ab5 100644 --- a/crates/metal2vulkan-runtime/src/render/executions/gpu.rs +++ b/crates/metal2vulkan-runtime/src/render/executions/gpu.rs @@ -117,8 +117,9 @@ //! states why (`bind::ReplayFaults`), as the host step's; the others draw. //! - **At a host step of a rate-mapped pass** that fans its triangles out, an execution that takes //! this form, merged, but for the pass's rate map has its records decoded on the GPU all the -//! same: the step runs the preprocess and the merge passes, reads back each command's corners, -//! and draws them (`gpu_route.rs`). +//! same: the step runs the preprocess and the merge passes, reads back each command's arguments +//! and index entry, and draws each command in its state's replay variant, its slot tables +//! pushed ([`CommandTables`], `gpu_route.rs`). use std::ops::Range; use std::sync::Arc; @@ -227,6 +228,92 @@ pub(in crate::render) struct TableHole { table: Table, } +/// Where the slot tables of a GPU route's commands lie (`gpu_route.rs`): its scratch's device +/// address past its lead and its preprocess's layout. Each command's draws, in the state's replay +/// variant, push the command's own ([`fill`](Self::fill)). +#[derive(Clone, Copy)] +pub(in crate::render) struct CommandTables { + address: u64, + layout: DrawReplayLayout, +} + +impl CommandTables { + /// The slot tables of the commands of `layout`, a preprocess's, whose scratch lies at device + /// address `address`. + pub(super) fn new(address: u64, layout: DrawReplayLayout) -> CommandTables { + CommandTables { address, layout } + } + + /// Fill each hole of `holes` (a draw's push holes) that takes a slot table in `pushes` (its + /// push writes) with the `command`th command's of the range: the binder's root tables are + /// none of the command's. Refused (internal) for a hole of other stages than one function's, + /// or one no push write covers. + pub(in crate::render) fn fill( + &self, + command: u32, + holes: &[PushHole], + pushes: &mut [PushWrite], + ) -> Result<(), Error> { + fill_tables((self.address, &self.layout), command, holes, pushes).map(drop) + } +} + +/// The holes of `holes` (a draw's push holes) that take a slot table, each filled in `pushes` +/// (its push writes) with the `command`th command's of the replay laid out in `layout` at device +/// address `address`. Refused (internal) for a hole of other stages than one function's, or one +/// no push write covers. +fn fill_tables( + (address, layout): (u64, &DrawReplayLayout), + command: u32, + holes: &[PushHole], + pushes: &mut [PushWrite], +) -> Result, Error> { + let mut tables = Vec::new(); + for hole in holes { + let PushHole::RootTableAddress { stages, offset } = *hole else { + continue; + }; + let stages: vk::ShaderStageFlags = stages.into(); + let table = match stages { + vk::ShaderStageFlags::VERTEX => Table::Vertex, + vk::ShaderStageFlags::FRAGMENT => Table::Fragment, + _ => return Err(internal("a replayed draw's slot table of several stages")), + }; + let hole = TableHole { + stages, + offset, + table, + }; + let write = pushes + .iter_mut() + .find(|(of, start, bytes)| { + *of == stages + && *start <= offset + && offset as usize + 8 <= *start as usize + bytes.len() + }) + .ok_or_else(|| internal("no push write covers a replayed draw's slot table"))?; + let at = (offset - write.1) as usize; + let table = table_address((address, layout), &hole, command); + write.2[at..at + 8].copy_from_slice(&table.to_le_bytes()); + tables.push(hole); + } + Ok(tables) +} + +/// The device address of `hole`'s slot table of the `command`th command of the replay laid out +/// in `layout` at device address `address`. +fn table_address( + (address, layout): (u64, &DrawReplayLayout), + hole: &TableHole, + command: u32, +) -> u64 { + address + + match hole.table { + Table::Vertex => layout.vertex_table_offset(command), + Table::Fragment => layout.fragment_table_offset(command), + } +} + /// A draw replay's draws, which the encoder that records an execution's GPU form records in /// place of its draw's own (`RenderCommandEncoder::draw`): every command's of the range, the /// first through the draw's recording. @@ -256,47 +343,18 @@ impl ReplayedDraws { holes: &[PushHole], pushes: &mut [PushWrite], ) -> Result, Error> { - let mut tables = Vec::new(); - for hole in holes { - let PushHole::RootTableAddress { stages, offset } = *hole else { - continue; - }; - if self.layout.merged.is_some() { - return Err(internal("a merged draw's slot table at a hole")); - } - let stages: vk::ShaderStageFlags = stages.into(); - let table = match stages { - vk::ShaderStageFlags::VERTEX => Table::Vertex, - vk::ShaderStageFlags::FRAGMENT => Table::Fragment, - _ => return Err(internal("a replayed draw's slot table of several stages")), - }; - let hole = TableHole { - stages, - offset, - table, - }; - let write = pushes - .iter_mut() - .find(|(of, start, bytes)| { - *of == stages - && *start <= offset - && offset as usize + 8 <= *start as usize + bytes.len() - }) - .ok_or_else(|| internal("no push write covers a replayed draw's slot table"))?; - let at = (offset - write.1) as usize; - write.2[at..at + 8].copy_from_slice(&self.table(&hole, 0).to_le_bytes()); - tables.push(hole); + let at_hole = holes + .iter() + .any(|hole| matches!(hole, PushHole::RootTableAddress { .. })); + if at_hole && self.layout.merged.is_some() { + return Err(internal("a merged draw's slot table at a hole")); } - Ok(tables) + fill_tables((self.address, &self.layout), 0, holes, pushes) } /// The device address of `hole`'s slot table of the `command`th command of the range. fn table(&self, hole: &TableHole, command: u32) -> u64 { - self.address - + match hole.table { - Table::Vertex => self.layout.vertex_table_offset(command), - Table::Fragment => self.layout.fragment_table_offset(command), - } + table_address((self.address, &self.layout), hole, command) } /// Record the commands' draws: `first`, the first command's recording, then for each later @@ -374,12 +432,15 @@ impl RenderExecution { /// The execution's GPU form, settled through an encoder of `core` that records nothing, over /// the pass's `storage`, with `residency`, the command buffer's (the module docs); else the /// first rule that sends it to the host step, past those the decision `passed` over - /// (`cause.rs`). Returns the core. Announces nothing: it draws nothing. + /// (`cause.rs`). For a host step's GPU route (`routed`, `gpu_route.rs`), the merged form's + /// preprocess, whose index entries the route reads, its commands' draws settled in the + /// state's replay variant, which the step draws them in. Returns the core. Announces nothing: + /// it draws nothing. pub(super) fn gpu_form( &self, core: EncoderCore, (storage, residency): (PassStorage, &Residency), - passed: &Passed, + (passed, routed): (&Passed, bool), ) -> (EncoderCore, Result) { let (decided, primitive_type, range) = match self.gpu_commands(passed) { Ok(commands) => commands, @@ -419,33 +480,39 @@ impl RenderExecution { inputs.clone(), (pipeline, state), commands.clone(), - (true, passed), + (true, routed, passed), ); core = back; match form { Ok(form) => return (core, Ok(form)), - Err(cause) if merged_alone => return (core, Err(cause)), + Err(cause) if merged_alone || routed => return (core, Err(cause)), Err(_) => {} } } - self.form_of(core, inputs, (pipeline, state), commands, (false, passed)) + if routed { + let rule = "a GPU route's commands draw strips, which its preprocess does not merge"; + return (core, Err(HostStepCause::Rule(rule))); + } + let apart = (false, false, passed); + self.form_of(core, inputs, (pipeline, state), commands, apart) } /// The execution's GPU form for `commands`, `merged` into one draw or one draw per command, /// its `pipeline`'s graphics `state` settled through an encoder of `core` that records nothing - /// in that form's buffer forms (the merged variant or the replay variant), over the pass's - /// `storage` with `residency`; else the rule that keeps it from that form, past those the - /// decision `passed` over. Returns the core. + /// in that form's buffer forms (the merged variant or the replay variant; the replay variant + /// for a GPU route's, `routed`, whose preprocess is merged), over the pass's `storage` with + /// `residency`; else the rule that keeps it from that form, past those the decision `passed` + /// over. Returns the core. fn form_of( &self, core: EncoderCore, (storage, residency): (PassStorage, &Residency), (pipeline, state): (&RenderPipelineState, &GraphicsState), (decided, primitive_type, range): (CommandWrites, PrimitiveType, Range), - (merged, passed): (bool, &Passed), + (merged, routed, passed): (bool, bool, &Passed), ) -> (EncoderCore, Result) { let snapshot = &self.snapshot; - let forms = match merged { + let forms = match merged && !routed { true => BufferForms::Merged, false => BufferForms::Replay, }; diff --git a/crates/metal2vulkan-runtime/src/render/executions/gpu_route.rs b/crates/metal2vulkan-runtime/src/render/executions/gpu_route.rs index edbdc4e5f..4d85a7570 100644 --- a/crates/metal2vulkan-runtime/src/render/executions/gpu_route.rs +++ b/crates/metal2vulkan-runtime/src/render/executions/gpu_route.rs @@ -5,68 +5,122 @@ //! //! - **What runs first.** The step records the form's prework for each such execution of the pass //! (`RenderExecution::prework`: the head carried into a scratch of its own, the preprocess, and -//! the two merge passes). Then a copy of each one's prefix (each command's first corner in the -//! merged draw, a `u64`) and of its merged draw's two `VkDrawIndirectCommand`s into the command -//! buffer's upload arena, behind a barrier to the host. The step submits that with a fence and -//! waits for it, as for its probe (`DeferredPass::submit_probe`). The host reads those words -//! alone, no record (`WorkCounts::indirect_records_read`). -//! - **Its commands' draws.** Each command that draws is one direct draw of its corners in the -//! state's merged variant (`BufferForms::Merged`), with the merged replay's header pushed -//! (`PushHole::MergedDrawAddress`): corners `[first, next)`, the prefix's, the last command's -//! next the total. Its vertex function finds the command, its vertex and its instance as the -//! merged draw's does (`bind::replay`'s merged docs): its `VertexIndex` is the corner, as in a -//! merged draw's first draw's first instance (a total below `MERGED_CHUNK`). The probe and the +//! the two merge passes). Then a copy of each one's arguments (each command's +//! `VkDrawIndirectCommand`, zero for a command that draws nothing) and index entries (the device +//! address of each command's first index and its index size, `bind::DRAW_INDEX_ENTRY_BYTES`) +//! into the command buffer's upload arena, behind a barrier to the host. The step submits that +//! with a fence and waits for it, as for its probe (`DeferredPass::submit_probe`). The host +//! reads those words alone, no record (`WorkCounts::indirect_records_read`). +//! - **Its commands' draws.** Each command that draws is drawn as the host step draws a command +//! it read (`RenderExecution::replay`): a draw of primitives, or an indexed draw of the index +//! buffer the host resolves the index entry's address to (the resident set's range that holds +//! it gives its Metal address, which resolves as a record's does), with its index count, +//! instances, base vertex and base instance. It runs in the state's replay variant +//! (`BufferForms::Replay`), whose vertex and fragment functions read the command's buffers in +//! the slot tables its preprocess wrote, at the addresses its draws push +//! (`PushHole::RootTableAddress`, [`CommandTables`](super::CommandTables)). Its vertex reuse, +//! `vertex_id`, `instance_id` and primitive order are an indexed draw's. The probe and the //! routes take those draws as they take the draws of the commands the host read -//! (`render/fan_out.rs`): probed, then fanned out, boxed, in parts or region by region. Vulkan -//! rasterizes one draw's primitives in instance order, then in order within an instance -//! ("Primitive Order"), and the draws in order, so a pixel takes the commands' fragments in the -//! commands' order and each command's in its own, as the merged draw's. `commit`'s settle of -//! the pass finds the same executions (`DeferredPass::route_forms`) and begins the merged -//! variants' `VkPipeline`s of their draws, the probe's and the fan-out's on the device's pool -//! (`DeferredPass::settle`), so the step makes none of them itself +//! (`render/fan_out.rs`): probed, then fanned out, boxed, in parts or region by region, and an +//! indexed one cut into ranges of its indices as any is (`rate_mapped_pass.rs`, **Pieces**). +//! `commit`'s settle of the pass finds the same executions (`DeferredPass::route_forms`) and +//! begins the replay variants' `VkPipeline`s of their draws, the probe's and the fan-out's, on +//! the device's pool (`DeferredPass::settle`), so the step makes none of them itself //! (`WorkCounts::host_step_pipelines_made`). -//! - **Where the host reads the records instead**, as without the route: a total of -//! `MERGED_CHUNK` corners or more, a prefix that does not rise to the total, and a step whose -//! prework did not complete. +//! - **Where the host reads the records instead**, as without the route: an index size the +//! preprocess does not write, an index entry's address in no range of the resident set, and a +//! step whose prework did not complete. //! - **What the pass holds.** The scratch, the head and the live buffers' table its resident set's //! ranges lie in, until the command buffer completes. The prework's resident set is the command //! buffer's as the step resolves it (`residency.rs`), as the host's read resolves the records' //! addresses, so no first submission points it again (`command_buffer/first_submission.rs`). //! - Counted: `WorkCounts::rate_map_gpu_routes` and `rate_map_gpu_route_wait_nanos`. -use std::ops::Range; use std::sync::Arc; use std::time::Instant; +use super::super::{Assembly, IndexedDraw}; use super::cause::Passed; -use super::gpu::{GpuForm, Prework, RATE_MAP}; -use super::{DeferredPass, HostStepCause, StepCommands, StepDraws}; +use super::gpu::{CommandTables, GpuForm, Prework, RATE_MAP}; +use super::{DeferredPass, Draw, HostStepCause, StepCommands, StepDraws}; use crate::blit::{reads, writes}; use crate::command_buffer::CommandBuffer; use crate::encoder::{EncoderCore, RecordedSegment}; use crate::error::{internal, Error}; +use crate::render_values::DrawPrimitiveType; use crate::residency::Residency; use crate::tracker::Barrier; use crate::upload::Upload; use ash::vk; -use metal2vulkan::bind::{ReplayFaults, DRAW_ARGUMENT_BYTES}; -use metal2vulkan::metal::PrimitiveType; +use metal2vulkan::bind::{ + DrawCall, ReplayFaults, ResidentRange, DRAW_ARGUMENT_BYTES, DRAW_INDEX_ENTRY_BYTES, +}; +use metal2vulkan::metal::{IndexType, PrimitiveType}; -/// An execution's GPU route at its host step, its prework run (the module docs): the merged -/// replay's header's device address, the type its commands draw, and each command that draws, its -/// corners in the merged draw, in order. +/// An execution's GPU route at its host step, its prework run (the module docs): where its +/// commands' slot tables lie, the type its commands draw, and each command that draws, its draw, +/// in order. pub(super) struct GpuRoute { - header: u64, + tables: CommandTables, primitive_type: PrimitiveType, - corners: Vec>, + draws: Vec, } impl GpuRoute { - /// Its commands as a host step's probe and routes take them: each that draws, its corners; - /// from no command the host read, with no fault the host found, and its header. + /// Its commands as a host step's probe and routes take them: each that draws, its draw; from + /// no command the host read, with no fault the host found. pub(super) fn step_commands(self) -> StepCommands { - let commands = StepDraws::Corners(self.corners, self.primitive_type); - (commands, 0, ReplayFaults::default(), Some(self.header)) + let commands = StepDraws::Routed(self.draws, self.primitive_type, self.tables); + (commands, 0, ReplayFaults::default()) + } +} + +/// A command's draw as the GPU route's preprocess decoded it (the module docs): its place in the +/// preprocess's range, whose slot tables its draws push; its vertex or index count, instances, +/// vertex start or base vertex, and base instance; and, for an indexed draw, its index type and +/// the Metal address of its first index. +#[derive(Clone, Copy)] +pub(in crate::render) struct RoutedDraw { + pub(super) command: u32, + count: u32, + instances: u32, + first: u32, + base_instance: u32, + indices: Option<(IndexType, u64)>, +} + +impl RoutedDraw { + /// Its draw of `primitive_type`, its index buffer at its Metal address, as a record's + /// (`Asked::of`). + pub(super) fn draw(&self, primitive_type: PrimitiveType) -> Draw { + match self.indices { + None => { + let draw = DrawCall::Primitives { + vertex_start: self.first, + vertex_count: self.count, + instance_count: self.instances, + base_instance: self.base_instance, + }; + Draw::Primitives(Assembly::Primitives(primitive_type), draw) + } + Some((index_type, address)) => { + let draw = IndexedDraw { + primitive_type: DrawPrimitiveType::Public(primitive_type), + index_count: self.count, + index_type, + instance_count: self.instances, + // The preprocess's first vertex of an indexed draw: Metal's base vertex. + base_vertex: i32::from_le_bytes(self.first.to_le_bytes()), + base_instance: self.base_instance, + }; + Draw::Indexed(draw, address) + } + } + } + + /// Whether it draws indices, and its count and instances (the encoder trail's). + pub(super) fn traced(&self) -> (bool, u32, u32) { + (self.indices.is_some(), self.count, self.instances) } } @@ -99,7 +153,7 @@ impl DeferredPass { continue; } let storage = self.storage.clone(); - let (back, form) = execution.gpu_form(core, (storage, residency), &passed); + let (back, form) = execution.gpu_form(core, (storage, residency), (&passed, true)); core = back; forms.push(form.ok().filter(GpuForm::merged)); } @@ -154,7 +208,7 @@ impl DeferredPass { let routes: Vec> = (recorded.into_iter()) .map(|recorded| { let (form, prework, words) = recorded?; - route(&form, &prework, &words) + route(&form, (&prework, &words), residency) }) .collect(); counts.rate_map_gpu_routes(routes.iter().flatten().count() as u64); @@ -162,10 +216,9 @@ impl DeferredPass { } } -/// Record into `core`, a segment of `command_buffer`, a copy of `form`'s prefix and its merged -/// draw's two `VkDrawIndirectCommand`s from `prework`'s scratch into an upload of the command -/// buffer's arena, after the barrier that follows the last merge pass: the upload, the prefix -/// first. +/// Record into `core`, a segment of `command_buffer`, a copy of `form`'s arguments and index +/// entries from `prework`'s scratch into an upload of the command buffer's arena, after the +/// barrier that follows the preprocess: the upload, the arguments first. fn read_back( core: &mut EncoderCore, command_buffer: &CommandBuffer, @@ -174,36 +227,37 @@ fn read_back( ) -> Result { let layout = form.layout(); let merged = (layout.merged).ok_or_else(|| internal("a GPU route that does not merge"))?; - let prefix = 8 * u64::from(layout.commands); - let draws = 2 * DRAW_ARGUMENT_BYTES; + let commands = u64::from(layout.commands); + let arguments = commands * u64::from(layout.types) * DRAW_ARGUMENT_BYTES; + let entries = commands * DRAW_INDEX_ENTRY_BYTES; let device = command_buffer.device(); - let words = (command_buffer.state().uploads).upload(device, &[], prefix + draws)?; + let words = (command_buffer.state().uploads).upload(device, &[], arguments + entries)?; let (scratch, lead) = (&prework.scratch, prework.lead); let (chunk, at) = words.buffer(); let (from, src) = scratch.at(lead); let (to, dst) = chunk.at(at); let regions = [ vk::BufferCopy { - src_offset: src + merged.prefix_offset, + src_offset: src + layout.arguments_offset, dst_offset: dst, - size: prefix, + size: arguments, }, vk::BufferCopy { - src_offset: src + merged.draws_offset, - dst_offset: dst + prefix, - size: draws, + src_offset: src + merged.indices_offset, + dst_offset: dst + arguments, + size: entries, }, ]; let uses = [ reads( scratch, - lead + merged.prefix_offset..lead + merged.prefix_offset + prefix, + lead + layout.arguments_offset..lead + layout.arguments_offset + arguments, ), reads( scratch, - lead + merged.draws_offset..lead + merged.draws_offset + draws, + lead + merged.indices_offset..lead + merged.indices_offset + entries, ), - writes(chunk, at..at + prefix + draws), + writes(chunk, at..at + arguments + entries), ]; core.command( vk::PipelineStageFlags2::TRANSFER, @@ -211,8 +265,8 @@ fn read_back( |raw, command_buffer| { // SAFETY: the segment's command buffer is recording outside a render pass; the // scratch lives until it completes (the segment holds it) and so does the upload (the - // arena); both regions lie in both: the prefix and the draws in the scratch's layout, - // and the upload holds them both. + // arena); both regions lie in both: the arguments and the entries in the scratch's + // layout, and the upload holds them both. unsafe { raw.cmd_copy_buffer(command_buffer, from, to, ®ions) }; }, ); @@ -220,42 +274,75 @@ fn read_back( } /// The route of `form`'s commands from the words its prework wrote into `words` -/// ([`read_back`]): `None` where the host reads the records instead (the module docs). -fn route(form: &GpuForm, prework: &Prework, words: &Upload) -> Option { +/// ([`read_back`]), the indices' addresses resolved in `residency`, the command buffer's, and the +/// form's live buffers: `None` where the host reads the records instead (the module docs). +fn route( + form: &GpuForm, + (prework, words): (&Prework, &Upload), + residency: &Residency, +) -> Option { let layout = form.layout(); - let merged = layout.merged?; + if layout.types != 1 { + return None; + } let commands = usize::try_from(layout.commands).ok()?; - let len = 8 * commands + 2 * DRAW_ARGUMENT_BYTES as usize; + let arguments = commands * DRAW_ARGUMENT_BYTES as usize; + let len = arguments + commands * DRAW_INDEX_ENTRY_BYTES as usize; let mut bytes = vec![0u8; len]; // SAFETY: the submission that wrote the words completed, its writes made visible to the host // by its last barrier; the bytes are writable and apart from the upload. unsafe { words.copy_out(0, bytes.as_mut_ptr(), len as u64) }; - let (prefix, draws) = bytes.split_at(8 * commands); - let word = - |at: usize| u32::from_le_bytes([draws[at], draws[at + 1], draws[at + 2], draws[at + 3]]); - // `VkDrawIndirectCommand`: `vertexCount`, `instanceCount`, `firstVertex`, `firstInstance`. - // The first draw's whole chunks, and the second's vertices. - let (chunks, rest) = (word(4), word(16)); - if chunks > 0 { - return None; - } - let total = u64::from(rest); - let firsts: Vec = (prefix.as_chunks::<8>().0.iter()) - .map(|first| u64::from_le_bytes(*first)) - .collect(); - let mut corners = Vec::new(); - for (at, &first) in firsts.iter().enumerate() { - let next = firsts.get(at + 1).copied().unwrap_or(total); - if first > next || next > total { - return None; - } - if next > first { - corners.push(u32::try_from(first).ok()?..u32::try_from(next).ok()?); + let (arguments, entries) = bytes.split_at(arguments); + // The ranges the preprocess resolved the indices' addresses in, by device address + // (`RenderExecution::preprocess`): the command buffer's resident buffers and heaps, then the + // live buffers. + let mut ranges: Vec = residency.resident_ranges(); + ranges.extend(form.live().ranges()); + ranges.sort_by_key(|range| range.host); + // The Metal address of device address `address`: of the nearest range below that holds it, + // an address at a range's end included, as a record's resolves. + let guest = |address: u64| { + let below = ranges.partition_point(|range| range.host <= address); + (ranges[..below].iter().rev()) + .find(|range| address - range.host <= range.length) + .map(|range| range.guest + (address - range.host)) + }; + let word = |bytes: &[u8], at: usize| { + u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) + }; + let mut draws = Vec::new(); + let arguments = arguments.as_chunks::<{ DRAW_ARGUMENT_BYTES as usize }>().0; + let entries = entries.as_chunks::<{ DRAW_INDEX_ENTRY_BYTES as usize }>().0; + for (command, (argument, entry)) in arguments.iter().zip(entries).enumerate() { + // `VkDrawIndirectCommand`: `vertexCount`, `instanceCount`, `firstVertex`, + // `firstInstance`; an indexed draw's index count and base vertex. + let [count, instances, first, base_instance] = [0, 4, 8, 12].map(|at| word(argument, at)); + if count == 0 || instances == 0 { + continue; } + // The entry: its first index's device address, the indices from there to the buffer's + // end, and the index size. + let mut address = [0u8; 8]; + address.copy_from_slice(&entry[..8]); + let address = u64::from_le_bytes(address); + let indices = match word(entry, 12) { + 0 => None, + 2 => Some((IndexType::UInt16, guest(address)?)), + 4 => Some((IndexType::UInt32, guest(address)?)), + _ => return None, + }; + draws.push(RoutedDraw { + command: u32::try_from(command).ok()?, + count, + instances, + first, + base_instance, + indices, + }); } Some(GpuRoute { - header: prework.address + merged.header_offset, + tables: CommandTables::new(prework.address, *layout), primitive_type: form.primitive_type(), - corners, + draws, }) } diff --git a/crates/metal2vulkan-runtime/src/render/fan_out.rs b/crates/metal2vulkan-runtime/src/render/fan_out.rs index 6271a1092..2253a625b 100644 --- a/crates/metal2vulkan-runtime/src/render/fan_out.rs +++ b/crates/metal2vulkan-runtime/src/render/fan_out.rs @@ -519,15 +519,13 @@ impl FanOutRun { /// The routes of an execution's commands at its host step (the module docs): the commands as the /// step read them, once, for the probe and the routes alike, from command `start`, or its GPU -/// route's (`render/executions/gpu_route.rs`); the faults the read found; a GPU route's merged -/// replay's header's device address; the index of each command's draw among the probe's, by its -/// place among the commands that run, where it was probed; and what the probe found of each draw -/// it probed, by its index. +/// route's (`render/executions/gpu_route.rs`); the faults the read found; the index of each +/// command's draw among the probe's, by its place among the commands that run, where it was +/// probed; and what the probe found of each draw it probed, by its index. pub(super) struct FanOutRoutes { pub(super) commands: StepDraws, pub(super) start: u32, pub(super) faults: ReplayFaults, - pub(super) header: Option, pub(super) slots: Vec>, pub(super) probed: Arc<[Probed]>, } diff --git a/crates/metal2vulkan-runtime/src/tests/rate_mapped_gpu_route.rs b/crates/metal2vulkan-runtime/src/tests/rate_mapped_gpu_route.rs index 3234eb853..b9f06d6d5 100644 --- a/crates/metal2vulkan-runtime/src/tests/rate_mapped_gpu_route.rs +++ b/crates/metal2vulkan-runtime/src/tests/rate_mapped_gpu_route.rs @@ -1,8 +1,9 @@ //! A rate-mapped pass's executed commands at a host step, through the execution's GPU route //! (`render/executions/gpu_route.rs`): the records the GPU may write, of a buffer that inherits //! the encoder's pipeline state, are decoded on the GPU, and the host reads none of them -//! (`WorkCounts::indirect_records_read`), only each command's corners, which it probes and routes -//! as it routes the commands it reads (`render/fan_out.rs`). Every command but three draws a grid +//! (`WorkCounts::indirect_records_read`), only each command's draw arguments and index buffer, and +//! it draws each command as decoded, indexed where it is, probed and routed as it routes the +//! commands it reads (`render/fan_out.rs`). Every command but three draws a grid //! of small triangles twice, one of them in two instances; one draws a triangle over the whole //! target, another a triangle over four tiles a side, and two the grid with two of its triangles //! far apart, one with indices and one without, so the probe flags three. Each command's positions @@ -396,9 +397,20 @@ fn route_counts(before: &WorkCounts, after: &WorkCounts) -> [u64; 4] { ] } +/// The indexed draws recorded between two counts, direct, multi and indirect. +fn indexed_draws(before: &WorkCounts, after: &WorkCounts) -> u64 { + let indexed = |counts: &WorkCounts| { + let recorded = &counts.commands_recorded; + recorded.cmd_draw_indexed + + recorded.cmd_draw_multi_indexed + + recorded.cmd_draw_indexed_indirect + }; + indexed(after) - indexed(before) +} + /// On a device that fans out, the host step records the execution through its GPU route: it -/// reads no record, probes the commands' corners once and flags the three draws that touch more -/// regions than the fan-out's copies. Elsewhere it reads the records. Either way the colour and the +/// reads no record, probes the commands' draws once, indexed where they are, and flags the three +/// that touch more regions than the fan-out's copies. Elsewhere it reads the records. Either way the colour and the /// depth are the encoder's draws', bit for bit. #[test] fn a_gpu_route_draws_the_encoder_s_pixels_and_depth_reading_no_record() { @@ -417,10 +429,11 @@ fn a_gpu_route_draws_the_encoder_s_pixels_and_depth_reading_no_record() { let parted = after.rate_map_parted_draws - before.rate_map_parted_draws; let copies = after.rate_map_region_copy_draws - before.rate_map_region_copy_draws; let boxed = after.rate_map_boxed_draws - before.rate_map_boxed_draws; + let indexed = indexed_draws(&before, &after); eprintln!( "RATE-MAP-GPU-ROUTE records read, routes, probes, flagged {counts:?}; waited {wait} ns; \ {fanned} fanned, {parted} in parts, {copies} through the region-copy variant, {boxed} \ - boxed" + boxed; {indexed} indexed draws recorded" ); match fans_out(&workload.device) { true => { @@ -430,6 +443,8 @@ fn a_gpu_route_draws_the_encoder_s_pixels_and_depth_reading_no_record() { "records read, routes, probes, flagged" ); assert!(wait > 0, "the host's wait for the route's prework"); + // Seven of the eight commands draw indices: the route draws them indexed. + assert!(indexed > 0, "indexed draws of the route's commands"); } false => assert_eq!(counts[1..], [0; 3], "routes, probes, flagged"), } @@ -452,27 +467,34 @@ fn a_gpu_route_draws_the_encoder_s_pixels_and_depth_reading_no_record() { /// The host step of an execution its GPU route takes makes no `VkPipeline` itself /// (`WorkCounts::host_step_pipelines_made`), at the execution's first frame or after: `commit`'s -/// settle began the merged variants' of the step's draws, the probe's and the fan-out's -/// (`DeferredPass::settle`). On a device that does not fan out, the step reads the records, and -/// the settle's large-buffer form is what it draws in. +/// settle began the replay variants' of the step's draws, the probe's and the fan-out's +/// (`DeferredPass::settle`). After the first frame nothing makes one at all +/// (`WorkCounts::variant_pipelines_made`): the state keeps the variants its frames draw. On a +/// device that does not fan out, the step reads the records, and the settle's large-buffer form +/// is what it draws in. #[test] fn a_gpu_route_s_host_step_makes_no_pipeline() { let scratch = Scratch::new("rate-mapped-gpu-route-made"); let workload = Workload::new(device_under(&scratch.0, RateMapRegionPolicy::FanOut)); let fans = fans_out(&workload.device); - for frame in ["first", "second"] { + for (at, frame) in ["first", "second", "third"].into_iter().enumerate() { let (_, _, before, after) = workload.frame(true); let routes = route_counts(&before, &after)[1]; let made = after.host_step_pipelines_made - before.host_step_pipelines_made; + let variants = after.variant_pipelines_made - before.variant_pipelines_made; let ready = after.rate_map_fan_out_pipelines_ready - before.rate_map_fan_out_pipelines_ready; let waited = after.rate_map_fan_out_pipelines_waited - before.rate_map_fan_out_pipelines_waited; eprintln!( "RATE-MAP-GPU-ROUTE-MADE {frame} frame: {routes} routes; the step made {made} \ - pipelines, found {ready} of the fan-out's ready and waited for {waited}" + pipelines, found {ready} of the fan-out's ready and waited for {waited}; {variants} \ + made in all" ); assert_eq!(routes, u64::from(fans), "{frame} frame: executions routed"); assert_eq!(made, 0, "{frame} frame: pipelines the host step made"); + if at > 0 { + assert_eq!(variants, 0, "{frame} frame: pipelines made at all"); + } } } diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 68908bb13..8ffcaab1c 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -8104,8 +8104,7 @@ pub struct WorkCounts { /// **Pieces**). pub rate_map_pieces: u64, /// Ranges past the first that executed commands' draws in rate-mapped passes were drawn as, - /// each a range of the draw's indices (or of a GPU route's command's corners, - /// `render/executions/gpu_route.rs`) drawn as a draw of its own, so a piece may begin between + /// each a range of the draw's indices drawn as a draw of its own, so a piece may begin between /// them: a draw that alone would hold more than a piece's work (`rate_mapped_pass.rs`, /// **Pieces**). pub rate_map_index_ranges: u64, @@ -8158,7 +8157,7 @@ pub struct WorkCounts { /// Executions of such passes a host step recorded in their GPU route /// (`render/executions/gpu_route.rs`): an execution whose records the GPU may write, and /// which takes its merged GPU form but for the pass's rate map, has its records decoded on - /// the GPU and its commands' corners read back, so the host reads none of its records + /// the GPU and its commands' draw arguments read back, so the host reads none of its records /// ([`indirect_records_read`](Self::indirect_records_read)). Its commands are probed and /// routed as the records the host reads are. pub rate_map_gpu_routes: u64, diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index 358b162cd..c4e670e66 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -274,8 +274,8 @@ pub use rate_map::{ RateMapRegion, RateMapRegions, RegionError, RegionLimits, UnpinnedCompile, MAX_SCREEN_EXTENT, }; pub use replay::{ - draw_merge_module, DrawMergeModule, MergePhase, MergedLayout, MERGED_CHUNK, - MERGED_HEADER_BYTES, MERGED_REST_FIRST, + draw_merge_module, DrawMergeModule, MergePhase, MergedLayout, DRAW_INDEX_ENTRY_BYTES, + MERGED_CHUNK, MERGED_HEADER_BYTES, MERGED_REST_FIRST, }; pub use replay::{ draw_replay_draw, draw_replay_indexed, draw_replay_merges, draw_replay_primitive_type, diff --git a/crates/metal2vulkan/src/bind/replay.rs b/crates/metal2vulkan/src/bind/replay.rs index ce2dd0131..9fd4ab046 100644 --- a/crates/metal2vulkan/src/bind/replay.rs +++ b/crates/metal2vulkan/src/bind/replay.rs @@ -157,8 +157,8 @@ mod flat; pub use flat::{flat_dispatch_module, FlatArguments, FlatDispatchModule, FlatIndirect}; mod merged; pub use merged::{ - draw_merge_module, DrawMergeModule, MergePhase, MergedLayout, MERGED_CHUNK, - MERGED_HEADER_BYTES, MERGED_REST_FIRST, + draw_merge_module, DrawMergeModule, MergePhase, MergedLayout, DRAW_INDEX_ENTRY_BYTES, + MERGED_CHUNK, MERGED_HEADER_BYTES, MERGED_REST_FIRST, }; pub(crate) use merged::{merged_fragment_table, merged_vertex, MergedVertex}; mod predication; diff --git a/crates/metal2vulkan/src/bind/replay/merged.rs b/crates/metal2vulkan/src/bind/replay/merged.rs index 2a0a97b3e..553cb828c 100644 --- a/crates/metal2vulkan/src/bind/replay/merged.rs +++ b/crates/metal2vulkan/src/bind/replay/merged.rs @@ -104,10 +104,11 @@ pub const MERGED_CHUNK: u32 = (1 << 31) - 2; pub const MERGED_REST_FIRST: u32 = 1 << 31; /// Bytes of a merged draw's header. pub const MERGED_HEADER_BYTES: u64 = 56; -/// Bytes of one command's index entry (the module docs): the device address of its first index -/// (`u64`), the whole indices from there to its index buffer's end (`u32`) and the index size -/// (`u32`: 2, 4, or 0 for a draw without indices). -pub(super) const DRAW_INDEX_ENTRY_BYTES: u64 = 16; +/// Bytes of one command's index entry (the module docs), from [`MergedLayout::indices_offset`] +/// in command order: the device address of its first index (`u64`), the whole indices from there +/// to its index buffer's end (`u32`) and the index size (`u32`: 2, 4, or 0 for a draw without +/// indices). +pub const DRAW_INDEX_ENTRY_BYTES: u64 = 16; // The header's words, in bytes from its start. The consumer writes all but `H_CHUNKS`, which the // last pass writes; every `*_AT` is an offset from the header. diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index cc065b9c5..921127c03 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 = 523; /// 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 = 2328; +pub const RUNTIME_VERSION: u32 = 2329; /// 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 9a21980e3..348e3a312 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1041,6 +1041,7 @@ const metal2vulkan-runtime::MAX_COLOR_ATTACHMENTS pub const MAX_COLOR_ATTACHMENT const metal2vulkan-runtime::NIL_PATCH_BUFFER_ADDRESS pub const NIL_PATCH_BUFFER_ADDRESS: u64 const metal2vulkan::bind::ARGUMENT_HANDLE_BYTES pub const ARGUMENT_HANDLE_BYTES: u64 const metal2vulkan::bind::DRAW_ARGUMENT_BYTES pub const DRAW_ARGUMENT_BYTES: u64 +const metal2vulkan::bind::DRAW_INDEX_ENTRY_BYTES pub const DRAW_INDEX_ENTRY_BYTES: u64 const metal2vulkan::bind::DRAW_REPLAY_WRITES pub const DRAW_REPLAY_WRITES: u32 const metal2vulkan::bind::GEOMETRY_NO_DUPLICATE_ANY_HIT_INVOCATION pub const GEOMETRY_NO_DUPLICATE_ANY_HIT_INVOCATION: u32 const metal2vulkan::bind::GEOMETRY_OPAQUE pub const GEOMETRY_OPAQUE: u32 @@ -1125,6 +1126,7 @@ const-value metal2vulkan-runtime::MAX_COLOR_ATTACHMENTS 8 const-value metal2vulkan-runtime::NIL_PATCH_BUFFER_ADDRESS 0x1_eeee_1111 const-value metal2vulkan::bind::ARGUMENT_HANDLE_BYTES 8 const-value metal2vulkan::bind::DRAW_ARGUMENT_BYTES 16 +const-value metal2vulkan::bind::DRAW_INDEX_ENTRY_BYTES 16 const-value metal2vulkan::bind::DRAW_REPLAY_WRITES CommandWrites::DRAW | CommandWrites::BUFFER | CommandWrites::RESET | CommandWrites::CLEAR_BARRIER const-value metal2vulkan::bind::GEOMETRY_NO_DUPLICATE_ANY_HIT_INVOCATION 0x2 const-value metal2vulkan::bind::GEOMETRY_OPAQUE 0x1 diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 9fb30f55c..c85353ab0 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -620,6 +620,7 @@ surface! { struct DrawMergeModule N; enum MergePhase E; struct MergedLayout N; + const DRAW_INDEX_ENTRY_BYTES; const MERGED_CHUNK; const MERGED_HEADER_BYTES; const MERGED_REST_FIRST; diff --git a/docs/API.md b/docs/API.md index e07ba87db..34f4f36c3 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2713,9 +2713,9 @@ bound. that VkPipeline then, as does a render command's draw of a state the CPU set on none of the commands. In a rate-mapped pass whose host step fans its triangles out, a render execution kept from the GPU alone by the rate map alone has its records decoded on the GPU at the step, which - reads back each command's corners and none of its records, and its commands run in their merged - variant (`WorkCounts::rate_map_gpu_routes`): a second round trip, for the decode, comes before - the probe's. Other commands run in the large-buffer form (their range-limited buffer slots at device + reads back each command's draw arguments and index buffer and none of its records, and each + command is drawn in its replay variant, indexed where it is (`WorkCounts::rate_map_gpu_routes`): + a second round trip, for the decode, comes before the probe's. Other commands run in the large-buffer form (their range-limited buffer slots at device addresses, with in-shader bounds checks), whose variants the commit compiles for every pipeline state a record may name (for a render execution, every state the CPU set on its commands; or, for an execution committed before a route that may write the records met the buffer, the call