Files
ThreadPilot/Services/ProcessMemoryPriorityService.cs
PrimeBuild-pc cb0c5c3efb feat: Game Boost scheduler hints and dynamic CPU Set release
Game Boost now gives Windows hints as well as constraints, and adapts
the game's CPU Set to its load instead of applying it once:

- the game gets high QoS (power throttling off), on every CPU, so
  Windows never throttles it while it is not in the foreground;
- in Isolation the listed background apps get EcoQoS, also on CPUs
  where CPU Sets are not applied;
- a game that keeps its confined CPUs saturated has its CPU Set
  released so Windows can use every core, and confined again after a
  minute of low load (hysteresis, at most two releases per session).

Same ownership rules as CPU Sets: only values Windows still manages
are changed, user rules and the app's own QoS win, everything is
journaled and restored on exit, toggle and after a crash.

Efficiency mode writes now keep the process's other power-throttling
flags: Windows replaces the whole state on set, so the old write wiped
a timer-resolution opt-out set by the process itself.
2026-10-22 10:54:37 +02:00

481 lines
22 KiB
C#

/*
* ThreadPilot - process memory priority service.
*/
namespace ThreadPilot.Services
{
using System.ComponentModel;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Logging;
using ThreadPilot.Models;
using ThreadPilot.Platforms.Windows;
public sealed class ProcessMemoryPriorityService : IProcessMemoryPriorityService
{
public const string UnsupportedUserMessage =
"Memory priority is not supported on this Windows version or process.";
private const string InvalidMemoryPriorityUserMessage =
"This memory priority value is not supported.";
private const string InvalidProcessErrorCode = "InvalidProcess";
private const string UnsupportedErrorCode = "Unsupported";
private const string InvalidPriorityErrorCode = "InvalidMemoryPriority";
private static readonly uint MemoryPriorityInformationSize =
(uint)Marshal.SizeOf<MemoryPriorityInformation>();
private readonly IProcessMemoryPriorityNativeApi nativeApi;
private readonly ILogger<ProcessMemoryPriorityService> logger;
public ProcessMemoryPriorityService(
IProcessMemoryPriorityNativeApi nativeApi,
ILogger<ProcessMemoryPriorityService> logger)
{
this.nativeApi = nativeApi ?? throw new ArgumentNullException(nameof(nativeApi));
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public Task<ProcessMemoryPriority?> GetMemoryPriorityAsync(ProcessModel process)
{
if (!this.nativeApi.IsSupported || !IsValidProcess(process))
{
return Task.FromResult<ProcessMemoryPriority?>(null);
}
try
{
using var handle = this.nativeApi.OpenProcess(
ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION,
inheritHandle: false,
(uint)process.ProcessId);
if (handle.IsInvalid)
{
this.logger.LogDebug(
"OpenProcess failed while reading memory priority for process {ProcessName} (PID: {ProcessId}): {Error}",
process.Name,
process.ProcessId,
this.nativeApi.GetLastWin32Error());
return Task.FromResult<ProcessMemoryPriority?>(null);
}
var information = default(MemoryPriorityInformation);
if (!this.nativeApi.GetProcessInformation(
handle,
ProcessInformationClass.ProcessMemoryPriority,
ref information,
MemoryPriorityInformationSize))
{
this.logger.LogDebug(
"GetProcessInformation(ProcessMemoryPriority) failed for process {ProcessName} (PID: {ProcessId}): {Error}",
process.Name,
process.ProcessId,
this.nativeApi.GetLastWin32Error());
return Task.FromResult<ProcessMemoryPriority?>(null);
}
return Task.FromResult(FromWindowsMemoryPriority(information.MemoryPriority));
}
catch (Exception ex) when (IsUnsupported(ex) || AffinityApplyExceptionClassifier.IsAccessDenied(ex) || AffinityApplyExceptionClassifier.IsProcessExited(ex))
{
this.logger.LogDebug(
ex,
"Could not read memory priority for process {ProcessName} (PID: {ProcessId})",
process.Name,
process.ProcessId);
return Task.FromResult<ProcessMemoryPriority?>(null);
}
}
public Task<ProcessOperationResult> SetMemoryPriorityAsync(ProcessModel process, ProcessMemoryPriority priority)
{
if (!IsValidProcess(process))
{
return Task.FromResult(ProcessOperationResult.Failed(
InvalidProcessErrorCode,
ProcessOperationUserMessages.ProcessExited,
"Process is null or has an invalid PID."));
}
if (!IsDefinedPriority(priority))
{
return Task.FromResult(ProcessOperationResult.Failed(
InvalidPriorityErrorCode,
InvalidMemoryPriorityUserMessage,
$"Memory priority value '{priority}' is not supported."));
}
if (!this.nativeApi.IsSupported)
{
return Task.FromResult(Unsupported("The Windows process memory priority APIs are unavailable."));
}
try
{
using var handle = this.nativeApi.OpenProcess(
ProcessAccessFlags.PROCESS_SET_INFORMATION,
inheritHandle: false,
(uint)process.ProcessId);
if (handle.IsInvalid)
{
return Task.FromResult(this.FromLastError(
"OpenProcess failed before SetProcessInformation(ProcessMemoryPriority)."));
}
var information = new MemoryPriorityInformation
{
MemoryPriority = ToWindowsMemoryPriority(priority),
};
if (!this.nativeApi.SetProcessInformation(
handle,
ProcessInformationClass.ProcessMemoryPriority,
ref information,
MemoryPriorityInformationSize))
{
return Task.FromResult(this.FromLastError(
"SetProcessInformation(ProcessMemoryPriority) failed."));
}
return Task.FromResult(ProcessOperationResult.Succeeded(
"Memory priority applied.",
$"Process {process.Name} (PID: {process.ProcessId}) memory priority set to {priority}."));
}
catch (Exception ex) when (IsUnsupported(ex))
{
return Task.FromResult(Unsupported(ex.Message));
}
catch (Exception ex) when (AffinityApplyExceptionClassifier.IsProcessExited(ex))
{
return Task.FromResult(ProcessOperationResult.Failed(
AffinityApplyErrorCodes.ProcessExited,
ProcessOperationUserMessages.ProcessExited,
ex.Message,
isProcessExited: true));
}
catch (Exception ex) when (AffinityApplyExceptionClassifier.IsAccessDenied(ex))
{
var antiCheatLikely = AffinityApplyExceptionClassifier.IsAntiCheatLikely(ex);
return Task.FromResult(ProcessOperationResult.Failed(
antiCheatLikely
? AffinityApplyErrorCodes.AntiCheatOrProtectedProcessLikely
: AffinityApplyErrorCodes.AccessDenied,
antiCheatLikely
? ProcessOperationUserMessages.AntiCheatProtectedLikely
: ProcessOperationUserMessages.AccessDenied,
ex.Message,
isAccessDenied: true,
isAntiCheatLikely: antiCheatLikely));
}
catch (Exception ex)
{
this.logger.LogWarning(
ex,
"Memory priority apply failed for process {ProcessName} (PID: {ProcessId})",
process.Name,
process.ProcessId);
return Task.FromResult(ProcessOperationResult.Failed(
AffinityApplyErrorCodes.NativeApplyFailed,
"ThreadPilot could not apply the memory priority change.",
ex.Message));
}
}
public Task<ProcessIoPriority?> GetIoPriorityAsync(ProcessModel process)
{
if (!this.nativeApi.IsSupported || !IsValidProcess(process))
{
return Task.FromResult<ProcessIoPriority?>(null);
}
try
{
using var handle = this.nativeApi.OpenProcess(
ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION,
inheritHandle: false,
(uint)process.ProcessId);
if (handle.IsInvalid)
{
return Task.FromResult<ProcessIoPriority?>(null);
}
var value = 0;
var status = this.nativeApi.QueryIoPriority(handle, ref value, out _);
return Task.FromResult(status == 0 && Enum.IsDefined(typeof(ProcessIoPriority), value)
? (ProcessIoPriority?)value
: null);
}
catch (Exception ex)
{
this.logger.LogDebug(ex, "Could not read I/O priority for process {ProcessId}", process.ProcessId);
return Task.FromResult<ProcessIoPriority?>(null);
}
}
public Task<ProcessOperationResult> SetIoPriorityAsync(ProcessModel process, ProcessIoPriority priority)
{
if (!IsValidProcess(process))
{
return Task.FromResult(ProcessOperationResult.Failed(
InvalidProcessErrorCode,
ProcessOperationUserMessages.ProcessExited,
"Process is null or has an invalid PID."));
}
if (!Enum.IsDefined(priority))
{
return Task.FromResult(ProcessOperationResult.Failed(
"InvalidIoPriority",
"This I/O priority value is not supported.",
$"I/O priority value '{priority}' is not supported."));
}
try
{
using var handle = this.nativeApi.OpenProcess(
ProcessAccessFlags.PROCESS_SET_INFORMATION,
inheritHandle: false,
(uint)process.ProcessId);
if (handle.IsInvalid)
{
return Task.FromResult(this.FromLastError("OpenProcess failed before setting I/O priority."));
}
var value = (int)priority;
int status;
IDisposable? privilegeScope = null;
if (priority == ProcessIoPriority.High)
{
privilegeScope = this.nativeApi.AcquirePrivilegeScope(ProcessMemoryPriorityNativeMethods.SeIncreaseBasePriorityPrivilege);
}
try
{
status = this.nativeApi.SetIoPriority(handle, ref value);
}
finally
{
privilegeScope?.Dispose();
}
if (status == 0)
{
return Task.FromResult(ProcessOperationResult.Succeeded(
"I/O priority applied.",
$"Process {process.Name} (PID: {process.ProcessId}) I/O priority set to {priority}."));
}
return Task.FromResult(status switch
{
unchecked((int)0xC0000022) or unchecked((int)0xC0000061) => ProcessOperationResult.Failed(
AffinityApplyErrorCodes.AccessDenied,
ProcessOperationUserMessages.AccessDenied,
$"NtSetInformationProcess failed with NTSTATUS 0x{status:X8}.",
isAccessDenied: true),
unchecked((int)0xC0000008) => ProcessOperationResult.Failed(
AffinityApplyErrorCodes.ProcessExited,
ProcessOperationUserMessages.ProcessExited,
$"NtSetInformationProcess failed with NTSTATUS 0x{status:X8}.",
isProcessExited: true),
_ => ProcessOperationResult.Failed(
AffinityApplyErrorCodes.NativeApplyFailed,
"ThreadPilot could not apply the I/O priority change.",
$"NtSetInformationProcess failed with NTSTATUS 0x{status:X8}."),
});
}
catch (Exception ex) when (AffinityApplyExceptionClassifier.IsProcessExited(ex))
{
return Task.FromResult(ProcessOperationResult.Failed(
AffinityApplyErrorCodes.ProcessExited,
ProcessOperationUserMessages.ProcessExited,
ex.Message,
isProcessExited: true));
}
catch (Exception ex) when (AffinityApplyExceptionClassifier.IsAccessDenied(ex))
{
return Task.FromResult(ProcessOperationResult.Failed(
AffinityApplyErrorCodes.AccessDenied,
ProcessOperationUserMessages.AccessDenied,
ex.Message,
isAccessDenied: true));
}
catch (Exception ex)
{
this.logger.LogWarning(ex, "I/O priority apply failed for process {ProcessId}", process.ProcessId);
return Task.FromResult(ProcessOperationResult.Failed(
AffinityApplyErrorCodes.NativeApplyFailed,
"ThreadPilot could not apply the I/O priority change.",
ex.Message));
}
}
public Task<ProcessEfficiencyMode?> GetEfficiencyModeAsync(ProcessModel process)
{
if (!this.nativeApi.IsSupported || !IsValidProcess(process))
{
return Task.FromResult<ProcessEfficiencyMode?>(null);
}
try
{
using var handle = this.nativeApi.OpenProcess(
ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION,
inheritHandle: false,
(uint)process.ProcessId);
var state = new PowerThrottlingState { Version = PowerThrottlingState.CurrentVersion };
if (handle.IsInvalid || !this.nativeApi.GetPowerThrottling(handle, ref state))
{
return Task.FromResult<ProcessEfficiencyMode?>(null);
}
return Task.FromResult<ProcessEfficiencyMode?>(
(state.ControlMask & PowerThrottlingState.ExecutionSpeed) == 0 ? ProcessEfficiencyMode.SystemManaged
: (state.StateMask & PowerThrottlingState.ExecutionSpeed) != 0 ? ProcessEfficiencyMode.On
: ProcessEfficiencyMode.Off);
}
catch (Exception ex)
{
this.logger.LogDebug(ex, "Could not read efficiency mode for process {ProcessId}", process.ProcessId);
return Task.FromResult<ProcessEfficiencyMode?>(null);
}
}
public Task<ProcessOperationResult> SetEfficiencyModeAsync(ProcessModel process, ProcessEfficiencyMode mode)
{
const string FailureMessage = "ThreadPilot could not change the efficiency mode.";
if (!IsValidProcess(process))
{
return Task.FromResult(ProcessOperationResult.Failed(
InvalidProcessErrorCode,
ProcessOperationUserMessages.ProcessExited,
"Process is null or has an invalid PID."));
}
if (!Enum.IsDefined(mode))
{
return Task.FromResult(ProcessOperationResult.Failed(
"InvalidEfficiencyMode",
"This efficiency mode value is not supported.",
$"Efficiency mode value '{mode}' is not supported."));
}
try
{
using var handle = this.nativeApi.OpenProcess(
ProcessAccessFlags.PROCESS_SET_INFORMATION | ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION,
inheritHandle: false,
(uint)process.ProcessId);
if (handle.IsInvalid)
{
return Task.FromResult(this.FromLastError("OpenProcess failed before SetProcessInformation(ProcessPowerThrottling).", FailureMessage));
}
// Windows replaces the whole state on set: keep the process's other throttling flags
// (e.g. its timer-resolution opt-out) and change only the execution-speed bit.
var state = new PowerThrottlingState { Version = PowerThrottlingState.CurrentVersion };
if (!this.nativeApi.GetPowerThrottling(handle, ref state))
{
state = default;
}
const uint speed = PowerThrottlingState.ExecutionSpeed;
state.Version = PowerThrottlingState.CurrentVersion;
state.ControlMask = mode == ProcessEfficiencyMode.SystemManaged ? state.ControlMask & ~speed : state.ControlMask | speed;
state.StateMask = mode == ProcessEfficiencyMode.On ? state.StateMask | speed : state.StateMask & ~speed;
if (!this.nativeApi.SetPowerThrottling(handle, ref state))
{
return Task.FromResult(this.FromLastError("SetProcessInformation(ProcessPowerThrottling) failed.", FailureMessage));
}
return Task.FromResult(ProcessOperationResult.Succeeded(
"Efficiency mode applied.",
$"Process {process.Name} (PID: {process.ProcessId}) efficiency mode set to {mode}."));
}
catch (Exception ex) when (AffinityApplyExceptionClassifier.IsProcessExited(ex))
{
return Task.FromResult(ProcessOperationResult.Failed(
AffinityApplyErrorCodes.ProcessExited,
ProcessOperationUserMessages.ProcessExited,
ex.Message,
isProcessExited: true));
}
catch (Exception ex) when (AffinityApplyExceptionClassifier.IsAccessDenied(ex))
{
return Task.FromResult(ProcessOperationResult.Failed(
AffinityApplyErrorCodes.AccessDenied,
ProcessOperationUserMessages.AccessDenied,
ex.Message,
isAccessDenied: true));
}
catch (Exception ex)
{
this.logger.LogWarning(ex, "Efficiency mode apply failed for process {ProcessId}", process.ProcessId);
return Task.FromResult(ProcessOperationResult.Failed(
AffinityApplyErrorCodes.NativeApplyFailed,
FailureMessage,
ex.Message));
}
}
private static bool IsValidProcess(ProcessModel? process) =>
process != null && process.ProcessId > 0;
private static bool IsDefinedPriority(ProcessMemoryPriority priority) =>
priority is ProcessMemoryPriority.VeryLow or
ProcessMemoryPriority.Low or
ProcessMemoryPriority.Medium or
ProcessMemoryPriority.BelowNormal or
ProcessMemoryPriority.Normal;
private static uint ToWindowsMemoryPriority(ProcessMemoryPriority priority) =>
IsDefinedPriority(priority)
? (uint)priority
: throw new ArgumentOutOfRangeException(nameof(priority), priority, "Unsupported memory priority value.");
private static ProcessMemoryPriority? FromWindowsMemoryPriority(uint priority) =>
priority is >= (uint)ProcessMemoryPriority.VeryLow and <= (uint)ProcessMemoryPriority.Normal
? (ProcessMemoryPriority)priority
: null;
private static bool IsUnsupported(Exception ex) =>
ex is EntryPointNotFoundException ||
ex is DllNotFoundException ||
(ex is Win32Exception win32Exception && win32Exception.NativeErrorCode == 50);
private static ProcessOperationResult Unsupported(string technicalMessage) =>
ProcessOperationResult.Failed(
UnsupportedErrorCode,
UnsupportedUserMessage,
technicalMessage);
private ProcessOperationResult FromLastError(
string context,
string failureMessage = "ThreadPilot could not apply the memory priority change.")
{
var error = this.nativeApi.GetLastWin32Error();
var technicalMessage = $"{context} Win32 error {error}.";
return error switch
{
5 => ProcessOperationResult.Failed(
AffinityApplyErrorCodes.AccessDenied,
ProcessOperationUserMessages.AccessDenied,
technicalMessage,
isAccessDenied: true),
50 => Unsupported(technicalMessage),
87 => ProcessOperationResult.Failed(
AffinityApplyErrorCodes.ProcessExited,
ProcessOperationUserMessages.ProcessExited,
technicalMessage,
isProcessExited: true),
_ => ProcessOperationResult.Failed(
AffinityApplyErrorCodes.NativeApplyFailed,
failureMessage,
technicalMessage),
};
}
}
}