diff --git a/crates/metal2vulkan-runtime/Cargo.toml b/crates/metal2vulkan-runtime/Cargo.toml index 9bb8fd8d9..fa40f5540 100644 --- a/crates/metal2vulkan-runtime/Cargo.toml +++ b/crates/metal2vulkan-runtime/Cargo.toml @@ -136,6 +136,18 @@ path = "examples/pass_costs.rs" name = "dispatch_chain" path = "examples/dispatch_chain.rs" +# Not a consumer's example: what the GPU pays a draw for reading the draw's own data in the +# command buffer's upload arena, by what its fragment function reads (examples/draw_reads.rs). +[[example]] +name = "draw_reads" +path = "examples/draw_reads.rs" + +# Not a consumer's example: what an indirect command buffer's records cost the GPU and the host, +# written by a kernel or the CPU and executed by a render pass (examples/icb_reads.rs). +[[example]] +name = "icb_reads" +path = "examples/icb_reads.rs" + [dependencies] # The translator, through its public API only: the compiler checks that the runtime # reaches nothing else. `ash` gives `ash_interop`'s conversions and `DeviceDescription::query`. diff --git a/crates/metal2vulkan-runtime/examples/draw_reads.rs b/crates/metal2vulkan-runtime/examples/draw_reads.rs new file mode 100644 index 000000000..22acf1563 --- /dev/null +++ b/crates/metal2vulkan-runtime/examples/draw_reads.rs @@ -0,0 +1,425 @@ +//! Not a consumer's example: what the GPU pays a draw for reading the draw's own data, the tables +//! and bytes the runtime writes into the command buffer's upload arena (`upload.rs`), by what the +//! draw's fragment function reads. +//! +//! ```sh +//! cargo run --release -p metal2vulkan-runtime --example draw_reads -- \ +//! [--draws N] [--tile T] [--side S] [--runs R] [--only READS,...] +//! ``` +//! +//! Each run is one command buffer of one render pass over an `S` by `S` `RGBA8Unorm` target +//! (1024 by default), cleared and stored, of `N` draws (2048 by default), each a 4-vertex +//! triangle strip over the next `T` by `T` tile of the target (64 by default), in rows. Each draw +//! sets its tile's corner and side as vertex bytes at index 0, which `tile_vertex` reads, then +//! what its fragment function reads at fragment index 0, by `READS`: +//! +//! - **`bytes`**: its color, as fragment bytes (`direct_fragment`, a `constant float4`); +//! - **`direct`**: the color, at the next of 256 slots of a `Private` buffer +//! (`set_fragment_buffer`, `direct_fragment`); +//! - **`ptr`**: the address of that color, at the next of 256 slots of another `Private` buffer +//! (`holder_fragment`: a `Holder` of one pointer, as an argument buffer holds a material's +//! parameters): every fragment loads the pointer and reads the color through it, which the +//! resident set resolves (`metal2vulkan::bind::ResidentSet`). +//! +//! Every color is opaque magenta, and once a kind's runs ended its target is read back: every +//! texel must hold it. +//! +//! Each line is the median over `R` runs (9 by default) after one not counted, of the command +//! buffer's GPU time (`gpu_start_time` to `gpu_end_time`) a draw, with the runtime's counts a +//! command buffer that moved over the counted runs (`WorkCounts`, by name from their `Debug` +//! form): +//! +//! ```text +//! DRAW-READS draws tile side gpu_us_per_draw least +//! DRAW-READS-COUNTS = ... +//! ``` +//! +//! The functions are LLVM text here, assembled by `llvm-as` from `PATH`. + +use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; +use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; +use metal2vulkan_runtime::{ + BlitOption, Buffer, ClearColor, CommandBuffer, CommandBufferStatus, Device, LoadAction, Origin, + PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, StoreAction, + Texture, TextureDescriptor, WorkCounts, +}; +use std::collections::BTreeMap; +use std::io::Write; +use std::process::{Command, Stdio}; +use std::time::Duration; + +/// The example's result: every runtime refusal is a typed `metal2vulkan_runtime::Error`. +type Result = std::result::Result>; + +/// The longest the example waits for a command buffer. +const WAIT: Duration = Duration::from_secs(60); + +/// The slots of the colors' buffer and of the holders' buffer. +const SLOTS: u64 = 256; + +/// Every draw's color: opaque magenta, exact in `RGBA8Unorm`. +const COLOR: [f32; 4] = [1.0, 0.0, 1.0, 1.0]; +const TEXEL: [u8; 4] = [255, 0, 255, 255]; + +/// `tile_vertex`: vertex `id`'s corner of the tile `rect` (x, y, width, height in normalized +/// device coordinates) sets at index 0; `direct_fragment`: the `float4` at fragment index 0; +/// `holder_fragment`: the `float4` the pointer of the `Holder` at fragment index 0 points at. +const FUNCTIONS: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ +target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ +%struct.Holder = type { ptr addrspace(1) }\n\n\ +define <4 x float> @tile_vertex(ptr addrspace(2) noundef %rect, i32 noundef %id) {\n\ +entry:\n\ + %r = load <4 x float>, ptr addrspace(2) %rect, align 16\n\ + %bx = and i32 %id, 1\n\ + %by = lshr i32 %id, 1\n\ + %fx = call float @air.convert.f.f32.u.i32(i32 %bx)\n\ + %fy = call float @air.convert.f.f32.u.i32(i32 %by)\n\ + %x0 = extractelement <4 x float> %r, i64 0\n\ + %y0 = extractelement <4 x float> %r, i64 1\n\ + %w = extractelement <4 x float> %r, i64 2\n\ + %h = extractelement <4 x float> %r, i64 3\n\ + %dx = fmul float %fx, %w\n\ + %dy = fmul float %fy, %h\n\ + %x = fadd float %x0, %dx\n\ + %y = fadd float %y0, %dy\n\ + %p0 = insertelement <4 x float> , float %x, i64 0\n\ + %p = insertelement <4 x float> %p0, float %y, i64 1\n\ + ret <4 x float> %p\n\ +}\n\n\ +define <4 x float> @direct_fragment(ptr addrspace(2) noundef %c) {\n\ +entry:\n\ + %v = load <4 x float>, ptr addrspace(2) %c, align 16\n\ + ret <4 x float> %v\n\ +}\n\n\ +define <4 x float> @holder_fragment(ptr addrspace(1) noundef readonly %h) {\n\ +entry:\n\ + %hp = getelementptr inbounds %struct.Holder, ptr addrspace(1) %h, i64 0, i32 0\n\ + %b = load ptr addrspace(1), ptr addrspace(1) %hp, align 8\n\ + %v = load <4 x float>, ptr addrspace(1) %b, align 16\n\ + ret <4 x float> %v\n\ +}\n\n\ +declare float @air.convert.f.f32.u.i32(i32)\n\n\ +!llvm.module.flags = !{!0, !1}\n!air.vertex = !{!20}\n!air.fragment = !{!30, !40}\n\ +!air.version = !{!8}\n!air.language_version = !{!9}\n\ +!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n\ +!1 = !{i32 7, !\"air.max_constant_buffers\", i32 31}\n\ +!8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\ +!20 = !{ptr @tile_vertex, !21, !23}\n\ +!21 = !{!22}\n\ +!22 = !{!\"air.position\", !\"air.arg_type_name\", !\"float4\"}\n\ +!23 = !{!24, !25}\n\ +!24 = !{i32 0, !\"air.buffer\", !\"air.buffer_size\", i32 16, !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 2, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"rect\"}\n\ +!25 = !{i32 1, !\"air.vertex_id\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"id\"}\n\ +!26 = !{!27}\n\ +!27 = !{!\"air.render_target\", i32 0, i32 0, !\"air.arg_type_name\", !\"float4\"}\n\ +!30 = !{ptr @direct_fragment, !26, !31}\n\ +!31 = !{!32}\n\ +!32 = !{i32 0, !\"air.buffer\", !\"air.buffer_size\", i32 16, !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 2, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"c\"}\n\ +!40 = !{ptr @holder_fragment, !26, !41}\n\ +!41 = !{!42}\n\ +!42 = !{i32 0, !\"air.indirect_buffer\", !\"air.buffer_size\", i32 8, !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.struct_type_info\", !43, !\"air.arg_type_size\", i32 8, !\"air.arg_type_align_size\", i32 8, !\"air.arg_type_name\", !\"Holder\", !\"air.arg_name\", !\"h\"}\n\ +!43 = !{i32 0, i32 8, i32 0, !\"float4\", !\"p\", !\"air.indirect_argument\", !44}\n\ +!44 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"p\"}\n"; + +/// What a draw's fragment function reads. +#[derive(Clone, Copy, PartialEq)] +enum Reads { + Bytes, + Direct, + Pointer, +} + +impl Reads { + const ALL: [Reads; 3] = [Reads::Bytes, Reads::Direct, Reads::Pointer]; + + fn name(self) -> &'static str { + match self { + Reads::Bytes => "bytes", + Reads::Direct => "direct", + Reads::Pointer => "ptr", + } + } +} + +/// The run's shape: draws a command buffer, a tile's and the target's side in texels, timed runs, +/// and the kinds to run. +struct Shape { + draws: u32, + tile: u64, + side: u64, + runs: usize, + only: Vec, +} + +impl Shape { + fn from_args() -> Result { + let mut shape = Shape { + draws: 2048, + tile: 64, + side: 1024, + runs: 9, + only: Vec::new(), + }; + let mut args = std::env::args().skip(1); + while let Some(arg) = args.next() { + let mut value = || args.next().ok_or_else(|| format!("{arg} takes a value")); + match arg.as_str() { + "--draws" => shape.draws = value()?.parse()?, + "--tile" => shape.tile = value()?.parse()?, + "--side" => shape.side = value()?.parse()?, + "--runs" => shape.runs = value()?.parse()?, + "--only" => shape.only = value()?.split(',').map(str::to_owned).collect(), + other => return Err(format!("unknown argument {other}").into()), + } + } + if shape.tile == 0 || !shape.side.is_multiple_of(shape.tile) || shape.runs == 0 { + return Err("the side must be a multiple of the tile, and runs at least 1".into()); + } + Ok(shape) + } + + fn runs(&self, reads: Reads) -> bool { + self.only.is_empty() || self.only.iter().any(|name| name == reads.name()) + } + + /// Draw `n`'s tile as vertex bytes: its corner and side in normalized device coordinates. + fn rect(&self, n: u32) -> Vec { + let across = self.side / self.tile; + let tile = u64::from(n) % (across * across); + let step = 2.0 * self.tile as f32 / self.side as f32; + let x = -1.0 + step * (tile % across) as f32; + let y = -1.0 + step * (tile / across) as f32; + [x, y, step, step] + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect() + } +} + +/// Run `tool` from `PATH` over `input`: its output. +fn tool(tool: &str, args: &[&str], input: &str) -> Result> { + let mut child = Command::new(tool) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|error| format!("cannot run {tool} (put it on PATH): {error}"))?; + child + .stdin + .take() + .ok_or("no stdin")? + .write_all(input.as_bytes())?; + let output = child.wait_with_output()?; + if !output.status.success() { + return Err(format!("{tool}: {}", String::from_utf8_lossy(&output.stderr)).into()); + } + Ok(output.stdout) +} + +/// The counts of `counts` by name, read from their `Debug` form. +fn counts(counts: &WorkCounts) -> BTreeMap { + let text = format!("{counts:?}"); + text.split([',', '{']) + .filter_map(|part| { + let (name, value) = part.split_once(':')?; + Some((name.trim().to_owned(), value.trim().parse().ok()?)) + }) + .collect() +} + +/// Commit `command_buffer` and wait for it: an error where it did not complete. +fn run(command_buffer: &CommandBuffer) -> Result<()> { + command_buffer.commit()?; + command_buffer + .wait_until_completed_for(WAIT) + .map_err(|_| format!("a command buffer did not complete within {WAIT:?}"))?; + match command_buffer.status() { + CommandBufferStatus::Completed => Ok(()), + status => Err(format!( + "a command buffer ended {status:?}: {:?}", + command_buffer.error() + ) + .into()), + } +} + +/// What every run draws with. +struct Ours<'a> { + device: &'a Device, + direct: RenderPipelineState, + holder: RenderPipelineState, + target: Texture, + /// [`SLOTS`] colors of 16 bytes. + colors: Buffer, + /// [`SLOTS`] addresses of 8 bytes, each of its color. + holders: Buffer, +} + +impl Ours<'_> { + /// One command buffer of `shape`'s draws reading as `reads` says, committed and waited for: + /// its GPU time a draw in microseconds. + fn run(&self, reads: Reads, shape: &Shape) -> Result { + let queue = self.device.new_command_queue()?; + let command_buffer = queue.command_buffer()?; + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(self.target.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); + let mut encoder = command_buffer.render_command_encoder(&pass)?; + encoder.set_render_pipeline_state(match reads { + Reads::Pointer => &self.holder, + _ => &self.direct, + })?; + let bytes: Vec = COLOR.iter().flat_map(|value| value.to_le_bytes()).collect(); + for n in 0..shape.draws { + encoder.set_vertex_bytes(&shape.rect(n), 0)?; + let slot = u64::from(n) % SLOTS; + match reads { + Reads::Bytes => encoder.set_fragment_bytes(&bytes, 0)?, + Reads::Direct => encoder.set_fragment_buffer(Some(&self.colors), 16 * slot, 0)?, + Reads::Pointer => encoder.set_fragment_buffer(Some(&self.holders), 8 * slot, 0)?, + } + encoder.draw_primitives(PrimitiveType::TriangleStrip, 0, 4, 1, 0)?; + } + encoder.end_encoding()?; + run(&command_buffer)?; + let gpu = command_buffer.gpu_end_time()? - command_buffer.gpu_start_time()?; + Ok(gpu * 1e6 / f64::from(shape.draws)) + } + + /// Every texel of the target, read back, is [`TEXEL`]. + fn check(&self, reads: Reads, shape: &Shape) -> Result<()> { + let row = shape.side * 4; + let readback = self + .device + .new_buffer(row * shape.side, ResourceOptions::shared())?; + let queue = self.device.new_command_queue()?; + let command_buffer = queue.command_buffer()?; + let mut blit = command_buffer.blit_command_encoder()?; + blit.copy_from_texture_to_buffer( + &self.target, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(shape.side, shape.side, 1), + &readback, + 0, + row, + row * shape.side, + BlitOption::None, + )?; + blit.end_encoding()?; + run(&command_buffer)?; + let contents = readback.contents().ok_or("the read-back has no contents")?; + // SAFETY: `contents` holds the buffer's bytes, which no command buffer writes now. + let texels = + unsafe { std::slice::from_raw_parts(contents.as_ptr(), readback.length() as usize) }; + match texels + .as_chunks::<4>() + .0 + .iter() + .position(|texel| *texel != TEXEL) + { + None => Ok(()), + Some(at) => Err(format!( + "{}: texel {at} is {:?}, not {TEXEL:?}", + reads.name(), + &texels[4 * at..4 * at + 4] + ) + .into()), + } + } +} + +/// A `Private` buffer holding `bytes`, copied in from a `Shared` one. +fn private_with(device: &Device, bytes: &[u8]) -> Result { + let staging = device.new_buffer_with_bytes(bytes, ResourceOptions::shared())?; + let buffer = device.new_buffer(bytes.len() as u64, ResourceOptions::private())?; + let queue = device.new_command_queue()?; + let command_buffer = queue.command_buffer()?; + let mut blit = command_buffer.blit_command_encoder()?; + blit.copy_from_buffer_to_buffer(&staging, 0, &buffer, 0, bytes.len() as u64)?; + blit.end_encoding()?; + run(&command_buffer)?; + Ok(buffer) +} + +fn main() -> Result<()> { + let shape = Shape::from_args()?; + let device = Device::system_default()?; + let name = device.name().to_string(); + println!("device: {name}"); + let bitcode = tool("llvm-as", &["-o", "-", "-"], FUNCTIONS)?; + let library = device + .new_library_with_compile_library(metal2vulkan::library::Library::from_air(&bitcode)?); + let vertex = library.new_function_with_name("tile_vertex")?; + let state = |fragment: &str| -> Result { + let fragment = library.new_function_with_name(fragment)?; + let mut descriptor = + RenderPipelineDescriptor::new(StageSource::Function(vertex.function_descriptor())); + descriptor.fragment = Some(StageSource::Function(fragment.function_descriptor())); + descriptor.color_attachments[0] = + Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + Ok(device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())?) + }; + let mut target = + TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, shape.side, shape.side, false); + target.usage = TextureUsage::RENDER_TARGET; + target.resource_options = ResourceOptions::private(); + let colors: Vec = (0..SLOTS) + .flat_map(|_| COLOR) + .flat_map(|value| value.to_le_bytes()) + .collect(); + let colors = private_with(&device, &colors)?; + let holders: Vec = (0..SLOTS) + .flat_map(|slot| (colors.gpu_address().0 + 16 * slot).to_le_bytes()) + .collect(); + let ours = Ours { + device: &device, + direct: state("direct_fragment")?, + holder: state("holder_fragment")?, + target: device.new_texture(&target)?, + holders: private_with(&device, &holders)?, + colors, + }; + for reads in Reads::ALL { + if !shape.runs(reads) { + continue; + } + let mut per_draw = Vec::new(); + let mut moved: BTreeMap = BTreeMap::new(); + for run in 0..=shape.runs { + let before = counts(&device.work_counts()); + let per = ours.run(reads, &shape)?; + if run == 0 { + continue; + } + per_draw.push(per); + for (count, value) in counts(&device.work_counts()) { + let delta = value.saturating_sub(before.get(&count).copied().unwrap_or(0)); + if delta > 0 { + *moved.entry(count).or_default() += delta; + } + } + } + ours.check(reads, &shape)?; + per_draw.sort_by(f64::total_cmp); + println!( + "DRAW-READS {} draws {} tile {} side {} gpu_us_per_draw {:.3} least {:.3} {name}", + reads.name(), + shape.draws, + shape.tile, + shape.side, + per_draw[per_draw.len() / 2], + per_draw[0], + ); + let line: Vec = (moved.iter()) + .map(|(count, sum)| format!("{count}={:.2}", *sum as f64 / shape.runs as f64)) + .collect(); + println!("DRAW-READS-COUNTS {} {}", reads.name(), line.join(" ")); + } + Ok(()) +} diff --git a/crates/metal2vulkan-runtime/examples/icb_reads.rs b/crates/metal2vulkan-runtime/examples/icb_reads.rs new file mode 100644 index 000000000..7af6f9828 --- /dev/null +++ b/crates/metal2vulkan-runtime/examples/icb_reads.rs @@ -0,0 +1,514 @@ +//! Not a consumer's example: what an indirect command buffer's records cost the GPU and the host, +//! where a kernel or the CPU writes them and a render pass executes them. +//! +//! ```sh +//! cargo run --release -p metal2vulkan-runtime --example icb_reads -- \ +//! [--commands N] [--runs R] [--only SHAPE,...] [--idle S] +//! ``` +//! +//! Each shape's buffer holds `N` draw commands (8192 by default) that inherit the pipeline state, +//! each of one triangle of its own over a 1024 by 1024 `RGBA8Unorm` target (an 8 by 8 texel +//! cell's lower half, in rows), its vertices read by vertex ID from vertex buffer 0, which every +//! command binds, with fragment buffer 1 (`kernel_icb_encode_render_commands`' bindings); the +//! fragment function returns opaque magenta. The shapes: +//! +//! - **`gpu-shared`** and **`gpu-private`**: a buffer of `Shared`, or `Private`, storage whose +//! commands the owned kernel `kernel_icb_encode_render_commands` writes, one thread a command, +//! in one command buffer, and a render pass of another command buffer executes; +//! - **`cpu-shared`**: a `Shared` buffer whose commands the CPU writes through each command's +//! setters (its two buffers and its draw), then a render pass executes. +//! +//! Each line is the median over `R` runs (9 by default) after one not counted, of each command +//! buffer's GPU time (`gpu_start_time` to `gpu_end_time`) a command, the writer's (`encode`, the +//! kernel's command buffer; none for the CPU's) and the pass's (`execute`), and the host's time a +//! command in the CPU's setters (`cpu_encode`), with the runtime's counts a run that moved over +//! the counted runs (`WorkCounts`, by name from their `Debug` form). Once a shape's runs ended its +//! target is read back: every texel a triangle covers must be magenta. +//! +//! ```text +//! ICB-READS commands gpu_us_per_command encode execute +//! cpu_encode_us_per_command +//! ICB-READS-COUNTS = ... +//! ``` +//! +//! With `--idle S`, the CPU's shape first waits `S` seconds with no work on the device, then +//! writes one buffer's commands, commits its pass and waits for it, printing the longest single +//! setter call, the writes' and the commit's times and the commit to the completion: +//! +//! ```text +//! ICB-IDLE longest_setter_ms encode_ms commit_ms commit_to_completed_ms +//! ``` +//! +//! The render functions are LLVM text here and the kernel the owned fixture's (`metal2vulkan- +//! validation/fixtures/public/kernel_icb_encode_render_commands.ll`, built in), each assembled by +//! `llvm-as` from `PATH`. + +use metal2vulkan::metal::{ + IndirectCommandType, PixelFormat, PrimitiveType, RenderStages, ResourceUsage, TextureUsage, +}; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, +}; +use metal2vulkan_runtime::{ + BlitOption, Buffer, ClearColor, CommandBuffer, CommandBufferStatus, ComputePipelineState, + Device, IndirectCommandBuffer, IndirectCommandBufferDescriptor, Library, LoadAction, Origin, + PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, StoreAction, + Texture, TextureDescriptor, WorkCounts, +}; +use std::collections::BTreeMap; +use std::io::Write; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +/// The example's result: every runtime refusal is a typed `metal2vulkan_runtime::Error`. +type Result = std::result::Result>; + +/// The longest the example waits for a command buffer. +const WAIT: Duration = Duration::from_secs(60); + +/// The target's side, and a cell's. +const SIDE: u64 = 1024; +const CELL: u64 = 8; + +/// The fragment function's color, exact in `RGBA8Unorm`. +const TEXEL: [u8; 4] = [255, 0, 255, 255]; + +/// The writer: the owned fixture's kernel. +const WRITER: &str = include_str!( + "../../metal2vulkan-validation/fixtures/public/kernel_icb_encode_render_commands.ll" +); + +/// `icb_vertex`: the `float4` at vertex `id` of vertex buffer 0; `icb_fragment`: opaque magenta. +const FUNCTIONS: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ +target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ +define <4 x float> @icb_vertex(ptr addrspace(1) noundef readonly %v, i32 noundef %id) {\n\ +entry:\n\ + %i = zext i32 %id to i64\n\ + %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %v, i64 %i\n\ + %x = load <4 x float>, ptr addrspace(1) %p, align 16\n\ + ret <4 x float> %x\n\ +}\n\n\ +define <4 x float> @icb_fragment() {\n\ +entry:\n\ + ret <4 x float> \n\ +}\n\n\ +!llvm.module.flags = !{!0, !1}\n!air.vertex = !{!20}\n!air.fragment = !{!30}\n\ +!air.version = !{!8}\n!air.language_version = !{!9}\n\ +!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n\ +!1 = !{i32 7, !\"air.max_constant_buffers\", i32 31}\n\ +!8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\ +!20 = !{ptr @icb_vertex, !21, !23}\n\ +!21 = !{!22}\n\ +!22 = !{!\"air.position\", !\"air.arg_type_name\", !\"float4\"}\n\ +!23 = !{!24, !25}\n\ +!24 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"v\"}\n\ +!25 = !{i32 1, !\"air.vertex_id\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"id\"}\n\ +!26 = !{!27}\n\ +!27 = !{!\"air.render_target\", i32 0, i32 0, !\"air.arg_type_name\", !\"float4\"}\n\ +!28 = !{}\n\ +!30 = !{ptr @icb_fragment, !26, !28}\n"; + +/// A shape: who writes the commands, and the buffer's storage. +#[derive(Clone, Copy, PartialEq)] +enum Shape { + GpuShared, + GpuPrivate, + CpuShared, +} + +impl Shape { + const ALL: [Shape; 3] = [Shape::GpuShared, Shape::GpuPrivate, Shape::CpuShared]; + + fn name(self) -> &'static str { + match self { + Shape::GpuShared => "gpu-shared", + Shape::GpuPrivate => "gpu-private", + Shape::CpuShared => "cpu-shared", + } + } + + fn options(self) -> ResourceOptions { + match self { + Shape::GpuPrivate => ResourceOptions::private(), + _ => ResourceOptions::shared(), + } + } +} + +/// The run's arguments. +struct Args { + commands: u64, + runs: usize, + only: Vec, + idle: Option, +} + +impl Args { + fn parse() -> Result { + let mut parsed = Args { + commands: 8192, + runs: 9, + only: Vec::new(), + idle: None, + }; + let mut args = std::env::args().skip(1); + while let Some(arg) = args.next() { + let mut value = || args.next().ok_or_else(|| format!("{arg} takes a value")); + match arg.as_str() { + "--commands" => parsed.commands = value()?.parse()?, + "--runs" => parsed.runs = value()?.parse()?, + "--only" => parsed.only = value()?.split(',').map(str::to_owned).collect(), + "--idle" => parsed.idle = Some(value()?.parse()?), + other => return Err(format!("unknown argument {other}").into()), + } + } + let cells = (SIDE / CELL) * (SIDE / CELL); + if parsed.commands == 0 || parsed.commands > cells || parsed.runs == 0 { + return Err(format!("commands must be 1 to {cells}, and runs at least 1").into()); + } + Ok(parsed) + } + + fn runs(&self, shape: Shape) -> bool { + self.only.is_empty() || self.only.iter().any(|name| name == shape.name()) + } +} + +/// Run `tool` from `PATH` over `input`: its output. +fn tool(tool: &str, args: &[&str], input: &str) -> Result> { + let mut child = Command::new(tool) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|error| format!("cannot run {tool} (put it on PATH): {error}"))?; + child + .stdin + .take() + .ok_or("no stdin")? + .write_all(input.as_bytes())?; + let output = child.wait_with_output()?; + if !output.status.success() { + return Err(format!("{tool}: {}", String::from_utf8_lossy(&output.stderr)).into()); + } + Ok(output.stdout) +} + +/// The counts of `counts` by name, read from their `Debug` form. +fn counts(counts: &WorkCounts) -> BTreeMap { + let text = format!("{counts:?}"); + text.split([',', '{']) + .filter_map(|part| { + let (name, value) = part.split_once(':')?; + Some((name.trim().to_owned(), value.trim().parse().ok()?)) + }) + .collect() +} + +/// Commit `command_buffer` and wait for it: an error where it did not complete. +fn run(command_buffer: &CommandBuffer) -> Result<()> { + command_buffer.commit()?; + wait(command_buffer) +} + +/// Wait for `command_buffer`: an error where it did not complete. +fn wait(command_buffer: &CommandBuffer) -> Result<()> { + command_buffer + .wait_until_completed_for(WAIT) + .map_err(|_| format!("a command buffer did not complete within {WAIT:?}"))?; + match command_buffer.status() { + CommandBufferStatus::Completed => Ok(()), + status => Err(format!( + "a command buffer ended {status:?}: {:?}", + command_buffer.error() + ) + .into()), + } +} + +/// `command_buffer`'s GPU time in microseconds. +fn gpu_us(command_buffer: &CommandBuffer) -> Result { + Ok((command_buffer.gpu_end_time()? - command_buffer.gpu_start_time()?) * 1e6) +} + +/// What every run uses. +struct Ours<'a> { + device: &'a Device, + writer: ComputePipelineState, + state: RenderPipelineState, + target: Texture, + /// Three vertices a command: the lower half of its cell. + vertices: Buffer, + /// The writer's third argument, a word a thread. + out: Buffer, + commands: u64, +} + +impl Ours<'_> { + /// A new buffer of the shape's storage for the commands. + fn icb(&self, shape: Shape) -> Result { + let mut descriptor = IndirectCommandBufferDescriptor::new(); + descriptor.command_types = IndirectCommandType::DRAW; + descriptor.inherit_pipeline_state = true; + descriptor.max_vertex_buffer_bind_count = 2; + descriptor.max_fragment_buffer_bind_count = 2; + Ok(self + .device + .new_indirect_command_buffer(&descriptor, self.commands, shape.options())?) + } + + /// The kernel's writes of every command of `icb`, committed and waited for: its GPU time. + fn write_on_gpu(&self, icb: &IndirectCommandBuffer) -> Result { + let arguments = self.device.new_buffer_with_bytes( + &icb.gpu_resource_id().0.to_le_bytes(), + ResourceOptions::shared(), + )?; + let queue = self.device.new_command_queue()?; + let command_buffer = queue.command_buffer()?; + let mut encoder = command_buffer.compute_command_encoder()?; + encoder.set_compute_pipeline_state(&self.writer)?; + encoder.set_buffer(Some(&arguments), 0, 0)?; + encoder.set_buffer(Some(&self.vertices), 0, 1)?; + encoder.set_buffer(Some(&self.out), 0, 2)?; + encoder.use_resource(icb.as_resource(), ResourceUsage::WRITE)?; + encoder.dispatch_threads(Size::new(self.commands, 1, 1), Size::new(64, 1, 1))?; + encoder.end_encoding()?; + run(&command_buffer)?; + gpu_us(&command_buffer) + } + + /// The CPU's writes of every command of `icb`: the longest single call and the whole. + fn write_on_cpu(&self, icb: &IndirectCommandBuffer) -> Result<(Duration, Duration)> { + let started = Instant::now(); + let mut longest = Duration::ZERO; + let mut timed = |call: &mut dyn FnMut() -> Result<()>| -> Result<()> { + let at = Instant::now(); + call()?; + longest = longest.max(at.elapsed()); + Ok(()) + }; + for index in 0..self.commands { + let command = icb.indirect_render_command_at(index)?; + timed(&mut || Ok(command.set_vertex_buffer(Some(&self.vertices), 0, 0)?))?; + timed(&mut || Ok(command.set_fragment_buffer(Some(&self.vertices), 0, 1)?))?; + let start = 3 * index; + timed(&mut || Ok(command.draw_primitives(PrimitiveType::Triangle, start, 3, 1, 0)?))?; + } + Ok((longest, started.elapsed())) + } + + /// A render pass that executes every command of `icb`, encoded, not committed. + fn execute(&self, icb: &IndirectCommandBuffer) -> Result { + let queue = self.device.new_command_queue()?; + let command_buffer = queue.command_buffer()?; + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(self.target.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); + let mut encoder = command_buffer.render_command_encoder(&pass)?; + encoder.set_render_pipeline_state(&self.state)?; + encoder.use_resource( + self.vertices.as_resource(), + ResourceUsage::READ, + RenderStages::VERTEX, + )?; + encoder.execute_commands_in_buffer(icb, 0..self.commands)?; + encoder.end_encoding()?; + Ok(command_buffer) + } + + /// Every texel a command's triangle covers fully is [`TEXEL`]. + fn check(&self, shape: Shape) -> Result<()> { + let row = SIDE * 4; + let readback = self + .device + .new_buffer(row * SIDE, ResourceOptions::shared())?; + let queue = self.device.new_command_queue()?; + let command_buffer = queue.command_buffer()?; + let mut blit = command_buffer.blit_command_encoder()?; + blit.copy_from_texture_to_buffer( + &self.target, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(SIDE, SIDE, 1), + &readback, + 0, + row, + row * SIDE, + BlitOption::None, + )?; + blit.end_encoding()?; + run(&command_buffer)?; + let contents = readback.contents().ok_or("the read-back has no contents")?; + // SAFETY: `contents` holds the buffer's bytes, which no command buffer writes now. + let texels = + unsafe { std::slice::from_raw_parts(contents.as_ptr(), readback.length() as usize) }; + let across = SIDE / CELL; + for command in 0..self.commands { + // Texel (1, 6) of the cell, in Metal's rows from the top: inside the lower half's + // triangle (`vertices`) whatever the rasterizer's rules for its edges. + let (cx, cy) = (command % across, command / across); + let x = cx * CELL + 1; + let y = SIDE - 1 - (cy * CELL + 1); + let at = ((y * SIDE + x) * 4) as usize; + if texels[at..at + 4] != TEXEL { + return Err(format!( + "{}: command {command}'s texel ({x}, {y}) is {:?}, not {TEXEL:?}", + shape.name(), + &texels[at..at + 4] + ) + .into()); + } + } + Ok(()) + } +} + +/// The library of the LLVM text `text`, assembled by `llvm-as`. +fn library(device: &Device, text: &str) -> Result { + let bitcode = tool("llvm-as", &["-o", "-", "-"], text)?; + let library = metal2vulkan::library::Library::from_air(&bitcode)?; + Ok(device.new_library_with_compile_library(library)) +} + +/// `bytes` in a new `Private` buffer, copied in from a `Shared` one. +fn private_with(device: &Device, bytes: &[u8]) -> Result { + let staging = device.new_buffer_with_bytes(bytes, ResourceOptions::shared())?; + let buffer = device.new_buffer(bytes.len() as u64, ResourceOptions::private())?; + let queue = device.new_command_queue()?; + let command_buffer = queue.command_buffer()?; + let mut blit = command_buffer.blit_command_encoder()?; + blit.copy_from_buffer_to_buffer(&staging, 0, &buffer, 0, bytes.len() as u64)?; + blit.end_encoding()?; + run(&command_buffer)?; + Ok(buffer) +} + +/// Three vertices a command, in normalized device coordinates: its cell's lower half, the cells in +/// rows from the bottom left. +fn vertices(commands: u64) -> Vec { + let across = SIDE / CELL; + let step = 2.0 * CELL as f32 / SIDE as f32; + (0..commands) + .flat_map(|command| { + let x = -1.0 + step * (command % across) as f32; + let y = -1.0 + step * (command / across) as f32; + [[x, y], [x + step, y], [x, y + step]] + }) + .flat_map(|[x, y]| [x, y, 0.0, 1.0]) + .flat_map(f32::to_le_bytes) + .collect() +} + +fn main() -> Result<()> { + let args = Args::parse()?; + let device = Device::system_default()?; + let name = device.name().to_string(); + println!("device: {name}"); + let functions = library(&device, FUNCTIONS)?; + let mut descriptor = RenderPipelineDescriptor::new(StageSource::Function( + functions + .new_function_with_name("icb_vertex")? + .function_descriptor(), + )); + descriptor.fragment = Some(StageSource::Function( + functions + .new_function_with_name("icb_fragment")? + .function_descriptor(), + )); + descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + descriptor.support_indirect_command_buffers = true; + let state = device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())?; + let writer = library(&device, WRITER)?; + let writer = ComputePipelineDescriptor::new(StageSource::Function( + writer + .new_function_with_name("kernel_icb_encode_render_commands")? + .function_descriptor(), + )); + let writer = device.new_compute_pipeline_state(&writer, &PipelineOptions::default())?; + let mut target = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + target.usage = TextureUsage::RENDER_TARGET; + target.resource_options = ResourceOptions::private(); + let ours = Ours { + device: &device, + writer, + state, + target: device.new_texture(&target)?, + vertices: private_with(&device, &vertices(args.commands))?, + out: device.new_buffer(4 * args.commands, ResourceOptions::private())?, + commands: args.commands, + }; + if let Some(seconds) = args.idle { + let icb = ours.icb(Shape::CpuShared)?; + std::thread::sleep(Duration::from_secs(seconds)); + let (longest, encode) = ours.write_on_cpu(&icb)?; + let command_buffer = ours.execute(&icb)?; + let at = Instant::now(); + command_buffer.commit()?; + let commit = at.elapsed(); + wait(&command_buffer)?; + println!( + "ICB-IDLE {seconds} longest_setter_ms {:.3} encode_ms {:.3} commit_ms {:.3} \ + commit_to_completed_ms {:.3}", + longest.as_secs_f64() * 1e3, + encode.as_secs_f64() * 1e3, + commit.as_secs_f64() * 1e3, + at.elapsed().as_secs_f64() * 1e3, + ); + } + let per = |us: f64| us / args.commands as f64; + for shape in Shape::ALL { + if !args.runs(shape) { + continue; + } + let mut samples: [Vec; 3] = Default::default(); + let mut moved: BTreeMap = BTreeMap::new(); + for round in 0..=args.runs { + let before = counts(&device.work_counts()); + let icb = ours.icb(shape)?; + let (encode, cpu) = match shape { + Shape::CpuShared => (0.0, ours.write_on_cpu(&icb)?.1.as_secs_f64() * 1e6), + _ => (ours.write_on_gpu(&icb)?, 0.0), + }; + let command_buffer = ours.execute(&icb)?; + run(&command_buffer)?; + let execute = gpu_us(&command_buffer)?; + if round == 0 { + continue; + } + for (sample, value) in samples.iter_mut().zip([encode, execute, cpu]) { + sample.push(per(value)); + } + for (count, value) in counts(&device.work_counts()) { + let delta = value.saturating_sub(before.get(&count).copied().unwrap_or(0)); + if delta > 0 { + *moved.entry(count).or_default() += delta; + } + } + } + ours.check(shape)?; + let median = |sample: &mut Vec| { + sample.sort_by(f64::total_cmp); + sample[sample.len() / 2] + }; + let [encode, execute, cpu] = &mut samples; + println!( + "ICB-READS {} commands {} gpu_us_per_command encode {:.4} execute {:.4} \ + cpu_encode_us_per_command {:.4} {name}", + shape.name(), + args.commands, + median(encode), + median(execute), + median(cpu), + ); + let line: Vec = (moved.iter()) + .map(|(count, sum)| format!("{count}={:.2}", *sum as f64 / args.runs as f64)) + .collect(); + println!("ICB-READS-COUNTS {} {}", shape.name(), line.join(" ")); + } + Ok(()) +} diff --git a/crates/metal2vulkan-runtime/src/blit_indirect.rs b/crates/metal2vulkan-runtime/src/blit_indirect.rs index 0298d795c..62cb93286 100644 --- a/crates/metal2vulkan-runtime/src/blit_indirect.rs +++ b/crates/metal2vulkan-runtime/src/blit_indirect.rs @@ -121,6 +121,10 @@ impl BlitCommandEncoder { if from.is_empty() { return Ok(()); } + // The records held where they lie in device-local memory, a copy's as any GPU + // work's (`indirect_command_buffer/home.rs`). + source.hold_records(this.core(), false); + destination.hold_records(this.core(), true); destination.written_by_gpu(GpuWriter::Copy); this.core().retain(destination.gpu_write()); destination.keep_copied(source, from.clone()); @@ -179,6 +183,9 @@ impl BlitCommandEncoder { if range.is_empty() { return Ok(()); } + // The records held where they lie in device-local memory, a reset's as any GPU + // work's (`indirect_command_buffer/home.rs`). + buffer.hold_records(this.core(), true); buffer.written_by_gpu(GpuWriter::Reset); this.core().retain(buffer.gpu_write()); let bytes = IndirectCommandBuffer::record_bytes(range.clone()); diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index fcddea0d3..08257fc9f 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -3112,6 +3112,28 @@ impl Device { self.zeroed_buffer_of(call, length, (modes, MemoryClass::Shared), of, placed) } + /// A `Private` buffer of the runtime's own of `length` bytes at `placement`, for an indirect + /// command buffer's records in device-local memory (`indirect_command_buffer/home.rs`): its + /// bytes as placed, no fill noted, as the caller sets every byte before any use. Refused as + /// [`zeroed_buffer`](Device::zeroed_buffer) is. + pub(super) fn device_records_buffer( + &self, + call: &'static str, + length: u64, + modes: Modes, + placement: impl Into, + ) -> Result { + let modes = Modes { + storage: StorageMode::Private, + ..modes + }; + let of = NewBufferOf::Runtime(FreshPages::WherePaid); + let placed = (placement.into(), None); + let (buffer, _) = + self.placed_new_buffer(call, length, modes, MemoryClass::Private, of, placed)?; + Ok(buffer) + } + /// [`zeroed_buffer`](Device::zeroed_buffer) for `of`, its byte `aligned` (where given) on a /// multiple of 256 bytes of its memory ([`Device::placed_new_buffer`]). fn zeroed_buffer_of( diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 9cfa198ea..03a9e049a 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -1263,6 +1263,11 @@ impl ComputeCommandEncoder { return Ok(()); } for &resource in resources { + // Its records held where they lie in device-local memory, before any listing of + // them reads where they lie (`indirect_command_buffer/home.rs`). + if let ResourceRef::IndirectCommandBuffer(icb) = resource { + icb.hold_records(&mut self.core, usage.contains(ResourceUsage::WRITE)); + } let used = self .residency .use_resource(resource, usage, RenderStages::empty()); @@ -1525,6 +1530,7 @@ impl ComputeCommandEncoder { if let Some(trail) = self.core.trail() { trail.execution(range.given()); } + icb.hold_records(&mut self.core, false); self.sync_heaps(); // Its commands bind the heap sets as they record, later. self.core.command_buffer().state().heaps.executes_later(); diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index e1c102cd9..3302607ce 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -733,6 +733,18 @@ degradations! { execution committed before a route that may write the records met the buffer, the \ call that met it: a later commit, a blit's, or a CPU setter's); without device \ addresses, a command's first buffer shape compiles its variant then"; + /// A host access of an indirect command buffer's records (a setter, a getter, a CPU + /// reset, a commit or host step that reads them) on a device without unified memory, + /// where the records lie in device-local memory and must stay there: a `Private` + /// buffer's, whose records never leave it, or a `Shared` one's that the GPU used first + /// while a command buffer that used them is not complete or dropped + /// (`indirect_command_buffer/home.rs`). A `Shared` buffer's records move into host memory + /// at its first host access once no command buffer holds them, and stay there. To avoid + /// it, touch a `Shared` buffer from the CPU before the GPU uses it. + StagedIndirectRecords = "staged-indirect-records", Performance, + "a round trip through the device's staging queue for each such access: the records it \ + reads are copied into host memory first, and those it writes copied back after, \ + each copy waited for, where Metal's CPU reads and writes the records in place"; /// A command buffer's GPU times on a device that calibrates its timestamps against no /// host clock the runtime reads (no `VK_KHR_calibrated_timestamps` or /// `VK_EXT_calibrated_timestamps` with the device's time domain and a monotonic host diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs index a7f360fce..343523199 100644 --- a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs @@ -12,13 +12,15 @@ //! holds it are gone, a blit's command holding only its records. The records lie at //! `records_address` of the ID, outside the Metal address space (`address.rs`), where a //! translated kernel that reads the ID from an argument buffer reaches the buffer last made with -//! the ID. The buffer is host-visible whatever storage mode the program asks for; the object -//! answers the mode asked for, and the CPU encodes and reads back a `Private` buffer's commands -//! as a `Shared` one's, as plain Metal does. The records, and the slots past them, lie in fresh -//! pages of the runtime's own where the device imports host pointers (`fresh_pages.rs`), so -//! that a device's recovery keeps them, as Metal keeps a buffer's records across its GPU's -//! restart; elsewhere in pooled memory, which the recovery's carry cannot keep -//! (`indirect_command_buffer/carry.rs`). +//! the ID. The object answers the storage mode asked for, and the CPU encodes and reads back a +//! `Private` buffer's commands as a `Shared` one's, as plain Metal does. The records lie in a +//! host-visible buffer of their own whatever the mode, and on a device without unified memory +//! in device-local memory where their first use is the GPU's or the buffer is `Private`, the +//! CPU reaching those only through copies (`indirect_command_buffer/home.rs`). The host's +//! records, and the slots past them, lie in fresh pages of the runtime's own where the device +//! imports host pointers (`fresh_pages.rs`), so that a device's recovery keeps them, as Metal +//! keeps a buffer's records across its GPU's restart; elsewhere in pooled memory, which the +//! recovery's carry cannot keep (`indirect_command_buffer/carry.rs`). //! - **CPU encoding.** [`IndirectCommandBuffer::indirect_compute_command_at`] gives a compute //! command's setters, which write its record as Metal's do (an M3 Max on macOS 26.7 and an M4 on //! 27.0.1): a buffer's address plus its offset's low 32 bits as one address; threadgroup lengths @@ -119,10 +121,12 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; pub(crate) mod carry; +mod home; mod set_each; mod set_states; mod writers; +use home::{Home, Reach}; pub use set_each::{IndirectComputeSet, IndirectRenderSet}; use set_states::{Keyed, SetKeys, SetStates, StateKey}; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] @@ -661,6 +665,7 @@ impl Device { let writers = Writers::new(!storage.in_own_pages()); let icb = IndirectCommandBuffer(Arc::new(IcbShared { storage, + home: Home::new(self, modes.storage), id, identifier, descriptor: *descriptor, @@ -1127,9 +1132,12 @@ impl RenderLayout { pub struct IndirectCommandBuffer(Arc); struct IcbShared { - /// The header and the records: host-visible on every generation it lies on, carried with - /// the buffer (`indirect_command_buffer/carry.rs`). + /// The header and the records in the host's memory: host-visible on every generation it lies + /// on, carried with the buffer (`indirect_command_buffer/carry.rs`). The GPU reaches them here + /// or in device-local memory, as their first use placed them (`home`). storage: Buffer, + /// Where the records lie (`indirect_command_buffer/home.rs`). + home: Home, /// Its ID, held while the buffer lives. id: RecordsHold, /// Its `uniqueIdentifier` (`unique_identifier.rs`), held while the buffer lives. @@ -1223,6 +1231,7 @@ const _: fn(&IcbShared) = |icb| { fn shared(_: &T) {} let IcbShared { storage, + home, id, identifier, descriptor, @@ -1250,6 +1259,7 @@ const _: fn(&IcbShared) = |icb| { keeping, } = icb; shared(storage); + shared(home); shared(id); shared(identifier); shared(descriptor); @@ -1726,6 +1736,17 @@ impl IndirectCommandBuffer { &self, index: u32, read: impl FnOnce(&RecordView<'_>) -> T, + ) -> Result { + let _access = self.records_access(index..index + 1, false, Reach::Reads)?; + self.read_record_in(index, read) + } + + /// [`read_record`](Self::read_record) inside the caller's host access of the record + /// (`home.rs`). + fn read_record_in( + &self, + index: u32, + read: impl FnOnce(&RecordView<'_>) -> T, ) -> Result { self.generation().shared().counts.indirect_records_read(1); let bytes = { @@ -1810,6 +1831,7 @@ impl IndirectCommandBuffer { /// Reset commands `range` (inside the size). fn reset_commands(&self, range: Range) -> Result<(), Error> { + let _access = self.records_access(range.clone(), true, Reach::Overwrites)?; let mut commands = lock(&self.0.pipelines); for index in range.clone() { self.write(&mut commands, index, &CommandRecord::default())?; @@ -2174,6 +2196,7 @@ impl IndirectCommandBuffer { index: u32, reset: impl FnOnce(&mut CommandRecord) -> bool, ) -> Result<(), Error> { + let _access = self.records_access(index..index + 1, true, Reach::Writes)?; let mut commands = lock(&self.0.pipelines); let mut record = self.record(index)?; if !reset(&mut record) { @@ -2186,12 +2209,18 @@ impl IndirectCommandBuffer { /// A [`Batch`] of a setter's writes, or of the setters `set_each` names, on command `index` /// (below the size). fn batch(&self, index: u32) -> Batch<'_> { + let (access, failed) = match self.records_access(index..index + 1, true, Reach::Writes) { + Ok(access) => (Some(access), None), + Err(error) => (None, Some(Box::new(error))), + }; Batch { icb: self, index, storage: self.bytes(), begun: None, unlocked: 0, + _access: access, + failed, } } @@ -2653,8 +2682,10 @@ impl IndirectCommandBuffer { &self, index: u32, ) -> Result<(Option, Option, Option), Error> { + // The host access before `pipelines`, as every one takes the two (`home.rs`). + let _access = self.records_access(index..index + 1, false, Reach::Reads)?; let commands = lock(&self.0.pipelines); - let (reported, runs) = self.read_record(index, |view| { + let (reported, runs) = self.read_record_in(index, |view| { ( view.pipeline(), view.pipeline().or(view.retained_pipeline()), @@ -2880,12 +2911,6 @@ impl IndirectCommandBuffer { } } - /// The records' buffer: what an encoder makes resident for the buffer, and where a function's - /// command encoders write (`gpu_resource_id`). - pub(super) fn storage(&self) -> &Buffer { - &self.0.storage - } - /// A route that may write the buffer's records met it (`writer`, `write_routes.rs`), so the /// GPU may write them from now on: an execution's records are known only once the work /// before it completed, and it is replayed on the host then (`indirect_execute.rs`). For @@ -3172,6 +3197,7 @@ impl IndirectCommandBuffer { if !self.0.nines.load(Ordering::Acquire) { return Ok(None); } + let _access = self.records_access(range.clone(), false, Reach::Reads)?; let nine = DrawPrimitiveType::Nine.raw() as u32; for index in range { let action = self.record(index)?.action; @@ -3211,6 +3237,8 @@ impl IndirectCommandBuffer { /// (`ReplayFaults::RECORD`). Each is read into the list it is returned in, with no state named /// yet (`step_states`, `step_render_states`). pub(super) fn written_records(&self, range: Range) -> Result, Error> { + let runs = [HEADER, Self::record_bytes(range.clone())]; + let _access = self.host_access(&runs, Reach::Reads)?; let count = range.len(); Ok(self.written_records_of(count, range.map(|index| self.record_now(index)))) } @@ -3235,6 +3263,12 @@ impl IndirectCommandBuffer { "a host step's reads of its records not one a command", )); } + let stored = sources.iter().filter_map(|source| match source { + RecordSource::Storage(commands) => Some(Self::record_bytes(commands.clone())), + RecordSource::Bytes(_) => None, + }); + let runs: Vec> = std::iter::once(HEADER).chain(stored).collect(); + let _access = self.host_access(&runs, Reach::Reads)?; let records = sources.iter().flat_map(|source| { let (bytes, storage) = match source { RecordSource::Bytes(bytes) => (*bytes, 0..0), @@ -3257,7 +3291,7 @@ impl IndirectCommandBuffer { count: usize, records: impl Iterator>, ) -> WrittenRecords { - if let Some(fault) = self.written_header_fault() { + if let Some(fault) = self.header_fault_now() { return WrittenRecords { faults: fault, records: Vec::new(), @@ -3281,7 +3315,17 @@ impl IndirectCommandBuffer { /// [`written_records`](Self::written_records) checks it: the producers' sticky encoding fault /// (`ReplayFaults::ENCODING`), or a write that overran it (`ReplayFaults::RECORD`); `None` /// where it holds none. + /// A header the host cannot read, its device lost, runs none of them. pub(super) fn written_header_fault(&self) -> Option { + let Ok(_access) = self.host_access(&[HEADER], Reach::Reads) else { + return Some(ReplayFaults::RECORD); + }; + self.header_fault_now() + } + + /// [`written_header_fault`](Self::written_header_fault) inside the caller's host access of + /// the header (`home.rs`). + fn header_fault_now(&self) -> Option { let mut header = [0; COMMAND_BUFFER_HEADER_BYTES]; // SAFETY: the header lies at the start of the mapped storage; the GPU's writes to it // completed (the caller's contract). @@ -3344,6 +3388,8 @@ impl IndirectCommandBuffer { range: Range, into: Option>, ) -> Box<[u8]> { + // Read where the records lie but for a lost device's, which lost them. + let _access = self.records_access(range.clone(), false, Reach::Reads).ok(); let bytes = record_offset(range.start)..record_offset(range.end); (self.generation().shared().counts).indirect_record_bytes_copied(bytes.len() as u64); let mut copy = match into { @@ -3369,6 +3415,9 @@ impl IndirectCommandBuffer { if bytes.len() != kept.len() { return false; } + let Ok(_access) = self.records_access(range, false, Reach::Reads) else { + return false; + }; // SAFETY: as `written_bytes`'s; the slice lives only for the comparison. let now = unsafe { std::slice::from_raw_parts(self.bytes().add(bytes.start), bytes.len()) }; now == kept @@ -3482,6 +3531,7 @@ impl IndirectCommandBuffer { if !range.is_empty() { counts.indirect_record_run_read(); } + let _access = self.records_access(range.clone(), false, Reach::Reads)?; let commands = lock(&self.0.pipelines); let mut records = Vec::with_capacity(range.len()); let mut sets = Vec::with_capacity(range.len()); @@ -3983,9 +4033,23 @@ struct Batch<'i> { begun: Option, /// The writes made without `pipelines`, not yet counted. unlocked: u64, + /// The host access of the command's record and written flag, from the batch's making until + /// it goes (`home.rs`): a staged one copies them back as it goes, after the writes counted. + _access: Option>, + /// Why the access failed (its device lost), which each write answers: boxed, as every + /// setter makes a batch and nearly none fails. + failed: Option>, } impl Batch<'_> { + /// Refuse a write where the batch's host access failed. + fn accessed(&self) -> Result<(), Error> { + match &self.failed { + Some(error) => Err((**error).clone()), + None => Ok(()), + } + } + /// Write `field`, which names no pipeline state, then note `then`: without `pipelines` where /// it adds nothing to what the records may hold, else under it. Records in the runtime's own /// pages are the bytes the batch read at its making, whatever a recovery's carry does @@ -3994,6 +4058,7 @@ impl Batch<'_> { fn field(&mut self, field: RecordField, then: Then) -> Result<(), Error> { #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] set_hook(HoldAt::Set); + self.accessed()?; let icb = self.icb; if icb.0.writers.counted() { if !self.counted_write(field, None)? { @@ -4017,6 +4082,7 @@ impl Batch<'_> { /// under the lock. In pooled memory the look at the command's key too is the /// [`counted_write`](Self::counted_write)'s, which goes without the lock or not at all. fn named(&mut self, key: StateKey, id: NonZeroU64) -> Result { + self.accessed()?; let field = RecordField::Pipeline(id); if self.icb.0.writers.counted() { #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] @@ -4067,6 +4133,7 @@ impl Batch<'_> { fn state(&mut self, id: NonZeroU64, set: StateSet<'_>) -> Result<(), Error> { #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] set_hook(HoldAt::Set); + self.accessed()?; self.icb .edit_locked(self.index, RecordField::Pipeline(id), Some(set)) } @@ -4096,6 +4163,7 @@ impl Batch<'_> { /// which an execution's records and the records the GPU writes both go through), and what /// Metal keeps such a slot in for its private getters is unmeasured. fn buffer(&mut self, call: &'static str, set: BufferSet<'_>) -> Result<(), Error> { + self.accessed()?; let icb = self.icb; let BufferSet { stage, @@ -4416,6 +4484,9 @@ fn record_offset(index: u32) -> usize { COMMAND_BUFFER_HEADER_BYTES + index as usize * COMMAND_BYTES } +/// The header's bytes in the storage. +const HEADER: Range = 0..COMMAND_BUFFER_HEADER_BYTES as u64; + /// `writes` in one word, as `IcbShared::added_writes` keeps them: the command kinds above the /// operations above the primitive types. fn packed(writes: CommandWrites) -> u64 { diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs index 157bb9856..85347b4d1 100644 --- a/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs @@ -30,6 +30,9 @@ //! lost generation's command buffers, are let go of; its executions there record them again. //! Where the GPU may write its records, the new generation's keepers list it //! (`Keepers::add`), so a state released there is kept for it too. +//! - **Records in device-local memory** (`home.rs`) are lost with the `VkDevice`, as pooled +//! memory's are: the host's buffer is written again as a new buffer's, its header and every +//! command reset, and the records lie there for good. //! - **Left** the lost generation's, refused where it meets the next: a buffer whose storage's //! carry fails (the making of its memory there). //! @@ -72,6 +75,10 @@ impl IndirectCommandBuffer { if shared.storage.generation().same(to) { return Ok(Contents::Kept); } + // Records in device-local memory are lost with it: the host's buffer holds them from now + // on, written again below. Decided before `pipelines` is taken, as a staged access takes + // the two (`home.rs`). + let device_lost = shared.home.leave_device(); // In pooled memory, the setters' writes without the lock under way end first, and none // begins until the records and the keys are the next generation's (`writers.rs`). let stopped = shared.writers.stop(); @@ -84,7 +91,10 @@ impl IndirectCommandBuffer { if let Some(overflow) = &shared.overflow { overflow.storage.carry_runtime(to)?; } - let contents = shared.storage.carry_runtime(to)?; + let contents = match (shared.storage.carry_runtime(to)?, device_lost) { + (Contents::Kept, true) => Contents::Lost(super::storage_length(shared.size)), + (contents, _) => contents, + }; if let Contents::Lost(_) = contents { // Every command reset, as a new buffer's: the states the CPU set on them go. self.write_header().map_err(|_| Left::Failed)?; diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer/home.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer/home.rs new file mode 100644 index 000000000..a01e1e688 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer/home.rs @@ -0,0 +1,430 @@ +//! Where an indirect command buffer's records lie: placed by their first use, on a device without +//! unified memory that reserves a staging queue (`device/staging.rs`). +//! +//! - **Why.** In system memory, every record a kernel writes and every record an execution reads +//! crosses the link to the GPU. On an RTX 3090 behind a PCIe x4 link, a kernel writing 8192 +//! render commands moved 32.3 MB in 17.2 ms, and the execution that read them 49.7 MB in +//! 26.0 ms, each near the link's 1.83 GB/s; in device-local memory on an RTX 5080 Laptop GPU +//! that kernel took about a hundredth of its time in system memory, and the execution's pass +//! about a sixth (`examples/icb_reads.rs`). The CPU's reads and writes of device-local memory +//! cross the link each, and on a GPU that sleeps when idle a write wakes it first (about 0.95 s +//! on the 5080), so the CPU never touches that memory: a buffer the CPU uses keeps its records +//! in the host's memory. +//! - **The first use decides.** The records start in the host's buffer (`IcbShared::storage`, +//! its header written and every command reset as it is made), placed nowhere yet. The first use +//! of the GPU (an execution, `useResource`, a blit's copy, reset or optimize) places them in +//! device-local memory ([`Home::device`], made then: a fill and an update of its header on the +//! staging queue, not waited for, which every later submission of the device's waits for on +//! the GPU). The first host access (a setter, a getter, a CPU reset, a commit or host step that +//! reads them) places a `Shared` buffer's in the host's buffer for good, counted as a move of +//! no bytes (`WorkCounts::icb_records_moved_to_host`), and a `Private` buffer's in device-local +//! memory. A device with unified memory, or without a staging queue, keeps every buffer's in +//! the host's buffer from its making. +//! - **Holds.** A command buffer that uses the records in device-local memory holds them +//! ([`RecordsHold`], an encoder's retained object) from the encoding call until it completes or +//! is dropped. A blit's copy, reset or optimize is GPU work, held as any other. +//! - **The move.** A `Shared` buffer's host access while no command buffer holds the records in +//! device-local memory moves them into the host's buffer for good: through one copy of the +//! whole storage on the staging queue, waited for, where the GPU may have written them +//! (`WorkCounts::icb_record_bytes_moved`), else none, the host's buffer holding what the host +//! left there. From then on the GPU reaches the host's buffer. The device-local buffer stays +//! until the indirect command buffer goes. +//! - **Staged.** Any other host access of records in device-local memory (a `Private` buffer's, +//! which never move, or a `Shared` one's while a command buffer holds them) copies the records +//! it reads into the host's buffer first and those it writes back after, each on the staging +//! queue and waited for, under the home's lock, so a move, a hold or another staged access +//! waits for it; counted (`WorkCounts::icb_records_staged_accesses`) and announced once per +//! device (`Degradation::StagedIndirectRecords`). The host never reads or writes device memory. +//! - **A recovery** (`carry.rs`) loses records in device-local memory with the lost `VkDevice`: +//! the host's buffer is written again as a new buffer's, and the records stay there. + +use super::{record_offset, storage_length, IndirectCommandBuffer}; +use crate::address::Place; +use crate::buffer::{Buffer, Modes}; +use crate::degradation::Degradation; +use crate::device::lock; +use crate::encoder::EncoderCore; +use crate::error::{internal, Error}; +use crate::texture::transfer_barrier; +use crate::{Device, StorageMode}; +use ash::vk; +use std::ops::Range; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; + +/// Where the records lie (the module docs). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Placed { + /// In the host's buffer, which no use placed yet. + Unplaced, + /// In device-local memory ([`Home::device`]). + Device, + /// In the host's buffer, for good. + Host, +} + +/// The home's state, under its lock. +struct State { + placed: Placed, + /// The command buffers that hold the records in device-local memory ([`RecordsHold`]). + held: u32, + /// The GPU may have written the records in device-local memory. + written: bool, + /// The staging queue's value of the submission that set the device-local records' bytes as + /// they were placed. + init: u64, + /// The host saw that submission complete. + init_seen: bool, +} + +/// Where an indirect command buffer's records lie (the module docs). +pub(super) struct Home { + /// The device-local records, from the use that placed them there. + device: OnceLock, + /// The records lie in the host's buffer for good: one load, a host access's way in place. + on_host: AtomicBool, + /// The records never move: a `Private` buffer's. + pinned: bool, + state: Arc>, +} + +impl Home { + /// The home of a buffer of `storage` mode on `device`: in the host's buffer for good where + /// the device has unified memory or no staging queue, else placed by the first use. + pub(super) fn new(device: &Device, storage: StorageMode) -> Home { + let placing = !device.properties().has_unified_memory && device.has_staging_queue(); + let placed = match placing { + true => Placed::Unplaced, + false => Placed::Host, + }; + Home { + device: OnceLock::new(), + on_host: AtomicBool::new(!placing), + pinned: storage == StorageMode::Private, + state: Arc::new(Mutex::new(State { + placed, + held: 0, + written: false, + init: 0, + init_seen: false, + })), + } + } + + /// The device-local records, while the GPU reaches them there. + pub(super) fn device(&self) -> Option<&Buffer> { + match self.on_host.load(Ordering::Acquire) { + true => None, + false => self.device.get(), + } + } + + /// Lie in the host's buffer for good, under `state`, the caller's hold of the lock. + fn to_host(&self, state: &mut State) { + state.placed = Placed::Host; + self.on_host.store(true, Ordering::Release); + } + + /// Whether the records lie in device-local memory, which a recovery's carry loses: they lie + /// in the host's buffer for good from now on (`carry.rs`). + pub(super) fn leave_device(&self) -> bool { + let mut state = lock(&self.state); + let left = state.placed == Placed::Device; + if left { + self.to_host(&mut state); + } + left + } +} + +impl Drop for Home { + fn drop(&mut self) { + // The submission that set the device-local records' bytes holds nothing: the records go + // once it completed. + let state = lock(&self.state); + if let (Some(records), false) = (self.device.get(), state.init_seen) { + let _ = records.generation().wait_staging(state.init); + } + } +} + +/// A command buffer's hold of an indirect command buffer's records in device-local memory (an +/// encoder's retained object), let go of as it completes or is dropped (the module docs). +pub(super) struct RecordsHold(Arc>); + +impl Drop for RecordsHold { + fn drop(&mut self) { + let mut state = lock(&self.0); + state.held = state.held.saturating_sub(1); + } +} + +/// What a host access does with the bytes of its runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Reach { + /// Reads them. + Reads, + /// Reads them, and writes some. + Writes, + /// Writes every byte of them, reading none. + Overwrites, +} + +/// A host access of an indirect command buffer's records ([`IndirectCommandBuffer::host_access`]): +/// in the host's buffer as they lie there, or staged. A staged write's runs are copied back as it +/// goes. One word: every setter's batch holds one (`Batch`), and nearly every one is in place. +#[must_use] +pub(super) struct HostAccess<'a> { + _staged: Option>>, +} + +/// A staged host access (the module docs): the home's lock, held until it goes. +struct Staged<'a> { + icb: &'a IndirectCommandBuffer, + state: Option>, + runs: Vec>, + back: bool, +} + +impl Drop for Staged<'_> { + fn drop(&mut self) { + if self.back { + let (Some(records), host) = (self.icb.0.home.device.get(), &self.icb.0.storage) else { + return; + }; + // A lost device lost the records: there is nothing to copy them back into. + let _ = copy_runs(self.icb.generation(), records, host, &self.runs, false); + } + drop(self.state.take()); + let icb = self.icb; + icb.generation() + .degrade(Degradation::StagedIndirectRecords, || { + let object = format!( + "a {:?} indirect command buffer of {} commands", + icb.storage_mode(), + icb.size() + ); + let reason = match icb.0.home.pinned { + true => { + "its records lie in device-local memory for good, which the CPU reaches \ + only through copies" + .to_owned() + } + false => { + "the GPU used its records first, in device-local memory, and a command \ + buffer that uses them is not complete or dropped" + .to_owned() + } + }; + (object, reason) + }); + } +} + +/// Copy `runs` of `from` into the same bytes of `to` on `device`'s staging queue, waited for: +/// from the device-local records into the host's buffer where `down`, else back. +fn copy_runs( + device: &Device, + records: &Buffer, + host: &Buffer, + runs: &[Range], + down: bool, +) -> Result<(), Error> { + let (records_raw, records_at) = records.at(0); + let (host_raw, host_at) = host.at(0); + let (from, from_at, to, to_at) = match down { + true => (records_raw, records_at, host_raw, host_at), + false => (host_raw, host_at, records_raw, records_at), + }; + let regions: Vec = (runs.iter()) + .filter(|run| !run.is_empty()) + .map(|run| vk::BufferCopy { + src_offset: from_at + run.start, + dst_offset: to_at + run.start, + size: run.end - run.start, + }) + .collect(); + if regions.is_empty() { + return Ok(()); + } + let mut staging = device.staging_lock()?; + let value = staging.submit(|raw, command_buffer, _| { + transfer_barrier(raw, command_buffer, true); + // SAFETY: the staging command buffer is recording, outside a render pass; both buffers + // are live, shared with the staging queue's family (`sharing.rs`), and the regions lie + // inside each (the storage's bytes). No command buffer's work writes the host's buffer + // meanwhile: the GPU reaches the records in device-local memory. + unsafe { raw.cmd_copy_buffer(command_buffer, from, to, ®ions) }; + transfer_barrier(raw, command_buffer, false); + })?; + drop(staging); + device.wait_staging(value) +} + +impl IndirectCommandBuffer { + /// The records' buffer the GPU reaches now: the device-local one where they lie there, else + /// the host's (the module docs). A command buffer reads it only once it holds the records + /// ([`hold_records`](Self::hold_records)). + pub(crate) fn storage(&self) -> &Buffer { + self.0.home.device().unwrap_or(&self.0.storage) + } + + /// Hold the records for the command buffer `core` encodes into, whose work uses them on the + /// GPU, writing them where `writes`: placed in device-local memory where nothing placed them + /// yet, and held there until the command buffer completes or is dropped. Nothing where they + /// lie in the host's buffer (the module docs); there too where device-local memory cannot + /// hold them. + pub(crate) fn hold_records(&self, core: &mut EncoderCore, writes: bool) { + let home = &self.0.home; + if home.on_host.load(Ordering::Acquire) { + return; + } + let mut state = lock(&home.state); + match state.placed { + Placed::Host => return, + Placed::Unplaced => { + if self.place_on_device(&mut state).is_err() { + home.to_host(&mut state); + return; + } + } + Placed::Device => {} + } + state.held += 1; + state.written |= writes; + drop(state); + core.retain(RecordsHold(Arc::clone(&home.state))); + } + + /// Place the records in device-local memory, under `state`, the caller's hold of the home's + /// lock: a new buffer at the records' address, its header written and every command reset, on + /// the staging queue (the module docs). + fn place_on_device(&self, state: &mut State) -> Result<(), Error> { + const CALL: &str = "new_indirect_command_buffer"; + let device = self.generation(); + let length = storage_length(self.0.size); + let modes = Modes::of(self.0.options)?; + let records = + device.device_records_buffer(CALL, length, modes, Place::Records(self.0.id.held.id))?; + let header = (self.0.records) + .encode_header(self.0.size, self.0.inheritance) + .map_err(|_| internal("an indirect command buffer's header was refused"))?; + let (raw, at) = records.at(0); + let mut staging = device.staging_lock()?; + let value = staging.submit(|commands, command_buffer, _| { + transfer_barrier(commands, command_buffer, true); + // SAFETY: the staging command buffer is recording, outside a render pass; the buffer + // is live (`Home`'s drop waits for this submission) and shared with the staging + // queue's family; the fill covers the storage's bytes, a multiple of 4 (records of + // 2248 bytes, a 16-byte header and 4-byte flags), from the records' start, and the + // header, 16 bytes, lies at its start. + unsafe { commands.cmd_fill_buffer(command_buffer, raw, at, length, 0) }; + transfer_barrier(commands, command_buffer, true); + // SAFETY: as the fill's. + unsafe { commands.cmd_update_buffer(command_buffer, raw, at, &header) }; + transfer_barrier(commands, command_buffer, false); + })?; + drop(staging); + if self.0.home.device.set(records).is_err() { + return Err(internal( + "an indirect command buffer's records placed twice", + )); + } + state.placed = Placed::Device; + state.init = value; + Ok(()) + } + + /// A host access of the records' `runs` (byte ranges of the storage) that does `reach` with + /// them, until the access goes: in place where they lie in the host's buffer; else a `Shared` + /// buffer's records unheld move there, or the access is staged (the module docs). Inside it, + /// the host's buffer ([`bytes`](Self::bytes)) holds the runs' bytes as they stand. + pub(super) fn host_access( + &self, + runs: &[Range], + reach: Reach, + ) -> Result, Error> { + let home = &self.0.home; + if home.on_host.load(Ordering::Acquire) { + return Ok(HostAccess { _staged: None }); + } + let mut state = lock(&home.state); + let counts = &self.generation().shared().counts; + match state.placed { + Placed::Host => return Ok(HostAccess { _staged: None }), + Placed::Unplaced if !home.pinned => { + home.to_host(&mut state); + counts.icb_records_moved_to_host(0); + return Ok(HostAccess { _staged: None }); + } + Placed::Unplaced => self.place_on_device(&mut state)?, + Placed::Device => {} + } + let Some(records) = home.device.get() else { + return Err(internal( + "an indirect command buffer's records placed nowhere", + )); + }; + if state.held == 0 && !home.pinned { + // Where the GPU wrote nothing, the host's buffer holds what the device-local one does: + // the header, every command reset, and what staged accesses wrote into both. + let moved = match state.written { + true => { + let whole = 0..storage_length(self.0.size); + let runs = std::slice::from_ref(&whole); + copy_runs(self.generation(), records, &self.0.storage, runs, true)?; + state.init_seen = true; + whole.end + } + false => 0, + }; + home.to_host(&mut state); + counts.icb_records_moved_to_host(moved); + return Ok(HostAccess { _staged: None }); + } + if reach != Reach::Overwrites { + copy_runs(self.generation(), records, &self.0.storage, runs, true)?; + state.init_seen = true; + } + counts.icb_records_staged_access(); + Ok(HostAccess { + _staged: Some(Box::new(Staged { + icb: self, + state: Some(state), + runs: runs.to_vec(), + back: reach != Reach::Reads, + })), + }) + } + + /// [`host_access`](Self::host_access) of commands `range`'s records, and their written flags + /// where `flags`: none of an empty range, which reaches no byte and places nothing. + #[inline] + pub(super) fn records_access( + &self, + range: Range, + flags: bool, + reach: Reach, + ) -> Result, Error> { + // Where the records lie in the host's buffer for good, as every setter of a buffer the CPU + // writes finds them, the access is in place: no runs to name. + if range.is_empty() || self.0.home.on_host.load(Ordering::Acquire) { + return Ok(HostAccess { _staged: None }); + } + let records = record_offset(range.start) as u64..record_offset(range.end) as u64; + let runs = [records, self.flag_bytes(range)]; + let runs = match flags { + true => &runs[..], + false => &runs[..1], + }; + self.host_access(runs, reach) + } + + /// Whether the records lie in device-local memory now, and how many command buffers hold them + /// there, for a device test of where they lie. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn records_on_device(&self) -> (bool, u32) { + let state = lock(&self.0.home.state); + (state.placed == Placed::Device, state.held) + } +} diff --git a/crates/metal2vulkan-runtime/src/render/arguments.rs b/crates/metal2vulkan-runtime/src/render/arguments.rs index 5365ac85d..b184c0265 100644 --- a/crates/metal2vulkan-runtime/src/render/arguments.rs +++ b/crates/metal2vulkan-runtime/src/render/arguments.rs @@ -96,6 +96,11 @@ impl RenderLowering { return Ok(()); } for &resource in resources { + // Its records held where they lie in device-local memory, before any listing of + // them reads where they lie (`indirect_command_buffer/home.rs`). + if let ResourceRef::IndirectCommandBuffer(icb) = resource { + icb.hold_records(&mut self.core, usage.contains(ResourceUsage::WRITE)); + } if let Some(used) = self.residency.use_resource(resource, usage, stages) { self.core.made_resident(used); } diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index 88c5f9637..cdff69884 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -776,6 +776,7 @@ impl RenderLowering { self.gathering().add_bytes(buffer, write); } self.core.retain(icb.clone()); + icb.hold_records(&mut self.core, false); self.executions.push(RenderExecution { icb: icb.clone(), range, diff --git a/crates/metal2vulkan-runtime/src/tests/icb_records_home.rs b/crates/metal2vulkan-runtime/src/tests/icb_records_home.rs new file mode 100644 index 000000000..fc766e1e9 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/icb_records_home.rs @@ -0,0 +1,513 @@ +//! Where an indirect command buffer's records lie (`indirect_command_buffer/home.rs`): on a device +//! without unified memory that reserves a staging queue, a buffer the GPU uses first keeps them in +//! device-local memory, held by each command buffer that uses them; a `Shared` one's move into the +//! host's memory at the first host access no command buffer holds them for, with their bytes where +//! the GPU wrote them and none where it did not; a `Private` one's never move; any other host +//! access is staged, announced once per device. Elsewhere every buffer's records lie in the host's +//! memory: nothing moves and nothing is staged. On every device the commands draw what was +//! encoded, whoever encoded them, and the getters answer it. +//! +//! A device test: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on the kind +//! of device the cfg selects. The kernel is the owned fixture +//! `validation/fixtures/public/kernel_icb_encode_render_commands.ll`, which encodes one draw a +//! thread through an argument buffer that holds the indirect command buffer; the render functions +//! are LLVM text here (`llvm-as`). + +use super::blit_holds::{options, Scratch, WAIT}; +use super::encoder_holds::library; +use crate::{ + BlitOption, Buffer, ClearColor, CommandBuffer, CommandBufferStatus, ComputePipelineState, + Degradation, DegradeNotice, Device, IndirectCommandBuffer, IndirectCommandBufferDescriptor, + IndirectDraw, LoadAction, MessageSink, Origin, PipelineOptions, RenderPassDescriptor, + RenderPipelineState, ResourceOptions, Size, StoreAction, Texture, TextureDescriptor, + WorkCounts, +}; +use metal2vulkan::bind::indirect_commands::written_flag_offset; +use metal2vulkan::metal::{ + IndirectCommandType, PixelFormat, PrimitiveType, RenderStages, ResourceUsage, TextureUsage, +}; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, +}; +use std::sync::{Arc, Mutex}; + +/// The commands of a buffer, and the cells of the target: a command draws the lower half of the +/// cell of its vertex start's third. +const COMMANDS: u32 = 32; +const SIDE: u64 = 64; +const CELL: u64 = 8; +const CELLS: u64 = (SIDE / CELL) * (SIDE / CELL); + +/// The cell a CPU setter moves command 0's draw to, past every command's own. +const MOVED_TO: u64 = 40; + +/// `icb_vertex`: the `float4` at vertex `id` of vertex buffer 0; `icb_fragment`: opaque magenta. +const FUNCTIONS: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ +target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ +define <4 x float> @icb_vertex(ptr addrspace(1) noundef readonly %v, i32 noundef %id) {\n\ +entry:\n\ + %i = zext i32 %id to i64\n\ + %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %v, i64 %i\n\ + %x = load <4 x float>, ptr addrspace(1) %p, align 16\n\ + ret <4 x float> %x\n\ +}\n\n\ +define <4 x float> @icb_fragment() {\n\ +entry:\n\ + ret <4 x float> \n\ +}\n\n\ +!llvm.module.flags = !{!0, !1}\n!air.vertex = !{!20}\n!air.fragment = !{!30}\n\ +!air.version = !{!8}\n!air.language_version = !{!9}\n\ +!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n\ +!1 = !{i32 7, !\"air.max_constant_buffers\", i32 31}\n\ +!8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\ +!20 = !{ptr @icb_vertex, !21, !23}\n\ +!21 = !{!22}\n\ +!22 = !{!\"air.position\", !\"air.arg_type_name\", !\"float4\"}\n\ +!23 = !{!24, !25}\n\ +!24 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"v\"}\n\ +!25 = !{i32 1, !\"air.vertex_id\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"id\"}\n\ +!26 = !{!27}\n\ +!27 = !{!\"air.render_target\", i32 0, i32 0, !\"air.arg_type_name\", !\"float4\"}\n\ +!28 = !{}\n\ +!30 = !{ptr @icb_fragment, !26, !28}\n"; + +/// The fragment function's color, exact in `RGBA8Unorm`. +const TEXEL: [u8; 4] = [255, 0, 255, 255]; + +/// What every test uses, on a device whose notices it hears. +struct Ours { + device: Device, + heard: Arc>>, + writer: ComputePipelineState, + state: RenderPipelineState, + target: Texture, + /// Three vertices a cell: its lower half. + vertices: Buffer, + /// The writer's third argument, a word a thread. + out: Buffer, + _scratch: Scratch, +} + +/// The counts a test reads: moves, their bytes, and staged accesses. +fn moves(counts: &WorkCounts) -> [u64; 3] { + [ + counts.icb_records_moved_to_host, + counts.icb_record_bytes_moved, + counts.icb_records_staged_accesses, + ] +} + +/// Commit `command_buffer` and wait for it to complete. +fn run(command_buffer: &CommandBuffer) { + command_buffer.commit().unwrap(); + wait(command_buffer); +} + +/// Wait for `command_buffer` to complete. +fn wait(command_buffer: &CommandBuffer) { + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!( + command_buffer.status(), + CommandBufferStatus::Completed, + "{:?}", + command_buffer.error() + ); +} + +/// Three vertices a cell in normalized device coordinates, the cells in rows from the bottom left. +fn vertices() -> Vec { + let across = SIDE / CELL; + let step = 2.0 * CELL as f32 / SIDE as f32; + (0..CELLS) + .flat_map(|cell| { + let x = -1.0 + step * (cell % across) as f32; + let y = -1.0 + step * (cell / across) as f32; + [[x, y], [x + step, y], [x, y + step]] + }) + .flat_map(|[x, y]| [x, y, 0.0, 1.0]) + .flat_map(f32::to_le_bytes) + .collect() +} + +impl Ours { + fn new(leg: &str) -> Ours { + let scratch = Scratch::new(leg); + let heard = Arc::new(Mutex::new(Vec::new())); + let sink = Arc::clone(&heard); + let mut options = options(&scratch.0); + options.messages = Some(MessageSink::new(move |message| { + if let Some(notice) = &message.degradation { + sink.lock().unwrap().push(notice.clone()); + } + })); + let device = Device::system_default_with(&options).unwrap(); + let bitcode = metal2vulkan_devtools::llvm_assemble_text(FUNCTIONS).unwrap(); + let functions = device.new_library_with_compile_library( + metal2vulkan::library::Library::from_air(&bitcode).unwrap(), + ); + let function = |name: &str| { + StageSource::Function( + functions + .new_function_with_name(name) + .unwrap() + .function_descriptor(), + ) + }; + let mut descriptor = RenderPipelineDescriptor::new(function("icb_vertex")); + descriptor.fragment = Some(function("icb_fragment")); + descriptor.color_attachments[0] = + Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + descriptor.support_indirect_command_buffers = true; + let state = device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap(); + let writer = library(&device, "kernel_icb_encode_render_commands.ll") + .new_function_with_name("kernel_icb_encode_render_commands") + .unwrap(); + let writer = + ComputePipelineDescriptor::new(StageSource::Function(writer.function_descriptor())); + let writer = device + .new_compute_pipeline_state(&writer, &PipelineOptions::default()) + .unwrap(); + let mut target = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + target.usage = TextureUsage::RENDER_TARGET; + target.resource_options = ResourceOptions::private(); + let target = device.new_texture(&target).unwrap(); + let vertices = device + .new_buffer_with_bytes(&vertices(), ResourceOptions::shared()) + .unwrap(); + let out = device + .new_buffer(4 * u64::from(COMMANDS), ResourceOptions::shared()) + .unwrap(); + Ours { + device, + heard, + writer, + state, + target, + vertices, + out, + _scratch: scratch, + } + } + + /// Whether the device places records by their first use: without unified memory, with a + /// staging queue (`home.rs`). + fn placing(&self) -> bool { + !self.device.properties().has_unified_memory && self.device.has_staging_queue() + } + + /// A buffer of [`COMMANDS`] draws that inherit the pipeline state, of `options`' storage. + fn icb(&self, options: ResourceOptions) -> IndirectCommandBuffer { + let mut descriptor = IndirectCommandBufferDescriptor::new(); + descriptor.command_types = IndirectCommandType::DRAW; + descriptor.inherit_pipeline_state = true; + descriptor.max_vertex_buffer_bind_count = 2; + descriptor.max_fragment_buffer_bind_count = 2; + self.device + .new_indirect_command_buffer(&descriptor, u64::from(COMMANDS), options) + .unwrap() + } + + /// The kernel's writes of every command of `icb` through an argument buffer that holds it, + /// committed and waited for. + fn encode_on_gpu(&self, icb: &IndirectCommandBuffer) { + let arguments = self + .device + .new_buffer_with_bytes( + &icb.gpu_resource_id().0.to_le_bytes(), + ResourceOptions::shared(), + ) + .unwrap(); + let queue = self.device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&self.writer).unwrap(); + encoder.set_buffer(Some(&arguments), 0, 0).unwrap(); + encoder.set_buffer(Some(&self.vertices), 0, 1).unwrap(); + encoder.set_buffer(Some(&self.out), 0, 2).unwrap(); + encoder + .use_resource(icb.as_resource(), ResourceUsage::WRITE) + .unwrap(); + encoder + .dispatch_threads(Size::new(u64::from(COMMANDS), 1, 1), Size::new(32, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + run(&command_buffer); + } + + /// The CPU's writes of every command of `icb`, as the kernel writes them. + fn encode_on_cpu(&self, icb: &IndirectCommandBuffer) { + for index in 0..u64::from(COMMANDS) { + let command = icb.indirect_render_command_at(index).unwrap(); + command + .set_vertex_buffer(Some(&self.vertices), 0, 0) + .unwrap(); + command + .set_fragment_buffer(Some(&self.vertices), 0, 1) + .unwrap(); + command + .draw_primitives(PrimitiveType::Triangle, 3 * index, 3, 1, 0) + .unwrap(); + } + } + + /// A render pass over the cleared target that executes every command of `icb`, encoded, not + /// committed. + fn execute(&self, icb: &IndirectCommandBuffer) -> CommandBuffer { + let queue = self.device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(self.target.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&self.state).unwrap(); + encoder + .use_resource( + self.vertices.as_resource(), + ResourceUsage::READ, + RenderStages::VERTEX, + ) + .unwrap(); + encoder + .execute_commands_in_buffer(icb, 0..u64::from(COMMANDS)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer + } + + /// The cells the last pass drew: texel (1, 6) of each, inside its lower half's triangle + /// whatever the rasterizer's rules for its edges, is [`TEXEL`]. + fn drawn(&self) -> Vec { + let row = SIDE * 4; + let readback = self + .device + .new_buffer(row * SIDE, ResourceOptions::shared()) + .unwrap(); + let queue = self.device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_texture_to_buffer( + &self.target, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(SIDE, SIDE, 1), + &readback, + 0, + row, + row * SIDE, + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + run(&command_buffer); + let contents = readback.contents().unwrap(); + // SAFETY: `contents` holds the buffer's bytes, which no command buffer writes now. + let texels = + unsafe { std::slice::from_raw_parts(contents.as_ptr(), readback.length() as usize) }; + let across = SIDE / CELL; + (0..CELLS) + .filter(|cell| { + let (cx, cy) = (cell % across, cell / across); + let x = cx * CELL + 1; + let y = SIDE - 1 - (cy * CELL + 1); + let at = ((y * SIDE + x) * 4) as usize; + texels[at..at + 4] == TEXEL + }) + .collect() + } + + /// The vertex start command `index`'s draw holds, as its getter answers it. + fn vertex_start(&self, icb: &IndirectCommandBuffer, index: u64) -> u64 { + let command = icb.indirect_render_command_at(index).unwrap(); + match command.draw().unwrap() { + Some(IndirectDraw::Primitives { vertex_start, .. }) => vertex_start, + other => panic!("command {index} holds {other:?}"), + } + } + + /// How many `staged-indirect-records` notices the device announced. + fn staged_notices(&self) -> usize { + (self.heard.lock().unwrap().iter()) + .filter(|notice| notice.degradation == Degradation::StagedIndirectRecords) + .count() + } + + /// The counts of [`moves`] since `before`. + fn moved_since(&self, before: [u64; 3]) -> [u64; 3] { + let now = moves(&self.device.work_counts()); + [0, 1, 2].map(|at| now[at] - before[at]) + } +} + +/// Every command's own cell. +fn every_command() -> Vec { + (0..u64::from(COMMANDS)).collect() +} + +/// The bytes of a buffer of [`COMMANDS`]' records: its header, records and written flags. +fn storage_bytes() -> u64 { + written_flag_offset(COMMANDS, COMMANDS) +} + +/// A `Shared` buffer a kernel writes through an argument buffer, executed twice: its records +/// lie in device-local memory where the device places them, held by no command buffer once both +/// completed, and nothing moves or is staged; the passes draw every command. +#[test] +fn gpu_encoded_shared_records_stay_on_the_device_across_executions() { + let ours = Ours::new("icb-home-gpu"); + let icb = ours.icb(ResourceOptions::shared()); + let before = moves(&ours.device.work_counts()); + ours.encode_on_gpu(&icb); + for _ in 0..2 { + run(&ours.execute(&icb)); + assert_eq!(ours.drawn(), every_command()); + } + assert_eq!(icb.records_on_device(), (ours.placing(), 0)); + assert_eq!(ours.moved_since(before), [0, 0, 0]); + assert_eq!(ours.staged_notices(), 0); +} + +/// A `Shared` buffer the CPU writes first: its records lie in the host's memory from the first +/// setter, a move of no bytes where the device places records, and no access is staged; the pass +/// draws every command and the getters answer them. +#[test] +fn cpu_encoded_shared_records_move_once_with_no_bytes() { + let ours = Ours::new("icb-home-cpu"); + let icb = ours.icb(ResourceOptions::shared()); + let before = moves(&ours.device.work_counts()); + ours.encode_on_cpu(&icb); + run(&ours.execute(&icb)); + assert_eq!(ours.drawn(), every_command()); + assert_eq!(ours.vertex_start(&icb, 7), 21); + assert_eq!(icb.records_on_device(), (false, 0)); + assert_eq!(ours.moved_since(before), [u64::from(ours.placing()), 0, 0]); + assert_eq!(ours.staged_notices(), 0); +} + +/// A getter of a `Shared` buffer a kernel wrote, once no command buffer holds its records: they +/// move into the host's memory with the GPU's bytes, a getter answers what the kernel wrote, and +/// a later execution draws every command from there. +#[test] +fn a_getter_after_the_gpu_wrote_moves_the_records_with_their_bytes() { + let ours = Ours::new("icb-home-getter"); + let icb = ours.icb(ResourceOptions::shared()); + ours.encode_on_gpu(&icb); + let before = moves(&ours.device.work_counts()); + for index in [0, 5, u64::from(COMMANDS) - 1] { + assert_eq!(ours.vertex_start(&icb, index), 3 * index); + } + let bytes = storage_bytes() * u64::from(ours.placing()); + assert_eq!( + ours.moved_since(before), + [u64::from(ours.placing()), bytes, 0] + ); + assert_eq!(icb.records_on_device(), (false, 0)); + run(&ours.execute(&icb)); + assert_eq!(ours.drawn(), every_command()); + assert_eq!(ours.staged_notices(), 0); +} + +/// A `Private` buffer's records never move: a kernel writes them, then each host access, a getter +/// and a setter, is staged where the device places records, announced once; the getter answers +/// what the kernel wrote and the pass draws the setter's write. +#[test] +fn private_records_never_move_and_their_host_accesses_are_staged() { + let ours = Ours::new("icb-home-private"); + let icb = ours.icb(ResourceOptions::private()); + ours.encode_on_gpu(&icb); + let before = moves(&ours.device.work_counts()); + assert_eq!(ours.vertex_start(&icb, 9), 27); + let command = icb.indirect_render_command_at(0).unwrap(); + command + .draw_primitives(PrimitiveType::Triangle, 3 * MOVED_TO, 3, 1, 0) + .unwrap(); + run(&ours.execute(&icb)); + let mut expected: Vec = (1..u64::from(COMMANDS)).collect(); + expected.push(MOVED_TO); + assert_eq!(ours.drawn(), expected); + let [moved, bytes, staged] = ours.moved_since(before); + assert_eq!((moved, bytes), (0, 0)); + match ours.placing() { + true => assert!(staged >= 2, "{staged} staged accesses"), + false => assert_eq!(staged, 0), + } + assert_eq!(icb.records_on_device(), (ours.placing(), 0)); + assert_eq!(ours.staged_notices(), usize::from(ours.placing())); +} + +/// A getter and a setter of a `Shared` buffer a kernel wrote while a command buffer that executes +/// it is not yet committed: each is staged where the device places records, announced once, the +/// getter answering what the kernel wrote and the command buffer drawing the setter's write once +/// committed; once it completed, the next access moves the records, and is not staged. +#[test] +fn a_held_buffer_s_host_accesses_are_staged_until_its_holder_completes() { + let ours = Ours::new("icb-home-held"); + let icb = ours.icb(ResourceOptions::shared()); + ours.encode_on_gpu(&icb); + let holder = ours.execute(&icb); + assert_eq!( + icb.records_on_device(), + (ours.placing(), u32::from(ours.placing())) + ); + let before = moves(&ours.device.work_counts()); + assert_eq!(ours.vertex_start(&icb, 9), 27); + let command = icb.indirect_render_command_at(0).unwrap(); + command + .draw_primitives(PrimitiveType::Triangle, 3 * MOVED_TO, 3, 1, 0) + .unwrap(); + let staged = ours.moved_since(before); + match ours.placing() { + true => assert_eq!(staged, [0, 0, 2]), + false => assert_eq!(staged, [0, 0, 0]), + } + run(&holder); + let mut expected: Vec = (1..u64::from(COMMANDS)).collect(); + expected.push(MOVED_TO); + assert_eq!(ours.drawn(), expected); + assert_eq!(icb.records_on_device(), (ours.placing(), 0)); + let before = moves(&ours.device.work_counts()); + assert_eq!(ours.vertex_start(&icb, 0), 3 * MOVED_TO); + let bytes = storage_bytes() * u64::from(ours.placing()); + assert_eq!( + ours.moved_since(before), + [u64::from(ours.placing()), bytes, 0] + ); + assert_eq!(icb.records_on_device(), (false, 0)); + assert_eq!(ours.staged_notices(), usize::from(ours.placing())); +} + +/// A kernel writes a `Shared` buffer through an argument buffer, a pass executes it, a blit resets +/// its commands, a pass executes it again and draws nothing (the control: the check of what is +/// drawn sees an empty pass), the kernel writes it again and a pass draws every command: the +/// blit's reset is GPU work, so the records stay in device-local memory throughout where the +/// device places them, nothing moves and nothing is staged. +#[test] +fn a_blit_reset_between_gpu_encodes_keeps_the_records_on_the_device() { + let ours = Ours::new("icb-home-reset"); + let icb = ours.icb(ResourceOptions::shared()); + let before = moves(&ours.device.work_counts()); + ours.encode_on_gpu(&icb); + run(&ours.execute(&icb)); + assert_eq!(ours.drawn(), every_command()); + let queue = ours.device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.reset_commands_in_buffer(&icb, 0..u64::from(COMMANDS)) + .unwrap(); + blit.end_encoding().unwrap(); + run(&command_buffer); + assert_eq!(icb.records_on_device(), (ours.placing(), 0)); + run(&ours.execute(&icb)); + assert_eq!(ours.drawn(), Vec::::new()); + ours.encode_on_gpu(&icb); + run(&ours.execute(&icb)); + assert_eq!(ours.drawn(), every_command()); + assert_eq!(icb.records_on_device(), (ours.placing(), 0)); + assert_eq!(ours.moved_since(before), [0, 0, 0]); + assert_eq!(ours.staged_notices(), 0); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index dc12f1484..12cee1958 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -365,6 +365,8 @@ mod icb_carry_race; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod icb_encode_bench; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod icb_records_home; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod icon_coverage; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod icon_levels; diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index c6e273b55..de9c84b32 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -213,6 +213,9 @@ pub(crate) struct Counters { indirect_record_bytes_gpu_copied: AtomicU64, indirect_record_bytes_gpu_reset: AtomicU64, indirect_record_reset_gpu_nanos: AtomicU64, + icb_records_moved_to_host: AtomicU64, + icb_record_bytes_moved: AtomicU64, + icb_records_staged_accesses: AtomicU64, indirect_write_residencies_unmarked: AtomicU64, indirect_chunks_kept: AtomicU64, indirect_commands_kept: AtomicU64, @@ -2812,6 +2815,19 @@ impl Counters { (self.indirect_record_reset_gpu_nanos).fetch_add(nanos, Ordering::Relaxed); } + /// An indirect command buffer's records came to lie in host memory for good at a host access, + /// `bytes` of them copied there from device-local memory (`indirect_command_buffer/home.rs`). + pub(crate) fn icb_records_moved_to_host(&self, bytes: u64) { + (self.icb_records_moved_to_host).fetch_add(1, Ordering::Relaxed); + (self.icb_record_bytes_moved).fetch_add(bytes, Ordering::Relaxed); + } + + /// A host access of an indirect command buffer's records in device-local memory went through + /// the staging queue (`indirect_command_buffer/home.rs`). + pub(crate) fn icb_records_staged_access(&self) { + (self.icb_records_staged_accesses).fetch_add(1, Ordering::Relaxed); + } + /// `count` records of an indirect command buffer's commands were read from its storage and /// decoded (`indirect_command_buffer.rs`). pub(crate) fn indirect_records_read(&self, count: u64) { @@ -6929,6 +6945,22 @@ pub struct WorkCounts { /// device writes timestamps and its driver's timestamps do not wait for every queue's /// (`DriverFact::TimestampsWaitForEveryQueue`); elsewhere none is written and this stays 0. pub indirect_record_reset_gpu_nanos: u64, + /// Indirect command buffers whose records came to lie in host memory for good at a host + /// access (a setter, a getter, a CPU reset, a commit or host step that reads them) on a device + /// without unified memory (`indirect_command_buffer/home.rs`): one placed there by its first + /// use, or one the GPU used first whose records moved there from device-local memory once no + /// command buffer held them. A `Private` buffer's never move. + pub icb_records_moved_to_host: u64, + /// Bytes of indirect command buffers' records those moves copied from device-local memory into + /// host memory, through the staging queue: the whole storage where the GPU may have written + /// the records, none where it did not or nothing placed them in device-local memory. + pub icb_record_bytes_moved: u64, + /// Host accesses of indirect command buffers' records in device-local memory that went through + /// the staging queue (`indirect_command_buffer/home.rs`): a `Private` buffer's, and a `Shared` + /// one's while a command buffer that used its records was not complete or dropped. Each copies + /// the records it reads into host memory, and the records it writes back, waiting for the + /// copies (`Degradation::StagedIndirectRecords`). + pub icb_records_staged_accesses: u64, /// Indirect command buffers a committed command buffer made resident for writing /// (`use_resource` or `use_resources` with `ResourceUsage::WRITE`, in any of its encoders) and /// left unmarked (`IndirectCommandBuffer::gpu_written` still `false`): it set no pipeline state @@ -11063,6 +11095,10 @@ impl Device { .load(Ordering::Relaxed), indirect_record_reset_gpu_nanos: (counters.indirect_record_reset_gpu_nanos) .load(Ordering::Relaxed), + icb_records_moved_to_host: (counters.icb_records_moved_to_host).load(Ordering::Relaxed), + icb_record_bytes_moved: counters.icb_record_bytes_moved.load(Ordering::Relaxed), + icb_records_staged_accesses: (counters.icb_records_staged_accesses) + .load(Ordering::Relaxed), indirect_record_bytes_copied: (counters.indirect_record_bytes_copied) .load(Ordering::Relaxed), indirect_write_residencies_unmarked: (counters.indirect_write_residencies_unmarked) diff --git a/crates/metal2vulkan-validation/src/runtime_lane/blits.rs b/crates/metal2vulkan-validation/src/runtime_lane/blits.rs index 50c41442a..7fc61846d 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/blits.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/blits.rs @@ -12,9 +12,11 @@ use super::{ CaseResources, Messages, ScratchCache, }; use crate::gpu::TEST_DEVICE; +use metal2vulkan::metal::{IndirectCommandType, PrimitiveType}; use metal2vulkan_runtime::{ Buffer, CommandBuffer, CommandQueue, CpuCacheMode, Degradation, Device, DeviceKind, Error, - EventRef, HazardTrackingMode, Invalid, Problem, ResourceOptions, SharedEvent, StorageMode, + EventRef, HazardTrackingMode, IndirectCommandBufferDescriptor, IndirectDraw, Invalid, Problem, + ResourceOptions, SharedEvent, StorageMode, }; use std::collections::BTreeMap; use std::time::Duration; @@ -437,6 +439,55 @@ fn managed_buffers_follow_the_memory_model() { /// and expects absent with it. pub(super) const SYSTEM_MEMORY: [Degradation; 1] = [Degradation::SharedInSystemMemory]; +/// The kind [`private_indirect_records_follow_the_memory_model`] takes where a `Private` +/// indirect command buffer's records lie in device-local memory, and expects absent elsewhere. +pub(super) const STAGED_RECORDS: [Degradation; 1] = [Degradation::StagedIndirectRecords]; + +/// A `Private` indirect command buffer's records lie in device-local memory on a device without +/// unified memory that reserves a staging queue, where the CPU reaches them only through that +/// queue's copies: its two setters and its getter are each staged, announced once +/// ([`STAGED_RECORDS`]); with unified memory none is, and nothing is announced. Either way the +/// getter answers what the setter wrote. +#[test] +fn private_indirect_records_follow_the_memory_model() { + on_device_with(|device, messages| { + messages.take_notices(); + let mut descriptor = IndirectCommandBufferDescriptor::new(); + descriptor.command_types = IndirectCommandType::DRAW; + let icb = device + .new_indirect_command_buffer(&descriptor, 4, ResourceOptions::private()) + .unwrap(); + let before = device.work_counts(); + for index in 0..2 { + let command = icb.indirect_render_command_at(index).unwrap(); + command + .draw_primitives(PrimitiveType::Triangle, 3 * index, 3, 1, 0) + .unwrap(); + } + let draw = icb.indirect_render_command_at(1).unwrap().draw().unwrap(); + let Some(IndirectDraw::Primitives { vertex_start, .. }) = draw else { + panic!("command 1 holds {draw:?}"); + }; + assert_eq!(vertex_start, 3); + let after = device.work_counts(); + let staged = after.icb_records_staged_accesses - before.icb_records_staged_accesses; + assert_eq!( + after.icb_records_moved_to_host, + before.icb_records_moved_to_host + ); + if device.properties().has_unified_memory { + assert_eq!(staged, 0); + } + let expected: &[Degradation] = match staged { + 0 => &[], + 3 => &STAGED_RECORDS, + _ => panic!("{staged} staged accesses, not 0 or 3"), + }; + let announced = assert_once(&messages.take_notices(), expected); + assert_eq!(announced.into_keys().collect::>(), expected); + }); +} + /// `Shared` storage lies where a Mac places it (docs/API.md "The runtime's memory model"): on a /// device without unified memory the first buffer of the default CPU cache mode the program makes /// announces `shared-in-system-memory`, once, and neither a buffer of the write-combined mode nor diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index 3e9c2a55f..d1cdab161 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -39,6 +39,7 @@ //! sparse textures on a device without strict residency ([`SPARSE`]), overlapping copies between textures over //! buffers ([`OVERLAPS`]), commands writing a shadowed texture's bytes two ways ([`MERGES`]), //! `Shared` buffers in system memory on a device without unified memory ([`SYSTEM_MEMORY`]), +//! `Private` indirect command buffers' records the CPU reaches through copies ([`STAGED_RECORDS`]), //! amplified draws drawn one amplification at a time ([`AMPLIFICATION`]), render pipeline states //! whose fragment rounds its color writes in `color_writes` ([`COLOR_WRITES`]), render pipeline //! states whose stages an archive holds from two adds in `binary_archives` ([`ARCHIVES`]), @@ -166,7 +167,7 @@ use super::astc_textures::{decodes_astc, ASTC_TWINS, CPU_DECODES}; use super::attachment_reads::IN_PLACE; use super::barycentric_weights::SYNTHESIZED_GEOMETRY; use super::binary_archives::ARCHIVES; -use super::blits::SYSTEM_MEMORY; +use super::blits::{STAGED_RECORDS, SYSTEM_MEMORY}; use super::buffer_texture_blits::{ COLLIDING_ROWS, NARROW_ROWS, OVERLAPS, SURFACE_APART, SURFACE_TAILS, }; @@ -527,6 +528,7 @@ fn every_kind_has_a_site_a_lane_test_takes() { &OVERLAPS, &MERGES, &SYSTEM_MEMORY, + &STAGED_RECORDS, &LIFICATION, &COLOR_WRITES, &ARCHIVES, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index dc1966e3f..4c1c7de04 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 = 522; /// 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 = 2293; +pub const RUNTIME_VERSION: u32 = 2294; /// 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 09a26052f..47d68ca3e 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3174,6 +3174,9 @@ field metal2vulkan-runtime::WorkCounts.host_texture_shadows_unchecked pub host_t field metal2vulkan-runtime::WorkCounts.host_textures_in_place pub host_textures_in_place: u64 field metal2vulkan-runtime::WorkCounts.host_textures_in_place_written pub host_textures_in_place_written: u64 field metal2vulkan-runtime::WorkCounts.host_textures_moved_in_place pub host_textures_moved_in_place: u64 +field metal2vulkan-runtime::WorkCounts.icb_record_bytes_moved pub icb_record_bytes_moved: u64 +field metal2vulkan-runtime::WorkCounts.icb_records_moved_to_host pub icb_records_moved_to_host: u64 +field metal2vulkan-runtime::WorkCounts.icb_records_staged_accesses pub icb_records_staged_accesses: u64 field metal2vulkan-runtime::WorkCounts.idle_submits pub idle_submits: u64 field metal2vulkan-runtime::WorkCounts.image_blits_recorded pub image_blits_recorded: u64 field metal2vulkan-runtime::WorkCounts.image_blocks_made_ahead pub image_blocks_made_ahead: u64 @@ -5994,6 +5997,7 @@ macro-member metal2vulkan-runtime::Degradation::SparseResidency SparseResidency macro-member metal2vulkan-runtime::Degradation::SplitBufferFill SplitBufferFill = "split-buffer-fill", Performance, macro-member metal2vulkan-runtime::Degradation::SplitDispatch SplitDispatch = "split-dispatch", Performance, macro-member metal2vulkan-runtime::Degradation::SrgbTexelDecode SrgbTexelDecode = "srgb-texel-decode"; +macro-member metal2vulkan-runtime::Degradation::StagedIndirectRecords StagedIndirectRecords = "staged-indirect-records", Performance, macro-member metal2vulkan-runtime::Degradation::StagedTextureBuffer StagedTextureBuffer = "staged-texture-buffer", Performance, macro-member metal2vulkan-runtime::Degradation::StagedTextureCopy StagedTextureCopy = "staged-texture-copy", Performance, macro-member metal2vulkan-runtime::Degradation::StaleDetachedReach StaleDetachedReach = "stale-detached-reach", Precision, diff --git a/docs/API.md b/docs/API.md index 515569fb2..136645083 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2657,6 +2657,20 @@ bound. for an execution committed before a route that may write the records met the buffer, the call that met it: a later commit, a blit's, or a CPU setter's); without device addresses, a command's first buffer shape compiles its variant then. +- `metal2vulkan-degrade-staged-indirect-records` (performance). `StagedIndirectRecords`: A host + access of an indirect command buffer's records (a setter, a getter, a CPU reset, a commit or host + step that reads them) on a device without unified memory that reserves a staging queue, where the + records lie in device-local memory and must stay there: a `Private` buffer's, which the first + use places there for good, or a `Shared` one's that the GPU used first while a command buffer that + used them is not complete or dropped. A `Shared` buffer's records lie where their first use + places them: in device-local memory where the GPU's use (an execution, `useResource`, a blit's + copy, reset or optimize) comes first, where kernels write and executions read them without + crossing the link, and otherwise in host memory. They move into host memory for good at the + first host access no command buffer holds them for, copying them there where the GPU may have + written them. To avoid it, touch a `Shared` buffer from the CPU before the GPU uses it. Cost: a + round trip through the device's staging queue for each such access: the records it reads are + copied into host memory first, and those it writes copied back after, each copy waited for, + where Metal's CPU reads and writes the records in place. - `metal2vulkan-degrade-uncalibrated-gpu-times` (precision). `UncalibratedGpuTimes`: A command buffer's GPU times on a device that calibrates its timestamps against no host clock the runtime reads (no `VK_KHR_calibrated_timestamps` or `VK_EXT_calibrated_timestamps` with the device's time