diff --git a/player/src/lib.rs b/player/src/lib.rs index bb26175a6..1645beecc 100644 --- a/player/src/lib.rs +++ b/player/src/lib.rs @@ -143,7 +143,13 @@ impl Player { let _ = buffer.unmap(); } Action::CreateTexture(id, desc) => { - let texture = device.create_texture(&desc).expect("create_texture error"); + let (texture, _) = device.create_texture(&desc); + + self.textures.insert(id, texture); + } + Action::CreateTextureError(id, desc) => { + let texture = device.create_texture_error(&desc); + self.textures.insert(id, texture); } Action::DestroyTexture(id) => { diff --git a/tests/tests/wgpu_trace.rs b/tests/tests/wgpu_trace.rs index 3da1a0891..0ebcf3e69 100644 --- a/tests/tests/wgpu_trace.rs +++ b/tests/tests/wgpu_trace.rs @@ -187,3 +187,86 @@ fn trace_failed_commands() { fn trace_failed_submit() { trace_test(TestType::FailedSubmit); } + +#[test] +fn trace_texture_test() { + let global = wgc::global::Global::new( + "test", + wgt::instance::InstanceDescriptor { + backends: wgt::Backends::NOOP, + backend_options: wgt::BackendOptions { + noop: wgt::NoopBackendOptions::enabled(), + ..Default::default() + }, + ..wgt::instance::InstanceDescriptor::new_without_display_handle() + }, + None, + ); + let adapter_id = global + .request_adapter( + &wgt::RequestAdapterOptions::default(), + wgt::Backends::NOOP, + None, + ) + .unwrap(); + let (device_id, _) = global + .adapter_request_device( + adapter_id, + &wgt::DeviceDescriptor { + trace: wgt::Trace::Memory, + ..Default::default() + }, + None, + None, + ) + .unwrap(); + + let desc = wgt::TextureDescriptor { + label: None, + size: wgt::Extent3d { + width: 1024, + height: 1024, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgt::TextureDimension::D2, + format: wgt::TextureFormat::Rgba8Unorm, + usage: wgt::TextureUsages::COPY_DST | wgt::TextureUsages::TEXTURE_BINDING, + view_formats: Vec::new(), + }; + + let (texture_id, error) = global.device_create_texture(device_id, &desc, None); + + assert!(error.is_none()); + + let texture_error_id = global.create_texture_error(device_id, None, &desc); + + global.texture_drop(texture_id); + global.texture_drop(texture_error_id); + + let trace = global.device_take_trace(device_id).unwrap(); + let trace = (trace.as_ref() as &dyn Any) + .downcast_ref::() + .unwrap(); + let actions = trace.actions(); + // first one is init + let actions = &actions[1..]; + + assert_eq!(actions.len(), 4); + + let Action::CreateTexture(texture, ..) = actions[0] else { + panic!("expected first action to be CreateTexture"); + }; + let Action::CreateTextureError(texture_error, ..) = actions[1] else { + panic!("expected second action to be CreateTextureError"); + }; + let Action::DropTexture(texture_drop) = actions[2] else { + panic!("expected third action to be DropTexture"); + }; + assert_eq!(texture, texture_drop); + let Action::DropTexture(texture_error_drop) = actions[3] else { + panic!("expected fourth action to be DropTexture"); + }; + assert_eq!(texture_error, texture_error_drop); +} diff --git a/wgpu-core/src/as_hal.rs b/wgpu-core/src/as_hal.rs index 7f997af6d..4e724b671 100644 --- a/wgpu-core/src/as_hal.rs +++ b/wgpu-core/src/as_hal.rs @@ -181,7 +181,7 @@ impl Global { let hub = &self.hub; - let texture = hub.textures.get(id).get().ok()?; + let texture = hub.textures.get(id); SnatchableResourceGuard::new(texture) } diff --git a/wgpu-core/src/command/clear.rs b/wgpu-core/src/command/clear.rs index eac7df65e..14f9f2a67 100644 --- a/wgpu-core/src/command/clear.rs +++ b/wgpu-core/src/command/clear.rs @@ -11,8 +11,9 @@ use crate::{ id::{BufferId, CommandEncoderId, TextureId}, init_tracker::{MemoryInitKind, TextureInitRange}, resource::{ - Buffer, DestroyedResourceError, InvalidResourceError, Labeled, MissingBufferUsageError, - ParentDevice, RawResourceAccess, ResourceErrorIdent, Texture, TextureClearMode, + Buffer, DestroyedResourceError, InvalidOrDestroyedResourceError, InvalidResourceError, + Labeled, MissingBufferUsageError, ParentDevice, RawResourceAccess, ResourceErrorIdent, + Texture, TextureClearMode, }, snatch::SnatchGuard, track::TextureTrackerSetSingle, @@ -79,6 +80,15 @@ whereas subesource range specified start {subresource_base_array_layer} and coun InvalidResource(#[from] InvalidResourceError), } +impl From for ClearError { + fn from(value: InvalidOrDestroyedResourceError) -> Self { + match value { + InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e), + InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e), + } + } +} + impl WebGpuError for ClearError { fn webgpu_error_type(&self) -> ErrorType { match self { @@ -137,11 +147,14 @@ impl Global { let hub = &self.hub; let cmd_enc = hub.command_encoders.get(command_encoder_id); + let mut cmd_buf_data = cmd_enc.data.lock(); cmd_buf_data.push_with(|| -> Result<_, ClearError> { + let texture = self.resolve_texture_id(dst); + texture.check_valid(&cmd_enc.device.snatchable_lock.read())?; Ok(ArcCommand::ClearTexture { - dst: self.resolve_texture_id(dst)?, + dst: texture, subresource_range: *subresource_range, }) }) @@ -297,7 +310,7 @@ pub(crate) fn clear_texture( snatch_guard: &SnatchGuard<'_>, instance_flags: wgt::InstanceFlags, ) -> Result<(), ClearError> { - let dst_raw = dst_texture.try_raw(snatch_guard)?; + let dst_raw = dst_texture.try_inner(snatch_guard)?.raw(); // Issue the right barrier. let clear_usage = match *dst_texture.clear_mode.read() { diff --git a/wgpu-core/src/command/mod.rs b/wgpu-core/src/command/mod.rs index 8b83c9ef4..713b84b6e 100644 --- a/wgpu-core/src/command/mod.rs +++ b/wgpu-core/src/command/mod.rs @@ -96,7 +96,8 @@ use crate::snatch::SnatchGuard; use crate::init_tracker::BufferInitTrackerAction; use crate::ray_tracing::{AsAction, BuildAccelerationStructureError}; use crate::resource::{ - DestroyedResourceError, Fallible, InvalidResourceError, Labeled, ParentDevice as _, QuerySet, + DestroyedResourceError, Fallible, InvalidOrDestroyedResourceError, InvalidResourceError, + Labeled, ParentDevice as _, QuerySet, }; use crate::storage::Storage; use crate::track::{DeviceTracker, ResourceUsageCompatibilityError, Tracker, UsageScope}; @@ -1617,6 +1618,15 @@ pub enum CommandEncoderError { RenderPass(#[from] RenderPassError), } +impl From for CommandEncoderError { + fn from(err: InvalidOrDestroyedResourceError) -> Self { + match err { + InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e), + InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e), + } + } +} + impl CommandEncoderError { fn is_destroyed_error(&self) -> bool { matches!( @@ -1716,8 +1726,8 @@ impl Global { fn resolve_texture_id( &self, texture_id: Id, - ) -> Result, InvalidResourceError> { - self.hub.textures.get(texture_id).get() + ) -> Arc { + self.hub.textures.get(texture_id) } fn resolve_query_set( diff --git a/wgpu-core/src/command/transfer.rs b/wgpu-core/src/command/transfer.rs index 8c5b91607..933e89d1d 100644 --- a/wgpu-core/src/command/transfer.rs +++ b/wgpu-core/src/command/transfer.rs @@ -866,16 +866,19 @@ impl Global { ); let cmd_enc = self.hub.command_encoders.get(command_encoder_id); + let mut cmd_buf_data = cmd_enc.data.lock(); cmd_buf_data.push_with(|| -> Result<_, CommandEncoderError> { + let texture = self.resolve_texture_id(destination.texture); + texture.check_valid(&cmd_enc.device.snatchable_lock.read())?; Ok(ArcCommand::CopyBufferToTexture { src: wgt::TexelCopyBufferInfo::> { buffer: self.resolve_buffer_id(source.buffer)?, layout: source.layout, }, dst: wgt::TexelCopyTextureInfo::> { - texture: self.resolve_texture_id(destination.texture)?, + texture, mip_level: destination.mip_level, origin: destination.origin, aspect: destination.aspect, @@ -900,12 +903,15 @@ impl Global { ); let cmd_enc = self.hub.command_encoders.get(command_encoder_id); + let mut cmd_buf_data = cmd_enc.data.lock(); cmd_buf_data.push_with(|| -> Result<_, CommandEncoderError> { + let texture = self.resolve_texture_id(source.texture); + texture.check_valid(&cmd_enc.device.snatchable_lock.read())?; Ok(ArcCommand::CopyTextureToBuffer { src: wgt::TexelCopyTextureInfo::> { - texture: self.resolve_texture_id(source.texture)?, + texture, mip_level: source.mip_level, origin: source.origin, aspect: source.aspect, @@ -934,18 +940,26 @@ impl Global { ); let cmd_enc = self.hub.command_encoders.get(command_encoder_id); + let mut cmd_buf_data = cmd_enc.data.lock(); cmd_buf_data.push_with(|| -> Result<_, CommandEncoderError> { + let src_texture = self.resolve_texture_id(source.texture); + let dst_texture = self.resolve_texture_id(destination.texture); + { + let snatch_guard = cmd_enc.device.snatchable_lock.read(); + src_texture.check_valid(&snatch_guard)?; + dst_texture.check_valid(&snatch_guard)?; + } Ok(ArcCommand::CopyTextureToTexture { src: wgt::TexelCopyTextureInfo { - texture: self.resolve_texture_id(source.texture)?, + texture: src_texture, mip_level: source.mip_level, origin: source.origin, aspect: source.aspect, }, dst: wgt::TexelCopyTextureInfo { - texture: self.resolve_texture_id(destination.texture)?, + texture: dst_texture, mip_level: destination.mip_level, origin: destination.origin, aspect: destination.aspect, @@ -1140,7 +1154,7 @@ pub(super) fn copy_buffer_to_texture( .check_usage(BufferUsages::COPY_SRC) .map_err(TransferError::MissingBufferUsage)?; - let dst_raw = dst_texture.try_raw(state.snatch_guard)?; + let dst_raw = dst_texture.try_inner(state.snatch_guard)?.raw(); dst_texture .check_usage(TextureUsages::COPY_DST) .map_err(TransferError::MissingTextureUsage)?; @@ -1249,7 +1263,7 @@ pub(super) fn copy_texture_to_buffer( let (src_range, src_base) = extract_texture_selector(source, copy_size, src_texture)?; - let src_raw = src_texture.try_raw(state.snatch_guard)?; + let src_raw = src_texture.try_inner(state.snatch_guard)?.raw(); src_texture .check_usage(TextureUsages::COPY_SRC) .map_err(TransferError::MissingTextureUsage)?; @@ -1471,11 +1485,11 @@ pub(super) fn copy_texture_to_texture( .into()); } - let src_raw = src_texture.try_raw(state.snatch_guard)?; + let src_raw = src_texture.try_inner(state.snatch_guard)?.raw(); src_texture .check_usage(TextureUsages::COPY_SRC) .map_err(TransferError::MissingTextureUsage)?; - let dst_raw = dst_texture.try_raw(state.snatch_guard)?; + let dst_raw = dst_texture.try_inner(state.snatch_guard)?.raw(); dst_texture .check_usage(TextureUsages::COPY_DST) .map_err(TransferError::MissingTextureUsage)?; diff --git a/wgpu-core/src/command/transition_resources.rs b/wgpu-core/src/command/transition_resources.rs index 4b8491130..cd529a9a7 100644 --- a/wgpu-core/src/command/transition_resources.rs +++ b/wgpu-core/src/command/transition_resources.rs @@ -26,6 +26,7 @@ impl Global { // Lock command encoder for recording let cmd_enc = hub.command_encoders.get(command_encoder_id); let mut cmd_buf_data = cmd_enc.data.lock(); + let snatch_guard = cmd_enc.device.snatchable_lock.read(); cmd_buf_data.push_with(|| -> Result<_, TransitionResourcesError> { Ok(ArcCommand::TransitionResources { buffer_transitions: buffer_transitions @@ -38,8 +39,10 @@ impl Global { .collect::>()?, texture_transitions: texture_transitions .map(|t| { + let texture = self.resolve_texture_id(t.texture); + texture.check_valid(&snatch_guard)?; Ok(wgt::TextureTransition { - texture: self.resolve_texture_id(t.texture)?, + texture, selector: t.selector, state: t.state, }) diff --git a/wgpu-core/src/device/global.rs b/wgpu-core/src/device/global.rs index 88a99dab8..ed9307c89 100644 --- a/wgpu-core/src/device/global.rs +++ b/wgpu-core/src/device/global.rs @@ -201,11 +201,14 @@ impl Global { /// See [`Self::create_buffer_error`] for more context and explanation. pub fn create_texture_error( &self, + device_id: DeviceId, id_in: Option, desc: &resource::TextureDescriptor, - ) { + ) -> id::TextureId { let fid = self.hub.textures.prepare(id_in); - fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string()))); + let device = self.hub.devices.get(device_id); + let texture = device.create_texture_error(desc); + fid.assign(texture) } /// Assign `id_in` an error with the given `label`. @@ -291,30 +294,13 @@ impl Global { let fid = hub.textures.prepare(id_in); - let error = 'error: { - let device = self.hub.devices.get(device_id); + let device = self.hub.devices.get(device_id); - let texture = match device.create_texture(desc) { - Ok(texture) => texture, - Err(error) => break 'error error, - }; + let (texture, error) = device.create_texture(desc); - #[cfg(feature = "trace")] - if let Some(ref mut trace) = *device.trace.lock() { - trace.add(trace::Action::CreateTexture( - texture.to_trace(), - desc.clone(), - )); - } + let id = fid.assign(texture); - let id = fid.assign(Fallible::Valid(texture)); - api_log!("Device::create_texture({desc:?}) -> {id:?}"); - - return (id, None); - }; - - let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string()))); - (id, Some(error)) + (id, error) } /// # Safety @@ -338,9 +324,9 @@ impl Global { let fid = hub.textures.prepare(id_in); - let error = 'error: { - let device = self.hub.devices.get(device_id); + let device = self.hub.devices.get(device_id); + let error = 'error: { let texture = match device.create_texture_from_hal(hal_texture, desc, initial_state) { Ok(texture) => texture, Err(error) => break 'error error, @@ -356,13 +342,13 @@ impl Global { )); } - let id = fid.assign(Fallible::Valid(texture)); + let id = fid.assign(texture); api_log!("Device::create_texture({desc:?}) -> {id:?}"); return (id, None); }; - let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string()))); + let id = fid.assign(Arc::new(resource::Texture::invalid(&device, desc))); (id, Some(error)) } @@ -412,10 +398,7 @@ impl Global { let hub = &self.hub; - let Ok(texture) = hub.textures.get(texture_id).get() else { - // If the texture is already invalid, there's nothing to do. - return; - }; + let texture = hub.textures.get(texture_id); #[cfg(feature = "trace")] if let Some(trace) = texture.device.trace.lock().as_mut() { @@ -431,13 +414,7 @@ impl Global { let hub = &self.hub; - let _texture = hub.textures.remove(texture_id); - #[cfg(feature = "trace")] - if let Ok(texture) = _texture.get() { - if let Some(t) = texture.device.trace.lock().as_mut() { - t.add(trace::Action::DropTexture(texture.to_trace())); - } - } + hub.textures.remove(texture_id); } pub fn texture_create_view( @@ -453,10 +430,7 @@ impl Global { let fid = hub.texture_views.prepare(id_in); let error = 'error: { - let texture = match hub.textures.get(texture_id).get() { - Ok(texture) => texture, - Err(e) => break 'error e.into(), - }; + let texture = hub.textures.get(texture_id); let device = &texture.device; let view = match device.create_texture_view(&texture, desc) { diff --git a/wgpu-core/src/device/queue.rs b/wgpu-core/src/device/queue.rs index f690f62ab..1c0ac264a 100644 --- a/wgpu-core/src/device/queue.rs +++ b/wgpu-core/src/device/queue.rs @@ -35,8 +35,9 @@ use crate::{ resource::{ Blas, BlasCompactState, Buffer, BufferAccessError, BufferMapState, DestroyedBuffer, DestroyedQuerySet, DestroyedResourceError, DestroyedTexture, Fallible, - FlushedStagingBuffer, InvalidResourceError, Labeled, ParentDevice, ResourceErrorIdent, - StagingBuffer, Texture, TextureInner, Trackable, TrackingData, + FlushedStagingBuffer, InvalidOrDestroyedResourceError, InvalidResourceError, Labeled, + ParentDevice, ResourceErrorIdent, StagingBuffer, Texture, TextureInner, Trackable, + TrackingData, }, resource_log, scratch::ScratchBuffer, @@ -198,8 +199,8 @@ impl Queue { // Emit the transition barriers to PRESENT. { let raw_texture = texture - .try_raw(&submission.snatch_guard) - .map_err(|_| DeviceError::Lost)?; + .raw(&submission.snatch_guard) + .ok_or(DeviceError::Lost)?; let barriers: Vec> = pending .into_iter() .map(|pt| pt.into_hal(raw_texture)) @@ -532,6 +533,15 @@ pub enum QueueWriteError { InvalidResource(#[from] InvalidResourceError), } +impl From for QueueWriteError { + fn from(e: InvalidOrDestroyedResourceError) -> Self { + match e { + InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e), + InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e), + } + } +} + impl WebGpuError for QueueWriteError { fn webgpu_error_type(&self) -> ErrorType { match self { @@ -561,6 +571,15 @@ pub enum QueueSubmitError { ValidateAsActionsError(#[from] crate::ray_tracing::ValidateAsActionsError), } +impl From for QueueSubmitError { + fn from(e: InvalidOrDestroyedResourceError) -> Self { + match e { + InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e), + InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e), + } + } +} + impl WebGpuError for QueueSubmitError { fn webgpu_error_type(&self) -> ErrorType { match self { @@ -893,7 +912,7 @@ impl Queue { let snatch_guard = self.device.snatchable_lock.read(); - let dst_raw = dst.try_raw(&snatch_guard)?; + let dst_raw = dst.try_inner(&snatch_guard)?.raw(); // This must happen after parameter validation (so that errors are reported // as required by the spec), but before any side effects. @@ -1065,7 +1084,7 @@ impl Queue { pub fn copy_external_image_to_texture( &self, source: &wgt::CopyExternalImageSourceInfo, - destination: wgt::CopyExternalImageDestInfo>, + destination: wgt::CopyExternalImageDestInfo>, size: wgt::Extent3d, ) -> Result<(), QueueWriteError> { use crate::conv; @@ -1093,7 +1112,7 @@ impl Queue { let src_width = source.source.width(); let src_height = source.source.height(); - let dst = destination.texture.get()?; + let dst = destination.texture; let premultiplied_alpha = destination.premultiplied_alpha; let destination = wgt::TexelCopyTextureInfo { texture: (), @@ -1646,7 +1665,10 @@ impl Queue { // encoded. If it was destroyed after that, then it was transferred // to `pending_writes.temp_resources` at the time of destruction, so // we are still okay to use it. - Err(DestroyedResourceError(_)) => {} + Err(InvalidOrDestroyedResourceError::DestroyedResource(_)) => {} + Err(InvalidOrDestroyedResourceError::InvalidResource(_)) => { + unreachable!() + } } } @@ -1680,7 +1702,7 @@ impl Queue { let mut submit_surface_textures = SmallVec::<[&dyn hal::DynSurfaceTexture; 2]>::with_capacity(surface_textures.len()); for texture in surface_textures.values() { - let raw = match texture.inner.get(&snatch_guard) { + let raw = match texture.inner.get(&snatch_guard).maybe_valid() { Some(TextureInner::Surface { raw, .. }) => raw.as_ref(), _ => unreachable!(), }; @@ -1898,7 +1920,7 @@ impl Global { size: &wgt::Extent3d, ) -> Result<(), QueueWriteError> { let queue = self.hub.queues.get(queue_id); - let texture = self.hub.textures.get(destination.texture).get()?; + let texture = self.hub.textures.get(destination.texture); let destination = wgt::TexelCopyTextureInfo { texture, mip_level: destination.mip_level, diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index b5299b724..94b0c543d 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -1373,7 +1373,7 @@ impl Device { } } - pub fn create_texture( + fn create_texture_inner( self: &Arc, desc: &resource::TextureDescriptor, ) -> Result, resource::CreateTextureError> { @@ -1748,6 +1748,52 @@ impl Device { Ok(texture) } + pub fn create_texture( + self: &Arc, + desc: &resource::TextureDescriptor, + ) -> (Arc, Option) { + let (texture, error) = match self.create_texture_inner(desc) { + Ok(texture) => (texture, None), + Err(e) => { + let texture = Texture::invalid(self, desc); + (Arc::new(texture), Some(e)) + } + }; + api_log!( + "Device::create_texture({desc:?}) -> {:?}", + Arc::as_ptr(&texture) + ); + + #[cfg(feature = "trace")] + if let Some(ref mut trace) = *self.trace.lock() { + use crate::device::trace::IntoTrace as _; + + trace.add(trace::Action::CreateTexture( + texture.to_trace(), + desc.clone(), + )); + } + (texture, error) + } + + /// Creates a texture that is guaranteed to be invalid + pub fn create_texture_error( + self: &Arc, + desc: &resource::TextureDescriptor, + ) -> Arc { + let texture = Arc::new(Texture::invalid(self, desc)); + #[cfg(feature = "trace")] + if let Some(ref mut trace) = *self.trace.lock() { + use crate::device::trace::IntoTrace as _; + + trace.add(trace::Action::CreateTextureError( + texture.to_trace(), + desc.clone(), + )); + } + texture + } + pub fn create_texture_view( self: &Arc, texture: &Arc, @@ -1757,7 +1803,7 @@ impl Device { let snatch_guard = texture.device.snatchable_lock.read(); - let texture_raw = texture.try_raw(&snatch_guard)?; + let texture_raw = texture.try_inner(&snatch_guard)?.raw(); // resolve TextureViewDescriptor defaults // https://gpuweb.github.io/gpuweb/#abstract-opdef-resolving-gputextureviewdescriptor-defaults diff --git a/wgpu-core/src/device/trace.rs b/wgpu-core/src/device/trace.rs index 3ed8139e7..576efacec 100644 --- a/wgpu-core/src/device/trace.rs +++ b/wgpu-core/src/device/trace.rs @@ -128,6 +128,7 @@ pub enum Action<'a, R: ReferenceType> { DestroyBuffer(R::Buffer), DropBuffer(R::Buffer), CreateTexture(R::Texture, crate::resource::TextureDescriptor<'a>), + CreateTextureError(R::Texture, crate::resource::TextureDescriptor<'a>), DestroyTexture(R::Texture), DropTexture(R::Texture), CreateTextureView { diff --git a/wgpu-core/src/device/trace/record.rs b/wgpu-core/src/device/trace/record.rs index 46e4d56eb..f2a4a109f 100644 --- a/wgpu-core/src/device/trace/record.rs +++ b/wgpu-core/src/device/trace/record.rs @@ -1,5 +1,5 @@ use alloc::{borrow::Cow, string::ToString, sync::Arc, vec::Vec}; -use core::{any::Any, convert::Infallible}; +use core::{any::Any, convert::Infallible, marker::PhantomData}; use std::io::Write as _; use crate::{ @@ -175,6 +175,15 @@ impl IntoTrace for Arc { } } +/// This will work as expected on heap-allocated types that are not moved around. +pub(crate) unsafe fn to_trace(t: &T) -> PointerId { + PointerId::PointerId( + #[expect(trivial_casts)] + core::num::NonZeroUsize::new(t as *const T as usize).unwrap(), + PhantomData, + ) +} + impl IntoTrace for ArcCommand { type Output = Command; fn into_trace(self) -> Self::Output { @@ -971,8 +980,9 @@ fn action_to_owned(action: Action<'_, PointerReferences>) -> Action<'static, Poi A::DropBlas(blas) => A::DropBlas(blas), A::DropTlas(tlas) => A::DropTlas(tlas), - A::CreateTexture(..) - | A::CreateTextureView { .. } + A::CreateTexture(id, desc) => A::CreateTexture(id, desc.map_label(owned_label)), + A::CreateTextureError(id, desc) => A::CreateTextureError(id, desc.map_label(owned_label)), + A::CreateTextureView { .. } | A::CreateExternalTexture { .. } | A::CreateSampler(..) | A::CreateBindGroupLayout(..) @@ -989,3 +999,7 @@ fn action_to_owned(action: Action<'_, PointerReferences>) -> Action<'static, Poi | A::CreateTlas { .. } => panic!("Unsupported action for tracing: {action:?}"), } } + +fn owned_label(l: &Option>) -> Option> { + l.as_ref().map(|l| Cow::Owned(l.to_string())) +} diff --git a/wgpu-core/src/hub.rs b/wgpu-core/src/hub.rs index 48968550c..c4fa954be 100644 --- a/wgpu-core/src/hub.rs +++ b/wgpu-core/src/hub.rs @@ -200,7 +200,7 @@ pub struct Hub { pub(crate) query_sets: Registry>, pub(crate) buffers: Registry>, pub(crate) staging_buffers: Registry, - pub(crate) textures: Registry>, + pub(crate) textures: Registry>, pub(crate) texture_views: Registry>, pub(crate) external_textures: Registry>, pub(crate) samplers: Registry>, diff --git a/wgpu-core/src/present.rs b/wgpu-core/src/present.rs index 4303b0c14..ee06dfb8a 100644 --- a/wgpu-core/src/present.rs +++ b/wgpu-core/src/present.rs @@ -331,7 +331,10 @@ impl Queue { let device = &self.device; let mut exclusive_snatch_guard = device.snatchable_lock.write(); - let inner = texture.inner.snatch(&mut exclusive_snatch_guard); + let inner = texture + .inner + .snatch(&mut exclusive_snatch_guard) + .maybe_valid(); drop(exclusive_snatch_guard); let result = match inner { @@ -387,7 +390,10 @@ impl Surface { .ok_or(SurfaceError::NothingToPresent)?; let mut exclusive_snatch_guard = device.snatchable_lock.write(); - let inner = texture.inner.snatch(&mut exclusive_snatch_guard); + let inner = texture + .inner + .snatch(&mut exclusive_snatch_guard) + .maybe_valid(); drop(exclusive_snatch_guard); match inner { @@ -450,9 +456,7 @@ impl Global { } let status = output.status; - let texture_id = output - .texture - .map(|texture| fid.assign(resource::Fallible::Valid(texture))); + let texture_id = output.texture.map(|texture| fid.assign(texture)); Ok(SurfaceOutput { status, diff --git a/wgpu-core/src/resource.rs b/wgpu-core/src/resource.rs index 305c583cc..958532b98 100644 --- a/wgpu-core/src/resource.rs +++ b/wgpu-core/src/resource.rs @@ -27,7 +27,7 @@ use crate::{ lock::{rank, Mutex, RwLock}, ray_tracing::{BlasCompactReadyPendingClosure, BlasPrepareCompactError}, resource_log, - snatch::{SnatchGuard, Snatchable}, + snatch::{SnatchGuard, Snatchable, Snatchable2}, timestamp_normalization::TimestampNormalizationBindGroup, track::{SharedTrackerIndexAllocator, TrackerIndex}, weak_vec::WeakVec, @@ -91,6 +91,44 @@ impl fmt::Display for ResourceErrorIdent { } } +pub enum DestructibleResourceState { + Valid(T), + Invalid, + Destroyed, +} + +impl DestructibleResourceState { + pub fn as_ref(&self) -> DestructibleResourceState<&T> { + match self { + DestructibleResourceState::Valid(v) => DestructibleResourceState::Valid(v), + DestructibleResourceState::Invalid => DestructibleResourceState::Invalid, + DestructibleResourceState::Destroyed => DestructibleResourceState::Destroyed, + } + } + + pub fn take(&mut self) -> DestructibleResourceState { + mem::replace(self, DestructibleResourceState::Destroyed) + } +} + +#[derive(thiserror::Error, Debug)] +pub enum InvalidOrDestroyedResourceError { + #[error(transparent)] + InvalidResource(#[from] InvalidResourceError), + #[error(transparent)] + DestroyedResource(#[from] DestroyedResourceError), +} + +impl DestructibleResourceState { + pub fn maybe_valid(self) -> Option { + match self { + DestructibleResourceState::Valid(t) => Some(t), + DestructibleResourceState::Invalid => None, + DestructibleResourceState::Destroyed => None, + } + } +} + pub trait ParentDevice: Labeled { fn device(&self) -> &Arc; @@ -1355,7 +1393,7 @@ pub enum TextureClearMode { #[derive(Debug)] pub struct Texture { - pub(crate) inner: Snatchable, + pub(crate) inner: Snatchable2, pub(crate) device: Arc, pub(crate) desc: wgt::TextureDescriptor>, pub(crate) _hal_usage: wgt::TextureUses, @@ -1380,7 +1418,7 @@ impl Texture { init: bool, ) -> Self { Texture { - inner: Snatchable::new(inner), + inner: Snatchable2::new(inner), device: device.clone(), desc: desc.map_label(|label| label.to_string()), _hal_usage: hal_usage, @@ -1404,6 +1442,31 @@ impl Texture { } } + pub(crate) fn invalid(device: &Arc, desc: &TextureDescriptor) -> Self { + Texture { + inner: Snatchable2::invalid(), + device: device.clone(), + desc: desc.map_label(|label| label.to_string()), + _hal_usage: wgt::TextureUses::empty(), + format_features: wgt::TextureFormatFeatures { + allowed_usages: wgt::TextureUsages::empty(), + flags: wgt::TextureFormatFeatureFlags::empty(), + }, + initialization_status: RwLock::new( + rank::TEXTURE_INITIALIZATION_STATUS, + TextureInitTracker::new(0, 0), + ), + full_range: TextureSelector { + mips: 0..desc.mip_level_count, + layers: 0..desc.array_layer_count(), + }, + tracking_data: TrackingData::new(device.tracker_indices.textures.clone()), + clear_mode: RwLock::new(rank::TEXTURE_CLEAR_MODE, TextureClearMode::None), + views: Mutex::new(rank::TEXTURE_VIEWS, WeakVec::new()), + bind_groups: Mutex::new(rank::TEXTURE_BIND_GROUPS, WeakVec::new()), + } + } + /// Checks that the given texture usage contains the required texture usage, /// returns an error otherwise. pub(crate) fn check_usage( @@ -1424,6 +1487,16 @@ impl Texture { impl Drop for Texture { fn drop(&mut self) { + #[cfg(feature = "trace")] + { + let mut t = self.device.trace.lock(); + if let Some(t) = t.as_mut() { + use crate::device::trace::to_trace; + + // SAFETY: All textures are constructed in Arc => are heap allocated + t.add(trace::Action::DropTexture(unsafe { to_trace(self) })); + } + } match *self.clear_mode.write() { TextureClearMode::Surface { ref mut clear_view, .. @@ -1449,7 +1522,7 @@ impl Drop for Texture { _ => {} }; - if let Some(TextureInner::Native { raw }) = self.inner.take() { + if let Some(TextureInner::Native { raw }) = self.inner.take().maybe_valid() { resource_log!("Destroy raw {}", self.error_ident()); unsafe { self.device.raw().destroy_texture(raw); @@ -1462,7 +1535,7 @@ impl RawResourceAccess for Texture { type DynResource = dyn hal::DynTexture; fn raw<'a>(&'a self, guard: &'a SnatchGuard) -> Option<&'a Self::DynResource> { - self.inner.get(guard).map(|t| t.raw()) + self.inner.get(guard).maybe_valid().map(|t| t.raw()) } } @@ -1470,20 +1543,39 @@ impl Texture { pub(crate) fn try_inner<'a>( &'a self, guard: &'a SnatchGuard, - ) -> Result<&'a TextureInner, DestroyedResourceError> { - self.inner - .get(guard) - .ok_or_else(|| DestroyedResourceError(self.error_ident())) + ) -> Result<&'a TextureInner, InvalidOrDestroyedResourceError> { + match self.inner.get(guard) { + DestructibleResourceState::Valid(t) => Ok(t), + DestructibleResourceState::Invalid => { + Err(InvalidOrDestroyedResourceError::InvalidResource( + InvalidResourceError(self.error_ident()), + )) + } + DestructibleResourceState::Destroyed => { + Err(InvalidOrDestroyedResourceError::DestroyedResource( + DestroyedResourceError(self.error_ident()), + )) + } + } } pub(crate) fn check_destroyed( &self, guard: &SnatchGuard, ) -> Result<(), DestroyedResourceError> { - self.inner - .get(guard) - .map(|_| ()) - .ok_or_else(|| DestroyedResourceError(self.error_ident())) + match self.inner.get(guard) { + DestructibleResourceState::Valid(_) => Ok(()), + DestructibleResourceState::Invalid => Ok(()), + DestructibleResourceState::Destroyed => Err(DestroyedResourceError(self.error_ident())), + } + } + + pub(crate) fn check_valid(&self, guard: &SnatchGuard) -> Result<(), InvalidResourceError> { + match self.inner.get(guard) { + DestructibleResourceState::Valid(_) => Ok(()), + DestructibleResourceState::Invalid => Err(InvalidResourceError(self.error_ident())), + DestructibleResourceState::Destroyed => Ok(()), + } } pub(crate) fn get_clear_view<'a>( @@ -1519,7 +1611,11 @@ impl Texture { let device = &self.device; let temp = { - let raw = match self.inner.snatch(&mut device.snatchable_lock.write()) { + let raw = match self + .inner + .snatch(&mut device.snatchable_lock.write()) + .maybe_valid() + { Some(TextureInner::Native { raw }) => raw, Some(TextureInner::Surface { .. }) => { return; @@ -1979,6 +2075,15 @@ pub enum CreateTextureViewError { MissingFeatures(#[from] MissingFeatures), } +impl From for CreateTextureViewError { + fn from(value: InvalidOrDestroyedResourceError) -> Self { + match value { + InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e), + InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e), + } + } +} + impl WebGpuError for CreateTextureViewError { fn webgpu_error_type(&self) -> ErrorType { match self { diff --git a/wgpu-core/src/snatch.rs b/wgpu-core/src/snatch.rs index a79cbcef3..8b18c5d89 100644 --- a/wgpu-core/src/snatch.rs +++ b/wgpu-core/src/snatch.rs @@ -1,6 +1,7 @@ use core::{cell::UnsafeCell, fmt, mem::ManuallyDrop}; use crate::lock::{rank, RankData, RwLock, RwLockReadGuard, RwLockWriteGuard}; +use crate::resource::DestructibleResourceState; /// A guard that provides read access to snatchable data. pub struct SnatchGuard<'a>(RwLockReadGuard<'a, ()>); @@ -13,20 +14,22 @@ pub struct ExclusiveSnatchGuard<'a>(#[expect(dead_code)] RwLockWriteGuard<'a, () /// In order to safely access the underlying data, the device's global snatchable /// lock must be taken. To guarantee it, methods take a read or write guard of that /// special lock. -pub struct Snatchable { - value: UnsafeCell>, +pub struct SnatchableInner { + value: UnsafeCell, } +pub type Snatchable = SnatchableInner>; + impl Snatchable { pub fn new(val: T) -> Self { - Snatchable { + SnatchableInner { value: UnsafeCell::new(Some(val)), } } #[allow(dead_code)] pub fn empty() -> Self { - Snatchable { + SnatchableInner { value: UnsafeCell::new(None), } } @@ -52,13 +55,53 @@ impl Snatchable { // Can't safely print the contents of a snatchable object without holding // the lock. -impl fmt::Debug for Snatchable { +impl fmt::Debug for SnatchableInner { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "") } } -unsafe impl Sync for Snatchable {} +unsafe impl Sync for SnatchableInner {} + +/// A value that is mostly immutable but can be "snatched" if we need to destroy +/// it early. +/// +/// In order to safely access the underlying data, the device's global snatchable +/// lock must be taken. To guarantee it, methods take a read or write guard of that +/// special lock. +pub type Snatchable2 = SnatchableInner>; + +impl Snatchable2 { + pub fn new(val: T) -> Self { + SnatchableInner { + value: UnsafeCell::new(DestructibleResourceState::Valid(val)), + } + } + + pub fn invalid() -> Self { + SnatchableInner { + value: UnsafeCell::new(DestructibleResourceState::Invalid), + } + } + + /// Get read access to the value. Requires a the snatchable lock's read guard. + pub fn get<'a>(&'a self, _guard: &'a SnatchGuard) -> DestructibleResourceState<&'a T> { + unsafe { (*self.value.get()).as_ref() } + } + + /// Take the value. Requires a the snatchable lock's write guard. + pub fn snatch(&self, _guard: &mut ExclusiveSnatchGuard) -> DestructibleResourceState { + unsafe { (*self.value.get()).take() } + } + + /// Take the value without a guard. This can only be used with exclusive access + /// to self, so it does not require locking. + /// + /// Typically useful in a drop implementation. + pub fn take(&mut self) -> DestructibleResourceState { + self.value.get_mut().take() + } +} use trace::LockTrace; #[cfg(all(debug_assertions, feature = "std"))] diff --git a/wgpu-core/src/track/texture.rs b/wgpu-core/src/track/texture.rs index 78f60fdb2..6cea59290 100644 --- a/wgpu-core/src/track/texture.rs +++ b/wgpu-core/src/track/texture.rs @@ -489,7 +489,7 @@ impl TextureTracker { .drain(..) .inspect(|pending| { let tex = unsafe { self.metadata.get_resource_unchecked(pending.id as _) }; - textures.push(tex.inner.get(snatch_guard)); + textures.push(tex.inner.get(snatch_guard).maybe_valid()); }) .collect(); (transitions, textures)