From 04f0d8d096f4c515584a50cd90106ecce110787f Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Sat, 5 Dec 2026 12:20:33 +0800 Subject: [PATCH] fix(storage): address PR review findings on raw disk enumeration, CoW guard, and capability gating --- frontend/src/App.tsx | 2 + frontend/src/components/SettingsModal.tsx | 5 +- .../src/components/vmSettings/diskCache.tsx | 6 +- frontend/src/i18n/domains/settings.gen.ts | 2 + frontend/src/i18n/keys.gen.ts | 1 + internal/app/macos_settings.go | 10 + internal/cli/cli.go | 3 + internal/cli/macos_native.go | 8 + internal/host/rawdisk_common.go | 34 +++ internal/host/rawdisk_test.go | 48 +++++ internal/host/rawdisk_windows.go | 199 +++++++++++------- internal/i18n/catalog_gen.go | 4 + internal/macos/macosdriver/driver.go | 17 +- internal/macos/macosdriver/validate_test.go | 27 +++ internal/macos/reims/cow_guard.go | 3 + internal/macos/reims/rawdisk_cache_test.go | 18 ++ locales/en-US/native.json | 2 + locales/en-US/settings.json | 1 + locales/zh-CN/native.json | 2 + locales/zh-CN/settings.json | 1 + 20 files changed, 316 insertions(+), 77 deletions(-) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 31fb25a..df9ffd5 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -487,6 +487,7 @@ export const App: React.FC = () => { const effectiveState = selectedVM ? (state?.transitions[vmRefKey(selectedVM)] ?? selectedVM.state) : '' const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : [] const fixedModeSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'display-fixed-mode') ?? false + const diskCacheSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'win32-native-aio') ?? false const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime const canSuspend = state?.can_suspend ?? false const fullscreenHotkey = state?.config.fullscreen_hotkey_enabled @@ -1463,6 +1464,7 @@ export const App: React.FC = () => { stats={latestVMStats(selectedVM?.driver_id ?? '', detail.name)} host={state.host} fixedModeSupported={fixedModeSupported} + diskCacheSupported={diskCacheSupported} optimizations={state.optimizations} running={effectiveState === 'running'} onCopy={copy} diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 8110990..6416d9f 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -144,6 +144,7 @@ interface Props { stats?: VMStats | null host: HostReport fixedModeSupported?: boolean + diskCacheSupported?: boolean optimizations?: Optimization[] running: boolean onCopy?: (text: string) => void @@ -157,7 +158,7 @@ interface Props { onSaved: () => void } -export const SettingsModal: React.FC = ({ locale, detail, driverID, stats, host, fixedModeSupported = false, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onToast, onClose, onSaved }) => { +export const SettingsModal: React.FC = ({ locale, detail, driverID, stats, host, fixedModeSupported = false, diskCacheSupported = false, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onToast, onClose, onSaved }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const irqOpt = findOptimization(optimizations, 'kernel_irqchip') const base = useMemo(() => baseline(detail, host), [detail, host]) @@ -689,6 +690,8 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats locale={locale} value={(form.disk_cache as DiskCache) || 'default'} dirty={dirty('disk_cache')} + disabled={!diskCacheSupported} + reason={tr('diskCacheRequiresRuntime')} onReset={reset('disk_cache')} resetLabel={tr('resetField')} error={issueOf('disk_cache')} diff --git a/frontend/src/components/vmSettings/diskCache.tsx b/frontend/src/components/vmSettings/diskCache.tsx index 43218d8..57ddb66 100644 --- a/frontend/src/components/vmSettings/diskCache.tsx +++ b/frontend/src/components/vmSettings/diskCache.tsx @@ -7,13 +7,15 @@ interface Props { locale: Locale value: DiskCache dirty: boolean + disabled?: boolean + reason?: string onReset: () => void resetLabel: string error?: string onChange: (cache: DiskCache) => void } -export const DiskCacheRow: React.FC = ({ locale, value, dirty, onReset, resetLabel, error, onChange }) => { +export const DiskCacheRow: React.FC = ({ locale, value, dirty, disabled = false, reason, onReset, resetLabel, error, onChange }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const desc = value === 'writeback' ? tr('diskCacheDescWriteback') @@ -27,6 +29,8 @@ export const DiskCacheRow: React.FC = ({ locale, value, dirty, onReset, r = { "diskCacheOptionNone": "直通", "diskCacheOptionUnsafe": "激进 (Unsafe)", "diskCacheOptionWriteback": "回写", + "diskCacheRequiresRuntime": "当前运行时版本过旧,请更新到支持磁盘缓存策略的新版运行时", "diskCacheTitle": "磁盘 I/O 缓存策略", "diskCompactAction": "立即回收", "diskCompactDesc": "把 macOS 里已删除文件占用的空间还给 Windows,过程中需要与当前占用差不多的空闲空间", @@ -674,6 +675,7 @@ export const settingsEn: Record = { "diskCacheOptionNone": "Direct", "diskCacheOptionUnsafe": "Unsafe", "diskCacheOptionWriteback": "Writeback", + "diskCacheRequiresRuntime": "Update to a newer runtime to configure disk I/O cache policy", "diskCacheTitle": "Disk I/O cache", "diskCompactAction": "Reclaim now", "diskCompactDesc": "Gives space from files deleted in macOS back to Windows. Needs about as much free space as the disk uses now", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index c75f1b6..9adf8e9 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -187,6 +187,7 @@ export type I18nKey = | "diskCacheOptionNone" | "diskCacheOptionUnsafe" | "diskCacheOptionWriteback" + | "diskCacheRequiresRuntime" | "diskCacheTitle" | "diskCompactAction" | "diskCompactDesc" diff --git a/internal/app/macos_settings.go b/internal/app/macos_settings.go index 07ec507..a878b25 100644 --- a/internal/app/macos_settings.go +++ b/internal/app/macos_settings.go @@ -137,6 +137,16 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) { return err } } else { + if strings.TrimSpace(opts.DiskCache) != "" { + cfg := a.runtimeConfig() + active, err := rt.ResolveActive(&cfg) + if err != nil { + return fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed")) + } + if !active.Manifest.HasCapability("win32-native-aio") { + return errors.New(i18n.T(i18n.EffectiveLocale(loc), "validate.disk_cache_requires_runtime")) + } + } c, err := a.client() if err != nil { return err diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 6ec1950..dc836d8 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -529,6 +529,9 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s if err != nil { return err } + if strings.TrimSpace(*disk) != "" || strings.TrimSpace(*diskMode) != "" { + return fmt.Errorf("--disk and --disk-mode are only supported by the %s driver", driver.BuiltinReimsMacOSDriverID) + } req := driver.CreateRequest{ DriverID: drv.ID(), Name: name, diff --git a/internal/cli/macos_native.go b/internal/cli/macos_native.go index 2c37b4e..f2a5f8f 100644 --- a/internal/cli/macos_native.go +++ b/internal/cli/macos_native.go @@ -78,6 +78,14 @@ func createMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, in if err != nil { return err } + if !prep.Runtime.Manifest.HasCapability("win32-native-aio") { + if dcache := strings.TrimSpace(in.DiskCache); dcache != "" && !strings.EqualFold(dcache, "default") { + return errors.New(i18n.T(loc, "validate.disk_cache_requires_runtime")) + } + if reims.IsWindowsRawDevicePath(in.Disk) { + return errors.New(i18n.T(loc, "validate.raw_disk_requires_runtime")) + } + } client := prep.Client opts := reims.CreateOpts{Name: in.Name, Dir: in.Dir, MacOS: in.MacOS, CPUs: in.CPUs, Memory: in.Memory, DiskSize: in.DiskSize, Disk: in.Disk, DiskMode: in.DiskMode, DiskCache: in.DiskCache, GPU: in.GPU, Capture: &in.Capture, Logs: &in.Logs, GuestLang: strings.TrimSpace(in.GuestLang), Start: false} existingVMs, err := client.List(ctx) diff --git a/internal/host/rawdisk_common.go b/internal/host/rawdisk_common.go index 6f9c55a..2093a9d 100644 --- a/internal/host/rawdisk_common.go +++ b/internal/host/rawdisk_common.go @@ -62,6 +62,40 @@ type RawVolumeObservation struct { Label string } +type indexedVolumeExtent struct { + start int64 + end int64 + volDev string + multiExtent bool + hasMountPoints bool + filesystem string + occupied bool +} + +func applyPartitionExtentMatches(obs *RawVolumeObservation, partStart int64, partLen uint64, extents []indexedVolumeExtent) { + if obs == nil || len(extents) == 0 || partLen == 0 { + return + } + partEnd := partStart + int64(partLen) + if partEnd <= partStart { + partEnd = 1<<63 - 1 + } + for _, ext := range extents { + if ext.end <= partStart || ext.start >= partEnd { + continue + } + if ext.occupied || ext.hasMountPoints { + obs.HasMountPoints = true + } + if ext.filesystem != "" && obs.Filesystem == "" { + obs.Filesystem = ext.filesystem + } + if !ext.multiExtent && ext.start == partStart && ext.volDev != "" { + obs.DevicePath = ext.volDev + } + } +} + func isMountedWindowsFilesystem(fsName string) bool { switch strings.ToUpper(strings.TrimSpace(fsName)) { case "NTFS", "FAT", "FAT32", "EXFAT", "REFS", "CDFS", "UDF": diff --git a/internal/host/rawdisk_test.go b/internal/host/rawdisk_test.go index 2d92a73..b7ca193 100644 --- a/internal/host/rawdisk_test.go +++ b/internal/host/rawdisk_test.go @@ -50,3 +50,51 @@ func TestFilterRawPartitionCandidatesSafety(t *testing.T) { t.Fatalf("unexpected third candidate: %+v", got[2]) } } + +func TestApplyPartitionExtentMatches(t *testing.T) { + extents := []indexedVolumeExtent{ + { + start: 1 << 20, + end: 100 << 20, + volDev: `\\?\Volume{spanned}`, + multiExtent: true, + occupied: true, + }, + { + start: 200 << 20, + end: 300 << 20, + volDev: `\\?\Volume{probe-err}`, + occupied: true, + }, + { + start: 400 << 20, + end: 500 << 20, + volDev: `\\?\Volume{apfs}`, + }, + } + + // Overlapping a multi-extent volume excludes the partition fail-closed. + spannedObs := RawVolumeObservation{DevicePath: `\\.\Harddisk1Partition1`, DiskNumber: 1, PartitionNumber: 1, SizeBytes: 99 << 20} + applyPartitionExtentMatches(&spannedObs, 1<<20, 99<<20, extents) + if !spannedObs.HasMountPoints { + t.Fatalf("expected spanned volume overlap to mark partition occupied") + } + + // Probe error on the volume also marks it occupied fail-closed. + errObs := RawVolumeObservation{DevicePath: `\\.\Harddisk1Partition2`, DiskNumber: 1, PartitionNumber: 2, SizeBytes: 100 << 20} + applyPartitionExtentMatches(&errObs, 200<<20, 100<<20, extents) + if !errObs.HasMountPoints { + t.Fatalf("expected volume probe error to mark partition occupied") + } + + // Clean unmounted APFS partition passes through with resolved volume device path. + apfsObs := RawVolumeObservation{DevicePath: `\\.\Harddisk1Partition3`, DiskNumber: 1, PartitionNumber: 3, SizeBytes: 100 << 20, PartitionTypeGUID: AppleAPFSPartitionTypeGUID} + applyPartitionExtentMatches(&apfsObs, 400<<20, 100<<20, extents) + if apfsObs.HasMountPoints || apfsObs.DevicePath != `\\?\Volume{apfs}` { + t.Fatalf("unexpected APFS observation after match: %+v", apfsObs) + } + got := filterRawPartitionCandidates([]RawVolumeObservation{spannedObs, errObs, apfsObs}, nil) + if len(got) != 1 || got[0].DevicePath != `\\?\Volume{apfs}` { + t.Fatalf("expected only clean APFS candidate, got %+v", got) + } +} diff --git a/internal/host/rawdisk_windows.go b/internal/host/rawdisk_windows.go index 6bbf468..c9f1564 100644 --- a/internal/host/rawdisk_windows.go +++ b/internal/host/rawdisk_windows.go @@ -4,6 +4,7 @@ package host import ( "encoding/binary" + "errors" "fmt" "os" "strings" @@ -35,76 +36,91 @@ const ( // mounted volumes, and Windows filesystems). func ListRawPartitions(dataRoot string) ([]RawDiskCandidate, error) { excluded := excludedHostDiskNumbers(dataRoot) - volByExtent := indexVolumesByExtent() + extentsByDisk, err := indexVolumesByExtent() + if err != nil { + return nil, err + } + maxSeenDisk := maxDiskNumber(excluded, extentsByDisk) var observations []RawVolumeObservation - for diskNum := uint32(0); diskNum < 32; diskNum++ { + consecutiveMisses := 0 + for diskNum := uint32(0); diskNum < 512; diskNum++ { if excluded[diskNum] { + consecutiveMisses = 0 continue } - dev := fmt.Sprintf(`\\.\PhysicalDrive%d`, diskNum) offline, readOnly, ok := queryDiskAttributes(diskNum) if !ok { - continue - } - if offline { - sizeBytes, _ := queryDeviceLengthBytes(dev) - if sizeBytes > 0 { - observations = append(observations, RawVolumeObservation{ - DevicePath: dev, - DiskNumber: diskNum, - SizeBytes: sizeBytes, - Offline: true, - ReadOnly: readOnly, - }) + consecutiveMisses++ + if diskNum >= 31 && diskNum >= maxSeenDisk && consecutiveMisses >= 32 { + break } continue } - parts := queryDiskPartitions(diskNum) - for _, p := range parts { - if p.number == 0 || p.length == 0 { - continue - } - obs := RawVolumeObservation{ - DevicePath: fmt.Sprintf(`\\.\Harddisk%dPartition%d`, diskNum, p.number), - DiskNumber: diskNum, - PartitionNumber: p.number, - SizeBytes: p.length, - PartitionTypeGUID: p.typeGUID, - ReadOnly: readOnly, - } - if v, mapped := volByExtent[extentKey{disk: diskNum, offset: p.offset}]; mapped { - obs.DevicePath = v.volDev - obs.HasMountPoints = v.hasMountPoints - obs.Filesystem = v.filesystem - } - if exact, ok := queryDeviceLengthBytes(obs.DevicePath); ok && exact > 0 { - obs.SizeBytes = exact - } - observations = append(observations, obs) - } + consecutiveMisses = 0 + observations = appendDiskObservations(observations, diskNum, offline, readOnly, extentsByDisk[diskNum]) } return filterRawPartitionCandidates(observations, excluded), nil } +func maxDiskNumber(excluded map[uint32]bool, extents map[uint32][]indexedVolumeExtent) uint32 { + var maxDisk uint32 + for d := range excluded { + if d > maxDisk { + maxDisk = d + } + } + for d := range extents { + if d > maxDisk { + maxDisk = d + } + } + return maxDisk +} + +func appendDiskObservations(observations []RawVolumeObservation, diskNum uint32, offline, readOnly bool, extents []indexedVolumeExtent) []RawVolumeObservation { + dev := fmt.Sprintf(`\\.\PhysicalDrive%d`, diskNum) + if offline { + sizeBytes, _ := queryDeviceLengthBytes(dev) + if sizeBytes > 0 { + observations = append(observations, RawVolumeObservation{ + DevicePath: dev, + DiskNumber: diskNum, + SizeBytes: sizeBytes, + Offline: true, + ReadOnly: readOnly, + }) + } + return observations + } + for _, p := range queryDiskPartitions(diskNum) { + if p.number == 0 || p.length == 0 { + continue + } + obs := RawVolumeObservation{ + DevicePath: fmt.Sprintf(`\\.\Harddisk%dPartition%d`, diskNum, p.number), + DiskNumber: diskNum, + PartitionNumber: p.number, + SizeBytes: p.length, + PartitionTypeGUID: p.typeGUID, + ReadOnly: readOnly, + } + applyPartitionExtentMatches(&obs, p.offset, p.length, extents) + if exact, ok := queryDeviceLengthBytes(obs.DevicePath); ok && exact > 0 { + obs.SizeBytes = exact + } + observations = append(observations, obs) + } + return observations +} + type volumeDiskExtent struct { diskNumber uint32 startingOffset int64 extentLength uint64 } -type extentKey struct { - disk uint32 - offset int64 -} - -type indexedVolume struct { - volDev string - hasMountPoints bool - filesystem string -} - type diskPartitionEntry struct { number uint32 offset int64 @@ -112,26 +128,39 @@ type diskPartitionEntry struct { typeGUID string } -func indexVolumesByExtent() map[extentKey]indexedVolume { - out := map[extentKey]indexedVolume{} +func indexVolumesByExtent() (map[uint32][]indexedVolumeExtent, error) { + out := map[uint32][]indexedVolumeExtent{} volNames, err := enumVolumeNames() if err != nil { - return out + return nil, err } for _, volWithSlash := range volNames { volDev := strings.TrimSuffix(volWithSlash, `\`) extents, ok := queryVolumeDiskExtents(volDev) - if !ok || len(extents) != 1 { + if !ok { continue } - ext := extents[0] - out[extentKey{disk: ext.diskNumber, offset: ext.startingOffset}] = indexedVolume{ - volDev: volDev, - hasMountPoints: volumeHasMountPoints(volWithSlash), - filesystem: queryVolumeFilesystem(volWithSlash), + hasMounts, mountErr := volumeHasMountPoints(volWithSlash) + fsName, fsKnown := queryVolumeFilesystem(volWithSlash) + multi := len(extents) > 1 + occupied := multi || mountErr != nil || hasMounts || !fsKnown + for _, ext := range extents { + end := ext.startingOffset + int64(ext.extentLength) + if end <= ext.startingOffset { + end = 1<<63 - 1 + } + out[ext.diskNumber] = append(out[ext.diskNumber], indexedVolumeExtent{ + start: ext.startingOffset, + end: end, + volDev: volDev, + multiExtent: multi, + hasMountPoints: hasMounts, + filesystem: fsName, + occupied: occupied, + }) } } - return out + return out, nil } func excludedHostDiskNumbers(dataRoot string) map[uint32]bool { @@ -200,10 +229,10 @@ func enumVolumeNames() ([]string, error) { return out, nil } -func volumeHasMountPoints(volWithSlash string) bool { +func volumeHasMountPoints(volWithSlash string) (bool, error) { p, err := windows.UTF16PtrFromString(volWithSlash) if err != nil { - return false + return true, err } buf := make([]uint16, 1024) var needed uint32 @@ -211,31 +240,36 @@ func volumeHasMountPoints(volWithSlash string) bool { if needed > uint32(len(buf)) { buf = make([]uint16, needed) if err := windows.GetVolumePathNamesForVolumeName(p, &buf[0], uint32(len(buf)), &needed); err != nil { - return false + return true, err } } else { - return false + return true, err } } - return len(buf) > 0 && buf[0] != 0 + return len(buf) > 0 && buf[0] != 0, nil } -func queryVolumeFilesystem(volWithSlash string) string { +func queryVolumeFilesystem(volWithSlash string) (string, bool) { p, err := syscall.UTF16PtrFromString(volWithSlash) if err != nil { - return "" + return "", false } fsBuf := make([]uint16, 64) - r, _, _ := procGetVolumeInformationW.Call( + r, _, callErr := procGetVolumeInformationW.Call( uintptr(unsafe.Pointer(p)), 0, 0, 0, 0, 0, uintptr(unsafe.Pointer(&fsBuf[0])), uintptr(len(fsBuf)), ) if r == 0 { - return "" + // Unformatted / foreign volumes (e.g. APFS) yield ERROR_UNRECOGNIZED_VOLUME (1005). + // Any other probe error (e.g. ERROR_ACCESS_DENIED) is treated fail-closed by caller. + if errors.Is(callErr, windows.ERROR_UNRECOGNIZED_VOLUME) { + return "", true + } + return "", false } - return syscall.UTF16ToString(fsBuf) + return syscall.UTF16ToString(fsBuf), true } func openDeviceMeta(devicePath string, access uint32) (windows.Handle, error) { @@ -261,12 +295,19 @@ func queryVolumeDiskExtents(volDev string) ([]volumeDiskExtent, bool) { } defer windows.CloseHandle(h) - buf := make([]byte, 256) + var buf []byte var n uint32 - if err := windows.DeviceIoControl(h, ioctlVolumeGetVolumeDiskExtents, nil, 0, &buf[0], uint32(len(buf)), &n, nil); err != nil { - return nil, false + for size := 256; size <= 65536; size *= 2 { + buf = make([]byte, size) + err = windows.DeviceIoControl(h, ioctlVolumeGetVolumeDiskExtents, nil, 0, &buf[0], uint32(len(buf)), &n, nil) + if err == nil { + break + } + if !errors.Is(err, windows.ERROR_MORE_DATA) { + return nil, false + } } - if n < 32 { + if err != nil || n < 32 { return nil, false } count := binary.LittleEndian.Uint32(buf[0:4]) @@ -327,14 +368,26 @@ func queryDiskPartitions(diskNum uint32) []diskPartitionEntry { return nil } style := binary.LittleEndian.Uint32(buf[0:4]) + if style != 0 && style != 1 { + return nil + } count := binary.LittleEndian.Uint32(buf[4:8]) var out []diskPartitionEntry + // Per winioctl.h (DRIVE_LAYOUT_INFORMATION_EX), the Mbr/Gpt union is padded to + // 40 bytes (DRIVE_LAYOUT_INFORMATION_GPT), so PartitionEntry[0] starts at byte 48 + // for both MBR (style=0) and GPT (style=1). for i := uint32(0); i < count; i++ { off := 48 + int(i)*144 if off+144 > int(n) { break } entryStyle := binary.LittleEndian.Uint32(buf[off : off+4]) + if style == 0 && entryStyle == 0 { + mbrType := buf[off+32] + if mbrType == 0x00 || mbrType == 0x05 || mbrType == 0x0F { + continue + } + } startOff := int64(binary.LittleEndian.Uint64(buf[off+8 : off+16])) length := binary.LittleEndian.Uint64(buf[off+16 : off+24]) num := binary.LittleEndian.Uint32(buf[off+24 : off+28]) diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 31edf2d..bb832ba 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -666,6 +666,7 @@ var catalog = map[Locale]map[string]string{ "validate.dir_inaccessible": "目标目录 {dir} 无法访问,检查权限或选择其他目录", "validate.dir_not_directory": "目标路径 {dir} 不是目录,选择新目录或空目录", "validate.dir_not_empty": "目标目录 {dir} 非空,选择新目录或空目录", + "validate.disk_cache_requires_runtime": "当前运行时不支持 --disk-cache,请更新至新版运行时", "validate.disk_not_found": "所选虚拟磁盘文件不存在", "validate.eject_before_controller_change": "切换磁盘控制器前须先弹出 macOS 安装盘", "validate.gpu_icd_not_found": "所选 Vulkan ICD JSON 文件不存在", @@ -689,6 +690,7 @@ var catalog = map[Locale]map[string]string{ "validate.missing_release": "请选择要离线安装的 macOS 版本", "validate.name_taken": "已存在名为 {name} 的虚拟机", "validate.raw_disk_in_place_only": "Windows 裸分区或物理盘路径仅支持原地直挂(in-place)", + "validate.raw_disk_requires_runtime": "当前运行时不支持 Windows 裸分区/物理盘直通,请更新至新版运行时", "validate.vm_suspended": "虚拟机当前处于挂起状态,请先恢复或放弃挂起状态后再修改配置", "viewLogs": "查看日志", "vm.already_running": "{name} 已在运行中", @@ -1371,6 +1373,7 @@ var catalog = map[Locale]map[string]string{ "validate.dir_inaccessible": "Target folder {dir} cannot be accessed; check permissions or choose another folder", "validate.dir_not_directory": "Target path {dir} is not a folder; choose a new or empty folder", "validate.dir_not_empty": "Target folder {dir} is not empty; choose a new or empty folder", + "validate.disk_cache_requires_runtime": "Active runtime does not support --disk-cache; update to a newer runtime", "validate.disk_not_found": "Selected disk image file does not exist", "validate.eject_before_controller_change": "Eject the macOS installer before changing disk controller", "validate.gpu_icd_not_found": "Selected Vulkan ICD JSON file does not exist", @@ -1394,6 +1397,7 @@ var catalog = map[Locale]map[string]string{ "validate.missing_release": "Choose the macOS release to install offline", "validate.name_taken": "A VM named {name} already exists", "validate.raw_disk_in_place_only": "Windows raw disk or partition paths must be attached in place", + "validate.raw_disk_requires_runtime": "Active runtime does not support Windows raw disk passthrough; update to a newer runtime", "validate.vm_suspended": "Resume or discard the VM's suspended state before changing its settings", "viewLogs": "View logs", "vm.already_running": "{name} is already running", diff --git a/internal/macos/macosdriver/driver.go b/internal/macos/macosdriver/driver.go index e30036a..a5ed302 100644 --- a/internal/macos/macosdriver/driver.go +++ b/internal/macos/macosdriver/driver.go @@ -12,6 +12,7 @@ import ( "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/macos/startprep" "github.com/Nwflower/reims-go/internal/plugin" @@ -248,7 +249,7 @@ func (d *ReimsMacOSDriver) ValidateCreate(_ context.Context, req driver.CreateRe } func (d *ReimsMacOSDriver) Create(ctx context.Context, req driver.CreateRequest, stdout, stderr io.Writer) error { - c, err := d.client() + c, active, err := d.startClient() if err != nil { return err } @@ -256,6 +257,15 @@ func (d *ReimsMacOSDriver) Create(ctx context.Context, req driver.CreateRequest, if err := decodeMap(req.Options, &opts); err != nil { return err } + loc := i18n.EffectiveLocale(d.getConfig().Locale) + if !active.Manifest.HasCapability("win32-native-aio") { + if dcache := strings.TrimSpace(opts.DiskCache); dcache != "" && !strings.EqualFold(dcache, "default") { + return errors.New(i18n.T(loc, "validate.disk_cache_requires_runtime")) + } + if reims.IsWindowsRawDevicePath(opts.Disk) { + return errors.New(i18n.T(loc, "validate.raw_disk_requires_runtime")) + } + } if opts.Name == "" { opts.Name = req.Name } @@ -299,7 +309,7 @@ func (d *ReimsMacOSDriver) ValidateSet(ctx context.Context, req driver.SetReques } func (d *ReimsMacOSDriver) Set(ctx context.Context, req driver.SetRequest, stdout, stderr io.Writer) error { - c, err := d.client() + c, active, err := d.startClient() if err != nil { return err } @@ -307,6 +317,9 @@ func (d *ReimsMacOSDriver) Set(ctx context.Context, req driver.SetRequest, stdou if err := decodeMap(req.Changes, &opts); err != nil { return err } + if strings.TrimSpace(opts.DiskCache) != "" && !active.Manifest.HasCapability("win32-native-aio") { + return errors.New(i18n.T(i18n.EffectiveLocale(d.getConfig().Locale), "validate.disk_cache_requires_runtime")) + } opts.Name = req.Name cur, release, err := startprep.LockMutableVM(ctx, c, req.Name) if err != nil { diff --git a/internal/macos/macosdriver/validate_test.go b/internal/macos/macosdriver/validate_test.go index 9399e74..12cdae9 100644 --- a/internal/macos/macosdriver/validate_test.go +++ b/internal/macos/macosdriver/validate_test.go @@ -110,3 +110,30 @@ func TestReimsMacOSDriverCreateProtectsRegisteredVMInAbortedDir(t *testing.T) { t.Fatalf("registered VM dir %s must not be removed: %v", vms[0].Directory, statErr) } } + +func TestReimsMacOSDriverRejectsDiskCacheAndRawDiskWithoutCapability(t *testing.T) { + d := newFakeRuntimeDriver(t) + ctx := context.Background() + var out bytes.Buffer + + if err := d.Create(ctx, driver.CreateRequest{ + Name: "new-mac", + Options: map[string]any{"disk_cache": "unsafe"}, + }, &out, &out); err == nil || !strings.Contains(err.Error(), "--disk-cache") { + t.Fatalf("expected runtime capability error for Create disk_cache, got %v", err) + } + + if err := d.Create(ctx, driver.CreateRequest{ + Name: "new-mac", + Options: map[string]any{"disk": `\\.\Harddisk1Partition2`, "disk_mode": "in-place"}, + }, &out, &out); err == nil { + t.Fatalf("expected runtime capability error for Create raw disk") + } + + if err := d.Set(ctx, driver.SetRequest{ + Name: "normal-vm", + Changes: map[string]any{"disk_cache": "none"}, + }, &out, &out); err == nil || !strings.Contains(err.Error(), "--disk-cache") { + t.Fatalf("expected runtime capability error for Set disk_cache, got %v", err) + } +} diff --git a/internal/macos/reims/cow_guard.go b/internal/macos/reims/cow_guard.go index adfd6b7..854fd49 100644 --- a/internal/macos/reims/cow_guard.go +++ b/internal/macos/reims/cow_guard.go @@ -612,6 +612,9 @@ func (c *Client) checkCoWBackingUse(vms []driver.VMInfo, excludeVM string, match func visitDiskBackings(disk string, visit func(string) bool) error { seen := make(map[string]bool) for disk != "" { + if IsWindowsRawDevicePath(disk) { + return nil + } key := diskPathKey(absoluteDiskPath(disk)) if seen[key] { return nil diff --git a/internal/macos/reims/rawdisk_cache_test.go b/internal/macos/reims/rawdisk_cache_test.go index ef1c031..56c88f5 100644 --- a/internal/macos/reims/rawdisk_cache_test.go +++ b/internal/macos/reims/rawdisk_cache_test.go @@ -2,9 +2,12 @@ package reims import ( "context" + "os" + "path/filepath" "slices" "testing" + "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" ) @@ -106,3 +109,18 @@ func TestLockCoWDisksAllowsRawDevicePath(t *testing.T) { } release() } + +func TestCheckCoWBackingUseSkipsRawDeviceVMs(t *testing.T) { + vmDir := filepath.Join(t.TempDir(), "raw-vm") + if err := os.MkdirAll(vmDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(vmDir, "vm.toml"), []byte("disk = \"\\\\\\\\.\\\\Harddisk1Partition2\"\n"), 0o644); err != nil { + t.Fatal(err) + } + c := &Client{Locale: i18n.EnUS} + vms := []driver.VMInfo{{Name: "raw-vm", Directory: vmDir}} + if err := c.checkCoWBackingUse(vms, "", func(string) bool { return false }); err != nil { + t.Fatalf("checkCoWBackingUse returned error for raw device VM: %v", err) + } +} diff --git a/locales/en-US/native.json b/locales/en-US/native.json index e2f11d2..df35b3c 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -522,8 +522,10 @@ "validate.invalid_disk_size": "New disk size must be at least 32G (recommended 128G)", "validate.disk_not_found": "Selected disk image file does not exist", "validate.raw_disk_in_place_only": "Windows raw disk or partition paths must be attached in place", + "validate.raw_disk_requires_runtime": "Active runtime does not support Windows raw disk passthrough; update to a newer runtime", "validate.invalid_disk_controller": "Disk controller must be nvme, ahci, or virtio", "validate.invalid_disk_cache": "Disk cache mode must be default, writeback, none, or unsafe", + "validate.disk_cache_requires_runtime": "Active runtime does not support --disk-cache; update to a newer runtime", "validate.installer_not_found": "Selected installer image file does not exist", "validate.gpu_icd_not_found": "Selected Vulkan ICD JSON file does not exist", "validate.invalid_resolution": "Resolution must match WIDTHxHEIGHT (e.g. 1920x1080)", diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index 9676786..f209c90 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -388,6 +388,7 @@ "diskCacheOptionWriteback": "Writeback", "diskCacheOptionNone": "Direct", "diskCacheOptionUnsafe": "Unsafe", + "diskCacheRequiresRuntime": "Update to a newer runtime to configure disk I/O cache policy", "diskUsageSummary": "{actual} used of {virtual}", "diskResizeTitle": "Expand disk", "diskResizeDesc": "Grow only. Afterwards, run the command shown in macOS Terminal to use the new space", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 0822d18..225d19f 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -522,8 +522,10 @@ "validate.invalid_disk_size": "新建磁盘上限不能小于 32G(推荐 128G)", "validate.disk_not_found": "所选虚拟磁盘文件不存在", "validate.raw_disk_in_place_only": "Windows 裸分区或物理盘路径仅支持原地直挂(in-place)", + "validate.raw_disk_requires_runtime": "当前运行时不支持 Windows 裸分区/物理盘直通,请更新至新版运行时", "validate.invalid_disk_controller": "磁盘控制器仅支持 nvme、ahci 或 virtio", "validate.invalid_disk_cache": "磁盘缓存策略仅支持 default、writeback、none 或 unsafe", + "validate.disk_cache_requires_runtime": "当前运行时不支持 --disk-cache,请更新至新版运行时", "validate.installer_not_found": "所选安装镜像文件不存在", "validate.gpu_icd_not_found": "所选 Vulkan ICD JSON 文件不存在", "validate.invalid_resolution": "分辨率格式须为 宽x高(如 1920x1080)", diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index 0ee7276..812d61c 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -388,6 +388,7 @@ "diskCacheOptionWriteback": "回写", "diskCacheOptionNone": "直通", "diskCacheOptionUnsafe": "激进 (Unsafe)", + "diskCacheRequiresRuntime": "当前运行时版本过旧,请更新到支持磁盘缓存策略的新版运行时", "diskUsageSummary": "已占用 {actual},上限 {virtual}", "diskResizeTitle": "扩大磁盘", "diskResizeDesc": "只能增大。扩大后在 macOS 终端运行提示的命令,新空间才能使用",