Switch device lost detection to fence signal callback
このコミットが含まれているのは:
1 親
5cb00a8924
コミット
041956b854
8ファイル変更
+168
-114
検索条件に一致するファイルはありません
@@ -39,26 +39,7 @@ internal static class HResultExtensions
|
||||
{
|
||||
if (result < 0)
|
||||
{
|
||||
// This method just throws the exception from the helper below, which includes the
|
||||
// additional logic for the device lost events. This structure ensures this method
|
||||
// only has a single basic block, so it can be identified as a throw helper and
|
||||
// imported properly, which results in better codegen.
|
||||
static void RaiseDeviceLostEventsAndThrowWin32Exception(int result)
|
||||
{
|
||||
throw RaiseDeviceLostEventsAndGetWin32Exception(result);
|
||||
}
|
||||
|
||||
// Raises all device lost events, if needed, and then creates the Win32Exception to throw.
|
||||
// This method is never inlined, which is needed to make handling the throw helper easier.
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
static Win32Exception RaiseDeviceLostEventsAndGetWin32Exception(int result)
|
||||
{
|
||||
DeviceHelper.RaiseAllDeviceLostEventsIfNeeded();
|
||||
|
||||
return new Win32Exception(result);
|
||||
}
|
||||
|
||||
RaiseDeviceLostEventsAndThrowWin32Exception(result);
|
||||
ThrowHelper.ThrowWin32Exception(result);
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -71,15 +52,11 @@ internal static class HResultExtensions
|
||||
|
||||
if (result < 0)
|
||||
{
|
||||
DeviceHelper.RaiseAllDeviceLostEventsIfNeeded();
|
||||
|
||||
ThrowHelper.ThrowWin32Exception(result);
|
||||
}
|
||||
|
||||
if (hasErrorsOrWarnings)
|
||||
{
|
||||
DeviceHelper.RaiseAllDeviceLostEventsIfNeeded();
|
||||
|
||||
ThrowHelper.ThrowWin32Exception("Warning or error detected by ID3D12InfoQueue.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using ComputeSharp.Core.Extensions;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
#if !NET6_0_OR_GREATER
|
||||
using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute;
|
||||
#endif
|
||||
|
||||
namespace ComputeSharp;
|
||||
|
||||
/// <inheritdoc/>
|
||||
unsafe partial class GraphicsDevice
|
||||
{
|
||||
#if !NET6_0_OR_GREATER
|
||||
/// <summary>
|
||||
/// A cached <see cref="WaitForSingleObjectCallbackDelegate"/> instance wrapping <see cref="WaitForSingleObjectCallbackForRegisterDeviceLostCallback(void*, byte)"/>.
|
||||
/// </summary>
|
||||
private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackForRegisterDeviceLostCallbackWrapper = WaitForSingleObjectCallbackForWaitForFenceAsync;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Raises the <see cref="DeviceLost"/> event if needed.
|
||||
/// </summary>
|
||||
private void QueueRaiseDeviceLostEventIfNeeded()
|
||||
{
|
||||
if (IsDisposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the current device removed reason is not S_OK, it means the event
|
||||
// has already been raised (but the device will keep reporting that reason).
|
||||
// In that case, do nothing to avoid raising it again while the device is alive.
|
||||
if (Volatile.Read(ref Unsafe.As<HRESULT, int>(ref this.deviceRemovedReason)) != S.S_OK)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
HRESULT result = this.d3D12Device.Get()->GetDeviceRemovedReason();
|
||||
|
||||
// Only raise the event once, and store the device removed reason to track it
|
||||
if (result != S.S_OK &&
|
||||
Interlocked.CompareExchange(
|
||||
ref Unsafe.As<HRESULT, int>(ref this.deviceRemovedReason),
|
||||
(int)result,
|
||||
S.S_OK) == S.S_OK)
|
||||
{
|
||||
QueueRaiseDeviceLostEvent();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues the <see cref="DeviceLost"/> event being raised on the thread pool.
|
||||
/// </summary>
|
||||
private void QueueRaiseDeviceLostEvent()
|
||||
{
|
||||
static void RaiseDeviceLostEvent(GraphicsDevice device)
|
||||
{
|
||||
HRESULT result = Volatile.Read(ref Unsafe.As<HRESULT, int>(ref device.deviceRemovedReason));
|
||||
|
||||
DeviceLostReason reason = (int)result switch
|
||||
{
|
||||
DXGI.DXGI_ERROR_DEVICE_HUNG => DeviceLostReason.DeviceHung,
|
||||
DXGI.DXGI_ERROR_DEVICE_REMOVED => DeviceLostReason.DeviceRemoved,
|
||||
DXGI.DXGI_ERROR_DEVICE_RESET => DeviceLostReason.DeviceReset,
|
||||
DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR => DeviceLostReason.DriverInternalError,
|
||||
DXGI.DXGI_ERROR_INVALID_CALL => DeviceLostReason.InvalidCall,
|
||||
_ => DeviceLostReason.UnspecifiedError
|
||||
};
|
||||
|
||||
device.DeviceLost?.Invoke(device, reason);
|
||||
}
|
||||
|
||||
ThreadPool.QueueUserWorkItem(static state => RaiseDeviceLostEvent((GraphicsDevice)state!), this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to notify whenever the current device is lost.
|
||||
/// </summary>
|
||||
/// <param name="device">The current <see cref="GraphicsDevice"/> instance.</param>
|
||||
/// <param name="deviceHandle">The resulting <see cref="GCHandle"/> used as callback state.</param>
|
||||
/// <param name="deviceRemovedEvent">The resulting device lost event for the callback.</param>
|
||||
private static void RegisterDeviceLostCallback(GraphicsDevice device, out GCHandle deviceHandle, out HANDLE deviceRemovedEvent)
|
||||
{
|
||||
HANDLE eventHandle = Windows.CreateEventW(null, Windows.FALSE, Windows.FALSE, null);
|
||||
|
||||
// Whenever a device is lost, for any reason, all fences are signaled to the highest value.
|
||||
// As such, a fence event with a value of ulong.MaxValue can act as a device lost callback.
|
||||
device.d3D12ComputeFence.Get()->SetEventOnCompletion(ulong.MaxValue, eventHandle).Assert();
|
||||
|
||||
GCHandle handle = deviceHandle = GCHandle.Alloc(device, GCHandleType.Weak);
|
||||
HANDLE waitHandle;
|
||||
|
||||
_ = Windows.RegisterWaitForSingleObject(
|
||||
phNewWaitObject: &waitHandle,
|
||||
hObject: eventHandle,
|
||||
#if NET6_0_OR_GREATER
|
||||
Callback: &WaitForSingleObjectCallbackForRegisterDeviceLostCallback,
|
||||
#else
|
||||
Callback: (void*)Marshal.GetFunctionPointerForDelegate(WaitForSingleObjectCallbackForRegisterDeviceLostCallbackWrapper),
|
||||
#endif
|
||||
Context: (void*)(IntPtr)handle,
|
||||
dwMilliseconds: Windows.INFINITE,
|
||||
dwFlags: 0);
|
||||
|
||||
deviceRemovedEvent = waitHandle;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unregisters a callback setup by <see cref="RegisterDeviceLostCallback"/>.
|
||||
/// </summary>
|
||||
/// <param name="device">The current <see cref="GraphicsDevice"/> instance.</param>
|
||||
private static void UnregisterDeviceLostCallback(GraphicsDevice device)
|
||||
{
|
||||
_ = Windows.UnregisterWait(device.deviceRemovedEvent);
|
||||
_ = Windows.CloseHandle(device.deviceRemovedEvent);
|
||||
|
||||
device.deviceHandle.Free();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The callback to signal a device lost event.
|
||||
/// </summary>
|
||||
/// <param name="pContext">The input context.</param>
|
||||
/// <param name="timedOut">Whether the wait has timed out.</param>
|
||||
[UnmanagedCallersOnly]
|
||||
private static void WaitForSingleObjectCallbackForRegisterDeviceLostCallback(void* pContext, byte timedOut)
|
||||
{
|
||||
GraphicsDevice device = Unsafe.As<GraphicsDevice>(GCHandle.FromIntPtr((IntPtr)pContext).Target!);
|
||||
|
||||
device.QueueRaiseDeviceLostEventIfNeeded();
|
||||
}
|
||||
}
|
||||
@@ -31,9 +31,9 @@ unsafe partial class GraphicsDevice
|
||||
private delegate void WaitForSingleObjectCallbackDelegate(void* pContext, byte timedOut);
|
||||
|
||||
/// <summary>
|
||||
/// A cached <see cref="WaitForSingleObjectCallbackDelegate"/> instance wrapping <see cref="WaitForSingleObjectCallback(void*, byte)"/>.
|
||||
/// A cached <see cref="WaitForSingleObjectCallbackDelegate"/> instance wrapping <see cref="WaitForSingleObjectCallbackForWaitForFenceAsync(void*, byte)"/>.
|
||||
/// </summary>
|
||||
private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackWrapper = WaitForSingleObjectCallback;
|
||||
private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackForWaitForFenceAsyncWrapper = WaitForSingleObjectCallbackForWaitForFenceAsync;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
@@ -131,7 +131,7 @@ unsafe partial class GraphicsDevice
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A context to support <see cref="WaitForSingleObjectCallback"/>.
|
||||
/// A context to support <see cref="WaitForSingleObjectCallbackForWaitForFenceAsync"/>.
|
||||
/// </summary>
|
||||
private struct CallbackContext
|
||||
{
|
||||
@@ -195,9 +195,9 @@ unsafe partial class GraphicsDevice
|
||||
phNewWaitObject: &waitHandle,
|
||||
hObject: eventHandle,
|
||||
#if NET6_0_OR_GREATER
|
||||
Callback: &WaitForSingleObjectCallback,
|
||||
Callback: &WaitForSingleObjectCallbackForWaitForFenceAsync,
|
||||
#else
|
||||
Callback: (void*)Marshal.GetFunctionPointerForDelegate(WaitForSingleObjectCallbackWrapper),
|
||||
Callback: (void*)Marshal.GetFunctionPointerForDelegate(WaitForSingleObjectCallbackForWaitForFenceAsyncWrapper),
|
||||
#endif
|
||||
Context: callbackContext,
|
||||
dwMilliseconds: Windows.INFINITE,
|
||||
@@ -212,7 +212,7 @@ unsafe partial class GraphicsDevice
|
||||
/// <param name="pContext">The input context.</param>
|
||||
/// <param name="timedOut">Whether the wait has timed out.</param>
|
||||
[UnmanagedCallersOnly]
|
||||
private static void WaitForSingleObjectCallback(void* pContext, byte timedOut)
|
||||
private static void WaitForSingleObjectCallbackForWaitForFenceAsync(void* pContext, byte timedOut)
|
||||
{
|
||||
CallbackContext* callbackContext = (CallbackContext*)pContext;
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Runtime.InteropServices;
|
||||
using CommunityToolkit.Diagnostics;
|
||||
using ComputeSharp.Graphics.Commands.Interop;
|
||||
#if NET6_0_OR_GREATER
|
||||
@@ -87,6 +87,16 @@ public sealed unsafe partial class GraphicsDevice : NativeObject
|
||||
private ComPtr<D3D12MA_Pool> pool;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A weak <see cref="GCHandle"/> to the current instance (used to support the device lost callback).
|
||||
/// </summary>
|
||||
private GCHandle deviceHandle;
|
||||
|
||||
/// <summary>
|
||||
/// The wait event for the device removed.
|
||||
/// </summary>
|
||||
private HANDLE deviceRemovedEvent;
|
||||
|
||||
/// <summary>
|
||||
/// The reason the device was removed, if any.
|
||||
/// </summary>
|
||||
@@ -153,6 +163,10 @@ public sealed unsafe partial class GraphicsDevice : NativeObject
|
||||
this.pool = this.allocator.Get()->CreatePoolForCacheCoherentUMA();
|
||||
}
|
||||
#endif
|
||||
|
||||
this.deviceRemovedReason = S.S_OK;
|
||||
|
||||
RegisterDeviceLostCallback(this, out this.deviceHandle, out this.deviceRemovedEvent);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -373,56 +387,6 @@ public sealed unsafe partial class GraphicsDevice : NativeObject
|
||||
d3D12GraphicsCommandList->SetDescriptorHeaps(1, &d3D12DescriptorHeap);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raises the <see cref="DeviceLost"/> event if needed.
|
||||
/// </summary>
|
||||
internal void RaiseDeviceLostEventIfNeeded()
|
||||
{
|
||||
if (IsDisposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If the current device removed reason is not S_OK, it means the event
|
||||
// has already been raised (but the device will keep reporting that reason).
|
||||
// In that case, do nothing to avoid raising it again while the device is alive.
|
||||
if (Volatile.Read(ref Unsafe.As<HRESULT, int>(ref this.deviceRemovedReason)) != S.S_OK)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
HRESULT result = this.d3D12Device.Get()->GetDeviceRemovedReason();
|
||||
|
||||
// Only raise the event once, and store the device removed reason to track it
|
||||
if (Interlocked.CompareExchange(
|
||||
ref Unsafe.As<HRESULT, int>(ref this.deviceRemovedReason),
|
||||
(int)result,
|
||||
S.S_OK) == S.S_OK)
|
||||
{
|
||||
ThreadPool.QueueUserWorkItem(static state => ((GraphicsDevice)state!).RaiseDeviceLostEvent(), this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raises the <see cref="DeviceLost"/> event.
|
||||
/// </summary>
|
||||
private void RaiseDeviceLostEvent()
|
||||
{
|
||||
HRESULT result = Volatile.Read(ref Unsafe.As<HRESULT, int>(ref this.deviceRemovedReason));
|
||||
|
||||
DeviceLostReason reason = (int)result switch
|
||||
{
|
||||
DXGI.DXGI_ERROR_DEVICE_HUNG => DeviceLostReason.DeviceHung,
|
||||
DXGI.DXGI_ERROR_DEVICE_REMOVED => DeviceLostReason.DeviceRemoved,
|
||||
DXGI.DXGI_ERROR_DEVICE_RESET => DeviceLostReason.DeviceReset,
|
||||
DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR => DeviceLostReason.DriverInternalError,
|
||||
DXGI.DXGI_ERROR_INVALID_CALL => DeviceLostReason.InvalidCall,
|
||||
_ => DeviceLostReason.UnspecifiedError
|
||||
};
|
||||
|
||||
DeviceLost?.Invoke(this, reason);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void OnDispose()
|
||||
{
|
||||
@@ -440,6 +404,8 @@ public sealed unsafe partial class GraphicsDevice : NativeObject
|
||||
this.pool.Dispose();
|
||||
this.allocator.Dispose();
|
||||
#endif
|
||||
|
||||
UnregisterDeviceLostCallback(this);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
|
||||
@@ -180,25 +180,4 @@ partial class DeviceHelper
|
||||
|
||||
return hasErrorsOrWarnings;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raises the <see cref="GraphicsDevice.DeviceLost"/> event if needed, on all existing devices.
|
||||
/// </summary>
|
||||
public static void RaiseAllDeviceLostEventsIfNeeded()
|
||||
{
|
||||
lock (DevicesCache)
|
||||
{
|
||||
foreach (GraphicsDevice device in DevicesCache.Values)
|
||||
{
|
||||
// Check whether the device was lost, and raise the event once. This method will
|
||||
// queue the event being raised on a thread pool thread, which is crucial to avoid
|
||||
// invoking the handlers while taking a lock on the devices cache. Doing so would
|
||||
// lead to issues if a handler tried to synchronously create a new device, which would
|
||||
// take the same lock (it's reentrant) and then add the new device to the cache. Then
|
||||
// once this method resumed, the collection would be invalid, and the foreach loop
|
||||
// would throw an exception on the next iteration. This will prevent that from happening.
|
||||
device.RaiseDeviceLostEventIfNeeded();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,7 @@ public abstract class NativeObject : IDisposable
|
||||
/// <summary>
|
||||
/// Throws an <see cref="ObjectDisposedException"/> if the current instance has been disposed.
|
||||
/// </summary>
|
||||
/// <exception cref="ObjectDisposedException">Thrown if the current instance is disposed.</exception>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal void ThrowIfDisposed()
|
||||
{
|
||||
@@ -80,9 +81,9 @@ public abstract class NativeObject : IDisposable
|
||||
// We can't use ThrowHelper here as we only want to invoke ToString if we
|
||||
// are about to throw an exception. The JIT will recognize this pattern
|
||||
// as this method has a single basic block that always throws an exception.
|
||||
void Throw() => throw new ObjectDisposedException(ToString());
|
||||
static void Throw(object self) => throw new ObjectDisposedException(self.ToString());
|
||||
|
||||
Throw();
|
||||
Throw(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,9 @@ namespace TerraFX.Interop.Windows
|
||||
[DllImport("kernel32", ExactSpelling = true)]
|
||||
public static extern BOOL RegisterWaitForSingleObject([NativeTypeName("PHANDLE")] HANDLE* phNewWaitObject, HANDLE hObject, [NativeTypeName("WAITORTIMERCALLBACK")] void* Callback, [NativeTypeName("PVOID")] void* Context, [NativeTypeName("ULONG")] uint dwMilliseconds, [NativeTypeName("ULONG")] uint dwFlags);
|
||||
|
||||
[DllImport("kernel32", ExactSpelling = true)]
|
||||
public static extern BOOL UnregisterWait(HANDLE WaitHandle);
|
||||
|
||||
[NativeTypeName("#define INFINITE 0xFFFFFFFF")]
|
||||
public const uint INFINITE = 0xFFFFFFFF;
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ public partial class DeviceLostTests
|
||||
{
|
||||
GraphicsDevice graphicsDevice = device.Get();
|
||||
|
||||
bool win32ExceptionThrown = false;
|
||||
//bool win32ExceptionThrown = false;
|
||||
TaskCompletionSource<(object? Sender, DeviceLostReason Reason)> tcs = new();
|
||||
|
||||
// Register the device lost callback
|
||||
@@ -28,20 +28,12 @@ public partial class DeviceLostTests
|
||||
using ReadWriteBuffer<float> bufferB = graphicsDevice.AllocateReadWriteBuffer<float>(128);
|
||||
|
||||
graphicsDevice.For(128, new ComputeShaderGettingStuck(bufferA, bufferB, 12345678, 87654321, 42));
|
||||
|
||||
// The shader above will always hang, but it's not guaranteed that the DirectX runtime will detect
|
||||
// the error right when executing that command. As such, we can force it to be detected by running
|
||||
// any other command after that. At this point the device is lost, so any operation will fail.
|
||||
graphicsDevice.For(128, new ComputeShaderGettingStuck(bufferA, bufferB, 2, 2, 42));
|
||||
}
|
||||
catch (Win32Exception)
|
||||
{
|
||||
win32ExceptionThrown = true;
|
||||
// This is not guaranteed to be thrown, but handle it just in case
|
||||
}
|
||||
|
||||
// The previous shader must hang and cause an exception
|
||||
Assert.IsTrue(win32ExceptionThrown);
|
||||
|
||||
// Wait up to a second for the event to be raised (it's raised asynchronously on a thread pool thread)
|
||||
await Task.WhenAny(tcs.Task, Task.Delay(1000));
|
||||
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする