diff --git a/CHANGELOG.md b/CHANGELOG.md index 675dccda0..158ca3d77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -122,7 +122,7 @@ By @sagudev in [#10115](https://github.com/gfx-rs/wgpu/pull/10115). - Fix required immediate slots calculation and remove `naga::valid::FunctionInfo::immediate_slots_used`. By @beicause in [#9725](https://github.com/gfx-rs/wgpu/pull/9725). - Fix a spurious assertion failure in `Device::maintain` when multiple threads race polling the same device. By @AdrianEddy in [#9958](https://github.com/gfx-rs/wgpu/pull/9958). - Fix `PendingSubmission` releasing its lock guards out of stacking order, which tripped `--cfg wgpu_validate_locks` on any submission. By @AdrianEddy in [#9960](https://github.com/gfx-rs/wgpu/pull/9960). -- Fixed some cases where initialization tracking was not correct. By @andyleiserson in [#10002](https://github.com/gfx-rs/wgpu/pull/10002). +- Fix initialization tracking for some cases of array textures, 3d textures, and depth/stencil textures with divergent usage in a render pass. By @andyleiserson in [#10002](https://github.com/gfx-rs/wgpu/pull/10002) and [#10060](https://github.com/gfx-rs/wgpu/pull/10060). #### naga diff --git a/cts_runner/fail.lst b/cts_runner/fail.lst index b9c51f671..456d2f67a 100644 --- a/cts_runner/fail.lst +++ b/cts_runner/fail.lst @@ -16,7 +16,6 @@ webgpu:api,operation,memory_sync,texture,readonly_depth_stencil:sampling_while_t webgpu:api,operation,memory_sync,texture,readonly_depth_stencil:sampling_while_testing:format="depth24plus-stencil8";depthReadOnly=true;stencilReadOnly=false // https://github.com/gfx-rs/wgpu/issues/8705 webgpu:api,operation,memory_sync,texture,readonly_depth_stencil:sampling_while_testing:format="depth32float-stencil8";depthReadOnly=false;stencilReadOnly=true // https://github.com/gfx-rs/wgpu/issues/8705 webgpu:api,operation,memory_sync,texture,readonly_depth_stencil:sampling_while_testing:format="depth32float-stencil8";depthReadOnly=true;stencilReadOnly=false // https://github.com/gfx-rs/wgpu/issues/8705 -webgpu:api,operation,rendering,3d_texture_slices:* // https://github.com/gfx-rs/wgpu/issues/9455 webgpu:api,validation,buffer,create:new_usages,* // 0%, deno_webgpu declares the GPU*Usage constants as static getters, which are non-enumerable, so the test sees no legal usage bits, https://github.com/denoland/deno/issues/33846 webgpu:api,validation,buffer,mapping:* // crash diff --git a/cts_runner/test.lst b/cts_runner/test.lst index 7281126dc..b4f676c92 100644 --- a/cts_runner/test.lst +++ b/cts_runner/test.lst @@ -55,6 +55,7 @@ webgpu:api,operation,memory_sync,texture,readonly_depth_stencil:sampling_while_t webgpu:api,operation,render_pass,* webgpu:api,operation,render_pipeline,overrides:* webgpu:api,operation,render_pipeline,pipeline_output_targets:color,component_count,blend:* +webgpu:api,operation,rendering,3d_texture_slices:* webgpu:api,operation,rendering,basic:clear:* webgpu:api,operation,rendering,basic:fullscreen_quad:* //FAIL: webgpu:api,operation,rendering,basic:large_draw:* diff --git a/wgpu-core/src/command/clear.rs b/wgpu-core/src/command/clear.rs index bed7f22be..360483922 100644 --- a/wgpu-core/src/command/clear.rs +++ b/wgpu-core/src/command/clear.rs @@ -289,6 +289,7 @@ pub(super) fn clear_texture_cmd( mip_range: subresource_mip_range, layer_range: subresource_layer_range, }, + None, state.raw_encoder, &mut state.tracker.textures, &state.device.alignments, @@ -307,9 +308,15 @@ pub(super) fn clear_texture_cmd( /// [`clear_texture_cmd`], which does the validation. This function is also /// called directly from various places within wgpu that need to clear a /// texture. +/// +/// For a 3D texture: +/// - If `depth_slice` is `Some`, clear only that depth slice (in this case, +/// `range.mip_range` must be a single mip level). +/// - If `depth_slice` is `None`, clear entire mip level(s). pub(crate) fn clear_texture( dst_texture: &Arc, range: TextureInitRange, + depth_slice: Option, encoder: &mut dyn hal::DynCommandEncoder, texture_tracker: &mut T, alignments: &hal::Alignments, @@ -369,6 +376,7 @@ pub(crate) fn clear_texture( alignments, zero_buffer, range, + depth_slice, encoder, dst_raw, ), @@ -394,10 +402,21 @@ fn clear_texture_via_buffer_copies( alignments: &hal::Alignments, zero_buffer: &dyn hal::DynBuffer, // Buffer of size device::ZERO_BUFFER_SIZE range: TextureInitRange, + depth_slice: Option, encoder: &mut dyn hal::DynCommandEncoder, dst_raw: &dyn hal::DynTexture, ) { + // These preconditions should apply to `clear_texture` as a whole, but since they're + // currently only serving this function, seems clearer to keep them here. assert!(!texture_desc.format.is_depth_stencil_format()); + assert!( + depth_slice.is_none() || texture_desc.dimension == wgt::TextureDimension::D3, + "depth_slice is only applicable to 3D textures", + ); + assert!( + depth_slice.is_none() || range.mip_range.len() == 1, + "must target a single depth slice when clearing a mip level", + ); if texture_desc.format == wgt::TextureFormat::NV12 || texture_desc.format == wgt::TextureFormat::P010 @@ -436,11 +455,13 @@ fn clear_texture_via_buffer_copies( texture_desc.size ); - let z_range = 0..(if texture_desc.dimension == wgt::TextureDimension::D3 { - mip_size.depth_or_array_layers + let z_range = if let Some(depth_slice) = depth_slice { + depth_slice..depth_slice + 1 + } else if texture_desc.dimension == wgt::TextureDimension::D3 { + 0..mip_size.depth_or_array_layers } else { - 1 - }); + 0..1 + }; for array_layer in range.layer_range.clone() { // TODO: Only doing one layer at a time for volume textures right now. diff --git a/wgpu-core/src/command/compute.rs b/wgpu-core/src/command/compute.rs index 84388511e..8ad6915c1 100644 --- a/wgpu-core/src/command/compute.rs +++ b/wgpu-core/src/command/compute.rs @@ -887,6 +887,8 @@ pub(super) fn encode_compute_pass( device.instance_flags, )) .map_pass_err(pass_scope)?; + // If the compute pass reads any surfaces that were discarded by a previous + // render pass in the same command buffer, initialize them. fixup_discarded_surfaces( pending_discard_init_fixups.into_iter(), transit, diff --git a/wgpu-core/src/command/memory_init.rs b/wgpu-core/src/command/memory_init.rs index ecb2e3d9b..7087c2854 100644 --- a/wgpu-core/src/command/memory_init.rs +++ b/wgpu-core/src/command/memory_init.rs @@ -23,7 +23,11 @@ use super::{clear_texture, BakedCommands, ClearError}; pub(crate) struct TextureSurfaceDiscard { pub texture: Arc, pub mip_level: u32, - pub layer: u32, + + /// For 3D textures, this field is a depth slice, otherwise, it is an array + /// layer. Unlike the primary initialization tracker, we _do_ track + /// individual discarded depth slices during encoding of a command buffer. + pub layer_or_depth_slice: u32, } pub(crate) type SurfacesInDiscardState = Vec; @@ -33,9 +37,19 @@ pub(crate) struct CommandBufferTextureMemoryActions { /// The tracker actions that we need to be executed before the command /// buffer is executed. init_actions: Vec, - /// All the discards that haven't been followed by init again within the - /// command buffer i.e. everything in this list resets the texture init - /// state *after* the command buffer execution + /// Tracks surfaces that were previously discarded within this command buffer. + /// + /// If a later pass reads from one of these surfaces, we must insert an immediate + /// clear operation in the command sequence. (Typically, memory initialization is done + /// in a dedicated pass prepended to the entire command buffer, but the discards we are + /// tracking here occur after that). Any discarded surfaces that are not reinitialized + /// prior to the end of the command buffer, will have their `initialization_status` set + /// to uninitialized at that point, except for depth slices, which must be reinitialized + /// prior to the end of the command buffer. + /// + /// We do a linear scan of the discarded surface list for _each_ initialization + /// action, i.e., we assume that most of the time there are no discarded surfaces. + /// If this list has more than a few items, performance will suffer. discards: Vec, } @@ -56,6 +70,9 @@ impl CommandBufferTextureMemoryActions { &mut self, action: &TextureInitTrackerAction, ) -> SurfacesInDiscardState { + // Texture subresources from `self.discards` that were discarded earlier in this + // command buffer and which the present `action` requires be initialized. These + // require inline initialization, which will be done by `fixup_discarded_surfaces`. let mut immediately_necessary_clears = SurfacesInDiscardState::new(); // Note that within a command buffer we may stack arbitrary memory init @@ -79,7 +96,11 @@ impl CommandBufferTextureMemoryActions { let init_actions = &mut self.init_actions; self.discards.retain(|discarded_surface| { if discarded_surface.texture.is_equal(&action.texture) - && action.range.layer_range.contains(&discarded_surface.layer) + && discarded_surface.texture.desc.dimension != wgt::TextureDimension::D3 + && action + .range + .layer_range + .contains(&discarded_surface.layer_or_depth_slice) && action .range .mip_range @@ -91,17 +112,39 @@ impl CommandBufferTextureMemoryActions { // Mark surface as implicitly initialized (this is relevant // because it might have been uninitialized prior to // discarding + let layer = discarded_surface.layer_or_depth_slice; init_actions.push(TextureInitTrackerAction { texture: discarded_surface.texture.clone(), range: TextureInitRange { mip_range: discarded_surface.mip_level ..(discarded_surface.mip_level + 1), - layer_range: discarded_surface.layer..(discarded_surface.layer + 1), + layer_range: layer..(layer + 1), }, kind: MemoryInitKind::ImplicitlyInitialized, }); } false + } else if discarded_surface.texture.is_equal(&action.texture) + && discarded_surface.texture.desc.dimension == wgt::TextureDimension::D3 + && action + .range + .mip_range + .contains(&discarded_surface.mip_level) + { + if let MemoryInitKind::NeedsInitializedMemory = action.kind { + immediately_necessary_clears.push(discarded_surface.clone()); + + // Init tracking of 3D textures is for mip levels only (not depth + // slices). If a mip was uninitialized at the start of the + // command buffer, we recorded an init action above. We don't need + // to additionally record `ImplicitlyInitialized` for it here. + // When the actual initialization commands are prepared in + // [`Queue::submit`], `initialize_texture_memory` collects a list of any + // slices remaining in `self.discards` and returns it, and they will be + // reinitialized before the conclusion of the command buffer by + // `initialize_discarded_depth_slices`. + } + false } else { true } @@ -138,12 +181,22 @@ pub(crate) fn fixup_discarded_surfaces, ) { for init in inits { + let (layer_range, depth_slice) = if init.texture.desc.dimension == wgt::TextureDimension::D3 + { + (0..1, Some(init.layer_or_depth_slice)) + } else { + ( + init.layer_or_depth_slice..(init.layer_or_depth_slice + 1), + None, + ) + }; clear_texture( &init.texture, TextureInitRange { mip_range: init.mip_level..(init.mip_level + 1), - layer_range: init.layer..(init.layer + 1), + layer_range, }, + depth_slice, encoder, texture_tracker, &device.alignments, @@ -268,8 +321,9 @@ impl BakedCommands { /// /// Inserts all texture initializations that are going to be needed for /// executing the commands, and updates resource init states accordingly. Any - /// textures that are left discarded by this command buffer will be marked as - /// uninitialized. + /// non-3D textures that are left discarded by this command buffer will be marked as + /// uninitialized, and a list of any 3D depth slices is returned, to be reinitialized + /// just prior to the end of the command buffer. /// /// The caller is responsible for checking that any texture this may touch has not been /// destroyed, and must have done that check under the same snatch guard that is passed @@ -285,9 +339,11 @@ impl BakedCommands { device_tracker: &mut DeviceTracker, device: &Device, snatch_guard: &SnatchGuard<'_>, - ) -> Result<(), ClearError> { + ) -> Result { profiling::scope!("initialize_texture_memory"); + let mut depth_slice_discards = SurfacesInDiscardState::new(); + let mut ranges: Vec = Vec::new(); for texture_use in self.texture_memory_actions.drain_init_actions() { { @@ -324,6 +380,7 @@ impl BakedCommands { let clear_result = clear_texture( &texture_use.texture, range, + None, self.encoder.raw.as_mut(), &mut device_tracker.textures, &device.alignments, @@ -344,15 +401,80 @@ impl BakedCommands { } } - // Now that all buffers/textures have the proper init state for before - // cmdbuf start, we discard init states for textures it left discarded - // after its execution. - for surface_discard in self.texture_memory_actions.discards.iter() { - surface_discard - .texture - .initialization_status - .write() - .discard(surface_discard.mip_level, surface_discard.layer); + // Process any surfaces that remain in discarded state after + // the command buffer executes. + for surface_discard in self.texture_memory_actions.discards.drain(..) { + if surface_discard.texture.desc.dimension == wgt::TextureDimension::D3 { + // Depth slices are below the resolution of the init tracker, so + // collect a list of them to be initialized just prior to the + // end of the command buffer. + // + // We could optimize this by checking whether the entire mip is + // uninitialized (command buffer either did Clear+Discard when it was + // already uninitialized, or discarded every slice), and if so, ignore the + // pending discard, but it's not clear that happens enough for the + // optimization to be worth it. + depth_slice_discards.push(surface_discard); + } else { + // Anything else, record the discarded state in the initialization tracker. + surface_discard + .texture + .initialization_status + .write() + .discard( + surface_discard.mip_level, + surface_discard.layer_or_depth_slice, + ); + } + } + + Ok(depth_slice_discards) + } + + /// Reinitialize any depth slices that were discarded during the command buffer and not + /// subsequently reinitialized. + /// + /// This is necessary because the initialization tracker does not track the status of + /// individual depth slices. + /// + /// We do not optimize the case where _every_ depth slice of a 3D texture is discarded. + pub(crate) fn initialize_discarded_depth_slices( + &mut self, + discards: SurfacesInDiscardState, + device_tracker: &mut DeviceTracker, + device: &Device, + snatch_guard: &SnatchGuard<'_>, + ) -> Result<(), ClearError> { + for discard in discards { + assert!( + discard.texture.desc.dimension == wgt::TextureDimension::D3, + "unexpected texture dimension {:?} in initialize_discarded_depth_slices", + discard.texture.desc.dimension, + ); + let range = TextureInitRange { + mip_range: discard.mip_level..(discard.mip_level + 1), + layer_range: 0..1, + }; + let clear_result = clear_texture( + &discard.texture, + range, + Some(discard.layer_or_depth_slice), + self.encoder.raw.as_mut(), + &mut device_tracker.textures, + &device.alignments, + device.zero_buffer.as_ref(), + snatch_guard, + device.instance_flags, + ); + // We panic on destroyed textures for symmetry with the main buffer + // and initialization pass. It should not happen, but supposing it + // did, it would also be fine to return the error and lose the + // device in queue submit. + if matches!(clear_result, Err(ClearError::DestroyedResource(_))) { + panic!("attempt to initialize a destroyed texture"); + } else { + clear_result?; + } } Ok(()) diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index 5fad4b8be..ad0f6be6a 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -1142,32 +1142,78 @@ impl RenderPassInfo { store_op: StoreOp, texture_memory_actions: &mut CommandBufferTextureMemoryActions, view: &TextureView, + depth_slice: Option, pending_discard_init_fixups: &mut SurfacesInDiscardState, ) { + match ( + depth_slice, + view.parent.desc.dimension == wgt::TextureDimension::D3, + ) { + (Some(_), true) | (None, false) => {} + _ => unreachable!("3D textures, but not any other kind, must specify a depth slice"), + } + // 3D textures with more than one depth slice are a special case, + // because we don't track initialization status per slice. + let partial_z = view.parent.desc.dimension == wgt::TextureDimension::D3 + && view + .parent + .desc + .mip_level_size(view.selector.mips.start) + .is_some_and(|dim| dim.depth_or_array_layers > 1); + if matches!(load_op, LoadOp::Load) { + // Record the initialization action for the texture. Simultaneously, collect a + // list of any ranges of the texture that were discarded within the current + // command buffer, for initialization by `fixup_discarded_surfaces`. + // (The analogous case for texture copies is in `handle_texture_init`.) + // + // Even when the target is a depth slice of a 3D texture, this is an action + // for the entire mip. In most cases that is what we want (if there is any + // live data in the mip at the end of a command buffer, we must have the + // entire thing initialized). The exception is Load+Discard of one slice in an + // uninitialized mip. In that case, we could initialize only one slice, and then + // leave the entire mip uninitialized at the end of the command buffer. But we + // don't optimize that, because it is a lot of complexity for a case that + // doesn't seem very useful (if the render targets are only used transiently, + // why is it important that they are volume slices?). pending_discard_init_fixups.extend(texture_memory_actions.register_init_action( &TextureInitTrackerAction { texture: view.parent.clone(), range: TextureInitRange::from(view), - // Note that this is needed even if the target is discarded, + // Note that this is needed for `Load` even if the target has `StoreOp::Discard`. kind: MemoryInitKind::NeedsInitializedMemory, }, )); } else if store_op == StoreOp::Store { - // Clear + Store - texture_memory_actions.register_implicit_init( - &view.parent, - TextureInitRange::from(view), - ); + if partial_z { + // We must initialize the entire mip due to init tracking granularity. + pending_discard_init_fixups.extend(texture_memory_actions.register_init_action( + &TextureInitTrackerAction { + texture: view.parent.clone(), + range: TextureInitRange::from(view), + kind: MemoryInitKind::NeedsInitializedMemory, + }, + )); + } else { + // Clear + Store + texture_memory_actions + .register_implicit_init(&view.parent, TextureInitRange::from(view)); + } } if store_op == StoreOp::Discard { - // the discard happens at the *end* of a pass, but recording the - // discard right away be alright since the texture can't be used - // during the pass anyways + // The discard happens at the *end* of a pass, but recording the + // discard right away is fine, since attachments can't be used + // for any other purpose during the pass. + // + // Discards are usually deferred as long as possible (i.e. until the + // next use of the subresource). But discarded depth slices of 3D + // textures will be reinitialized at the end of the command buffer + // (by [`BakedCommands::initialize_discarded_depth_slices`]), + // because the primary init tracker does not track individual slices. texture_memory_actions.discard(TextureSurfaceDiscard { texture: view.parent.clone(), mip_level: view.selector.mips.start, - layer: view.selector.layers.start, + layer_or_depth_slice: depth_slice.unwrap_or(view.selector.layers.start), }); } } @@ -1292,6 +1338,7 @@ impl RenderPassInfo { at.depth.store_op(), texture_memory_actions, view, + None, pending_discard_init_fixups, ); } else if !ds_aspects.contains(hal::FormatAspects::DEPTH) { @@ -1300,6 +1347,7 @@ impl RenderPassInfo { at.stencil.store_op(), texture_memory_actions, view, + None, pending_discard_init_fixups, ); } else { @@ -1365,7 +1413,7 @@ impl RenderPassInfo { texture_memory_actions.discard(TextureSurfaceDiscard { texture: view.parent.clone(), mip_level: view.selector.mips.start, - layer: view.selector.layers.start, + layer_or_depth_slice: view.selector.layers.start, }); } } @@ -1520,6 +1568,7 @@ impl RenderPassInfo { at.store_op, texture_memory_actions, color_view, + at.depth_slice, pending_discard_init_fixups, ); render_attachments @@ -2626,6 +2675,8 @@ pub(super) fn encode_render_pass( )) .map_pass_err(pass_scope)?; + // If this pass reads any surfaces that were discarded by a previous + // pass in the same command buffer, initialize them. fixup_discarded_surfaces( pending_discard_init_fixups.into_iter(), transit, diff --git a/wgpu-core/src/command/transfer.rs b/wgpu-core/src/command/transfer.rs index c8d2f9237..9d92f004f 100644 --- a/wgpu-core/src/command/transfer.rs +++ b/wgpu-core/src/command/transfer.rs @@ -666,7 +666,10 @@ fn handle_texture_init( kind: init_kind, }; - // Register the init action. + // Record the initialization action. Simultaneously, collect a list of any + // ranges of the texture that were discarded within the current command + // buffer, for immediate initialization. (The analogous case for passes is + // in `fixup_discarded_surfaces`.) let immediate_inits = state .texture_memory_actions .register_init_action(&{ init_action }); @@ -674,12 +677,20 @@ fn handle_texture_init( // In rare cases we may need to insert an init operation immediately onto the command buffer. if !immediate_inits.is_empty() { for init in immediate_inits { + let index = init.layer_or_depth_slice; + let (layer_range, depth_slice) = if texture.desc.dimension == wgt::TextureDimension::D3 + { + (0..1, Some(index)) + } else { + (index..(index + 1), None) + }; clear_texture( &init.texture, TextureInitRange { mip_range: init.mip_level..(init.mip_level + 1), - layer_range: init.layer..(init.layer + 1), + layer_range, }, + depth_slice, state.raw_encoder, &mut state.tracker.textures, &state.device.alignments, diff --git a/wgpu-core/src/device/queue.rs b/wgpu-core/src/device/queue.rs index adb5c5b02..5665d1a88 100644 --- a/wgpu-core/src/device/queue.rs +++ b/wgpu-core/src/device/queue.rs @@ -156,6 +156,7 @@ impl Queue { mip_range: 0..1, layer_range: 0..1, }, + None, encoder, &mut trackers.textures, &device.alignments, @@ -1089,6 +1090,7 @@ impl Queue { mip_range: destination.mip_level..(destination.mip_level + 1), layer_range, }, + None, encoder, &mut trackers.textures, &self.device.alignments, @@ -1377,6 +1379,7 @@ impl Queue { mip_range: destination.mip_level..(destination.mip_level + 1), layer_range, }, + None, encoder, &mut trackers.textures, &self.device.alignments, @@ -1620,7 +1623,7 @@ impl Queue { // this stage: // - `hal` command encoding errors. These produce device loss in // `handle_hal_error`, independent of what we do here. - // - Errors from `initialize_texture_memory`. The error cases that + // - Errors from texture initialization. The error cases that // can actually occur should also be encoder errors, but we map // everything to device loss, just in case. lose_device_on_error = true; @@ -1641,15 +1644,18 @@ impl Queue { baked.initialize_buffer_memory(&mut trackers, &submission.snatch_guard); - if let Err(e) = baked.initialize_texture_memory( + let depth_slice_discards = match baked.initialize_texture_memory( &mut trackers, &self.device, &submission.snatch_guard, ) { - break 'error Err(QueueSubmitError::CommandEncoder( - CommandEncoderError::Clear(e), - )); - } + Ok(discards) => discards, + Err(e) => { + break 'error Err(QueueSubmitError::CommandEncoder( + CommandEncoderError::Clear(e), + )); + } + }; //Note: stateless trackers are not merged: // device already knows these resources exist. @@ -1664,16 +1670,28 @@ impl Queue { break 'error Err(e.into()); } - // Transition surface textures into `Present` state. - // Note: we could technically do it after all of the command buffers, - // but here we have a command encoder by hand, so it's easier to use it. - if !used_surface_textures.is_empty() { + if !depth_slice_discards.is_empty() || !used_surface_textures.is_empty() { if let Err(e) = baked.encoder.open_pass(hal_label( - Some("(wgpu internal) Present"), + Some("(wgpu internal) Finalize"), self.device.instance_flags, )) { break 'error Err(e.into()); } + + if let Err(e) = baked.initialize_discarded_depth_slices( + depth_slice_discards, + &mut trackers, + &self.device, + &submission.snatch_guard, + ) { + break 'error Err(QueueSubmitError::CommandEncoder( + CommandEncoderError::Clear(e), + )); + } + + // Transition surface textures into `Present` state. + // Note: we could technically do it after all of the command buffers, + // but here we have a command encoder by hand, so it's easier to use it. let texture_barriers = trackers .textures .set_from_usage_scope_and_drain_transitions(