Files
Reims-Go/internal/macos/reims/compat.go
T

256 lines
8.0 KiB
Go

package reims
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"regexp"
"slices"
"strings"
"sync"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
// creatingMarker is written by upstream `reims-ctl create` while building a VM
// directory and removed once vm.toml is saved (upstream 3731afd create.rs:451).
const creatingMarker = ".reims-ctl-creating"
// CleanAbortedCreateDir removes an unregistered VM target directory left behind
// by a previously killed `reims-ctl create` run. It only removes a directory
// when all three safety conditions hold:
// 1. opts.Name is not present in registered VMs,
// 2. `.reims-ctl-creating` exists inside the directory, and
// 3. `vm.toml` does NOT exist inside the directory.
//
// Returns the removed path if cleaned, or "" if nothing was touched.
func CleanAbortedCreateDir(xdgDataDir string, opts CreateOpts, registered []VMListItem) (string, error) {
name := strings.TrimSpace(opts.Name)
if name == "" {
return "", nil
}
for _, vm := range registered {
if strings.EqualFold(vm.Name, name) {
return "", nil
}
}
target := strings.TrimSpace(opts.Dir)
if target == "" {
if strings.TrimSpace(xdgDataDir) == "" {
return "", nil
}
target = filepath.Join(xdgDataDir, "reims-ctl", "vms", name)
}
markerInfo, err := os.Stat(filepath.Join(target, creatingMarker))
if err != nil || markerInfo.IsDir() {
return "", nil
}
if _, err := os.Stat(filepath.Join(target, "vm.toml")); err == nil {
return "", nil
}
if err := os.RemoveAll(target); err != nil {
return "", err
}
return target, nil
}
// IsWHPXNoAcceleratorError reports whether QEMU exited because Windows
// Hypervisor was not active. In that branch QEMU logs "WHPX: No accelerator
// found" and returns -ENOSPC ("failed to initialize whpx: No space left on
// device"), which is unrelated to disk space.
func IsWHPXNoAcceleratorError(output string) bool {
return strings.Contains(output, "WHPX: No accelerator found") ||
strings.Contains(output, "failed to initialize whpx: No space left on device")
}
// IsWHPXNestedVirtError reports whether QEMU exited because WHPX failed to
// enable nested virtualization (e.g. hr=80370302 WHV_E_UNKNOWN_PROPERTY on
// Windows 11 builds that advertise Bank1.NestedVirtSupport but reject
// WHvPartitionPropertyCodeNestedVirtualization; qemu-reims-vgpu 4571bc5
// target/i386/whpx/whpx-all.c:3471-3484).
func IsWHPXNestedVirtError(output string) bool {
return strings.Contains(output, "WHPX: Failed to enable nested virtualization")
}
// DiagnoseGPULog inspects QEMU / reims-vgpu output for known Vulkan GPU
// compatibility or device-loss failures and returns a machine-readable code
// ("gpu_device_lost" | "gpu_vulkan_floor") and matching line excerpt.
func DiagnoseGPULog(output string) (code, detail string) { return host.DiagnoseGPULog(output) }
// HasKernelIrqchipArg reports whether extra-args already specifies a
// kernel-irqchip setting.
func HasKernelIrqchipArg(extraArgs string) bool {
return strings.Contains(strings.ToLower(extraArgs), "kernel-irqchip=")
}
// MergeKernelIrqchipOffArgs appends `-machine kernel-irqchip=off` to existing
// QEMU extra-args unless a kernel-irqchip setting is already present.
func MergeKernelIrqchipOffArgs(existing string) string {
trimmed := strings.TrimSpace(existing)
if HasKernelIrqchipArg(trimmed) {
return trimmed
}
const flag = "-machine kernel-irqchip=off"
if trimmed == "" {
return flag
}
return trimmed + " " + flag
}
type captureWriter struct {
mu sync.Mutex
buf bytes.Buffer
dst io.Writer
}
func (w *captureWriter) Write(p []byte) (int, error) {
w.mu.Lock()
if w.buf.Len() < 64*1024 {
w.buf.Write(p)
}
w.mu.Unlock()
if w.dst != nil {
return w.dst.Write(p)
}
return len(p), nil
}
func (w *captureWriter) String() string {
w.mu.Lock()
defer w.mu.Unlock()
return w.buf.String()
}
var driverStoreICDPattern = regexp.MustCompile(`^([a-z]:/(?:[^/]+/)*driverstore/filerepository)/([^/]+)_[0-9a-f]{8,}/([^/]+(?:/[^/]+)*)$`)
func parseDriverStoreICD(raw string) []string {
cleaned := path.Clean(strings.ToLower(strings.ReplaceAll(strings.TrimSpace(raw), `\`, "/")))
return driverStoreICDPattern.FindStringSubmatch(cleaned)
}
// ResolveStaleDriverStoreICD matches a stale ICD to the same driver package and
// relative path, provided exactly one physical adapter matches and is usable.
func ResolveStaleDriverStoreICD(oldPath string, gpus []host.GPUInfo) (newPath string, ambiguous bool) {
old := parseDriverStoreICD(oldPath)
if old == nil {
return "", false
}
var matched []host.GPUInfo
for _, gpu := range gpus {
if gpu.Kind == host.GPUVirtual {
continue
}
candidate := parseDriverStoreICD(gpu.VulkanICD)
if candidate != nil && slices.Equal(candidate[1:], old[1:]) {
matched = append(matched, gpu)
}
}
if len(matched) != 1 {
return "", len(matched) > 1
}
gpu := matched[0]
// Warning grades can also come from PCI IDs alone. A Vulkan version
// confirms that the adapter was probed.
if gpu.VulkanVersion == "" || (gpu.Compat != host.GPUCompatSupported && gpu.Compat != host.GPUCompatWarn) {
return "", false
}
return gpu.VulkanICD, false
}
func (c *Client) reconcileStaleGPUICD(ctx context.Context, name string, stderr io.Writer, onNote func(string)) error {
detail, err := c.Show(ctx, name)
if err != nil || detail.Graphics != "reims-vgpu" || detail.State == "running" {
return nil
}
oldPath := strings.TrimSpace(detail.GPU)
if !strings.HasSuffix(strings.ToLower(oldPath), ".json") {
return nil
}
stat := c.statFile
if stat == nil {
stat = os.Stat
}
if _, err := stat(oldPath); !errors.Is(err, os.ErrNotExist) {
return nil
}
probe := c.probeGPUs
if probe == nil {
probe = host.ProbeVulkanGPUs
}
if onNote == nil && stderr != nil {
onNote = func(msg string) { fmt.Fprintln(stderr, msg) }
}
newPath, _ := ResolveStaleDriverStoreICD(oldPath, probe())
if newPath == "" {
msg := i18n.M(c.Locale, "err.gpu_icd_stale", i18n.Vars{"path": oldPath})
if onNote != nil {
onNote(msg)
}
return errors.New(msg)
}
var setErrBuf bytes.Buffer
if err := c.Set(ctx, SetOpts{Name: name, GPU: newPath}, io.Discard, &setErrBuf); err != nil {
if detail := strings.TrimSpace(setErrBuf.String()); detail != "" {
return fmt.Errorf("reims-ctl set %s --gpu: %w (%s)", name, err, detail)
}
return fmt.Errorf("reims-ctl set %s --gpu: %w", name, err)
}
if onNote != nil {
onNote(i18n.M(c.Locale, "compat.gpu_icd_rebound", i18n.Vars{"old": oldPath, "new": newPath}))
}
return nil
}
// StartWithCompat checks the configured Vulkan ICD before starting a VM and
// automatically recovers once if QEMU aborts with the WHPX nested-virtualization
// property error (hr=80370302) by setting `-machine kernel-irqchip=off` via
// `reims-ctl set` and retrying start.
func (c *Client) StartWithCompat(ctx context.Context, name string, stdout, stderr io.Writer, onNote func(string)) error {
if err := c.reconcileStaleGPUICD(ctx, name, stderr, onNote); err != nil {
return err
}
outCap := &captureWriter{dst: stdout}
errCap := &captureWriter{dst: stderr}
err := c.Start(ctx, name, outCap, errCap)
if err == nil {
return nil
}
combined := outCap.String() + "\n" + errCap.String()
if IsWHPXNoAcceleratorError(combined) {
msg := i18n.T(c.Locale, "err.whpx_no_hypervisor")
if onNote != nil {
onNote(msg)
}
return fmt.Errorf("%s (%w)", msg, err)
}
if gpuCode, _ := DiagnoseGPULog(combined); gpuCode != "" {
msg := i18n.T(c.Locale, "err."+gpuCode)
if onNote != nil {
onNote(msg)
}
return fmt.Errorf("%s (%w)", msg, err)
}
if !IsWHPXNestedVirtError(combined) {
return err
}
cur, serr := c.Show(ctx, name)
if serr != nil || HasKernelIrqchipArg(cur.ExtraArgs) {
return err
}
merged := MergeKernelIrqchipOffArgs(cur.ExtraArgs)
if setErr := c.Set(ctx, SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); setErr != nil {
return err
}
if onNote != nil {
onNote("WHPX host rejected nested virtualization property (hr=80370302); applied -machine kernel-irqchip=off and retrying start...")
}
return c.Start(ctx, name, stdout, stderr)
}