Files
ThreadPilot/Models/CpuSelection.cs
T
Prime Build 2665d2be9f feat: release experimental Game Boost preview 1.7.8-beta.1
Restore the complete local Game Boost/runtime topology work from 6c36ea6, including Activity diagnostics, while preserving the stable 1.7.7 release and channel guards. Preview notes document pending dual-CCD Ryzen/X3D, Intel hybrid, benchmarks and anti-cheat validation, with tester instructions.
2026-10-16 12:09:56 +02:00

373 lines
16 KiB
C#

namespace ThreadPilot.Models
{
using System;
using System.Collections.Generic;
using System.Linq;
public enum CpuAssignmentMode
{
Automatic = 0,
AffinityMask,
IdealProcessor,
CpuSets,
}
public readonly record struct ProcessorRef(ushort Group, byte LogicalProcessorNumber, int GlobalIndex);
public sealed record CpuTopologySignature
{
public string CpuBrand { get; init; } = "Unknown";
public int LogicalProcessorCount { get; init; }
public int PhysicalCoreCount { get; init; }
public int ProcessorGroupCount { get; init; } = 1;
public int NumaNodeCount { get; init; }
public int LastLevelCacheGroupCount { get; init; }
public int PackageCount { get; init; }
public string Source { get; init; } = "Unknown";
}
public sealed record CpuSelectionMetadata
{
public CpuTopologySignature? TopologySignature { get; init; }
public bool CreatedFromLegacyAffinityMask { get; init; }
public bool ContainsLogicalProcessorsBeyondLegacyMask { get; init; }
public bool HasMultipleProcessorGroups { get; init; }
public int ProcessorGroupCount { get; init; }
public int MaxGlobalLogicalProcessorIndex { get; init; } = -1;
public string SelectionReason { get; init; } = string.Empty;
}
public sealed class CpuTopologySnapshot
{
private readonly IReadOnlyDictionary<ProcessorRef, uint> cpuSetIdsByProcessor;
private readonly IReadOnlyDictionary<ProcessorRef, byte> efficiencyClassesByProcessor;
private readonly IReadOnlyDictionary<ProcessorRef, int> coreIndexesByProcessor;
private readonly IReadOnlyDictionary<ProcessorRef, int> numaNodeIndexesByProcessor;
private readonly IReadOnlyDictionary<ProcessorRef, int> lastLevelCacheIndexesByProcessor;
private readonly IReadOnlyDictionary<ProcessorRef, int> packageIndexesByProcessor;
private readonly IReadOnlyDictionary<ProcessorRef, IReadOnlyList<int>> smtSiblingGlobalIndexesByProcessor;
private readonly IReadOnlyDictionary<int, ulong> lastLevelCacheSizesByIndex;
private CpuTopologySnapshot(
IReadOnlyList<ProcessorRef> logicalProcessors,
IReadOnlyDictionary<ProcessorRef, uint> cpuSetIdsByProcessor,
IReadOnlyDictionary<ProcessorRef, byte> efficiencyClassesByProcessor,
IReadOnlyDictionary<ProcessorRef, int> coreIndexesByProcessor,
IReadOnlyDictionary<ProcessorRef, int> numaNodeIndexesByProcessor,
IReadOnlyDictionary<ProcessorRef, int> lastLevelCacheIndexesByProcessor,
IReadOnlyDictionary<ProcessorRef, int> packageIndexesByProcessor,
IReadOnlyDictionary<ProcessorRef, IReadOnlyList<int>> smtSiblingGlobalIndexesByProcessor,
CpuTopologySignature signature,
IReadOnlyList<int> reservedLogicalProcessorIndexes,
IReadOnlyDictionary<int, ulong> lastLevelCacheSizesByIndex)
{
this.LogicalProcessors = logicalProcessors;
this.cpuSetIdsByProcessor = cpuSetIdsByProcessor;
this.efficiencyClassesByProcessor = efficiencyClassesByProcessor;
this.coreIndexesByProcessor = coreIndexesByProcessor;
this.numaNodeIndexesByProcessor = numaNodeIndexesByProcessor;
this.lastLevelCacheIndexesByProcessor = lastLevelCacheIndexesByProcessor;
this.packageIndexesByProcessor = packageIndexesByProcessor;
this.smtSiblingGlobalIndexesByProcessor = smtSiblingGlobalIndexesByProcessor;
this.Signature = signature;
this.ReservedLogicalProcessorIndexes = reservedLogicalProcessorIndexes;
this.lastLevelCacheSizesByIndex = lastLevelCacheSizesByIndex;
}
public IReadOnlyList<ProcessorRef> LogicalProcessors { get; }
public CpuTopologySignature Signature { get; }
public IReadOnlyList<int> ReservedLogicalProcessorIndexes { get; }
public static CpuTopologySnapshot Create(
IEnumerable<ProcessorRef> logicalProcessors,
IReadOnlyDictionary<ProcessorRef, uint>? cpuSetIds = null,
IReadOnlyDictionary<ProcessorRef, byte>? efficiencyClasses = null,
CpuTopologySignature? signature = null,
IReadOnlyDictionary<ProcessorRef, int>? coreIndexes = null,
IReadOnlyDictionary<ProcessorRef, int>? numaNodeIndexes = null,
IReadOnlyDictionary<ProcessorRef, int>? lastLevelCacheIndexes = null,
IReadOnlyDictionary<ProcessorRef, int>? packageIndexes = null,
IReadOnlyDictionary<ProcessorRef, IReadOnlyList<int>>? smtSiblingGlobalIndexes = null,
IEnumerable<int>? reservedLogicalProcessorIndexes = null,
IReadOnlyDictionary<int, ulong>? lastLevelCacheSizes = null)
{
ArgumentNullException.ThrowIfNull(logicalProcessors);
var processors = logicalProcessors
.Distinct()
.OrderBy(processor => processor.GlobalIndex)
.ThenBy(processor => processor.Group)
.ThenBy(processor => processor.LogicalProcessorNumber)
.ToList();
var duplicatedGlobalIndexes = processors
.GroupBy(processor => processor.GlobalIndex)
.Where(group => group.Count() > 1)
.Select(group => group.Key)
.ToList();
if (duplicatedGlobalIndexes.Count > 0)
{
throw new ArgumentException(
$"GlobalIndex must be unique in a CPU topology snapshot. Duplicates: {string.Join(", ", duplicatedGlobalIndexes)}.",
nameof(logicalProcessors));
}
var processorSet = processors.ToHashSet();
var cpuSetMap = cpuSetIds?
.Where(kvp => processorSet.Contains(kvp.Key))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
?? new Dictionary<ProcessorRef, uint>();
var efficiencyClassMap = efficiencyClasses?
.Where(kvp => processorSet.Contains(kvp.Key))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
?? new Dictionary<ProcessorRef, byte>();
var coreIndexMap = FilterKnownProcessorMap(coreIndexes, processorSet);
var numaNodeIndexMap = FilterKnownProcessorMap(numaNodeIndexes, processorSet);
var lastLevelCacheIndexMap = FilterKnownProcessorMap(lastLevelCacheIndexes, processorSet);
var packageIndexMap = FilterKnownProcessorMap(packageIndexes, processorSet);
var knownGlobalIndexes = processors.Select(processor => processor.GlobalIndex).ToHashSet();
var smtSiblingMap = smtSiblingGlobalIndexes?
.Where(kvp => processorSet.Contains(kvp.Key))
.ToDictionary(
kvp => kvp.Key,
kvp => (IReadOnlyList<int>)kvp.Value
.Where(knownGlobalIndexes.Contains)
.Distinct()
.OrderBy(index => index)
.ToList())
?? new Dictionary<ProcessorRef, IReadOnlyList<int>>();
var resolvedSignature = signature ?? new CpuTopologySignature
{
LogicalProcessorCount = processors.Count,
PhysicalCoreCount = coreIndexMap.Count == 0
? processors.Count
: coreIndexMap.Values.Distinct().Count(),
ProcessorGroupCount = processors.Select(processor => processor.Group).Distinct().Count(),
NumaNodeCount = numaNodeIndexMap.Values.Distinct().Count(),
LastLevelCacheGroupCount = lastLevelCacheIndexMap.Values.Distinct().Count(),
PackageCount = packageIndexMap.Values.Distinct().Count(),
Source = "Snapshot",
};
return new CpuTopologySnapshot(
processors,
cpuSetMap,
efficiencyClassMap,
coreIndexMap,
numaNodeIndexMap,
lastLevelCacheIndexMap,
packageIndexMap,
smtSiblingMap,
resolvedSignature,
(reservedLogicalProcessorIndexes ?? [])
.Where(knownGlobalIndexes.Contains)
.Distinct()
.OrderBy(index => index)
.ToList(),
lastLevelCacheSizes?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value) ?? new Dictionary<int, ulong>());
}
public bool TryGetCpuSetId(ProcessorRef processor, out uint cpuSetId) =>
this.cpuSetIdsByProcessor.TryGetValue(processor, out cpuSetId);
public bool TryGetEfficiencyClass(ProcessorRef processor, out byte efficiencyClass) =>
this.efficiencyClassesByProcessor.TryGetValue(processor, out efficiencyClass);
public bool TryGetCoreIndex(ProcessorRef processor, out int coreIndex) =>
this.coreIndexesByProcessor.TryGetValue(processor, out coreIndex);
public bool TryGetNumaNodeIndex(ProcessorRef processor, out int numaNodeIndex) =>
this.numaNodeIndexesByProcessor.TryGetValue(processor, out numaNodeIndex);
public bool TryGetLastLevelCacheIndex(ProcessorRef processor, out int lastLevelCacheIndex) =>
this.lastLevelCacheIndexesByProcessor.TryGetValue(processor, out lastLevelCacheIndex);
public bool TryGetLastLevelCacheSize(int lastLevelCacheIndex, out ulong cacheSizeBytes) =>
this.lastLevelCacheSizesByIndex.TryGetValue(lastLevelCacheIndex, out cacheSizeBytes);
public bool TryGetPackageIndex(ProcessorRef processor, out int packageIndex) =>
this.packageIndexesByProcessor.TryGetValue(processor, out packageIndex);
public IReadOnlyList<int> GetSmtSiblingGlobalIndexes(ProcessorRef processor) =>
this.smtSiblingGlobalIndexesByProcessor.TryGetValue(processor, out var siblings)
? siblings
: [];
public byte? GetPerformanceEfficiencyClass()
{
if (this.efficiencyClassesByProcessor.Count == 0)
{
return null;
}
return this.efficiencyClassesByProcessor.Values.Max();
}
private static Dictionary<ProcessorRef, int> FilterKnownProcessorMap(
IReadOnlyDictionary<ProcessorRef, int>? source,
HashSet<ProcessorRef> processorSet)
{
return source?
.Where(kvp => processorSet.Contains(kvp.Key))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
?? new Dictionary<ProcessorRef, int>();
}
}
public sealed record CpuSelection
{
public List<uint> CpuSetIds { get; init; } = new();
public List<ProcessorRef> LogicalProcessors { get; init; } = new();
public List<int> GlobalLogicalProcessorIndexes { get; init; } = new();
public CpuSelectionMetadata Metadata { get; init; } = new();
public static CpuSelection FromProcessors(
IEnumerable<ProcessorRef> processors,
CpuTopologySnapshot topology,
string selectionReason = "")
{
ArgumentNullException.ThrowIfNull(processors);
ArgumentNullException.ThrowIfNull(topology);
var selectedProcessors = processors
.Distinct()
.OrderBy(processor => processor.GlobalIndex)
.ThenBy(processor => processor.Group)
.ThenBy(processor => processor.LogicalProcessorNumber)
.ToList();
var topologyProcessors = topology.LogicalProcessors.ToHashSet();
var missingProcessors = selectedProcessors
.Where(processor => !topologyProcessors.Contains(processor))
.ToList();
if (missingProcessors.Count > 0)
{
throw new ArgumentException(
$"CPU selection contains processor(s) not present in the topology: {string.Join(", ", missingProcessors)}.",
nameof(processors));
}
var cpuSetIds = selectedProcessors
.Select(processor => topology.TryGetCpuSetId(processor, out var cpuSetId) ? (uint?)cpuSetId : null)
.Where(cpuSetId => cpuSetId.HasValue)
.Select(cpuSetId => cpuSetId!.Value)
.Distinct()
.OrderBy(cpuSetId => cpuSetId)
.ToList();
return new CpuSelection
{
CpuSetIds = cpuSetIds,
LogicalProcessors = selectedProcessors,
GlobalLogicalProcessorIndexes = selectedProcessors
.Select(processor => processor.GlobalIndex)
.Distinct()
.OrderBy(index => index)
.ToList(),
Metadata = CreateMetadata(selectedProcessors, topology.Signature, createdFromLegacyAffinityMask: false, selectionReason),
};
}
public static CpuSelection FromLegacyAffinityMask(long mask, CpuTopologySnapshot topology)
{
ArgumentNullException.ThrowIfNull(topology);
var unsignedMask = unchecked((ulong)mask);
var selectedIndexes = new HashSet<int>();
for (var bit = 0; bit < 64; bit++)
{
if ((unsignedMask & (1UL << bit)) != 0)
{
selectedIndexes.Add(bit);
}
}
var selectedProcessors = topology.LogicalProcessors
.Where(processor => selectedIndexes.Contains(processor.GlobalIndex))
.ToList();
var selection = FromProcessors(selectedProcessors, topology, "Migrated from legacy affinity mask");
return selection with
{
Metadata = CreateMetadata(
selection.LogicalProcessors,
topology.Signature,
createdFromLegacyAffinityMask: true,
"Migrated from legacy affinity mask"),
};
}
public static long? ToLegacyAffinityMaskOrNull(CpuSelection selection)
{
ArgumentNullException.ThrowIfNull(selection);
if (selection.LogicalProcessors.Any(processor => processor.GlobalIndex >= 64))
{
return null;
}
if (selection.LogicalProcessors.Select(processor => processor.Group).Distinct().Count() > 1)
{
return null;
}
long mask = 0;
foreach (var processor in selection.LogicalProcessors)
{
if (processor.GlobalIndex < 0)
{
return null;
}
mask |= 1L << processor.GlobalIndex;
}
return mask;
}
private static CpuSelectionMetadata CreateMetadata(
IReadOnlyCollection<ProcessorRef> processors,
CpuTopologySignature signature,
bool createdFromLegacyAffinityMask,
string selectionReason)
{
var groups = processors.Select(processor => processor.Group).Distinct().ToList();
var maxGlobalIndex = processors.Count == 0
? -1
: processors.Max(processor => processor.GlobalIndex);
return new CpuSelectionMetadata
{
TopologySignature = signature,
CreatedFromLegacyAffinityMask = createdFromLegacyAffinityMask,
ContainsLogicalProcessorsBeyondLegacyMask = maxGlobalIndex >= 64,
HasMultipleProcessorGroups = groups.Count > 1,
ProcessorGroupCount = groups.Count,
MaxGlobalLogicalProcessorIndex = maxGlobalIndex,
SelectionReason = selectionReason,
};
}
}
}