diff --git a/DiskInfoToolkit/Core/Windows/IoControlRequest.cs b/DiskInfoToolkit/Core/Windows/IoControlRequest.cs new file mode 100644 index 0000000..659c97e --- /dev/null +++ b/DiskInfoToolkit/Core/Windows/IoControlRequest.cs @@ -0,0 +1,141 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + * + * Copyright (c) 2026 Florian K. + */ + +using Microsoft.Win32.SafeHandles; +using OS = BlackSharp.Core.Platform.OperatingSystem; + +namespace DiskInfoToolkit.Core.Windows +{ + internal sealed class IoControlRequest : IDisposable + { + #region Constructor + + public IoControlRequest(SafeFileHandle handle, uint ioControlCode, byte[] inBuffer, byte[] outBuffer) + { + if (!OS.IsWindows()) + { + throw new PlatformNotSupportedException(); + } + + Handle = handle; + IoControlCode = ioControlCode; + InBuffer = inBuffer; + OutBuffer = outBuffer; + } + + #endregion + + #region Fields + + private readonly ManualResetEvent _completed = new ManualResetEvent(false); + + private readonly object _syncRoot = new object(); + + private bool _completedState; + + private bool _timedOut; + + private bool _disposed; + + #endregion + + #region Properties + + public SafeFileHandle Handle { get; } + + public uint IoControlCode { get; } + + public byte[] InBuffer { get; } + + public byte[] OutBuffer { get; } + + public bool Succeeded { get; private set; } + + public int LastError { get; private set; } + + public int BytesReturned { get; private set; } + + public Exception Exception { get; private set; } + + #endregion + + #region Public + + public bool Wait(int timeoutMilliseconds) + { + return _completed.WaitOne(timeoutMilliseconds); + } + + public bool MarkTimedOut() + { + lock (_syncRoot) + { + if (_completedState) + { + return false; + } + + _timedOut = true; + return true; + } + } + + public void Complete(bool succeeded, int lastError, int bytesReturned, Exception exception) + { + bool shouldDispose = false; + + lock (_syncRoot) + { + if (_timedOut) + { + return; + } + + Succeeded = succeeded; + LastError = lastError; + BytesReturned = bytesReturned; + Exception = exception; + _completedState = true; + + if (_disposed) + { + shouldDispose = true; + } + else + { + _completed.Set(); + } + } + + if (shouldDispose) + { + _completed.Dispose(); + } + } + + public void Dispose() + { + lock (_syncRoot) + { + if (_disposed) + { + return; + } + + _disposed = true; + + if (_completedState) + { + _completed.Dispose(); + } + } + } + + #endregion + } +} diff --git a/DiskInfoToolkit/Core/Windows/IoControlWorker.cs b/DiskInfoToolkit/Core/Windows/IoControlWorker.cs new file mode 100644 index 0000000..694307a --- /dev/null +++ b/DiskInfoToolkit/Core/Windows/IoControlWorker.cs @@ -0,0 +1,160 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + * + * Copyright (c) 2026 Florian K. + */ + +using OS = BlackSharp.Core.Platform.OperatingSystem; + +namespace DiskInfoToolkit.Core.Windows +{ + internal sealed class IoControlWorker + { + #region Constructor + + public IoControlWorker(int id) + { + if (!OS.IsWindows()) + { + throw new PlatformNotSupportedException(); + } + + ID = id; + + _thread = new Thread(ProcessRequests) + { + IsBackground = true, + Name = $"{nameof(WindowsStorageIoControl)}.{nameof(IoControlWorker)}" + }; + + _thread.Start(); + } + + #endregion + + #region Fields + + private readonly object _syncRoot = new object(); + + private readonly AutoResetEvent _requestAvailable = new AutoResetEvent(false); + + private readonly Thread _thread; + + private IoControlRequest _request; + + private bool _abandoned; + + #endregion + + #region Properties + + public int ID { get; } + + public bool CanAcceptWork + { + get + { + lock (_syncRoot) + { + return !_abandoned; + } + } + } + + #endregion + + #region Public + + public bool TryEnqueue(IoControlRequest request) + { + lock (_syncRoot) + { + if (_abandoned || _request != null) + { + return false; + } + + _request = request; + _requestAvailable.Set(); + + return true; + } + } + + public void MarkAbandoned() + { + lock (_syncRoot) + { + _abandoned = true; + } + } + + #endregion + + #region Private + + private void ProcessRequests() + { + try + { + while (true) + { + _requestAvailable.WaitOne(); + + IoControlRequest request; + lock (_syncRoot) + { + request = _request; + _request = null; + } + + if (request != null) + { + ProcessRequest(request); + } + + lock (_syncRoot) + { + if (_abandoned) + { + break; + } + } + } + } + finally + { + _requestAvailable.Dispose(); + } + } + + private static void ProcessRequest(IoControlRequest request) + { + bool success = false; + int lastError = 0; + int bytesReturned = 0; + Exception exception = null; + + try + { + success = WindowsStorageIoControl.SendRawIoControlCore( + request.Handle, + request.IoControlCode, + request.InBuffer, + request.OutBuffer, + out bytesReturned, + out lastError); + } + catch (Exception ex) + { + exception = ex; + } + + request.Complete(success, lastError, bytesReturned, exception); + } + + #endregion + } +} diff --git a/DiskInfoToolkit/Core/WindowsStorageIoControl.cs b/DiskInfoToolkit/Core/WindowsStorageIoControl.cs index 4169b22..b69900d 100644 --- a/DiskInfoToolkit/Core/WindowsStorageIoControl.cs +++ b/DiskInfoToolkit/Core/WindowsStorageIoControl.cs @@ -14,6 +14,7 @@ using DiskInfoToolkit.Utilities; using Microsoft.Win32.SafeHandles; using System.Collections.Concurrent; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; @@ -35,6 +36,22 @@ public sealed class WindowsStorageIoControl : IStorageIoControl private static int _openDeviceWorkerSequence; + private const int DefaultIoControlTimeoutMilliseconds = 30000; + + private const int DefaultIoControlTimeoutCooldownMilliseconds = 300000; + + private const int IoControlTimeoutError = 1460; //ERROR_TIMEOUT + + private static readonly ConcurrentDictionary IoControlTimeouts = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + + private static readonly ConditionalWeakTable OpenDeviceHandlePaths = new ConditionalWeakTable(); + + private static readonly object IoControlWorkerSyncRoot = new object(); + + private static IoControlWorker _ioControlWorker; + + private static int _ioControlWorkerSequence; + #endregion #region Properties @@ -43,6 +60,10 @@ public sealed class WindowsStorageIoControl : IStorageIoControl public static int OpenDeviceTimeoutCooldownMilliseconds { get; set; } = DefaultOpenDeviceTimeoutCooldownMilliseconds; + public static int IoControlTimeoutMilliseconds { get; set; } = DefaultIoControlTimeoutMilliseconds; + + public static int IoControlTimeoutCooldownMilliseconds { get; set; } = DefaultIoControlTimeoutCooldownMilliseconds; + public uint LastIoControlCode { get; private set; } public int LastIoControlError { get; private set; } @@ -71,31 +92,35 @@ public SafeFileHandle OpenDevice(string path, uint desiredAccess, uint shareMode if (OpenDeviceTimeoutMilliseconds <= 0) { - return OpenDeviceCore(path, desiredAccess, shareMode, creationDisposition, flagsAndAttributes); + SafeFileHandle handle = OpenDeviceCore(path, desiredAccess, shareMode, creationDisposition, flagsAndAttributes); + TrackOpenDevicePath(handle, path); + return handle; } - return OpenDeviceWithTimeout(path, desiredAccess, shareMode, creationDisposition, flagsAndAttributes, OpenDeviceTimeoutMilliseconds); + SafeFileHandle handleWithTimeout = OpenDeviceWithTimeout(path, desiredAccess, shareMode, creationDisposition, flagsAndAttributes, OpenDeviceTimeoutMilliseconds); + TrackOpenDevicePath(handleWithTimeout, path); + return handleWithTimeout; } public bool SendRawIoControl(SafeFileHandle handle, uint ioControlCode, byte[] inBuffer, byte[] outBuffer, out int bytesReturned) { - bool success = Kernel32Native.DeviceIoControl( - handle, - ioControlCode, - inBuffer, - inBuffer != null ? inBuffer.Length : 0, - outBuffer, - outBuffer != null ? outBuffer.Length : 0, - out bytesReturned, - IntPtr.Zero); + if (IsIoControlInTimeoutCooldown(handle)) + { + return RecordIoControlTimeout(ioControlCode, out bytesReturned); + } - int lastError = Marshal.GetLastWin32Error(); + if (IoControlTimeoutMilliseconds <= 0) + { + bool success = SendRawIoControlCore(handle, ioControlCode, inBuffer, outBuffer, out bytesReturned, out int lastError); - LastIoControlCode = ioControlCode; - LastIoControlSucceeded = success; - LastIoControlError = success ? 0 : lastError; + LastIoControlCode = ioControlCode; + LastIoControlSucceeded = success; + LastIoControlError = success ? 0 : lastError; - return success; + return success; + } + + return SendRawIoControlWithTimeout(handle, ioControlCode, inBuffer, outBuffer, out bytesReturned, IoControlTimeoutMilliseconds); } public bool TryGetStorageDeviceDescriptor(SafeFileHandle handle, out StorageDeviceDescriptorInfo descriptor) @@ -385,6 +410,23 @@ internal static SafeFileHandle OpenDeviceCore(string path, uint desiredAccess, u return Kernel32Native.CreateFile(path, desiredAccess, shareMode, IntPtr.Zero, creationDisposition, flagsAndAttributes, IntPtr.Zero); } + internal static bool SendRawIoControlCore(SafeFileHandle handle, uint ioControlCode, byte[] inBuffer, byte[] outBuffer, out int bytesReturned, out int lastError) + { + bool success = Kernel32Native.DeviceIoControl( + handle, + ioControlCode, + inBuffer, + inBuffer != null ? inBuffer.Length : 0, + outBuffer, + outBuffer != null ? outBuffer.Length : 0, + out bytesReturned, + IntPtr.Zero); + + lastError = Marshal.GetLastWin32Error(); + + return success; + } + #endregion #region Private @@ -478,7 +520,108 @@ private static OpenDeviceWorker CreateOpenDeviceWorker() return new OpenDeviceWorker(id); } + private bool SendRawIoControlWithTimeout(SafeFileHandle handle, uint ioControlCode, byte[] inBuffer, byte[] outBuffer, out int bytesReturned, int timeoutMilliseconds) + { + var request = new IoControlRequest(handle, ioControlCode, inBuffer, outBuffer); + + try + { + IoControlWorker worker; + + lock (IoControlWorkerSyncRoot) + { + worker = GetOrCreateIoControlWorker(); + if (!worker.TryEnqueue(request)) + { + worker.MarkAbandoned(); + worker = CreateIoControlWorker(); + + if (!worker.TryEnqueue(request)) + { + RememberIoControlTimeout(handle); + return RecordIoControlTimeout(ioControlCode, out bytesReturned); + } + } + + if (!request.Wait(timeoutMilliseconds) && request.MarkTimedOut()) + { + worker.MarkAbandoned(); + + if (ReferenceEquals(_ioControlWorker, worker)) + { + _ioControlWorker = null; + } + + RememberIoControlTimeout(handle); + return RecordIoControlTimeout(ioControlCode, out bytesReturned); + } + } + + if (request.Exception != null) + { + throw request.Exception; + } + + bytesReturned = request.BytesReturned; + LastIoControlCode = ioControlCode; + LastIoControlSucceeded = request.Succeeded; + LastIoControlError = request.Succeeded ? 0 : request.LastError; + + return request.Succeeded; + } + finally + { + request.Dispose(); + } + } + + private bool RecordIoControlTimeout(uint ioControlCode, out int bytesReturned) + { + bytesReturned = 0; + LastIoControlCode = ioControlCode; + LastIoControlSucceeded = false; + LastIoControlError = IoControlTimeoutError; + + return false; + } + + private static IoControlWorker GetOrCreateIoControlWorker() + { + if (_ioControlWorker == null || !_ioControlWorker.CanAcceptWork) + { + _ioControlWorker = CreateIoControlWorker(); + } + + return _ioControlWorker; + } + + private static IoControlWorker CreateIoControlWorker() + { + int id = Interlocked.Increment(ref _ioControlWorkerSequence); + return new IoControlWorker(id); + } + private static bool IsOpenDeviceInTimeoutCooldown(string path) + { + return IsPathInTimeoutCooldown(OpenDeviceTimeouts, path); + } + + private static bool IsIoControlInTimeoutCooldown(SafeFileHandle handle) + { + return IsPathInTimeoutCooldown(IoControlTimeouts, GetHandleDevicePath(handle)); + } + + private static void RememberOpenDeviceTimeout(string path) + { + RememberPathTimeout(OpenDeviceTimeouts, path, OpenDeviceTimeoutCooldownMilliseconds); + } + + private static void RememberIoControlTimeout(SafeFileHandle handle) + { + RememberPathTimeout(IoControlTimeouts, GetHandleDevicePath(handle), IoControlTimeoutCooldownMilliseconds); + } + + private static bool IsPathInTimeoutCooldown(ConcurrentDictionary timeouts, string path) { string key = StringUtil.TrimStorageString(path); if (string.IsNullOrWhiteSpace(key)) @@ -486,7 +629,7 @@ private static bool IsOpenDeviceInTimeoutCooldown(string path) return false; } - if (!OpenDeviceTimeouts.TryGetValue(key, out var blockedUntilUtc)) + if (!timeouts.TryGetValue(key, out var blockedUntilUtc)) { return false; } @@ -496,20 +639,41 @@ private static bool IsOpenDeviceInTimeoutCooldown(string path) return true; } - OpenDeviceTimeouts.TryRemove(key, out _); + timeouts.TryRemove(key, out _); return false; } - private static void RememberOpenDeviceTimeout(string path) + private static void RememberPathTimeout(ConcurrentDictionary timeouts, string path, int cooldownMilliseconds) { string key = StringUtil.TrimStorageString(path); - if (string.IsNullOrWhiteSpace(key) || OpenDeviceTimeoutCooldownMilliseconds <= 0) + if (string.IsNullOrWhiteSpace(key) || cooldownMilliseconds <= 0) + { + return; + } + + var blockedUntilUtc = DateTime.UtcNow.AddMilliseconds(cooldownMilliseconds); + timeouts[key] = blockedUntilUtc; + } + + private static string GetHandleDevicePath(SafeFileHandle handle) + { + if (handle == null) + { + return null; + } + + OpenDeviceHandlePaths.TryGetValue(handle, out string path); + return path; + } + + private static void TrackOpenDevicePath(SafeFileHandle handle, string path) + { + if (handle == null || handle.IsInvalid || string.IsNullOrWhiteSpace(path)) { return; } - var blockedUntilUtc = DateTime.UtcNow.AddMilliseconds(OpenDeviceTimeoutCooldownMilliseconds); - OpenDeviceTimeouts[key] = blockedUntilUtc; + OpenDeviceHandlePaths.Add(handle, path); } private static SafeFileHandle CreateInvalidFileHandle()