diff --git a/Models/CpuSelection.cs b/Models/CpuSelection.cs index 0d1e78d..ce45f73 100644 --- a/Models/CpuSelection.cs +++ b/Models/CpuSelection.cs @@ -59,6 +59,7 @@ namespace ThreadPilot.Models private readonly IReadOnlyDictionary lastLevelCacheIndexesByProcessor; private readonly IReadOnlyDictionary packageIndexesByProcessor; private readonly IReadOnlyDictionary> smtSiblingGlobalIndexesByProcessor; + private readonly IReadOnlyDictionary lastLevelCacheSizesByIndex; private CpuTopologySnapshot( IReadOnlyList logicalProcessors, @@ -70,7 +71,8 @@ namespace ThreadPilot.Models IReadOnlyDictionary packageIndexesByProcessor, IReadOnlyDictionary> smtSiblingGlobalIndexesByProcessor, CpuTopologySignature signature, - IReadOnlyList reservedLogicalProcessorIndexes) + IReadOnlyList reservedLogicalProcessorIndexes, + IReadOnlyDictionary lastLevelCacheSizesByIndex) { this.LogicalProcessors = logicalProcessors; this.cpuSetIdsByProcessor = cpuSetIdsByProcessor; @@ -82,6 +84,7 @@ namespace ThreadPilot.Models this.smtSiblingGlobalIndexesByProcessor = smtSiblingGlobalIndexesByProcessor; this.Signature = signature; this.ReservedLogicalProcessorIndexes = reservedLogicalProcessorIndexes; + this.lastLevelCacheSizesByIndex = lastLevelCacheSizesByIndex; } public IReadOnlyList LogicalProcessors { get; } @@ -100,7 +103,8 @@ namespace ThreadPilot.Models IReadOnlyDictionary? lastLevelCacheIndexes = null, IReadOnlyDictionary? packageIndexes = null, IReadOnlyDictionary>? smtSiblingGlobalIndexes = null, - IEnumerable? reservedLogicalProcessorIndexes = null) + IEnumerable? reservedLogicalProcessorIndexes = null, + IReadOnlyDictionary? lastLevelCacheSizes = null) { ArgumentNullException.ThrowIfNull(logicalProcessors); @@ -177,7 +181,8 @@ namespace ThreadPilot.Models .Where(knownGlobalIndexes.Contains) .Distinct() .OrderBy(index => index) - .ToList()); + .ToList(), + lastLevelCacheSizes?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value) ?? new Dictionary()); } public bool TryGetCpuSetId(ProcessorRef processor, out uint cpuSetId) => @@ -195,6 +200,9 @@ namespace ThreadPilot.Models 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); diff --git a/Services/CpuTopologyService.cs b/Services/CpuTopologyService.cs index 2a44da2..2406135 100644 --- a/Services/CpuTopologyService.cs +++ b/Services/CpuTopologyService.cs @@ -14,6 +14,7 @@ namespace ThreadPilot.Services public class CpuTopologyService : ICpuTopologyService { private readonly ILogger logger; + private readonly ICpuTopologyProvider? topologyProvider; private readonly SemaphoreSlim detectSemaphore = new(1, 1); private CpuTopologyModel? currentTopology; private DateTime topologyCachedAtUtc = DateTime.MinValue; @@ -72,9 +73,10 @@ namespace ThreadPilot.Services IntPtr buffer, ref int returnedLength); - public CpuTopologyService(ILogger logger) + public CpuTopologyService(ILogger logger, ICpuTopologyProvider? topologyProvider = null) { this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); + this.topologyProvider = topologyProvider; } public async Task DetectTopologyAsync() @@ -290,7 +292,7 @@ namespace ThreadPilot.Services } this.ApplyHyperThreadingFromPhysicalMapping(topology); - this.ApplyCoreTypeFromEfficiencyClass(topology, discovered); + ApplyCoreTypeFromEfficiencyClass(topology, discovered); this.logger.LogInformation( "Detected CPU topology via GetLogicalProcessorInformationEx: {LogicalCpuCount} logical CPUs, {PhysicalCpuCount} physical CPUs", @@ -345,13 +347,13 @@ namespace ThreadPilot.Services } } - private void ApplyCoreTypeFromEfficiencyClass( + internal static void ApplyCoreTypeFromEfficiencyClass( CpuTopologyModel topology, List<(int PhysicalCpuId, int LogicalCpuId, byte EfficiencyClass)> discovered) { var byPhysical = discovered .GroupBy(d => d.PhysicalCpuId) - .Select(g => new { PhysicalCpuId = g.Key, EfficiencyClass = g.Min(x => x.EfficiencyClass) }) + .Select(g => new { PhysicalCpuId = g.Key, EfficiencyClass = g.Max(x => x.EfficiencyClass) }) .ToList(); var classes = byPhysical @@ -365,7 +367,8 @@ namespace ThreadPilot.Services return; } - byte performanceClass = classes.Min(); + // A higher EfficiencyClass is the more performant core (PROCESSOR_RELATIONSHIP docs). + byte performanceClass = classes.Max(); foreach (var logicalCpu in topology.LogicalCores) { byte classValue = byPhysical.First(x => x.PhysicalCpuId == logicalCpu.PhysicalCoreId).EfficiencyClass; @@ -525,6 +528,12 @@ namespace ThreadPilot.Services { if (topology.CpuBrand.Contains("AMD", StringComparison.OrdinalIgnoreCase)) { + if (await this.TryAssignCcdsFromL3GroupsAsync(topology)) + { + return; + } + + // Fallback estimate, display only: Game Boost never uses it (it reads CpuTopologySnapshot). // AMD CCD detection - improved heuristic // Only assign CCD if we actually have multiple CCDs var totalPhysicalCores = topology.TotalPhysicalCores; @@ -562,6 +571,48 @@ namespace ThreadPilot.Services } } + // Each Zen CCD (CCX on Zen 2) has its own L3, so the real L3 groups replace the 8-cores-per-CCD guess, + // which split 6+6 parts such as the 7900X3D into 8+4. + internal async Task TryAssignCcdsFromL3GroupsAsync(CpuTopologyModel topology) + { + if (this.topologyProvider == null) + { + return false; + } + + var snapshot = await this.topologyProvider.GetTopologySnapshotAsync(); + var l3ByLogicalCore = new Dictionary(); + foreach (var processor in snapshot.LogicalProcessors) + { + if (snapshot.TryGetLastLevelCacheIndex(processor, out var l3Index)) + { + l3ByLogicalCore[processor.GlobalIndex] = l3Index; + } + } + + if (topology.LogicalCores.Count == 0 || topology.LogicalCores.Any(core => !l3ByLogicalCore.ContainsKey(core.LogicalCoreId))) + { + return false; + } + + // Number the groups by their lowest CPU, so CCD 0 is always the one holding CPU 0. + var ccdByL3 = topology.LogicalCores + .GroupBy(core => l3ByLogicalCore[core.LogicalCoreId]) + .OrderBy(group => group.Min(core => core.LogicalCoreId)) + .Select((group, ccdId) => (group.Key, ccdId)) + .ToDictionary(item => item.Key, item => item.ccdId); + var hasMultipleL3Groups = ccdByL3.Count > 1; + + foreach (var core in topology.LogicalCores) + { + core.CcdId = hasMultipleL3Groups ? ccdByL3[l3ByLogicalCore[core.LogicalCoreId]] : null; + core.CoreType = CpuCoreType.Zen3; // Default assumption, as in the estimate below + } + + this.logger.LogInformation("Detected AMD L3 groups from Windows topology: {L3GroupCount}", ccdByL3.Count); + return true; + } + private void DetectHyperThreading(CpuTopologyModel topology) { try diff --git a/Services/WindowsCpuTopologyNativeLayout.cs b/Services/WindowsCpuTopologyNativeLayout.cs index 6717520..55dd48f 100644 --- a/Services/WindowsCpuTopologyNativeLayout.cs +++ b/Services/WindowsCpuTopologyNativeLayout.cs @@ -81,9 +81,13 @@ namespace ThreadPilot.Services return ReadProcessorsFromGroupMasks(relationshipPtr, ProcessorGroupMaskOffset, groupCount).ToList(); } - public static bool TryReadL3CacheProcessors(IntPtr relationshipPtr, out IReadOnlyList processors) + public static bool TryReadL3CacheProcessors(IntPtr relationshipPtr, out IReadOnlyList processors) => + TryReadL3CacheProcessors(relationshipPtr, out processors, out _); + + public static bool TryReadL3CacheProcessors(IntPtr relationshipPtr, out IReadOnlyList processors, out uint cacheSizeBytes) { var cache = Marshal.PtrToStructure(relationshipPtr); + cacheSizeBytes = cache.CacheSize; if (cache.Level != 3 || cache.GroupCount == 0) { processors = []; diff --git a/Services/WindowsCpuTopologyProvider.cs b/Services/WindowsCpuTopologyProvider.cs index 6d0c70e..d248424 100644 --- a/Services/WindowsCpuTopologyProvider.cs +++ b/Services/WindowsCpuTopologyProvider.cs @@ -91,6 +91,7 @@ namespace ThreadPilot.Services var coreIndexes = new Dictionary(); var numaNodeIndexes = new Dictionary(); var lastLevelCacheIndexes = new Dictionary(); + var lastLevelCacheSizes = new Dictionary(); var packageIndexes = new Dictionary(); var smtSiblingGlobalIndexes = new Dictionary>(); var reservedLogicalProcessorIndexes = new HashSet(); @@ -111,6 +112,7 @@ namespace ThreadPilot.Services coreIndexes, numaNodeIndexes, lastLevelCacheIndexes, + lastLevelCacheSizes, packageIndexes, smtSiblingGlobalIndexes, cancellationToken); @@ -159,7 +161,8 @@ namespace ThreadPilot.Services lastLevelCacheIndexes, packageIndexes, smtSiblingGlobalIndexes, - reservedLogicalProcessorIndexes); + reservedLogicalProcessorIndexes, + lastLevelCacheSizes); } private void ReadCpuSetInformation( @@ -236,6 +239,7 @@ namespace ThreadPilot.Services IDictionary coreIndexes, IDictionary numaNodeIndexes, IDictionary lastLevelCacheIndexes, + IDictionary lastLevelCacheSizes, IDictionary packageIndexes, IDictionary> smtSiblingGlobalIndexes, CancellationToken cancellationToken) @@ -296,8 +300,9 @@ namespace ThreadPilot.Services packageIndexes); break; case LogicalProcessorRelationship.RelationCache: - if (TryReadL3CacheProcessors(itemPtr, out var cacheProcessors)) + if (TryReadL3CacheProcessors(itemPtr, out var cacheProcessors, out var cacheSizeBytes)) { + lastLevelCacheSizes[lastLevelCacheIndex] = cacheSizeBytes; foreach (var processor in cacheProcessors) { logicalProcessors.Add(processor); @@ -365,9 +370,9 @@ namespace ThreadPilot.Services } } - private static bool TryReadL3CacheProcessors(IntPtr itemPtr, out IReadOnlyList processors) + private static bool TryReadL3CacheProcessors(IntPtr itemPtr, out IReadOnlyList processors, out uint cacheSizeBytes) { - return WindowsCpuTopologyNativeLayout.TryReadL3CacheProcessors(IntPtr.Add(itemPtr, 8), out processors); + return WindowsCpuTopologyNativeLayout.TryReadL3CacheProcessors(IntPtr.Add(itemPtr, 8), out processors, out cacheSizeBytes); } private void ReadNumaNodeRelationship( diff --git a/Tests/ThreadPilot.Core.Tests/CpuTopologyServiceTopologyFixTests.cs b/Tests/ThreadPilot.Core.Tests/CpuTopologyServiceTopologyFixTests.cs new file mode 100644 index 0000000..1e9eccc --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/CpuTopologyServiceTopologyFixTests.cs @@ -0,0 +1,78 @@ +namespace ThreadPilot.Core.Tests +{ + using Microsoft.Extensions.Logging.Abstractions; + using ThreadPilot.Models; + using ThreadPilot.Services; + + public sealed class CpuTopologyServiceTopologyFixTests + { + [Fact] + public void EfficiencyClass_HigherClassIsThePerformanceCore() + { + var topology = new CpuTopologyModel(); + for (var i = 0; i < 4; i++) + { + topology.LogicalCores.Add(new CpuCoreModel { LogicalCoreId = i, PhysicalCoreId = i }); + } + + CpuTopologyService.ApplyCoreTypeFromEfficiencyClass( + topology, + [(0, 0, (byte)1), (1, 1, (byte)1), (2, 2, (byte)0), (3, 3, (byte)0)]); + + Assert.Equal( + [CpuCoreType.PerformanceCore, CpuCoreType.PerformanceCore, CpuCoreType.EfficiencyCore, CpuCoreType.EfficiencyCore], + topology.LogicalCores.Select(core => core.CoreType)); + } + + [Fact] + public async Task AmdCcds_ComeFromRealL3Groups_SixPlusSix() + { + var snapshot = TopologyFixtures.Amd([6, 6], cacheSizes: null); + var service = new CpuTopologyService(NullLogger.Instance, new FixedTopologyProvider(snapshot)); + var topology = CreateLegacyTopology(24); + + Assert.True(await service.TryAssignCcdsFromL3GroupsAsync(topology)); + + Assert.Equal(12, topology.LogicalCores.Count(core => core.CcdId == 0)); + Assert.Equal(12, topology.LogicalCores.Count(core => core.CcdId == 1)); + } + + [Fact] + public async Task AmdCcds_SingleL3_HasNoCcdIds() + { + var snapshot = TopologyFixtures.Amd([8], cacheSizes: null); + var service = new CpuTopologyService(NullLogger.Instance, new FixedTopologyProvider(snapshot)); + var topology = CreateLegacyTopology(16); + + Assert.True(await service.TryAssignCcdsFromL3GroupsAsync(topology)); + + Assert.All(topology.LogicalCores, core => Assert.Null(core.CcdId)); + } + + [Fact] + public async Task AmdCcds_WithoutL3Data_FallsBackToEstimate() + { + var snapshot = TopologyFixtures.Amd([8, 8], cacheSizes: null, withL3Indexes: false); + var service = new CpuTopologyService(NullLogger.Instance, new FixedTopologyProvider(snapshot)); + + Assert.False(await service.TryAssignCcdsFromL3GroupsAsync(CreateLegacyTopology(32))); + } + + private static CpuTopologyModel CreateLegacyTopology(int logicalCount) + { + var topology = new CpuTopologyModel { CpuBrand = "AMD Ryzen" }; + for (var i = 0; i < logicalCount; i++) + { + topology.LogicalCores.Add(new CpuCoreModel { LogicalCoreId = i, PhysicalCoreId = i / 2 }); + } + + return topology; + } + + private sealed class FixedTopologyProvider(CpuTopologySnapshot snapshot) : ICpuTopologyProvider + { + public Task GetTopologySnapshotAsync(CancellationToken cancellationToken = default) => + Task.FromResult(snapshot); + } + } +} diff --git a/Tests/ThreadPilot.Core.Tests/TopologyFixtures.cs b/Tests/ThreadPilot.Core.Tests/TopologyFixtures.cs new file mode 100644 index 0000000..1307c9f --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/TopologyFixtures.cs @@ -0,0 +1,70 @@ +namespace ThreadPilot.Core.Tests +{ + using ThreadPilot.Models; + + internal static class TopologyFixtures + { + /// AMD with SMT: each entry of coresPerL3 is one L3 group (CCD), two logical CPUs per core. + public static CpuTopologySnapshot Amd( + int[] coresPerL3, + ulong[]? cacheSizes, + bool withL3Indexes = true, + bool withCpuSetIds = true, + int[]? reserved = null) + { + var processors = new List(); + var l3Indexes = new Dictionary(); + var coreIndexes = new Dictionary(); + var core = 0; + for (var l3 = 0; l3 < coresPerL3.Length; l3++) + { + for (var c = 0; c < coresPerL3[l3]; c++, core++) + { + for (var thread = 0; thread < 2; thread++) + { + var index = (core * 2) + thread; + var processor = new ProcessorRef(0, (byte)index, index); + processors.Add(processor); + coreIndexes[processor] = core; + l3Indexes[processor] = l3; + } + } + } + + return CpuTopologySnapshot.Create( + processors, + cpuSetIds: withCpuSetIds ? processors.ToDictionary(p => p, p => (uint)(256 + p.GlobalIndex)) : null, + coreIndexes: coreIndexes, + lastLevelCacheIndexes: withL3Indexes ? l3Indexes : null, + reservedLogicalProcessorIndexes: reserved, + lastLevelCacheSizes: cacheSizes?.Select((size, index) => (size, index)).ToDictionary(x => x.index, x => x.size)); + } + + /// Intel hybrid: P-cores with HT first (EfficiencyClass 1), then single-thread E-cores (class 0). + public static CpuTopologySnapshot IntelHybrid(int performanceCores, int efficiencyCores, bool withL3Indexes = true) + { + var processors = new List(); + var classes = new Dictionary(); + var coreIndexes = new Dictionary(); + var index = 0; + for (var core = 0; core < performanceCores + efficiencyCores; core++) + { + var isPerformance = core < performanceCores; + for (var thread = 0; thread < (isPerformance ? 2 : 1); thread++, index++) + { + var processor = new ProcessorRef(0, (byte)index, index); + processors.Add(processor); + classes[processor] = isPerformance ? (byte)1 : (byte)0; + coreIndexes[processor] = core; + } + } + + return CpuTopologySnapshot.Create( + processors, + cpuSetIds: processors.ToDictionary(p => p, p => (uint)(256 + p.GlobalIndex)), + efficiencyClasses: classes, + coreIndexes: coreIndexes, + lastLevelCacheIndexes: withL3Indexes ? processors.ToDictionary(p => p, _ => 0) : null); + } + } +}