406352f38e
Three loose ends from the 1.7.3 review. Custom masks were flagged and left alone on a CPU change. Growing one is not a judgement call - the CPUs that appeared were not part of a selection made before they existed - and shrinking is safe while something is still selected, so both now happen automatically. Two cases stay with the user: a mask that would be left selecting nothing, and a mask a power plan association is using, where a silent resize would change what that automation does without saying so. Those are named in the Masks tab instead. A different CPU with the same thread count is also caught now, by comparing the topology signature stored in the mask's selection against the running machine. That signature is what CpuSelectionMigrationMetadata.ReviewRequired was being computed from in four places and read from in none; this is the first thing to actually use it. The flag itself is still unread, and is now redundant here. A rule's cores could only be changed from the Process tab, which needs the process to be running - so the cores of a rule for a game you are not currently playing were the one thing about it you could not edit. The saved-rules editor now shows them and can set them from any saved CPU mask, through the same migration path the Process tab uses. The per-core picker stays where it is rather than being duplicated. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1007 lines
40 KiB
C#
1007 lines
40 KiB
C#
namespace ThreadPilot.Services
|
|
{
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Collections.ObjectModel;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using System.Windows;
|
|
using Microsoft.Extensions.Logging;
|
|
using ThreadPilot.Models;
|
|
|
|
public class CoreMaskService : ICoreMaskService
|
|
{
|
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
|
{
|
|
WriteIndented = true,
|
|
PropertyNameCaseInsensitive = true,
|
|
ReadCommentHandling = JsonCommentHandling.Skip,
|
|
AllowTrailingCommas = true,
|
|
};
|
|
|
|
private readonly ILogger<CoreMaskService> logger;
|
|
private readonly ICpuTopologyService cpuTopologyService;
|
|
private readonly IServiceProvider serviceProvider;
|
|
private readonly ICpuTopologyProvider? cpuTopologyProvider;
|
|
private readonly CpuSelectionMigrationService cpuSelectionMigrationService;
|
|
private readonly string masksFilePath;
|
|
private bool initialized = false;
|
|
private int topologyBackfillInProgress;
|
|
|
|
// Tracks which masks are actively applied to processes
|
|
private readonly Dictionary<int, string> activeProcessMasks = new(); // ProcessId -> MaskId
|
|
|
|
public ObservableCollection<CoreMask> AvailableMasks { get; private set; } = new();
|
|
|
|
public IReadOnlyList<string> MasksNeedingTopologyReview { get; private set; } = [];
|
|
|
|
public CoreMask? DefaultMask => this.AvailableMasks.FirstOrDefault(m => m.IsDefault);
|
|
|
|
private const string ALLCORESMASKNAME = "All Cores";
|
|
private const string NOCORE0MASKNAME = "No Core 0";
|
|
|
|
public CoreMaskService(
|
|
ILogger<CoreMaskService> logger,
|
|
ICpuTopologyService cpuTopologyService,
|
|
IServiceProvider serviceProvider,
|
|
ICpuTopologyProvider? cpuTopologyProvider = null,
|
|
CpuSelectionMigrationService? cpuSelectionMigrationService = null,
|
|
string? masksFilePath = null)
|
|
{
|
|
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
this.cpuTopologyService = cpuTopologyService ?? throw new ArgumentNullException(nameof(cpuTopologyService));
|
|
this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
|
|
this.cpuTopologyProvider = cpuTopologyProvider;
|
|
this.cpuSelectionMigrationService = cpuSelectionMigrationService ?? new CpuSelectionMigrationService();
|
|
|
|
if (string.IsNullOrWhiteSpace(masksFilePath))
|
|
{
|
|
StoragePaths.EnsureAppDataDirectories();
|
|
this.masksFilePath = StoragePaths.CoreMasksFilePath;
|
|
}
|
|
else
|
|
{
|
|
Directory.CreateDirectory(Path.GetDirectoryName(masksFilePath)!);
|
|
this.masksFilePath = masksFilePath;
|
|
}
|
|
|
|
this.cpuTopologyService.TopologyDetected += this.OnTopologyDetected;
|
|
}
|
|
|
|
public async Task InitializeAsync()
|
|
{
|
|
if (this.initialized)
|
|
{
|
|
return;
|
|
}
|
|
|
|
this.logger.LogInformation("Initializing CoreMaskService...");
|
|
|
|
await this.LoadMasksAsync();
|
|
|
|
if (this.AvailableMasks.Count == 0)
|
|
{
|
|
this.logger.LogInformation("No masks found, creating defaults...");
|
|
}
|
|
|
|
if (await this.BackfillBuiltInDefaultMasksAsync())
|
|
{
|
|
await this.SaveMasksAsync();
|
|
}
|
|
|
|
this.initialized = true;
|
|
this.logger.LogInformation("CoreMaskService initialized with {Count} masks", this.AvailableMasks.Count);
|
|
}
|
|
|
|
private void OnTopologyDetected(object? sender, CpuTopologyDetectedEventArgs e)
|
|
{
|
|
if (!this.initialized || !e.DetectionSuccessful)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var dispatcher = Application.Current?.Dispatcher;
|
|
if (dispatcher != null)
|
|
{
|
|
_ = dispatcher.InvokeAsync(async () => await this.BackfillBuiltInDefaultMasksAndSaveAsync());
|
|
return;
|
|
}
|
|
|
|
_ = Task.Run(this.BackfillBuiltInDefaultMasksAndSaveAsync);
|
|
}
|
|
|
|
private async Task BackfillBuiltInDefaultMasksAndSaveAsync()
|
|
{
|
|
if (Interlocked.Exchange(ref this.topologyBackfillInProgress, 1) != 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
if (await this.BackfillBuiltInDefaultMasksAsync())
|
|
{
|
|
await this.SaveMasksAsync();
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
Interlocked.Exchange(ref this.topologyBackfillInProgress, 0);
|
|
}
|
|
}
|
|
|
|
public async Task<CoreMask> CreateMaskAsync(string name, string description, IEnumerable<bool> boolMask)
|
|
{
|
|
var mask = new CoreMask
|
|
{
|
|
Name = name,
|
|
Description = description,
|
|
CreatedAt = DateTime.UtcNow,
|
|
UpdatedAt = DateTime.UtcNow,
|
|
};
|
|
|
|
foreach (var bit in boolMask)
|
|
{
|
|
mask.BoolMask.Add(bit);
|
|
}
|
|
|
|
this.AvailableMasks.Add(mask);
|
|
await this.SaveMasksAsync();
|
|
|
|
this.logger.LogInformation(
|
|
"Created new mask '{Name}' with {Count} cores selected",
|
|
name, mask.SelectedCoreCount);
|
|
|
|
return mask;
|
|
}
|
|
|
|
public async Task UpdateMaskAsync(CoreMask mask)
|
|
{
|
|
if (mask == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(mask));
|
|
}
|
|
|
|
var existing = this.GetMaskById(mask.Id);
|
|
if (existing == null)
|
|
{
|
|
this.logger.LogWarning("Cannot update mask {Id}: not found", mask.Id);
|
|
return;
|
|
}
|
|
|
|
mask.UpdatedAt = DateTime.UtcNow;
|
|
await this.SaveMasksAsync();
|
|
|
|
this.logger.LogInformation("Updated mask '{Name}'", mask.Name);
|
|
}
|
|
|
|
public async Task DeleteMaskAsync(string maskId)
|
|
{
|
|
var mask = this.GetMaskById(maskId);
|
|
if (mask == null)
|
|
{
|
|
this.logger.LogWarning("Cannot delete mask {Id}: not found", maskId);
|
|
return;
|
|
}
|
|
|
|
// Cannot delete the "All Cores" baseline mask
|
|
if (mask.Name == ALLCORESMASKNAME)
|
|
{
|
|
this.logger.LogWarning("Cannot delete 'All Cores' baseline mask");
|
|
throw new InvalidOperationException("Cannot delete the 'All Cores' baseline mask - it is required as the default fallback");
|
|
}
|
|
|
|
// Check if mask is actively applied to running processes
|
|
if (await this.IsMaskActivelyAppliedAsync(maskId))
|
|
{
|
|
this.logger.LogWarning("Cannot delete mask '{Name}': it is actively applied to running processes", mask.Name);
|
|
throw new InvalidOperationException($"Cannot delete mask '{mask.Name}' - it is currently applied to running processes. Please change the mask on those processes first.");
|
|
}
|
|
|
|
this.AvailableMasks.Remove(mask);
|
|
await this.SaveMasksAsync();
|
|
|
|
this.logger.LogInformation("Deleted mask '{Name}'", mask.Name);
|
|
}
|
|
|
|
public CoreMask? GetMaskById(string maskId)
|
|
{
|
|
return this.AvailableMasks.FirstOrDefault(m => m.Id == maskId);
|
|
}
|
|
|
|
public CoreMask? GetMaskByName(string name)
|
|
{
|
|
return this.AvailableMasks.FirstOrDefault(m =>
|
|
m.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
|
}
|
|
|
|
public async Task SaveMasksAsync()
|
|
{
|
|
try
|
|
{
|
|
await this.ApplyCpuSelectionMigrationAsync().ConfigureAwait(false);
|
|
|
|
var data = this.AvailableMasks.Select(m => new
|
|
{
|
|
id = m.Id,
|
|
name = m.Name,
|
|
description = m.Description,
|
|
boolMask = m.BoolMask.ToList(),
|
|
profileSchemaVersion = m.ProfileSchemaVersion,
|
|
cpuSelection = m.CpuSelection,
|
|
cpuSelectionMigration = m.CpuSelectionMigration,
|
|
isDefault = m.IsDefault,
|
|
isEnabled = m.IsEnabled,
|
|
createdAt = m.CreatedAt,
|
|
updatedAt = m.UpdatedAt,
|
|
}).ToList();
|
|
|
|
var json = JsonSerializer.Serialize(data, JsonOptions);
|
|
|
|
await AtomicFileWriter.WriteAllTextAsync(this.masksFilePath, json, Encoding.UTF8);
|
|
this.logger.LogDebug("Saved {Count} masks to {Path}", this.AvailableMasks.Count, this.masksFilePath);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogError(ex, "Failed to save masks to {Path}", this.masksFilePath);
|
|
throw;
|
|
}
|
|
}
|
|
|
|
public async Task LoadMasksAsync()
|
|
{
|
|
try
|
|
{
|
|
if (!File.Exists(this.masksFilePath))
|
|
{
|
|
this.logger.LogInformation("Masks file not found at {Path}, will create defaults", this.masksFilePath);
|
|
return;
|
|
}
|
|
|
|
var json = await File.ReadAllTextAsync(this.masksFilePath);
|
|
var data = JsonSerializer.Deserialize<List<JsonElement>>(json, JsonOptions);
|
|
|
|
if (data == null)
|
|
{
|
|
this.logger.LogWarning("Failed to deserialize masks from {Path}", this.masksFilePath);
|
|
return;
|
|
}
|
|
|
|
this.AvailableMasks.Clear();
|
|
|
|
foreach (var item in data)
|
|
{
|
|
try
|
|
{
|
|
var mask = new CoreMask
|
|
{
|
|
Id = item.GetProperty("id").GetString() ?? Guid.NewGuid().ToString(),
|
|
Name = item.GetProperty("name").GetString() ?? "Unnamed",
|
|
Description = item.GetProperty("description").GetString() ?? string.Empty,
|
|
ProfileSchemaVersion = item.TryGetProperty("profileSchemaVersion", out var schemaVersion)
|
|
? schemaVersion.GetInt32()
|
|
: CpuAffinityProfileSchemaVersions.Legacy,
|
|
IsDefault = item.GetProperty("isDefault").GetBoolean(),
|
|
IsEnabled = item.GetProperty("isEnabled").GetBoolean(),
|
|
CreatedAt = item.GetProperty("createdAt").GetDateTime(),
|
|
UpdatedAt = item.GetProperty("updatedAt").GetDateTime(),
|
|
};
|
|
|
|
var boolMask = item.GetProperty("boolMask");
|
|
foreach (var bit in boolMask.EnumerateArray())
|
|
{
|
|
mask.BoolMask.Add(bit.GetBoolean());
|
|
}
|
|
|
|
if (item.TryGetProperty("cpuSelection", out var cpuSelectionElement) &&
|
|
cpuSelectionElement.ValueKind != JsonValueKind.Null)
|
|
{
|
|
mask.CpuSelection = cpuSelectionElement.Deserialize<CpuSelection>(JsonOptions);
|
|
}
|
|
|
|
if (item.TryGetProperty("cpuSelectionMigration", out var migrationElement) &&
|
|
migrationElement.ValueKind != JsonValueKind.Null)
|
|
{
|
|
mask.CpuSelectionMigration = migrationElement.Deserialize<CpuSelectionMigrationMetadata>(JsonOptions);
|
|
}
|
|
|
|
this.AvailableMasks.Add(mask);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogWarning(ex, "Failed to load individual mask, skipping");
|
|
}
|
|
}
|
|
|
|
await this.ApplyCpuSelectionMigrationAsync().ConfigureAwait(false);
|
|
this.logger.LogInformation("Loaded {Count} masks from {Path}", this.AvailableMasks.Count, this.masksFilePath);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogError(ex, "Failed to load masks from {Path}", this.masksFilePath);
|
|
}
|
|
}
|
|
|
|
public async Task<bool> IsMaskReferencedByProfilesAsync(string maskId)
|
|
{
|
|
try
|
|
{
|
|
var profileNames = await this.GetProfilesReferencingMaskAsync(maskId);
|
|
return profileNames.Any();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogError(ex, "Failed to check if mask {MaskId} is referenced by profiles", maskId);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private async Task ApplyCpuSelectionMigrationAsync()
|
|
{
|
|
var topology = await this.TryGetTopologySnapshotAsync().ConfigureAwait(false);
|
|
if (topology == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
foreach (var mask in this.AvailableMasks)
|
|
{
|
|
if (mask.CpuSelection != null)
|
|
{
|
|
mask.ProfileSchemaVersion = CpuAffinityProfileSchemaVersions.CpuSelection;
|
|
continue;
|
|
}
|
|
|
|
if (mask.BoolMask.Count == 0)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var migrated = this.cpuSelectionMigrationService.MigrateFromLegacyCoreMask(
|
|
mask.BoolMask.ToList(),
|
|
topology);
|
|
mask.ProfileSchemaVersion = CpuAffinityProfileSchemaVersions.CpuSelection;
|
|
mask.CpuSelection = migrated.Selection;
|
|
mask.CpuSelectionMigration = migrated.Metadata;
|
|
}
|
|
}
|
|
|
|
private async Task<CpuTopologySnapshot?> TryGetTopologySnapshotAsync()
|
|
{
|
|
if (this.cpuTopologyProvider == null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
try
|
|
{
|
|
return await this.cpuTopologyProvider.GetTopologySnapshotAsync().ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogWarning(ex, "Failed to get CPU topology snapshot for core mask CpuSelection migration");
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public async Task<bool> IsMaskActivelyAppliedAsync(string maskId)
|
|
{
|
|
try
|
|
{
|
|
// Check our tracking dictionary for active process masks
|
|
var isActive = this.activeProcessMasks.ContainsValue(maskId);
|
|
|
|
if (isActive)
|
|
{
|
|
// Verify processes are still running
|
|
var deadProcesses = new List<int>();
|
|
foreach (var kvp in this.activeProcessMasks.Where(x => x.Value == maskId))
|
|
{
|
|
try
|
|
{
|
|
Process.GetProcessById(kvp.Key);
|
|
}
|
|
catch (ArgumentException)
|
|
{
|
|
// Process no longer exists
|
|
deadProcesses.Add(kvp.Key);
|
|
}
|
|
}
|
|
|
|
// Clean up dead processes
|
|
foreach (var pid in deadProcesses)
|
|
{
|
|
this.activeProcessMasks.Remove(pid);
|
|
}
|
|
|
|
// Re-check after cleanup
|
|
isActive = this.activeProcessMasks.ContainsValue(maskId);
|
|
}
|
|
|
|
await Task.CompletedTask;
|
|
return isActive;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogError(ex, "Failed to check if mask {MaskId} is actively applied", maskId);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public async Task<IEnumerable<string>> GetProfilesReferencingMaskAsync(string maskId)
|
|
{
|
|
var referencingProfiles = new List<string>();
|
|
|
|
try
|
|
{
|
|
// Get the association service to check profiles
|
|
var associationService = this.serviceProvider.GetService(typeof(IProcessPowerPlanAssociationService)) as IProcessPowerPlanAssociationService;
|
|
if (associationService != null)
|
|
{
|
|
var associations = await associationService.GetAssociationsAsync();
|
|
foreach (var association in associations)
|
|
{
|
|
if (association.CoreMaskId == maskId)
|
|
{
|
|
var profileName = !string.IsNullOrEmpty(association.Description)
|
|
? association.Description
|
|
: association.ExecutableName;
|
|
referencingProfiles.Add(profileName);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogError(ex, "Failed to get profiles referencing mask {MaskId}", maskId);
|
|
}
|
|
|
|
return referencingProfiles;
|
|
}
|
|
|
|
public async Task UpdateProfilesToDefaultMaskAsync(string maskId)
|
|
{
|
|
try
|
|
{
|
|
var allCoresMask = this.GetAllCoresMask();
|
|
if (allCoresMask == null)
|
|
{
|
|
this.logger.LogError("Cannot update profiles: 'All Cores' mask not found");
|
|
return;
|
|
}
|
|
|
|
var associationService = this.serviceProvider.GetService(typeof(IProcessPowerPlanAssociationService)) as IProcessPowerPlanAssociationService;
|
|
if (associationService != null)
|
|
{
|
|
var associations = await associationService.GetAssociationsAsync();
|
|
foreach (var association in associations)
|
|
{
|
|
if (association.CoreMaskId == maskId)
|
|
{
|
|
association.CoreMaskId = allCoresMask.Id;
|
|
association.CoreMaskName = allCoresMask.Name;
|
|
await associationService.UpdateAssociationAsync(association);
|
|
this.logger.LogInformation("Updated association '{Name}' to use 'All Cores' mask", association.ExecutableName);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogError(ex, "Failed to update profiles to default mask");
|
|
}
|
|
}
|
|
|
|
public CoreMask? GetAllCoresMask()
|
|
{
|
|
return this.AvailableMasks.FirstOrDefault(m => m.Name == ALLCORESMASKNAME);
|
|
}
|
|
|
|
public void RegisterMaskApplication(int processId, string maskId)
|
|
{
|
|
this.activeProcessMasks[processId] = maskId;
|
|
this.logger.LogDebug("Registered mask {MaskId} for process {ProcessId}", maskId, processId);
|
|
}
|
|
|
|
public void UnregisterMaskApplication(int processId)
|
|
{
|
|
if (this.activeProcessMasks.Remove(processId))
|
|
{
|
|
this.logger.LogDebug("Unregistered mask for process {ProcessId}", processId);
|
|
}
|
|
}
|
|
|
|
public IEnumerable<int> GetProcessesWithMask(string maskId)
|
|
{
|
|
return this.activeProcessMasks.Where(x => x.Value == maskId).Select(x => x.Key);
|
|
}
|
|
|
|
public async Task CreateDefaultMasksAsync()
|
|
{
|
|
bool changed = await this.BackfillBuiltInDefaultMasksAsync();
|
|
if (changed)
|
|
{
|
|
await this.SaveMasksAsync();
|
|
}
|
|
|
|
this.logger.LogInformation(
|
|
"Created or backfilled default masks with topology-aware presets; total masks: {Count}",
|
|
this.AvailableMasks.Count);
|
|
}
|
|
|
|
private async Task<bool> BackfillBuiltInDefaultMasksAsync()
|
|
{
|
|
var topology = this.cpuTopologyService.CurrentTopology;
|
|
int coreCount = this.ResolveLogicalCoreCount(topology);
|
|
bool topologyConfident = topology?.TopologyDetectionSuccessful == true;
|
|
bool hasHyperThreading = topology?.HasHyperThreading == true;
|
|
bool canCreateNoSmtVariants = topologyConfident && hasHyperThreading;
|
|
bool changed = false;
|
|
|
|
// Only rewrite already-stored masks when the core count came from a successful
|
|
// topology detection. Environment.ProcessorCount (the ResolveLogicalCoreCount
|
|
// fallback) can under-report under affinity/job-object limits, and resizing masks
|
|
// to a wrong length would silently redefine them.
|
|
bool canReconcileLengths = topologyConfident && coreCount > 0;
|
|
|
|
// Collect all default masks with their "no SMT" variants
|
|
var defaultMasks = new List<(string name, List<bool> boolMask, string description)>();
|
|
|
|
// Determine CPU manufacturer for naming convention
|
|
bool isIntel = topology?.CpuBrand?.Contains("Intel", StringComparison.OrdinalIgnoreCase) == true;
|
|
bool isAmd = topology?.CpuBrand?.Contains("AMD", StringComparison.OrdinalIgnoreCase) == true;
|
|
string noSmtSuffix = isIntel ? " no HT" : " no SMT";
|
|
|
|
// 1. Always add "All Cores" baseline mask (IsDefault = true, cannot be deleted)
|
|
var allCoresMask = new CoreMask
|
|
{
|
|
Name = ALLCORESMASKNAME,
|
|
Description = "Use all available CPU cores - baseline mask",
|
|
IsDefault = true,
|
|
IsEnabled = true,
|
|
};
|
|
for (int i = 0; i < coreCount; i++)
|
|
{
|
|
allCoresMask.BoolMask.Add(true);
|
|
}
|
|
|
|
changed |= this.AddOrReconcileBuiltInMask(allCoresMask, canReconcileLengths);
|
|
|
|
if (coreCount > 1)
|
|
{
|
|
var noCoreZeroMask = new CoreMask
|
|
{
|
|
Name = NOCORE0MASKNAME,
|
|
Description = "Use all logical CPUs except CPU 0",
|
|
IsDefault = false,
|
|
IsEnabled = true,
|
|
};
|
|
|
|
for (int i = 0; i < coreCount; i++)
|
|
{
|
|
noCoreZeroMask.BoolMask.Add(i != 0);
|
|
}
|
|
|
|
changed |= this.AddOrReconcileBuiltInMask(noCoreZeroMask, canReconcileLengths);
|
|
}
|
|
|
|
// 2. Intel Hybrid Architecture: P-Cores, E-Cores, LPE-Cores (Arrow Lake+)
|
|
if (topology != null && topology.HasIntelHybrid)
|
|
{
|
|
// Detect efficiency class distribution for LPE support
|
|
var efficiencyClasses = topology.LogicalCores
|
|
.Select(c => this.GetEfficiencyClass(c))
|
|
.Distinct()
|
|
.OrderByDescending(x => x)
|
|
.ToList();
|
|
|
|
bool hasLpeCores = efficiencyClasses.Count >= 3; // P, E, LPE
|
|
int pClass = hasLpeCores ? 2 : 1;
|
|
int eClass = hasLpeCores ? 1 : 0;
|
|
int lpeClass = 0;
|
|
|
|
// P-Cores mask
|
|
var pCoresBoolMask = new List<bool>();
|
|
for (int i = 0; i < coreCount; i++)
|
|
{
|
|
var core = topology.LogicalCores.FirstOrDefault(c => c.LogicalCoreId == i);
|
|
pCoresBoolMask.Add(this.GetEfficiencyClass(core) == pClass);
|
|
}
|
|
if (pCoresBoolMask.Any(b => b))
|
|
{
|
|
defaultMasks.Add(("P-Cores", pCoresBoolMask, "Intel Performance cores (highest performance)"));
|
|
}
|
|
|
|
// E-Cores mask
|
|
var eCoresBoolMask = new List<bool>();
|
|
for (int i = 0; i < coreCount; i++)
|
|
{
|
|
var core = topology.LogicalCores.FirstOrDefault(c => c.LogicalCoreId == i);
|
|
eCoresBoolMask.Add(this.GetEfficiencyClass(core) == eClass);
|
|
}
|
|
if (eCoresBoolMask.Any(b => b))
|
|
{
|
|
defaultMasks.Add(("E-Cores", eCoresBoolMask, "Intel Efficiency cores (power efficient)"));
|
|
}
|
|
|
|
// LPE-Cores mask (Arrow Lake and beyond)
|
|
if (hasLpeCores)
|
|
{
|
|
var lpeCoresBoolMask = new List<bool>();
|
|
for (int i = 0; i < coreCount; i++)
|
|
{
|
|
var core = topology.LogicalCores.FirstOrDefault(c => c.LogicalCoreId == i);
|
|
lpeCoresBoolMask.Add(this.GetEfficiencyClass(core) == lpeClass);
|
|
}
|
|
if (lpeCoresBoolMask.Any(b => b))
|
|
{
|
|
defaultMasks.Add(("LPE-Cores", lpeCoresBoolMask, "Intel Low-Power Efficiency cores (ultra power efficient)"));
|
|
}
|
|
}
|
|
|
|
this.logger.LogInformation("Created Intel Hybrid masks (P/E{0})", hasLpeCores ? "/LPE" : string.Empty);
|
|
}
|
|
|
|
// 3. AMD CCD Masks with Cache/Freq differentiation (like CPU Set Setter)
|
|
if (topology != null && topology.HasAmdCcd)
|
|
{
|
|
await this.CreateAmdCcdMasksAsync(topology, defaultMasks, coreCount);
|
|
}
|
|
|
|
// 4. Generate "no SMT/HT" variants for each mask
|
|
var resultMasks = new List<CoreMask>();
|
|
foreach (var (name, boolMask, description) in defaultMasks)
|
|
{
|
|
// Original mask
|
|
resultMasks.Add(this.CreateCoreMaskFromBoolList(name, boolMask, description));
|
|
|
|
// Skip "no HT" variants for E-Cores and LPE-Cores since they don't have HyperThreading
|
|
// Only P-Cores on Intel hybrid architectures have HT
|
|
if (name == "E-Cores" || name == "LPE-Cores")
|
|
{
|
|
continue;
|
|
}
|
|
|
|
// No SMT variant
|
|
if (canCreateNoSmtVariants)
|
|
{
|
|
var noSmtMask = this.StripSMT(boolMask, topology, out bool wasStripped);
|
|
if (wasStripped)
|
|
{
|
|
resultMasks.Add(this.CreateCoreMaskFromBoolList(
|
|
name + noSmtSuffix,
|
|
noSmtMask,
|
|
description + " (no HyperThreading/SMT)"));
|
|
}
|
|
}
|
|
}
|
|
|
|
// 5. "All no HT/SMT" as the last mask
|
|
if (canCreateNoSmtVariants)
|
|
{
|
|
var allCoresBoolMask = Enumerable.Repeat(true, coreCount).ToList();
|
|
var allNoSmtMask = this.StripSMT(allCoresBoolMask, topology, out bool hasStripped);
|
|
if (hasStripped)
|
|
{
|
|
resultMasks.Add(this.CreateCoreMaskFromBoolList(
|
|
"All" + noSmtSuffix,
|
|
allNoSmtMask,
|
|
"All physical cores without HyperThreading/SMT"));
|
|
}
|
|
}
|
|
|
|
// Add all generated masks to AvailableMasks
|
|
foreach (var mask in resultMasks)
|
|
{
|
|
changed |= this.AddOrReconcileBuiltInMask(mask, canReconcileLengths);
|
|
}
|
|
|
|
changed |= await this.ReconcileCustomMaskLengthsAsync(coreCount, canReconcileLengths).ConfigureAwait(false);
|
|
|
|
await Task.CompletedTask;
|
|
return changed;
|
|
}
|
|
|
|
private int ResolveLogicalCoreCount(CpuTopologyModel? topology)
|
|
{
|
|
if (topology?.TopologyDetectionSuccessful == true && topology.TotalLogicalCores > 0)
|
|
{
|
|
return topology.TotalLogicalCores;
|
|
}
|
|
|
|
return Environment.ProcessorCount;
|
|
}
|
|
|
|
// A built-in mask can be re-derived: ThreadPilot knows what "All Cores" is supposed to mean.
|
|
// A mask the user drew is different. Growing it is safe - the CPUs that appeared are simply
|
|
// not part of a selection made before they existed - and shrinking it is safe as long as
|
|
// something is left. Two cases are not ours to decide: a mask that would end up empty, and
|
|
// a mask a power plan association is actively using, where a silent resize would change what
|
|
// that automation does. Those are flagged for the user instead.
|
|
private async Task<bool> ReconcileCustomMaskLengthsAsync(int coreCount, bool topologyIsTrustworthy)
|
|
{
|
|
if (!topologyIsTrustworthy || coreCount <= 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var currentBrand = this.cpuTopologyService.CurrentTopology?.CpuBrand;
|
|
|
|
// A different CPU with the same thread count - a 5800X swapped for a 5800X3D, say -
|
|
// changes what "cores 8-15" means without changing how many there are. The stored
|
|
// selection carries the signature of the machine it was made on, which is the only way
|
|
// to see that. This is what CpuSelectionMigrationMetadata.ReviewRequired was computed
|
|
// for; nothing ever read it.
|
|
var differentCpu = this.AvailableMasks
|
|
.Where(mask => !mask.IsDefault
|
|
&& mask.BoolMask.Count == coreCount
|
|
&& WasBuiltOnADifferentCpu(mask, currentBrand))
|
|
.Select(mask => mask.Name);
|
|
|
|
var stale = this.AvailableMasks
|
|
.Where(mask => !mask.IsDefault && mask.BoolMask.Count > 0 && mask.BoolMask.Count != coreCount)
|
|
.ToList();
|
|
if (stale.Count == 0)
|
|
{
|
|
this.MasksNeedingTopologyReview = differentCpu.ToList();
|
|
return false;
|
|
}
|
|
|
|
var needsReview = new List<string>(differentCpu);
|
|
var changed = false;
|
|
|
|
foreach (var mask in stale)
|
|
{
|
|
var previousCount = mask.BoolMask.Count;
|
|
var resized = ResizeBoolMask(mask.BoolMask, coreCount);
|
|
|
|
if (!resized.Any(selected => selected))
|
|
{
|
|
needsReview.Add(mask.Name);
|
|
this.logger.LogInformation(
|
|
"Custom core mask '{Name}' selects no CPU that still exists ({OldCount} -> {NewCount}): left untouched for review",
|
|
mask.Name,
|
|
previousCount,
|
|
coreCount);
|
|
continue;
|
|
}
|
|
|
|
if (await this.IsMaskReferencedByProfilesAsync(mask.Id).ConfigureAwait(false))
|
|
{
|
|
needsReview.Add(mask.Name);
|
|
this.logger.LogInformation(
|
|
"Custom core mask '{Name}' is used by an automation rule and was built for a different CPU ({OldCount} -> {NewCount}): left untouched for review",
|
|
mask.Name,
|
|
previousCount,
|
|
coreCount);
|
|
continue;
|
|
}
|
|
|
|
ReplaceBoolMask(mask, resized);
|
|
changed = true;
|
|
this.logger.LogInformation(
|
|
"Resized custom core mask '{Name}' from {OldCount} to {NewCount} logical CPUs",
|
|
mask.Name,
|
|
previousCount,
|
|
coreCount);
|
|
}
|
|
|
|
this.MasksNeedingTopologyReview = needsReview;
|
|
return changed;
|
|
}
|
|
|
|
private static bool WasBuiltOnADifferentCpu(CoreMask mask, string? currentBrand)
|
|
{
|
|
var savedBrand = mask.CpuSelection?.Metadata.TopologySignature?.CpuBrand;
|
|
return !string.IsNullOrWhiteSpace(savedBrand)
|
|
&& !string.IsNullOrWhiteSpace(currentBrand)
|
|
&& !string.Equals(savedBrand, currentBrand, StringComparison.OrdinalIgnoreCase);
|
|
}
|
|
|
|
internal static List<bool> ResizeBoolMask(IReadOnlyList<bool> bits, int coreCount)
|
|
{
|
|
var resized = new List<bool>(coreCount);
|
|
for (var index = 0; index < coreCount; index++)
|
|
{
|
|
resized.Add(index < bits.Count && bits[index]);
|
|
}
|
|
|
|
return resized;
|
|
}
|
|
private bool AddOrReconcileBuiltInMask(CoreMask mask, bool reconcileLength)
|
|
{
|
|
var existing = this.AvailableMasks.FirstOrDefault(m =>
|
|
m.Name.Equals(mask.Name, StringComparison.OrdinalIgnoreCase));
|
|
|
|
if (existing == null)
|
|
{
|
|
this.AvailableMasks.Add(mask);
|
|
this.logger.LogInformation("Backfilled built-in core mask '{Name}'", mask.Name);
|
|
return true;
|
|
}
|
|
|
|
if (!reconcileLength || existing.BoolMask.Count == mask.BoolMask.Count)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
this.logger.LogInformation(
|
|
"Re-derived built-in core mask '{Name}' ({Id}) from the current topology: stored {OldCount} logical CPUs, machine has {NewCount}",
|
|
existing.Name, existing.Id, existing.BoolMask.Count, mask.BoolMask.Count);
|
|
|
|
ReplaceBoolMask(existing, mask.BoolMask);
|
|
return true;
|
|
}
|
|
|
|
private static void ReplaceBoolMask(CoreMask mask, IEnumerable<bool> bits)
|
|
{
|
|
mask.BoolMask.Clear();
|
|
foreach (var bit in bits)
|
|
{
|
|
mask.BoolMask.Add(bit);
|
|
}
|
|
|
|
// Drop the stale CpuSelection so it is re-derived from the new BoolMask by
|
|
// ApplyCpuSelectionMigrationAsync (which skips masks that already have one).
|
|
mask.CpuSelection = null;
|
|
mask.CpuSelectionMigration = null;
|
|
mask.ProfileSchemaVersion = CpuAffinityProfileSchemaVersions.Legacy;
|
|
mask.UpdatedAt = DateTime.UtcNow;
|
|
}
|
|
|
|
private async Task CreateAmdCcdMasksAsync(
|
|
CpuTopologyModel topology,
|
|
List<(string name, List<bool> boolMask, string description)> defaultMasks,
|
|
int coreCount)
|
|
{
|
|
try
|
|
{
|
|
var ccdIds = topology.AvailableCcds.ToList();
|
|
|
|
if (ccdIds.Count < 2)
|
|
{
|
|
// Single CCD - just create one CCD mask
|
|
if (ccdIds.Count == 1)
|
|
{
|
|
var ccdBoolMask = new List<bool>();
|
|
for (int i = 0; i < coreCount; i++)
|
|
{
|
|
var core = topology.LogicalCores.FirstOrDefault(c => c.LogicalCoreId == i);
|
|
ccdBoolMask.Add(core?.CcdId == ccdIds[0]);
|
|
}
|
|
defaultMasks.Add(($"CCD{ccdIds[0]}", ccdBoolMask, $"AMD Core Complex Die {ccdIds[0]}"));
|
|
}
|
|
return;
|
|
}
|
|
|
|
// Multiple CCDs - try to detect X3D (Cache vs Freq CCDs)
|
|
// X3D chips have one CCD with significantly more L3 cache
|
|
// For simplicity, we'll create numbered CCD masks
|
|
// TODO: Implement L3 cache size detection for X3D differentiation
|
|
|
|
foreach (var ccdId in ccdIds)
|
|
{
|
|
var ccdBoolMask = new List<bool>();
|
|
for (int i = 0; i < coreCount; i++)
|
|
{
|
|
var core = topology.LogicalCores.FirstOrDefault(c => c.LogicalCoreId == i);
|
|
ccdBoolMask.Add(core?.CcdId == ccdId);
|
|
}
|
|
|
|
if (ccdBoolMask.Any(b => b))
|
|
{
|
|
defaultMasks.Add(($"CCD{ccdId}", ccdBoolMask, $"AMD Core Complex Die {ccdId}"));
|
|
}
|
|
}
|
|
|
|
this.logger.LogInformation(
|
|
"Created {Count} AMD CCD masks for CCDs: {CCDs}",
|
|
ccdIds.Count, string.Join(", ", ccdIds));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogError(ex, "Failed to create AMD CCD masks");
|
|
}
|
|
}
|
|
|
|
private List<bool> StripSMT(List<bool> boolMask, CpuTopologyModel? topology, out bool hasStripped)
|
|
{
|
|
var result = new List<bool>(boolMask.Count);
|
|
hasStripped = false;
|
|
|
|
var coreById = topology?.LogicalCores.ToDictionary(c => c.LogicalCoreId);
|
|
var primaryThreadIds = new HashSet<int>();
|
|
|
|
if (coreById != null)
|
|
{
|
|
foreach (var group in coreById.Values.GroupBy(c => c.PhysicalCoreId))
|
|
{
|
|
var primary = group.OrderBy(c => c.LogicalCoreId).First();
|
|
primaryThreadIds.Add(primary.LogicalCoreId);
|
|
}
|
|
}
|
|
|
|
bool topologyBased = topology?.TopologyDetectionSuccessful == true && primaryThreadIds.Count > 0;
|
|
|
|
for (int i = 0; i < boolMask.Count; i++)
|
|
{
|
|
bool isSMTThread = false;
|
|
bool keepBit = boolMask[i];
|
|
|
|
if (keepBit)
|
|
{
|
|
if (topologyBased && coreById != null && coreById.TryGetValue(i, out var core))
|
|
{
|
|
isSMTThread = core.IsHyperThreaded && !primaryThreadIds.Contains(i);
|
|
}
|
|
else
|
|
{
|
|
// Fallback heuristic based on naming
|
|
var fallbackCore = coreById != null && coreById.TryGetValue(i, out var c) ? c : null;
|
|
var name = fallbackCore?.LogicalProcessorName;
|
|
if (!string.IsNullOrEmpty(name) && name.Length >= 2)
|
|
{
|
|
var lastTwo = name.Substring(name.Length - 2);
|
|
if (lastTwo.StartsWith("T") || lastTwo.StartsWith("_T"))
|
|
{
|
|
isSMTThread = !name.EndsWith("T0") && !name.EndsWith("_T0");
|
|
}
|
|
}
|
|
else if (fallbackCore?.IsHyperThreaded == true && fallbackCore.HyperThreadSibling.HasValue)
|
|
{
|
|
isSMTThread = fallbackCore.LogicalCoreId > fallbackCore.HyperThreadSibling.Value;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (keepBit && isSMTThread)
|
|
{
|
|
hasStripped = true;
|
|
}
|
|
|
|
result.Add(keepBit && !isSMTThread);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private int GetEfficiencyClass(CpuCoreModel? core)
|
|
{
|
|
if (core == null)
|
|
{
|
|
return 0;
|
|
}
|
|
|
|
return core.CoreType switch
|
|
{
|
|
CpuCoreType.PerformanceCore => 2, // Highest efficiency class
|
|
CpuCoreType.EfficiencyCore => 1, // Middle efficiency class
|
|
_ => 0, // Lowest (or unknown/LPE)
|
|
};
|
|
}
|
|
|
|
private CoreMask CreateCoreMaskFromBoolList(string name, List<bool> boolMask, string description)
|
|
{
|
|
var mask = new CoreMask
|
|
{
|
|
Name = name,
|
|
Description = description,
|
|
IsDefault = false,
|
|
IsEnabled = true,
|
|
};
|
|
|
|
foreach (var bit in boolMask)
|
|
{
|
|
mask.BoolMask.Add(bit);
|
|
}
|
|
|
|
return mask;
|
|
}
|
|
}
|
|
}
|