//go:build windows package host import ( "encoding/binary" "fmt" "math/bits" "os" "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 recGPU *GPUInfo topo hybridTopology topoOK bool } var ( staticHostOnce sync.Once staticHostData staticHostSnapshot whpxCapsMu sync.Mutex whpxCapsCached bool whpxCapsVal WHPXCapabilities ) func getStaticHostSnapshot() staticHostSnapshot { staticHostOnce.Do(func() { gpus := probeVulkanGPUs() topo, ok := probeHybridTopology() staticHostData = staticHostSnapshot{ needsColdReboot: probeNeedsColdRebootWorkaround(), gpus: gpus, recGPU: PickRecommendedGPU(gpus), topo: topo, topoOK: ok, } }) 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 } rep := Report{ OS: "windows", Arch: runtime.GOARCH, LogicalCPUs: runtime.NumCPU(), DataRoot: dataRoot, WHPX: probeWHPX(), NeedsColdRebootWorkaround: st.needsColdReboot, GPUs: gpusCopy, RecommendedGPU: recGPUCopy, } 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, ok := probeCommitGB(); ok { rep.CommitLimitGB = limitGB rep.CommitAvailGB = availGB } 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)<