From ce51de5e70aeb0ad641df6ac4dd1980cdcfe2a97 Mon Sep 17 00:00:00 2001 From: PrimeBuild Date: Sat, 28 Nov 2026 03:05:09 +0100 Subject: [PATCH 1/6] Show thread CPU Set overrides without calling them All Cores Read the process default and per-thread CPU Sets on the Processes page, and stop the mask picker from staying on All Cores when a subset is active. Isolation no longer cites CCD0 on Intel. --- Locales/de-DE.xaml | 28 ++- Locales/en-US.xaml | 28 ++- Locales/es-ES.xaml | 28 ++- Locales/fr-FR.xaml | 28 ++- Locales/it-IT.xaml | 28 ++- Locales/ru-RU.xaml | 28 ++- Locales/zh-CN.xaml | 28 ++- Platforms/Windows/CpuSetMapping.cs | 2 + Platforms/Windows/ProcessCpuSetHandler.cs | 27 +- .../ProcessThreadCpuAssignmentHandler.cs | 81 ++++++ Platforms/Windows/ThreadCpuSetDiagnostic.cs | 231 ++++++++++++++++++ .../ProcessViewModelAffinityTests.cs | 78 +++++- .../ProcessViewXamlBindingTests.cs | 10 + .../SystemTweaksGameBoostTests.cs | 29 ++- .../ThreadCpuSetDiagnosticTests.cs | 200 +++++++++++++++ .../ThreadPilot.Core.Tests.csproj | 1 + ViewModels/CpuSetDiagnosticText.cs | 156 ++++++++++++ .../ProcessViewModel.Behaviors.partial.cs | 78 +++++- .../ProcessViewModel.CpuSetDiagnostic.cs | 46 ++++ ViewModels/ProcessViewModel.cs | 7 + ViewModels/SystemTweaksViewModel.GameBoost.cs | 25 +- Views/ProcessView.xaml | 21 ++ Views/SystemTweaksView.xaml | 2 +- .../game-boost-benchmarks-2026-11-28.md | 26 ++ 24 files changed, 1199 insertions(+), 17 deletions(-) create mode 100644 Platforms/Windows/ThreadCpuSetDiagnostic.cs create mode 100644 Tests/ThreadPilot.Core.Tests/ThreadCpuSetDiagnosticTests.cs create mode 100644 ViewModels/CpuSetDiagnosticText.cs create mode 100644 ViewModels/ProcessViewModel.CpuSetDiagnostic.cs create mode 100644 docs/validation/game-boost-benchmarks-2026-11-28.md diff --git a/Locales/de-DE.xaml b/Locales/de-DE.xaml index 95b1734..dcc5894 100644 --- a/Locales/de-DE.xaml +++ b/Locales/de-DE.xaml @@ -302,6 +302,28 @@ manuell, von der App selbst oder von einem anderen Tool gesetzt Aktuelle ideale Prozessoren: CPU {0} keine CPU-Sets, Windows wählt die Kerne + CPU Sets sind aktiv. Das ist nicht die Maske All Cores. + CPU-Set-Diagnose + Liest den Prozessstandard und Thread-Overrides. Der Prozess wird nicht geändert. + Wähle einen Prozess, um seine CPU Sets zu lesen. Der Lesevorgang ändert den Prozess nicht. + CPU Sets konnten nicht gelesen werden. + {0} Threads erben den Prozessstandard; {1} haben ein explizites Override; {2} Lesevorgänge verweigert; {3} Threads während des Lesens beendet; {4} unvollständige Lesevorgänge. + Die Threadliste konnte nicht gelesen werden. Die Zusammenfassung oben enthält sie nicht. + Lesen unvollständig oder verweigert. Fehlende Threads sind nicht Threads, die den Prozessstandard erben. + Das sind von Windows gelesene Zuweisungen, nicht die CPU, auf der der Thread gerade läuft. + Und {0} weitere Threads wurden nicht aufgeführt. + Prozessstandard: keiner. Threads ohne Override platziert Windows. + Prozessstandard: Lesen verweigert. + Prozessstandard: nicht lesbar. + Prozessstandard: unvollständig gelesen, {0}. + Prozessstandard: {0}. + TID {0}: Lesen verweigert. + TID {0}: Thread während des Lesens beendet. + TID {0}: nicht gelesen. + TID {0}: explizites Override, unvollständig gelesen, {1}. + TID {0}: explizites Override, {1}. + Ideale CPU {0} (nicht die CPU, auf der er läuft). + Die harte Affinität enthält diese Zuweisung nicht. Kerne anwenden Wendet die CPU-Auswahl im gewählten Modus an und überprüft den Windows-Status CPU-Zuweisung anwenden und als Regel speichern @@ -590,7 +612,11 @@ Modus Automatisch Isolation - Isolation verschiebt zusätzlich weitere Neben-Apps (Launcher-Helfer, Mediaplayer, Office-Apps), versetzt die ausgewählten Hintergrund-Apps in den Effizienzmodus (EcoQoS) und hält das Spiel auf CPUs mit zwei gleichen CCDs auf CCD0. + Isolation verschiebt zusätzlich weitere Neben-Apps (Launcher-Helfer, Mediaplayer, Office-Apps) und versetzt die ausgewählten Hintergrund-Apps in den Effizienzmodus (EcoQoS). Auf dieser CPU platziert Windows das Spiel. + Isolation verschiebt zusätzlich weitere Neben-Apps (Launcher-Helfer, Mediaplayer, Office-Apps), versetzt die ausgewählten Hintergrund-Apps in den Effizienzmodus (EcoQoS) und hält das Spiel auf den P-Cores. + Isolation verschiebt zusätzlich weitere Neben-Apps (Launcher-Helfer, Mediaplayer, Office-Apps), versetzt die ausgewählten Hintergrund-Apps in den Effizienzmodus (EcoQoS) und hält das Spiel auf CPUs mit zwei gleichen CCDs auf CCD0. + Isolation verschiebt zusätzlich weitere Neben-Apps (Launcher-Helfer, Mediaplayer, Office-Apps), versetzt die ausgewählten Hintergrund-Apps in den Effizienzmodus (EcoQoS) und hält das Spiel auf dem CCD mit 3D V-Cache. + Isolation verschiebt zusätzlich weitere Neben-Apps (Launcher-Helfer, Mediaplayer, Office-Apps) und versetzt die ausgewählten Hintergrund-Apps in den Effizienzmodus (EcoQoS). Auf dieser CPU platziert Windows das Spiel. Spielpriorität auf Höher als normal setzen Experimentell: in deinen Spielen messen. Niemals Hoch oder Echtzeit. Spiele und Apps diff --git a/Locales/en-US.xaml b/Locales/en-US.xaml index 0f4daea..ae1bbdc 100644 --- a/Locales/en-US.xaml +++ b/Locales/en-US.xaml @@ -302,6 +302,28 @@ set by hand, by the app itself or by another tool Current ideal processors: CPU {0} no CPU Sets, Windows picks the cores + CPU Sets are active. This is not the All Cores mask. + CPU Sets diagnostic + Read the process default and any thread overrides. This does not change the process. + Select a process to read its CPU Sets. The read does not change the process. + Could not read CPU Sets. + {0} threads inherit the process default; {1} have an explicit override; {2} reads were denied; {3} threads ended during the read; {4} reads were partial. + The thread list could not be read. The summary above does not include those threads. + Read is partial or denied. Missing threads are not the same as threads that inherit the process default. + These are assignments read from Windows, not the CPU a thread is running on. + And {0} more threads were not listed. + Process default: none. Threads without an override are placed by Windows. + Process default: read denied. + Process default: could not be read. + Process default: partial read, {0}. + Process default: {0}. + TID {0}: read denied. + TID {0}: thread ended during the read. + TID {0}: could not be read. + TID {0}: explicit override, partial read, {1}. + TID {0}: explicit override, {1}. + Ideal CPU {0} (not the CPU it is running on). + Hard affinity does not include this assignment. Apply cores Apply the pending CPU selection with the selected mode and verify the Windows state Apply CPU Assignment and Save as Rule @@ -590,7 +612,11 @@ Mode Automatic Isolation - Isolation also moves more secondary apps (launcher helpers, media players, office apps), puts the selected background apps in efficiency mode (EcoQoS) and, on CPUs with two equal CCDs, keeps the game on CCD0. + Isolation also moves more secondary apps (launcher helpers, media players, office apps) and puts the selected background apps in efficiency mode (EcoQoS). On this CPU Windows still places the game. + Isolation also moves more secondary apps (launcher helpers, media players, office apps), puts the selected background apps in efficiency mode (EcoQoS) and keeps the game on the P-cores. + Isolation also moves more secondary apps (launcher helpers, media players, office apps), puts the selected background apps in efficiency mode (EcoQoS) and, on CPUs with two equal CCDs, keeps the game on CCD0. + Isolation also moves more secondary apps (launcher helpers, media players, office apps), puts the selected background apps in efficiency mode (EcoQoS) and keeps the game on the CCD with 3D V-Cache. + Isolation also moves more secondary apps (launcher helpers, media players, office apps) and puts the selected background apps in efficiency mode (EcoQoS). On this CPU Windows still places the game. Raise game priority to Above Normal Experimental: measure it on your games. Never High or Realtime. Games and apps diff --git a/Locales/es-ES.xaml b/Locales/es-ES.xaml index ebcb4ba..c21135b 100644 --- a/Locales/es-ES.xaml +++ b/Locales/es-ES.xaml @@ -302,6 +302,28 @@ establecidos a mano, por la propia app o por otra herramienta Procesadores ideales actuales: CPU {0} sin CPU Sets, Windows elige los núcleos + Hay CPU Sets activos. No es la máscara All Cores. + Diagnóstico de CPU Sets + Lee el valor predeterminado del proceso y las excepciones de los hilos. No modifica el proceso. + Selecciona un proceso para leer sus CPU Sets. La lectura no modifica el proceso. + No se pudieron leer los CPU Sets. + {0} hilos heredan el valor predeterminado del proceso; {1} tienen una excepción explícita; {2} lecturas denegadas; {3} hilos terminados durante la lectura; {4} lecturas parciales. + No se pudo leer la lista de hilos. El resumen de arriba no los incluye. + Lectura parcial o denegada. Los hilos que faltan no son hilos que heredan el valor predeterminado del proceso. + Son asignaciones leídas de Windows, no la CPU en la que se está ejecutando el hilo. + Y {0} hilos más no se muestran. + Valor predeterminado del proceso: ninguno. Windows coloca los hilos sin excepción. + Valor predeterminado del proceso: lectura denegada. + Valor predeterminado del proceso: no se pudo leer. + Valor predeterminado del proceso: lectura parcial, {0}. + Valor predeterminado del proceso: {0}. + TID {0}: lectura denegada. + TID {0}: el hilo terminó durante la lectura. + TID {0}: no se pudo leer. + TID {0}: excepción explícita, lectura parcial, {1}. + TID {0}: excepción explícita, {1}. + CPU ideal {0} (no la CPU en la que se está ejecutando). + La afinidad rígida no incluye esta asignación. Aplicar núcleos Aplica la selección de CPU con el modo elegido y verifica el estado de Windows Aplicar asignación de CPU y guardar como regla @@ -590,7 +612,11 @@ Modo Automático Aislamiento - Aislamiento también mueve otras aplicaciones secundarias (ayudantes de lanzadores, reproductores multimedia, aplicaciones de oficina), pone las aplicaciones en segundo plano seleccionadas en modo de eficiencia (EcoQoS) y, en CPU con dos CCD iguales, mantiene el juego en el CCD0. + Aislamiento también mueve otras aplicaciones secundarias (ayudantes de lanzadores, reproductores multimedia, aplicaciones de oficina) y pone las aplicaciones en segundo plano seleccionadas en modo de eficiencia (EcoQoS). En esta CPU Windows coloca el juego. + Aislamiento también mueve otras aplicaciones secundarias (ayudantes de lanzadores, reproductores multimedia, aplicaciones de oficina), pone las aplicaciones en segundo plano seleccionadas en modo de eficiencia (EcoQoS) y mantiene el juego en los P-cores. + Aislamiento también mueve otras aplicaciones secundarias (ayudantes de lanzadores, reproductores multimedia, aplicaciones de oficina), pone las aplicaciones en segundo plano seleccionadas en modo de eficiencia (EcoQoS) y, en CPU con dos CCD iguales, mantiene el juego en el CCD0. + Aislamiento también mueve otras aplicaciones secundarias (ayudantes de lanzadores, reproductores multimedia, aplicaciones de oficina), pone las aplicaciones en segundo plano seleccionadas en modo de eficiencia (EcoQoS) y mantiene el juego en el CCD con 3D V-Cache. + Aislamiento también mueve otras aplicaciones secundarias (ayudantes de lanzadores, reproductores multimedia, aplicaciones de oficina) y pone las aplicaciones en segundo plano seleccionadas en modo de eficiencia (EcoQoS). En esta CPU Windows coloca el juego. Subir la prioridad del juego a Por encima de lo normal Experimental: mídelo en tus juegos. Nunca Alta ni Tiempo real. Juegos y aplicaciones diff --git a/Locales/fr-FR.xaml b/Locales/fr-FR.xaml index 26695cf..673b6ff 100644 --- a/Locales/fr-FR.xaml +++ b/Locales/fr-FR.xaml @@ -302,6 +302,28 @@ définis à la main, par l'application elle-même ou par un autre outil Processeurs idéaux actuels : CPU {0} aucun CPU Set, Windows choisit les cœurs + Des CPU Sets sont actifs. Ce n'est pas le masque All Cores. + Diagnostic des CPU Sets + Lit la valeur par défaut du processus et les exceptions des threads. Ne modifie pas le processus. + Sélectionnez un processus pour lire ses CPU Sets. La lecture ne modifie pas le processus. + Impossible de lire les CPU Sets. + {0} threads héritent de la valeur par défaut du processus ; {1} ont une exception explicite ; {2} lectures refusées ; {3} threads terminés pendant la lecture ; {4} lectures partielles. + La liste des threads n'a pas pu être lue. Le résumé ci-dessus ne les inclut pas. + Lecture partielle ou refusée. Les threads manquants ne sont pas des threads qui héritent de la valeur par défaut du processus. + Ce sont des affectations lues dans Windows, pas le CPU sur lequel le thread s'exécute. + Et {0} autres threads ne sont pas listés. + Valeur par défaut du processus : aucune. Windows place les threads sans exception. + Valeur par défaut du processus : lecture refusée. + Valeur par défaut du processus : illisible. + Valeur par défaut du processus : lecture partielle, {0}. + Valeur par défaut du processus : {0}. + TID {0} : lecture refusée. + TID {0} : thread terminé pendant la lecture. + TID {0} : illisible. + TID {0} : exception explicite, lecture partielle, {1}. + TID {0} : exception explicite, {1}. + CPU idéal {0} (pas le CPU sur lequel il s'exécute). + L'affinité stricte n'inclut pas cette affectation. Appliquer les cœurs Applique la sélection CPU avec le mode choisi et vérifie l’état Windows Appliquer l’affectation CPU et enregistrer la règle @@ -590,7 +612,11 @@ Mode Automatique Isolation - L'isolation déplace aussi d'autres applications secondaires (assistants de lanceurs, lecteurs multimédias, applications bureautiques), met les applications d'arrière-plan sélectionnées en mode efficacité (EcoQoS) et, sur les CPU à deux CCD identiques, garde le jeu sur le CCD0. + L'isolation déplace aussi d'autres applications secondaires (assistants de lanceurs, lecteurs multimédias, applications bureautiques) et met les applications d'arrière-plan sélectionnées en mode efficacité (EcoQoS). Sur ce CPU, Windows place le jeu. + L'isolation déplace aussi d'autres applications secondaires (assistants de lanceurs, lecteurs multimédias, applications bureautiques), met les applications d'arrière-plan sélectionnées en mode efficacité (EcoQoS) et garde le jeu sur les P-cores. + L'isolation déplace aussi d'autres applications secondaires (assistants de lanceurs, lecteurs multimédias, applications bureautiques), met les applications d'arrière-plan sélectionnées en mode efficacité (EcoQoS) et, sur les CPU à deux CCD identiques, garde le jeu sur le CCD0. + L'isolation déplace aussi d'autres applications secondaires (assistants de lanceurs, lecteurs multimédias, applications bureautiques), met les applications d'arrière-plan sélectionnées en mode efficacité (EcoQoS) et garde le jeu sur le CCD avec 3D V-Cache. + L'isolation déplace aussi d'autres applications secondaires (assistants de lanceurs, lecteurs multimédias, applications bureautiques) et met les applications d'arrière-plan sélectionnées en mode efficacité (EcoQoS). Sur ce CPU, Windows place le jeu. Passer la priorité du jeu à Supérieure à la normale Expérimental : mesurez-le sur vos jeux. Jamais Haute ni Temps réel. Jeux et applications diff --git a/Locales/it-IT.xaml b/Locales/it-IT.xaml index f1aedef..ae3ead0 100644 --- a/Locales/it-IT.xaml +++ b/Locales/it-IT.xaml @@ -302,6 +302,28 @@ impostati a mano, dall'app stessa o da un altro programma Processori ideali attuali: CPU {0} nessun CPU Set, i core li sceglie Windows + CPU Set attivi. Non è la maschera Tutti i core. + Diagnostica CPU Set + Legge il default del processo e gli override dei thread. Non modifica il processo. + Seleziona un processo per leggere i CPU Set. La lettura non modifica il processo. + Impossibile leggere i CPU Set. + {0} thread ereditano il default del processo; {1} hanno un override esplicito; {2} letture negate; {3} thread terminati durante la lettura; {4} letture parziali. + L'elenco dei thread non è stato letto. Il riepilogo sopra non li include. + Lettura parziale o negata. I thread mancanti non sono thread che ereditano il default del processo. + Sono assegnazioni lette da Windows, non la CPU su cui il thread sta girando. + E altri {0} thread non elencati. + Default del processo: nessuno. I thread senza override li posiziona Windows. + Default del processo: lettura negata. + Default del processo: non letto. + Default del processo: lettura parziale, {0}. + Default del processo: {0}. + TID {0}: lettura negata. + TID {0}: thread terminato durante la lettura. + TID {0}: non letto. + TID {0}: override esplicito, lettura parziale, {1}. + TID {0}: override esplicito, {1}. + CPU ideale {0} (non la CPU su cui sta girando). + L'affinità rigida non include questa assegnazione. Applica core Applica la selezione CPU con la modalità scelta e verifica lo stato di Windows Applica assegnazione CPU e salva come regola @@ -590,7 +612,11 @@ Modalità Automatico Isolamento - Isolamento sposta anche altre app secondarie (helper dei launcher, lettori multimediali, app per ufficio), mette le app in background selezionate in modalità efficienza (EcoQoS) e, sulle CPU con due CCD uguali, tiene il gioco sul CCD0. + Isolamento sposta anche altre app secondarie (helper dei launcher, lettori multimediali, app per ufficio) e mette le app in background selezionate in modalità efficienza (EcoQoS). Su questa CPU il gioco lo posiziona Windows. + Isolamento sposta anche altre app secondarie (helper dei launcher, lettori multimediali, app per ufficio), mette le app in background selezionate in modalità efficienza (EcoQoS) e tiene il gioco sui P-core. + Isolamento sposta anche altre app secondarie (helper dei launcher, lettori multimediali, app per ufficio), mette le app in background selezionate in modalità efficienza (EcoQoS) e, sulle CPU con due CCD uguali, tiene il gioco sul CCD0. + Isolamento sposta anche altre app secondarie (helper dei launcher, lettori multimediali, app per ufficio), mette le app in background selezionate in modalità efficienza (EcoQoS) e tiene il gioco sul CCD con 3D V-Cache. + Isolamento sposta anche altre app secondarie (helper dei launcher, lettori multimediali, app per ufficio) e mette le app in background selezionate in modalità efficienza (EcoQoS). Su questa CPU il gioco lo posiziona Windows. Alza la priorità del gioco a Superiore al normale Sperimentale: misuralo sui tuoi giochi. Mai Alta o Tempo reale. Giochi e app diff --git a/Locales/ru-RU.xaml b/Locales/ru-RU.xaml index e4a33f5..8104d7d 100644 --- a/Locales/ru-RU.xaml +++ b/Locales/ru-RU.xaml @@ -302,6 +302,28 @@ заданы вручную, самим приложением или другой программой Текущие идеальные процессоры: ЦП {0} нет CPU Sets, ядра выбирает Windows + CPU Sets активны. Это не маска All Cores. + Диагностика CPU Sets + Читает значение процесса по умолчанию и исключения потоков. Процесс не изменяется. + Выберите процесс, чтобы прочитать его CPU Sets. Чтение не изменяет процесс. + Не удалось прочитать CPU Sets. + {0} потоков наследуют значение процесса; {1} имеют явное исключение; {2} чтений отклонено; {3} потоков завершились во время чтения; {4} чтений частичные. + Список потоков прочитать не удалось. Сводка выше их не включает. + Чтение частичное или отклонено. Отсутствующие потоки — это не потоки, наследующие значение процесса. + Это назначения, прочитанные из Windows, а не ЦП, на котором поток выполняется. + И ещё {0} потоков не показаны. + Значение процесса: нет. Потоки без исключения размещает Windows. + Значение процесса: чтение отклонено. + Значение процесса: не прочитано. + Значение процесса: частичное чтение, {0}. + Значение процесса: {0}. + TID {0}: чтение отклонено. + TID {0}: поток завершился во время чтения. + TID {0}: не прочитан. + TID {0}: явное исключение, частичное чтение, {1}. + TID {0}: явное исключение, {1}. + Идеальный ЦП {0} (не тот, на котором поток выполняется). + Жёсткая affinity не включает это назначение. Применить ядра Применяет выбор ЦП в выбранном режиме и проверяет состояние Windows. Применить назначение ЦП и сохранить правило @@ -590,7 +612,11 @@ Режим Автоматически Изоляция - Изоляция также переносит другие второстепенные приложения (помощники лаунчеров, медиаплееры, офисные приложения), включает для выбранных фоновых приложений режим эффективности (EcoQoS), а на ЦП с двумя одинаковыми CCD оставляет игру на CCD0. + Изоляция также переносит другие второстепенные приложения (помощники лаунчеров, медиаплееры, офисные приложения) и включает для выбранных фоновых приложений режим эффективности (EcoQoS). На этом ЦП игру размещает Windows. + Изоляция также переносит другие второстепенные приложения (помощники лаунчеров, медиаплееры, офисные приложения), включает для выбранных фоновых приложений режим эффективности (EcoQoS) и оставляет игру на P-ядрах. + Изоляция также переносит другие второстепенные приложения (помощники лаунчеров, медиаплееры, офисные приложения), включает для выбранных фоновых приложений режим эффективности (EcoQoS), а на ЦП с двумя одинаковыми CCD оставляет игру на CCD0. + Изоляция также переносит другие второстепенные приложения (помощники лаунчеров, медиаплееры, офисные приложения), включает для выбранных фоновых приложений режим эффективности (EcoQoS) и оставляет игру на CCD с 3D V-Cache. + Изоляция также переносит другие второстепенные приложения (помощники лаунчеров, медиаплееры, офисные приложения) и включает для выбранных фоновых приложений режим эффективности (EcoQoS). На этом ЦП игру размещает Windows. Повысить приоритет игры до «Выше среднего» Экспериментально: проверьте на своих играх. Никогда «Высокий» или «Реального времени». Игры и приложения diff --git a/Locales/zh-CN.xaml b/Locales/zh-CN.xaml index cbbbd46..749e99f 100644 --- a/Locales/zh-CN.xaml +++ b/Locales/zh-CN.xaml @@ -302,6 +302,28 @@ 由手动、应用自身或其他工具设置 当前理想处理器:CPU {0} 无 CPU 集,由 Windows 选择核心 + CPU Sets 已生效。这不是 All Cores 掩码。 + CPU Sets 诊断 + 读取进程默认值和线程覆盖。不会修改进程。 + 选择一个进程以读取其 CPU Sets。读取不会修改进程。 + 无法读取 CPU Sets。 + {0} 个线程继承进程默认值;{1} 个有显式覆盖;{2} 次读取被拒绝;{3} 个线程在读取期间结束;{4} 次读取不完整。 + 无法读取线程列表。上面的摘要不包含这些线程。 + 读取不完整或被拒绝。缺失的线程并不是继承进程默认值的线程。 + 这些是从 Windows 读取的分配,不是线程正在运行的 CPU。 + 还有 {0} 个线程未列出。 + 进程默认值:无。没有覆盖的线程由 Windows 放置。 + 进程默认值:读取被拒绝。 + 进程默认值:未能读取。 + 进程默认值:部分读取,{0}。 + 进程默认值:{0}。 + TID {0}:读取被拒绝。 + TID {0}:线程在读取期间结束。 + TID {0}:未能读取。 + TID {0}:显式覆盖,部分读取,{1}。 + TID {0}:显式覆盖,{1}。 + 理想 CPU {0}(不是它正在运行的 CPU)。 + 硬亲和性不包含此分配。 应用核心 使用所选模式应用待处理 CPU 选择,并验证 Windows 状态 应用 CPU 分配并保存为规则 @@ -590,7 +612,11 @@ 模式 自动 隔离 - 隔离模式还会移动更多次要应用(启动器辅助进程、媒体播放器、办公应用),让选定的后台应用进入效率模式(EcoQoS),并在两个 CCD 相同的 CPU 上让游戏保持在 CCD0。 + 隔离模式还会移动更多次要应用(启动器辅助进程、媒体播放器、办公应用),并让选定的后台应用进入效率模式(EcoQoS)。在这颗 CPU 上,游戏由 Windows 放置。 + 隔离模式还会移动更多次要应用(启动器辅助进程、媒体播放器、办公应用),让选定的后台应用进入效率模式(EcoQoS),并让游戏保持在 P 核上。 + 隔离模式还会移动更多次要应用(启动器辅助进程、媒体播放器、办公应用),让选定的后台应用进入效率模式(EcoQoS),并在两个 CCD 相同的 CPU 上让游戏保持在 CCD0。 + 隔离模式还会移动更多次要应用(启动器辅助进程、媒体播放器、办公应用),让选定的后台应用进入效率模式(EcoQoS),并让游戏保持在带 3D V-Cache 的 CCD 上。 + 隔离模式还会移动更多次要应用(启动器辅助进程、媒体播放器、办公应用),并让选定的后台应用进入效率模式(EcoQoS)。在这颗 CPU 上,游戏由 Windows 放置。 将游戏优先级提高到“高于正常” 实验性功能:请在你的游戏中实测。绝不使用“高”或“实时”。 游戏和应用 diff --git a/Platforms/Windows/CpuSetMapping.cs b/Platforms/Windows/CpuSetMapping.cs index 3d92ce3..f227929 100644 --- a/Platforms/Windows/CpuSetMapping.cs +++ b/Platforms/Windows/CpuSetMapping.cs @@ -24,6 +24,8 @@ private CpuSetMapping( public bool IsEmpty => this.cpuSetIdsByProcessor.Count == 0; + public IReadOnlyList CpuSetIds => this.processorsByCpuSetId.Keys.OrderBy(id => id).ToArray(); + public static CpuSetMapping Create(IReadOnlyDictionary cpuSetIdsByProcessor) { ArgumentNullException.ThrowIfNull(cpuSetIdsByProcessor); diff --git a/Platforms/Windows/ProcessCpuSetHandler.cs b/Platforms/Windows/ProcessCpuSetHandler.cs index 6cf562b..3f0bf31 100644 --- a/Platforms/Windows/ProcessCpuSetHandler.cs +++ b/Platforms/Windows/ProcessCpuSetHandler.cs @@ -27,6 +27,7 @@ public class ProcessCpuSetHandler : IProcessCpuSetHandler private SafeProcessHandle? queryLimitedInfoHandle; private SafeProcessHandle? setLimitedInfoHandle; + private readonly int queryOpenError; private bool disposed = false; public ProcessCpuSetHandler(uint processId, string executableName, ILogger? logger = null) @@ -52,11 +53,12 @@ internal ProcessCpuSetHandler( ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION, false, processId); + this.queryOpenError = 0; if (this.queryLimitedInfoHandle == null || this.queryLimitedInfoHandle.IsInvalid) { - var error = this.nativeApi.GetLastWin32Error(); - this.logger?.LogWarning("Failed to open process {ProcessId} for querying: {Error}", processId, new Win32Exception(error).Message); + this.queryOpenError = this.nativeApi.GetLastWin32Error(); + this.logger?.LogWarning("Failed to open process {ProcessId} for querying: {Error}", processId, new Win32Exception(this.queryOpenError).Message); } } @@ -66,6 +68,27 @@ internal ProcessCpuSetHandler( public bool IsValid => this.queryLimitedInfoHandle != null && !this.queryLimitedInfoHandle.IsInvalid; + internal CpuSetMapping Mapping => this.cpuSetMapping; + + internal CpuSetIdRead ReadDefaultCpuSets() + { + if (!this.IsValid) + { + return new CpuSetIdRead( + this.queryOpenError == 5 ? CpuSetReadKind.AccessDenied : CpuSetReadKind.Unavailable, + [], + this.queryOpenError); + } + + var ids = this.TryGetDefaultCpuSetIds(); + if (ids == null) + { + return new CpuSetIdRead(CpuSetReadKind.Unavailable, [], this.nativeApi.GetLastWin32Error()); + } + + return new CpuSetIdRead(ids.Count == 0 ? CpuSetReadKind.Empty : CpuSetReadKind.Read, ids, 0); + } + public IReadOnlyList? GetDefaultCpuSetLogicalProcessorIndexes() { var cpuSetIds = this.TryGetDefaultCpuSetIds(); diff --git a/Platforms/Windows/ProcessThreadCpuAssignmentHandler.cs b/Platforms/Windows/ProcessThreadCpuAssignmentHandler.cs index b727bff..1967190 100644 --- a/Platforms/Windows/ProcessThreadCpuAssignmentHandler.cs +++ b/Platforms/Windows/ProcessThreadCpuAssignmentHandler.cs @@ -68,6 +68,59 @@ public ThreadCpuAssignmentResult ApplyGroupAffinity(IReadOnlyList }); } + internal static ThreadCpuSetProbeResult ProbeSelectedCpuSets(int processId) + { + try + { + using var process = Process.GetProcessById(processId); + var probes = new List(); + foreach (ProcessThread thread in process.Threads) + { + probes.Add(ProbeThread(thread.Id)); + } + + return new ThreadCpuSetProbeResult(true, null, probes); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or Win32Exception) + { + var error = ex is Win32Exception win32 ? win32.NativeErrorCode : 0; + return new ThreadCpuSetProbeResult(false, error == 0 ? null : error, []); + } + } + + internal static ThreadCpuSetProbe ProbeThread(int threadId) + { + using var handle = NativeMethods.OpenThread(ThreadQueryLimitedInformation, false, (uint)threadId); + if (handle.IsInvalid) + { + return ThreadCpuSetProbe.OpenFailed(threadId, Marshal.GetLastWin32Error()); + } + + var affinity = ReadAffinity(handle); + var ideal = ReadIdeal(handle); + if (!NativeMethods.GetThreadSelectedCpuSets(handle, null, 0, out var required)) + { + var error = Marshal.GetLastWin32Error(); + if (error != 122 || required == 0) + { + return ThreadCpuSetProbe.QueryFailed(threadId, error, ideal, affinity); + } + } + + if (required == 0) + { + return ThreadCpuSetProbe.NoOverride(threadId, ideal, affinity); + } + + var ids = new uint[required]; + if (!NativeMethods.GetThreadSelectedCpuSets(handle, ids, required, out var filled)) + { + return ThreadCpuSetProbe.QueryFailed(threadId, Marshal.GetLastWin32Error(), ideal, affinity); + } + + return ThreadCpuSetProbe.Override(threadId, ids.Take((int)filled).ToArray(), ideal, affinity); + } + public IReadOnlyList? GetIdealProcessorIndexes() { try @@ -201,6 +254,26 @@ private ThreadCpuAssignmentResult ApplyToThreads(Func : ThreadCpuAssignmentResult.Succeeded(applied); } + private static ProcessorRef? ReadIdeal(SafeWaitHandle handle) + { + if (!NativeMethods.GetThreadIdealProcessorEx(handle, out var processor)) + { + return null; + } + + return new ProcessorRef(processor.Group, processor.Number, (processor.Group * 64) + processor.Number); + } + + private static (bool Read, ushort Group, ulong Mask) ReadAffinity(SafeWaitHandle handle) + { + if (!NativeMethods.GetThreadGroupAffinity(handle, out var affinity)) + { + return (false, 0, 0); + } + + return (true, affinity.Group, (ulong)affinity.Mask); + } + private static ProcessorNumber ToProcessorNumber(ProcessorRef processor) => new() { @@ -246,6 +319,14 @@ private static partial class NativeMethods [LibraryImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool GetThreadGroupAffinity(SafeWaitHandle thread, out GroupAffinity groupAffinity); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool GetThreadSelectedCpuSets( + SafeWaitHandle thread, + uint[]? cpuSetIds, + uint cpuSetIdCount, + out uint requiredIdCount); } } diff --git a/Platforms/Windows/ThreadCpuSetDiagnostic.cs b/Platforms/Windows/ThreadCpuSetDiagnostic.cs new file mode 100644 index 0000000..3a21f10 --- /dev/null +++ b/Platforms/Windows/ThreadCpuSetDiagnostic.cs @@ -0,0 +1,231 @@ +namespace ThreadPilot.Platforms.Windows +{ + using ThreadPilot.Models; + + internal enum CpuSetReadKind + { + Read, + Empty, + AccessDenied, + Terminated, + Unavailable, + Partial, + } + + internal sealed record CpuSetIdRead(CpuSetReadKind Kind, IReadOnlyList Ids, int Win32Error); + + internal readonly record struct ThreadCpuSetProbe( + int ThreadId, + bool Opened, + int OpenError, + bool Queried, + int QueryError, + uint RequiredCount, + IReadOnlyList Ids, + ProcessorRef? IdealProcessor, + bool AffinityRead, + ushort AffinityGroup, + ulong AffinityMask) + { + public static ThreadCpuSetProbe OpenFailed(int threadId, int error) => + new(threadId, false, error, false, 0, 0, [], null, false, 0, 0); + + public static ThreadCpuSetProbe QueryFailed(int threadId, int error, ProcessorRef? ideal, (bool Read, ushort Group, ulong Mask) affinity) => + new(threadId, true, 0, false, error, 0, [], ideal, affinity.Read, affinity.Group, affinity.Mask); + + public static ThreadCpuSetProbe NoOverride(int threadId, ProcessorRef? ideal, (bool Read, ushort Group, ulong Mask) affinity) => + new(threadId, true, 0, true, 0, 0, [], ideal, affinity.Read, affinity.Group, affinity.Mask); + + public static ThreadCpuSetProbe Override(int threadId, IReadOnlyList ids, ProcessorRef? ideal, (bool Read, ushort Group, ulong Mask) affinity) => + new(threadId, true, 0, true, 0, (uint)ids.Count, ids, ideal, affinity.Read, affinity.Group, affinity.Mask); + } + + internal sealed record ThreadCpuSetProbeResult(bool ProcessEnumerated, int? ProcessError, IReadOnlyList Threads); + + internal sealed record ThreadCpuSetObservation( + int ThreadId, + CpuSetReadKind Kind, + bool HasExplicitOverride, + IReadOnlyList CpuSetIds, + IReadOnlyList Processors, + bool MappingIncomplete, + int? Win32Error, + ProcessorRef? IdealProcessor, + bool AffinityConflictsWithAssignment); + + internal sealed record ProcessCpuSetDiagnostic( + CpuSetReadKind DefaultKind, + IReadOnlyList DefaultCpuSetIds, + IReadOnlyList DefaultProcessors, + bool DefaultMappingIncomplete, + bool ThreadsEnumerated, + int? ThreadEnumerationError, + IReadOnlyList Threads) + { + public int InheritedCount => this.Threads.Count(thread => thread.Kind == CpuSetReadKind.Empty && !thread.HasExplicitOverride); + + public int OverrideCount => this.Threads.Count(thread => thread.HasExplicitOverride); + + public int DeniedCount => this.Threads.Count(thread => thread.Kind == CpuSetReadKind.AccessDenied); + + public int TerminatedCount => this.Threads.Count(thread => thread.Kind == CpuSetReadKind.Terminated); + + public int PartialCount => this.Threads.Count(thread => thread.Kind == CpuSetReadKind.Partial || thread.MappingIncomplete); + + public bool IsPartial => + this.DefaultKind is CpuSetReadKind.Partial or CpuSetReadKind.AccessDenied or CpuSetReadKind.Unavailable + || this.DefaultMappingIncomplete + || !this.ThreadsEnumerated + || this.Threads.Any(thread => thread.Kind is not CpuSetReadKind.Read and not CpuSetReadKind.Empty || thread.MappingIncomplete); + } + + internal static class ThreadCpuSetDiagnosticClassifier + { + public static ProcessCpuSetDiagnostic Combine( + CpuSetIdRead defaults, + ThreadCpuSetProbeResult probes, + CpuSetMapping mapping) + { + ArgumentNullException.ThrowIfNull(defaults); + ArgumentNullException.ThrowIfNull(probes); + ArgumentNullException.ThrowIfNull(mapping); + + var mappedDefault = Map(defaults.Ids, mapping); + var defaultKind = defaults.Kind; + if (defaultKind == CpuSetReadKind.Read && mappedDefault.Incomplete) + { + defaultKind = CpuSetReadKind.Partial; + } + + var threads = probes.Threads + .Select(probe => Classify(probe, mapping)) + .OrderBy(thread => thread.Kind == CpuSetReadKind.Empty ? 1 : 0) + .ThenBy(thread => thread.ThreadId) + .ToList(); + + return new ProcessCpuSetDiagnostic( + defaultKind, + defaults.Ids, + mappedDefault.Processors, + mappedDefault.Incomplete, + probes.ProcessEnumerated, + probes.ProcessError, + threads); + } + + public static ThreadCpuSetObservation Classify(ThreadCpuSetProbe probe, CpuSetMapping mapping) + { + ArgumentNullException.ThrowIfNull(mapping); + + if (!probe.Opened) + { + return Failed(probe.ThreadId, KindForOpenError(probe.OpenError), probe.OpenError, probe); + } + + if (!probe.Queried) + { + return Failed(probe.ThreadId, KindForQueryError(probe.QueryError), probe.QueryError, probe); + } + + if (probe.RequiredCount == 0 || probe.Ids.Count == 0) + { + return new ThreadCpuSetObservation( + probe.ThreadId, + CpuSetReadKind.Empty, + false, + [], + [], + false, + null, + probe.IdealProcessor, + false); + } + + var mapped = Map(probe.Ids, mapping); + var kind = mapped.Incomplete ? CpuSetReadKind.Partial : CpuSetReadKind.Read; + return new ThreadCpuSetObservation( + probe.ThreadId, + kind, + true, + probe.Ids, + mapped.Processors, + mapped.Incomplete, + null, + probe.IdealProcessor, + AffinityConflicts(probe, mapped.Processors)); + } + + public static (IReadOnlyList Processors, bool Incomplete) Map(IReadOnlyList ids, CpuSetMapping mapping) + { + var processors = new List(); + var incomplete = false; + foreach (var id in ids.Distinct().OrderBy(id => id)) + { + if (mapping.TryGetProcessorRef(id, out var processor)) + { + processors.Add(processor); + } + else + { + incomplete = true; + } + } + + if (ids.Count > 0 && mapping.IsEmpty) + { + incomplete = true; + } + + return (processors, incomplete); + } + + private static ThreadCpuSetObservation Failed(int threadId, CpuSetReadKind kind, int error, ThreadCpuSetProbe probe) => + new(threadId, kind, false, [], [], kind == CpuSetReadKind.Partial, error, probe.IdealProcessor, false); + + private static CpuSetReadKind KindForOpenError(int error) => error switch + { + 5 => CpuSetReadKind.AccessDenied, + 87 => CpuSetReadKind.Terminated, + _ => CpuSetReadKind.Unavailable, + }; + + private static CpuSetReadKind KindForQueryError(int error) => error switch + { + 5 => CpuSetReadKind.AccessDenied, + 87 => CpuSetReadKind.Terminated, + 122 => CpuSetReadKind.Partial, + _ => CpuSetReadKind.Unavailable, + }; + + private static bool AffinityConflicts(ThreadCpuSetProbe probe, IReadOnlyList processors) + { + if (!probe.AffinityRead || processors.Count == 0) + { + return false; + } + + return processors.Any(processor => + processor.Group != probe.AffinityGroup + || processor.LogicalProcessorNumber >= 64 + || (probe.AffinityMask & (1UL << processor.LogicalProcessorNumber)) == 0); + } + } + + internal interface ICpuSetDiagnosticSource + { + ProcessCpuSetDiagnostic Read(int processId, string name); + } + + internal sealed class ProcessCpuSetDiagnosticReader : ICpuSetDiagnosticSource + { + public static ProcessCpuSetDiagnosticReader Instance { get; } = new(); + + public ProcessCpuSetDiagnostic Read(int processId, string name) + { + using var handler = new ProcessCpuSetHandler((uint)processId, name); + var defaults = handler.ReadDefaultCpuSets(); + var probes = ProcessThreadCpuAssignmentHandler.ProbeSelectedCpuSets(processId); + return ThreadCpuSetDiagnosticClassifier.Combine(defaults, probes, handler.Mapping); + } + } +} diff --git a/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs index 781e85f..b1c77f4 100644 --- a/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs @@ -3,6 +3,7 @@ namespace ThreadPilot.Core.Tests using Microsoft.Extensions.Logging.Abstractions; using Moq; using ThreadPilot.Models; + using ThreadPilot.Platforms.Windows; using ThreadPilot.Services; using ThreadPilot.ViewModels; @@ -169,6 +170,64 @@ public void SelectingProcessBoostedByGameBoost_SaysGameBoostSetTheCpuSets() Assert.True(SpinWait.SpinUntil(() => viewModel.CurrentAffinityText == expected, TimeSpan.FromSeconds(2)), viewModel.CurrentAffinityText); } + [Fact] + public void SelectingProcessWithCpuSets_DoesNotLeaveTheAllCoresMaskSelected() + { + var processService = CreateRunningProcessService(cpuSets: [0]); + var allCores = CoreMask.CreateAllCoresMask(2); + var masks = new System.Collections.ObjectModel.ObservableCollection { allCores }; + var coreMaskService = new Mock(MockBehavior.Loose); + coreMaskService.SetupGet(service => service.AvailableMasks).Returns(masks); + coreMaskService.SetupGet(service => service.DefaultMask).Returns(allCores); + using var viewModel = CreateViewModel( + processService.Object, + new Mock(MockBehavior.Loose).Object, + cpuTopologyProvider: null, + coreMaskService: coreMaskService.Object); + viewModel.CpuTopology = CreateTwoCoreTopology(); + viewModel.CpuCores = new System.Collections.ObjectModel.ObservableCollection(viewModel.CpuTopology.LogicalCores); + viewModel.AvailableCoreMasks = masks; + viewModel.SelectedCoreMask = allCores; + + viewModel.SelectedProcess = new ProcessModel { ProcessId = 1234, Name = "Game", ProcessorAffinity = 3 }; + + Assert.True(SpinWait.SpinUntil( + () => viewModel.SelectedCoreMask == null && viewModel.CoreMaskPickerHint.Contains("All Cores", StringComparison.Ordinal), + TimeSpan.FromSeconds(2)), + viewModel.CoreMaskPickerHint); + Assert.False(viewModel.HasPendingAffinityEdits); + Assert.True(viewModel.CpuCores[0].IsSelected); + Assert.False(viewModel.CpuCores[1].IsSelected); + } + + [Fact] + public void ReadCpuSetDiagnostic_ShowsOverrideSeparatelyFromDeniedReads() + { + var processService = CreateRunningProcessService(cpuSets: []); + using var viewModel = CreateViewModel(processService.Object, new Mock(MockBehavior.Loose).Object, cpuTopologyProvider: null); + viewModel.SelectedProcess = new ProcessModel { ProcessId = 1234, Name = "Game", ProcessorAffinity = 3 }; + var mapping = CpuSetMapping.Create(new Dictionary { [new ProcessorRef(0, 1, 1)] = 10 }); + viewModel.CpuSetDiagnosticSource = new FakeCpuSetDiagnosticSource( + ThreadCpuSetDiagnosticClassifier.Combine( + new CpuSetIdRead(CpuSetReadKind.Read, [10], 0), + new ThreadCpuSetProbeResult( + true, + null, + [ + ThreadCpuSetProbe.NoOverride(1, null, (false, 0, 0)), + ThreadCpuSetProbe.Override(2, [10], null, (false, 0, 0)), + ThreadCpuSetProbe.OpenFailed(3, 5), + ]), + mapping)); + + viewModel.ReadCpuSetDiagnosticCommand.Execute(null); + + Assert.True(SpinWait.SpinUntil(() => viewModel.CpuSetDiagnosticText.Contains("TID 2", StringComparison.Ordinal), TimeSpan.FromSeconds(2)), viewModel.CpuSetDiagnosticText); + Assert.Contains("explicit override", viewModel.CpuSetDiagnosticText, StringComparison.Ordinal); + Assert.Contains("TID 3: read denied.", viewModel.CpuSetDiagnosticText, StringComparison.Ordinal); + Assert.Contains("not the CPU a thread is running on", viewModel.CpuSetDiagnosticText, StringComparison.Ordinal); + } + [Fact] public void SelectingProcessWithoutCpuSets_SaysWindowsPicksTheCores() { @@ -202,7 +261,8 @@ private static ProcessViewModel CreateViewModel( IGameModeService gameModeService, ICpuTopologyProvider? cpuTopologyProvider, IApplicationSettingsService? settingsService = null, - IGameSessionService? gameSessionService = null) + IGameSessionService? gameSessionService = null, + ICoreMaskService? coreMaskService = null) { var virtualizedProcessService = new Mock(MockBehavior.Loose); virtualizedProcessService.SetupProperty( @@ -213,7 +273,7 @@ private static ProcessViewModel CreateViewModel( var powerPlanService = new Mock(MockBehavior.Loose); var notificationService = new Mock(MockBehavior.Loose); var systemTrayService = new Mock(MockBehavior.Loose); - var coreMaskService = new Mock(MockBehavior.Loose); + coreMaskService ??= new Mock(MockBehavior.Loose).Object; var associationService = new Mock(MockBehavior.Loose); return new ProcessViewModel( @@ -225,7 +285,7 @@ private static ProcessViewModel CreateViewModel( powerPlanService.Object, notificationService.Object, systemTrayService.Object, - coreMaskService.Object, + coreMaskService, associationService.Object, gameModeService, cpuTopologyProvider: cpuTopologyProvider, @@ -233,6 +293,18 @@ private static ProcessViewModel CreateViewModel( gameSessionService: gameSessionService); } + private sealed class FakeCpuSetDiagnosticSource : ICpuSetDiagnosticSource + { + private readonly ProcessCpuSetDiagnostic diagnostic; + + public FakeCpuSetDiagnosticSource(ProcessCpuSetDiagnostic diagnostic) + { + this.diagnostic = diagnostic; + } + + public ProcessCpuSetDiagnostic Read(int processId, string name) => this.diagnostic; + } + private static CpuTopologyModel CreateTwoCoreTopology() { return new CpuTopologyModel diff --git a/Tests/ThreadPilot.Core.Tests/ProcessViewXamlBindingTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessViewXamlBindingTests.cs index a6fba0e..d99aebf 100644 --- a/Tests/ThreadPilot.Core.Tests/ProcessViewXamlBindingTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ProcessViewXamlBindingTests.cs @@ -14,6 +14,16 @@ public sealed class ProcessViewXamlBindingTests "Views", "ProcessView.xaml"); + [Fact] + public void CpuSetDiagnostic_IsAReadOnlyDisplayNextToTheMaskPicker() + { + var serialized = File.ReadAllText(ProcessViewPath); + Assert.Contains("ReadCpuSetDiagnosticCommand", serialized, StringComparison.Ordinal); + Assert.Contains("CpuSetDiagnosticText", serialized, StringComparison.Ordinal); + Assert.Contains("CoreMaskPickerHint", serialized, StringComparison.Ordinal); + Assert.Contains("SelectedItem=\"{Binding SelectedCoreMask, Mode=TwoWay}\"", serialized, StringComparison.Ordinal); + } + [Fact] public void LastOperationMessageBinding_IsDisplayOnly() { diff --git a/Tests/ThreadPilot.Core.Tests/SystemTweaksGameBoostTests.cs b/Tests/ThreadPilot.Core.Tests/SystemTweaksGameBoostTests.cs index 8626f20..37756fe 100644 --- a/Tests/ThreadPilot.Core.Tests/SystemTweaksGameBoostTests.cs +++ b/Tests/ThreadPilot.Core.Tests/SystemTweaksGameBoostTests.cs @@ -52,6 +52,31 @@ public async Task Load_ShowsSettingsAndDecision_ToggleSavesAtOnce() Assert.Equal(["Wow"], saved.GameBoostManualGames); } + [Fact] + public async Task IsolationDescription_OnIntelDoesNotCiteCcd0() + { + var settings = new ApplicationSettingsModel(); + var settingsService = new Mock(); + settingsService.SetupGet(service => service.Settings).Returns(settings); + var session = new Mock(); + session.Setup(service => service.GetDecisionAsync()) + .ReturnsAsync(new GameBoostDecision(GameBoostTopologyKind.IntelHybrid, null, null)); + var localization = new Mock(); + localization.Setup(service => service.GetString(It.IsAny())).Returns((string key) => key); + var viewModel = new SystemTweaksViewModel( + new Mock().Object, + new Mock().Object, + localization.Object, + NullLogger.Instance, + settingsService: settingsService.Object, + gameSessionService: session.Object); + + await viewModel.LoadGameBoostAsync(); + + Assert.Contains("P-cores", viewModel.GameBoostIsolationDescription, StringComparison.Ordinal); + Assert.DoesNotContain("CCD0", viewModel.GameBoostIsolationDescription, StringComparison.Ordinal); + } + [Fact] public void TweaksView_HasGameBoostCard() { @@ -61,13 +86,15 @@ public void TweaksView_HasGameBoostCard() Assert.Contains("{Binding GameBoostIsolation, Mode=TwoWay}", serialized, StringComparison.Ordinal); Assert.Contains("{Binding SaveGameBoostListsCommand}", serialized, StringComparison.Ordinal); Assert.Contains("{Binding GameBoostDecisionText}", serialized, StringComparison.Ordinal); + Assert.Contains("{Binding GameBoostIsolationDescription}", serialized, StringComparison.Ordinal); + Assert.DoesNotContain("GameBoost_Mode_Description", serialized, StringComparison.Ordinal); } [Fact] public void EveryLocale_HasTheGameBoostKeys() { var english = GameBoostKeys("en-US"); - Assert.Equal(19, english.Count); + Assert.Equal(23, english.Count); foreach (var language in new[] { "it-IT", "de-DE", "es-ES", "fr-FR", "ru-RU", "zh-CN" }) { Assert.Equal(english, GameBoostKeys(language)); diff --git a/Tests/ThreadPilot.Core.Tests/ThreadCpuSetDiagnosticTests.cs b/Tests/ThreadPilot.Core.Tests/ThreadCpuSetDiagnosticTests.cs new file mode 100644 index 0000000..5984d6a --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/ThreadCpuSetDiagnosticTests.cs @@ -0,0 +1,200 @@ +namespace ThreadPilot.Core.Tests +{ + using System.Runtime.InteropServices; + using Microsoft.Win32.SafeHandles; + using ThreadPilot.Models; + using ThreadPilot.Platforms.Windows; + using ThreadPilot.ViewModels; + + public sealed partial class ThreadCpuSetDiagnosticTests + { + [Fact] + public void NoOverride_IsNotAnExplicitSelection() + { + var observation = ThreadCpuSetDiagnosticClassifier.Classify( + ThreadCpuSetProbe.NoOverride(11, new ProcessorRef(0, 1, 1), (false, 0, 0)), + CpuSetMapping.Empty); + + Assert.Equal(CpuSetReadKind.Empty, observation.Kind); + Assert.False(observation.HasExplicitOverride); + Assert.Empty(observation.CpuSetIds); + } + + [Fact] + public void Override_IsSeparateFromTheProcessDefault() + { + var mapping = Mapping((0, 1, 1, 10u), (0, 2, 2, 20u)); + var diagnostic = ThreadCpuSetDiagnosticClassifier.Combine( + new CpuSetIdRead(CpuSetReadKind.Read, [10], 0), + new ThreadCpuSetProbeResult(true, null, [ThreadCpuSetProbe.Override(42, [20], new ProcessorRef(0, 2, 2), (false, 0, 0))]), + mapping); + + Assert.Equal([10u], diagnostic.DefaultCpuSetIds); + var thread = Assert.Single(diagnostic.Threads); + Assert.True(thread.HasExplicitOverride); + Assert.Equal([20u], thread.CpuSetIds); + Assert.Equal(0, diagnostic.InheritedCount); + Assert.Equal(1, diagnostic.OverrideCount); + var text = CpuSetDiagnosticFormatter.Format(diagnostic, (_, fallback) => fallback); + Assert.Contains("Process default: CPU 1.", text, StringComparison.Ordinal); + Assert.Contains("TID 42: explicit override, CPU 2.", text, StringComparison.Ordinal); + Assert.Contains("not the CPU a thread is running on", text, StringComparison.Ordinal); + } + + [Fact] + public void TerminatedThread_IsReportedAndDoesNotCountAsInherited() + { + var diagnostic = Combine(ThreadCpuSetProbe.OpenFailed(8, 87)); + + Assert.Equal(CpuSetReadKind.Terminated, Assert.Single(diagnostic.Threads).Kind); + Assert.Equal(1, diagnostic.TerminatedCount); + Assert.Equal(0, diagnostic.InheritedCount); + Assert.True(diagnostic.IsPartial); + Assert.Contains("thread ended during the read", CpuSetDiagnosticFormatter.Format(diagnostic, (_, fallback) => fallback), StringComparison.Ordinal); + } + + [Fact] + public void AccessDenied_IsShownAsDeniedNotAsNoOverride() + { + var diagnostic = Combine(ThreadCpuSetProbe.OpenFailed(9, 5), ThreadCpuSetProbe.NoOverride(10, null, (false, 0, 0))); + + Assert.Equal(1, diagnostic.DeniedCount); + Assert.Equal(1, diagnostic.InheritedCount); + Assert.True(diagnostic.IsPartial); + var text = CpuSetDiagnosticFormatter.Format(diagnostic, (_, fallback) => fallback); + Assert.Contains("TID 9: read denied.", text, StringComparison.Ordinal); + Assert.Contains("Read is partial or denied.", text, StringComparison.Ordinal); + Assert.DoesNotContain("TID 9: explicit override", text, StringComparison.Ordinal); + } + + [Fact] + public void UnmappedCpuSetId_IsAPartialRead() + { + var mapping = Mapping((0, 0, 0, 10u)); + var observation = ThreadCpuSetDiagnosticClassifier.Classify( + ThreadCpuSetProbe.Override(4, [10, 999], null, (false, 0, 0)), + mapping); + + Assert.Equal(CpuSetReadKind.Partial, observation.Kind); + Assert.True(observation.HasExplicitOverride); + Assert.True(observation.MappingIncomplete); + Assert.Equal(new ProcessorRef(0, 0, 0), Assert.Single(observation.Processors)); + } + + [Fact] + public void MultipleGroups_AreNotFlattenedIntoOneMask() + { + var mapping = CpuSetMapping.Create(new Dictionary + { + [new ProcessorRef(0, 1, 1)] = 10, + [new ProcessorRef(1, 0, 64)] = 20, + }); + var observation = ThreadCpuSetDiagnosticClassifier.Classify( + ThreadCpuSetProbe.Override(7, [20, 10], null, (false, 0, 0)), + mapping); + + Assert.Equal([(ushort)0, (ushort)1], observation.Processors.Select(processor => processor.Group)); + var text = CpuSetDiagnosticFormatter.FormatProcessors(observation.Processors); + Assert.Equal("G0:CPU 1, G1:CPU 0", text); + } + + [Fact] + public void RigidAffinity_IsDistinctFromTheCpuSetAssignment() + { + var mapping = Mapping((0, 2, 2, 20u)); + var observation = ThreadCpuSetDiagnosticClassifier.Classify( + ThreadCpuSetProbe.Override(5, [20], null, (true, 0, 0x1)), + mapping); + + Assert.True(observation.AffinityConflictsWithAssignment); + Assert.Contains( + "Hard affinity does not include this assignment.", + CpuSetDiagnosticFormatter.Format( + ThreadCpuSetDiagnosticClassifier.Combine( + new CpuSetIdRead(CpuSetReadKind.Empty, [], 0), + new ThreadCpuSetProbeResult(true, null, [ThreadCpuSetProbe.Override(5, [20], null, (true, 0, 0x1))]), + mapping), + (_, fallback) => fallback), + StringComparison.Ordinal); + } + + [Fact] + public void LiveProcess_NoOverrideThenOverrideThenTerminatedThread() + { + using var handler = new ProcessCpuSetHandler((uint)Environment.ProcessId, "ThreadPilot.Tests"); + var cpuSetIds = handler.Mapping.CpuSetIds; + Assert.NotEmpty(cpuSetIds); + var cpuSetId = cpuSetIds[0]; + + using var started = new ManualResetEventSlim(false); + using var release = new ManualResetEventSlim(false); + var threadId = 0; + var thread = new Thread(() => + { + threadId = (int)Native.GetCurrentThreadId(); + started.Set(); + release.Wait(); + }); + thread.Start(); + Assert.True(started.Wait(TimeSpan.FromSeconds(5))); + + try + { + var before = ProcessThreadCpuAssignmentHandler.ProbeThread(threadId); + Assert.False(before.RequiredCount > 0 && before.Ids.Count > 0, "The worker started with an unexpected CPU Set override."); + + using (var handle = Native.OpenThread(0x0400 | 0x0800, false, (uint)threadId)) + { + Assert.False(handle.IsInvalid); + Assert.True(Native.SetThreadSelectedCpuSets(handle, [cpuSetId], 1)); + var overridden = ProcessThreadCpuAssignmentHandler.ProbeThread(threadId); + Assert.Equal([cpuSetId], overridden.Ids); + Assert.True(Native.SetThreadSelectedCpuSets(handle, null, 0)); + } + + var cleared = ProcessThreadCpuAssignmentHandler.ProbeThread(threadId); + Assert.Equal(0u, cleared.RequiredCount); + Assert.Empty(cleared.Ids); + } + finally + { + release.Set(); + Assert.True(thread.Join(TimeSpan.FromSeconds(5))); + } + + // A just-exited thread object can still be opened until Windows drops it, and the id can be reused. + // ERROR_INVALID_PARAMETER from OpenThread is the terminated signal the reader records; a tid that + // was never a thread produces that error without the race. + var ended = ProcessThreadCpuAssignmentHandler.ProbeThread(int.MaxValue); + Assert.False(ended.Opened); + Assert.Equal(87, ended.OpenError); + Assert.Equal( + CpuSetReadKind.Terminated, + ThreadCpuSetDiagnosticClassifier.Classify(ended, handler.Mapping).Kind); + } + + private static ProcessCpuSetDiagnostic Combine(params ThreadCpuSetProbe[] probes) => + ThreadCpuSetDiagnosticClassifier.Combine( + new CpuSetIdRead(CpuSetReadKind.Empty, [], 0), + new ThreadCpuSetProbeResult(true, null, probes), + CpuSetMapping.Empty); + + private static CpuSetMapping Mapping(params (ushort Group, byte Number, int Global, uint Id)[] items) => + CpuSetMapping.Create(items.ToDictionary( + item => new ProcessorRef(item.Group, item.Number, item.Global), + item => item.Id)); + + private static partial class Native + { + [LibraryImport("kernel32.dll")] + internal static partial uint GetCurrentThreadId(); + + [LibraryImport("kernel32.dll", SetLastError = true)] + internal static partial SafeWaitHandle OpenThread(uint desiredAccess, [MarshalAs(UnmanagedType.Bool)] bool inheritHandle, uint threadId); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool SetThreadSelectedCpuSets(SafeWaitHandle thread, uint[]? cpuSetIds, uint cpuSetIdCount); + } + } +} diff --git a/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj b/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj index c24baec..4747442 100644 --- a/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj +++ b/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj @@ -4,6 +4,7 @@ net8.0-windows10.0.22000.0 enable enable + true false cobertura diff --git a/ViewModels/CpuSetDiagnosticText.cs b/ViewModels/CpuSetDiagnosticText.cs new file mode 100644 index 0000000..aa14d09 --- /dev/null +++ b/ViewModels/CpuSetDiagnosticText.cs @@ -0,0 +1,156 @@ +namespace ThreadPilot.ViewModels +{ + using System.Globalization; + using ThreadPilot.Models; + using ThreadPilot.Platforms.Windows; + + internal static class CpuSetDiagnosticFormatter + { + public static string Format(ProcessCpuSetDiagnostic diagnostic, Func text) + { + ArgumentNullException.ThrowIfNull(diagnostic); + ArgumentNullException.ThrowIfNull(text); + + var lines = new List + { + FormatDefault(diagnostic, text), + string.Format( + CultureInfo.CurrentCulture, + text( + "ProcessView_CpuSetDiag_Summary", + "{0} threads inherit the process default; {1} have an explicit override; {2} reads were denied; {3} threads ended during the read; {4} reads were partial."), + diagnostic.InheritedCount, + diagnostic.OverrideCount, + diagnostic.DeniedCount, + diagnostic.TerminatedCount, + diagnostic.PartialCount), + }; + + if (!diagnostic.ThreadsEnumerated) + { + lines.Add(text( + "ProcessView_CpuSetDiag_ThreadsUnlisted", + "The thread list could not be read. The summary above does not include those threads.")); + } + + if (diagnostic.IsPartial) + { + lines.Add(text( + "ProcessView_CpuSetDiag_PartialBanner", + "Read is partial or denied. Missing threads are not the same as threads that inherit the process default.")); + } + + lines.Add(text( + "ProcessView_CpuSetDiag_NotRunningCpu", + "These are assignments read from Windows, not the CPU a thread is running on.")); + + foreach (var thread in diagnostic.Threads.Where(item => item.HasExplicitOverride || item.Kind is CpuSetReadKind.AccessDenied or CpuSetReadKind.Terminated or CpuSetReadKind.Unavailable or CpuSetReadKind.Partial).Take(12)) + { + lines.Add(FormatThread(thread, text)); + } + + var listed = diagnostic.Threads.Count(item => item.HasExplicitOverride || item.Kind is CpuSetReadKind.AccessDenied or CpuSetReadKind.Terminated or CpuSetReadKind.Unavailable or CpuSetReadKind.Partial); + if (listed > 12) + { + lines.Add(string.Format( + CultureInfo.CurrentCulture, + text("ProcessView_CpuSetDiag_More", "And {0} more threads were not listed."), + listed - 12)); + } + + return string.Join(Environment.NewLine, lines); + } + + public static string FormatProcessors(IReadOnlyList processors) + { + if (processors.Count == 0) + { + return string.Empty; + } + + var showGroup = processors.Any(processor => processor.Group != 0); + return string.Join(", ", processors.Select(processor => showGroup + ? FormattableString.Invariant($"G{processor.Group}:CPU {processor.LogicalProcessorNumber}") + : FormattableString.Invariant($"CPU {processor.LogicalProcessorNumber}"))); + } + + private static string FormatDefault(ProcessCpuSetDiagnostic diagnostic, Func text) + { + return diagnostic.DefaultKind switch + { + CpuSetReadKind.Empty => text( + "ProcessView_CpuSetDiag_DefaultNone", + "Process default: none. Threads without an override are placed by Windows."), + CpuSetReadKind.AccessDenied => text( + "ProcessView_CpuSetDiag_DefaultDenied", + "Process default: read denied."), + CpuSetReadKind.Unavailable => text( + "ProcessView_CpuSetDiag_DefaultUnavailable", + "Process default: could not be read."), + _ => string.Format( + CultureInfo.CurrentCulture, + diagnostic.DefaultMappingIncomplete + ? text("ProcessView_CpuSetDiag_DefaultPartial", "Process default: partial read, {0}.") + : text("ProcessView_CpuSetDiag_DefaultRead", "Process default: {0}."), + DescribeIds(diagnostic.DefaultCpuSetIds, diagnostic.DefaultProcessors)), + }; + } + + private static string FormatThread(ThreadCpuSetObservation thread, Func text) + { + if (thread.Kind == CpuSetReadKind.AccessDenied) + { + return string.Format(CultureInfo.CurrentCulture, text("ProcessView_CpuSetDiag_ThreadDenied", "TID {0}: read denied."), thread.ThreadId); + } + + if (thread.Kind == CpuSetReadKind.Terminated) + { + return string.Format(CultureInfo.CurrentCulture, text("ProcessView_CpuSetDiag_ThreadEnded", "TID {0}: thread ended during the read."), thread.ThreadId); + } + + if (!thread.HasExplicitOverride) + { + return string.Format(CultureInfo.CurrentCulture, text("ProcessView_CpuSetDiag_ThreadUnread", "TID {0}: could not be read."), thread.ThreadId); + } + + var assignment = DescribeIds(thread.CpuSetIds, thread.Processors); + var line = string.Format( + CultureInfo.CurrentCulture, + thread.MappingIncomplete + ? text("ProcessView_CpuSetDiag_OverridePartial", "TID {0}: explicit override, partial read, {1}.") + : text("ProcessView_CpuSetDiag_Override", "TID {0}: explicit override, {1}."), + thread.ThreadId, + assignment); + if (thread.IdealProcessor is ProcessorRef ideal) + { + line += " " + string.Format( + CultureInfo.CurrentCulture, + text("ProcessView_CpuSetDiag_Ideal", "Ideal CPU {0} (not the CPU it is running on)."), + FormatProcessors([ideal])); + } + + if (thread.AffinityConflictsWithAssignment) + { + line += " " + text( + "ProcessView_CpuSetDiag_RigidAffinity", + "Hard affinity does not include this assignment."); + } + + return line; + } + + private static string DescribeIds(IReadOnlyList ids, IReadOnlyList processors) + { + var formatted = FormatProcessors(processors); + var unmapped = ids.Distinct().Count() - processors.Count; + if (formatted.Length == 0) + { + return ids.Count == 0 ? "none" : "CPU set ids " + string.Join(", ", ids.Distinct().OrderBy(id => id)); + } + + return unmapped > 0 + ? formatted + ", " + unmapped.ToString(CultureInfo.CurrentCulture) + " unmapped" + : formatted; + } + } +} diff --git a/ViewModels/ProcessViewModel.Behaviors.partial.cs b/ViewModels/ProcessViewModel.Behaviors.partial.cs index 21b5571..fc73321 100644 --- a/ViewModels/ProcessViewModel.Behaviors.partial.cs +++ b/ViewModels/ProcessViewModel.Behaviors.partial.cs @@ -537,6 +537,7 @@ private void UpdateCoreSelections( } this.UpdateAffinityDisplayState(); + this.SyncCoreMaskPickerToDisplayedCores(); } private long CalculateAffinityMask() @@ -1193,10 +1194,81 @@ private void CreateCustomMask() partial void OnSelectedCoreMaskChanged(CoreMask? oldValue, CoreMask? newValue) { - if (newValue == null) + if (this.suppressCoreMaskPickerSync || newValue == null) + { return; + } + + this.UpdateCoreSelectionsFromMask(newValue); + } + + private void SyncCoreMaskPickerToDisplayedCores() + { + if (this.HasPendingAffinityEdits || this.CpuCores.Count == 0) + { + return; + } + + var match = this.FindMaskMatchingDisplayedCores(); + this.SetDisplayedCoreMask(match); + var cpuSetsAreActive = this.currentSoftCpuAssignmentText != null + && this.SelectedCpuAssignmentMode == CpuAssignmentMode.CpuSets; + this.CoreMaskPickerHint = match == null && cpuSetsAreActive && this.SelectedProcess != null + ? this.UiText( + "ProcessView_CpuSetsNotAMask", + "CPU Sets are active. This is not the All Cores mask.") + : string.Empty; + } - UpdateCoreSelectionsFromMask(newValue); + private CoreMask? FindMaskMatchingDisplayedCores() + { + if (this.SelectedCoreMask != null && this.MaskMatchesDisplayedCores(this.SelectedCoreMask)) + { + return this.SelectedCoreMask; + } + + return this.AvailableCoreMasks.FirstOrDefault(this.MaskMatchesDisplayedCores); + } + + private bool MaskMatchesDisplayedCores(CoreMask mask) + { + if (mask.BoolMask.Count == 0) + { + return false; + } + + foreach (var core in this.CpuCores) + { + if (core.LogicalCoreId < 0 || core.LogicalCoreId >= mask.BoolMask.Count) + { + return false; + } + + if (core.IsSelected != mask.BoolMask[core.LogicalCoreId]) + { + return false; + } + } + + return true; + } + + private void SetDisplayedCoreMask(CoreMask? mask) + { + if (ReferenceEquals(this.SelectedCoreMask, mask)) + { + return; + } + + this.suppressCoreMaskPickerSync = true; + try + { + this.SelectedCoreMask = mask; + } + finally + { + this.suppressCoreMaskPickerSync = false; + } } private void UpdateCoreSelectionsFromMask(CoreMask mask) @@ -2269,6 +2341,8 @@ private void ClearProcessSelection() this.HasPendingAffinityEdits = false; this.currentSoftCpuAssignmentText = null; + this.CoreMaskPickerHint = string.Empty; + this.CpuSetDiagnosticText = string.Empty; this.UpdateAffinityDisplayState(); // Reset power plan to current system default diff --git a/ViewModels/ProcessViewModel.CpuSetDiagnostic.cs b/ViewModels/ProcessViewModel.CpuSetDiagnostic.cs new file mode 100644 index 0000000..a5416f4 --- /dev/null +++ b/ViewModels/ProcessViewModel.CpuSetDiagnostic.cs @@ -0,0 +1,46 @@ +namespace ThreadPilot.ViewModels +{ + using CommunityToolkit.Mvvm.Input; + using Microsoft.Extensions.Logging; + using ThreadPilot.Platforms.Windows; + + public partial class ProcessViewModel + { + internal ICpuSetDiagnosticSource CpuSetDiagnosticSource { get; set; } = ProcessCpuSetDiagnosticReader.Instance; + + [RelayCommand] + private async Task ReadCpuSetDiagnosticAsync() + { + var process = this.SelectedProcess; + if (process == null) + { + this.CpuSetDiagnosticText = this.UiText( + "ProcessView_CpuSetDiag_NoProcess", + "Select a process to read its CPU Sets. The read does not change the process."); + return; + } + + var source = this.CpuSetDiagnosticSource; + try + { + var diagnostic = await Task.Run(() => source.Read(process.ProcessId, process.Name)).ConfigureAwait(true); + if (!ReferenceEquals(this.SelectedProcess, process)) + { + return; + } + + this.CpuSetDiagnosticText = CpuSetDiagnosticFormatter.Format(diagnostic, this.UiText); + } + catch (Exception ex) + { + this.Logger.LogWarning(ex, "CPU Set diagnostic failed for {ProcessName}", process.Name); + if (ReferenceEquals(this.SelectedProcess, process)) + { + this.CpuSetDiagnosticText = this.UiText( + "ProcessView_CpuSetDiag_Failed", + "Could not read CPU Sets."); + } + } + } + } +} diff --git a/ViewModels/ProcessViewModel.cs b/ViewModels/ProcessViewModel.cs index 65be7fa..bb5e051 100644 --- a/ViewModels/ProcessViewModel.cs +++ b/ViewModels/ProcessViewModel.cs @@ -53,6 +53,7 @@ public partial class ProcessViewModel : BaseViewModel private bool isApplyingFilter; private bool filterRefreshPending; private bool suppressCoreSelectionEvents; + private bool suppressCoreMaskPickerSync; private bool suppressCpuAssignmentModeChanges; private bool cpuAssignmentModeOverriddenByRule; private string? currentSoftCpuAssignmentText; @@ -105,6 +106,12 @@ public partial class ProcessViewModel : BaseViewModel [ObservableProperty] private string affinityEditStateText = "Select a process to view its current Windows affinity."; + [ObservableProperty] + private string coreMaskPickerHint = string.Empty; + + [ObservableProperty] + private string cpuSetDiagnosticText = string.Empty; + [ObservableProperty] private bool isTopologyDetectionSuccessful = false; diff --git a/ViewModels/SystemTweaksViewModel.GameBoost.cs b/ViewModels/SystemTweaksViewModel.GameBoost.cs index 54853e9..30c29ea 100644 --- a/ViewModels/SystemTweaksViewModel.GameBoost.cs +++ b/ViewModels/SystemTweaksViewModel.GameBoost.cs @@ -37,6 +37,10 @@ public partial class SystemTweaksViewModel [ObservableProperty] private string gameBoostDecisionText = string.Empty; + [ObservableProperty] + private string gameBoostIsolationDescription = + "Isolation also moves more secondary apps (launcher helpers, media players, office apps) and puts the selected background apps in efficiency mode (EcoQoS). On this CPU Windows still places the game."; + [ObservableProperty] private string gameBoostManualGamesText = string.Empty; @@ -152,6 +156,21 @@ private async Task RefreshGameBoostDecisionTextAsync() var decision = await this.gameSessionService.GetDecisionAsync(); var game = decision.GameSelection?.GlobalLogicalProcessorIndexes.Count ?? 0; var background = decision.BackgroundSelection?.GlobalLogicalProcessorIndexes.Count ?? 0; + var isolation = decision.Kind switch + { + GameBoostTopologyKind.IntelHybrid => this.Localize( + "GameBoost_Isolation_Intel", + "Isolation also moves more secondary apps (launcher helpers, media players, office apps), puts the selected background apps in efficiency mode (EcoQoS) and keeps the game on the P-cores."), + GameBoostTopologyKind.AmdSymmetricMultiL3 => this.Localize( + "GameBoost_Isolation_AmdEqual", + "Isolation also moves more secondary apps (launcher helpers, media players, office apps), puts the selected background apps in efficiency mode (EcoQoS) and, on CPUs with two equal CCDs, keeps the game on CCD0."), + GameBoostTopologyKind.AmdAsymmetricCache => this.Localize( + "GameBoost_Isolation_AmdVCache", + "Isolation also moves more secondary apps (launcher helpers, media players, office apps), puts the selected background apps in efficiency mode (EcoQoS) and keeps the game on the CCD with 3D V-Cache."), + _ => this.Localize( + "GameBoost_Isolation_Generic", + "Isolation also moves more secondary apps (launcher helpers, media players, office apps) and puts the selected background apps in efficiency mode (EcoQoS). On this CPU Windows still places the game."), + }; var text = decision.Kind switch { GameBoostTopologyKind.AmdAsymmetricCache => this.Localize( @@ -178,7 +197,11 @@ private async Task RefreshGameBoostDecisionTextAsync() "On this CPU Windows decides the cores; Game Boost only applies the optional priority."), }; - await InvokeOnUiAsync(() => this.GameBoostDecisionText = text); + await InvokeOnUiAsync(() => + { + this.GameBoostDecisionText = text; + this.GameBoostIsolationDescription = isolation; + }); } private static List SplitLines(string text) => diff --git a/Views/ProcessView.xaml b/Views/ProcessView.xaml index 93e068b..6081971 100644 --- a/Views/ProcessView.xaml +++ b/Views/ProcessView.xaml @@ -611,6 +611,15 @@ DisplayMemberPath="Name" ToolTip="{DynamicResource ProcessView_RowMaskTooltip}" AutomationProperties.Name="{DynamicResource ProcessView_PendingCoreMask}"/> +