package vmstart import ( "encoding/json" "errors" "fmt" "math/bits" "os" "path/filepath" "strings" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" ) const affinityConfigFile = ".reims-go-affinity.json" // AffinityMode selects how a VM's QEMU process maps onto host logical CPUs. type AffinityMode string const ( AffinityAuto AffinityMode = "auto" AffinityAll AffinityMode = "all" AffinityPCores AffinityMode = "pcores" AffinityNonLPE AffinityMode = "non_lpe" AffinityCustom AffinityMode = "custom" ) // VMAffinityConfig is persisted per VM in /.reims-go-affinity.json // without modifying upstream vm.toml. type VMAffinityConfig struct { Mode AffinityMode `json:"mode"` CPUs []int `json:"cpus,omitempty"` DisableEcoQoS *bool `json:"disable_eco_qos,omitempty"` } // ShouldDisableEcoQoS reports whether Windows EcoQoS power throttling should // be turned off for the VM's QEMU process. Defaults to true. func (c VMAffinityConfig) ShouldDisableEcoQoS() bool { if c.DisableEcoQoS == nil { return true } return *c.DisableEcoQoS } // NormalizeAffinityMode maps empty or unknown mode values to AffinityAuto. func NormalizeAffinityMode(m AffinityMode) AffinityMode { switch AffinityMode(strings.ToLower(strings.TrimSpace(string(m)))) { case AffinityAll: return AffinityAll case AffinityPCores: return AffinityPCores case AffinityNonLPE: return AffinityNonLPE case AffinityCustom: return AffinityCustom default: return AffinityAuto } } // DefaultVMAffinityConfig returns the default per-VM affinity preference. func DefaultVMAffinityConfig() VMAffinityConfig { eco := true return VMAffinityConfig{ Mode: AffinityAuto, DisableEcoQoS: &eco, } } // ReadVMAffinity loads /.reims-go-affinity.json, returning defaults when // absent or unreadable. func ReadVMAffinity(vmDir string) VMAffinityConfig { def := DefaultVMAffinityConfig() if strings.TrimSpace(vmDir) == "" { return def } raw, err := os.ReadFile(filepath.Join(vmDir, affinityConfigFile)) if err != nil { return def } var cfg VMAffinityConfig if json.Unmarshal(raw, &cfg) != nil { return def } cfg.Mode = NormalizeAffinityMode(cfg.Mode) if cfg.Mode == AffinityCustom { _, cfg.CPUs = host.CPUsToMask(cfg.CPUs, 64) } else { cfg.CPUs = nil } if cfg.DisableEcoQoS == nil { eco := true cfg.DisableEcoQoS = &eco } return cfg } // HasSavedVMAffinity reports whether /.reims-go-affinity.json exists. func HasSavedVMAffinity(vmDir string) bool { if strings.TrimSpace(vmDir) == "" { return false } _, err := os.Stat(filepath.Join(vmDir, affinityConfigFile)) return err == nil } // SaveVMAffinity validates and atomically writes /.reims-go-affinity.json. func SaveVMAffinity(vmDir string, cfg VMAffinityConfig, maxCPUs int) (VMAffinityConfig, error) { if strings.TrimSpace(vmDir) == "" { return VMAffinityConfig{}, errors.New("VM directory is empty") } cfg.Mode = NormalizeAffinityMode(cfg.Mode) if cfg.DisableEcoQoS == nil { eco := true cfg.DisableEcoQoS = &eco } if cfg.Mode == AffinityCustom { limit := maxCPUs if limit <= 0 || limit > 64 { limit = 64 } mask, normalized := host.CPUsToMask(cfg.CPUs, limit) if mask == 0 { return VMAffinityConfig{}, errors.New("select at least one valid host CPU") } cfg.CPUs = normalized } else { cfg.CPUs = nil } data, err := json.MarshalIndent(cfg, "", " ") if err != nil { return VMAffinityConfig{}, err } dst := filepath.Join(vmDir, affinityConfigFile) tmp := dst + ".tmp" if err := os.WriteFile(tmp, data, 0o600); err != nil { return VMAffinityConfig{}, err } if err := os.Rename(tmp, dst); err != nil { _ = os.Remove(tmp) return VMAffinityConfig{}, err } return cfg, nil } // ResolvedAffinity is the concrete CPU mask computed for a VM on the current host. type ResolvedAffinity struct { ConfigMode AffinityMode EffectiveMode AffinityMode Mask uint64 MaskHex string CPUs []int ShouldPin bool DisableEcoQoS bool AutoSkipped bool PThreads int } // ResolveVMAffinity computes the effective host CPU mask for a VM given its // saved config, global auto-pin setting, current host report, and vCPU count. func ResolveVMAffinity(cfg VMAffinityConfig, globalAutoPin bool, rep host.Report, vcpus int) ResolvedAffinity { limit := rep.LogicalCPUs if limit <= 0 { limit = len(rep.CPUTopology) } if limit <= 0 { limit = 64 } if limit > 64 { limit = 64 } allMask := host.AllCPUsMask(limit) allCPUs := host.MaskToCPUs(allMask, limit) mode := NormalizeAffinityMode(cfg.Mode) res := ResolvedAffinity{ ConfigMode: mode, EffectiveMode: AffinityAll, Mask: allMask, MaskHex: fmt.Sprintf("0x%X", allMask), CPUs: allCPUs, DisableEcoQoS: cfg.ShouldDisableEcoQoS(), PThreads: len(rep.PCoreLogicalCPUs), } if res.PThreads == 0 { res.PThreads = rep.PCoreCount } applyMask := func(eff AffinityMode, mask uint64) ResolvedAffinity { if mask == 0 { return res } cpus := host.MaskToCPUs(mask, limit) if len(cpus) == 0 { return res } res.EffectiveMode = eff res.Mask = mask res.MaskHex = fmt.Sprintf("0x%X", mask) res.CPUs = cpus res.ShouldPin = mask != allMask return res } switch mode { case AffinityAll: return res case AffinityPCores: if rep.HasHybridCores && rep.PCoreMask > 0 { return applyMask(AffinityPCores, rep.PCoreMask) } return res case AffinityNonLPE: if rep.LPECoreCount > 0 && rep.NonLPEMask > 0 { return applyMask(AffinityNonLPE, rep.NonLPEMask) } return res case AffinityCustom: mask, _ := host.CPUsToMask(cfg.CPUs, limit) if mask != 0 { return applyMask(AffinityCustom, mask) } return res default: // AffinityAuto if !globalAutoPin || !rep.HasHybridCores || rep.PCoreMask == 0 { return res } plan := host.SelectSafeAffinity(rep, vcpus) res.PThreads = plan.PThreads switch plan.Mode { case "pcores": return applyMask(AffinityPCores, plan.Mask) case "non_lpe": return applyMask(AffinityNonLPE, plan.Mask) default: res.AutoSkipped = true return res } } } // ApplyVMAffinity applies the VM's persisted CPU affinity mask and EcoQoS // setting to a running QEMU PID. When forceApplyAll is true (e.g. a live user // edit switching back to "all"), SetProcessAffinityMask is called even for the // all-CPUs mask to clear any previous restriction. func ApplyVMAffinity(loc i18n.Locale, rep host.Report, vmDir string, globalAutoPin bool, pid, vcpus int, forceApplyAll bool) (string, error) { cfg := ReadVMAffinity(vmDir) res := ResolveVMAffinity(cfg, globalAutoPin, rep, vcpus) zh := loc == i18n.ZhCN ecoDisabled := false if res.DisableEcoQoS { if err := host.DisableProcessPowerThrottling(uint32(pid)); err == nil { ecoDisabled = true } } var ecoSuffix string if ecoDisabled { if zh { ecoSuffix = ",已禁用 EcoQoS 节流" } else { ecoSuffix = ", EcoQoS disabled" } } if res.ShouldPin || forceApplyAll { targetMask := res.Mask if res.EffectiveMode == AffinityAll { if _, sysMask, err := host.GetProcessAffinityMask(uint32(pid)); err == nil && sysMask != 0 { targetMask = sysMask } } if targetMask == 0 { return "", errors.New("no valid CPU affinity mask available") } if err := host.SetProcessAffinityMask(uint32(pid), targetMask); err != nil { line := fmt.Sprintf("[CPU] Warning: CPU affinity update failed for PID %d (mask 0x%X): %v", pid, targetMask, err) return line, err } count := bits.OnesCount64(targetMask) maskHex := fmt.Sprintf("0x%X", targetMask) switch res.EffectiveMode { case AffinityPCores: if zh { return fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 绑定到 P 核(%d 个逻辑处理器,掩码 %s%s)", pid, count, maskHex, ecoSuffix), nil } return fmt.Sprintf("[CPU] Pinned QEMU (PID %d) to P-cores (%d logical CPUs, mask %s%s)", pid, count, maskHex, ecoSuffix), nil case AffinityNonLPE: if zh { return fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 绑定到 P+E 核(%d 个逻辑处理器,排除 LP-E 核,掩码 %s%s)", pid, count, maskHex, ecoSuffix), nil } return fmt.Sprintf("[CPU] Pinned QEMU (PID %d) to P+E cores (%d logical CPUs, LP-E excluded, mask %s%s)", pid, count, maskHex, ecoSuffix), nil case AffinityCustom: if zh { return fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 映射到自定义核心(%d 个逻辑处理器,掩码 %s%s)", pid, count, maskHex, ecoSuffix), nil } return fmt.Sprintf("[CPU] Mapped QEMU (PID %d) to custom CPUs (%d logical CPUs, mask %s%s)", pid, count, maskHex, ecoSuffix), nil default: if zh { return fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 设为所有处理器(%d 个逻辑处理器,掩码 %s%s)", pid, count, maskHex, ecoSuffix), nil } return fmt.Sprintf("[CPU] Set QEMU (PID %d) affinity to all CPUs (%d logical CPUs, mask %s%s)", pid, count, maskHex, ecoSuffix), nil } } if res.AutoSkipped { if zh { return fmt.Sprintf("[CPU] 跳过自动绑核:虚拟机配置了 %d vCPU,超过可用安全绑定上限(P 核仅 %d 线程),使用全部核心%s", vcpus, res.PThreads, ecoSuffix), nil } return fmt.Sprintf("[CPU] Skipped auto pinning: VM has %d vCPUs, exceeding safe headroom (only %d P-core threads); using all CPUs%s", vcpus, res.PThreads, ecoSuffix), nil } if ecoDisabled { if zh { return fmt.Sprintf("[CPU] 已为 QEMU (PID %d) 禁用 Windows EcoQoS 效率节流(当前使用全部处理器)", pid), nil } return fmt.Sprintf("[CPU] Disabled Windows EcoQoS power throttling for QEMU (PID %d) (using all CPUs)", pid), nil } return "", nil } // AffinitySummary formats a concise summary for startup logs. func AffinitySummary(loc i18n.Locale, rep host.Report, vmDir string, globalAutoPin bool, vcpus int) string { cfg := ReadVMAffinity(vmDir) res := ResolveVMAffinity(cfg, globalAutoPin, rep, vcpus) zh := loc == i18n.ZhCN switch res.EffectiveMode { case AffinityPCores: if zh { return fmt.Sprintf("P核(%d线程)", len(res.CPUs)) } return fmt.Sprintf("P-cores(%dT)", len(res.CPUs)) case AffinityNonLPE: if zh { return fmt.Sprintf("P+E(%d线程,避开LP-E)", len(res.CPUs)) } return fmt.Sprintf("P+E(%dT,no-LPE)", len(res.CPUs)) case AffinityCustom: if zh { return fmt.Sprintf("自定义(%d线程,%s)", len(res.CPUs), res.MaskHex) } return fmt.Sprintf("custom(%dT,%s)", len(res.CPUs), res.MaskHex) default: if res.AutoSkipped { if zh { return fmt.Sprintf("自动跳过(%d核≥%dP线程)", vcpus, res.PThreads) } return fmt.Sprintf("skipped(%dvCPU>=%dPT)", vcpus, res.PThreads) } if zh { return "全部核心" } return "all" } }