From 8ef6b77ab574e3c0704592c1d999a804fedbf94e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 7 Oct 2023 12:53:51 +0200 Subject: [PATCH 1/3] Fix deadlock in D2D1ResourceTextureManagerImpl.Update --- ...ManagerImpl.ID2D1ResourceTextureManager.cs | 46 +++++++++++-------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManager.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManager.cs index 624b129b..b4eeac93 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManager.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManager.cs @@ -83,35 +83,41 @@ unsafe partial struct D2D1ResourceTextureManagerImpl return E.E_NOT_VALID_STATE; } - // If a resource texture already exists, just forward the call - if (@this->d2D1ResourceTexture is not null) + // If no resource texture already exists, update the staging buffer + if (@this->d2D1ResourceTexture is null) { - @this->d2D1Multithread->Enter(); - - // Take a D2D lock here too to ensure thread safety - int hresult = @this->d2D1ResourceTexture->Update( + return ID2D1ResourceTextureManagerMethods.UpdateWithStagingBuffer( + @this: @this, minimumExtents: minimumExtents, maximimumExtents: maximimumExtents, strides: strides, dimensions: dimensions, data: data, dataCount: dataCount); - - @this->d2D1Multithread->Leave(); - - return hresult; } - - // Otherwise update the staging buffer - return ID2D1ResourceTextureManagerMethods.UpdateWithStagingBuffer( - @this: @this, - minimumExtents: minimumExtents, - maximimumExtents: maximimumExtents, - strides: strides, - dimensions: dimensions, - data: data, - dataCount: dataCount); } + + // If we got to this point, it means we have a D2D1 resource texture already + // initialized. This means we can be sure no other thread is concurrently + // touching any other local state, as the initialization (potentially from the + // staging buffer has already been completely if this is the case, since we also + // checked for this while taking the instance lock). So we can now take the D2D + // lock and update the texture directly. We need to take this when we're not also + // taking the instance lock, or we might trigger an AB/BA deadlock across threads. + @this->d2D1Multithread->Enter(); + + // Take a D2D lock here too to ensure thread safety + int hresult = @this->d2D1ResourceTexture->Update( + minimumExtents: minimumExtents, + maximimumExtents: maximimumExtents, + strides: strides, + dimensions: dimensions, + data: data, + dataCount: dataCount); + + @this->d2D1Multithread->Leave(); + + return hresult; } /// From 1a2a1bc22b1064ae8d57267ce927462c60761cac Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 7 Oct 2023 20:47:01 +0200 Subject: [PATCH 2/3] Add unit test for deadlock when updating resource texture --- .../D2D1ResourceTextureManagerTests.cs | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs index 67cdca7d..7f546b02 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs @@ -4,6 +4,7 @@ using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography; +using System.Threading; using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Tests.Helpers; using ComputeSharp.Tests.Helpers; @@ -719,6 +720,78 @@ public partial class D2D1ResourceTextureManagerTests Assert.IsTrue(texture.AsSpan().SequenceEqual(resultingBytes)); } + [TestMethod] + public unsafe void UpdateResourceTexture2D_ConcurrentAccess_DoesNotDeadlock() + { + const int width = 4096; + const int height = 4096; + + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), width, height); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + CopyFromResourceTexture2DShader shader = new(width, height); + + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader); + + byte[] texture = new byte[width * height]; + + D2D1ResourceTextureManager resourceTextureManager = new( + extents: stackalloc[] { (uint)width, (uint)height }, + bufferPrecision: D2D1BufferPrecision.UInt8Normalized, + channelDepth: D2D1ChannelDepth.One, + filter: D2D1Filter.MinMagMipPoint, + extendModes: stackalloc[] { D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp }, + data: texture, + strides: stackalloc uint[] { width }); + + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager, 0); + + CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(20)); + + // Thread As are constantly updating the resource texture + void UpdateResourceTexture() + { + ReadOnlySpan minimumExtents = stackalloc uint[] { 0, 0 }; + ReadOnlySpan maximumExtents = stackalloc uint[] { width, height }; + ReadOnlySpan strides = stackalloc uint[] { width }; + + while (!cancellationTokenSource.IsCancellationRequested) + { + resourceTextureManager.Update( + minimumExtents: minimumExtents, + maximimumExtents: maximumExtents, + strides: strides, + data: texture); + } + } + + // Thread Bs are constantly drawing on the target bitmap + void Draw() + { + while (!cancellationTokenSource.IsCancellationRequested) + { + D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get()); + } + } + + Thread threadA = new(UpdateResourceTexture); + Thread threadB = new(Draw); + + threadA.Start(); + threadB.Start(); + + threadA.Join(); + threadB.Join(); + } + [D2DInputCount(0)] [D2DRequiresScenePosition] [D2DGeneratedPixelShaderDescriptor] From 6c218184a34687a7305e294c39aa5296515e7d6e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 8 Oct 2023 20:25:21 +0200 Subject: [PATCH 3/3] Remove lock in D2D1ResourceTextureManagerImpl.Release --- .../D2D1ResourceTextureManagerImpl.cs | 49 ++++++++++--------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs index c0ac8d04..22887754 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs @@ -235,37 +235,38 @@ internal unsafe partial struct D2D1ResourceTextureManagerImpl if (referenceCount == 0) { - lock (this.lockHandle.Target!) + // Note: if this object is being destroyed, it means that no other caller can exist. As such, there + // is no need to take the instance lock, as it's impossible for this logic to be racing against other + // threads referencing this object. If someone else was doing this, this would be falling apart anyway. + // As such, we can simply free this GC handle and run the rest of the logic without the additional lock. + this.lockHandle.Free(); + + // Synchronize on the ID2D1Multithread instance before touching D2D objects + if (this.d2D1Multithread is not null) { - // Also synchronize on the ID2D1Multithread instance before touching D2D objects - if (this.d2D1Multithread is not null) - { - // Enter the lock, and then free the effect context. That is guaranteed to - // not be null here, as it is only ever set if ID2D1Multithread is retrieved. - this.d2D1Multithread->Enter(); + // Enter the lock, and then free the effect context. That is guaranteed to + // not be null here, as it is only ever set if ID2D1Multithread is retrieved. + this.d2D1Multithread->Enter(); - // Release the resource too if it has been created - ComPtr.Release(this.d2D1ResourceTexture); + // Release the resource too if it has been created + ComPtr.Release(this.d2D1ResourceTexture); - // Now that the resource, if any, has been released, the effect context can also - // be released. This must be done only after any associated resource textures have - // been released. Releasing an effect context first, in case it was the last reference - // to it, will otherwise cause the Release() call on the resource texture to explode. - _ = this.d2D1EffectContext->Release(); + // Now that the resource, if any, has been released, the effect context can also + // be released. This must be done only after any associated resource textures have + // been released. Releasing an effect context first, in case it was the last reference + // to it, will otherwise cause the Release() call on the resource texture to explode. + _ = this.d2D1EffectContext->Release(); - this.d2D1Multithread->Leave(); + this.d2D1Multithread->Leave(); - _ = this.d2D1Multithread->Release(); - } - - NativeMemory.Free(this.resourceId); - NativeMemory.Free(this.resourceTextureProperties.extents); - NativeMemory.Free(this.resourceTextureProperties.extendModes); - NativeMemory.Free(this.data); - NativeMemory.Free(this.strides); + _ = this.d2D1Multithread->Release(); } - this.lockHandle.Free(); + NativeMemory.Free(this.resourceId); + NativeMemory.Free(this.resourceTextureProperties.extents); + NativeMemory.Free(this.resourceTextureProperties.extendModes); + NativeMemory.Free(this.data); + NativeMemory.Free(this.strides); NativeMemory.Free(Unsafe.AsPointer(ref this)); }