diff --git a/changes/vm-nested-virtualization.json b/changes/vm-nested-virtualization.json new file mode 100644 index 0000000..22e8707 --- /dev/null +++ b/changes/vm-nested-virtualization.json @@ -0,0 +1,7 @@ +{ + "group": "new", + "order": 68, + "authors": ["zhongruan0522", "yxc0915"], + "zh": "支持 VMX 的 Windows 宿主机可为单台 macOS 虚拟机启用嵌套虚拟化。默认关闭,冷启动后生效。 [#72](https://github.com/Nwflower/Reims-Go/pull/72)", + "en": "Enable nested virtualization per macOS VM on Windows hosts with WHPX VMX support. Off by default, applied on cold start. [#72](https://github.com/Nwflower/Reims-Go/pull/72)" +} diff --git a/docs/design-guidelines.md b/docs/design-guidelines.md index ed4b134..cc423ba 100644 --- a/docs/design-guidelines.md +++ b/docs/design-guidelines.md @@ -4,6 +4,8 @@ ## 设计定位与配置原语 +嵌套虚拟化由客户端按虚拟机保存,默认关闭,冷启动时按宿主机的 WHPX 能力生成驱动参数。界面只显示用户手动添加的额外参数。 + 桌面界面采用贴近 macOS 系统设置的侧栏加详情结构和硬件分类词表,同时遵循 Windows 窗口控制、字体渲染与多档缩放习惯。宿主机全局能力(虚拟化平台、处理器调度、显卡驱动、运行时版本与数据目录)集中在「内核」与「设置」页,不混入单台虚拟机的设置表单。 1. 每台虚拟机对应一份声明式配置,界面只编辑结构化选项,不要求用户手工拼接底层启动命令行。 diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 58553cd..5cfd705 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -309,6 +309,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats const resBad = customRes && !RES_RE.test(form.resolution ?? '') const sshOn = (form.ssh_port ?? 0) > 0 const localBlock = resBad + const nestedVirtAvailable = host.whpx === 'ready' && host.whpx_caps?.nested_vmx && !host.needs_cold_reboot_workaround const rowProps = (f: Field) => ({ field: f, @@ -823,8 +824,9 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats set({ nested_virt })} />} + desc={tr(nestedVirtAvailable ? 'nestedVirtDesc' : 'nestedVirtUnavailable')} + error={detail.nested_virt_invalid && !dirty('nested_virt') ? tr('nestedVirtInvalid') : issueOf('nested_virt')} + control={ set({ nested_virt })} />} /> = { "minimizeToTraySub": "关闭窗口后剪贴板和共享文件夹继续工作,可从托盘启停虚拟机", "multiDisplayHint": "{n, plural, other {检测到 # 块显示器,排列方式在 macOS「系统设置 › 显示器」里调整}}", "navHasIssue": "这一页有需要修改的项", - "nestedVirtDesc": "在 macOS 里再运行虚拟机(如 Docker Desktop),部分电脑不支持,可能无法启用", + "nestedVirtDesc": "允许 macOS 运行自己的虚拟机,完全关机后再次启动时生效。", + "nestedVirtInvalid": "保存的设置无法读取,虚拟机将按默认 CPU 设置启动。", "nestedVirtLabel": "嵌套虚拟化", + "nestedVirtUnavailable": "当前 Windows 宿主机无法通过 WHPX 提供 VMX。", "networkDesc": "通过 Windows 的网络连接上网", "networkOfflineHint": "离线安装默认关闭;看到「设置助理」后退出恢复模式并重启即可联网", "networkTitle": "网络", @@ -750,8 +752,10 @@ export const settingsEn: Record = { "minimizeToTraySub": "Clipboard and shared folders keep working; start and stop VMs from the tray", "multiDisplayHint": "{n, plural, one {# display detected; arrange displays inside macOS System Settings › Displays} other {# displays detected; arrange them inside macOS System Settings › Displays}}", "navHasIssue": "This page has settings to fix", - "nestedVirtDesc": "Lets macOS run VMs of its own, such as Docker Desktop; some PCs cannot enable it", + "nestedVirtDesc": "Lets macOS run its own virtual machines. Applies on a full restart.", + "nestedVirtInvalid": "The saved setting could not be read. The VM starts with the default CPU settings.", "nestedVirtLabel": "Nested virtualization", + "nestedVirtUnavailable": "The Windows host does not provide VMX through WHPX.", "networkDesc": "Uses the Windows network connection", "networkOfflineHint": "Off by default for offline installs. Exit recovery and restart when Setup Assistant appears to enable networking", "networkTitle": "Network", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index afda943..51792de 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -529,7 +529,9 @@ export type I18nKey = | "multiDisplayHint" | "navHasIssue" | "nestedVirtDesc" + | "nestedVirtInvalid" | "nestedVirtLabel" + | "nestedVirtUnavailable" | "netOff" | "netShared" | "networkDesc" diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 53ffdf5..48c6d5c 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -1029,6 +1029,7 @@ export namespace host { apic_emulation: boolean; kernel_irqchip_available: boolean; nested_virt_property: boolean; + nested_vmx: boolean; nested_virt_probe_error?: string; static createFrom(source: any = {}) { @@ -1041,6 +1042,7 @@ export namespace host { this.apic_emulation = source["apic_emulation"]; this.kernel_irqchip_available = source["kernel_irqchip_available"]; this.nested_virt_property = source["nested_virt_property"]; + this.nested_vmx = source["nested_vmx"]; this.nested_virt_probe_error = source["nested_virt_probe_error"]; } } @@ -2755,6 +2757,7 @@ export namespace reims { shared_dir?: string; guest_lang?: string; nested_virt: boolean; + nested_virt_invalid?: boolean; suspend_info?: SuspendInfo; static createFrom(source: any = {}) { @@ -2804,6 +2807,7 @@ export namespace reims { this.shared_dir = source["shared_dir"]; this.guest_lang = source["guest_lang"]; this.nested_virt = source["nested_virt"]; + this.nested_virt_invalid = source["nested_virt_invalid"]; this.suspend_info = this.convertValues(source["suspend_info"], SuspendInfo); } diff --git a/internal/app/macos_detail.go b/internal/app/macos_detail.go index 28d87e2..12034e0 100644 --- a/internal/app/macos_detail.go +++ b/internal/app/macos_detail.go @@ -3,7 +3,6 @@ package app import ( "context" "encoding/json" - "fmt" "path/filepath" "strings" @@ -65,9 +64,7 @@ func (a *App) getVMDetailLegacy(name string, epoch uint64) (reims.VMDetail, erro a.populateGuestToolsDetail(&d, epoch) a.populateGuestLangDetail(&d) populateSuspendDetail(&d) - if err := populateNestedVirtDetail(&d); err != nil { - return reims.VMDetail{}, err - } + populateNestedVirtDetail(&d) return d, nil } @@ -101,21 +98,16 @@ func (a *App) getVMDetail(name string, epoch uint64) (reims.VMDetail, error) { a.populateGuestToolsDetail(&d, epoch) a.populateGuestLangDetail(&d) populateSuspendDetail(&d) - if err := populateNestedVirtDetail(&d); err != nil { - return reims.VMDetail{}, err - } + populateNestedVirtDetail(&d) return d, nil } // populateNestedVirtDetail reads the VM's nested-virtualization switch, which Reims-Go keeps // in the VM directory rather than in the configuration reims-ctl manages. -func populateNestedVirtDetail(d *reims.VMDetail) error { +func populateNestedVirtDetail(d *reims.VMDetail) { cfg, err := vmstart.ReadVMNestedVirt(d.Directory) - if err != nil { - return fmt.Errorf("read nested virtualization switch: %w", err) - } + d.NestedVirtInvalid = err != nil d.NestedVirt = cfg.Enabled - return nil } func populateSuspendDetail(d *reims.VMDetail) { diff --git a/internal/app/macos_lifecycle_native.go b/internal/app/macos_lifecycle_native.go index 4c2d923..15f81fd 100644 --- a/internal/app/macos_lifecycle_native.go +++ b/internal/app/macos_lifecycle_native.go @@ -203,6 +203,7 @@ func (a *App) startVMLegacy(name string) error { a.mu.Lock() root := a.cfg.DataRoot tmpDir := a.cfg.TempDir() + locale := a.cfg.Locale a.mu.Unlock() rep := host.Inspect(root) if err := prep.CheckWHPX(rep); err != nil { @@ -253,7 +254,9 @@ func (a *App) startVMLegacy(name string) error { // Strip pre-ledger or out-of-band managed fragments so upgrading existing // VMs never duplicates QEMU device IDs. baseExtraArgs := stripLegacyManagedExtraArgs(curDetail.ExtraArgs) - reconciled := plugin.ReconcileStartIntents(baseExtraArgs, ledger, mgr.Registry().ActivePluginIDs(), intents) + nested := plugin.StartIntent{PluginID: builtin.IDDriverReimsMacOS} + macosdriver.AppendNestedVirtIntent(&nested, locale, curDetail.Directory, plugin.UserExtraArgs(baseExtraArgs, ledger), rep) + reconciled := plugin.ReconcileStartIntentsForDriver(baseExtraArgs, ledger, mgr.Registry().ActivePluginIDs(), nested.PluginID, append(intents, nested)) reconciled.Changed = strings.TrimSpace(curDetail.ExtraArgs) != reconciled.ExtraArgs for _, warn := range reconciled.Warnings { a.emitVMLog(name, "[plugin] "+warn) @@ -285,9 +288,7 @@ func (a *App) startVMLegacy(name string) error { c.Env = append(c.Env, env...) } } - if err := prep.Prepare(context.Background(), name, rep, &curDetail); err != nil { - return err - } + prep.Prepare(context.Background(), name, rep, &curDetail) if rep.NeedsColdRebootWorkaround { sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name) _ = os.MkdirAll(filepath.Dir(sockPath), 0o755) @@ -300,6 +301,25 @@ func (a *App) startVMLegacy(name string) error { curDetail.ExtraArgs = merged } } + ledger, err := plugin.LoadArgLedger(curDetail.Directory) + if err != nil { + return err + } + nested := plugin.StartIntent{PluginID: builtin.IDDriverReimsMacOS} + macosdriver.AppendNestedVirtIntent(&nested, locale, curDetail.Directory, plugin.UserExtraArgs(curDetail.ExtraArgs, ledger), rep) + reconciled := plugin.ReconcileStartIntentsForDriver(curDetail.ExtraArgs, ledger, nil, nested.PluginID, []plugin.StartIntent{nested}) + for _, warning := range reconciled.Warnings { + a.emitVMLog(name, warning) + } + if reconciled.Changed { + if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil { + return err + } + if err := plugin.SaveArgLedger(curDetail.Directory, ledger); err != nil { + return err + } + curDetail.ExtraArgs = reconciled.ExtraArgs + } } if prep.Runtime.Manifest.HasCapability("display-fixed-mode") && diff --git a/internal/app/macos_settings.go b/internal/app/macos_settings.go index ba2eba3..3e6d710 100644 --- a/internal/app/macos_settings.go +++ b/internal/app/macos_settings.go @@ -63,6 +63,9 @@ func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) { } func (a *App) ApplyVMSettings(opts reims.SetOpts) error { + if err := a.requireWritableDataRoot(); err != nil { + return err + } cur, err := a.GetVMDetail(opts.Name) if err != nil { return err @@ -92,7 +95,7 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error { if err != nil { return err } - _, release, err := startprep.LockMutableVM(a.baseCtx(), c, opts.Name) + locked, release, err := startprep.LockMutableVM(a.baseCtx(), c, opts.Name) if err != nil { return err } @@ -104,7 +107,7 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error { } } if opts.NestedVirt != nil { - if err := vmstart.SaveVMNestedVirt(cur.Directory, vmstart.VMNestedVirtConfig{Enabled: *opts.NestedVirt}); err != nil { + if err := vmstart.SaveVMNestedVirt(locked.Directory, vmstart.VMNestedVirtConfig{Enabled: *opts.NestedVirt}); err != nil { return err } } diff --git a/internal/host/host.go b/internal/host/host.go index 9605b4e..83a2df2 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -47,6 +47,7 @@ type WHPXCapabilities struct { APICEmulation bool `json:"apic_emulation"` KernelIrqchipAvailable bool `json:"kernel_irqchip_available"` NestedVirtProperty bool `json:"nested_virt_property"` + NestedVMX bool `json:"nested_vmx"` NestedVirtProbeError string `json:"nested_virt_probe_error,omitempty"` } diff --git a/internal/host/whpx_probe_windows.go b/internal/host/whpx_probe_windows.go index 3528e00..dc19f38 100644 --- a/internal/host/whpx_probe_windows.go +++ b/internal/host/whpx_probe_windows.go @@ -13,6 +13,7 @@ const ( // WinHvPlatformDefs.h capability & partition property codes. whvCapFeatures = 0x00000001 whvCapProcessorPerfmon = 0x00001009 + whvCapVmxBasic = 0x00002000 whvPropNestedVirtualization = 0x00000004 whvPropLocalApicEmulationMode = 0x00001005 whvPropProcessorCount = 0x00001fff @@ -90,6 +91,9 @@ func probeWHPXCapabilities() WHPXCapabilities { hr, _, _ = setProp.Call(part, uintptr(whvPropNestedVirtualization), uintptr(unsafe.Pointer(&nestedBuf[0])), uintptr(len(nestedBuf))) if int32(hr) >= 0 { caps.NestedVirtProperty = true + var vmxBasic uint64 + hr, _, _ = getCap.Call(whvCapVmxBasic, uintptr(unsafe.Pointer(&vmxBasic)), unsafe.Sizeof(vmxBasic), uintptr(unsafe.Pointer(&written))) + caps.NestedVMX = caps.KernelIrqchipAvailable && int32(hr) >= 0 && vmxBasic != 0 } else { caps.NestedVirtProbeError = fmt.Sprintf("0x%08x", uint32(hr)) } diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 0b2e1b0..717aa3b 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -552,6 +552,8 @@ var catalog = map[Locale]map[string]string{ "vm.resize.stop_first": "请先停止 {name} 再扩容虚拟磁盘", "vm.typed": "{count, plural, other {已敲入 # 个键。}}", "vmstart.compat.nested_virt": "[兼容] 当前 Windows 不支持嵌套虚拟化属性({code}),已自动启用 kernel-irqchip=off", + "vmstart.nested_vmx.invalid": "无法读取嵌套虚拟化设置。虚拟机将按默认 CPU 设置启动。", + "vmstart.nested_vmx.unavailable": "当前 Windows 宿主机和中断控制器设置无法启用嵌套虚拟化。", "vmstart.pin.non_lpe": "[CPU] 虚拟机配置了 {vcpus} vCPU(超过 {pthreads} 个 P 核线程),已自动将 QEMU (PID {pid}) 绑定到 P+E 核({cores} 核 / {threads} 线程,掩码 {mask};仅排除 {lpe} 个慢速 LP-E 核)", "vmstart.pin.pcores": "[CPU] 已将 QEMU (PID {pid}) 绑定到 {cores} 个 P 核({threads} 个逻辑线程,掩码 {mask};未占用 {excluded} 个 E 核)", "vmstart.pin.skipped": "[CPU] 跳过绑核:虚拟机配置了 {vcpus} vCPU,超过可用安全绑定线程上限(P 核仅 {pthreads} 线程),已使用全部核心避免超售卡顿", @@ -1109,6 +1111,8 @@ var catalog = map[Locale]map[string]string{ "vm.resize.stop_first": "stop {name} before resizing its disk", "vm.typed": "{count, plural, one {Typed # key.} other {Typed # keys.}}", "vmstart.compat.nested_virt": "[compat] Host rejects nested-virtualization property ({code}); enabled kernel-irqchip=off automatically", + "vmstart.nested_vmx.invalid": "The nested virtualization setting could not be read. Starting with the default CPU settings.", + "vmstart.nested_vmx.unavailable": "Nested virtualization is unavailable with the current Windows host and interrupt controller settings.", "vmstart.pin.non_lpe": "[CPU] VM has {vcpus} vCPUs (exceeds {pthreads} P-core threads); pinned QEMU (PID {pid}) to P+E cores ({cores} cores / {threads} logical CPUs, mask {mask}; {lpe} slow LP-E cores excluded)", "vmstart.pin.pcores": "[CPU] Pinned QEMU (PID {pid}) to {cores} P-cores ({threads} logical CPUs, mask {mask}; {excluded} E/LP-E cores excluded)", "vmstart.pin.skipped": "[CPU] Skipped CPU pinning: VM has {vcpus} vCPUs, exceeding safe headroom (only {pthreads} P-core threads); using all host CPUs to avoid spinlock stall", diff --git a/internal/macos/macosdriver/prepare.go b/internal/macos/macosdriver/prepare.go index f54d092..6f02c22 100644 --- a/internal/macos/macosdriver/prepare.go +++ b/internal/macos/macosdriver/prepare.go @@ -148,9 +148,7 @@ func (d *ReimsMacOSDriver) prepareStart(ctx context.Context, cfg config.Config, if err := d.prepareColdReboot(cfg, name, cur.Directory, rep, &in); err != nil { return in, err } - if err := d.prepareNestedVirt(cur.Directory, &in); err != nil { - return in, err - } + AppendNestedVirtIntent(&in, cfg.Locale, cur.Directory, userExtraArgs, rep) d.prepareHostMemorySMBIOS(cfg, rep, userExtraArgs, func() bool { return reims.ProbeQEMUSupportsSMBIOSMemoryType(active.QemuPath(), c.Env) }, &in) @@ -241,22 +239,27 @@ func (d *ReimsMacOSDriver) prepareColdReboot(cfg config.Config, name, vmDir stri return nil } -// prepareNestedVirt asks for VMX in the guest's CPU when the VM's nested-virtualization switch -// is on, and takes the argument away when it is off. The argument belongs to this driver in the -// ledger, so it never shows up among the VM's own extra arguments. A switch that cannot be -// read stops the start: the VM must not come up without VMX when the user switched it on. -func (d *ReimsMacOSDriver) prepareNestedVirt(vmDir string, in *plugin.StartIntent) error { +// AppendNestedVirtIntent keeps generated VMX arguments in the driver's ledger. +func AppendNestedVirtIntent(in *plugin.StartIntent, locale i18n.Locale, vmDir, userArgs string, rep host.Report) { + in.ClearKeys = append(in.ClearKeys, keyNestedVirt) cfg, err := vmstart.ReadVMNestedVirt(vmDir) if err != nil { - return fmt.Errorf("read the nested virtualization switch: %w", err) + in.Warnings = append(in.Warnings, i18n.NewCodedError(locale, "E_NESTED_VMX_CONFIG", "vmstart.nested_vmx.invalid", nil, err).Error()) + return } if !cfg.Enabled { - in.ClearKeys = append(in.ClearKeys, keyNestedVirt) - return nil + return } - in.Args = append(in.Args, plugin.ArgFragment{PluginID: d.opts.OwnerID, Key: keyNestedVirt, - Tokens: reims.NestedVirtTokens, Builtin: true, Priority: 90}) - return nil + if !rep.WHPXCaps.NestedVMX || rep.NeedsColdRebootWorkaround || strings.Contains(userArgs, "kernel-irqchip=off") { + in.Warnings = append(in.Warnings, i18n.T(locale, "vmstart.nested_vmx.unavailable")) + return + } + const property = "driver=x86_64-cpu,property=vmx,value=on" + if strings.Contains(userArgs, "-global "+property) { + return + } + in.Args = append(in.Args, plugin.ArgFragment{PluginID: in.PluginID, Key: keyNestedVirt, + Tokens: []string{"-global", property}, Builtin: true, Priority: 90}) } // prepareHostMemorySMBIOS appends `-smbios type=17,speed=...,memory_type=...` @@ -296,8 +299,5 @@ func startBaseArgs(extraArgs string, managedByDesktop bool, active map[string]bo s = reims.StripOfflineHelperArgs(s) s = qmp.StripLegacyWin10RebootArgs(s) s = reims.StripIncomingDeferArgs(s) - // The nested-virtualization argument is the driver's (prepareNestedVirt). One written by a - // start without the plugin manager counts as the VM's own and would outlive the switch. - s = reims.StripNestedVirtArgs(s) return strings.TrimSpace(s) } diff --git a/internal/macos/macosdriver/prepare_test.go b/internal/macos/macosdriver/prepare_test.go index 8f8754a..77fbe12 100644 --- a/internal/macos/macosdriver/prepare_test.go +++ b/internal/macos/macosdriver/prepare_test.go @@ -98,47 +98,47 @@ func TestPrepareWorkaroundsHonourSettingsAndRuntime(t *testing.T) { func TestNestedVirtFollowsTheVMSwitch(t *testing.T) { const owner = "test.macos" + const owned = "-global driver=x86_64-cpu,property=vmx,value=on" dir := t.TempDir() - d := &ReimsMacOSDriver{opts: Options{OwnerID: owner}} - prepare := func() plugin.StartIntent { + rep := host.Report{WHPXCaps: host.WHPXCapabilities{NestedVMX: true}} + prepare := func(userArgs string, rep host.Report) plugin.StartIntent { in := plugin.StartIntent{PluginID: owner} - if err := d.prepareNestedVirt(dir, &in); err != nil { - t.Fatal(err) - } + AppendNestedVirtIntent(&in, "en-US", dir, userArgs, rep) return in } - if in := prepare(); !slices.Contains(in.ClearKeys, keyNestedVirt) || len(in.Args) != 0 { + if in := prepare("", rep); !slices.Contains(in.ClearKeys, keyNestedVirt) || len(in.Args) != 0 { t.Fatalf("switched off = %+v", in) } - // A switch that cannot be read stops the start instead of leaving VMX out silently. if err := os.WriteFile(filepath.Join(dir, ".reims-go-nested-virt.json"), []byte("{"), 0o644); err != nil { t.Fatal(err) } - damaged := plugin.StartIntent{PluginID: owner} - if err := d.prepareNestedVirt(dir, &damaged); err == nil || len(damaged.Args) != 0 { - t.Fatalf("a damaged switch file: err = %v, args = %+v", err, damaged.Args) + if in := prepare("", rep); len(in.Warnings) != 1 || len(in.Args) != 0 { + t.Fatalf("damaged switch = %+v", in) } if err := vmstart.SaveVMNestedVirt(dir, vmstart.VMNestedVirtConfig{Enabled: true}); err != nil { t.Fatal(err) } - in := prepare() + if in := prepare("", host.Report{}); len(in.Args) != 0 || len(in.Warnings) != 1 { + t.Fatalf("unsupported host = %+v", in) + } + if in := prepare("-accel whpx,kernel-irqchip=off", rep); len(in.Args) != 0 || len(in.Warnings) != 1 { + t.Fatalf("userspace interrupt controller = %+v", in) + } + if in := prepare(owned, rep); len(in.Args) != 0 { + t.Fatalf("user owns VMX argument = %+v", in) + } + in := prepare("", rep) if !slices.Equal(argKeys(in), []string{keyNestedVirt}) || !in.Args[0].Builtin || - in.Args[0].PluginID != owner || !slices.Equal(in.Args[0].Tokens, reims.NestedVirtTokens) { + in.Args[0].PluginID != owner || strings.Join(in.Args[0].Tokens, " ") != owned { t.Fatalf("switched on = %+v", in.Args) } const user = "-cpu host -machine kernel-irqchip=on" - own := strings.Join(reims.NestedVirtTokens, " ") active := map[string]bool{owner: true} ledger := &plugin.ArgLedger{} - // An argument written by a start without the ledger must not pass for the VM's own. - base := startBaseArgs(user+" "+own, false, active) - if base != user { - t.Fatalf("startBaseArgs = %q", base) - } - on := plugin.ReconcileStartIntentsForDriver(base, ledger, active, owner, []plugin.StartIntent{in}) - if on.ExtraArgs != user+" "+own { + on := plugin.ReconcileStartIntentsForDriver(user, ledger, active, owner, []plugin.StartIntent{in}) + if on.ExtraArgs != user+" "+owned { t.Fatalf("launch args with the switch on = %q", on.ExtraArgs) } if got := plugin.UserExtraArgs(on.ExtraArgs, ledger); got != user { @@ -148,7 +148,7 @@ func TestNestedVirtFollowsTheVMSwitch(t *testing.T) { if err := vmstart.SaveVMNestedVirt(dir, vmstart.VMNestedVirtConfig{}); err != nil { t.Fatal(err) } - off := plugin.ReconcileStartIntentsForDriver(on.ExtraArgs, ledger, active, owner, []plugin.StartIntent{prepare()}) + off := plugin.ReconcileStartIntentsForDriver(on.ExtraArgs, ledger, active, owner, []plugin.StartIntent{prepare("", rep)}) if off.ExtraArgs != user { t.Fatalf("launch args after switching off = %q", off.ExtraArgs) } diff --git a/internal/macos/reims/nested_virt_args.go b/internal/macos/reims/nested_virt_args.go deleted file mode 100644 index b8cb207..0000000 --- a/internal/macos/reims/nested_virt_args.go +++ /dev/null @@ -1,40 +0,0 @@ -package reims - -import "strings" - -// NestedVirtTokens asks QEMU for VMX in the guest's CPU, so that macOS can run VMs of its own -// (Docker Desktop, UTM). reims-ctl adds `vmx=on` to `-cpu` only where KVM offers VMX -// (reims-vgpu 3731afd9 crates/reims-ctl/src/qemu.rs:310-315), never on Windows. QEMU registers -// a `-cpu` `name=value` flag as a global property of the CPU type (qemu-reims-vgpu 4571bc5 -// target/i386/cpu.c:7952-7956) and applies every global property to each device it creates -// (qom/object.c:445-480), so `-global` on the x86-64 CPU type adds that one feature to any -// CPU model and every vCPU without restating the rest of `-cpu`. Whether the hypervisor then -// gives VMX shows only in the guest: on some PCs Windows refuses nested virtualization (see -// prepareWHPXFallback in the macOS driver), and the switch has no effect there. -var NestedVirtTokens = []string{"-global", "driver=x86_64-cpu,property=vmx,value=on"} - -// StripNestedVirtArgs takes NestedVirtTokens out of a QEMU extra-args string and leaves the -// other arguments as they are. -func StripNestedVirtArgs(extraArgs string) string { - tokens := splitShellTokens(extraArgs) - kept := make([]string, 0, len(tokens)) - for i := 0; i < len(tokens); i++ { - if tokens[i] == NestedVirtTokens[0] && i+1 < len(tokens) && tokens[i+1] == NestedVirtTokens[1] { - i++ - continue - } - kept = append(kept, tokens[i]) - } - return strings.Join(kept, " ") -} - -// MergeNestedVirtArgs puts NestedVirtTokens at the end of a QEMU extra-args string, or takes -// them out. They then count as the VM's own arguments, so this is for starts that have no -// argument ledger (startprep.Prepare); with one, the macOS driver owns them. -func MergeNestedVirtArgs(extraArgs string, enabled bool) string { - base := strings.TrimSpace(StripNestedVirtArgs(extraArgs)) - if !enabled { - return base - } - return strings.TrimSpace(base + " " + strings.Join(NestedVirtTokens, " ")) -} diff --git a/internal/macos/reims/nested_virt_args_test.go b/internal/macos/reims/nested_virt_args_test.go deleted file mode 100644 index 9710587..0000000 --- a/internal/macos/reims/nested_virt_args_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package reims - -import ( - "slices" - "strings" - "testing" -) - -func TestMergeNestedVirtArgs(t *testing.T) { - // The user's arguments, one of them quoted around a path with a space. - const user = "-cpu host -drive 'id=disk,file=D:/My VMs/disk.img'" - on := user + " " + strings.Join(NestedVirtTokens, " ") - for _, tc := range []struct { - name string - in string - enabled bool - want string - }{ - {"adds them after the VM's own arguments", user, true, on}, - {"adds nothing else", on, true, on}, - {"takes them out", on, false, user}, - {"leaves a VM without them as it is", user, false, user}, - {"empties a VM that had only them", strings.Join(NestedVirtTokens, " "), false, ""}, - {"fills an empty string", "", true, strings.Join(NestedVirtTokens, " ")}, - } { - if got := MergeNestedVirtArgs(tc.in, tc.enabled); got != tc.want { - t.Errorf("%s: MergeNestedVirtArgs(%q, %v) = %q, want %q", tc.name, tc.in, tc.enabled, got, tc.want) - } - } -} - -func TestNestedVirtLeavesAHandWrittenCPUModelAlone(t *testing.T) { - // What a user may have written by hand before the switch existed. - const own = "-cpu host,kvm=on,check,vmx=on -global driver=x86_64-cpu,property=vmx,value=off" - if got := StripNestedVirtArgs(own); got != own { - t.Fatalf("StripNestedVirtArgs(%q) = %q", own, got) - } -} - -func TestNestedVirtIsNotAReimsCtlOption(t *testing.T) { - yes := true - args, err := BuildSetArgs(SetOpts{Name: "mac", NestedVirt: &yes}) - if err != nil || !slices.Equal(args, []string{"set", "mac"}) { - t.Fatalf("BuildSetArgs = %q, %v", args, err) - } - if HasCtlSetChanges(SetOpts{Name: "mac", NestedVirt: &yes}) { - t.Fatal("the switch alone would call reims-ctl set") - } -} diff --git a/internal/macos/reims/reims.go b/internal/macos/reims/reims.go index da17914..1f15133 100644 --- a/internal/macos/reims/reims.go +++ b/internal/macos/reims/reims.go @@ -84,11 +84,12 @@ type VMDetail struct { GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"` // GuestToolsDisabled is set when the Guest Tools plugin is switched off. GuestToolsDisabled bool `json:"guest_tools_disabled,omitempty"` - SharedDir string `json:"shared_dir,omitempty"` - GuestLang string `json:"guest_lang,omitempty"` + SharedDir string `json:"shared_dir,omitempty"` + GuestLang string `json:"guest_lang,omitempty"` // NestedVirt is the VM's nested-virtualization switch (vmstart.ReadVMNestedVirt). - NestedVirt bool `json:"nested_virt"` - SuspendInfo *SuspendInfo `json:"suspend_info,omitempty"` + NestedVirt bool `json:"nested_virt"` + NestedVirtInvalid bool `json:"nested_virt_invalid,omitempty"` + SuspendInfo *SuspendInfo `json:"suspend_info,omitempty"` } type ValidationIssue struct { diff --git a/internal/macos/startprep/startprep.go b/internal/macos/startprep/startprep.go index 786ea1b..12f7fe3 100644 --- a/internal/macos/startprep/startprep.go +++ b/internal/macos/startprep/startprep.go @@ -79,10 +79,7 @@ func (p *Prep) CheckMemory(memory string, rep host.Report) error { // 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`. -// -// It fails when the VM's nested-virtualization switch cannot be read or applied; the -// other steps report what they could not do in the log. -func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) error { +func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) { if stripped := reims.StripIncomingDeferArgs(cur.ExtraArgs); stripped != cur.ExtraArgs { if err := p.setExtraArgs(ctx, name, stripped); err == nil { cur.ExtraArgs = stripped @@ -94,11 +91,7 @@ func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *r if !p.SkipWHPXFallback { p.applyProbedWHPXCompat(ctx, name, rep, cur) } - if err := p.syncNestedVirt(ctx, name, cur); err != nil { - return err - } p.syncHostMemorySMBIOS(ctx, name, rep, cur) - return nil } func (p *Prep) syncHostMemorySMBIOS(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) { @@ -199,25 +192,6 @@ func (p *Prep) applyProbedWHPXCompat(ctx context.Context, name string, rep host. p.log(i18n.M(p.cfg.Locale, "vmstart.compat.nested_virt", i18n.Vars{"code": code})) } -// syncNestedVirt follows the VM's nested-virtualization switch. These starts have no -// argument ledger, so the argument goes in as the VM's own; the macOS driver takes it over -// from there. -func (p *Prep) syncNestedVirt(ctx context.Context, name string, cur *reims.VMDetail) error { - cfg, err := vmstart.ReadVMNestedVirt(cur.Directory) - if err != nil { - return fmt.Errorf("read the nested virtualization switch: %w", err) - } - merged := reims.MergeNestedVirtArgs(cur.ExtraArgs, cfg.Enabled) - if merged == cur.ExtraArgs { - return nil - } - if err := p.setExtraArgs(ctx, name, merged); err != nil { - return fmt.Errorf("apply the nested virtualization switch: %w", err) - } - cur.ExtraArgs = merged - return nil -} - // RuntimeHasPatch reports whether the active runtime was built with a patch // whose name contains substr (case-insensitive). func (p *Prep) RuntimeHasPatch(substr string) bool { diff --git a/locales/en-US/native.json b/locales/en-US/native.json index 1bda9d3..9082381 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -234,6 +234,8 @@ "err.whpx_missing": "Windows Hypervisor Platform (WHPX) is not enabled. Enable WHPX on the Host page and restart Windows before starting the VM", "err.whpx_no_hypervisor": "Windows Hypervisor is not active (unrelated to disk space). Ensure Intel VT-x / AMD SVM is enabled in BIOS, enable WHPX on the Host page, run `bcdedit /set hypervisorlaunchtype auto` as Administrator, and restart Windows", "err.whpx_unsupported": "Windows Hypervisor Platform (WHPX) is not supported on this OS; Windows 10 1803 or newer is required", + "vmstart.nested_vmx.invalid": "The nested virtualization setting could not be read. Starting with the default CPU settings.", + "vmstart.nested_vmx.unavailable": "Nested virtualization is unavailable with the current Windows host and interrupt controller settings.", "installer.paused": { "message": "Paused. Run `reims-go installer download {ver}` again to continue where it stopped.", "$params": [ diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index 7b3ee50..d251ecb 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -339,7 +339,9 @@ "kernelIrqchipOn": "On", "kernelIrqchipOff": "Off", "nestedVirtLabel": "Nested virtualization", - "nestedVirtDesc": "Lets macOS run VMs of its own, such as Docker Desktop; some PCs cannot enable it", + "nestedVirtDesc": "Lets macOS run its own virtual machines. Applies on a full restart.", + "nestedVirtUnavailable": "The Windows host does not provide VMX through WHPX.", + "nestedVirtInvalid": "The saved setting could not be read. The VM starts with the default CPU settings.", "diskControllerNvmeHint": "NVMe is faster", "diskControllerInstallHint": "Keep SATA while installing; switch to NVMe after ejecting the installer", "gpuUnavailableHint": "No GPU available for acceleration; try VMware SVGA", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index ddf0aa5..4f8d516 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -234,6 +234,8 @@ "err.whpx_missing": "未启用 Windows 虚拟机监控程序平台(WHPX)。在「宿主机」页启用 WHPX 并重启 Windows 后再启动虚拟机", "err.whpx_no_hypervisor": "Windows Hypervisor 虚拟化引擎未激活(与磁盘空间无关)。确认 BIOS 已开启 Intel VT-x / AMD SVM,在「宿主机」页启用 WHPX,以管理员运行 bcdedit /set hypervisorlaunchtype auto,然后重启 Windows", "err.whpx_unsupported": "当前系统不支持 Windows 虚拟机监控程序平台(WHPX),需要 Windows 10 1803 或更高版本", + "vmstart.nested_vmx.invalid": "无法读取嵌套虚拟化设置。虚拟机将按默认 CPU 设置启动。", + "vmstart.nested_vmx.unavailable": "当前 Windows 宿主机和中断控制器设置无法启用嵌套虚拟化。", "installer.paused": { "message": "已暂停。再次运行 `reims-go installer download {ver}` 会从中断处继续。", "$params": [ diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index df8b338..6c4e81e 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -339,7 +339,9 @@ "kernelIrqchipOn": "开启", "kernelIrqchipOff": "关闭", "nestedVirtLabel": "嵌套虚拟化", - "nestedVirtDesc": "在 macOS 里再运行虚拟机(如 Docker Desktop),部分电脑不支持,可能无法启用", + "nestedVirtDesc": "允许 macOS 运行自己的虚拟机,完全关机后再次启动时生效。", + "nestedVirtUnavailable": "当前 Windows 宿主机无法通过 WHPX 提供 VMX。", + "nestedVirtInvalid": "保存的设置无法读取,虚拟机将按默认 CPU 设置启动。", "diskControllerNvmeHint": "NVMe 读写更快", "diskControllerInstallHint": "装机时保持 SATA,装完弹出安装盘再改 NVMe", "gpuUnavailableHint": "没有找到能加速的显卡,可改用 VMware SVGA",