package vmstart import ( "encoding/json" "errors" "fmt" "math/bits" "os" "path/filepath" "strings" "github.com/Nwflower/reims-go/internal/atomicfile" "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 } if err := atomicfile.WriteJSON(filepath.Join(vmDir, affinityConfigFile), cfg, 0o600); err != nil { 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) ecoDisabled := false if res.DisableEcoQoS { if err := host.DisableProcessPowerThrottling(uint32(pid)); err == nil { ecoDisabled = true } } var ecoSuffix string if ecoDisabled { ecoSuffix = i18n.T(loc, "affinity.eco_suffix") } 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 "", i18n.NewCodedError(loc, "E_AFFINITY_EMPTY_MASK", "err.affinity.empty_mask", nil, nil) } 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) vars := i18n.Vars{"pid": pid, "count": count, "mask": maskHex, "eco": ecoSuffix} switch res.EffectiveMode { case AffinityPCores: return i18n.M(loc, "affinity.applied.pcores", vars), nil case AffinityNonLPE: return i18n.M(loc, "affinity.applied.non_lpe", vars), nil case AffinityCustom: return i18n.M(loc, "affinity.applied.custom", vars), nil default: return i18n.M(loc, "affinity.applied.all", vars), nil } } if res.AutoSkipped { return i18n.M(loc, "affinity.skipped", i18n.Vars{ "vcpus": vcpus, "pthreads": res.PThreads, "eco": ecoSuffix, }), nil } if ecoDisabled { return i18n.M(loc, "affinity.eco_only", i18n.Vars{"pid": 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) switch res.EffectiveMode { case AffinityPCores: return i18n.M(loc, "affinity.summary.pcores", i18n.Vars{"count": len(res.CPUs)}) case AffinityNonLPE: return i18n.M(loc, "affinity.summary.non_lpe", i18n.Vars{"count": len(res.CPUs)}) case AffinityCustom: return i18n.M(loc, "affinity.summary.custom", i18n.Vars{"count": len(res.CPUs), "mask": res.MaskHex}) default: if res.AutoSkipped { return i18n.M(loc, "affinity.summary.skipped", i18n.Vars{"vcpus": vcpus, "pthreads": res.PThreads}) } return i18n.T(loc, "affinity.summary.all") } }