diff --git a/wgpu-core/src/command/clear.rs b/wgpu-core/src/command/clear.rs index 14f9f2a67..64eb6990b 100644 --- a/wgpu-core/src/command/clear.rs +++ b/wgpu-core/src/command/clear.rs @@ -152,7 +152,7 @@ impl Global { cmd_buf_data.push_with(|| -> Result<_, ClearError> { let texture = self.resolve_texture_id(dst); - texture.check_valid(&cmd_enc.device.snatchable_lock.read())?; + texture.check_valid()?; Ok(ArcCommand::ClearTexture { dst: texture, subresource_range: *subresource_range, diff --git a/wgpu-core/src/command/transfer.rs b/wgpu-core/src/command/transfer.rs index 98865d707..4f9a8bd41 100644 --- a/wgpu-core/src/command/transfer.rs +++ b/wgpu-core/src/command/transfer.rs @@ -876,7 +876,7 @@ impl Global { cmd_buf_data.push_with(|| -> Result<_, CommandEncoderError> { let texture = self.resolve_texture_id(destination.texture); - texture.check_valid(&cmd_enc.device.snatchable_lock.read())?; + texture.check_valid()?; Ok(ArcCommand::CopyBufferToTexture { src: wgt::TexelCopyBufferInfo::> { buffer: self.resolve_buffer_id(source.buffer)?, @@ -913,7 +913,7 @@ impl Global { cmd_buf_data.push_with(|| -> Result<_, CommandEncoderError> { let texture = self.resolve_texture_id(source.texture); - texture.check_valid(&cmd_enc.device.snatchable_lock.read())?; + texture.check_valid()?; Ok(ArcCommand::CopyTextureToBuffer { src: wgt::TexelCopyTextureInfo::> { texture, @@ -951,11 +951,8 @@ impl Global { 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)?; - } + src_texture.check_valid()?; + dst_texture.check_valid()?; Ok(ArcCommand::CopyTextureToTexture { src: wgt::TexelCopyTextureInfo { texture: src_texture, diff --git a/wgpu-core/src/command/transition_resources.rs b/wgpu-core/src/command/transition_resources.rs index cd529a9a7..97362715f 100644 --- a/wgpu-core/src/command/transition_resources.rs +++ b/wgpu-core/src/command/transition_resources.rs @@ -26,7 +26,6 @@ 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 @@ -40,7 +39,7 @@ impl Global { texture_transitions: texture_transitions .map(|t| { let texture = self.resolve_texture_id(t.texture); - texture.check_valid(&snatch_guard)?; + texture.check_valid()?; Ok(wgt::TextureTransition { texture, selector: t.selector, diff --git a/wgpu-core/src/device/queue.rs b/wgpu-core/src/device/queue.rs index 1c0ac264a..723e160f2 100644 --- a/wgpu-core/src/device/queue.rs +++ b/wgpu-core/src/device/queue.rs @@ -1702,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).maybe_valid() { + let raw = match texture.try_inner(&snatch_guard).ok() { Some(TextureInner::Surface { raw, .. }) => raw.as_ref(), _ => unreachable!(), }; diff --git a/wgpu-core/src/present.rs b/wgpu-core/src/present.rs index c7e051b11..5ba5c661a 100644 --- a/wgpu-core/src/present.rs +++ b/wgpu-core/src/present.rs @@ -339,9 +339,9 @@ impl Queue { let mut exclusive_snatch_guard = device.snatchable_lock.write(); let inner = texture - .inner - .snatch(&mut exclusive_snatch_guard) - .maybe_valid(); + .state() + .ok() + .and_then(|state| state.inner.snatch(&mut exclusive_snatch_guard)); drop(exclusive_snatch_guard); let result = match inner { @@ -398,9 +398,9 @@ impl Surface { let mut exclusive_snatch_guard = device.snatchable_lock.write(); let inner = texture - .inner - .snatch(&mut exclusive_snatch_guard) - .maybe_valid(); + .state() + .ok() + .and_then(|state| state.inner.snatch(&mut exclusive_snatch_guard)); drop(exclusive_snatch_guard); match inner { diff --git a/wgpu-core/src/resource.rs b/wgpu-core/src/resource.rs index b97bbdf52..16dea1240 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, Snatchable2}, + snatch::{SnatchGuard, Snatchable}, timestamp_normalization::TimestampNormalizationBindGroup, track::{SharedTrackerIndexAllocator, TrackerIndex}, weak_vec::WeakVec, @@ -113,26 +113,6 @@ impl ResourceState { } } -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)] @@ -141,16 +121,6 @@ pub enum InvalidOrDestroyedResourceError { 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; @@ -1413,9 +1383,14 @@ pub enum TextureClearMode { None, } +#[derive(Debug)] +pub struct TextureState { + pub(crate) inner: Snatchable, +} + #[derive(Debug)] pub struct Texture { - pub(crate) inner: Snatchable2, + pub(crate) state: ResourceState, pub(crate) device: Arc, pub(crate) desc: wgt::TextureDescriptor>, pub(crate) _hal_usage: wgt::TextureUses, @@ -1440,7 +1415,9 @@ impl Texture { init: bool, ) -> Self { Texture { - inner: Snatchable2::new(inner), + state: ResourceState::Valid(TextureState { + inner: Snatchable::new(inner), + }), device: device.clone(), desc: desc.map_label(|label| label.to_string()), _hal_usage: hal_usage, @@ -1466,7 +1443,7 @@ impl Texture { pub(crate) fn invalid(device: &Arc, desc: &TextureDescriptor) -> Self { Texture { - inner: Snatchable2::invalid(), + state: ResourceState::Invalid, device: device.clone(), desc: desc.map_label(|label| label.to_string()), _hal_usage: wgt::TextureUses::empty(), @@ -1544,7 +1521,10 @@ impl Drop for Texture { _ => {} }; - if let Some(TextureInner::Native { raw }) = self.inner.take().maybe_valid() { + let ResourceState::Valid(state) = &mut self.state else { + return; + }; + if let Some(TextureInner::Native { raw }) = state.inner.take() { resource_log!("Destroy raw {}", self.error_ident()); unsafe { self.device.raw().destroy_texture(raw); @@ -1557,27 +1537,18 @@ 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).maybe_valid().map(|t| t.raw()) + self.state + .as_ref() + .valid() + .and_then(|t| t.inner.get(guard).map(|t| t.raw())) } } impl Texture { - pub(crate) fn try_inner<'a>( - &'a self, - guard: &'a SnatchGuard, - ) -> 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 state(&self) -> Result<&TextureState, InvalidResourceError> { + match &self.state { + ResourceState::Valid(state) => Ok(state), + ResourceState::Invalid => Err(InvalidResourceError(self.error_ident())), } } @@ -1585,19 +1556,28 @@ impl Texture { &self, guard: &SnatchGuard, ) -> Result<(), DestroyedResourceError> { - match self.inner.get(guard) { - DestructibleResourceState::Valid(_) => Ok(()), - DestructibleResourceState::Invalid => Ok(()), - DestructibleResourceState::Destroyed => Err(DestroyedResourceError(self.error_ident())), - } + let Ok(state) = self.state() else { + return Ok(()); + }; + state + .inner + .get(guard) + .map(|_| ()) + .ok_or_else(|| 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 check_valid(&self) -> Result<(), InvalidResourceError> { + self.state().map(|_| ()) + } + + pub(crate) fn try_inner<'a>( + &'a self, + guard: &'a SnatchGuard, + ) -> Result<&'a TextureInner, InvalidOrDestroyedResourceError> { + self.state()? + .inner + .get(guard) + .ok_or_else(|| DestroyedResourceError(self.error_ident()).into()) } pub(crate) fn get_clear_view<'a>( @@ -1632,12 +1612,12 @@ impl Texture { pub fn destroy(self: &Arc) { let device = &self.device; + let ResourceState::Valid(state) = &self.state else { + return; + }; + let temp = { - let raw = match self - .inner - .snatch(&mut device.snatchable_lock.write()) - .maybe_valid() - { + let raw = match state.inner.snatch(&mut device.snatchable_lock.write()) { Some(TextureInner::Native { raw }) => raw, Some(TextureInner::Surface { .. }) => { return; diff --git a/wgpu-core/src/snatch.rs b/wgpu-core/src/snatch.rs index 8b18c5d89..dced88826 100644 --- a/wgpu-core/src/snatch.rs +++ b/wgpu-core/src/snatch.rs @@ -1,7 +1,6 @@ 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, ()>); @@ -63,46 +62,6 @@ impl fmt::Debug for SnatchableInner { 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"))] mod trace { diff --git a/wgpu-core/src/track/texture.rs b/wgpu-core/src/track/texture.rs index 6cea59290..3e2154323 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).maybe_valid()); + textures.push(tex.try_inner(snatch_guard).ok()); }) .collect(); (transitions, textures)