Files
Reims-Go/internal/host/host_windows.go
T
icaruszezen b3b5f7a0fd fix(host): exclude unplugged and inactive display adapters on Windows
Enumerate Windows display adapters via SetupAPI (DIGCF_PRESENT) and CfgMgr32 (CM_Get_DevNode_Status: DN_STARTED, no DN_HAS_PROBLEM, no DN_WILL_BE_REMOVED) instead of blindly scanning Control\Class\{4d36e968-...}\0000..0031, so unplugged (phantom) and disabled GPUs whose DriverStore ICD files still remain on disk are no longer listed as available GPUs. Also reuse active adapter filtering for DriverStore manifest recovery and prevent MergeRegistryAndVulkanGPUs from cross-matching distinct PCI devices by generic name.
2026-12-02 10:09:57 +08:00

628 lines
18 KiB
Go

//go:build windows
package host
import (
"encoding/binary"
"fmt"
"math/bits"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"syscall"
"unsafe"
)
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procGetLogicalProcessorInformationEx = kernel32.NewProc("GetLogicalProcessorInformationEx")
procGlobalMemoryStatusEx = kernel32.NewProc("GlobalMemoryStatusEx")
procGetDiskFreeSpaceExW = kernel32.NewProc("GetDiskFreeSpaceExW")
procDeviceIoControl = kernel32.NewProc("DeviceIoControl")
procOpenProcess = kernel32.NewProc("OpenProcess")
procSetProcessAffinityMask = kernel32.NewProc("SetProcessAffinityMask")
procGetProcessAffinityMask = kernel32.NewProc("GetProcessAffinityMask")
procSetProcessInformation = kernel32.NewProc("SetProcessInformation")
procCloseHandle = kernel32.NewProc("CloseHandle")
advapi32 = syscall.NewLazyDLL("advapi32.dll")
procRegOpenKeyExW = advapi32.NewProc("RegOpenKeyExW")
procRegQueryValueExW = advapi32.NewProc("RegQueryValueExW")
procRegCloseKey = advapi32.NewProc("RegCloseKey")
shell32 = syscall.NewLazyDLL("shell32.dll")
procShellExecuteW = shell32.NewProc("ShellExecuteW")
)
const (
hkeyLocalMachine = 0x80000002
keyRead = 0x20019
regSZ = 1
regExpandSZ = 2
regMultiSZ = 7
processSetInformation = 0x0200
processQueryLimitedInformation = 0x1000
processPowerThrottlingClass = 4
powerThrottlingCurrentVersion = 1
powerThrottlingExecutionSpeed = 0x1
whvCapHypervisorPresent = 0x00000001
)
type memoryStatusEx struct {
Length uint32
MemoryLoad uint32
TotalPhys uint64
AvailPhys uint64
TotalPageFile uint64
AvailPageFile uint64
TotalVirtual uint64
AvailVirtual uint64
AvailExtendedVirtual uint64
}
type staticHostSnapshot struct {
needsColdReboot bool
gpus []GPUInfo
vulkanProbeError string
recGPU *GPUInfo
topo hybridTopology
topoOK bool
memSpec *HostMemorySpec
}
var (
staticHostOnce sync.Once
staticHostData staticHostSnapshot
whpxCapsMu sync.Mutex
whpxCapsCached bool
whpxCapsVal WHPXCapabilities
)
func getStaticHostSnapshot() staticHostSnapshot {
staticHostOnce.Do(func() {
gpus, err := probeVulkanGPUs()
topo, ok := probeHybridTopology()
staticHostData = staticHostSnapshot{
needsColdReboot: probeNeedsColdRebootWorkaround(),
gpus: gpus,
recGPU: PickRecommendedGPU(gpus),
topo: topo,
topoOK: ok,
memSpec: probeHostMemorySpec(),
}
if err != nil {
staticHostData.vulkanProbeError = err.Error()
}
})
return staticHostData
}
func getCachedWHPXCapabilities() WHPXCapabilities {
whpxCapsMu.Lock()
defer whpxCapsMu.Unlock()
if !whpxCapsCached {
whpxCapsVal = probeWHPXCapabilities()
whpxCapsCached = true
}
return whpxCapsVal
}
// Inspect collects Windows host capabilities without requiring administrator privileges.
func Inspect(dataRoot string) Report {
st := getStaticHostSnapshot()
gpusCopy := append([]GPUInfo(nil), st.gpus...)
var recGPUCopy *GPUInfo
if st.recGPU != nil {
cp := *st.recGPU
recGPUCopy = &cp
}
var memSpecCopy *HostMemorySpec
if st.memSpec != nil {
cp := *st.memSpec
memSpecCopy = &cp
}
rep := Report{
DefenderRealtimeActive: probeDefenderRealtime(),
OS: "windows",
Arch: runtime.GOARCH,
LogicalCPUs: runtime.NumCPU(),
DataRoot: dataRoot,
Timezone: DetectHostTimezone(),
WHPX: probeWHPX(),
NeedsColdRebootWorkaround: st.needsColdReboot,
GPUs: gpusCopy,
VulkanProbeError: st.vulkanProbeError,
RecommendedGPU: recGPUCopy,
MemorySpec: memSpecCopy,
}
if rep.WHPX == WHPXReady {
rep.WHPXCaps = getCachedWHPXCapabilities()
}
if st.topoOK {
topo := st.topo
rep.PhysicalCores = topo.phys
rep.PCoreCount = topo.pCount
rep.ECoreCount = topo.eCount
rep.LPECoreCount = topo.lpeCount
rep.HasHybridCores = topo.eCount > 0 || topo.lpeCount > 0
rep.PCoreMask = topo.pMask
rep.PCoreMaskHex = fmt.Sprintf("0x%X", topo.pMask)
rep.PCoreLogicalCPUs = append([]int(nil), topo.pLPs...)
rep.ECoreLogicalCPUs = append([]int(nil), topo.eLPs...)
if topo.lpeCount > 0 && topo.nonLPEMask > 0 {
rep.NonLPEMask = topo.nonLPEMask
rep.NonLPEMaskHex = fmt.Sprintf("0x%X", topo.nonLPEMask)
rep.NonLPELogicalCPUs = append([]int(nil), topo.nonLPELPs...)
}
rep.CPUTopology = append([]LogicalCPUInfo(nil), topo.cpus...)
}
if len(rep.CPUTopology) == 0 {
rep.CPUTopology = DefaultCPUTopology(rep.LogicalCPUs)
}
if totalGB, availGB, ok := probeMemoryGB(); ok {
rep.TotalRAMGB = totalGB
rep.AvailRAMGB = availGB
}
if ms, ok := memoryStatus(); ok {
rep.MemoryLoadPct = int(ms.MemoryLoad)
}
if limitGB, availGB, growthGB, ok := probeCommitGB(); ok {
rep.CommitLimitGB = limitGB
rep.CommitAvailGB = availGB
rep.PagingFileGrowthGB = growthGB
}
if freeGB, ok := probeFreeDiskGB(dataRoot); ok {
rep.FreeDiskGB = freeGB
}
rep.DataRootDriveType = probeDriveType(dataRoot)
rep.DeepBackingChains = InspectVMDiskChains(dataRoot)
rep.Displays = probeDisplays()
rep.PrimaryDisplay = PrimaryDisplayOf(rep.Displays)
rep.DisplayPresets, rep.RecommendedResolution = RecommendDisplayPresets(rep.PrimaryDisplay)
rep.HiDPIAdvice = HiDPIAdvice(rep.PrimaryDisplay, rep.DisplayPresets)
rep.FullscreenHiDPI = FullscreenStartsHiDPI(rep.PrimaryDisplay)
rep.ProcessorScheduling = probeProcessorScheduling()
rep.Audio = ProbeAudio()
return rep
}
// PinProcessToPCores restricts the given PID's affinity mask to the given bitmask.
func PinProcessToPCores(pid uint32, mask uint64) error {
return SetProcessAffinityMask(pid, mask)
}
// SetProcessAffinityMask sets the Win32 processor affinity mask for pid.
func SetProcessAffinityMask(pid uint32, mask uint64) error {
if mask == 0 {
return fmt.Errorf("invalid affinity mask 0")
}
h, _, err := procOpenProcess.Call(uintptr(processSetInformation), 0, uintptr(pid))
if h == 0 {
return fmt.Errorf("OpenProcess(%d): %w", pid, err)
}
defer procCloseHandle.Call(h)
r, _, err := procSetProcessAffinityMask.Call(h, uintptr(mask))
if r == 0 {
return fmt.Errorf("SetProcessAffinityMask(%d, 0x%X): %w", pid, mask, err)
}
return nil
}
// GetProcessAffinityMask reads the current process and system affinity masks for pid.
func GetProcessAffinityMask(pid uint32) (uint64, uint64, error) {
h, _, err := procOpenProcess.Call(uintptr(processQueryLimitedInformation), 0, uintptr(pid))
if h == 0 {
return 0, 0, fmt.Errorf("OpenProcess(%d): %w", pid, err)
}
defer procCloseHandle.Call(h)
var procMask, sysMask uintptr
r, _, err := procGetProcessAffinityMask.Call(
h,
uintptr(unsafe.Pointer(&procMask)),
uintptr(unsafe.Pointer(&sysMask)),
)
if r == 0 {
return 0, 0, fmt.Errorf("GetProcessAffinityMask(%d): %w", pid, err)
}
return uint64(procMask), uint64(sysMask), nil
}
type processPowerThrottlingState struct {
Version uint32
ControlMask uint32
StateMask uint32
}
// DisableProcessPowerThrottling opts pid out of Windows EcoQoS execution-speed
// power throttling so background / unfocused QEMU threads are not parked onto
// efficiency or LP-E cores by the scheduler.
func DisableProcessPowerThrottling(pid uint32) error {
if err := procSetProcessInformation.Find(); err != nil {
return err
}
h, _, err := procOpenProcess.Call(uintptr(processSetInformation), 0, uintptr(pid))
if h == 0 {
return fmt.Errorf("OpenProcess(%d): %w", pid, err)
}
defer procCloseHandle.Call(h)
state := processPowerThrottlingState{
Version: powerThrottlingCurrentVersion,
ControlMask: powerThrottlingExecutionSpeed,
StateMask: 0,
}
r, _, err := procSetProcessInformation.Call(
h,
uintptr(processPowerThrottlingClass),
uintptr(unsafe.Pointer(&state)),
uintptr(unsafe.Sizeof(state)),
)
if r == 0 {
return fmt.Errorf("SetProcessInformation(ProcessPowerThrottling, %d): %w", pid, err)
}
return nil
}
// EnableWHPXElevated invokes a standard Windows UAC prompt to enable Windows Hypervisor Platform.
func EnableWHPXElevated() error {
verb, _ := syscall.UTF16PtrFromString("runas")
file, _ := syscall.UTF16PtrFromString("powershell.exe")
params, _ := syscall.UTF16PtrFromString(`-NoProfile -Command "Enable-WindowsOptionalFeature -Online -FeatureName HypervisorPlatform -All -NoRestart; Write-Host 'Done. Please restart Windows.'; Start-Sleep -Seconds 3"`)
r, _, err := procShellExecuteW.Call(
0,
uintptr(unsafe.Pointer(verb)),
uintptr(unsafe.Pointer(file)),
uintptr(unsafe.Pointer(params)),
0,
1, // SW_SHOWNORMAL
)
if r <= 32 {
return fmt.Errorf("ShellExecuteW runas failed (code %d): %w", r, err)
}
return nil
}
func probeWHPX() WHPXState {
mod := syscall.NewLazyDLL("WinHvPlatform.dll")
if err := mod.Load(); err != nil {
return WHPXMissing
}
proc := mod.NewProc("WHvGetCapability")
if err := proc.Find(); err != nil {
return WHPXMissing
}
var capVal uint64
var written uint32
hr, _, _ := proc.Call(
uintptr(whvCapHypervisorPresent),
uintptr(unsafe.Pointer(&capVal)),
uintptr(unsafe.Sizeof(capVal)),
uintptr(unsafe.Pointer(&written)),
)
if int32(hr) < 0 {
return WHPXNoHypervisor
}
if capVal&1 != 0 {
return WHPXReady
}
return WHPXNoHypervisor
}
// probeNeedsColdRebootWorkaround reports true on Windows hosts whose WinHvPlatform.dll
// does not export WHvResetPartition (e.g. Windows 10 19045), where in-guest warm reboots
// stall with WHPX Unexpected VP exit code 4 unless QEMU exits via -no-reboot and is
// cold-restarted in a fresh Hyper-V partition.
func probeNeedsColdRebootWorkaround() bool {
mod := syscall.NewLazyDLL("WinHvPlatform.dll")
if err := mod.Load(); err != nil {
return false
}
return mod.NewProc("WHvResetPartition").Find() != nil
}
type hybridTopology struct {
phys int
pCount int
eCount int
lpeCount int
pMask uint64
nonLPEMask uint64
pLPs []int
eLPs []int
nonLPELPs []int
cpus []LogicalCPUInfo
}
func probeHybridTopology() (topo hybridTopology, ok bool) {
var bufLen uint32
procGetLogicalProcessorInformationEx.Call(0, 0, uintptr(unsafe.Pointer(&bufLen)))
if bufLen == 0 {
return
}
buf := make([]byte, bufLen)
r, _, _ := procGetLogicalProcessorInformationEx.Call(
0, // RelationProcessorCore
uintptr(unsafe.Pointer(&buf[0])),
uintptr(unsafe.Pointer(&bufLen)),
)
if r == 0 {
return
}
type coreRec struct {
eff byte
mask uint64
}
var cores []coreRec
effSet := make(map[byte]bool)
var maxEff byte
var minEff byte = 0xFF
for off := uint32(0); off+48 <= bufLen; {
size := binary.LittleEndian.Uint32(buf[off+4 : off+8])
if size < 48 || off+size > bufLen {
break
}
eff := buf[off+9]
mask := binary.LittleEndian.Uint64(buf[off+32 : off+40])
if eff > maxEff {
maxEff = eff
}
if eff < minEff {
minEff = eff
}
effSet[eff] = true
cores = append(cores, coreRec{eff: eff, mask: mask})
off += size
}
if len(cores) == 0 {
return
}
hasThreeTiers := len(effSet) >= 3
isHybrid := len(effSet) >= 2
topo.phys = len(cores)
var eMask uint64
for coreIdx, c := range cores {
tier := "standard"
switch {
case c.eff == maxEff:
topo.pCount++
topo.pMask |= c.mask
topo.nonLPEMask |= c.mask
if isHybrid {
tier = "p"
}
case hasThreeTiers && c.eff == minEff:
topo.lpeCount++
tier = "lpe"
default:
topo.eCount++
eMask |= c.mask
topo.nonLPEMask |= c.mask
tier = "e"
}
smt := bits.OnesCount64(c.mask) > 1
for i := 0; i < 64; i++ {
if c.mask&(uint64(1)<<uint(i)) != 0 {
topo.cpus = append(topo.cpus, LogicalCPUInfo{
Index: i,
CoreIndex: coreIdx,
Tier: tier,
SMT: smt,
})
}
}
}
sort.Slice(topo.cpus, func(i, j int) bool {
return topo.cpus[i].Index < topo.cpus[j].Index
})
if !hasThreeTiers {
topo.nonLPEMask = 0
}
for i := 0; i < 64; i++ {
bit := uint64(1) << uint(i)
if topo.pMask&bit != 0 {
topo.pLPs = append(topo.pLPs, i)
}
if eMask&bit != 0 {
topo.eLPs = append(topo.eLPs, i)
}
if topo.nonLPEMask&bit != 0 {
topo.nonLPELPs = append(topo.nonLPELPs, i)
}
}
ok = true
return
}
func probeMemoryGB() (totalGB, availGB float64, ok bool) {
ms, ok := memoryStatus()
if !ok {
return 0, 0, false
}
const gb = 1024 * 1024 * 1024
return float64(ms.TotalPhys) / gb, float64(ms.AvailPhys) / gb, true
}
// probeCommitGB reads the commit limit Windows can reach and the commit it can
// still grant, including what the paging files can still grow
// (CommitHeadroom). GlobalMemoryStatusEx's "page file" fields are the current
// commit limit and free commit (not the page file alone); growthGB is the
// part added on top of them. When the paging files can't be read, growth is
// taken as zero and the current values stand.
func probeCommitGB() (limitGB, availGB, growthGB float64, ok bool) {
ms, ok := memoryStatus()
if !ok {
return 0, 0, 0, false
}
const gb = 1024 * 1024 * 1024
limitGB, availGB = float64(ms.TotalPageFile)/gb, float64(ms.AvailPageFile)/gb
files, err := probePagingFiles()
if err != nil {
return limitGB, availGB, 0, true
}
growthGB = PagingFileGrowthGB(files)
limitGB, availGB = CommitHeadroom(limitGB, availGB, files)
return limitGB, availGB, growthGB, true
}
func memoryStatus() (memoryStatusEx, bool) {
var ms memoryStatusEx
ms.Length = uint32(unsafe.Sizeof(ms))
r, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&ms)))
return ms, r != 0
}
// CommitAvailGB is the commit memory Windows can grant right now, paging file
// growth included (for start-time checks).
func CommitAvailGB() (float64, bool) {
_, avail, _, ok := probeCommitGB()
return avail, ok
}
func probeFreeDiskGB(path string) (float64, bool) {
vol := filepath.VolumeName(path)
if vol != "" {
path = vol + `\`
}
p, err := syscall.UTF16PtrFromString(path)
if err != nil {
return 0, false
}
var freeBytesAvail, totalBytes, totalFree uint64
r, _, _ := procGetDiskFreeSpaceExW.Call(
uintptr(unsafe.Pointer(p)),
uintptr(unsafe.Pointer(&freeBytesAvail)),
uintptr(unsafe.Pointer(&totalBytes)),
uintptr(unsafe.Pointer(&totalFree)),
)
if r == 0 {
return 0, false
}
return float64(freeBytesAvail) / (1024 * 1024 * 1024), true
}
// probeDriveType detects whether path resides on a local fixed drive, USB
// external enclosure (via IOCTL_STORAGE_QUERY_PROPERTY BusTypeUsb=7),
// removable drive, or network share. Requires no admin privileges.
func probeDriveType(path string) string {
vol := filepath.VolumeName(path)
if vol == "" {
return "unknown"
}
root := vol + `\`
p, err := syscall.UTF16PtrFromString(root)
if err != nil {
return "unknown"
}
dt, _, _ := procGetDriveTypeW.Call(uintptr(unsafe.Pointer(p)))
switch dt {
case 2: // DRIVE_REMOVABLE
return "removable"
case 4: // DRIVE_REMOTE
return "network"
case 3: // DRIVE_FIXED
if isUSBBusVolume(vol) {
return "usb"
}
return "fixed"
default:
return "unknown"
}
}
func isUSBBusVolume(vol string) bool {
if len(vol) < 2 || vol[1] != ':' {
return false
}
devPath, err := syscall.UTF16PtrFromString(`\\.\` + vol[:2])
if err != nil {
return false
}
// Access = 0 allows metadata IOCTLs (IOCTL_STORAGE_QUERY_PROPERTY) without elevation.
h, err := syscall.CreateFile(devPath, 0, syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE, nil, syscall.OPEN_EXISTING, 0, 0)
if err != nil || h == syscall.InvalidHandle {
return false
}
defer syscall.CloseHandle(h)
const ioctlStorageQueryProperty = 0x002D1400
var query [12]byte // STORAGE_PROPERTY_QUERY: PropertyId=0 (StorageDeviceProperty), QueryType=0
var out [512]byte
var returned uint32
r, _, _ := procDeviceIoControl.Call(
uintptr(h),
ioctlStorageQueryProperty,
uintptr(unsafe.Pointer(&query[0])),
uintptr(len(query)),
uintptr(unsafe.Pointer(&out[0])),
uintptr(len(out)),
uintptr(unsafe.Pointer(&returned)),
0,
)
if r == 0 || returned < 32 {
return false
}
// STORAGE_DEVICE_DESCRIPTOR.BusType is a 4-byte enum at offset 28; BusTypeUsb == 7.
busType := binary.LittleEndian.Uint32(out[28:32])
return busType == 7
}
// ProbeVulkanGPUs returns the current Vulkan adapters without using Inspect's cache.
func ProbeVulkanGPUs() []GPUInfo {
gpus, _ := probeVulkanGPUs()
return gpus
}
func probeVulkanGPUs() ([]GPUInfo, error) {
// 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)
for i, gpu := range gpus {
if gpu.VulkanICD != "" || gpu.VulkanVersion == "" {
continue
}
gpus[i].VulkanICD = recovered[gpu.VendorID+":"+gpu.DeviceID]
}
return gpus, err
}
func regReadString(root uintptr, subKey, valueName string) (string, bool) {
sk, err := syscall.UTF16PtrFromString(subKey)
if err != nil {
return "", false
}
var hKey uintptr
r, _, _ := procRegOpenKeyExW.Call(root, uintptr(unsafe.Pointer(sk)), 0, keyRead, uintptr(unsafe.Pointer(&hKey)))
if r != 0 {
return "", false
}
defer procRegCloseKey.Call(hKey)
vn, err := syscall.UTF16PtrFromString(valueName)
if err != nil {
return "", false
}
var typ, size uint32
r, _, _ = procRegQueryValueExW.Call(hKey, uintptr(unsafe.Pointer(vn)), 0, uintptr(unsafe.Pointer(&typ)), 0, uintptr(unsafe.Pointer(&size)))
if r != 0 || size == 0 {
return "", false
}
buf := make([]uint16, (size+1)/2)
r, _, _ = procRegQueryValueExW.Call(hKey, uintptr(unsafe.Pointer(vn)), 0, uintptr(unsafe.Pointer(&typ)), uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&size)))
if r != 0 {
return "", false
}
if typ != regSZ && typ != regExpandSZ && typ != regMultiSZ {
return "", false
}
// For REG_MULTI_SZ, take the first NUL-terminated entry (64-bit Vulkan ICD JSON).
return strings.TrimSpace(syscall.UTF16ToString(buf)), true
}