diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl index 09dd4cc415..91cc2ff662 100644 --- a/crates/gpu/src/compose.wgsl +++ b/crates/gpu/src/compose.wgsl @@ -73,14 +73,10 @@ const F_LAYER_SHAPE: u32 = 1048576u; // fx merge: B is the shape; layer = its co @group(1) @binding(6) var map_tex: texture_2d; @group(1) @binding(7) var pat_tex: texture_2d; +// The full-chunk triangle's vertex stage lives in `vertex_shader` (kit.rs): one entry point per +// pipeline build job, so no two threads share a compiled vertex shader. struct VOut { @builtin(position) pos: vec4 }; -@vertex -fn vs(@builtin(vertex_index) vi: u32) -> VOut { - let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u)); - return VOut(vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0)); -} - fn local(pos: vec4) -> vec2 { return vec2(floor(pos.xy)); } fn doc_px(p: vec2) -> vec2 { return chunk.origin + p; } diff --git a/crates/gpu/src/kit.rs b/crates/gpu/src/kit.rs index 6ac1b76dc3..60c640e0d1 100644 --- a/crates/gpu/src/kit.rs +++ b/crates/gpu/src/kit.rs @@ -1,4 +1,4 @@ -use super::consts::{CHUNK_UNIFORM, OP_UNIFORM, STRIDE}; +use super::consts::{CHUNK_UNIFORM, MAP16, MAP32, OP_UNIFORM, STRIDE}; use super::convert::{lut_texture, words}; use super::textures::{ResKey, ResidentRef}; use super::{Arc, HashMap, I, Kernel, NonZeroU64, Rect}; @@ -127,6 +127,46 @@ pub(crate) fn uniform_entry(binding: u32, size: u64) -> wgpu::BindGroupLayoutEnt /// The compositor's WGSL source (exposed for validation in tests). pub const SHADER: &str = include_str!("compose.wgsl"); +/// The compositor's pipelines, grouped by the thread that builds them: one job per kernel, and +/// an effect-map kernel's R32F and R16F pipelines in the same job. With [`vertex_entry`], no two +/// jobs share a shader (see `Compositor::build`). +pub(crate) fn build_jobs(acc_format: wgpu::TextureFormat) -> Vec> { + let one = |k: Kernel| if k.is_map() { vec![(k, MAP32), (k, MAP16)] } else { vec![(k, acc_format)] }; + let (plain, maps): (Vec, Vec) = Kernel::DRAWN.iter().partition(|k| !k.is_map()); + plain.into_iter().chain(maps).map(one).collect() +} + +/// The vertex entry point of build job `job` in [`vertex_shader`]. +pub(crate) fn vertex_entry(job: usize) -> String { + format!("vs_{job}") +} + +/// The full-chunk triangle's vertex stage, once per build job (`vs_0`, `vs_1`, ...): the same +/// code under distinct names, so each job compiles its own vertex shader. +/// +/// A workaround, not a design: wgpu-hal's D3D12 shader cache shares a compiled FXC blob between +/// threads, and FXC's blobs don't count references atomically, so a shared one can be freed +/// while still cached (gfx-rs/wgpu#10547, #9173). Each copy costs one compile of a three-line +/// shader. Once a wgpu release fixes the cache, go back to one `vs` in `compose.wgsl` and let +/// `build_jobs` split map kernels by format again. +pub(crate) fn vertex_shader(jobs: usize) -> String { + let mut s = String::from( + "struct VOut { @builtin(position) pos: vec4 }; +", + ); + for job in 0..jobs { + s.push_str(&format!( + "@vertex fn {}(@builtin(vertex_index) vi: u32) -> VOut {{ + let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u)); + return VOut(vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0)); +}} +", + vertex_entry(job) + )); + } + s +} + /// Pass-level resources resolved for one page cell: resident pages (texture, mask) and effect /// maps (view and region) per pass. pub(crate) struct Bound { diff --git a/crates/gpu/src/setup.rs b/crates/gpu/src/setup.rs index 15217ed236..ddf5670617 100644 --- a/crates/gpu/src/setup.rs +++ b/crates/gpu/src/setup.rs @@ -1,6 +1,6 @@ use super::batch::tile_grid; -use super::consts::{ACC_FORMAT, CHUNK, CHUNK_UNIFORM, FX_BUDGET, MAP16, MAP32, MAX_PATTERN_TEXTURE_BYTES, OP_UNIFORM, PAGE, PATTERN_BUDGET, RESIDENT_BUDGET}; -use super::kit::{Kit, SHADER, tex_entry, uniform_entry}; +use super::consts::{ACC_FORMAT, CHUNK, CHUNK_UNIFORM, FX_BUDGET, MAX_PATTERN_TEXTURE_BYTES, OP_UNIFORM, PAGE, PATTERN_BUDGET, RESIDENT_BUDGET}; +use super::kit::{Kit, SHADER, build_jobs, tex_entry, uniform_entry, vertex_entry, vertex_shader}; use super::paging::{cell_rect, field_reaches, first_error, grid_rects}; use super::textures::{FxEntry, Resident, Tex, TexKind}; use super::{ @@ -47,8 +47,22 @@ impl Compositor { /// built in parallel, each inside its own error scope on the thread that builds it (wgpu's /// scopes are per thread): on DX12, FXC compiles one shader at a time and the ~30 pipelines /// took about 8 s on one core (#6419). + /// + /// No shader is used by two threads at once (#9173): wgpu-hal's D3D12 backend caches each + /// compiled shader and hands every pipeline a reference to it, but FXC's blobs count + /// references without atomics (gfx-rs/wgpu#10547), so threads sharing one could free it + /// while the cache still held it, and dropping the device then aborted the process. So each + /// job has its own vertex entry point and fragment shaders ([`build_jobs`]), and builds of + /// several compositors take turns. fn build(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> (Self, Option) { + static BUILDING: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let _building = BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_compose"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let jobs = build_jobs(acc_format); + let vertex = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("pc_compose_vertex"), + source: wgpu::ShaderSource::Wgsl(vertex_shader(jobs.len()).into()), + }); let bgl0 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_compose_uniforms"), entries: &[uniform_entry(0, CHUNK_UNIFORM), uniform_entry(1, OP_UNIFORM)], @@ -63,12 +77,12 @@ impl Compositor { immediate_size: 0, }); // `None` only for kernels without a fragment entry point, which are never drawn. - let pipeline = |k: Kernel, format: wgpu::TextureFormat| { + let pipeline = |k: Kernel, format: wgpu::TextureFormat, vs: &str| { let entry = k.entry()?; Some(device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some(entry), layout: Some(&layout), - vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, + vertex: wgpu::VertexState { module: &vertex, entry_point: Some(vs), buffers: &[], compilation_options: Default::default() }, primitive: wgpu::PrimitiveState::default(), depth_stencil: None, multisample: wgpu::MultisampleState::default(), @@ -84,12 +98,16 @@ impl Compositor { }; // Effect maps render to R32Float / R16Float, which some adapters (e.g. GL without float // render targets) can't: then layer effects use the CPU compositor and the rest stays here. - let keys = Kernel::DRAWN.iter().filter(|k| !k.is_map()).map(|&k| (k, acc_format)); - let keys: Vec<_> = keys.chain(Kernel::DRAWN.iter().filter(|k| k.is_map()).flat_map(|&k| [(k, MAP32), (k, MAP16)])).collect(); - let built = fx::par_map(keys, |key| { - let (built, error) = first_error(device, || pipeline(key.0, key.1)); - (key, built, error) + let built = fx::par_map(jobs.into_iter().enumerate().collect(), |(job, keys)| { + let vs = vertex_entry(job); + keys.into_iter() + .map(|key| { + let (built, error) = first_error(device, || pipeline(key.0, key.1, &vs)); + (key, built, error) + }) + .collect::>() }); + let built = built.into_iter().flatten(); let (mut pipelines, mut maps) = (HashMap::new(), Vec::new()); let (mut error, mut map_error) = (None, None); for (key, built, e) in built { diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 281c67421e..17e41851c1 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -132,6 +132,41 @@ fn half_roundtrip() { } } +/// #9173: no two pipeline build jobs share a shader, so no FXC blob is shared across threads. +#[test] +fn build_jobs_share_no_shader() { + use super::consts::{MAP16, MAP32}; + use super::kit::{build_jobs, vertex_entry, vertex_shader}; + let jobs = build_jobs(wgpu::TextureFormat::Rgba32Float); + let mut seen = std::collections::HashSet::new(); + for (job, keys) in jobs.iter().enumerate() { + let fragments: std::collections::HashSet<_> = keys.iter().filter_map(|k| k.0.entry()).collect(); + for f in fragments { + assert!(seen.insert(f.to_string()), "fragment shader {f} is built by two jobs"); + } + assert!(seen.insert(vertex_entry(job)), "vertex entry of job {job} is shared"); + } + // Every drawn pipeline is still built, in the same formats. + let keys: Vec<_> = jobs.concat(); + let plain = Kernel::DRAWN.iter().filter(|k| !k.is_map()).count(); + assert_eq!(keys.len(), plain + 2 * (Kernel::DRAWN.len() - plain)); + for k in Kernel::DRAWN { + let formats: Vec<_> = keys.iter().filter(|key| key.0 == k).map(|key| key.1).collect(); + let want = if k.is_map() { vec![MAP32, MAP16] } else { vec![wgpu::TextureFormat::Rgba32Float] }; + assert_eq!(formats, want, "{k:?}"); + } + // The vertex module validates and has every job's entry point. + let src = vertex_shader(jobs.len()); + let module = wgpu::naga::front::wgsl::parse_str(&src).unwrap_or_else(|e| panic!("{}", e.emit_to_string(&src))); + wgpu::naga::valid::Validator::new(wgpu::naga::valid::ValidationFlags::all(), wgpu::naga::valid::Capabilities::empty()) + .validate(&module) + .unwrap_or_else(|e| panic!("{e:?}")); + for job in 0..jobs.len() { + let e = vertex_entry(job); + assert!(module.entry_points.iter().any(|ep| ep.name == e && ep.stage == wgpu::naga::ShaderStage::Vertex), "missing {e}"); + } +} + #[test] fn shader_validates() { let module = wgpu::naga::front::wgsl::parse_str(SHADER).unwrap_or_else(|e| panic!("{}", e.emit_to_string(SHADER))); diff --git a/crates/gpu/tests/it/pipeline_errors.rs b/crates/gpu/tests/it/pipeline_errors.rs index 28d7a56791..2c6018fdc1 100644 --- a/crates/gpu/tests/it/pipeline_errors.rs +++ b/crates/gpu/tests/it/pipeline_errors.rs @@ -48,3 +48,55 @@ fn a_compositor_with_failed_pipelines_draws_without_panicking() { // Drawing into an unrenderable format can't succeed, but must not panic. let _ = render_to_vec(&mut comp, &device, &queue, &doc, doc.bounds()); } + +/// #9173: the compositor builds its pipelines on several threads (#6419). On Direct3D 12 with FXC, +/// wgpu-hal caches each compiled shader as an `ID3DBlob` whose reference count isn't atomic +/// (gfx-rs/wgpu#10547), so two threads building pipelines from the same shader could free a blob +/// the cache still holds; dropping the device then aborted the process (`null reference +/// produced` in `IUnknown::drop`). Each thread now builds from shaders no other thread uses. +/// +/// Stress test, ignored by default (it builds many compositors). Run it on WARP with FXC, e.g. +/// `WGPU_BACKEND=dx12 WGPU_DX12_COMPILER=fxc WGPU_ADAPTER_NAME="basic render" +/// PC_BUILD_ROUNDS=10 PC_BUILDS_PER_DEVICE=50 +/// cargo test -p photocraft-gpu --test it parallel_compositor_builds -- --ignored`. +/// Windows' full page heap makes the race abort more reliably. +#[test] +#[ignore = "stress test: builds many compositors"] +fn parallel_compositor_builds_leave_the_shader_cache_intact() { + let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let var = |name: &str, default: u32| std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default); + let (rounds, builds) = (var("PC_BUILD_ROUNDS", 4), var("PC_BUILDS_PER_DEVICE", 8)); + for round in 0..rounds { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let Ok(adapter) = pollster::block_on(wgpu::util::initialize_adapter_from_env_or_default(&instance, None)) else { + eprintln!("skipping: no adapter"); + return; + }; + if round == 0 { + let info = adapter.get_info(); + eprintln!("shader cache stress: {:?} ({}), {rounds} devices x {builds} builds", info.backend, info.name); + } + let Ok((device, _queue)) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())) else { + eprintln!("skipping: no device"); + return; + }; + let format = Compositor::preferred_acc_format(&adapter); + // The first build compiles every shader; the rest are cache hits, so their threads take + // and release references to the cached shaders densely. The builds start together, so + // overlapping `Compositor::build` calls are exercised too (the process-wide lock). + std::thread::scope(|scope| { + let handles: Vec<_> = (0..builds) + .map(|_| { + scope.spawn(|| { + let built = Compositor::try_new_with_format(&device, format); + assert!(built.is_ok(), "round {round}: {:?}", built.err()); + }) + }) + .collect(); + for handle in handles { + handle.join().expect("compositor build thread panicked"); + } + }); + // Dropping the device releases every cached blob: a freed one aborts here. + } +}