Files
Reims-Go/internal/vmstart/vmstart.go
T
NwflowerandClaude Opus 5.5 331d0748a4 refactor(vmstart): share VM start preparation between GUI and CLI
New internal/vmstart holds the steps both front ends need: commit-memory
precheck, offline helper disk, recovery boot picker, guest-language replay,
WHPX nested-virt compatibility, and P-core pinning after start. app.go's
StartVM and the CLI's "vm start" / "vm create --start" (cmd/reims-go/start.go)
call it, replacing memcheck.go and the copies in install/opencore flows.
"vm start" now refuses a VM that is already running instead of rewriting its
OpenCore image. Guest Tools bridging and the Win10 cold-reboot watcher still
need a long-lived process and stay GUI-only (architecture.md 3.5).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:51:23 -07:00

294 lines
11 KiB
Go

// Package vmstart holds what has to happen around `reims-ctl start` for both
// the GUI and the CLI (docs/architecture.md principle 3): the commit-memory
// check, VM preparation before QEMU launches, the macOS language preset and
// P-core pinning afterwards.
//
// Two start steps stay in the GUI because they need a process that outlives
// the start command: the Guest Tools bridge (guesttools_flow.go) and the Win10
// cold-reboot watcher (app.go).
package vmstart
import (
"bufio"
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/installer"
"github.com/Nwflower/reims-go/internal/opencore"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
// Prep runs start preparation against the active runtime. Log receives one
// human-readable line per step; the GUI routes it to the VM's log panel, the
// CLI to stderr.
type Prep struct {
Client *reims.Client
Runtime rt.Installed
cfg config.Config
log func(string)
}
// New resolves the active runtime for cfg. It fails when none is installed.
func New(cfg config.Config, log func(string)) (*Prep, error) {
active, err := rt.ResolveActive(&cfg)
if err != nil || active == nil {
return nil, fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed"))
}
if log == nil {
log = func(string) {}
}
return &Prep{Client: reims.NewClient(&cfg, *active), Runtime: *active, cfg: cfg, log: log}, nil
}
// CheckMemory refuses to start a VM whose guest RAM can't be committed right
// now. Without it QEMU exits with "Cannot set up guest memory 'ram'" (measured
// 2026-11-28, portable-runtime-spec.md §5.1), which says nothing about what to do.
func (p *Prep) CheckMemory(memory string, rep host.Report) error {
avail, ok := host.CommitAvailGB()
if !ok {
return nil
}
memGB, ok := reims.ParseSizeGB(memory)
if !ok || memGB+host.StartMarginGB <= avail {
return nil
}
return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.commit_memory", memGB, avail, host.RecommendedMemoryGB(rep)))
}
// Prepare brings a stopped VM's configuration up to date before it starts:
// the offline-install helper disk, the recovery boot picker, the macOS
// language preset and the WHPX nested-virtualization fallback. cur is updated
// to match what was written through `reims-ctl set`.
func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) {
p.syncOfflineHelper(ctx, name, cur)
p.syncRecoveryBootPicker(ctx, name, cur)
p.ReplayGuestLang(ctx, cur.Directory)
p.applyProbedWHPXCompat(ctx, name, rep, cur)
}
func (p *Prep) setExtraArgs(ctx context.Context, name, args string) error {
return p.Client.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &args}, io.Discard, io.Discard)
}
// syncOfflineHelper attaches the REIMSHELP HFS+ helper disk while an offline
// installer is attached, and strips it once the installer is ejected.
func (p *Prep) syncOfflineHelper(ctx context.Context, name string, cur *reims.VMDetail) {
if cur.HasInstaller && reims.IsOfflineInstallerPath(cur.InstallerPath) {
p.log("Preparing offline install helper disk (REIMSHELP)...")
helperPath, err := installer.EnsureOfflineHelperImage(p.cfg.XDGCacheDir(), cur.InstallerPath)
if err != nil {
p.log("Warning: offline install helper disk skipped: " + err.Error())
return
}
merged := reims.MergeOfflineHelperArgs(cur.ExtraArgs, helperPath)
if merged != cur.ExtraArgs {
if err := p.setExtraArgs(ctx, name, merged); err != nil {
p.log("Warning: could not attach REIMSHELP disk: " + err.Error())
return
}
cur.ExtraArgs = merged
}
return
}
stripped := reims.StripOfflineHelperArgs(cur.ExtraArgs)
if stripped != cur.ExtraArgs {
if err := p.setExtraArgs(ctx, name, stripped); err == nil {
cur.ExtraArgs = stripped
}
}
}
// syncRecoveryBootPicker applies a recovery-mode switch made while the VM was
// running: update-opencore needs a stopped VM (upstream 3731afd
// opencore.rs:400-402), so the switch is recorded in a marker file and done here.
func (p *Prep) syncRecoveryBootPicker(ctx context.Context, name string, cur *reims.VMDetail) {
var show bool
var done string
switch ReadRecoveryMarker(cur.Directory) {
case "want":
p.log("Enabling OpenCore boot picker for recovery mode...")
show, done = true, "on"
case "restore":
p.log("Restoring OpenCore direct boot after exiting recovery mode...")
show, done = false, ""
default:
return
}
w := LineWriter(p.log)
if err := p.Client.UpdateOpenCore(ctx, name, show, w, w); err != nil {
p.log("Warning: could not update OpenCore boot picker: " + err.Error())
return
}
WriteRecoveryMarker(cur.Directory, done)
p.ReplayGuestLang(ctx, cur.Directory)
}
// applyProbedWHPXCompat pre-applies `-machine kernel-irqchip=off` on Windows 11
// builds where WHvPartitionPropertyCodeNestedVirtualization is probed as
// unsupported (e.g. hr=0x80370302) and the active runtime lacks
// qemu-whpx-nested-virt-nonfatal.patch, avoiding a first-start crash and retry.
func (p *Prep) applyProbedWHPXCompat(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) {
if rep.NeedsColdRebootWorkaround || !rep.WHPXCaps.KernelIrqchipAvailable || rep.WHPXCaps.NestedVirtProperty {
return
}
if p.RuntimeHasPatch("nested-virt-nonfatal") || reims.HasKernelIrqchipArg(cur.ExtraArgs) {
return
}
merged := reims.MergeKernelIrqchipOffArgs(cur.ExtraArgs)
if err := p.setExtraArgs(ctx, name, merged); err != nil {
return
}
cur.ExtraArgs = merged
code := rep.WHPXCaps.NestedVirtProbeError
if code == "" {
code = "unsupported"
}
if p.cfg.Locale == i18n.ZhCN {
p.log(fmt.Sprintf("[兼容] 当前 Windows 不支持嵌套虚拟化属性(%s),已自动启用 kernel-irqchip=off", code))
} else {
p.log(fmt.Sprintf("[compat] Host rejects nested-virtualization property (%s); enabled kernel-irqchip=off automatically", code))
}
}
// RuntimeHasPatch reports whether the active runtime was built with a patch
// whose name contains substr (case-insensitive).
func (p *Prep) RuntimeHasPatch(substr string) bool {
needle := strings.ToLower(substr)
for _, patch := range p.Runtime.Manifest.Patches {
if strings.Contains(strings.ToLower(patch.Name), needle) {
return true
}
}
return false
}
// ApplyGuestLang saves the VM's macOS prev-lang:kbd preference and, when the
// VM is stopped, writes it into the OpenCore image right away. A running VM
// gets it on its next start (ReplayGuestLang). An empty lang is a no-op.
func (p *Prep) ApplyGuestLang(ctx context.Context, vmDir, lang string, running bool) error {
norm, err := opencore.NormalizeGuestLang(lang)
if err != nil || norm == "" {
return err
}
if err := opencore.WriteSavedGuestLang(vmDir, norm); err != nil {
return err
}
if running {
p.log(fmt.Sprintf("Scheduled macOS boot/recovery language (%s) for next start", norm))
return nil
}
return p.patchGuestLang(ctx, vmDir, norm)
}
// ReplayGuestLang re-applies the saved language after anything that rebuilds
// the OpenCore image (update-opencore, a graphics switch, a clone) and before
// every start. Failures are logged, not returned: the VM still boots.
func (p *Prep) ReplayGuestLang(ctx context.Context, vmDir string) {
saved := opencore.ReadSavedGuestLang(vmDir)
if saved == "" {
return
}
if err := p.patchGuestLang(ctx, vmDir, saved); err != nil {
p.log(fmt.Sprintf("Warning: could not apply macOS language (%s) to OpenCore: %v", saved, err))
}
}
func (p *Prep) patchGuestLang(ctx context.Context, vmDir, lang string) error {
ocPath := opencore.ResolveOpenCorePath(vmDir)
if ocPath == "" {
return nil
}
changed, err := opencore.PatchImagePrevLang(ctx, ocPath, lang, p.Runtime.QemuImgPath(), p.Client.Env)
if err != nil {
return err
}
if changed {
p.log(fmt.Sprintf("Applied macOS boot/recovery language (%s) to OpenCore NVRAM", lang))
}
return nil
}
// PinQEMU sets a running VM's QEMU process affinity per host.SelectSafeAffinity
// and returns the line to log about it.
func PinQEMU(loc i18n.Locale, rep host.Report, pid, vcpus int) string {
plan := host.SelectSafeAffinity(rep, vcpus)
zh := loc == i18n.ZhCN
if plan.Mode == "all" {
if zh {
return fmt.Sprintf("[CPU] 跳过绑核:虚拟机配置了 %d vCPU,超过可用安全绑定线程上限(P 核仅 %d 线程),已使用全部核心避免超售卡顿", vcpus, plan.PThreads)
}
return fmt.Sprintf("[CPU] Skipped CPU pinning: VM has %d vCPUs, exceeding safe headroom (only %d P-core threads); using all host CPUs to avoid spinlock stall", vcpus, plan.PThreads)
}
err := host.PinProcessToPCores(uint32(pid), plan.Mask)
if plan.Mode == "non_lpe" {
if err != nil {
return fmt.Sprintf("[CPU] Warning: P+E core pinning failed for PID %d: %v", pid, err)
}
if zh {
return fmt.Sprintf("[CPU] 虚拟机配置了 %d vCPU(超过 %d 个 P 核线程),已自动将 QEMU (PID %d) 绑定到 P+E 核(%d 核 / %d 线程,掩码 %s;仅排除 %d 个慢速 LP-E 核)",
vcpus, plan.PThreads, pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, rep.LPECoreCount)
}
return fmt.Sprintf("[CPU] VM has %d vCPUs (exceeds %d P-core threads); pinned QEMU (PID %d) to P+E cores (%d cores / %d logical CPUs, mask %s; %d slow LP-E cores excluded)",
vcpus, plan.PThreads, pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, rep.LPECoreCount)
}
if err != nil {
return fmt.Sprintf("[CPU] Warning: P-core pinning failed for PID %d: %v", pid, err)
}
if zh {
return fmt.Sprintf("[CPU] 已将 QEMU (PID %d) 绑定到 %d 个 P 核(%d 个逻辑线程,掩码 %s;未占用 %d 个 E 核)",
pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, rep.ECoreCount+rep.LPECoreCount)
}
return fmt.Sprintf("[CPU] Pinned QEMU (PID %d) to %d P-cores (%d logical CPUs, mask %s; %d E/LP-E cores excluded)",
pid, plan.CoreCount, plan.ThreadCount, plan.MaskHex, rep.ECoreCount+rep.LPECoreCount)
}
const recoveryMarkerFile = ".reims-go-recovery-picker"
// ReadRecoveryMarker returns the VM's pending recovery boot-picker state:
// "want" (enable on next start), "on" (enabled), "restore" (disable on next
// start) or "" (none).
func ReadRecoveryMarker(vmDir string) string {
if vmDir == "" {
return ""
}
b, err := os.ReadFile(filepath.Join(vmDir, recoveryMarkerFile))
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
// WriteRecoveryMarker records state; "" removes the marker.
func WriteRecoveryMarker(vmDir, state string) {
if vmDir == "" {
return
}
p := filepath.Join(vmDir, recoveryMarkerFile)
if state == "" {
_ = os.Remove(p)
return
}
_ = os.WriteFile(p, []byte(state), 0o644)
}
// LineWriter turns command output into one log call per non-empty line.
type LineWriter func(string)
func (w LineWriter) Write(b []byte) (int, error) {
sc := bufio.NewScanner(strings.NewReader(string(b)))
for sc.Scan() {
if line := strings.TrimSpace(sc.Text()); line != "" {
w(line)
}
}
return len(b), nil
}