Files
Reims-Go/internal/host/host_windows.go
T
Nwflower 9e357ba38c fix(perf,sec): add 3-tier hybrid CPU affinity fallback and move QMP to AF_UNIX
- Detect 3-tier hybrid CPUs (P + E + LP-E, e.g. Intel Core Ultra 200 Arrow Lake) in host topology probe and select NonLPEMask (P+E, excluding slow LP-E cores) when VM vCPUs exceed P-core thread headroom
- Migrate Win10 cold-reboot secondary QMP socket from tcp:127.0.0.1:<port> to Windows AF_UNIX (reims-go-reboot.sock, with short tmp fallback) so guest code cannot reach unauthenticated QMP via SLIRP 10.0.2.2
- Automatically strip legacy tcp:127.0.0.1 QMP args on next start and update roadmap M3.2
2026-11-28 08:32:44 -07:00

376 lines
10 KiB
Go

//go:build windows
package host
import (
"encoding/binary"
"fmt"
"path/filepath"
"runtime"
"strings"
"syscall"
"unsafe"
)
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procGetLogicalProcessorInformationEx = kernel32.NewProc("GetLogicalProcessorInformationEx")
procGlobalMemoryStatusEx = kernel32.NewProc("GlobalMemoryStatusEx")
procGetDiskFreeSpaceExW = kernel32.NewProc("GetDiskFreeSpaceExW")
procOpenProcess = kernel32.NewProc("OpenProcess")
procSetProcessAffinityMask = kernel32.NewProc("SetProcessAffinityMask")
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
whvCapHypervisorPresent = 0x00000001
)
type memoryStatusEx struct {
Length uint32
MemoryLoad uint32
TotalPhys uint64
AvailPhys uint64
TotalPageFile uint64
AvailPageFile uint64
TotalVirtual uint64
AvailVirtual uint64
AvailExtendedVirtual uint64
}
// Inspect collects Windows host capabilities without requiring administrator privileges.
func Inspect(dataRoot string) Report {
rep := Report{
OS: "windows",
Arch: runtime.GOARCH,
LogicalCPUs: runtime.NumCPU(),
DataRoot: dataRoot,
WHPX: probeWHPX(),
NeedsColdRebootWorkaround: probeNeedsColdRebootWorkaround(),
GPUs: probeVulkanGPUs(),
}
if rep.WHPX == WHPXReady {
rep.WHPXCaps = probeWHPXCapabilities()
}
rep.RecommendedGPU = PickRecommendedGPU(rep.GPUs)
if topo, ok := probeHybridTopology(); ok {
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 = topo.pLPs
rep.ECoreLogicalCPUs = topo.eLPs
if topo.lpeCount > 0 && topo.nonLPEMask > 0 {
rep.NonLPEMask = topo.nonLPEMask
rep.NonLPEMaskHex = fmt.Sprintf("0x%X", topo.nonLPEMask)
rep.NonLPELogicalCPUs = topo.nonLPELPs
}
}
if totalGB, availGB, ok := probeMemoryGB(); ok {
rep.TotalRAMGB = totalGB
rep.AvailRAMGB = availGB
}
if limitGB, availGB, ok := probeCommitGB(); ok {
rep.CommitLimitGB = limitGB
rep.CommitAvailGB = availGB
}
if freeGB, ok := probeFreeDiskGB(dataRoot); ok {
rep.FreeDiskGB = freeGB
}
return rep
}
// PinProcessToPCores restricts the given PID's affinity mask to P-cores.
func PinProcessToPCores(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
}
// 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
}
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
topo.phys = len(cores)
var eMask uint64
for _, c := range cores {
switch {
case c.eff == maxEff:
topo.pCount++
topo.pMask |= c.mask
topo.nonLPEMask |= c.mask
case hasThreeTiers && c.eff == minEff:
topo.lpeCount++
default:
topo.eCount++
eMask |= c.mask
topo.nonLPEMask |= c.mask
}
}
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 system commit limit and what is still free in it.
// GlobalMemoryStatusEx's "page file" fields are the commit limit and the
// available commit for the system (not the page file alone).
func probeCommitGB() (limitGB, availGB float64, ok bool) {
ms, ok := memoryStatus()
if !ok {
return 0, 0, false
}
const gb = 1024 * 1024 * 1024
return float64(ms.TotalPageFile) / gb, float64(ms.AvailPageFile) / gb, 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 free right now (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
}
func probeVulkanGPUs() []GPUInfo {
const baseKey = `SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}`
var out []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
}
out = append(out, GPUInfo{
Name: desc,
VulkanICD: icd,
Kind: ClassifyGPU(desc),
})
}
return out
}
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
}