Merge PR #85: Exclude unplugged and inactive display adapters on Windows

This commit is contained in:
千川白浪 committed 2026-12-01 19:20:31 -07:00
commit 1daec9c80d
6 files changed
+428 -50

No files matched your search

@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["icaruszezen"],
"zh": "Windows 显卡检测仅保留当前在位且正常启动的显示适配器,避免已拔出或已禁用的显卡继续出现在可用显卡列表中。",
"en": "Detect only present, started display adapters on Windows so unplugged or disabled GPUs no longer appear in the available GPU list."
}
+11 -3
View File
@@ -209,24 +209,32 @@ func MergeRegistryAndVulkanGPUs(regGPUs []GPUInfo, vkProbes []VulkanDeviceProbe)
matchProbe := func(g GPUInfo) *VulkanDeviceProbe {
// 1. Exact PCI vendor:device match.
if g.VendorID != "" && g.DeviceID != "" {
wantVen := strings.ToLower(g.VendorID)
wantDev := strings.ToLower(g.DeviceID)
for i := range vkProbes {
if used[i] {
continue
}
if fmt.Sprintf("%04x", vkProbes[i].VendorID) == g.VendorID &&
fmt.Sprintf("%04x", vkProbes[i].DeviceID) == g.DeviceID {
if fmt.Sprintf("%04x", vkProbes[i].VendorID) == wantVen &&
fmt.Sprintf("%04x", vkProbes[i].DeviceID) == wantDev {
used[i] = true
return &vkProbes[i]
}
}
}
// 2. Case-insensitive name fallback when MatchingDeviceId was absent.
// 2. Case-insensitive name fallback only when PCI IDs are absent on either side;
// never cross-match two different PCI devices that share a generic marketing name
// (e.g. "AMD Radeon(TM) Graphics").
lowName := strings.ToLower(strings.TrimSpace(g.Name))
if lowName != "" {
for i := range vkProbes {
if used[i] {
continue
}
if g.VendorID != "" && g.DeviceID != "" &&
vkProbes[i].VendorID != 0 && vkProbes[i].DeviceID != 0 {
continue
}
pName := strings.ToLower(strings.TrimSpace(vkProbes[i].Name))
if pName == lowName || strings.Contains(pName, lowName) || strings.Contains(lowName, pName) {
used[i] = true
+29
View File
@@ -136,6 +136,35 @@ func TestGPUCompatibilityGradingAndRecommendation(t *testing.T) {
if len(merged) != 2 || merged[0].Compat != GPUCompatWarn || merged[1].Compat != GPUCompatSupported {
t.Fatalf("merged = %+v", merged)
}
// 10. MergeRegistryAndVulkanGPUs never cross-matches distinct PCI IDs by generic name,
// while still matching uppercase PCI IDs and falling back to name when PCI IDs are absent.
noCross := MergeRegistryAndVulkanGPUs(
[]GPUInfo{
{Name: "AMD Radeon(TM) Graphics", VulkanICD: `C:\old-amd.json`, VendorID: "1002", DeviceID: "164e"},
{Name: "NVIDIA GeForce RTX 3060", VulkanICD: `C:\nv-vk64.json`, VendorID: "10DE", DeviceID: "2504"},
{Name: "Intel(R) UHD Graphics 770", VulkanICD: `C:\igvk64.json`},
},
[]VulkanDeviceProbe{
{Name: "AMD Radeon(TM) Graphics", VendorID: 0x1002, DeviceID: 0x13c0, DeviceType: 1, APIVersion: v13, Extensions: allReqExts},
{Name: "NVIDIA GeForce RTX 3060", VendorID: 0x10de, DeviceID: 0x2504, DeviceType: 2, APIVersion: v13, Extensions: allReqExts},
{Name: "Intel(R) UHD Graphics 770", VendorID: 0x8086, DeviceID: 0x4680, DeviceType: 1, APIVersion: v13, Extensions: allReqExts},
},
)
if len(noCross) != 4 {
t.Fatalf("expected 4 GPUs (unmatched 164e + matched 2504 + name-matched 4680 + vulkan-only 13c0), got %+v", noCross)
}
if noCross[0].DeviceID != "164e" || noCross[0].Compat != GPUCompatUnknown || noCross[0].VulkanVersion != "" {
t.Fatalf("164e must not cross-match 13c0 probe: %+v", noCross[0])
}
if noCross[1].DeviceID != "2504" || noCross[1].Compat != GPUCompatSupported {
t.Fatalf("uppercase PCI ID should match 2504 probe: %+v", noCross[1])
}
if noCross[2].DeviceID != "4680" || noCross[2].Compat != GPUCompatSupported {
t.Fatalf("missing PCI ID should fall back to name match: %+v", noCross[2])
}
if noCross[3].DeviceID != "13c0" || noCross[3].Compat != GPUCompatSupported || noCross[3].VulkanICD != "" {
t.Fatalf("13c0 probe should remain separate with no stale ICD: %+v", noCross[3])
}
}
func TestAffinityMaskHelpers(t *testing.T) {
+5 -30
View File
@@ -6,7 +6,6 @@ import (
"encoding/binary"
"fmt"
"math/bits"
"os"
"path/filepath"
"runtime"
"sort"
@@ -577,35 +576,11 @@ func ProbeVulkanGPUs() []GPUInfo {
}
func probeVulkanGPUs() ([]GPUInfo, error) {
const baseKey = `SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}`
var regGPUs []GPUInfo
for i := 0; i < 32; i++ {
sub := fmt.Sprintf(`%s\%04d`, baseKey, i)
desc, okDesc := regReadString(hkeyLocalMachine, sub, "DriverDesc")
if !okDesc || desc == "" {
continue
}
icd, _ := regReadString(hkeyLocalMachine, sub, "VulkanDriverName")
if icd == "" {
continue
}
// Skip stale registry entries left behind by removed adapters or old drivers
// (matching upstream reims-ctl os/windows.rs vulkan_driver_files).
if _, err := os.Stat(icd); err != nil {
continue
}
matchID, _ := regReadString(hkeyLocalMachine, sub, "MatchingDeviceId")
vendorID, deviceID := ParsePCIIDs(matchID)
drvVer, _ := regReadString(hkeyLocalMachine, sub, "DriverVersion")
regGPUs = append(regGPUs, GPUInfo{
Name: desc,
VulkanICD: icd,
Kind: ClassifyGPU(desc),
VendorID: vendorID,
DeviceID: deviceID,
DriverVersion: drvVer,
})
}
// Enumerate only physically present, started, problem-free display adapters
// via SetupAPI + CfgMgr32. Scanning Control\Class\{4d36e968-...}\0000..0031
// directly picks up stale registry keys left behind by unplugged (phantom)
// or disabled GPUs whose DriverStore ICD manifests still exist on disk.
regGPUs := probeActiveRegistryGPUs()
recovered := recoveredManifests()
vkProbes, err := probeVulkanDevices()
gpus := MergeRegistryAndVulkanGPUs(regGPUs, vkProbes)
+231
View File
@@ -5,9 +5,240 @@ package host
import (
"maps"
"os"
"strings"
"testing"
"golang.org/x/sys/windows"
)
func TestIsActiveDevNodeStatus(t *testing.T) {
cases := []struct {
name string
status uint32
want bool
}{
{
name: "started healthy adapter",
status: windows.DN_NT_DRIVER | windows.DN_NT_ENUMERATOR | windows.DN_DISABLEABLE | windows.DN_STARTED | windows.DN_DRIVER_LOADED,
want: true,
},
{
name: "started multi-function adapter ignores aliased bits",
status: windows.DN_STARTED | windows.DN_MF_PARENT | windows.DN_MF_CHILD | windows.DN_NEEDS_LOCKING,
want: true,
},
{
name: "phantom or zero status",
status: 0,
want: false,
},
{
name: "driver loaded but not started",
status: windows.DN_DRIVER_LOADED | windows.DN_DISABLEABLE,
want: false,
},
{
name: "disabled in device manager",
status: windows.DN_DISABLEABLE | windows.DN_HAS_PROBLEM,
want: false,
},
{
name: "started with problem flag",
status: windows.DN_STARTED | windows.DN_HAS_PROBLEM,
want: false,
},
{
name: "pending removal",
status: windows.DN_STARTED | windows.DN_WILL_BE_REMOVED,
want: false,
},
}
for _, tc := range cases {
if got := isActiveDevNodeStatus(tc.status); got != tc.want {
t.Errorf("%s: isActiveDevNodeStatus(0x%X) = %v, want %v", tc.name, tc.status, got, tc.want)
}
}
}
func TestFilterActiveDisplayAdaptersAndReadRegistryGPUs(t *testing.T) {
const (
activeStatus = windows.DN_NT_DRIVER | windows.DN_NT_ENUMERATOR | windows.DN_DISABLEABLE | windows.DN_STARTED | windows.DN_DRIVER_LOADED
disabledStatus = windows.DN_DISABLEABLE | windows.DN_HAS_PROBLEM
removingStatus = activeStatus | windows.DN_WILL_BE_REMOVED
)
cls := func(idx string) string {
return `SYSTEM\CurrentControlSet\Control\Class\` + displayClass + `\` + idx
}
// Simulate registry keys including an unplugged (phantom) NVIDIA GPU at 0001
// whose DriverStore nv-vk64.json still exists on disk, a disabled NVIDIA GPU
// at 0002, an ejecting NVIDIA GPU at 0003, a virtual adapter at 0005, and
// two real active GPUs at 0007 and 0042 (index >= 32).
reg := map[string]map[string]string{
cls("0001"): {
"DriverDesc": "NVIDIA GeForce RTX 3080",
"VulkanDriverName": `C:\DriverStore\nv_old\nv-vk64.json`,
"MatchingDeviceId": `pci\ven_10de&dev_2206`,
"DriverVersion": "32.0.15.6636",
},
cls("0002"): {
"DriverDesc": "NVIDIA GeForce RTX 4070",
"VulkanDriverName": `C:\DriverStore\nv_dis\nv-vk64.json`,
"MatchingDeviceId": `pci\ven_10de&dev_2786`,
"DriverVersion": "32.0.15.6636",
},
cls("0003"): {
"DriverDesc": "NVIDIA GeForce RTX 4060",
"VulkanDriverName": `C:\DriverStore\nv_rem\nv-vk64.json`,
"MatchingDeviceId": `pci\ven_10de&dev_2882`,
"DriverVersion": "32.0.15.6636",
},
cls("0004"): {
"DriverDesc": "NVIDIA GeForce GTX 1080",
"VulkanDriverName": `C:\DriverStore\nv_err\nv-vk64.json`,
"MatchingDeviceId": `pci\ven_10de&dev_1b80`,
},
cls("0005"): {
"DriverDesc": "Todesk Virtual Display Adapter",
"MatchingDeviceId": `Root\tdIdd`,
},
cls("0006"): {
"DriverDesc": "Intel(R) Arc(TM) A770 Graphics",
"VulkanDriverName": `C:\DriverStore\missing\igvk64.json`,
"MatchingDeviceId": `pci\ven_8086&dev_56a0`,
},
cls("0007"): {
"DriverDesc": "Intel(R) UHD Graphics 770",
"VulkanDriverName": `C:\DriverStore\intel\igvk64.json`,
"MatchingDeviceId": `pci\ven_8086&dev_4680`,
"DriverVersion": "31.0.101.5590",
},
cls("0042"): {
"DriverDesc": "AMD Radeon RX 7900 XTX",
"VulkanDriverName": `C:\DriverStore\amd\amd-vulkan64.json`,
"MatchingDeviceId": `PCI\VEN_1002&DEV_744C&REV_C8`,
"DriverVersion": "32.0.11024.2",
},
}
existingFiles := map[string]bool{
`C:\DriverStore\nv_old\nv-vk64.json`: true,
`C:\DriverStore\nv_dis\nv-vk64.json`: true,
`C:\DriverStore\nv_rem\nv-vk64.json`: true,
`C:\DriverStore\nv_err\nv-vk64.json`: true,
`C:\DriverStore\intel\igvk64.json`: true,
`C:\DriverStore\amd\amd-vulkan64.json`: true,
}
// Only present PnP devices appear here (0001 phantom NVIDIA GPU is absent).
records := []displayAdapterRecord{
{instanceID: `PCI\VEN_10DE&DEV_2786\0`, driverKey: displayClass + `\0002`, status: disabledStatus, statusOK: true},
{instanceID: `PCI\VEN_10DE&DEV_2882\0`, driverKey: displayClass + `\0003`, status: removingStatus, statusOK: true},
{instanceID: `PCI\VEN_10DE&DEV_1B80\0`, driverKey: displayClass + `\0004`, status: activeStatus, statusOK: false},
{instanceID: `ROOT\DISPLAY\0000`, driverKey: displayClass + `\0005`, status: activeStatus, statusOK: true},
{instanceID: `PCI\VEN_8086&DEV_56A0\0`, driverKey: displayClass + `\0006`, status: activeStatus, statusOK: true},
{instanceID: `DISPLAY\CUSTOM\0`, driverKey: displayClass + `\0042`, status: activeStatus, statusOK: true},
{instanceID: `PCI\VEN_8086&DEV_4680\0`, driverKey: displayClass + `\0007`, status: activeStatus, statusOK: true},
{instanceID: `PCI\VEN_8086&DEV_4680\0`, driverKey: strings.ToUpper(displayClass) + `\0007`, status: activeStatus, statusOK: true},
{instanceID: `PCI\VEN_10DE&DEV_9999\0`, driverKey: `..\bad`, status: activeStatus, statusOK: true},
}
adapters := filterActiveDisplayAdapters(records)
gpus := readRegistryGPUs(
adapters,
func(subKey, valueName string) (string, bool) {
v, ok := reg[subKey][valueName]
return v, ok
},
func(path string) bool {
return existingFiles[path]
},
)
if len(gpus) != 2 {
t.Fatalf("expected 2 active GPUs, got %d: %+v", len(gpus), gpus)
}
if gpus[0].Name != "Intel(R) UHD Graphics 770" || gpus[0].VendorID != "8086" || gpus[0].DeviceID != "4680" || gpus[0].Kind != GPUIntegrated {
t.Fatalf("unexpected gpus[0]: %+v", gpus[0])
}
if gpus[1].Name != "AMD Radeon RX 7900 XTX" || gpus[1].VendorID != "1002" || gpus[1].DeviceID != "744c" || gpus[1].Kind != GPUDiscrete {
t.Fatalf("unexpected gpus[1]: %+v", gpus[1])
}
}
func TestLiveGPUsExcludeInactiveDisplayAdapters(t *testing.T) {
active := activeDisplayAdapters()
activeKeys := make(map[string]bool, len(active))
activePCI := make(map[string]bool, len(active))
for _, a := range active {
activeKeys[strings.ToLower(a.driverKey)] = true
if a.vendorID != "" && a.deviceID != "" {
activePCI[a.vendorID+":"+a.deviceID] = true
}
}
guid, err := windows.GUIDFromString(displayClass)
if err != nil {
t.Fatalf("GUIDFromString: %v", err)
}
allDevs, err := windows.SetupDiGetClassDevsEx(&guid, "", 0, 0, 0, "")
if err != nil {
t.Fatalf("SetupDiGetClassDevsEx(all): %v", err)
}
defer allDevs.Close()
inactiveOnlyPCI := make(map[string]string)
for i := 0; ; i++ {
dev, err := allDevs.EnumDeviceInfo(i)
if err != nil {
break
}
val, _ := allDevs.DeviceRegistryProperty(dev, windows.SPDRP_DRIVER)
driverKey, _ := val.(string)
driverKey = strings.Trim(strings.TrimSpace(driverKey), `\`)
if driverKey != "" && activeKeys[strings.ToLower(driverKey)] {
continue
}
id, _ := allDevs.DeviceInstanceID(dev)
ven, devID := ParsePCIIDs(id)
if (ven == "" || devID == "") && driverKey != "" && !strings.Contains(driverKey, "..") {
matchID, _ := regReadString(hkeyLocalMachine, `SYSTEM\CurrentControlSet\Control\Class\`+driverKey, "MatchingDeviceId")
v2, d2 := ParsePCIIDs(matchID)
if ven == "" {
ven = v2
}
if devID == "" {
devID = d2
}
}
if ven == "" || devID == "" {
continue
}
pci := ven + ":" + devID
if !activePCI[pci] {
inactiveOnlyPCI[pci] = id
}
}
for _, g := range probeActiveRegistryGPUs() {
if g.VulkanICD == "" || !isRegularFile(g.VulkanICD) {
t.Errorf("active registry GPU %q has invalid VulkanICD %q", g.Name, g.VulkanICD)
}
}
probed := ProbeVulkanGPUs()
for _, g := range probed {
if g.VendorID == "" || g.DeviceID == "" {
continue
}
pci := strings.ToLower(g.VendorID) + ":" + strings.ToLower(g.DeviceID)
if id, bad := inactiveOnlyPCI[pci]; bad {
t.Errorf("ProbeVulkanGPUs included inactive/unplugged GPU %q (%s, instance %s): %+v", g.Name, pci, id, g)
}
}
if len(inactiveOnlyPCI) > 0 {
t.Logf("verified %d inactive/phantom display adapter PCI ID(s) excluded from ProbeVulkanGPUs (%d active GPUs returned)", len(inactiveOnlyPCI), len(probed))
}
}
func TestMissingDriverPackages(t *testing.T) {
candidates := []adapterManifest{
{"10de:28e0", "nvidia.json"},
+145 -17
View File
@@ -51,7 +51,7 @@ func driverStoreManifest(inf, vendor string) string {
var manifest string
for _, name := range names {
path := filepath.Join(dir, name)
if info, err := os.Stat(path); err == nil && info.Mode().IsRegular() {
if isRegularFile(path) {
if manifest != "" {
return "" // Multiple driver implementations in this package.
}
@@ -61,42 +61,170 @@ func driverStoreManifest(inf, vendor string) string {
return manifest
}
type adapterManifest struct {
id, path string
func isRegularFile(path string) bool {
info, err := os.Stat(path)
return err == nil && info.Mode().IsRegular()
}
func unregisteredDriverManifests() []adapterManifest {
guid, _ := windows.GUIDFromString(displayClass)
type displayAdapterRecord struct {
instanceID string
driverKey string
status uint32
statusOK bool
}
type activeDisplayAdapter struct {
instanceID string
driverKey string
classKey string
vendorID string
deviceID string
}
// isActiveDevNodeStatus reports whether a Windows PnP devnode is started,
// problem-free, and not pending removal. Unplugged (phantom) GPUs are excluded
// by DIGCF_PRESENT; disabled or failed adapters (e.g. Code 22 / Code 43) lack
// DN_STARTED and/or carry DN_HAS_PROBLEM.
func isActiveDevNodeStatus(status uint32) bool {
return status&windows.DN_STARTED != 0 &&
status&windows.DN_HAS_PROBLEM == 0 &&
status&windows.DN_WILL_BE_REMOVED == 0
}
func enumeratePresentDisplayAdapters() []displayAdapterRecord {
guid, err := windows.GUIDFromString(displayClass)
if err != nil {
return nil
}
devs, err := windows.SetupDiGetClassDevsEx(&guid, "", 0, windows.DIGCF_PRESENT, 0, "")
if err != nil {
return nil
}
defer devs.Close()
var candidates []adapterManifest
var records []displayAdapterRecord
for i := 0; ; i++ {
dev, err := devs.EnumDeviceInfo(i)
if err != nil {
break
}
var status, problem uint32
statusErr := windows.CM_Get_DevNode_Status(&status, &problem, dev.DevInst, 0)
id, _ := devs.DeviceInstanceID(dev)
vendor, device := ParsePCIIDs(id)
if device == "" || !strings.HasPrefix(strings.ToUpper(id), `PCI\`) {
val, _ := devs.DeviceRegistryProperty(dev, windows.SPDRP_DRIVER)
driverKey, _ := val.(string)
records = append(records, displayAdapterRecord{
instanceID: id,
driverKey: driverKey,
status: status,
statusOK: statusErr == nil,
})
}
return records
}
func filterActiveDisplayAdapters(records []displayAdapterRecord) []activeDisplayAdapter {
seen := make(map[string]bool, len(records))
out := make([]activeDisplayAdapter, 0, len(records))
for _, r := range records {
if !r.statusOK || !isActiveDevNodeStatus(r.status) {
continue
}
value, _ := devs.DeviceRegistryProperty(dev, windows.SPDRP_DRIVER)
driverKey, ok := value.(string)
if !ok || driverKey == "" {
driverKey := strings.Trim(strings.TrimSpace(r.driverKey), `\`)
if driverKey == "" || strings.Contains(driverKey, "..") {
continue
}
sub := `SYSTEM\CurrentControlSet\Control\Class\` + driverKey
if path, _ := regReadString(hkeyLocalMachine, sub, "VulkanDriverName"); path != "" {
if info, err := os.Stat(path); err == nil && info.Mode().IsRegular() {
lowKey := strings.ToLower(driverKey)
if seen[lowKey] {
continue
}
seen[lowKey] = true
vendorID, deviceID := ParsePCIIDs(r.instanceID)
out = append(out, activeDisplayAdapter{
instanceID: r.instanceID,
driverKey: driverKey,
classKey: `SYSTEM\CurrentControlSet\Control\Class\` + driverKey,
vendorID: vendorID,
deviceID: deviceID,
})
}
slices.SortFunc(out, func(a, b activeDisplayAdapter) int {
return strings.Compare(strings.ToLower(a.driverKey), strings.ToLower(b.driverKey))
})
return out
}
func activeDisplayAdapters() []activeDisplayAdapter {
return filterActiveDisplayAdapters(enumeratePresentDisplayAdapters())
}
func readRegistryGPUs(
adapters []activeDisplayAdapter,
readString func(subKey, valueName string) (string, bool),
regularFile func(path string) bool,
) []GPUInfo {
var regGPUs []GPUInfo
for _, a := range adapters {
desc, okDesc := readString(a.classKey, "DriverDesc")
if !okDesc || desc == "" {
continue
}
icd, _ := readString(a.classKey, "VulkanDriverName")
if icd == "" || !regularFile(icd) {
continue
}
vendorID, deviceID := a.vendorID, a.deviceID
if vendorID == "" || deviceID == "" {
matchID, _ := readString(a.classKey, "MatchingDeviceId")
v2, d2 := ParsePCIIDs(matchID)
if vendorID == "" {
vendorID = v2
}
if deviceID == "" {
deviceID = d2
}
}
drvVer, _ := readString(a.classKey, "DriverVersion")
regGPUs = append(regGPUs, GPUInfo{
Name: desc,
VulkanICD: icd,
Kind: ClassifyGPU(desc),
VendorID: vendorID,
DeviceID: deviceID,
DriverVersion: drvVer,
})
}
return regGPUs
}
func probeActiveRegistryGPUs() []GPUInfo {
return readRegistryGPUs(
activeDisplayAdapters(),
func(subKey, valueName string) (string, bool) {
return regReadString(hkeyLocalMachine, subKey, valueName)
},
isRegularFile,
)
}
type adapterManifest struct {
id, path string
}
func unregisteredDriverManifests() []adapterManifest {
var candidates []adapterManifest
for _, a := range activeDisplayAdapters() {
if a.vendorID == "" || a.deviceID == "" || !strings.HasPrefix(strings.ToUpper(a.instanceID), `PCI\`) {
continue
}
if path, _ := regReadString(hkeyLocalMachine, a.classKey, "VulkanDriverName"); path != "" {
if isRegularFile(path) {
continue
}
}
inf, _ := regReadString(hkeyLocalMachine, sub, "InfPath")
if path := driverStoreManifest(inf, vendor); path != "" {
candidates = append(candidates, adapterManifest{vendor + ":" + device, path})
inf, _ := regReadString(hkeyLocalMachine, a.classKey, "InfPath")
if path := driverStoreManifest(inf, a.vendorID); path != "" {
candidates = append(candidates, adapterManifest{a.vendorID + ":" + a.deviceID, path})
}
}
return candidates