diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.cs
index 4239096..bd25acc 100644
--- a/MainWindow.xaml.cs
+++ b/MainWindow.xaml.cs
@@ -1,6 +1,7 @@
using System.Windows;
using System.Windows.Input;
using ModernWpf.Controls;
+using TweakHub.Localization;
using TweakHub.Services;
using TweakHub.Views;
@@ -44,6 +45,11 @@ private async void MainWindow_ContentRendered(object? sender, EventArgs e)
while (!TweakService.Instance.RegistryDisclaimerShown) await Task.Delay(500);
await Task.Delay(1000);
await UpdateService.Instance.CheckAndPromptAsync(this, showNoUpdate: false);
+ // A driver update (often the GPU one) recreates the device key and drops the suggested layout without a word.
+ var reset = await Task.Run(() => InterruptService.ResetAffinityDevices(DeviceTree.Read()));
+ if (reset.Count > 0)
+ await Views.Dialogs.AppDialog.ShowWarningAsync(this, L.Get("Maintenance:LayoutResetTitle"),
+ L.Format("Maintenance:LayoutResetMessage", string.Join("\n", reset)));
}
private void Navigation_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
diff --git a/README.md b/README.md
index c58b799..ac8b6ac 100644
--- a/README.md
+++ b/README.md
@@ -109,6 +109,12 @@ It runs as the current user and requests administrator privileges only when an o
+New in 1.7.0:
+- **Suggested interrupt layout** (Devices → Affinity): one physical core each for graphics, USB, network and audio, outside core 0, chosen from the CPU topology (P-cores only on hybrid CPUs, the CCD without 3D V-Cache on dual-CCD Ryzen). Only devices in use count: disabled devices, network cards without a link, the graphics card's HDMI/DisplayPort audio and unused sound cards are left out. The USB controller of your DAC or audio interface gets the audio core when no mouse or keyboard shares it. The preview lists what is plugged into each USB controller, warns about headphones on a front-panel jack, shows the measured load of the chosen cores, offers MSI where the driver supports it, and tells whether Windows already uses the layout or needs a restart. One backup and one elevation; each device is undone with its restore button.
+- **Driver update check:** at startup TweakHub warns when a driver update has reset the layout on some devices.
+- **Disable unused** also suggests, unticked, the slower of two live network connections (wired before Wi-Fi, then the fastest link) and audio devices nobody listens to.
+- **External tools:** NVIDIA VBIOS Vix Editor, with its warnings in the description.
+
New in 1.6.1:
- **Windows Update "Security" mode:** security updates are no longer deferred, but nothing downloads, installs or restarts by itself: Windows notifies you, and you download, install and restart. Drivers stay excluded and feature updates are deferred for 365 days. A clean Windows install is now recognized as "Default". On Windows Home, TweakHub explains which parts the edition ignores.
- **Hardening:** elevated script output goes through a private named pipe instead of temporary files, system folder variables are reset in every script, a running service is stopped before it is deleted, and elevated startup scans by another administrator read the right user.
diff --git a/Resources/Devices.es.resx b/Resources/Devices.es.resx
index d4daa99..3d18fe3 100644
--- a/Resources/Devices.es.resx
+++ b/Resources/Devices.es.resx
@@ -806,6 +806,9 @@ TweakHub no puede comprobar lo que hace el script y el autor puede cambiarlo en
tarjeta de red sin enlace; otra tarjeta está conectada
+ Conectada, pero {0} es más rápida: con dos conexiones activas Windows puede enviar los juegos por la más lenta.
+ Audio HDMI/DisplayPort de la tarjeta gráfica, no es tu dispositivo predeterminado de reproducción ni de grabación. Consérvalo si usas los altavoces del monitor.
+ Tarjeta de sonido integrada que no es tu dispositivo predeterminado de reproducción ni de grabación. Consérvala si conectas algo a los conectores de audio del PC.
Controladores
diff --git a/Resources/Devices.it.resx b/Resources/Devices.it.resx
index 3295c39..4ce1dba 100644
--- a/Resources/Devices.it.resx
+++ b/Resources/Devices.it.resx
@@ -806,6 +806,9 @@ TweakHub non può controllare cosa fa lo script e l'autore può modificarlo in q
scheda di rete senza collegamento; un'altra scheda è connessa
+ Collegata, ma {0} è più veloce: con due connessioni attive Windows può far passare i giochi da quella più lenta.
+ Audio HDMI/DisplayPort della scheda video, non è il tuo dispositivo predefinito di riproduzione o registrazione. Tienilo se usi le casse del monitor.
+ Scheda audio integrata che non è il tuo dispositivo predefinito di riproduzione o registrazione. Tienila se colleghi qualcosa ai jack audio del PC.
Driver
diff --git a/Resources/Devices.ja.resx b/Resources/Devices.ja.resx
index a19e437..f5d1e6a 100644
--- a/Resources/Devices.ja.resx
+++ b/Resources/Devices.ja.resx
@@ -806,6 +806,9 @@ TweakHub はスクリプトの動作を確認できず、作者はいつでも
リンクのないネットワーク カード(別のカードが接続中)
+ 接続されていますが {0} のほうが高速です。接続が 2 つあると、Windows がゲームを遅いほうで通信することがあります。
+ グラフィックカードの HDMI/DisplayPort オーディオで、既定の再生・録音デバイスではありません。モニターのスピーカーを使う場合は残してください。
+ 既定の再生・録音デバイスではないオンボードのサウンドカードです。PC のオーディオ ジャックに何か接続する場合は残してください。
ドライバー
diff --git a/Resources/Devices.resx b/Resources/Devices.resx
index e6a235a..54e446d 100644
--- a/Resources/Devices.resx
+++ b/Resources/Devices.resx
@@ -806,6 +806,9 @@ TweakHub cannot check what the script does, and the author can change it at any
network card without a link; another card is connected
+ Connected, but {0} is faster: with two live connections Windows may send games over the slower one.
+ HDMI/DisplayPort audio of the graphics card, not your default playback or recording device. Keep it if you use the monitor's speakers.
+ Built-in sound card that is not your default playback or recording device. Keep it if you plug anything into the PC's audio jacks.
Drivers
diff --git a/Resources/Devices.ru.resx b/Resources/Devices.ru.resx
index b091ab7..8733f45 100644
--- a/Resources/Devices.ru.resx
+++ b/Resources/Devices.ru.resx
@@ -806,6 +806,9 @@ TweakHub не может проверить, что делает скрипт,
сетевая карта без подключения; другая карта подключена
+ Подключена, но {0} быстрее: при двух активных подключениях Windows может пустить игры через более медленное.
+ Звук HDMI/DisplayPort видеокарты, не ваше устройство воспроизведения или записи по умолчанию. Оставьте, если пользуетесь динамиками монитора.
+ Встроенная звуковая карта, которая не является устройством воспроизведения или записи по умолчанию. Оставьте, если подключаете что-то к аудиоразъёмам ПК.
Драйверы
diff --git a/Resources/Devices.zh-CN.resx b/Resources/Devices.zh-CN.resx
index 63da044..7e78891 100644
--- a/Resources/Devices.zh-CN.resx
+++ b/Resources/Devices.zh-CN.resx
@@ -806,6 +806,9 @@ TweakHub 无法检查脚本的行为,作者也可以随时修改它。如有
网卡未连接;另一张网卡已连接
+ 已连接,但 {0} 更快:有两个活动连接时,Windows 可能让游戏走较慢的那个。
+ 显卡的 HDMI/DisplayPort 音频,不是你的默认播放或录音设备。如果使用显示器扬声器请保留。
+ 不是默认播放或录音设备的板载声卡。如果你会在电脑音频插孔上插设备请保留。
驱动程序
diff --git a/Resources/Maintenance.es.resx b/Resources/Maintenance.es.resx
index 85796a7..305f2ee 100644
--- a/Resources/Maintenance.es.resx
+++ b/Resources/Maintenance.es.resx
@@ -56,4 +56,44 @@ Se abre una consola elevada con su aviso. -p -spr -m -sor -se -scs conservan ene
Desactivar por completo la suspensión con corriente
Con el equipo enchufado, Windows ya no permite los estados de espera (S1–S3), la tecla de suspensión no hace nada y Suspender desaparece del menú de apagado de Inicio. Úsalo solo si nunca suspendes este equipo. Opcional, no se aplica entre los recomendados. Los equipos con Modern Standby no usan S1–S3 y conservan su propia suspensión. Restaurar devuelve los valores originales. Requiere reinicio.
Microsoft Defender (o tu antivirus) bloqueó el paquete de Tron como software potencialmente no deseado y lo eliminó. TweakHub nunca añade exclusiones al antivirus. Si confías en Tron, añade tú las exclusiones para la carpeta Data\Tools\Tron de esta copia y para C:\ProgramData\TweakHub-Tron-*, y vuelve a intentarlo.
+ Distribución sugerida por función
+ Distribución de interrupciones sugerida
+ Un núcleo físico para gráficos, USB, red y audio, fuera del núcleo 0, elegido según la topología de esta CPU. Es una distribución sugerida para medir: el beneficio no está demostrado. Solo cambia la afinidad; MSI y la prioridad no se tocan. Desmarca los dispositivos que quieras dejar como están.
+ Gráficos
+ USB
+ Red
+ Audio
+ CPU híbrida: solo se usan núcleos P.
+ CPU con varias cachés L3 (CCD): los dispositivos van al CCD sin 3D V-Cache, o al que no tiene la CPU 0 si las cachés son iguales.
+ Esta CPU tiene 6 núcleos o menos: red y audio comparten un núcleo.
+ El RSS de red no se modifica: mover su inicio hace que Windows cambie también las colas y los procesadores, y no se puede restaurar con exactitud.
+ No se puede sugerir una distribución en este PC: varios grupos de procesadores, muy pocos núcleos o topología ilegible.
+ Todos los dispositivos ya tienen la afinidad sugerida.
+ Reinicia con Reiniciar, no con Apagar (el inicio rápido conserva el estado anterior). Vuelve a comprobarlo tras cada actualización del controlador de la GPU, que puede restablecer estos valores. Compara los frame times 1% y 0,1% low, no solo los FPS medios. El botón de restaurar de cada dispositivo lo deshace.
+ {0}: CPU {1} – {2}
+ {0}: audio HDMI/DisplayPort de la tarjeta gráfica, no se mueve (no es el audio para jugar).
+ {0}: ningún dispositivo de audio activo detrás (desactivado o ausente), no se mueve.
+ No hay tarjeta de sonido integrada en uso: el audio USB (auriculares, DAC, interfaces de audio) sigue el núcleo del controlador USB al que está conectado.
+ USB {0}: {1}
+ ratón
+ teclado
+ cámara
+ audio: {0}
+ sin ratón, teclado, cámara ni dispositivo de audio predeterminado
+ {0} comparte el controlador USB con el ratón o el teclado, así que se queda en el núcleo USB. Para darle su propio núcleo, conéctalo a un puerto de un controlador sin ratón ni teclado (mira la lista de arriba) y vuelve a abrir este diseño.
+ {0} está conectado a un conector frontal de la caja: ese cable pasa por dentro de la caja y suele captar ruido. Para jugar, usa el conector trasero de la placa base.
+ Carga medida ahora durante 2 segundos (con un juego en marcha es distinta):
+ CPU {0}: {1:0}% ocupada, {2:0.0}% interrupciones y DPC, {3:0} interrupciones/s
+ La CPU {0} ya está ocupada al {1:0}%: un programa la está usando. Revisa el Administrador de tareas antes de aplicar.
+ {0}: desactivado o sin funcionar, fuera del diseño.
+ {0}: sin conexión de red, fuera del diseño.
+ Activar MSI para {0} (su controlador lo admite, ahora está desactivado)
+ {0} está ligado solo a {1}: los controladores de almacenamiento con varias colas van mejor con el reparto predeterminado de Windows. Usa el botón de restaurar o el editor para quitar su afinidad.
+ Activo ahora: {0}
+ Configurado, pero Windows usa los núcleos anteriores hasta reiniciar: {0}
+ Diseño de interrupciones restablecido
+ La afinidad de interrupciones sugerida ya no está en estos dispositivos, normalmente tras actualizar un controlador:
+{0}
+
+Abre Dispositivos → Afinidad y vuelve a aplicar el diseño sugerido.
diff --git a/Resources/Maintenance.it.resx b/Resources/Maintenance.it.resx
index 524a004..5402f48 100644
--- a/Resources/Maintenance.it.resx
+++ b/Resources/Maintenance.it.resx
@@ -56,4 +56,44 @@ Avvio elevato in una console visibile, con il disclaimer di Tron. Argomenti: -p
Disattiva del tutto la sospensione alla presa
Con il PC collegato alla corrente Windows non consente più gli stati di standby (S1–S3), il tasto di sospensione non fa nulla e la voce Sospendi sparisce dal menu di arresto di Start. Usalo solo se non sospendi mai questo PC. Opzionale, non applicato tra i consigliati. I PC con Modern Standby non usano S1–S3 e mantengono la propria sospensione. Il ripristino rimette i valori originali. Richiede riavvio.
Microsoft Defender (o il tuo antivirus) ha bloccato il pacchetto Tron come software potenzialmente indesiderato e lo ha rimosso. TweakHub non aggiunge mai esclusioni all'antivirus. Se ti fidi di Tron, aggiungi tu le esclusioni per la cartella Data\Tools\Tron di questa copia e per C:\ProgramData\TweakHub-Tron-*, poi riprova.
+ Layout suggerito per ruolo
+ Layout degli interrupt suggerito
+ Un core fisico ciascuno per grafica, USB, rete e audio, fuori dal core 0, scelto dalla topologia di questa CPU. È un layout suggerito da misurare: il beneficio non è dimostrato. Cambia solo l'affinità; MSI e priorità restano come sono. Togli la spunta ai dispositivi che vuoi lasciare invariati.
+ Grafica
+ USB
+ Rete
+ Audio
+ CPU ibrida: si usano solo i P-core.
+ CPU con più cache L3 (CCD): i dispositivi vanno sul CCD senza 3D V-Cache, o su quello senza la CPU 0 se le cache sono uguali.
+ Questa CPU ha 6 core o meno: rete e audio condividono un core.
+ L'RSS di rete non viene modificato: spostarne l'inizio fa cambiare a Windows anche code e processori, e non si potrebbe ripristinare esattamente.
+ Su questo PC non si può suggerire un layout: più gruppi di processori, troppo pochi core o topologia non leggibile.
+ Tutti i dispositivi hanno già l'affinità suggerita.
+ Riavvia con Riavvia, non con Arresta (l'Avvio rapido conserva lo stato precedente). Ricontrolla dopo ogni aggiornamento del driver della GPU, che può azzerare questi valori. Confronta i frame time 1% e 0,1% low, non solo gli FPS medi. Il pulsante di ripristino di ogni dispositivo annulla la modifica.
+ {0}: CPU {1} – {2}
+ {0}: audio HDMI/DisplayPort della scheda video, non spostato (non è l'audio per giocare).
+ {0}: nessun dispositivo audio attivo dietro di esso (disattivato o assente), non spostato.
+ Nessuna scheda audio integrata in uso: l'audio USB (cuffie, DAC, schede audio esterne) segue il core del controller USB a cui è collegato.
+ USB {0}: {1}
+ mouse
+ tastiera
+ webcam
+ audio: {0}
+ nessun mouse, tastiera, webcam o dispositivo audio predefinito
+ {0} condivide il controller USB con il mouse o la tastiera, quindi resta sul core USB. Per dargli un core tutto suo, collegalo a una porta di un controller senza mouse e tastiera (vedi l'elenco sopra), poi riapri questo layout.
+ {0} è collegato a un jack frontale del case: quel cavo passa dentro il case e prende spesso disturbi. Per giocare usa il jack sul retro della scheda madre.
+ Carico misurato ora per 2 secondi (mentre gira un gioco è diverso):
+ CPU {0}: occupata al {1:0}%, {2:0.0}% interrupt e DPC, {3:0} interrupt/s
+ La CPU {0} è già occupata al {1:0}%: un programma la sta usando. Controlla Gestione attività prima di applicare.
+ {0}: disattivato o non funzionante, escluso dal layout.
+ {0}: nessun collegamento di rete, escluso dal layout.
+ Attiva MSI per {0} (supportato dal driver, ora spento)
+ {0} è legato solo a {1}: i controller di archiviazione con più code vanno meglio con la distribuzione predefinita di Windows. Usa il pulsante di ripristino o l'editor per azzerare la sua affinità.
+ Attivo ora: {0}
+ Impostato, ma Windows usa i core precedenti fino al riavvio: {0}
+ Layout degli interrupt azzerato
+ L'affinità degli interrupt suggerita non c'è più su questi dispositivi, di solito dopo un aggiornamento dei driver:
+{0}
+
+Apri Dispositivi → Affinità e applica di nuovo il layout suggerito.
diff --git a/Resources/Maintenance.ja.resx b/Resources/Maintenance.ja.resx
index 843969f..8c8be35 100644
--- a/Resources/Maintenance.ja.resx
+++ b/Resources/Maintenance.ja.resx
@@ -56,4 +56,44 @@
電源接続時にスリープを完全に無効化
電源接続時に Windows はスタンバイ状態 (S1–S3) を使用しなくなり、スリープ キーは何もせず、スタートの電源メニューから「スリープ」が非表示になります。この PC を一切スリープさせない場合のみ使用してください。任意設定で、推奨には含まれません。Modern Standby の PC は S1–S3 を使用しないため、独自のスリープが残ります。復元すると元の値に戻ります。再起動が必要です。
Microsoft Defender(またはお使いのウイルス対策)が Tron パッケージを望ましくない可能性のあるソフトウェアとしてブロックし、削除しました。TweakHub がウイルス対策の除外を追加することはありません。Tron を信頼する場合は、このコピーの Data\Tools\Tron フォルダーと C:\ProgramData\TweakHub-Tron-* をご自身で除外に追加してから、もう一度お試しください。
+ 役割別の推奨レイアウト
+ 推奨される割り込みレイアウト
+ グラフィックス、USB、ネットワーク、オーディオにそれぞれ物理コアを 1 つずつ、コア 0 以外からこの CPU のトポロジーに基づいて割り当てます。効果は実証されていないため、測定して確認するための推奨レイアウトです。変更するのはアフィニティのみで、MSI と優先度はそのままです。変更しないデバイスのチェックを外してください。
+ グラフィックス
+ USB
+ ネットワーク
+ オーディオ
+ ハイブリッド CPU:P コアのみを使用します。
+ 複数の L3 キャッシュ(CCD)を持つ CPU:デバイスは 3D V-Cache のない CCD に、キャッシュが同じ場合は CPU 0 を含まない CCD に割り当てます。
+ この CPU のコアは 6 個以下のため、ネットワークとオーディオで 1 つのコアを共有します。
+ ネットワークの RSS は変更しません。開始位置を動かすと Windows がキューとプロセッサの数も変更し、正確に元に戻せないためです。
+ この PC では推奨レイアウトを作成できません(複数のプロセッサ グループ、コア不足、またはトポロジーを読み取れません)。
+ すべてのデバイスが既に推奨アフィニティになっています。
+ 「シャットダウン」ではなく「再起動」を使ってください(高速スタートアップは以前の状態を保持します)。GPU ドライバーを更新するたびに再確認してください。これらの値がリセットされる場合があります。平均 FPS だけでなく、1% と 0.1% low のフレームタイムを比較してください。各デバイスの復元ボタンで元に戻せます。
+ {0}:CPU {1} – {2}
+ {0}: グラフィックカードの HDMI/DisplayPort オーディオのため移動しません(ゲーム用の音声ではありません)。
+ {0}: この背後に動作中のオーディオデバイスがありません(無効または存在しない)。移動しません。
+ オンボードのサウンドカードは使用されていません。USB オーディオ(ヘッドセット、DAC、オーディオインターフェイス)は接続先 USB コントローラーのコアに従います。
+ USB {0}: {1}
+ マウス
+ キーボード
+ カメラ
+ オーディオ: {0}
+ マウス、キーボード、カメラ、既定のオーディオデバイスなし
+ {0} はマウスまたはキーボードと USB コントローラーを共有しているため、USB のコアのままです。専用のコアにするには、マウスとキーボードのないコントローラーのポート(上の一覧を参照)に接続し、このレイアウトを開き直してください。
+ {0} はケース前面のジャックに接続されています。そのケーブルはケース内部を通るためノイズを拾いやすいです。ゲームではマザーボード背面のジャックを使ってください。
+ 現在 2 秒間測定した負荷(ゲーム実行中は異なります):
+ CPU {0}: 使用率 {1:0}%、割り込みと DPC {2:0.0}%、割り込み {3:0} 回/秒
+ CPU {0} はすでに {1:0}% 使用されています。プログラムが使用中です。適用する前にタスク マネージャーを確認してください。
+ {0}: 無効または動作していないため、レイアウトから除外しました。
+ {0}: ネットワーク接続がないため、レイアウトから除外しました。
+ {0} の MSI をオンにする(ドライバーは対応、現在オフ)
+ {0} は {1} のみに固定されています。複数のキューを持つストレージ コントローラーは Windows 既定の分散のほうが高速です。復元ボタンまたはエディターでアフィニティをリセットしてください。
+ 現在有効: {0}
+ 設定済みですが、再起動するまで Windows は以前のコアを使います: {0}
+ 割り込みレイアウトがリセットされました
+ 推奨した割り込みアフィニティがこれらのデバイスから消えています。通常はドライバーの更新後です:
+{0}
+
+[デバイス] → [アフィニティ] を開き、推奨レイアウトをもう一度適用してください。
diff --git a/Resources/Maintenance.resx b/Resources/Maintenance.resx
index 75f8fba..ce725dd 100644
--- a/Resources/Maintenance.resx
+++ b/Resources/Maintenance.resx
@@ -58,4 +58,44 @@ Launch elevated in a visible console with its own disclaimer. Arguments: -p -spr
Turn off sleep completely when plugged in
When plugged in, Windows no longer allows standby (S1–S3), the sleep key does nothing and Sleep is hidden from the Start power menu. Use it only if you never put this PC to sleep. Optional, not recommended automatically. PCs with Modern Standby do not use S1–S3 and keep their own sleep. Restore puts back the original values. Restart required.
Microsoft Defender (or your antivirus) blocked the Tron package as potentially unwanted software and removed it. TweakHub never adds antivirus exclusions. If you trust Tron, add exclusions yourself for this copy's Data\Tools\Tron folder and for C:\ProgramData\TweakHub-Tron-*, then try again.
+ Suggested layout by role
+ Suggested interrupt layout
+ One physical core each for graphics, USB, network and audio, outside core 0, chosen from this CPU's topology. It is a suggested layout to measure: the benefit is not proven. Only the affinity changes; MSI and priority stay as they are. Untick the devices you want to leave alone.
+ Graphics
+ USB
+ Network
+ Audio
+ Hybrid CPU: only P-cores are used.
+ CPU with several L3 caches (CCDs): devices go to the CCD without 3D V-Cache, or to the one without CPU 0 when the caches are equal.
+ This CPU has 6 cores or fewer: network and audio share one core.
+ Network RSS is not changed: moving its start makes Windows also change the queues and processors, which cannot be restored exactly.
+ No layout can be suggested on this PC: several processor groups, too few cores or an unreadable topology.
+ Every device already has the suggested affinity.
+ Restart with Restart, not Shut down (Fast Startup keeps the old state). Check again after every GPU driver update, which can reset these values. Compare 1% and 0.1% low frame times, not only average FPS. The restore button of each device undoes it.
+ {0}: CPU {1} – {2}
+ {0}: HDMI/DisplayPort audio of the graphics card, not moved (it is not the gaming audio).
+ {0}: no working audio device behind it (disabled or missing), not moved.
+ No built-in sound card in use: USB audio (headsets, DACs, audio interfaces) follows the core of the USB controller it is plugged into.
+ USB {0}: {1}
+ mouse
+ keyboard
+ camera
+ audio: {0}
+ no mouse, keyboard, camera or default audio device
+ {0} shares its USB controller with the mouse or keyboard, so it stays on the USB core. To give it its own core, plug it into a port of a controller without mouse and keyboard (see the list above), then open this layout again.
+ {0} is plugged into a front-panel jack of the case: that cable runs inside the case and often picks up noise. For gaming, use the jack on the back of the motherboard.
+ Load measured now over 2 seconds (it is different while a game runs):
+ CPU {0}: {1:0}% busy, {2:0.0}% interrupts and DPC, {3:0} interrupts/s
+ CPU {0} is already {1:0}% busy now: a program is using it. Check Task Manager before applying.
+ {0}: disabled or not working, left out of the layout.
+ {0}: no network link, left out of the layout.
+ Turn on MSI for {0} (supported by its driver, now off)
+ {0} is tied to {1} only: storage controllers with several queues are faster with Windows' default spread. Use the restore button or the editor to reset its affinity.
+ Active now: {0}
+ Set, but Windows still uses the old cores until a restart: {0}
+ Interrupt layout reset
+ The suggested interrupt affinity is gone on these devices, usually after a driver update:
+{0}
+
+Open Devices → Affinity and apply the suggested layout again.
diff --git a/Resources/Maintenance.ru.resx b/Resources/Maintenance.ru.resx
index 1c1d4aa..aa100cf 100644
--- a/Resources/Maintenance.ru.resx
+++ b/Resources/Maintenance.ru.resx
@@ -56,4 +56,44 @@
Полностью отключить сон от сети
При питании от сети Windows больше не разрешает ждущие режимы (S1–S3), клавиша сна ничего не делает, а пункт «Спящий режим» скрыт из меню завершения работы в «Пуске». Используйте, только если никогда не переводите этот ПК в сон. Необязательно, не входит в рекомендуемые. ПК с Modern Standby не используют S1–S3 и сохраняют свой режим сна. Восстановление возвращает исходные значения. Требуется перезагрузка.
Microsoft Defender (или ваш антивирус) заблокировал пакет Tron как потенциально нежелательное ПО и удалил его. TweakHub никогда не добавляет исключения в антивирус. Если вы доверяете Tron, сами добавьте исключения для папки Data\Tools\Tron этой копии и для C:\ProgramData\TweakHub-Tron-*, затем повторите попытку.
+ Рекомендуемая раскладка по ролям
+ Рекомендуемая раскладка прерываний
+ По одному физическому ядру для графики, USB, сети и звука, вне ядра 0, по топологии этого процессора. Это рекомендуемая раскладка для измерения: польза не доказана. Меняется только привязка; MSI и приоритет остаются как есть. Снимите отметку с устройств, которые не нужно менять.
+ Графика
+ USB
+ Сеть
+ Звук
+ Гибридный процессор: используются только P-ядра.
+ Процессор с несколькими кэшами L3 (CCD): устройства назначаются на CCD без 3D V-Cache или, при равных кэшах, на CCD без CPU 0.
+ У этого процессора 6 ядер или меньше: сеть и звук делят одно ядро.
+ RSS сети не меняется: при переносе начала Windows меняет и очереди, и процессоры, а точно вернуть это нельзя.
+ На этом ПК нельзя предложить раскладку: несколько групп процессоров, слишком мало ядер или нечитаемая топология.
+ У всех устройств уже установлена рекомендуемая привязка.
+ Перезагрузите через «Перезагрузка», а не «Завершение работы» (быстрый запуск сохраняет старое состояние). Проверяйте снова после каждого обновления драйвера GPU — он может сбросить эти значения. Сравнивайте 1% и 0,1% low frame time, а не только средний FPS. Кнопка восстановления у каждого устройства отменяет изменение.
+ {0}: CPU {1} – {2}
+ {0}: звук HDMI/DisplayPort видеокарты, не переносится (это не игровой звук).
+ {0}: за ним нет работающего аудиоустройства (отключено или отсутствует), не переносится.
+ Встроенная звуковая карта не используется: USB-звук (гарнитуры, ЦАП, аудиоинтерфейсы) работает на ядре того USB-контроллера, к которому подключён.
+ USB {0}: {1}
+ мышь
+ клавиатура
+ камера
+ звук: {0}
+ нет мыши, клавиатуры, камеры или аудиоустройства по умолчанию
+ {0} делит USB-контроллер с мышью или клавиатурой, поэтому остаётся на ядре USB. Чтобы дать ему своё ядро, подключите его к порту контроллера без мыши и клавиатуры (см. список выше) и снова откройте эту раскладку.
+ {0} подключено к переднему разъёму корпуса: этот кабель проходит внутри корпуса и часто ловит помехи. Для игр используйте разъём на задней панели материнской платы.
+ Нагрузка, измеренная сейчас за 2 секунды (во время игры она другая):
+ CPU {0}: занят на {1:0}%, прерывания и DPC {2:0.0}%, {3:0} прерываний/с
+ CPU {0} уже занят на {1:0}%: его использует программа. Проверьте диспетчер задач перед применением.
+ {0}: отключено или не работает, исключено из раскладки.
+ {0}: нет сетевого подключения, исключено из раскладки.
+ Включить MSI для {0} (драйвер поддерживает, сейчас выключено)
+ {0} привязан только к {1}: контроллеры накопителей с несколькими очередями работают быстрее со стандартным распределением Windows. Сбросьте его привязку кнопкой восстановления или в редакторе.
+ Действует сейчас: {0}
+ Задано, но до перезагрузки Windows использует прежние ядра: {0}
+ Раскладка прерываний сброшена
+ Предложенная привязка прерываний исчезла на этих устройствах, обычно после обновления драйвера:
+{0}
+
+Откройте «Устройства» → «Привязка» и снова примените предложенную раскладку.
diff --git a/Resources/Maintenance.zh-CN.resx b/Resources/Maintenance.zh-CN.resx
index ab44404..e0c42d3 100644
--- a/Resources/Maintenance.zh-CN.resx
+++ b/Resources/Maintenance.zh-CN.resx
@@ -56,4 +56,44 @@
接通电源时完全关闭睡眠
接通电源时,Windows 不再允许待机状态 (S1–S3),睡眠键不执行任何操作,并从“开始”的电源菜单中隐藏“睡眠”。仅在从不让这台电脑睡眠时使用。可选,不包含在推荐项中。使用现代待机 (Modern Standby) 的电脑不使用 S1–S3,保留其自身的睡眠功能。还原会恢复原始值。需要重启。
Microsoft Defender(或你的杀毒软件)将 Tron 软件包识别为可能不需要的软件并已将其删除。TweakHub 从不添加杀毒软件排除项。如果你信任 Tron,请自行为此副本的 Data\Tools\Tron 文件夹和 C:\ProgramData\TweakHub-Tron-* 添加排除项,然后重试。
+ 按用途的建议布局
+ 建议的中断布局
+ 根据此 CPU 的拓扑,为显卡、USB、网络和音频各分配一个物理核心,避开核心 0。这是需要实测的建议布局:效果尚未得到证实。只更改关联性,MSI 和优先级保持不变。取消勾选不想更改的设备。
+ 显卡
+ USB
+ 网络
+ 音频
+ 混合架构 CPU:只使用 P 核。
+ 具有多个 L3 缓存(CCD)的 CPU:设备分配到没有 3D V-Cache 的 CCD;缓存相同时,分配到不含 CPU 0 的 CCD。
+ 此 CPU 只有 6 个或更少核心:网络和音频共用一个核心。
+ 不会更改网络 RSS:移动其起始位置会让 Windows 同时更改队列和处理器,无法精确还原。
+ 无法在此电脑上建议布局:存在多个处理器组、核心太少或无法读取拓扑。
+ 所有设备都已是建议的关联性。
+ 请使用“重启”而不是“关机”(快速启动会保留旧状态)。每次更新 GPU 驱动后请重新检查,驱动可能会重置这些值。请比较 1% 和 0.1% low 帧时间,而不只是平均 FPS。每个设备的还原按钮可撤销此更改。
+ {0}:CPU {1} – {2}
+ {0}:显卡的 HDMI/DisplayPort 音频,不移动(它不是游戏音频)。
+ {0}:其后没有可用的音频设备(已禁用或不存在),不移动。
+ 未使用板载声卡:USB 音频(耳机、DAC、音频接口)跟随其所连接 USB 控制器的核心。
+ USB {0}:{1}
+ 鼠标
+ 键盘
+ 摄像头
+ 音频:{0}
+ 没有鼠标、键盘、摄像头或默认音频设备
+ {0} 与鼠标或键盘共用 USB 控制器,因此留在 USB 核心上。若要为它分配独立核心,请将其插入没有鼠标和键盘的控制器端口(见上面的列表),然后重新打开此布局。
+ {0} 插在机箱前面板的插孔上:该线缆经过机箱内部,容易受到干扰。玩游戏时请使用主板背面的插孔。
+ 当前测量 2 秒的负载(游戏运行时会不同):
+ CPU {0}:占用 {1:0}%,中断和 DPC {2:0.0}%,每秒 {3:0} 次中断
+ CPU {0} 当前已占用 {1:0}%:有程序正在使用它。应用前请检查任务管理器。
+ {0}:已禁用或无法工作,不参与布局。
+ {0}:没有网络连接,不参与布局。
+ 为 {0} 开启 MSI(驱动支持,当前关闭)
+ {0} 仅绑定到 {1}:多队列存储控制器使用 Windows 默认分布更快。请用还原按钮或编辑器重置其亲和性。
+ 当前生效:{0}
+ 已设置,但重启前 Windows 仍使用之前的核心:{0}
+ 中断布局已被重置
+ 这些设备上建议的中断亲和性已消失,通常是在驱动更新之后:
+{0}
+
+请打开“设备”→“亲和性”,再次应用建议的布局。
diff --git a/Resources/Tools.es.resx b/Resources/Tools.es.resx
index d79243d..5219336 100644
--- a/Resources/Tools.es.resx
+++ b/Resources/Tools.es.resx
@@ -992,4 +992,7 @@ Esto puede deberse a permisos insuficientes o a que la aplicación de destino no
Escáner de vulnerabilidades basado en plantillas de ProjectDiscovery para tus propios servidores y aplicaciones web. Herramienta de línea de comandos: úsala solo en sistemas que estés autorizado a probar. Abre solo el repositorio oficial.
+
+ Editor offline de VBIOS NVIDIA (Blackwell; Ada, Ampere y Turing casi solo lectura). Guarda una ROM nueva con un manifiesto y nunca flashea: las ROM editadas se cargan con los cargadores Vix o mVolt+. Las ROM editadas no pasan la firma original: nunca las flashees con nvflash. Subir potencia, corriente o voltaje puede dañar el hardware; muchas funciones son experimentales, también en portátiles. Binarios sin firmar (SmartScreen puede avisar). Abre solo el repositorio oficial.
+
diff --git a/Resources/Tools.it.resx b/Resources/Tools.it.resx
index df2255f..cd38722 100644
--- a/Resources/Tools.it.resx
+++ b/Resources/Tools.it.resx
@@ -992,4 +992,7 @@ Questo potrebbe essere dovuto a permessi insufficienti o al fatto che l'applicaz
Scanner di vulnerabilità basato su template di ProjectDiscovery per i propri server e applicazioni web. Strumento da riga di comando: usalo solo su sistemi che sei autorizzato a testare. Apre solo il repository ufficiale.
+
+ Editor offline di VBIOS NVIDIA (Blackwell; Ada, Ampere e Turing quasi solo in lettura). Salva una ROM nuova con un manifest e non flasha mai: le ROM modificate si caricano con i loader Vix o mVolt+. Le ROM modificate non superano la firma originale: non flasharle mai con nvflash. Alzare potenza, corrente o tensione può danneggiare l'hardware; molte funzioni sono sperimentali, anche sui portatili. Binari non firmati (SmartScreen può avvisare). Apre solo il repository ufficiale.
+
diff --git a/Resources/Tools.ja.resx b/Resources/Tools.ja.resx
index 4b1f52c..309d838 100644
--- a/Resources/Tools.ja.resx
+++ b/Resources/Tools.ja.resx
@@ -992,4 +992,7 @@
ProjectDiscovery による、自分のサーバーや Web アプリ向けのテンプレート ベースの脆弱性スキャナーです。コマンドライン ツールです。テストを許可されたシステムでのみ使用してください。公式リポジトリのみを開きます。
+
+ オフラインの NVIDIA VBIOS エディター(Blackwell 対応。Ada、Ampere、Turing はほぼ読み取り専用)。新しい ROM とマニフェストを保存し、書き込みは行いません。編集した ROM は Vix ローダーまたは mVolt+ で読み込みます。編集した ROM は元の署名と一致しないため、nvflash で書き込まないでください。電力、電流、電圧を上げるとハードウェアが損傷する場合があります。多くの項目はノート PC を含め実験的です。バイナリは未署名です(SmartScreen の警告が出る場合があります)。公式リポジトリのみを開きます。
+
diff --git a/Resources/Tools.resx b/Resources/Tools.resx
index 577d824..64763f9 100644
--- a/Resources/Tools.resx
+++ b/Resources/Tools.resx
@@ -992,4 +992,7 @@ This may be due to insufficient permissions or the target application not being
Template-based vulnerability scanner from ProjectDiscovery for your own servers and web apps. Command-line tool; use it only on systems you are authorized to test. Opens only the official repository.
+
+ Offline NVIDIA VBIOS editor (Blackwell; Ada, Ampere and Turing mostly read-only). Saves a new ROM plus a manifest and never flashes: edited ROMs load through the Vix loaders or mVolt+. Edited ROMs fail the original signature, so never flash them with nvflash. Raising power, current or voltage can damage hardware; many fields are experimental, laptops included. Unsigned binaries (SmartScreen may warn). Opens the official repository only.
+
diff --git a/Resources/Tools.ru.resx b/Resources/Tools.ru.resx
index e7078bf..43d657e 100644
--- a/Resources/Tools.ru.resx
+++ b/Resources/Tools.ru.resx
@@ -992,4 +992,7 @@
Сканер уязвимостей на основе шаблонов от ProjectDiscovery для собственных серверов и веб-приложений. Инструмент командной строки: используйте его только на системах, которые вам разрешено тестировать. Открывает только официальный репозиторий.
+
+ Офлайн-редактор VBIOS NVIDIA (Blackwell; Ada, Ampere и Turing почти только для чтения). Сохраняет новый ROM с манифестом и никогда не прошивает: изменённые ROM загружаются через загрузчики Vix или mVolt+. Изменённые ROM не проходят проверку исходной подписи — никогда не прошивайте их через nvflash. Повышение мощности, тока или напряжения может повредить оборудование; многие параметры экспериментальные, в том числе на ноутбуках. Файлы не подписаны (SmartScreen может предупредить). Открывает только официальный репозиторий.
+
diff --git a/Resources/Tools.zh-CN.resx b/Resources/Tools.zh-CN.resx
index 37d6170..a5e810f 100644
--- a/Resources/Tools.zh-CN.resx
+++ b/Resources/Tools.zh-CN.resx
@@ -992,4 +992,7 @@
ProjectDiscovery 出品的基于模板的漏洞扫描器,用于检测你自己的服务器和 Web 应用。命令行工具,仅可在获得授权测试的系统上使用。仅打开官方仓库。
+
+ 离线 NVIDIA VBIOS 编辑器(支持 Blackwell;Ada、Ampere 和 Turing 基本只读)。保存为新的 ROM 和清单文件,从不刷写:修改后的 ROM 通过 Vix 加载器或 mVolt+ 加载。修改后的 ROM 与原始签名不符,切勿用 nvflash 刷写。提高功耗、电流或电压可能损坏硬件;许多项目仍为实验性功能,笔记本也是如此。程序未签名(SmartScreen 可能发出警告)。仅打开官方仓库。
+
diff --git a/Services/AudioEndpoints.cs b/Services/AudioEndpoints.cs
new file mode 100644
index 0000000..f08495e
--- /dev/null
+++ b/Services/AudioEndpoints.cs
@@ -0,0 +1,121 @@
+using System.Runtime.InteropServices;
+
+namespace TweakHub.Services;
+
+/// A default audio endpoint (playback or recording) and whether a front-panel jack of it is in use.
+internal sealed record AudioEndpoint(string Id, bool Capture, bool FrontJack);
+
+/// Default playback and recording devices from Core Audio; jack positions come from the driver (KSJACK_DESCRIPTION).
+internal static class AudioEndpoints
+{
+ public static IReadOnlyList ReadDefaults()
+ {
+ var result = new List();
+ try
+ {
+ var enumerator = (IMMDeviceEnumerator)new MMDeviceEnumerator();
+ foreach (var capture in new[] { false, true })
+ {
+ // eRender = 0, eCapture = 1; eConsole = 0, the role games use.
+ if (enumerator.GetDefaultAudioEndpoint(capture ? 1 : 0, 0, out var device) != 0 || device is null) continue;
+ if (device.GetId(out var id) != 0 || string.IsNullOrEmpty(id)) continue;
+ result.Add(new AudioEndpoint(id, capture, UsesFrontJack(device)));
+ }
+ }
+ catch (COMException) { /* No audio service or no devices: nothing to suggest. */ }
+ return result;
+ }
+
+ // eGeoLocFront = 2 and eGenLocPrimaryBox = 0: the jacks on the front of the case.
+ internal static bool IsFrontPanel(KsJackDescription jack) => jack.IsConnected != 0 && jack.GeoLocation == 2 && jack.GenLocation == 0;
+
+ private static bool UsesFrontJack(IMMDevice device)
+ {
+ try
+ {
+ var topologyId = typeof(IDeviceTopology).GUID;
+ if (device.Activate(ref topologyId, 1, IntPtr.Zero, out var topologyObject) != 0) return false;
+ var topology = (IDeviceTopology)topologyObject;
+ if (topology.GetConnector(0, out var connector) != 0 || connector.GetConnectedTo(out var other) != 0) return false;
+ var jackId = typeof(IKsJackDescription).GUID;
+ if (((IPart)other).Activate(1, ref jackId, out var jackObject) != 0) return false;
+ var jacks = (IKsJackDescription)jackObject;
+ if (jacks.GetJackCount(out var count) != 0) return false;
+ for (uint index = 0; index < count; index++)
+ if (jacks.GetJackDescription(index, out var jack) == 0 && IsFrontPanel(jack)) return true;
+ }
+ catch (Exception error) when (error is COMException or InvalidCastException) { /* Many USB drivers describe no jacks. */ }
+ return false;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct KsJackDescription
+ {
+ public uint ChannelMapping;
+ public uint Color;
+ public int ConnectionType;
+ public int GeoLocation;
+ public int GenLocation;
+ public int PortConnection;
+ public int IsConnected;
+ }
+
+ [ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
+ private class MMDeviceEnumerator;
+
+ [ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IMMDeviceEnumerator
+ {
+ [PreserveSig] int EnumAudioEndpoints(int dataFlow, int stateMask, out IntPtr devices);
+ [PreserveSig] int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice? device);
+ }
+
+ [ComImport, Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IMMDevice
+ {
+ [PreserveSig] int Activate(ref Guid iid, int clsCtx, IntPtr activationParams, [MarshalAs(UnmanagedType.IUnknown)] out object instance);
+ [PreserveSig] int OpenPropertyStore(int access, out IntPtr store);
+ [PreserveSig] int GetId([MarshalAs(UnmanagedType.LPWStr)] out string id);
+ }
+
+ [ComImport, Guid("2A07407E-6497-4A18-9787-32F79BD0D98F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IDeviceTopology
+ {
+ [PreserveSig] int GetConnectorCount(out uint count);
+ [PreserveSig] int GetConnector(uint index, out IConnector connector);
+ }
+
+ [ComImport, Guid("9C2C4058-23F5-41DE-877A-DF3AF236A09E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IConnector
+ {
+ [PreserveSig] int GetType(out int type);
+ [PreserveSig] int GetDataFlow(out int flow);
+ [PreserveSig] int ConnectTo(IConnector other);
+ [PreserveSig] int Disconnect();
+ [PreserveSig] int IsConnected(out int connected);
+ [PreserveSig] int GetConnectedTo(out IConnector other);
+ }
+
+ [ComImport, Guid("AE2DE0E4-5BCA-4F2D-AA46-5D13F8FDB3A9"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IPart
+ {
+ [PreserveSig] int GetName(out IntPtr name);
+ [PreserveSig] int GetLocalId(out uint id);
+ [PreserveSig] int GetGlobalId(out IntPtr id);
+ [PreserveSig] int GetPartType(out int type);
+ [PreserveSig] int GetSubType(out Guid subType);
+ [PreserveSig] int GetControlInterfaceCount(out uint count);
+ [PreserveSig] int GetControlInterface(uint index, out IntPtr control);
+ [PreserveSig] int EnumPartsIncoming(out IntPtr parts);
+ [PreserveSig] int EnumPartsOutgoing(out IntPtr parts);
+ [PreserveSig] int GetTopologyObject(out IntPtr topology);
+ [PreserveSig] int Activate(int clsContext, ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object instance);
+ }
+
+ [ComImport, Guid("4509F757-2D46-4637-8E62-CE7DB944F57B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IKsJackDescription
+ {
+ [PreserveSig] int GetJackCount(out uint count);
+ [PreserveSig] int GetJackDescription(uint index, out KsJackDescription description);
+ }
+}
diff --git a/Services/CpuLoad.cs b/Services/CpuLoad.cs
new file mode 100644
index 0000000..e4005ae
--- /dev/null
+++ b/Services/CpuLoad.cs
@@ -0,0 +1,44 @@
+using System.Runtime.InteropServices;
+
+namespace TweakHub.Services;
+
+/// Load of one logical CPU over a short sample: busy share, interrupt and DPC share, interrupts per second.
+internal sealed record CpuLoadSample(int Cpu, double BusyPercent, double InterruptDpcPercent, double InterruptsPerSecond);
+
+/// Per-CPU load from NtQuerySystemInformation: language independent, unlike performance counter names.
+internal static class CpuLoad
+{
+ [DllImport("ntdll.dll")]
+ private static extern int NtQuerySystemInformation(int infoClass, byte[] buffer, int length, out int returned);
+
+ private const int ProcessorPerformance = 8; // SystemProcessorPerformanceInformation
+ private const int EntrySize = 48; // Idle, Kernel, User, Dpc, Interrupt (100 ns) and InterruptCount
+
+ public static async Task> SampleAsync(TimeSpan duration)
+ {
+ if (!CpuTopology.Supported) return [];
+ var before = Read();
+ await Task.Delay(duration);
+ var after = Read();
+ return before is null || after is null ? [] : Compare(before, after, duration.TotalSeconds);
+ }
+
+ private static byte[]? Read()
+ {
+ var buffer = new byte[EntrySize * CpuTopology.Count];
+ return NtQuerySystemInformation(ProcessorPerformance, buffer, buffer.Length, out var returned) == 0 && returned == buffer.Length ? buffer : null;
+ }
+
+ internal static IReadOnlyList Compare(byte[] before, byte[] after, double seconds)
+ {
+ long Delta(int cpu, int field) => BitConverter.ToInt64(after, cpu * EntrySize + field * 8) - BitConverter.ToInt64(before, cpu * EntrySize + field * 8);
+ return Enumerable.Range(0, Math.Min(before.Length, after.Length) / EntrySize).Select(cpu =>
+ {
+ // Kernel time includes idle time.
+ var total = Math.Max(1, Delta(cpu, 1) + Delta(cpu, 2));
+ var interrupts = BitConverter.ToUInt32(after, cpu * EntrySize + 40) - BitConverter.ToUInt32(before, cpu * EntrySize + 40);
+ return new CpuLoadSample(cpu, 100.0 * (total - Delta(cpu, 0)) / total, 100.0 * (Delta(cpu, 3) + Delta(cpu, 4)) / total,
+ interrupts / Math.Max(0.001, seconds));
+ }).ToList();
+ }
+}
diff --git a/Services/CpuTopology.cs b/Services/CpuTopology.cs
index f0d8559..00fec2d 100644
--- a/Services/CpuTopology.cs
+++ b/Services/CpuTopology.cs
@@ -4,6 +4,9 @@ namespace TweakHub.Services;
internal sealed record LogicalCpu(int Index, int Core, byte EfficiencyClass);
+/// One level-3 cache: the group-0 CPUs that share it and its size.
+internal sealed record CacheGroup(ulong Mask, long Bytes);
+
internal static class CpuTopology
{
[DllImport("kernel32.dll")]
@@ -35,6 +38,40 @@ public static IReadOnlyList Read()
finally { Marshal.FreeHGlobal(pointer); }
}
+ /// Level-3 caches of group 0; several on dual-CCD CPUs, with the 3D V-Cache one larger.
+ public static IReadOnlyList ReadL3()
+ {
+ if (!Supported) return [];
+ var length = 0;
+ GetLogicalProcessorInformationEx(2, IntPtr.Zero, ref length); // RelationCache
+ if (length <= 0) return [];
+ var pointer = Marshal.AllocHGlobal(length);
+ try
+ {
+ if (!GetLogicalProcessorInformationEx(2, pointer, ref length)) return [];
+ var bytes = new byte[length];
+ Marshal.Copy(pointer, bytes, 0, length);
+ return ParseL3(bytes);
+ }
+ finally { Marshal.FreeHGlobal(pointer); }
+ }
+
+ internal static IReadOnlyList ParseL3(byte[] buffer)
+ {
+ var groups = new List();
+ for (var offset = 0; offset + 8 <= buffer.Length;)
+ {
+ var size = BitConverter.ToInt32(buffer, offset + 4);
+ if (size < 8 || size > buffer.Length - offset) return [];
+ // CACHE_RELATIONSHIP: Level at 8, CacheSize at 12, Type at 16 (0 = unified), GroupMask at 40.
+ if (BitConverter.ToInt32(buffer, offset) == 2 && size >= 56 && buffer[offset + 8] == 3
+ && BitConverter.ToInt32(buffer, offset + 16) == 0 && BitConverter.ToUInt16(buffer, offset + 48) == 0)
+ groups.Add(new CacheGroup(BitConverter.ToUInt64(buffer, offset + 40), BitConverter.ToUInt32(buffer, offset + 12)));
+ offset += size;
+ }
+ return groups;
+ }
+
internal static IReadOnlyList Parse(byte[] buffer)
{
var cpus = new List();
diff --git a/Services/DeviceService.cs b/Services/DeviceService.cs
index 690f072..fa0cde4 100644
--- a/Services/DeviceService.cs
+++ b/Services/DeviceService.cs
@@ -225,6 +225,41 @@ public sealed record UsageContext(bool RemoteDesktopOff, bool NoDialUpEntries, I
{
public IReadOnlyList OtherVpnUsers { get; init; } = [];
public IReadOnlyList UncheckedUsers { get; init; } = [];
+ public IReadOnlyList Nics { get; init; } = [];
+ /// HD Audio functions of a graphics card (HDMI/DP) that no default audio device uses.
+ public IReadOnlySet SpareGpuAudio { get; init; } = new HashSet();
+ /// Other HD Audio functions (the built-in sound card) that no default audio device uses.
+ public IReadOnlySet SpareOnboardAudio { get; init; } = new HashSet();
+
+ /// The connected card to keep: wired before wireless, then the fastest link.
+ public NicLink? BestNic => Nics.Where(nic => nic.Connected).OrderBy(nic => nic.Wireless).ThenByDescending(nic => nic.Speed).FirstOrDefault();
+ }
+
+ public sealed record NicLink(string Id, string Name, bool Connected, bool Wireless, long Speed);
+
+ ///
+ /// Adds the audio functions nobody listens to: an HD Audio function is in use when a default playback or recording
+ /// endpoint hangs below it. A GPU function is the one in the slot of a display device from the same vendor.
+ ///
+ public static UsageContext WithAudio(UsageContext context, IReadOnlyList devices, IReadOnlyCollection defaultEndpointIds)
+ {
+ if (defaultEndpointIds.Count == 0) return context;
+ var byId = devices.DistinctBy(device => device.Id, StringComparer.OrdinalIgnoreCase).ToDictionary(device => device.Id, StringComparer.OrdinalIgnoreCase);
+ var used = new HashSet(StringComparer.OrdinalIgnoreCase);
+ foreach (var id in defaultEndpointIds)
+ for (var current = byId.GetValueOrDefault(@"SWD\MMDEVAPI\" + id); current is not null && used.Add(current.Id);
+ current = byId.GetValueOrDefault(current.Parent)) { }
+ var displays = devices.Where(device => device.Class == "Display" && device.BusNumber >= 0 && device.Address >= 0).ToList();
+ bool OnGpu(PnpDeviceInfo controller) => displays.Any(display => display.BusNumber == controller.BusNumber
+ && display.Address >> 16 == controller.Address >> 16 && InterruptLayoutPlanner.PciVendor(display.Id) == InterruptLayoutPlanner.PciVendor(controller.Id));
+ var spare = devices.Where(device => device.Id.StartsWith(@"HDAUDIO\", StringComparison.OrdinalIgnoreCase) && device.Present
+ && !device.IsDisabled && !used.Contains(device.Id))
+ .Select(device => (device.Id, Gpu: byId.GetValueOrDefault(device.Parent) is { } controller && OnGpu(controller))).ToList();
+ return context with
+ {
+ SpareGpuAudio = spare.Where(item => item.Gpu).Select(item => item.Id).ToHashSet(StringComparer.OrdinalIgnoreCase),
+ SpareOnboardAudio = spare.Where(item => !item.Gpu).Select(item => item.Id).ToHashSet(StringComparer.OrdinalIgnoreCase)
+ };
}
internal const string UsageScript = """
@@ -244,7 +279,9 @@ public sealed record UsageContext(bool RemoteDesktopOff, bool NoDialUpEntries, I
if (Test-Path -LiteralPath $pbk) { @(Select-String -LiteralPath $pbk -Pattern '^\[').Count } else { 0 }
} catch [UnauthorizedAccessException] { -1 } catch { 0 }
[pscustomobject]@{ User = [string]$name; Entries = [int]$count } })
- $nics = @(Get-NetAdapter -Physical | ForEach-Object { [pscustomobject]@{ Id = [string]$_.PnPDeviceID; Connected = [int]$_.MediaConnectionState -eq 1 } })
+ # NdisPhysicalMedium 9 is native 802.11 (Wi-Fi); Speed is the link in bits per second.
+ $nics = @(Get-NetAdapter -Physical | ForEach-Object { [pscustomobject]@{ Id = [string]$_.PnPDeviceID; Name = [string]$_.InterfaceDescription
+ Connected = [int]$_.MediaConnectionState -eq 1; Wireless = [int]$_.NdisPhysicalMedium -eq 9; Speed = [long]$_.Speed } })
[pscustomobject]@{ RemoteDesktopOff = $rdp -eq 1; DialUpEntries = $entries; Others = $others; Nics = $nics } | ConvertTo-Json -Compress -Depth 3
""" + PowerShellService.AsciiJson;
@@ -269,7 +306,10 @@ List Users(Func entries) => others.Where(user => entries(Json
nics.Any(nic => JsonRead.Bool(nic, "Connected")))
{
OtherVpnUsers = Users(entries => entries > 0),
- UncheckedUsers = Users(entries => entries < 0)
+ UncheckedUsers = Users(entries => entries < 0),
+ Nics = nics.Select(nic => new NicLink(JsonRead.Text(nic, "Id"), JsonRead.Text(nic, "Name"), JsonRead.Bool(nic, "Connected"),
+ JsonRead.Bool(nic, "Wireless"), nic.TryGetProperty("Speed", out var speed) && speed.TryGetInt64(out var bits) ? bits : 0))
+ .Where(nic => nic.Id.Length > 0).ToList()
};
}
@@ -288,6 +328,11 @@ List Users(Func entries) => others.Where(user => entries(Json
: context.UncheckedUsers.Count > 0 ? "Devices:UnusedVpnUnchecked" : "Devices:UnusedVpn";
// Never the last way online: only when another physical card has a link.
if (context.DisconnectedNics.Contains(device.Id) && context.AnyNicConnected) return "Devices:UnusedNic";
+ // Two live connections: Windows may route games over the worse one.
+ if (context.Nics.Any(nic => nic.Connected && nic.Id.Equals(device.Id, StringComparison.OrdinalIgnoreCase))
+ && context.BestNic is { } best && !best.Id.Equals(device.Id, StringComparison.OrdinalIgnoreCase)) return "Devices:UnusedNicSlower";
+ if (context.SpareGpuAudio.Contains(device.Id)) return "Devices:UnusedGpuAudio";
+ if (context.SpareOnboardAudio.Contains(device.Id)) return "Devices:UnusedOnboardAudio";
return null;
}
@@ -296,12 +341,14 @@ List Users(Func entries) => others.Where(user => entries(Json
{
"Devices:UnusedVpnOtherUser" => L.Format(reason, string.Join(", ", context.OtherVpnUsers)),
"Devices:UnusedVpnUnchecked" => L.Format(reason, string.Join(", ", context.UncheckedUsers)),
+ "Devices:UnusedNicSlower" => L.Format(reason, context.BestNic?.Name ?? string.Empty),
_ => L.Get(reason)
};
- /// Ticked in the list unless it may still be needed: a card without a link today, another account's VPN.
+ /// Ticked in the list unless it may still be needed: a card without a link today, another account's VPN, a second connection, audio.
public static bool TickedByDefault(string reason) =>
- reason is not ("Devices:UnusedNic" or "Devices:UnusedVpnOtherUser" or "Devices:UnusedVpnUnchecked");
+ reason is not ("Devices:UnusedNic" or "Devices:UnusedVpnOtherUser" or "Devices:UnusedVpnUnchecked"
+ or "Devices:UnusedNicSlower" or "Devices:UnusedGpuAudio" or "Devices:UnusedOnboardAudio");
/// One elevated script for the whole list; each line reports OK|id or FAIL|id|reason so partial runs stay tracked.
internal static string BuildDisableManyScript(IEnumerable instanceIds) =>
diff --git a/Services/DeviceTree.cs b/Services/DeviceTree.cs
new file mode 100644
index 0000000..e6dd392
--- /dev/null
+++ b/Services/DeviceTree.cs
@@ -0,0 +1,117 @@
+using System.Runtime.InteropServices;
+
+namespace TweakHub.Services;
+
+/// A present device: its parent, setup class, container (one physical device) and display name.
+internal sealed record DeviceNode(string Id, string? Parent, Guid ClassGuid, Guid? Container, string Name);
+
+/// Reads the present device tree through cfgmgr32: fast and without PowerShell.
+internal static class DeviceTree
+{
+ [StructLayout(LayoutKind.Sequential)]
+ private struct DevPropKey(Guid fmtid, uint pid)
+ {
+ public Guid Fmtid = fmtid;
+ public uint Pid = pid;
+ }
+
+ private static readonly DevPropKey ClassGuidKey = new(new("a45c254e-df1c-4efd-8020-67d146a850e0"), 10);
+ private static readonly DevPropKey ContainerKey = new(new("8c7ed206-3f8a-4827-b3ab-ae9e1faefc6c"), 2);
+ private static readonly DevPropKey FriendlyNameKey = new(new("a45c254e-df1c-4efd-8020-67d146a850e0"), 14);
+ private static readonly DevPropKey DescriptionKey = new(new("a45c254e-df1c-4efd-8020-67d146a850e0"), 2);
+
+ [DllImport("cfgmgr32.dll", CharSet = CharSet.Unicode)]
+ private static extern int CM_Get_Device_ID_List_SizeW(out int length, string? filter, int flags);
+ [DllImport("cfgmgr32.dll", CharSet = CharSet.Unicode)]
+ private static extern int CM_Get_Device_ID_ListW(string? filter, char[] buffer, int length, int flags);
+ [DllImport("cfgmgr32.dll", CharSet = CharSet.Unicode)]
+ private static extern int CM_Locate_DevNodeW(out int devInst, string id, int flags);
+ [DllImport("cfgmgr32.dll")]
+ private static extern int CM_Get_Parent(out int parent, int devInst, int flags);
+ [DllImport("cfgmgr32.dll", CharSet = CharSet.Unicode)]
+ private static extern int CM_Get_Device_IDW(int devInst, char[] buffer, int length, int flags);
+ [DllImport("cfgmgr32.dll", CharSet = CharSet.Unicode)]
+ private static extern int CM_Get_DevNode_PropertyW(int devInst, in DevPropKey key, out int type, byte[]? buffer, ref int size, int flags);
+
+ [DllImport("cfgmgr32.dll")]
+ private static extern int CM_Get_First_Log_Conf(out IntPtr logConf, int devInst, int flags);
+ [DllImport("cfgmgr32.dll")]
+ private static extern int CM_Get_Next_Res_Des(out IntPtr resDes, IntPtr current, int forResource, out int resourceId, int flags);
+ [DllImport("cfgmgr32.dll")]
+ private static extern int CM_Get_Res_Des_Data_Size(out int size, IntPtr resDes, int flags);
+ [DllImport("cfgmgr32.dll")]
+ private static extern int CM_Get_Res_Des_Data(IntPtr resDes, byte[] buffer, int size, int flags);
+ [DllImport("cfgmgr32.dll")]
+ private static extern int CM_Free_Res_Des_Handle(IntPtr resDes);
+ [DllImport("cfgmgr32.dll")]
+ private static extern int CM_Free_Log_Conf_Handle(IntPtr logConf);
+
+ private const int FilterPresent = 0x100; // CM_GETIDLIST_FILTER_PRESENT
+
+ ///
+ /// Processor masks of the interrupts Windows allocated to a device in this boot (one per message; 0 means no specific
+ /// processor). They show the affinity Windows really uses, which changes only after a restart.
+ ///
+ public static IReadOnlyList AllocatedInterruptAffinities(string id)
+ {
+ var masks = new List();
+ // ALLOC_LOG_CONF = 2, ResType_IRQ = 4; IRQ_DES_64 keeps IRQD_Affinity at offset 16.
+ if (CM_Locate_DevNodeW(out var node, id, 0) != 0 || CM_Get_First_Log_Conf(out var conf, node, 2) != 0) return masks;
+ var current = conf;
+ while (CM_Get_Next_Res_Des(out var descriptor, current, 4, out _, 0) == 0)
+ {
+ if (CM_Get_Res_Des_Data_Size(out var size, descriptor, 0) == 0 && size >= 24)
+ {
+ var buffer = new byte[size];
+ if (CM_Get_Res_Des_Data(descriptor, buffer, size, 0) == 0) masks.Add(BitConverter.ToUInt64(buffer, 16));
+ }
+ if (current != conf) CM_Free_Res_Des_Handle(current);
+ current = descriptor;
+ }
+ if (current != conf) CM_Free_Res_Des_Handle(current);
+ CM_Free_Log_Conf_Handle(conf);
+ return masks;
+ }
+
+ public static IReadOnlyList Read()
+ {
+ var ids = List(FilterPresent) ?? List(0) ?? [];
+ var nodes = new List(ids.Length);
+ foreach (var id in ids)
+ {
+ // Locating with the normal flag fails for devices that are not present.
+ if (CM_Locate_DevNodeW(out var node, id, 0) != 0) continue;
+ string? parent = null;
+ if (CM_Get_Parent(out var parentNode, node, 0) == 0)
+ {
+ var buffer = new char[512];
+ if (CM_Get_Device_IDW(parentNode, buffer, buffer.Length, 0) == 0) parent = new string(buffer).TrimEnd('\0');
+ }
+ var classBytes = Property(node, ClassGuidKey);
+ var containerBytes = Property(node, ContainerKey);
+ var nameBytes = Property(node, FriendlyNameKey) ?? Property(node, DescriptionKey);
+ nodes.Add(new DeviceNode(id, parent,
+ classBytes is { Length: 16 } ? new Guid(classBytes) : Guid.Empty,
+ containerBytes is { Length: 16 } ? new Guid(containerBytes) : null,
+ nameBytes is null ? string.Empty : System.Text.Encoding.Unicode.GetString(nameBytes).TrimEnd('\0')));
+ }
+ return nodes;
+ }
+
+ private static string[]? List(int flags)
+ {
+ if (CM_Get_Device_ID_List_SizeW(out var length, null, flags) != 0 || length <= 0) return null;
+ var buffer = new char[length];
+ if (CM_Get_Device_ID_ListW(null, buffer, length, flags) != 0) return null;
+ return new string(buffer).Split('\0', StringSplitOptions.RemoveEmptyEntries);
+ }
+
+ private static byte[]? Property(int node, DevPropKey key)
+ {
+ var size = 0;
+ CM_Get_DevNode_PropertyW(node, key, out _, null, ref size, 0);
+ if (size <= 0) return null;
+ var buffer = new byte[size];
+ return CM_Get_DevNode_PropertyW(node, key, out _, buffer, ref size, 0) == 0 ? buffer : null;
+ }
+}
diff --git a/Services/InterruptLayout.cs b/Services/InterruptLayout.cs
new file mode 100644
index 0000000..6c6800a
--- /dev/null
+++ b/Services/InterruptLayout.cs
@@ -0,0 +1,196 @@
+namespace TweakHub.Services;
+
+public enum InterruptRole { Gpu, Usb, Network, Audio }
+
+/// One logical CPU (the first thread of a physical core) per role, or why none can be suggested.
+internal sealed record InterruptLayout(
+ IReadOnlyDictionary CpuByRole,
+ bool HybridPerformanceOnly = false,
+ bool CacheGroupChosen = false,
+ bool SharedNetworkAudio = false,
+ bool Unavailable = false);
+
+/// Why a device is left out: disabled or not working, a network card without a link, or audio that is not where gaming audio plays.
+public enum LayoutSkip { GpuAudio, AudioUnused, Disabled, NetDisconnected }
+
+/// A device of the layout and whether its affinity is already the suggested one.
+internal sealed record InterruptLayoutRow(InterruptDevice Device, InterruptRole Role, int Cpu, ulong Mask, bool AlreadySet,
+ LayoutSkip? Skip = null, string? AudioDevice = null);
+
+/// What is plugged into one USB controller: input devices, a camera and the default audio devices.
+internal sealed record UsbControllerUse(bool Mouse, bool Keyboard, bool Camera, IReadOnlyList Audio)
+{
+ public bool HasInput => Mouse || Keyboard;
+}
+
+internal static class InterruptLayoutPlanner
+{
+ private static readonly InterruptLayout None = new(new Dictionary(), Unavailable: true);
+
+ public static InterruptRole? RoleOf(InterruptDevice device) => device.IsHdAudio ? InterruptRole.Audio : device.Class switch
+ {
+ "Display" => InterruptRole.Gpu,
+ "USB" => InterruptRole.Usb,
+ "Net" => InterruptRole.Network,
+ "MEDIA" => InterruptRole.Audio,
+ _ => null
+ };
+
+ ///
+ /// Cores come from the live topology, never from fixed numbers: outside core 0, P-cores only on hybrid CPUs,
+ /// and with several L3 caches (dual CCD) the smaller one (no 3D V-Cache), or the one without CPU 0 when equal.
+ /// Up to 6 cores, network and audio share a core. Highest cores first: games favour the lowest ones.
+ ///
+ public static InterruptLayout Plan(IReadOnlyList cpus, IReadOnlyList caches)
+ {
+ if (cpus.Count == 0 || cpus.All(cpu => cpu.Index != 0)) return None;
+ var cores = cpus.GroupBy(cpu => cpu.Core).Select(core => core.OrderBy(cpu => cpu.Index).First()).ToList();
+ var coreZero = cpus.First(cpu => cpu.Index == 0).Core;
+ var candidates = cores.Where(cpu => cpu.Core != coreZero).ToList();
+ var classes = cpus.Select(cpu => cpu.EfficiencyClass).Distinct().ToList();
+ var hybrid = classes.Count > 1;
+ if (hybrid) candidates = candidates.Where(cpu => cpu.EfficiencyClass == classes.Max()).ToList();
+ var cacheChosen = false;
+ if (caches.Count > 1)
+ {
+ var smallest = caches.Min(cache => cache.Bytes);
+ var chosen = caches.All(cache => cache.Bytes == smallest)
+ ? caches.FirstOrDefault(cache => (cache.Mask & 1) == 0)
+ : caches.First(cache => cache.Bytes == smallest);
+ if (chosen is not null)
+ {
+ candidates = candidates.Where(cpu => (chosen.Mask >> cpu.Index & 1) == 1).ToList();
+ cacheChosen = true;
+ }
+ }
+ candidates = candidates.OrderByDescending(cpu => cpu.Index).ToList();
+ if (candidates.Count < 3) return None;
+ var shared = cores.Count <= 6 || candidates.Count < 4;
+ return new InterruptLayout(new Dictionary
+ {
+ [InterruptRole.Gpu] = candidates[0].Index,
+ [InterruptRole.Usb] = candidates[1].Index,
+ [InterruptRole.Network] = candidates[2].Index,
+ [InterruptRole.Audio] = candidates[shared ? 2 : 3].Index
+ }, hybrid, cacheChosen, shared);
+ }
+
+ ///
+ /// Rows of the layout. A USB controller that carries the default playback or recording device and no mouse or keyboard
+ /// gets the audio core, so the audio interface or DAC is not interrupted by input polling.
+ ///
+ public static IReadOnlyList Rows(InterruptLayout layout, IEnumerable devices,
+ IReadOnlyDictionary? usb = null)
+ {
+ var all = devices.ToList();
+ return all.Select(device => (Device: device, Role: RoleOf(device)))
+ .Where(item => item.Role is { } role && layout.CpuByRole.ContainsKey(role))
+ .Select(item =>
+ {
+ var role = item.Role!.Value;
+ string? audioDevice = null;
+ if (role == InterruptRole.Usb && usb?.GetValueOrDefault(item.Device.Id) is { Audio.Count: > 0, HasInput: false } use)
+ {
+ role = InterruptRole.Audio;
+ audioDevice = string.Join(", ", use.Audio);
+ }
+ var cpu = layout.CpuByRole[role];
+ var mask = 1UL << cpu;
+ // The mask is computed only for devices in use: never a disabled one or a card without a link.
+ var skip = !item.Device.Working ? LayoutSkip.Disabled
+ : role == InterruptRole.Network && item.Device.NetConnected == false ? LayoutSkip.NetDisconnected
+ : role == InterruptRole.Audio && audioDevice is null ? AudioSkip(item.Device, all) : null;
+ return new InterruptLayoutRow(item.Device, role, cpu, mask,
+ skip is null && item.Device.HasAffinity && item.Device.AffinityMask == mask, skip, audioDevice);
+ })
+ .ToList();
+ }
+
+ private static readonly Guid RootContainer = new("00000000-0000-0000-ffff-ffffffffffff");
+ private static readonly Guid MouseClass = new("4d36e96f-e325-11ce-bfc1-08002be10318");
+ private static readonly Guid KeyboardClass = new("4d36e96b-e325-11ce-bfc1-08002be10318");
+ private static readonly Guid ImageClass = new("6bdd1fc6-810f-11d0-bec7-08002be2092f");
+ private static readonly Guid CameraClass = new("ca3e7ab9-b4c3-4ae6-8251-579ef933890f");
+
+ ///
+ /// For each PCI USB controller (by instance ID), what hangs below it. Default audio endpoints are matched to their USB
+ /// device through the container ID; a headset's own media-key "keyboard" belongs to the audio device, not to input.
+ ///
+ public static IReadOnlyDictionary UsbUse(IReadOnlyList nodes, IEnumerable defaultAudioIds)
+ {
+ var byId = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (var node in nodes) byId.TryAdd(node.Id, node);
+ var audio = new Dictionary>();
+ foreach (var id in defaultAudioIds)
+ if (byId.GetValueOrDefault(@"SWD\MMDEVAPI\" + id) is { Container: { } container } endpoint && container != RootContainer && container != Guid.Empty)
+ {
+ var names = audio.TryGetValue(container, out var list) ? list : audio[container] = [];
+ if (!names.Contains(endpoint.Name)) names.Add(endpoint.Name);
+ }
+
+ string? Controller(DeviceNode node)
+ {
+ for (DeviceNode? current = node; current is not null; current = current.Parent is { } parent ? byId.GetValueOrDefault(parent) : null)
+ if (current.Id.StartsWith(@"PCI\", StringComparison.OrdinalIgnoreCase)) return current == node ? null : current.Id;
+ return null;
+ }
+
+ var uses = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (var node in nodes.Where(node => node.Id.StartsWith(@"USB\", StringComparison.OrdinalIgnoreCase) || node.Id.StartsWith(@"HID\", StringComparison.OrdinalIgnoreCase)))
+ {
+ if (Controller(node) is not { } controller) continue;
+ if (!uses.TryGetValue(controller, out var use)) uses[controller] = use = new UseBuilder();
+ if (node.Container is { } container && audio.TryGetValue(container, out var names))
+ use.Audio.AddRange(names.Where(name => !use.Audio.Contains(name)));
+ else
+ {
+ use.Mouse |= node.ClassGuid == MouseClass;
+ use.Keyboard |= node.ClassGuid == KeyboardClass;
+ use.Camera |= node.ClassGuid == ImageClass || node.ClassGuid == CameraClass;
+ }
+ }
+ return uses.ToDictionary(entry => entry.Key, entry => new UsbControllerUse(entry.Value.Mouse, entry.Value.Keyboard, entry.Value.Camera, entry.Value.Audio),
+ StringComparer.OrdinalIgnoreCase);
+ }
+
+ private sealed class UseBuilder
+ {
+ public bool Mouse, Keyboard, Camera;
+ public List Audio { get; } = [];
+ }
+
+ internal static string PciVendor(string instanceId) =>
+ System.Text.RegularExpressions.Regex.Match(instanceId, "VEN_([0-9A-F]{4})", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Groups[1].Value.ToUpperInvariant();
+
+ /// Storage controllers tied to a single CPU: multi-queue NVMe and AHCI work best with Windows' default spread.
+ public static IReadOnlyList PinnedStorage(IEnumerable devices) =>
+ devices.Where(device => device.Class is "SCSIAdapter" or "HDC" && device.HasAffinity
+ && System.Numerics.BitOperations.PopCount(device.AffinityMask) == 1).ToList();
+
+ /// Layout devices that support MSI but have it off; MSI is offered, never forced.
+ public static IReadOnlyList MsiCandidates(IEnumerable rows) =>
+ rows.Where(row => row.Skip is null && row.Device.MsiCapable && !row.Device.MsiEnabled).ToList();
+
+ ///
+ /// Whether the affinity a device has in the registry is the one Windows uses now: every allocated interrupt targets
+ /// exactly the mask. Before a restart Windows still reports the old targets (0 means no specific processor).
+ ///
+ public static bool IsActive(ulong mask, IReadOnlyList allocated) => allocated.Count > 0 && allocated.All(target => target == mask);
+
+ /// True when some audio device will actually get the audio core.
+ public static bool HasAudio(IEnumerable rows) => rows.Any(row => row.Role == InterruptRole.Audio && row.Skip is null);
+
+ ///
+ /// The HDMI/DP audio of a graphics card (same PCI slot and vendor as a display device) or a controller with no
+ /// working audio device behind it is not the gaming audio, which is then USB or elsewhere.
+ ///
+ private static LayoutSkip? AudioSkip(InterruptDevice audio, IReadOnlyList devices)
+ {
+ static string Vendor(InterruptDevice device) => PciVendor(device.Id);
+ if (audio is { Bus: { } bus, Address: { } address } && devices.Any(other => other.Class == "Display"
+ && other.Bus == bus && other.Address is { } otherAddress && otherAddress >> 16 == address >> 16
+ && Vendor(other) == Vendor(audio)))
+ return LayoutSkip.GpuAudio;
+ return audio.AudioInUse ? null : LayoutSkip.AudioUnused;
+ }
+}
diff --git a/Services/InterruptService.cs b/Services/InterruptService.cs
index 66e8f8c..ddb00a2 100644
--- a/Services/InterruptService.cs
+++ b/Services/InterruptService.cs
@@ -7,7 +7,8 @@ namespace TweakHub.Services;
public enum InterruptPriority { Undefined = 0, Low = 1, Normal = 2, High = 3 }
public sealed record InterruptDevice(string Id, string Name, string Class, bool MsiCapable, bool MsiEnabled, int? MessageLimit,
- InterruptPriority Priority, int Policy, ulong AffinityMask)
+ InterruptPriority Priority, int Policy, ulong AffinityMask, bool IsHdAudio = false,
+ int? Bus = null, int? Address = null, bool AudioInUse = true, bool Working = true, bool? NetConnected = null)
{
// IrqPolicySpecifiedProcessors: the device only interrupts the CPUs in AssignmentSetOverride.
public const int SpecifiedProcessorsPolicy = 4;
@@ -27,11 +28,23 @@ private InterruptService() { }
private const string ScanScript = """
$ErrorActionPreference = 'SilentlyContinue'
- @(Get-PnpDevice -PresentOnly | Where-Object { $_.InstanceId -like 'PCI\*' } | ForEach-Object {
+ $present = @(Get-PnpDevice -PresentOnly)
+ $links = @{}
+ Get-NetAdapter -Physical | ForEach-Object { $links[([string]$_.PnPDeviceID).ToUpperInvariant()] = [int]$_.MediaConnectionState -eq 1 }
+ # Controllers with at least one working HD Audio function behind them.
+ $working = @($present | Where-Object { $_.InstanceId -like 'HDAUDIO\*' -and $_.Status -eq 'OK' } | ForEach-Object {
+ ([string](Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName DEVPKEY_Device_Parent).Data).ToUpperInvariant() })
+ @($present | Where-Object { $_.InstanceId -like 'PCI\*' } | ForEach-Object {
$base = "HKLM:\SYSTEM\CurrentControlSet\Enum\$($_.InstanceId)\Device Parameters\Interrupt Management"
$msi = Get-ItemProperty -LiteralPath "$base\MessageSignaledInterruptProperties"
$affinity = Get-ItemProperty -LiteralPath "$base\Affinity Policy"
+ $hd = [bool](@($_.CompatibleID) -match '&CC_0403')
+ $slot = @($null, $null)
+ if ($hd -or $_.Class -eq 'Display') { $slot = @(Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName DEVPKEY_Device_BusNumber, DEVPKEY_Device_Address) }
[pscustomobject]@{ Id = [string]$_.InstanceId; Name = [string]$_.FriendlyName; Class = [string]$_.Class
+ HdAudio = $hd; Bus = $slot[0].Data; Address = $slot[1].Data
+ AudioInUse = (-not $hd) -or ($working -contains $_.InstanceId.ToUpperInvariant())
+ Working = $_.Status -eq 'OK'; NetConnected = $links[$_.InstanceId.ToUpperInvariant()]
MsiCapable = [bool]$msi; Msi = $msi.MSISupported; Limit = $msi.MessageNumberLimit
Priority = $affinity.DevicePriority; Policy = $affinity.DevicePolicy
Mask = $(if ($affinity.AssignmentSetOverride) { [Convert]::ToBase64String([byte[]]$affinity.AssignmentSetOverride) }) }
@@ -58,7 +71,10 @@ internal static List ParseDevices(string json)
JsonRead.Text(item, "Id"), JsonRead.Text(item, "Name"), JsonRead.Text(item, "Class"),
JsonRead.Bool(item, "MsiCapable"), JsonRead.Int(item, "Msi") == 1, JsonRead.Int(item, "Limit"),
(InterruptPriority)Math.Clamp(JsonRead.Int(item, "Priority") ?? 0, 0, 3), JsonRead.Int(item, "Policy") ?? 0,
- BitConverter.ToUInt64(bytes));
+ BitConverter.ToUInt64(bytes), JsonRead.Bool(item, "HdAudio"),
+ JsonRead.Int(item, "Bus"), JsonRead.Int(item, "Address"), JsonRead.Bool(item, "AudioInUse", fallback: true),
+ JsonRead.Bool(item, "Working", fallback: true),
+ item.TryGetProperty("NetConnected", out var link) && link.ValueKind is JsonValueKind.True or JsonValueKind.False ? link.GetBoolean() : null);
})
// Bridges and root ports have no driver-level interrupt settings worth changing.
.Where(device => device.Id.Length > 0 && (device.MsiCapable || device.Class is not "System"))
@@ -107,6 +123,39 @@ public Task RestoreAsync(InterruptDevice device, bool affinityOnly = false
RegistryService.Instance.RestoreValuesAsync(ManagedValues(device.Id).Skip(affinityOnly ? 2 : 0).Take(2)
.Where(change => RegistryService.Instance.HasBackup(change.KeyPath, change.ValueName)).ToList());
+ /// Writes several affinities, and MSI on the devices given, with one backup and one elevation; priority is not touched.
+ public Task ApplyAffinitiesAsync(IReadOnlyCollection<(InterruptDevice Device, ulong Mask)> items,
+ IReadOnlyCollection? enableMsi = null) =>
+ items.Count + (enableMsi?.Count ?? 0) == 0 || items.Any(item => !CanAssign(item.Mask))
+ ? Task.FromResult(false)
+ : RegistryService.Instance.ApplyValuesWithBackupAsync(
+ items.SelectMany(item => BuildChanges(item.Device, null, null, item.Mask))
+ .Concat((enableMsi ?? []).Where(device => device.MsiCapable).SelectMany(device => BuildChanges(device, true, null, null))).ToList());
+
+ ///
+ /// Devices whose layout affinity is back to the original value while TweakHub's backup is still there: a driver update
+ /// (often the GPU one) recreated the device key. Only present PCI devices, by display name.
+ ///
+ internal static IReadOnlyList ResetAffinityDevices(IReadOnlyList nodes)
+ {
+ var present = nodes.DistinctBy(node => node.Id, StringComparer.OrdinalIgnoreCase)
+ .ToDictionary(node => node.Id, node => node.Name, StringComparer.OrdinalIgnoreCase);
+ return RegistryService.Instance.BackedUpValues
+ .Where(value => value.ValueName == "DevicePolicy")
+ .Select(value => (value.KeyPath, Id: AffinityKeyDevice(value.KeyPath)))
+ .Where(item => item.Id is not null && present.ContainsKey(item.Id) && RegistryService.Instance.IsAtOriginal(item.KeyPath, "DevicePolicy") == true)
+ .Select(item => present[item.Id!] is { Length: > 0 } name ? name : item.Id!)
+ .ToList();
+ }
+
+ internal static string? AffinityKeyDevice(string keyPath)
+ {
+ var match = System.Text.RegularExpressions.Regex.Match(keyPath,
+ @"^HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Enum\\(PCI\\[^\\]+\\[^\\]+)\\Device Parameters\\Interrupt Management\\Affinity Policy$",
+ System.Text.RegularExpressions.RegexOptions.IgnoreCase);
+ return match.Success ? match.Groups[1].Value : null;
+ }
+
internal static string FormatMask(ulong mask) => string.Join(", ",
Enumerable.Range(0, 64).Where(cpu => (mask >> cpu & 1) == 1).Select(cpu => $"CPU {cpu}"));
}
diff --git a/Services/RegistryService.cs b/Services/RegistryService.cs
index 461c457..5738bde 100644
--- a/Services/RegistryService.cs
+++ b/Services/RegistryService.cs
@@ -168,6 +168,14 @@ public async Task RestoreValuesAsync(IReadOnlyCollectionTrue when a backed-up value is back to its original state, false when it differs, null without a backup.
+ internal bool? IsAtOriginal(string keyPath, string valueName)
+ {
+ RegistryBackup? backup;
+ lock (_lock) backup = _backups.GetValueOrDefault(BackupKey(keyPath, valueName));
+ return backup is null ? null : IsOriginal(backup);
+ }
+
private bool IsOriginal(RegistryBackup backup) => backup.Existed
? ValuesEqual(GetRegistryValue(backup.KeyPath, backup.ValueName), Decode(backup))
: !RegistryValueExists(backup.KeyPath, backup.ValueName);
diff --git a/Services/ShortcutService.cs b/Services/ShortcutService.cs
index d4d1ef1..fb551e5 100644
--- a/Services/ShortcutService.cs
+++ b/Services/ShortcutService.cs
@@ -120,6 +120,7 @@ private void LoadExternalTools()
// GPU and display
new ExternalTool { Name = "mVolt", Description = L.Get("Tools:DescriptionMVolt"), Category = "GPU & Display", DownloadUrl = "https://github.com/b00nz/mVolt" },
+ new ExternalTool { Name = "NVIDIA VBIOS Vix Editor", Description = L.Get("Tools:DescriptionVixEditor"), Category = "GPU & Display", DownloadUrl = "https://github.com/Panchovix/nvidia-vbios-vix-editor" },
new ExternalTool { Name = "GPU-Z", Description = L.Get("Tools:DescriptionGPUInformationSensorsAndValidation"), Category = "GPU & Display", WingetId = "TechPowerUp.GPU-Z" },
new ExternalTool { Name = "MSI Afterburner", Description = L.Get("Tools:DescriptionGPUMonitoringFanCurvesAndOverclockingControls"), Category = "GPU & Display", WingetId = "Guru3D.Afterburner" },
new ExternalTool { Name = "RivaTuner Statistics Server", Description = L.Get("Tools:DescriptionFrameRateLimitingAndInGamePerformance"), Category = "GPU & Display", WingetId = "Guru3D.RTSS" },
diff --git a/TweakHub.Tests/InterruptLayoutTests.cs b/TweakHub.Tests/InterruptLayoutTests.cs
new file mode 100644
index 0000000..9bbc19c
--- /dev/null
+++ b/TweakHub.Tests/InterruptLayoutTests.cs
@@ -0,0 +1,259 @@
+using NUnit.Framework;
+using TweakHub.Services;
+
+namespace TweakHub.Tests;
+
+public class InterruptLayoutTests
+{
+ /// CPU numbers in core order, like GetLogicalProcessorInformationEx reports them.
+ private static List Cpus(int cores, int smt = 2, Func? efficiency = null) =>
+ Enumerable.Range(0, cores).SelectMany(core => Enumerable.Range(0, smt)
+ .Select(thread => new LogicalCpu(core * smt + thread, core, efficiency?.Invoke(core) ?? 0))).ToList();
+
+ private static ulong Mask(int from, int count) => Enumerable.Range(from, count).Aggregate(0UL, (mask, cpu) => mask | 1UL << cpu);
+
+ [Test]
+ public void EightCoresGetOneFirstThreadPerRoleOutsideCoreZero()
+ {
+ var layout = InterruptLayoutPlanner.Plan(Cpus(8), []);
+ Assert.That(layout.Unavailable, Is.False);
+ Assert.That(layout.CpuByRole[InterruptRole.Gpu], Is.EqualTo(14));
+ Assert.That(layout.CpuByRole[InterruptRole.Usb], Is.EqualTo(12));
+ Assert.That(layout.CpuByRole[InterruptRole.Network], Is.EqualTo(10));
+ Assert.That(layout.CpuByRole[InterruptRole.Audio], Is.EqualTo(8));
+ Assert.That(layout.SharedNetworkAudio, Is.False);
+ }
+
+ [Test]
+ public void SixCoresOrFewerShareNetworkAndAudio()
+ {
+ var layout = InterruptLayoutPlanner.Plan(Cpus(6), []);
+ Assert.That(layout.SharedNetworkAudio, Is.True);
+ Assert.That(layout.CpuByRole[InterruptRole.Audio], Is.EqualTo(layout.CpuByRole[InterruptRole.Network]));
+ var four = InterruptLayoutPlanner.Plan(Cpus(4, smt: 1), []);
+ Assert.That(four.CpuByRole.Values, Has.None.EqualTo(0));
+ Assert.That(InterruptLayoutPlanner.Plan(Cpus(2), []).Unavailable, Is.True);
+ Assert.That(InterruptLayoutPlanner.Plan([], []).Unavailable, Is.True);
+ }
+
+ [Test]
+ public void HybridUsesOnlyPerformanceCores()
+ {
+ // 8 P-cores with SMT (CPU 0-15, class 1), then 16 E-cores (class 0).
+ var cpus = Cpus(8, efficiency: _ => 1)
+ .Concat(Enumerable.Range(16, 16).Select(cpu => new LogicalCpu(cpu, cpu - 8, 0))).ToList();
+ var layout = InterruptLayoutPlanner.Plan(cpus, []);
+ Assert.That(layout.HybridPerformanceOnly, Is.True);
+ Assert.That(layout.CpuByRole.Values, Has.All.InRange(2, 15));
+ }
+
+ [Test]
+ public void DualCcdPicksTheCcdWithoutVCacheOrWithoutCpuZero()
+ {
+ var x3d = InterruptLayoutPlanner.Plan(Cpus(16), [new(Mask(0, 16), 96 << 20), new(Mask(16, 16), 32 << 20)]);
+ Assert.That(x3d.CacheGroupChosen, Is.True);
+ Assert.That(x3d.CpuByRole[InterruptRole.Gpu], Is.EqualTo(30));
+ Assert.That(x3d.CpuByRole.Values, Has.All.GreaterThanOrEqualTo(16));
+
+ var swapped = InterruptLayoutPlanner.Plan(Cpus(16), [new(Mask(0, 16), 32 << 20), new(Mask(16, 16), 96 << 20)]);
+ Assert.That(swapped.CpuByRole.Values, Has.All.InRange(2, 15));
+
+ var equal = InterruptLayoutPlanner.Plan(Cpus(16), [new(Mask(0, 16), 32 << 20), new(Mask(16, 16), 32 << 20)]);
+ Assert.That(equal.CpuByRole.Values, Has.All.GreaterThanOrEqualTo(16));
+ }
+
+ [Test]
+ public void RolesComeFromTheClassAndHdAudioFromTheClassCode()
+ {
+ static InterruptDevice Device(string cls, bool hdAudio = false, int policy = 0, ulong mask = 0) =>
+ new($@"PCI\{cls}", cls, cls, true, false, null, InterruptPriority.Undefined, policy, mask, hdAudio);
+ Assert.That(InterruptLayoutPlanner.RoleOf(Device("Display")), Is.EqualTo(InterruptRole.Gpu));
+ Assert.That(InterruptLayoutPlanner.RoleOf(Device("USB")), Is.EqualTo(InterruptRole.Usb));
+ Assert.That(InterruptLayoutPlanner.RoleOf(Device("Net")), Is.EqualTo(InterruptRole.Network));
+ Assert.That(InterruptLayoutPlanner.RoleOf(Device("System", hdAudio: true)), Is.EqualTo(InterruptRole.Audio));
+ Assert.That(InterruptLayoutPlanner.RoleOf(Device("System")), Is.Null);
+
+ var layout = InterruptLayoutPlanner.Plan(Cpus(8), []);
+ var rows = InterruptLayoutPlanner.Rows(layout, [Device("Display", policy: 4, mask: 1UL << 14), Device("Net"), Device("System")]);
+ Assert.That(rows, Has.Count.EqualTo(2));
+ Assert.That(rows[0].AlreadySet, Is.True);
+ Assert.That(rows[1].AlreadySet, Is.False);
+ Assert.That(rows[1].Mask, Is.EqualTo(1UL << 10));
+ }
+
+ [Test]
+ public void LayoutWritesOnlyAffinityNeverMsiOrPriority()
+ {
+ var device = new InterruptDevice(@"PCI\GPU", "GPU", "Display", true, true, 1, InterruptPriority.High, 0, 0);
+ var changes = InterruptService.BuildChanges(device, null, null, 1UL << 14);
+ Assert.That(changes.Select(change => change.ValueName), Is.EquivalentTo(new[] { "DevicePolicy", "AssignmentSetOverride" }));
+ }
+
+ [Test]
+ public void ScanReadsTheHdAudioClassCode()
+ {
+ var device = InterruptService.ParseDevices("""
+ [{"Id":"PCI\\VEN_1002&DEV_AB30\\4&1","Name":"HD Audio","Class":"System","HdAudio":true,"MsiCapable":true,"Msi":1}]
+ """).Single();
+ Assert.That(device.IsHdAudio, Is.True);
+ Assert.That(device.AudioInUse, Is.True, "older scans without the field keep the device");
+ }
+
+ [Test]
+ public void AudioCoreSkipsGpuAudioAndUnusedControllers()
+ {
+ static InterruptDevice Audio(string id, int address, bool inUse = true) =>
+ new(id, id, "System", true, true, null, InterruptPriority.Undefined, 0, 0, true, 48, address, inUse);
+ var gpu = new InterruptDevice(@"PCI\VEN_1002&DEV_73A5\1", "GPU", "Display", true, true, 1, InterruptPriority.Undefined, 0, 0,
+ Bus: 48, Address: 0);
+ var layout = InterruptLayoutPlanner.Plan(Cpus(8), []);
+ IReadOnlyList Rows(InterruptDevice audio) => InterruptLayoutPlanner.Rows(layout, [gpu, audio]);
+
+ // Radeon HDMI/DP audio: function 1 of the GPU slot, same vendor.
+ var hdmi = Rows(Audio(@"PCI\VEN_1002&DEV_AB28\2", 1));
+ Assert.That(hdmi[1].Skip, Is.EqualTo(LayoutSkip.GpuAudio));
+ Assert.That(InterruptLayoutPlanner.HasAudio(hdmi), Is.False);
+
+ // APU: onboard HD Audio shares the slot but not the vendor.
+ var onboard = Rows(Audio(@"PCI\VEN_1022&DEV_15E3\3", 6));
+ Assert.That(onboard[1].Skip, Is.Null);
+ Assert.That(InterruptLayoutPlanner.HasAudio(onboard), Is.True);
+
+ // Realtek disabled by a user who plays with a USB DAC.
+ var unused = Rows(Audio(@"PCI\VEN_1022&DEV_1487\4", 0x10003, inUse: false));
+ Assert.That(unused[1].Skip, Is.EqualTo(LayoutSkip.AudioUnused));
+ Assert.That(unused[1].AlreadySet, Is.False);
+ }
+
+ [Test]
+ public void UsbControllerWithTheDacAndNoInputGetsTheAudioCore()
+ {
+ var mouse = new Guid("4d36e96f-e325-11ce-bfc1-08002be10318");
+ var keyboard = new Guid("4d36e96b-e325-11ce-bfc1-08002be10318");
+ var media = new Guid("4d36e96c-e325-11ce-bfc1-08002be10318");
+ Guid dac = Guid.NewGuid(), headset = Guid.NewGuid(), receiver = Guid.NewGuid();
+ DeviceNode Node(string id, string parent, Guid cls = default, Guid? container = null, string name = "") => new(id, parent, cls, container, name);
+ var nodes = new List
+ {
+ Node(@"PCI\USB1", @"PCI\ROOT"), Node(@"USB\ROOT_HUB30\1", @"PCI\USB1"),
+ Node(@"USB\VID_06CB\DAC", @"USB\ROOT_HUB30\1", media, dac),
+ // A headset's media keys show up as a keyboard of the same physical device: not input.
+ Node(@"PCI\USB2", @"PCI\ROOT"), Node(@"USB\ROOT_HUB30\2", @"PCI\USB2"),
+ Node(@"USB\VID_1111\HEADSET", @"USB\ROOT_HUB30\2", media, headset),
+ Node(@"HID\VID_1111\KEYS", @"USB\VID_1111\HEADSET", keyboard, headset),
+ Node(@"PCI\USB3", @"PCI\ROOT"), Node(@"USB\ROOT_HUB30\3", @"PCI\USB3"),
+ Node(@"USB\VID_046D\RECEIVER", @"USB\ROOT_HUB30\3", default, receiver),
+ Node(@"HID\VID_046D\MOUSE", @"USB\VID_046D\RECEIVER", mouse, receiver),
+ Node(@"USB\VID_2708\EVO8", @"USB\ROOT_HUB30\3", media, Guid.NewGuid()),
+ Node(@"SWD\MMDEVAPI\{0.0.0.00000000}.{dac}", @"SWD\MMDEVAPI", default, dac, "Headphones (DAC)"),
+ Node(@"SWD\MMDEVAPI\{0.0.1.00000000}.{mic}", @"SWD\MMDEVAPI", default, headset, "Mic (Headset)"),
+ };
+ var usb = InterruptLayoutPlanner.UsbUse(nodes, ["{0.0.0.00000000}.{DAC}", "{0.0.1.00000000}.{mic}"]);
+ Assert.That(usb[@"PCI\USB1"], Is.EqualTo(usb[@"PCI\USB1"] with { Mouse = false, Keyboard = false }));
+ Assert.That(usb[@"PCI\USB1"].Audio, Is.EqualTo(new[] { "Headphones (DAC)" }));
+ Assert.That(usb[@"PCI\USB2"].HasInput, Is.False);
+ Assert.That(usb[@"PCI\USB3"].Mouse, Is.True);
+ Assert.That(usb[@"PCI\USB3"].Audio, Is.Empty, "the EVO8 is not a default device here");
+
+ static InterruptDevice Controller(string id) => new(id, "xHCI", "USB", true, true, 8, InterruptPriority.Undefined, 0, 0);
+ var layout = InterruptLayoutPlanner.Plan(Cpus(8), []);
+ var rows = InterruptLayoutPlanner.Rows(layout, [Controller(@"PCI\USB1"), Controller(@"PCI\USB3")], usb);
+ Assert.That(rows[0].Role, Is.EqualTo(InterruptRole.Audio));
+ Assert.That(rows[0].Cpu, Is.EqualTo(layout.CpuByRole[InterruptRole.Audio]));
+ Assert.That(rows[0].AudioDevice, Is.EqualTo("Headphones (DAC)"));
+ Assert.That(rows[1].Role, Is.EqualTo(InterruptRole.Usb));
+ Assert.That(InterruptLayoutPlanner.HasAudio(rows), Is.True);
+
+ // The same DAC next to the mouse stays on the USB core.
+ var shared = InterruptLayoutPlanner.Rows(layout, [Controller(@"PCI\USB1")],
+ new Dictionary { [@"PCI\USB1"] = new(true, false, false, ["Headphones (DAC)"]) });
+ Assert.That(shared[0].Role, Is.EqualTo(InterruptRole.Usb));
+ }
+
+ [Test]
+ public void DisabledDevicesAndCardsWithoutALinkGetNoMask()
+ {
+ static InterruptDevice Nic(string id, bool working = true, bool? link = true) =>
+ new(id, id, "Net", true, true, 4, InterruptPriority.Undefined, 0, 0, Working: working, NetConnected: link);
+ var layout = InterruptLayoutPlanner.Plan(Cpus(8), []);
+ var rows = InterruptLayoutPlanner.Rows(layout, [Nic(@"PCI\ETH2"), Nic(@"PCI\ETH1", working: false, link: null), Nic(@"PCI\WIFI", link: false),
+ new InterruptDevice(@"PCI\USB", "USB", "USB", true, true, 8, InterruptPriority.Undefined, 0, 0, Working: false)]);
+ Assert.That(rows.Select(row => row.Skip), Is.EqualTo(new LayoutSkip?[] { null, LayoutSkip.Disabled, LayoutSkip.NetDisconnected, LayoutSkip.Disabled }));
+ Assert.That(rows.Count(row => row.Skip is null && !row.AlreadySet), Is.EqualTo(1));
+ }
+
+ [Test]
+ public void MsiStoragePinsAndActiveAffinity()
+ {
+ static InterruptDevice Device(string cls, bool msi, int policy = 0, ulong mask = 0) =>
+ new($@"PCI\{cls}", cls, cls, true, msi, 4, InterruptPriority.Undefined, policy, mask);
+ var layout = InterruptLayoutPlanner.Plan(Cpus(8), []);
+ var rows = InterruptLayoutPlanner.Rows(layout, [Device("Net", msi: false), Device("Display", msi: true)]);
+ Assert.That(InterruptLayoutPlanner.MsiCandidates(rows).Select(row => row.Device.Class), Is.EqualTo(new[] { "Net" }));
+
+ Assert.That(InterruptLayoutPlanner.PinnedStorage([Device("SCSIAdapter", true, 4, 1UL << 3), Device("SCSIAdapter", true, 5),
+ Device("HDC", true, 4, 0b1100), Device("Net", true, 4, 1)]).Count, Is.EqualTo(1));
+
+ // Windows reports the allocated targets; before a restart they are still the old ones (0 = no specific CPU).
+ Assert.That(InterruptLayoutPlanner.IsActive(1UL << 14, [1UL << 14, 1UL << 14]), Is.True);
+ Assert.That(InterruptLayoutPlanner.IsActive(1UL << 14, [0]), Is.False);
+ Assert.That(InterruptLayoutPlanner.IsActive(1UL << 14, []), Is.False);
+ }
+
+ [Test]
+ public void ResetCheckFindsTheDeviceOfAnAffinityKey()
+ {
+ Assert.That(InterruptService.AffinityKeyDevice(
+ @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\PCI\VEN_1002&DEV_73A5&SUBSYS_05041043&REV_C0\6&e5c6fd0&0&00000019\Device Parameters\Interrupt Management\Affinity Policy"),
+ Is.EqualTo(@"PCI\VEN_1002&DEV_73A5&SUBSYS_05041043&REV_C0\6&e5c6fd0&0&00000019"));
+ Assert.That(InterruptService.AffinityKeyDevice(@"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\X"), Is.Null);
+ }
+
+ [Test]
+ public void FrontPanelMeansAPluggedJackOnTheFrontOfTheCase()
+ {
+ static AudioEndpoints.KsJackDescription Jack(int geo, int gen, int connected) => new() { GeoLocation = geo, GenLocation = gen, IsConnected = connected };
+ Assert.That(AudioEndpoints.IsFrontPanel(Jack(2, 0, 1)), Is.True);
+ Assert.That(AudioEndpoints.IsFrontPanel(Jack(1, 0, 1)), Is.False, "rear panel");
+ Assert.That(AudioEndpoints.IsFrontPanel(Jack(2, 0, 0)), Is.False, "nothing plugged in");
+ Assert.That(AudioEndpoints.IsFrontPanel(Jack(2, 2, 1)), Is.False, "front of a separate box, such as a monitor");
+ }
+
+ [Test]
+ public void CpuLoadComesFromTimeDeltas()
+ {
+ static byte[] Entry(long idle, long kernel, long user, long dpc, long interrupt, uint count)
+ {
+ var entry = new byte[48];
+ foreach (var (value, index) in new[] { idle, kernel, user, dpc, interrupt }.Select((value, index) => (value, index)))
+ BitConverter.GetBytes(value).CopyTo(entry, index * 8);
+ BitConverter.GetBytes(count).CopyTo(entry, 40);
+ return entry;
+ }
+ var load = CpuLoad.Compare(Entry(0, 0, 0, 0, 0, 0), Entry(750, 900, 100, 10, 10, 2000), 2).Single();
+ Assert.That(load.BusyPercent, Is.EqualTo(25).Within(0.01));
+ Assert.That(load.InterruptDpcPercent, Is.EqualTo(2).Within(0.01));
+ Assert.That(load.InterruptsPerSecond, Is.EqualTo(1000));
+ }
+
+ [Test]
+ public void ParsesUnifiedLevelThreeCaches()
+ {
+ static byte[] Record(byte level, uint bytes, ulong mask)
+ {
+ var record = new byte[56];
+ BitConverter.GetBytes(2).CopyTo(record, 0); // RelationCache
+ BitConverter.GetBytes(56).CopyTo(record, 4);
+ record[8] = level;
+ BitConverter.GetBytes(bytes).CopyTo(record, 12);
+ BitConverter.GetBytes((ushort)1).CopyTo(record, 38);
+ BitConverter.GetBytes(mask).CopyTo(record, 40);
+ return record;
+ }
+ var buffer = Record(2, 1 << 20, 0x3).Concat(Record(3, 32u << 20, 0xffff)).Concat(Record(3, 96u << 20, 0xffff0000)).ToArray();
+ var caches = CpuTopology.ParseL3(buffer);
+ Assert.That(caches, Has.Count.EqualTo(2));
+ Assert.That(caches[0], Is.EqualTo(new CacheGroup(0xffff, 32 << 20)));
+ Assert.That(caches[1].Bytes, Is.EqualTo(96 << 20));
+ }
+}
diff --git a/TweakHub.Tests/LocalizationTests.cs b/TweakHub.Tests/LocalizationTests.cs
index 979b99c..b48c717 100644
--- a/TweakHub.Tests/LocalizationTests.cs
+++ b/TweakHub.Tests/LocalizationTests.cs
@@ -48,7 +48,7 @@ public void TranslationHasSameKeysAndPlaceholders(string domain, string culture)
"UI:MainWindowTweakHubWindows11TweakUtility", "Scripts:PowerShellFilter", "Scripts:ctt_winutil_Name", "Scripts:CmdBatch",
"Security:SafetyScannerTitle", "Security:StartupActiveSetup", "Security:StartupAppInit", "Security:StartupWinlogon",
"Security:TabDefender", "Security:CheckUpdates", "Security:CheckAntivirus", "Security:CheckFirewall", "Devices:LinkKindNvme",
- "Devices:ChipsetLabel", "Devices:SourceChipset", "Devices:UsbKindAudio", "Tools:CategoryAudio", "Tools:HttpsUrl",
+ "Devices:ChipsetLabel", "Devices:SourceChipset", "Devices:UsbKindAudio", "Tools:CategoryAudio", "Maintenance:LayoutRoleAudio", "Maintenance:LayoutUsbAudio", "Maintenance:LayoutUsbMouse", "Tools:HttpsUrl",
"es/Scripts:ImportFilter", "es/Scripts:PlaybookTypeScript", "es/Scripts:Playbooks", "es/Devices:PriorityNormal", "es/Maintenance:Manual",
"it/Devices:ControllerMode", "it/Devices:InputController", "it/Devices:InputMouse", "it/Devices:UsbKindInput", "it/Maintenance:CpuLabel",
"it/Scripts:PlaybookTypeScript", "it/Scripts:PlaybookTypeTweak", "it/Scripts:PlaybookTypeWinget", "it/Scripts:adobe_hosts_block_Category",
diff --git a/TweakHub.Tests/UnusedDevicesAndDriversTests.cs b/TweakHub.Tests/UnusedDevicesAndDriversTests.cs
index 6f7215f..9f2cda8 100644
--- a/TweakHub.Tests/UnusedDevicesAndDriversTests.cs
+++ b/TweakHub.Tests/UnusedDevicesAndDriversTests.cs
@@ -38,6 +38,49 @@ public void UnusedDevicesFollowWhatThisPcActuallyUses()
});
}
+ [Test]
+ public void TheSlowerOfTwoLiveConnectionsIsSuggestedUnticked()
+ {
+ var context = DeviceService.ParseUsageContext("""
+ {"RemoteDesktopOff":false,"DialUpEntries":1,"Nics":[
+ {"Id":"PCI\\WIFI","Name":"Wi-Fi 6E","Connected":true,"Wireless":true,"Speed":2400000000},
+ {"Id":"PCI\\ETH1","Name":"Ethernet 1G","Connected":true,"Wireless":false,"Speed":1000000000},
+ {"Id":"PCI\\ETH25","Name":"Ethernet 2.5G","Connected":true,"Wireless":false,"Speed":2500000000}]}
+ """);
+ // Wired beats a faster Wi-Fi link; among wired cards the fastest stays.
+ Assert.That(context.BestNic?.Id, Is.EqualTo(@"PCI\ETH25"));
+ Assert.That(DeviceService.UnusedReason(Device(@"PCI\WIFI", "Wi-Fi 6E"), context), Is.EqualTo("Devices:UnusedNicSlower"));
+ Assert.That(DeviceService.UnusedReason(Device(@"PCI\ETH1", "Ethernet 1G"), context), Is.EqualTo("Devices:UnusedNicSlower"));
+ Assert.That(DeviceService.UnusedReason(Device(@"PCI\ETH25", "Ethernet 2.5G"), context), Is.Null);
+ Assert.That(DeviceService.TickedByDefault("Devices:UnusedNicSlower"), Is.False);
+ }
+
+ [Test]
+ public void AudioFunctionsNobodyListensToAreSuggested()
+ {
+ PnpDeviceInfo Pci(string id, string cls, int bus, int address) => Device(id, id, cls) with { BusNumber = bus, Address = address };
+ PnpDeviceInfo Child(string id, string parent, int problem = 0) =>
+ new(id, id, "MEDIA", problem == 0 ? "OK" : "Error", true, problem, parent, "", "");
+ var devices = new List
+ {
+ Pci(@"PCI\VEN_1002&DEV_73A5\GPU", "Display", 48, 0),
+ Pci(@"PCI\VEN_1002&DEV_AB28\HDMI", "System", 48, 1),
+ Child(@"HDAUDIO\FUNC_01&VEN_1002\HDMI", @"PCI\VEN_1002&DEV_AB28\HDMI"),
+ Pci(@"PCI\VEN_1022&DEV_1487\HDA", "System", 10, 0x10003),
+ Child(@"HDAUDIO\FUNC_01&VEN_10EC\REALTEK", @"PCI\VEN_1022&DEV_1487\HDA"),
+ Child(@"USB\VID_06CB\DAC", @"USB\ROOT"),
+ Child(@"SWD\MMDEVAPI\{0.0.0.00000000}.{dac}", @"USB\VID_06CB\DAC"),
+ };
+ var context = DeviceService.WithAudio(Unused, devices, ["{0.0.0.00000000}.{dac}"]);
+ Assert.That(DeviceService.UnusedReason(devices[2], context), Is.EqualTo("Devices:UnusedGpuAudio"));
+ Assert.That(DeviceService.UnusedReason(devices[4], context), Is.EqualTo("Devices:UnusedOnboardAudio"));
+ // The Realtek plays the default output: it stays.
+ var realtek = devices.Append(Child(@"SWD\MMDEVAPI\{0.0.0.00000000}.{spk}", @"HDAUDIO\FUNC_01&VEN_10EC\REALTEK")).ToList();
+ Assert.That(DeviceService.UnusedReason(devices[4], DeviceService.WithAudio(Unused, realtek, ["{0.0.0.00000000}.{spk}"])), Is.Null);
+ // No default audio device known: nothing is suggested.
+ Assert.That(DeviceService.WithAudio(Unused, devices, []).SpareOnboardAudio, Is.Empty);
+ }
+
[Test]
public void UsageContextReadsTheScriptOutput()
{
diff --git a/TweakHub.csproj b/TweakHub.csproj
index f62f812..3e808aa 100644
--- a/TweakHub.csproj
+++ b/TweakHub.csproj
@@ -13,7 +13,7 @@
app.manifest
TweakHub
Windows 11 Performance Tweaking Application
- 1.6.1
+ 1.7.0
false
Copyright © 2025–2026
TweakHub
diff --git a/Views/DeviceListView.xaml.cs b/Views/DeviceListView.xaml.cs
index 0622937..7c99836 100644
--- a/Views/DeviceListView.xaml.cs
+++ b/Views/DeviceListView.xaml.cs
@@ -144,7 +144,9 @@ private async void DisableUnused_Click(object sender, RoutedEventArgs e)
DisableUnusedButton.IsEnabled = false;
try
{
- var context = await DeviceService.Instance.GetUsageContextAsync();
+ var endpoints = await Task.Run(AudioEndpoints.ReadDefaults);
+ var context = DeviceService.WithAudio(await DeviceService.Instance.GetUsageContextAsync(), _devices,
+ endpoints.Select(endpoint => endpoint.Id).ToList());
var unused = _devices.Select(device => (Device: device, Reason: DeviceService.UnusedReason(device, context)))
.Where(item => item.Reason is not null).ToList();
if (unused.Count == 0)
diff --git a/Views/InterruptView.xaml b/Views/InterruptView.xaml
index 2707a59..de24ee6 100644
--- a/Views/InterruptView.xaml
+++ b/Views/InterruptView.xaml
@@ -31,6 +31,12 @@
+
diff --git a/Views/InterruptView.xaml.cs b/Views/InterruptView.xaml.cs
index b5b8787..5022088 100644
--- a/Views/InterruptView.xaml.cs
+++ b/Views/InterruptView.xaml.cs
@@ -26,6 +26,7 @@ public bool AffinityOnly
MsiTile.Visibility = value ? Visibility.Collapsed : Visibility.Visible;
ModeLabel.Visibility = MsiCheckBox.Visibility = PriorityLabel.Visibility = PriorityBox.Visibility = MsiChartPanel.Visibility = value ? Visibility.Collapsed : Visibility.Visible;
AffinityLabel.Visibility = AffinityEditor.Visibility = value ? Visibility.Visible : Visibility.Collapsed;
+ LayoutButton.Visibility = value && _canSetAffinity ? Visibility.Visible : Visibility.Collapsed;
foreach (var index in new[] { 2, 3, 4 }) DevicesGrid.Columns[index].Visibility = value ? Visibility.Collapsed : Visibility.Visible;
}
}
@@ -176,6 +177,118 @@ private async void Apply_Click(object sender, RoutedEventArgs e)
finally { EditorCard.IsEnabled = true; }
}
+ // shortcut: a fixed threshold on a 2-second idle sample; the load during a game is different, so it only warns.
+ private const double BusyCpuPercent = 30;
+
+ /// Suggested one-core-per-role affinity, previewed with a checkbox per device before anything is written.
+ private async void Layout_Click(object sender, RoutedEventArgs e)
+ {
+ var owner = Window.GetWindow(this);
+ var layout = InterruptLayoutPlanner.Plan(CpuTopology.Read(), CpuTopology.ReadL3());
+ if (layout.Unavailable)
+ {
+ await AppDialog.ShowWarningAsync(owner, L.Get("Maintenance:LayoutTitle"), L.Get("Maintenance:LayoutUnavailable"));
+ return;
+ }
+ string Role(InterruptRole role) => L.Get($"Maintenance:LayoutRole{role}");
+ IReadOnlyList nodes;
+ IReadOnlyList endpoints;
+ IReadOnlyList load;
+ LayoutButton.IsEnabled = false;
+ try
+ {
+ // Device tree, default audio devices and two seconds of per-core load, all read-only.
+ var sample = CpuLoad.SampleAsync(TimeSpan.FromSeconds(2));
+ (nodes, endpoints) = await Task.Run(() => (DeviceTree.Read(), AudioEndpoints.ReadDefaults()));
+ load = await sample;
+ }
+ finally { LayoutButton.IsEnabled = true; }
+ var usb = InterruptLayoutPlanner.UsbUse(nodes, endpoints.Select(endpoint => endpoint.Id));
+ var rows = InterruptLayoutPlanner.Rows(layout, _devices, usb);
+ var todo = rows.Where(row => !row.AlreadySet && row.Skip is null).ToList();
+ var audio = InterruptLayoutPlanner.HasAudio(rows);
+ var usbNumbers = rows.Where(row => row.Device.Class == "USB").Select((row, index) => (row.Device.Id, index + 1))
+ .ToDictionary(item => item.Id, item => item.Item2, StringComparer.OrdinalIgnoreCase);
+ string Name(InterruptLayoutRow row) => row.Device.Name
+ + (usbNumbers.TryGetValue(row.Device.Id, out var number) ? $" (USB {number})" : string.Empty)
+ + (row.AudioDevice is { } device ? $" – {device}" : string.Empty);
+ var lines = new List { L.Get("Maintenance:LayoutIntro"), string.Empty };
+ lines.AddRange(layout.CpuByRole.Where(entry => audio || entry.Key != InterruptRole.Audio)
+ .Select(entry => $"{Role(entry.Key)}: CPU {entry.Value}"));
+ if (!audio) lines.Add(L.Get("Maintenance:LayoutAudioUsb"));
+
+ lines.Add(string.Empty);
+ foreach (var (id, number) in usbNumbers)
+ {
+ var use = usb.GetValueOrDefault(id);
+ var parts = new List();
+ if (use?.Mouse == true) parts.Add(L.Get("Maintenance:LayoutUsbMouse"));
+ if (use?.Keyboard == true) parts.Add(L.Get("Maintenance:LayoutUsbKeyboard"));
+ if (use?.Camera == true) parts.Add(L.Get("Maintenance:LayoutUsbCamera"));
+ if (use is { Audio.Count: > 0 }) parts.Add(L.Format("Maintenance:LayoutUsbAudio", string.Join(", ", use.Audio)));
+ lines.Add(L.Format("Maintenance:LayoutUsbController", number,
+ parts.Count > 0 ? string.Join(", ", parts) : L.Get("Maintenance:LayoutUsbNothing")));
+ }
+ var sharedAudio = usbNumbers.Keys.Select(id => usb.GetValueOrDefault(id)).Where(use => use is { Audio.Count: > 0, HasInput: true }).ToList();
+ if (sharedAudio.Count > 0 && usbNumbers.Keys.Any(id => usb.GetValueOrDefault(id) is not { HasInput: true }))
+ lines.AddRange(sharedAudio.SelectMany(use => use!.Audio).Distinct().Select(device => L.Format("Maintenance:LayoutUsbAudioShared", device)));
+ var names = nodes.DistinctBy(node => node.Id, StringComparer.OrdinalIgnoreCase)
+ .ToDictionary(node => node.Id, node => node.Name, StringComparer.OrdinalIgnoreCase);
+ foreach (var endpoint in endpoints.Where(endpoint => endpoint.FrontJack))
+ lines.Add(L.Format("Maintenance:LayoutFrontJack", names.GetValueOrDefault(@"SWD\MMDEVAPI\" + endpoint.Id) ?? endpoint.Id));
+ if (layout.HybridPerformanceOnly) lines.Add(L.Get("Maintenance:LayoutNoteHybrid"));
+ if (layout.CacheGroupChosen) lines.Add(L.Get("Maintenance:LayoutNoteCache"));
+ if (layout.SharedNetworkAudio) lines.Add(L.Get("Maintenance:LayoutNoteShared"));
+ if (rows.Any(row => row.Role == InterruptRole.Network)) lines.Add(L.Get("Maintenance:LayoutRss"));
+ // Set in the registry is not the same as in use: the interrupts Windows allocated in this boot tell.
+ lines.AddRange(rows.Where(row => row.AlreadySet).Select(row => L.Format(
+ InterruptLayoutPlanner.IsActive(row.Mask, DeviceTree.AllocatedInterruptAffinities(row.Device.Id)) ? "Maintenance:LayoutActive" : "Maintenance:LayoutPendingRestart",
+ Name(row))));
+ lines.AddRange(rows.Where(row => row.Skip is not null).Select(row => L.Format($"Maintenance:Layout{row.Skip}", Name(row))));
+ lines.AddRange(InterruptLayoutPlanner.PinnedStorage(_devices).Select(device =>
+ L.Format("Maintenance:LayoutStoragePinned", device.Name, InterruptService.FormatMask(device.AffinityMask))));
+
+ if (load.Count > 0)
+ {
+ lines.Add(string.Empty);
+ lines.Add(L.Get("Maintenance:LayoutLoadTitle"));
+ // CPU 0 for comparison, then only the cores some device will really get.
+ var used = rows.Where(row => row.Skip is null).Select(row => row.Cpu);
+ foreach (var cpu in used.Prepend(0).Distinct().Where(cpu => cpu < load.Count))
+ {
+ var sample = load[cpu];
+ lines.Add(L.Format("Maintenance:LayoutLoadCpu", cpu, sample.BusyPercent, sample.InterruptDpcPercent, sample.InterruptsPerSecond));
+ if (cpu != 0 && sample.BusyPercent >= BusyCpuPercent) lines.Add(L.Format("Maintenance:LayoutLoadBusy", cpu, sample.BusyPercent));
+ }
+ }
+ var msi = InterruptLayoutPlanner.MsiCandidates(rows);
+ if (todo.Count == 0 && msi.Count == 0)
+ {
+ lines.Add(string.Empty);
+ lines.Add(L.Get("Maintenance:LayoutNothingToDo"));
+ await AppDialog.ShowAsync(owner, L.Get("Maintenance:LayoutTitle"), string.Join("\n", lines));
+ return;
+ }
+ // MSI boxes come after the affinity ones and start unticked: MSI is a driver change the user opts into.
+ var chosen = await AppDialog.ChooseAsync(owner, L.Get("Maintenance:LayoutTitle"), string.Join("\n", lines),
+ todo.Select(row => (L.Format("Maintenance:LayoutChoice", Role(row.Role), row.Cpu, Name(row)), true))
+ .Concat(msi.Select(row => (L.Format("Maintenance:LayoutMsiChoice", Name(row)), false))));
+ if (chosen is not { Count: > 0 }) return;
+ EditorCard.IsEnabled = LayoutButton.IsEnabled = false;
+ try
+ {
+ if (!await InterruptService.Instance.ApplyAffinitiesAsync(
+ chosen.Where(index => index < todo.Count).Select(index => (todo[index].Device, todo[index].Mask)).ToList(),
+ chosen.Where(index => index >= todo.Count).Select(index => msi[index - todo.Count].Device).ToList()))
+ await AppDialog.ShowErrorAsync(owner, L.Get("Devices:ApplyFailedTitle"), L.Get("Devices:ApplyFailedMessage"));
+ else
+ await AppDialog.ShowRestartRequiredAsync(owner, L.Get("Maintenance:LayoutReminder"));
+ await ScanAsync();
+ }
+ catch (Exception ex) { await AppDialog.ShowErrorAsync(owner, L.Get("Devices:ApplyFailedTitle"), ex.Message); }
+ finally { EditorCard.IsEnabled = LayoutButton.IsEnabled = true; }
+ }
+
private async void Restore_Click(object sender, RoutedEventArgs e)
{
if (DevicesGrid.SelectedItem is not InterruptDevice device) return;