From 78d76f7353e08cf1366fc9d68b9f960004cb1f8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Sun, 29 Nov 2026 18:16:20 -0700 Subject: [PATCH] feat(host,ui): probe Vulkan 1.3 GPU capabilities and grade compatibility --- frontend/src/components/CreateWizard.tsx | 41 +++- frontend/src/components/HostView.tsx | 29 ++- frontend/src/components/SettingsModal.tsx | 36 ++- frontend/src/components/Setup.tsx | 17 +- frontend/src/i18n.ts | 16 ++ frontend/src/lib/format.ts | 60 ++++- frontend/src/types.ts | 5 +- frontend/wailsjs/go/models.ts | 14 ++ internal/app/diagnostics_flow.go | 6 + internal/cli/cli.go | 62 +++++- internal/driver/reims/compat.go | 42 ++++ internal/driver/reims/compat_test.go | 14 ++ internal/host/gpu_compat.go | 260 ++++++++++++++++++++++ internal/host/host.go | 125 +++++++++-- internal/host/host_test.go | 115 ++++++++++ internal/host/host_windows.go | 25 ++- internal/host/host_windows_test.go | 9 + internal/host/optimizations.go | 16 +- internal/host/vulkan_windows.go | 175 +++++++++++++++ internal/i18n/i18n.go | 26 ++- 20 files changed, 1036 insertions(+), 57 deletions(-) create mode 100644 internal/host/gpu_compat.go create mode 100644 internal/host/vulkan_windows.go diff --git a/frontend/src/components/CreateWizard.tsx b/frontend/src/components/CreateWizard.tsx index f4f8ca9..763a415 100644 --- a/frontend/src/components/CreateWizard.tsx +++ b/frontend/src/components/CreateWizard.tsx @@ -6,8 +6,11 @@ import { MEMORY_MARKS, controllerLabel, defaultGuestLang, + findGPU, formatMemory, + gpuCompatHint, gpuLabel, + gpuOptionValue, guestLangLabel, memorySafeLimitGB, parseMemoryGB, @@ -102,8 +105,10 @@ export const CreateWizard: React.FC = ({ locale, host, draft, onClose, on disk: '', disk_mode: 'copy', disk_controller: 'nvme', - graphics: 'reims-vgpu', - gpu: host.recommended_gpu?.vulkan_icd ?? 'auto', + graphics: host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga', + // Default to "auto" rather than a DriverStore FileRepository ICD path so + // Windows GPU driver updates never break existing VM configs. + gpu: 'auto', resolution: recommendedResolution(host), displays: 1, borderless: false, @@ -195,6 +200,8 @@ export const CreateWizard: React.FC = ({ locale, host, draft, onClose, on const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : []) const realGPUs = (host.gpus ?? []).filter((g) => g.kind !== 'virtual') + const selectedGPU = findGPU(host, opts.gpu) + const selectedGPUHint = gpuCompatHint(locale, selectedGPU) const threads = Math.max(host.logical_cpus || 0, 1) const cpuRec = recommendedCPUs(host) const memRec = recommendedMemoryGB(host) @@ -485,7 +492,22 @@ export const CreateWizard: React.FC = ({ locale, host, draft, onClose, on title={tr('gpuSelect')} disabled={opts.graphics !== 'reims-vgpu'} reason={tr('gpuSvgaReason')} - desc={realGPUs.length === 0 ? {tr('gpuUnavailableHint')} : undefined} + desc={ + realGPUs.length === 0 ? ( + {tr('gpuUnavailableHint')} + ) : selectedGPUHint ? ( + + {selectedGPUHint}{' '} + + + ) : undefined + } control={ = ({ locale, host, draft, onClose, on onChange={(gpu) => set({ gpu })} options={[ { value: 'auto', label: tr('gpuAutoTitle'), detail: host.recommended_gpu ? shortGPUName(host.recommended_gpu.name) : undefined }, - ...realGPUs.map((g) => ({ value: g.vulkan_icd, label: shortGPUName(g.name) })), + ...realGPUs.map((g) => ({ + value: gpuOptionValue(g, realGPUs), + label: shortGPUName(g.name), + detail: + g.compat === 'unsupported' + ? tr('gpuCompatUnsupported') + : g.compat === 'warn' + ? tr('gpuCompatWarn') + : g.vulkan_version + ? `Vulkan ${g.vulkan_version}` + : undefined, + })), ]} /> } diff --git a/frontend/src/components/HostView.tsx b/frontend/src/components/HostView.tsx index a141145..4bb38f8 100644 --- a/frontend/src/components/HostView.tsx +++ b/frontend/src/components/HostView.tsx @@ -1,7 +1,7 @@ import { Cpu, HardDrive, MemoryStick, Plus, RefreshCw, ShieldCheck } from 'lucide-react' import React, { useEffect, useState } from 'react' import { I18nKey, t } from '../i18n' -import { formatBytes } from '../lib/format' +import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format' import { AppState, Locale, RuntimeSource, StorageBreakdown, Task } from '../types' import { Button, IconButton } from '../ui/controls' import { api } from '../wails' @@ -202,17 +202,26 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o {realGPUs.length === 0 ? (
—
) : ( - realGPUs.map((g) => ( -
-
-
- {g.name} - {gpuKind(g.kind)} - {host.recommended_gpu?.vulkan_icd === g.vulkan_icd && {tr('gpuRecommended')}} + realGPUs.map((g, idx) => { + const meta = gpuMetaLine(g) + const hint = gpuCompatHint(locale, g) + const isRec = sameGPU(host.recommended_gpu, g) + return ( +
+
+
+ {g.name} + {gpuKind(g.kind)} + {g.compat === 'unsupported' && {tr('gpuCompatUnsupported')}} + {g.compat === 'warn' && {tr('gpuCompatWarn')}} + {isRec && g.compat !== 'warn' && g.compat !== 'unsupported' && {tr('gpuRecommended')}} +
+ {meta &&
{meta}
} + {hint &&
{hint}
}
-
- )) + ) + }) )}
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 4fc70c8..5094f7a 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -5,7 +5,10 @@ import { GUEST_LANG_PRESETS, splitLangLabel, MEMORY_MARKS, + findGPU, formatBytes, + gpuCompatHint, + gpuOptionValue, memorySafeLimitGB, parseMemoryGB, recommendedCPUs, @@ -487,14 +490,21 @@ export const SettingsModal: React.FC = ({ locale, detail, stats, host, op sub: host.recommended_gpu ? tr('gpuAutoSub', { name: shortGPUName(host.recommended_gpu.name) }) : tr('gpuAutoOption'), }, ...realGPUs.map((g) => ({ - value: g.vulkan_icd, + value: gpuOptionValue(g, realGPUs), title: shortGPUName(g.name), - sub: g.kind === 'discrete' ? tr('gpuKindDiscrete') : g.kind === 'integrated' ? tr('gpuKindIntegrated') : undefined, + sub: [ + g.kind === 'discrete' ? tr('gpuKindDiscrete') : g.kind === 'integrated' ? tr('gpuKindIntegrated') : '', + g.compat === 'unsupported' ? tr('gpuCompatUnsupported') : g.compat === 'warn' ? tr('gpuCompatWarn') : '', + ] + .filter(Boolean) + .join(' · ') || undefined, })), ] if (form.gpu && form.gpu !== 'auto' && !gpuOptions.some((o) => normPath(o.value) === normPath(form.gpu))) { gpuOptions.push({ value: form.gpu, title: form.gpu.split(/[\\/]/).pop() || form.gpu, sub: tr('gpuCustomIcd') }) } + const selectedGPU = findGPU(host, form.gpu) + const selectedGPUHint = gpuCompatHint(locale, selectedGPU) const vgpu = form.graphics !== 'vmware-svga' const pd = host.primary_display const hidpiAdvice = hostDisplayAdvice(host, tr) @@ -527,7 +537,27 @@ export const SettingsModal: React.FC = ({ locale, detail, stats, host, op {tr('gpuUnavailableHint')} : undefined} + desc={ + realGPUs.length === 0 ? ( + {tr('gpuUnavailableHint')} + ) : selectedGPUHint ? ( + + {selectedGPUHint} + {!running && vgpu && ( + <> + {' '} + + + )} + + ) : undefined + } disabled={!vgpu} reason={tr('gpuSvgaReason')} block={ normPath(o.value) === normPath(form.gpu))?.value} onChange={(gpu) => set({ gpu })} options={gpuOptions} />} diff --git a/frontend/src/components/Setup.tsx b/frontend/src/components/Setup.tsx index 819dfa9..388b33c 100644 --- a/frontend/src/components/Setup.tsx +++ b/frontend/src/components/Setup.tsx @@ -4,7 +4,7 @@ import { getLocaleOptions, I18nKey, joinNotices, t } from '../i18n' import { AppState, DataRootCheck, DataRootChoice, Locale, ResolvedLocalePack, RuntimeSource, Task } from '../types' import { Button } from '../ui/controls' import { PopupSelect } from '../ui/settings' -import { recommendedMemoryGB, shortGPUName } from '../lib/format' +import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format' import { api } from '../wails' import { RuntimeOnline } from './RuntimeOnline' @@ -165,6 +165,8 @@ const RuntimeStep: React.FC = ({ locale, tr, state, runtimeTask, onCh } const whpxOK = host.whpx === 'ready' const gpu = host.recommended_gpu ?? (host.gpus ?? []).find((g) => g.kind !== 'virtual') + const gpuHint = gpuCompatHint(locale, gpu) + const gpuOK = !!gpu && gpu.compat !== 'warn' && gpu.compat !== 'unsupported' const recMem = recommendedMemoryGB(host) return ( <> @@ -198,9 +200,20 @@ const RuntimeStep: React.FC = ({ locale, tr, state, runtimeTask, onCh
{tr('setupGPU')}
{gpu ? shortGPUName(gpu.name) : tr('setupNoGPU')}
+ {gpuHint &&
{gpuHint}
}
- {tr(gpu ? 'whpxReady' : 'hostNeedsAction')} + + {tr( + gpuOK + ? 'whpxReady' + : gpu?.compat === 'unsupported' + ? 'gpuCompatUnsupported' + : gpu?.compat === 'warn' + ? 'gpuCompatWarn' + : 'hostNeedsAction', + )} +
diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index 329cc7a..7390383 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -403,6 +403,14 @@ const dict = { gpuIntegrated: '核显', gpuVirtual: '虚拟', gpuUnknown: '未知', + gpuCompatWarn: '已知兼容风险', + gpuCompatUnsupported: '不支持加速', + gpuWarnAmdLegacy: 'AMD Vega/Polaris 在 Windows 闭源驱动下存在上游已知黑屏/设备丢失问题({ref});若有其他独显请改选独显,否则建议暂用 VMware SVGA', + gpuWarnAmdRdna2: '该 AMD 显卡在 Windows 下存在上游已知设备丢失风险({ref});若卡死黑屏请升级驱动或暂用 VMware SVGA', + gpuErrVulkanTooOld: 'Vulkan {ver} 低于 1.3 最低要求,请更新显卡驱动或改用 VMware SVGA', + gpuErrMissingExt: '缺少必需 Vulkan 扩展({ext}),请更新显卡驱动或改用 VMware SVGA', + gpuErrVulkanCpu: '软件 Vulkan 实现不满足 vGPU 加速要求,请改用 VMware SVGA', + gpuSwitchSvga: '改用 VMware SVGA', // Wizard wizardTitle: '新建虚拟机', @@ -1183,6 +1191,14 @@ const dict = { gpuIntegrated: 'Integrated', gpuVirtual: 'Virtual', gpuUnknown: 'Unknown', + gpuCompatWarn: 'Known issue', + gpuCompatUnsupported: 'Unsupported', + gpuWarnAmdLegacy: 'AMD Vega/Polaris on Windows hits known upstream black-screen/device-loss issues ({ref}); prefer another discrete GPU or use VMware SVGA for now', + gpuWarnAmdRdna2: 'This AMD GPU hits known Windows device-loss issues upstream ({ref}); update drivers or use VMware SVGA if it freezes', + gpuErrVulkanTooOld: 'Vulkan {ver} is below the required 1.3 floor; update GPU drivers or use VMware SVGA', + gpuErrMissingExt: 'Missing required Vulkan extensions ({ext}); update GPU drivers or use VMware SVGA', + gpuErrVulkanCpu: 'Software Vulkan implementation cannot accelerate vGPU; use VMware SVGA', + gpuSwitchSvga: 'Use VMware SVGA', wizardTitle: 'New virtual machine', srcOfflineTitle: 'Offline installer', diff --git a/frontend/src/lib/format.ts b/frontend/src/lib/format.ts index 9a1eef4..e8c4fc7 100644 --- a/frontend/src/lib/format.ts +++ b/frontend/src/lib/format.ts @@ -62,9 +62,63 @@ export function controllerLabel(raw: string): string { } } -function findGPU(host: HostReport, icd: string): GPUInfo | undefined { - const norm = (s: string) => s.replace(/\//g, '\\').toLowerCase() - return (host.gpus ?? []).find((g) => norm(g.vulkan_icd) === norm(icd)) +const normPath = (s: string) => s.replace(/\//g, '\\').toLowerCase() + +export function gpuKey(g: GPUInfo, idx = 0): string { + const pci = g.vendor_id && g.device_id ? `${g.vendor_id}:${g.device_id}` : '' + return `${pci}|${normPath(g.vulkan_icd || '')}|${g.name}|${idx}` +} + +export function sameGPU(a?: GPUInfo, b?: GPUInfo): boolean { + if (!a || !b) return false + if (a.vendor_id && a.device_id && b.vendor_id && b.device_id) { + return a.vendor_id === b.vendor_id && a.device_id === b.device_id + } + return !!a.vulkan_icd && normPath(a.vulkan_icd) === normPath(b.vulkan_icd) && a.name === b.name +} + +/** Stable `--gpu` value for a GPU: its ICD path when unique, else its name (for shared AMD ICDs). */ +export function gpuOptionValue(g: GPUInfo, all: GPUInfo[]): string { + if (g.vulkan_icd) { + const target = normPath(g.vulkan_icd) + const shared = all.filter((o) => o.vulkan_icd && normPath(o.vulkan_icd) === target).length > 1 + if (!shared) return g.vulkan_icd + } + return g.name +} + +export function findGPU(host: HostReport, value: string | undefined): GPUInfo | undefined { + if (!value || value === 'auto') return host.recommended_gpu + const norm = normPath(value) + return (host.gpus ?? []).find( + (g) => (g.vulkan_icd && normPath(g.vulkan_icd) === norm) || g.name.toLowerCase() === value.toLowerCase(), + ) +} + +export function gpuMetaLine(g: GPUInfo): string { + const parts: string[] = [] + if (g.vendor_id && g.device_id) parts.push(`${g.vendor_id}:${g.device_id}`) + if (g.vulkan_version) parts.push(`Vulkan ${g.vulkan_version}`) + if (g.driver_version) parts.push(g.driver_version) + return parts.join(' · ') +} + +export function gpuCompatHint(locale: Locale, g?: GPUInfo): string { + if (!g) return '' + switch (g.compat_code) { + case 'amd_legacy_win_driver': + return t(locale, 'gpuWarnAmdLegacy', { ref: g.compat_detail || 'steelbrain/reims-vgpu#181' }) + case 'amd_rdna2_device_lost': + return t(locale, 'gpuWarnAmdRdna2', { ref: g.compat_detail || 'steelbrain/reims-vgpu#173' }) + case 'vulkan_too_old': + return t(locale, 'gpuErrVulkanTooOld', { ver: g.compat_detail || g.vulkan_version || '?' }) + case 'vulkan_missing_extensions': + return t(locale, 'gpuErrMissingExt', { ext: g.compat_detail || '' }) + case 'vulkan_cpu': + return t(locale, 'gpuErrVulkanCpu') + default: + return '' + } } /** Drop vendor boilerplate: "NVIDIA GeForce RTX 4070 Ti" → "RTX 4070 Ti". */ diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 38dfb2a..fbb1aff 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -23,8 +23,11 @@ export type AudioInfo = host.AudioInfo export type WHPXCapabilities = host.WHPXCapabilities export type LogicalCPUInfo = host.LogicalCPUInfo -export type GPUInfo = Model & { +export type GPUCompat = 'supported' | 'warn' | 'unsupported' | 'unknown' + +export type GPUInfo = Omit, 'compat'> & { kind: 'discrete' | 'integrated' | 'virtual' | 'unknown' + compat?: GPUCompat } export type OptimizationStatus = 'recommended' | 'available' | 'experimental' | 'auto' | 'unavailable' diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 992f296..69d26e4 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -592,6 +592,13 @@ export namespace host { name: string; vulkan_icd: string; kind: string; + vendor_id?: string; + device_id?: string; + driver_version?: string; + vulkan_version?: string; + compat?: string; + compat_code?: string; + compat_detail?: string; static createFrom(source: any = {}) { return new GPUInfo(source); @@ -602,6 +609,13 @@ export namespace host { this.name = source["name"]; this.vulkan_icd = source["vulkan_icd"]; this.kind = source["kind"]; + this.vendor_id = source["vendor_id"]; + this.device_id = source["device_id"]; + this.driver_version = source["driver_version"]; + this.vulkan_version = source["vulkan_version"]; + this.compat = source["compat"]; + this.compat_code = source["compat_code"]; + this.compat_detail = source["compat_detail"]; } } export class LogicalCPUInfo { diff --git a/internal/app/diagnostics_flow.go b/internal/app/diagnostics_flow.go index 421c462..00993d6 100644 --- a/internal/app/diagnostics_flow.go +++ b/internal/app/diagnostics_flow.go @@ -57,6 +57,12 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error { "host": b.HostReport, "optimizations": b.Optimizations, } + if code, detail := reims.DiagnoseGPULog(b.QEMULog); code != "" { + hostSummary["gpu_diagnosis"] = map[string]string{ + "code": code, + "detail": detail, + } + } if err := addJSON("host-report.json", hostSummary); err != nil { _ = zw.Close() _ = f.Close() diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 8466ae0..142e90d 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -207,11 +207,38 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { } else { fmt.Printf("%s:\n", i18n.T(loc, "doctor.gpu")) for _, g := range rep.GPUs { - rec := "" - if rep.RecommendedGPU != nil && rep.RecommendedGPU.VulkanICD == g.VulkanICD { - rec = " [" + i18n.T(loc, "doctor.gpu.recommended") + "]" + tags := []string{} + if rep.RecommendedGPU != nil && sameGPU(rep.RecommendedGPU, &g) { + tags = append(tags, i18n.T(loc, "doctor.gpu.recommended")) + } + if g.Compat != "" { + tags = append(tags, i18n.T(loc, "doctor.gpu.compat."+string(g.Compat))) + } + tagStr := "" + if len(tags) > 0 { + tagStr = " [" + strings.Join(tags, " | ") + "]" + } + meta := []string{} + if g.VendorID != "" && g.DeviceID != "" { + meta = append(meta, g.VendorID+":"+g.DeviceID) + } + if g.VulkanVersion != "" { + meta = append(meta, "Vulkan "+g.VulkanVersion) + } + if g.DriverVersion != "" { + meta = append(meta, "drv "+g.DriverVersion) + } + metaStr := "" + if len(meta) > 0 { + metaStr = " (" + strings.Join(meta, ", ") + ")" + } + fmt.Printf(" - [%s] %s%s%s\n", g.Kind, g.Name, metaStr, tagStr) + if g.VulkanICD != "" { + fmt.Printf(" ICD: %s\n", g.VulkanICD) + } + if note := formatGPUCompatNote(loc, g); note != "" { + fmt.Printf(" ! %s\n", note) } - fmt.Printf(" - [%s] %s%s\n ICD: %s\n", g.Kind, g.Name, rec, g.VulkanICD) } } @@ -223,6 +250,33 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { return nil } +func sameGPU(a, b *host.GPUInfo) bool { + if a == nil || b == nil { + return false + } + if a.VendorID != "" && a.DeviceID != "" && b.VendorID != "" && b.DeviceID != "" { + return a.VendorID == b.VendorID && a.DeviceID == b.DeviceID + } + return a.VulkanICD != "" && a.VulkanICD == b.VulkanICD && a.Name == b.Name +} + +func formatGPUCompatNote(loc i18n.Locale, g host.GPUInfo) string { + switch g.CompatCode { + case "amd_legacy_win_driver": + return i18n.T(loc, "doctor.gpu.warn.amd_legacy", g.CompatDetail) + case "amd_rdna2_device_lost": + return i18n.T(loc, "doctor.gpu.warn.amd_rdna2", g.CompatDetail) + case "vulkan_too_old": + return i18n.T(loc, "doctor.gpu.err.vulkan_too_old", g.CompatDetail) + case "vulkan_missing_extensions": + return i18n.T(loc, "doctor.gpu.err.missing_ext", g.CompatDetail) + case "vulkan_cpu": + return i18n.T(loc, "doctor.gpu.err.vulkan_cpu") + default: + return "" + } +} + func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error { if len(args) == 0 { return fmt.Errorf("usage: reims-go runtime ") diff --git a/internal/driver/reims/compat.go b/internal/driver/reims/compat.go index 4bbf7c4..9c77b7c 100644 --- a/internal/driver/reims/compat.go +++ b/internal/driver/reims/compat.go @@ -73,6 +73,41 @@ 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) { + if output == "" { + return "", "" + } + for _, rawLine := range strings.Split(output, "\n") { + line := strings.TrimSpace(rawLine) + if line == "" { + continue + } + if strings.Contains(line, "ERROR_DEVICE_LOST") || + strings.Contains(line, "was lost at vkQueueSubmit2") || + strings.Contains(line, "rt-device-lost-in-flight") { + return "gpu_device_lost", line + } + } + for _, rawLine := range strings.Split(output, "\n") { + line := strings.TrimSpace(rawLine) + if line == "" { + continue + } + low := strings.ToLower(line) + if strings.Contains(line, "VK_ERROR_INCOMPATIBLE_DRIVER") || + strings.Contains(low, "no vulkan gpu found") || + strings.Contains(low, "meets the floor") || + strings.Contains(low, "below the floor") || + strings.Contains(low, "no physical device") { + return "gpu_vulkan_floor", line + } + } + return "", "" +} + // HasKernelIrqchipArg reports whether extra-args already specifies a // kernel-irqchip setting. func HasKernelIrqchipArg(extraArgs string) bool { @@ -135,6 +170,13 @@ func (c *Client) StartWithCompat(ctx context.Context, name string, stdout, stder } 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 } diff --git a/internal/driver/reims/compat_test.go b/internal/driver/reims/compat_test.go index 88dee15..70377b8 100644 --- a/internal/driver/reims/compat_test.go +++ b/internal/driver/reims/compat_test.go @@ -121,6 +121,20 @@ func TestIsWHPXNoAcceleratorError(t *testing.T) { } } +func TestDiagnoseGPULog(t *testing.T) { + lost := "reims-vgpu: the rt platform's device on AMD Radeon (TM) Graphics (1002:15e7) was lost at vkQueueSubmit2 (ERROR_DEVICE_LOST)" + if code, detail := DiagnoseGPULog(lost); code != "gpu_device_lost" || detail == "" { + t.Fatalf("DiagnoseGPULog(lost) = (%q, %q), want gpu_device_lost", code, detail) + } + floor := "reims-vgpu: no physical device meets the floor (VK_ERROR_INCOMPATIBLE_DRIVER)" + if code, detail := DiagnoseGPULog(floor); code != "gpu_vulkan_floor" || detail == "" { + t.Fatalf("DiagnoseGPULog(floor) = (%q, %q), want gpu_vulkan_floor", code, detail) + } + if code, _ := DiagnoseGPULog("normal boot log line"); code != "" { + t.Fatalf("expected empty code for normal log, got %q", code) + } +} + func TestMergeAndStripOfflineHelperArgs(t *testing.T) { base := `-no-reboot -qmp tcp:127.0.0.1:45555,server=on,wait=off -machine kernel-irqchip=off` merged := MergeOfflineHelperArgs(base, `D:\Data\reims-go\cache\reims-helper.img`) diff --git a/internal/host/gpu_compat.go b/internal/host/gpu_compat.go new file mode 100644 index 0000000..c48b55c --- /dev/null +++ b/internal/host/gpu_compat.go @@ -0,0 +1,260 @@ +package host + +import ( + "fmt" + "regexp" + "strings" +) + +// RequiredVulkanExtensions mirrors the mandatory device extensions enforced by +// upstream metal2vulkan-runtime (crates/metal2vulkan-runtime/src/floor.rs:36-41). +var RequiredVulkanExtensions = []string{ + "VK_KHR_swapchain", + "VK_EXT_robustness2", + "VK_EXT_calibrated_timestamps", + "VK_EXT_line_rasterization", +} + +// VulkanDeviceProbe holds raw Vulkan physical-device properties queried via +// vulkan-1.dll on Windows. +type VulkanDeviceProbe struct { + Name string + VendorID uint32 + DeviceID uint32 + DeviceType uint32 // VkPhysicalDeviceType: 1=integrated, 2=discrete, 3=virtual, 4=cpu + APIVersion uint32 + Extensions map[string]bool +} + +var ( + rePCIVen = regexp.MustCompile(`(?i)VEN_([0-9a-f]{4})`) + rePCIDev = regexp.MustCompile(`(?i)DEV_([0-9a-f]{4})`) +) + +// ParsePCIIDs extracts lowercase 4-hex vendor and device IDs from a Windows +// PnP MatchingDeviceId string (e.g. "PCI\VEN_1002&DEV_164C&REV_C2"). +func ParsePCIIDs(matchingID string) (vendorID, deviceID string) { + if m := rePCIVen.FindStringSubmatch(matchingID); len(m) == 2 { + vendorID = strings.ToLower(m[1]) + } + if m := rePCIDev.FindStringSubmatch(matchingID); len(m) == 2 { + deviceID = strings.ToLower(m[1]) + } + return vendorID, deviceID +} + +// FormatVulkanVersion decodes a Vulkan packed API version uint32 into "major.minor.patch". +func FormatVulkanVersion(apiVersion uint32) string { + if apiVersion == 0 { + return "" + } + major := (apiVersion >> 22) & 0x7F + minor := (apiVersion >> 12) & 0x3FF + patch := apiVersion & 0xFFF + return fmt.Sprintf("%d.%d.%d", major, minor, patch) +} + +func vulkanSupports13(apiVersion uint32) bool { + major := (apiVersion >> 22) & 0x7F + minor := (apiVersion >> 12) & 0x3FF + return major > 1 || (major == 1 && minor >= 3) +} + +// amdLegacyVegaOrPolarisIDs covers AMD GCN4 (Polaris) and GCN5 (Vega) GPUs +// whose Windows proprietary Adrenalin driver moved to the legacy vega-polaris +// maintenance branch (26.5.2) and currently hits WindowServer black screen / +// vkQueueSubmit2 ERROR_DEVICE_LOST on Windows (steelbrain/reims-vgpu#181). +var amdLegacyVegaOrPolarisIDs = map[string]bool{ + // Vega integrated APUs (Raven / Picasso / Renoir / Cezanne / Lucienne / Barcelo) + "15dd": true, // Raven Ridge / Picasso (Ryzen 2000/3000) + "15d8": true, // Picasso (Ryzen 3000U/H) + "1636": true, // Renoir (Ryzen 4000U/H/G) + "1638": true, // Cezanne / Barcelo (Ryzen 5000H/G) + "164c": true, // Lucienne (Ryzen 3 5300U / Ryzen 5 5500U / Ryzen 7 5700U) + "15e7": true, // Barcelo / Barcelo-R (Ryzen 5 5625U / Ryzen 7 5825U / 7530U / 7730U) + // Vega discrete GPUs (Vega 10 / 12 / 20) + "6860": true, "6861": true, "6862": true, "6863": true, "6864": true, + "6867": true, "6868": true, "686c": true, "687f": true, + "69a0": true, "69a1": true, "69a2": true, "69a3": true, "69af": true, + "66a0": true, "66a1": true, "66a2": true, "66a3": true, "66a7": true, "66af": true, + // Polaris discrete GPUs (RX 460/470/480/550/560/570/580/590) + "67df": true, "67ef": true, "67ff": true, "6fdf": true, +} + +func isAMDLegacyVegaOrPolaris(vendorID, deviceID, name string) bool { + if vendorID == "1002" && deviceID != "" { + return amdLegacyVegaOrPolarisIDs[strings.ToLower(deviceID)] + } + if vendorID != "" && vendorID != "1002" { + return false + } + // Name fallback only when PCI device ID is unavailable. + low := strings.ToLower(name) + if !strings.Contains(low, "radeon") { + return false + } + for _, pat := range []string{ + "radeon(tm) vega", "radeon vega", "rx vega", "radeon vii", + "rx 460", "rx 470", "rx 480", "rx 550", "rx 560", "rx 570", "rx 580", "rx 590", + } { + if strings.Contains(low, pat) { + return true + } + } + return false +} + +// isAMDRDNA2DeviceLost reports GPUs hitting deterministic Windows 11 +// vkQueueSubmit2 ERROR_DEVICE_LOST / GPU fault (READ_INVALID) at boot +// (steelbrain/reims-vgpu#173). +func isAMDRDNA2DeviceLost(vendorID, deviceID string) bool { + return vendorID == "1002" && strings.ToLower(deviceID) == "73ff" +} + +// EvaluateGPUCompat merges optional Vulkan runtime probe data into g and +// assigns a compatibility grade aligned with metal2vulkan-runtime's floor +// requirements and verified Windows upstream issues. +func EvaluateGPUCompat(g GPUInfo, probe *VulkanDeviceProbe) GPUInfo { + if probe != nil { + if g.Name == "" { + g.Name = probe.Name + } + if probe.VendorID != 0 { + g.VendorID = fmt.Sprintf("%04x", probe.VendorID) + } + if probe.DeviceID != 0 { + g.DeviceID = fmt.Sprintf("%04x", probe.DeviceID) + } + g.VulkanVersion = FormatVulkanVersion(probe.APIVersion) + + // VkPhysicalDeviceType: 1=INTEGRATED_GPU, 2=DISCRETE_GPU, 3=VIRTUAL_GPU, 4=CPU + switch probe.DeviceType { + case 4: + g.Kind = GPUVirtual + g.Compat = GPUCompatUnsupported + g.CompatCode = "vulkan_cpu" + g.CompatDetail = g.Name + return g + case 3: + g.Kind = GPUVirtual + case 2: + if g.Kind != GPUVirtual { + g.Kind = GPUDiscrete + } + case 1: + if g.Kind != GPUVirtual { + g.Kind = GPUIntegrated + } + } + } + + if g.Kind == GPUVirtual { + g.Compat = GPUCompatUnsupported + g.CompatCode = "virtual_adapter" + return g + } + + if probe != nil { + if !vulkanSupports13(probe.APIVersion) { + g.Compat = GPUCompatUnsupported + g.CompatCode = "vulkan_too_old" + g.CompatDetail = g.VulkanVersion + return g + } + if len(probe.Extensions) > 0 { + var missing []string + for _, ext := range RequiredVulkanExtensions { + if !probe.Extensions[ext] { + missing = append(missing, ext) + } + } + if len(missing) > 0 { + g.Compat = GPUCompatUnsupported + g.CompatCode = "vulkan_missing_extensions" + g.CompatDetail = strings.Join(missing, ", ") + return g + } + } + } + + if isAMDLegacyVegaOrPolaris(g.VendorID, g.DeviceID, g.Name) { + g.Compat = GPUCompatWarn + g.CompatCode = "amd_legacy_win_driver" + g.CompatDetail = "steelbrain/reims-vgpu#181" + return g + } + if isAMDRDNA2DeviceLost(g.VendorID, g.DeviceID) { + g.Compat = GPUCompatWarn + g.CompatCode = "amd_rdna2_device_lost" + g.CompatDetail = "steelbrain/reims-vgpu#173" + return g + } + + if probe != nil { + g.Compat = GPUCompatSupported + g.CompatCode = "ok" + return g + } + g.Compat = GPUCompatUnknown + g.CompatCode = "vulkan_unprobed" + return g +} + +// MergeRegistryAndVulkanGPUs reconciles Windows display-class registry entries +// with live Vulkan physical devices from vulkan-1.dll, preserving ICD paths and +// driver versions while enriching each GPU with real Vulkan 1.3 capability and +// compatibility grades. +func MergeRegistryAndVulkanGPUs(regGPUs []GPUInfo, vkProbes []VulkanDeviceProbe) []GPUInfo { + used := make([]bool, len(vkProbes)) + matchProbe := func(g GPUInfo) *VulkanDeviceProbe { + // 1. Exact PCI vendor:device match. + if g.VendorID != "" && g.DeviceID != "" { + for i := range vkProbes { + if used[i] { + continue + } + if fmt.Sprintf("%04x", vkProbes[i].VendorID) == g.VendorID && + fmt.Sprintf("%04x", vkProbes[i].DeviceID) == g.DeviceID { + used[i] = true + return &vkProbes[i] + } + } + } + // 2. Case-insensitive name fallback when MatchingDeviceId was absent. + lowName := strings.ToLower(strings.TrimSpace(g.Name)) + if lowName != "" { + for i := range vkProbes { + if used[i] { + continue + } + pName := strings.ToLower(strings.TrimSpace(vkProbes[i].Name)) + if pName == lowName || strings.Contains(pName, lowName) || strings.Contains(lowName, pName) { + used[i] = true + return &vkProbes[i] + } + } + } + return nil + } + + out := make([]GPUInfo, 0, len(regGPUs)+len(vkProbes)) + for _, g := range regGPUs { + p := matchProbe(g) + out = append(out, EvaluateGPUCompat(g, p)) + } + // Include any non-CPU Vulkan GPU enumerated by vulkan-1.dll that wasn't + // listed under the display-class registry (e.g. registered only under + // HKLM\SOFTWARE\Khronos\Vulkan\Drivers). + for i := range vkProbes { + if used[i] || vkProbes[i].DeviceType == 4 { + continue + } + p := vkProbes[i] + base := GPUInfo{ + Name: p.Name, + Kind: ClassifyGPU(p.Name), + } + out = append(out, EvaluateGPUCompat(base, &p)) + } + return out +} diff --git a/internal/host/host.go b/internal/host/host.go index c125e7d..df6472d 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -11,10 +11,26 @@ const ( GPUUnknown GPUKind = "unknown" ) +type GPUCompat string + +const ( + GPUCompatSupported GPUCompat = "supported" + GPUCompatWarn GPUCompat = "warn" + GPUCompatUnsupported GPUCompat = "unsupported" + GPUCompatUnknown GPUCompat = "unknown" +) + type GPUInfo struct { - Name string `json:"name"` - VulkanICD string `json:"vulkan_icd"` - Kind GPUKind `json:"kind"` + Name string `json:"name"` + VulkanICD string `json:"vulkan_icd"` + Kind GPUKind `json:"kind"` + VendorID string `json:"vendor_id,omitempty"` + DeviceID string `json:"device_id,omitempty"` + DriverVersion string `json:"driver_version,omitempty"` + VulkanVersion string `json:"vulkan_version,omitempty"` + Compat GPUCompat `json:"compat,omitempty"` + CompatCode string `json:"compat_code,omitempty"` + CompatDetail string `json:"compat_detail,omitempty"` } type WHPXState string @@ -85,20 +101,43 @@ type Report struct { Audio AudioInfo `json:"audio"` } -// ClassifyGPU distinguishes discrete, integrated, and virtual display adapters. +// ClassifyGPU distinguishes discrete, integrated, and virtual display adapters +// from their Windows display adapter name when Vulkan device-type metadata is +// unavailable. func ClassifyGPU(name string) GPUKind { - low := strings.ToLower(name) - for _, v := range []string{"todesk", "gameviewer", "parsec", "virtual", "idd", "microsoft basic", "spacedesk"} { + low := strings.ToLower(strings.TrimSpace(name)) + for _, v := range []string{ + "todesk", "gameviewer", "parsec", "virtual", "idd", + "microsoft basic", "microsoft remote", "spacedesk", + "llvmpipe", "lavapipe", "swiftshader", + } { if strings.Contains(low, v) { return GPUVirtual } } - for _, d := range []string{"nvidia", "geforce", "rtx", "gtx", "quadro", "radeon rx", "radeon pro", "intel(r) arc"} { + // Integrated Intel Arc (Core Ultra Meteor/Arrow/Lunar Lake: "Intel(R) Arc(TM) Graphics", + // "Intel(R) Arc(TM) 140V/130V/140T/130T") must be checked before discrete "intel(r) arc". + if isIntegratedIntelArcName(low) { + return GPUIntegrated + } + for _, d := range []string{ + "nvidia", "geforce", "rtx", "gtx", "quadro", + "radeon rx", "radeon pro", "radeon vii", "radeon r9", "radeon r7", + "intel(r) arc", "intel arc", + } { if strings.Contains(low, d) { return GPUDiscrete } } - for _, i := range []string{"intel(r) uhd", "intel(r) hd", "intel(r) iris", "radeon(tm) graphics"} { + for _, i := range []string{ + "intel(r) uhd", "intel(r) hd", "intel(r) iris", "intel(r) graphics", + "intel uhd", "intel hd", "intel iris", + "radeon(tm) graphics", "radeon graphics", + "radeon(tm) vega", "radeon vega", + "radeon 610m", "radeon 660m", "radeon 680m", + "radeon 740m", "radeon 760m", "radeon 780m", + "radeon 880m", "radeon 890m", + } { if strings.Contains(low, i) { return GPUIntegrated } @@ -106,27 +145,71 @@ func ClassifyGPU(name string) GPUKind { return GPUUnknown } -// PickRecommendedGPU selects the best Vulkan GPU (preferring discrete over integrated, skipping virtual). +func isIntegratedIntelArcName(low string) bool { + if !strings.Contains(low, "intel") || !strings.Contains(low, "arc") { + return false + } + // Discrete Arc cards carry an A/B/Pro series model designator (e.g. A380, A770, B580, Pro A60). + for _, token := range []string{" a3", " a5", " a7", " b5", " b7", " pro "} { + if strings.Contains(low, token) { + return false + } + } + return strings.Contains(low, "arc(tm) graphics") || + strings.Contains(low, "arc graphics") || + strings.Contains(low, "130v") || + strings.Contains(low, "140v") || + strings.Contains(low, "130t") || + strings.Contains(low, "140t") +} + +// PickRecommendedGPU selects the best Vulkan GPU, preferring verified-supported +// discrete GPUs over integrated ones, skipping virtual and unsupported GPUs, +// and falling back to warned GPUs only when no cleaner option exists. func PickRecommendedGPU(gpus []GPUInfo) *GPUInfo { - for i := range gpus { - if gpus[i].Kind == GPUDiscrete && gpus[i].VulkanICD != "" { - cp := gpus[i] - return &cp + compatRank := func(c GPUCompat) int { + switch c { + case GPUCompatSupported, "": + return 0 + case GPUCompatUnknown: + return 1 + case GPUCompatWarn: + return 2 + default: // GPUCompatUnsupported + return 99 } } - for i := range gpus { - if gpus[i].Kind == GPUIntegrated && gpus[i].VulkanICD != "" { - cp := gpus[i] - return &cp + kindRank := func(k GPUKind) int { + switch k { + case GPUDiscrete: + return 0 + case GPUIntegrated: + return 1 + default: + return 2 } } + bestIdx := -1 + bestScore := 1000 for i := range gpus { - if gpus[i].Kind != GPUVirtual && gpus[i].VulkanICD != "" { - cp := gpus[i] - return &cp + g := gpus[i] + if g.Kind == GPUVirtual || g.Compat == GPUCompatUnsupported { + continue + } + if g.VulkanICD == "" && g.VulkanVersion == "" { + continue + } + score := compatRank(g.Compat)*10 + kindRank(g.Kind) + if score < bestScore { + bestScore = score + bestIdx = i } } - return nil + if bestIdx < 0 { + return nil + } + cp := gpus[bestIdx] + return &cp } // AllCPUsMask returns the 64-bit affinity mask covering logical CPUs 0..n-1 diff --git a/internal/host/host_test.go b/internal/host/host_test.go index d553c3b..1f8bd83 100644 --- a/internal/host/host_test.go +++ b/internal/host/host_test.go @@ -21,6 +21,121 @@ func TestGPUClassificationAndRecommendation(t *testing.T) { if rec == nil || rec.VulkanICD != `C:\nv-vk64.json` { t.Fatalf("expected NVIDIA discrete GPU to be recommended, got %#v", rec) } + + // Regression checks for AMD iGPUs and Intel Core Ultra integrated Arc vs discrete Arc. + cases := []struct { + name string + want GPUKind + }{ + {"AMD Radeon Graphics", GPUIntegrated}, + {"AMD Radeon(TM) Graphics", GPUIntegrated}, + {"AMD Radeon(TM) Vega 8 Graphics", GPUIntegrated}, + {"AMD Radeon 780M Graphics", GPUIntegrated}, + {"AMD Radeon RX 7900 XTX", GPUDiscrete}, + {"Intel(R) Arc(TM) Graphics", GPUIntegrated}, + {"Intel(R) Arc(TM) 140V GPU", GPUIntegrated}, + {"Intel(R) Arc(TM) A770 Graphics", GPUDiscrete}, + {"Intel(R) Arc(TM) B580 Graphics", GPUDiscrete}, + {"Microsoft Remote Display Adapter", GPUVirtual}, + } + for _, tc := range cases { + if got := ClassifyGPU(tc.name); got != tc.want { + t.Errorf("ClassifyGPU(%q) = %s, want %s", tc.name, got, tc.want) + } + } +} + +func TestGPUCompatibilityGradingAndRecommendation(t *testing.T) { + allReqExts := map[string]bool{ + "VK_KHR_swapchain": true, + "VK_EXT_robustness2": true, + "VK_EXT_calibrated_timestamps": true, + "VK_EXT_line_rasterization": true, + } + v13 := uint32((1 << 22) | (3 << 12) | 289) + v12 := uint32((1 << 22) | (2 << 12) | 195) + + if ven, dev := ParsePCIIDs(`PCI\VEN_1002&DEV_164C&SUBSYS_380117AA`); ven != "1002" || dev != "164c" { + t.Fatalf("ParsePCIIDs = (%q, %q), want (1002, 164c)", ven, dev) + } + if got := FormatVulkanVersion(v13); got != "1.3.289" { + t.Fatalf("FormatVulkanVersion = %q, want 1.3.289", got) + } + + // 1. AMD Ryzen 5 5500U (Lucienne Vega 7, 1002:164c) -> warn (#181) + vega7 := EvaluateGPUCompat( + GPUInfo{Name: "AMD Radeon Graphics", VulkanICD: `C:\amd-vulkan64.json`, VendorID: "1002", DeviceID: "164c"}, + &VulkanDeviceProbe{Name: "AMD Radeon(TM) Graphics", VendorID: 0x1002, DeviceID: 0x164c, DeviceType: 1, APIVersion: v13, Extensions: allReqExts}, + ) + if vega7.Kind != GPUIntegrated || vega7.Compat != GPUCompatWarn || vega7.CompatCode != "amd_legacy_win_driver" { + t.Fatalf("vega7 = %+v", vega7) + } + + // 2. AMD RX 6600 XT (1002:73ff) -> warn (#173) + rx6600 := EvaluateGPUCompat( + GPUInfo{Name: "AMD Radeon RX 6600 XT", VulkanICD: `C:\amd-vulkan64.json`, VendorID: "1002", DeviceID: "73ff"}, + &VulkanDeviceProbe{Name: "AMD Radeon RX 6600 XT", VendorID: 0x1002, DeviceID: 0x73ff, DeviceType: 2, APIVersion: v13, Extensions: allReqExts}, + ) + if rx6600.Compat != GPUCompatWarn || rx6600.CompatCode != "amd_rdna2_device_lost" { + t.Fatalf("rx6600 = %+v", rx6600) + } + + // 3. AMD Radeon 780M (RDNA 3, 1002:15bf) -> supported + rdna3 := EvaluateGPUCompat( + GPUInfo{Name: "AMD Radeon 780M Graphics", VulkanICD: `C:\amd-vulkan64.json`, VendorID: "1002", DeviceID: "15bf"}, + &VulkanDeviceProbe{Name: "AMD Radeon 780M Graphics", VendorID: 0x1002, DeviceID: 0x15bf, DeviceType: 1, APIVersion: v13, Extensions: allReqExts}, + ) + if rdna3.Compat != GPUCompatSupported || rdna3.Kind != GPUIntegrated { + t.Fatalf("rdna3 = %+v", rdna3) + } + + // 4. Old Vulkan 1.2 GPU -> unsupported + oldVK := EvaluateGPUCompat( + GPUInfo{Name: "Old GPU", VulkanICD: `C:\old.json`, Kind: GPUDiscrete}, + &VulkanDeviceProbe{Name: "Old GPU", VendorID: 0x10de, DeviceID: 0x1180, DeviceType: 2, APIVersion: v12, Extensions: allReqExts}, + ) + if oldVK.Compat != GPUCompatUnsupported || oldVK.CompatCode != "vulkan_too_old" { + t.Fatalf("oldVK = %+v", oldVK) + } + + // 5. Missing required extension -> unsupported + noRob2 := EvaluateGPUCompat( + GPUInfo{Name: "Partial GPU", VulkanICD: `C:\p.json`, Kind: GPUIntegrated}, + &VulkanDeviceProbe{Name: "Partial GPU", VendorID: 0x8086, DeviceID: 0x5912, DeviceType: 1, APIVersion: v13, Extensions: map[string]bool{"VK_KHR_swapchain": true}}, + ) + if noRob2.Compat != GPUCompatUnsupported || noRob2.CompatCode != "vulkan_missing_extensions" { + t.Fatalf("noRob2 = %+v", noRob2) + } + + // 6. PickRecommendedGPU skips unsupported discrete GPU and picks supported iGPU. + rec := PickRecommendedGPU([]GPUInfo{oldVK, rdna3}) + if rec == nil || rec.DeviceID != "15bf" { + t.Fatalf("PickRecommendedGPU(oldVK, rdna3) = %+v, want 15bf", rec) + } + // 7. PickRecommendedGPU skips unsupported completely -> nil. + if recNone := PickRecommendedGPU([]GPUInfo{oldVK, noRob2}); recNone != nil { + t.Fatalf("expected nil when all GPUs unsupported, got %+v", recNone) + } + // 8. PickRecommendedGPU prefers supported discrete over warned Vega iGPU. + rtx := EvaluateGPUCompat( + GPUInfo{Name: "NVIDIA GeForce RTX 3060", VulkanICD: `C:\nv-vk64.json`, VendorID: "10de", DeviceID: "2504"}, + &VulkanDeviceProbe{Name: "NVIDIA GeForce RTX 3060", VendorID: 0x10de, DeviceID: 0x2504, DeviceType: 2, APIVersion: v13, Extensions: allReqExts}, + ) + recDual := PickRecommendedGPU([]GPUInfo{vega7, rtx}) + if recDual == nil || recDual.VendorID != "10de" { + t.Fatalf("PickRecommendedGPU(vega7, rtx) = %+v, want 10de", recDual) + } + // 9. MergeRegistryAndVulkanGPUs matches by PCI ID and appends Vulkan-only GPUs. + merged := MergeRegistryAndVulkanGPUs( + []GPUInfo{{Name: "AMD Radeon Graphics", VulkanICD: `C:\amd-vulkan64.json`, VendorID: "1002", DeviceID: "164c", DriverVersion: "31.0.21924.61"}}, + []VulkanDeviceProbe{ + {Name: "AMD Radeon(TM) Graphics", VendorID: 0x1002, DeviceID: 0x164c, DeviceType: 1, APIVersion: v13, Extensions: allReqExts}, + {Name: "NVIDIA GeForce RTX 3060", VendorID: 0x10de, DeviceID: 0x2504, DeviceType: 2, APIVersion: v13, Extensions: allReqExts}, + }, + ) + if len(merged) != 2 || merged[0].Compat != GPUCompatWarn || merged[1].Compat != GPUCompatSupported { + t.Fatalf("merged = %+v", merged) + } } func TestAffinityMaskHelpers(t *testing.T) { diff --git a/internal/host/host_windows.go b/internal/host/host_windows.go index 3e70c0e..ba3bc6d 100644 --- a/internal/host/host_windows.go +++ b/internal/host/host_windows.go @@ -6,6 +6,7 @@ import ( "encoding/binary" "fmt" "math/bits" + "os" "path/filepath" "runtime" "sort" @@ -543,7 +544,7 @@ func isUSBBusVolume(vol string) bool { func probeVulkanGPUs() []GPUInfo { const baseKey = `SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}` - var out []GPUInfo + var regGPUs []GPUInfo for i := 0; i < 32; i++ { sub := fmt.Sprintf(`%s\%04d`, baseKey, i) desc, okDesc := regReadString(hkeyLocalMachine, sub, "DriverDesc") @@ -554,13 +555,25 @@ func probeVulkanGPUs() []GPUInfo { if icd == "" { continue } - out = append(out, GPUInfo{ - Name: desc, - VulkanICD: icd, - Kind: ClassifyGPU(desc), + // Skip stale registry entries left behind by removed adapters or old drivers + // (matching upstream reims-ctl os/windows.rs vulkan_driver_files). + if _, err := os.Stat(icd); err != nil { + continue + } + matchID, _ := regReadString(hkeyLocalMachine, sub, "MatchingDeviceId") + vendorID, deviceID := ParsePCIIDs(matchID) + drvVer, _ := regReadString(hkeyLocalMachine, sub, "DriverVersion") + regGPUs = append(regGPUs, GPUInfo{ + Name: desc, + VulkanICD: icd, + Kind: ClassifyGPU(desc), + VendorID: vendorID, + DeviceID: deviceID, + DriverVersion: drvVer, }) } - return out + vkProbes := probeVulkanDevices() + return MergeRegistryAndVulkanGPUs(regGPUs, vkProbes) } func regReadString(root uintptr, subKey, valueName string) (string, bool) { diff --git a/internal/host/host_windows_test.go b/internal/host/host_windows_test.go index 913fd29..8d85fa2 100644 --- a/internal/host/host_windows_test.go +++ b/internal/host/host_windows_test.go @@ -24,6 +24,15 @@ func TestWindowsProcessAffinityAndTopology(t *testing.T) { if len(rep.CPUTopology) == 0 { t.Fatalf("expected non-empty CPUTopology on Windows") } + if len(rep.GPUs) > 0 { + for _, g := range rep.GPUs { + if g.Compat == "" { + t.Errorf("GPU %q missing Compat grade: %+v", g.Name, g) + } + t.Logf("probed GPU: name=%q kind=%s pci=%s:%s drv=%s vk=%s compat=%s (%s %s)", + g.Name, g.Kind, g.VendorID, g.DeviceID, g.DriverVersion, g.VulkanVersion, g.Compat, g.CompatCode, g.CompatDetail) + } + } for i, c := range rep.CPUTopology { if i > 0 && c.Index <= rep.CPUTopology[i-1].Index { t.Fatalf("CPUTopology not strictly sorted at %d: %+v", i, rep.CPUTopology) diff --git a/internal/host/optimizations.go b/internal/host/optimizations.go index 7c0aa2f..59026a6 100644 --- a/internal/host/optimizations.go +++ b/internal/host/optimizations.go @@ -197,7 +197,21 @@ func EvaluateOptimizations(rep Report, runtimePatches []string) []Optimization { } // 4. Discrete Vulkan GPU acceleration - if rep.RecommendedGPU != nil && rep.RecommendedGPU.Kind == GPUDiscrete { + if rep.RecommendedGPU != nil && rep.RecommendedGPU.Compat == GPUCompatUnsupported { + out = append(out, Optimization{ + ID: "discrete_gpu", + Status: "unavailable", + Supported: false, + Detail: rep.RecommendedGPU.Name, + }) + } else if rep.RecommendedGPU != nil && rep.RecommendedGPU.Compat == GPUCompatWarn { + out = append(out, Optimization{ + ID: "discrete_gpu", + Status: "experimental", + Supported: true, + Detail: rep.RecommendedGPU.Name, + }) + } else if rep.RecommendedGPU != nil && rep.RecommendedGPU.Kind == GPUDiscrete { out = append(out, Optimization{ ID: "discrete_gpu", Status: "recommended", diff --git a/internal/host/vulkan_windows.go b/internal/host/vulkan_windows.go new file mode 100644 index 0000000..f9c1cab --- /dev/null +++ b/internal/host/vulkan_windows.go @@ -0,0 +1,175 @@ +//go:build windows + +package host + +import ( + "bytes" + "encoding/binary" + "syscall" + "unsafe" +) + +const ( + vkSuccess = 0 + vkIncomplete = 5 + vkErrorIncompatibleDriver = -9 + vkStructureTypeAppInfo = 0 + vkStructureTypeInstCreate = 1 + vkAPIVersion10 = (1 << 22) + vkAPIVersion13 = (1 << 22) | (3 << 12) +) + +// vkApplicationInfo matches VkApplicationInfo on x86-64 Windows (48 bytes). +type vkApplicationInfo struct { + sType uint32 + pNext uintptr + pApplicationName uintptr + applicationVersion uint32 + pEngineName uintptr + engineVersion uint32 + apiVersion uint32 +} + +// vkInstanceCreateInfo matches VkInstanceCreateInfo on x86-64 Windows (64 bytes). +type vkInstanceCreateInfo struct { + sType uint32 + pNext uintptr + flags uint32 + pApplicationInfo *vkApplicationInfo + enabledLayerCount uint32 + ppEnabledLayerNames uintptr + enabledExtensionCount uint32 + ppEnabledExtensionNames uintptr +} + +// vkExtensionProperties matches VkExtensionProperties (260 bytes). +type vkExtensionProperties struct { + ExtensionName [256]byte + SpecVersion uint32 +} + +// probeVulkanDevices loads vulkan-1.dll and enumerates all visible Vulkan +// physical devices along with their API version, PCI IDs, device type, and +// advertised device extensions. Returns nil cleanly if the Vulkan loader is +// absent or refuses instance creation. +func probeVulkanDevices() []VulkanDeviceProbe { + dll := syscall.NewLazyDLL("vulkan-1.dll") + if err := dll.Load(); err != nil { + return nil + } + pCreateInst := dll.NewProc("vkCreateInstance") + pDestroyInst := dll.NewProc("vkDestroyInstance") + pEnumPhys := dll.NewProc("vkEnumeratePhysicalDevices") + pGetProps := dll.NewProc("vkGetPhysicalDeviceProperties") + pEnumExts := dll.NewProc("vkEnumerateDeviceExtensionProperties") + if pCreateInst.Find() != nil || pDestroyInst.Find() != nil || + pEnumPhys.Find() != nil || pGetProps.Find() != nil || pEnumExts.Find() != nil { + return nil + } + + appName := append([]byte("reims-go"), 0) + appInfo := vkApplicationInfo{ + sType: vkStructureTypeAppInfo, + pApplicationName: uintptr(unsafe.Pointer(&appName[0])), + apiVersion: vkAPIVersion13, + } + createInfo := vkInstanceCreateInfo{ + sType: vkStructureTypeInstCreate, + pApplicationInfo: &appInfo, + } + + var instance uintptr + res, _, _ := pCreateInst.Call( + uintptr(unsafe.Pointer(&createInfo)), + 0, + uintptr(unsafe.Pointer(&instance)), + ) + if int32(res) == vkErrorIncompatibleDriver { + appInfo.apiVersion = vkAPIVersion10 + res, _, _ = pCreateInst.Call( + uintptr(unsafe.Pointer(&createInfo)), + 0, + uintptr(unsafe.Pointer(&instance)), + ) + } + if int32(res) != vkSuccess || instance == 0 { + return nil + } + defer pDestroyInst.Call(instance, 0) + + var count uint32 + res, _, _ = pEnumPhys.Call(instance, uintptr(unsafe.Pointer(&count)), 0) + if (int32(res) != vkSuccess && int32(res) != vkIncomplete) || count == 0 { + return nil + } + if count > 32 { + count = 32 + } + devices := make([]uintptr, count) + res, _, _ = pEnumPhys.Call( + instance, + uintptr(unsafe.Pointer(&count)), + uintptr(unsafe.Pointer(&devices[0])), + ) + if int32(res) != vkSuccess && int32(res) != vkIncomplete { + return nil + } + + out := make([]VulkanDeviceProbe, 0, count) + for i := uint32(0); i < count; i++ { + pd := devices[i] + if pd == 0 { + continue + } + // VkPhysicalDeviceProperties is ~824 bytes; use 2048 bytes to stay + // immune to padding differences while reading fixed header offsets 0..276. + var propsBuf [2048]byte + pGetProps.Call(pd, uintptr(unsafe.Pointer(&propsBuf[0]))) + + probe := VulkanDeviceProbe{ + APIVersion: binary.LittleEndian.Uint32(propsBuf[0:4]), + VendorID: binary.LittleEndian.Uint32(propsBuf[8:12]), + DeviceID: binary.LittleEndian.Uint32(propsBuf[12:16]), + DeviceType: binary.LittleEndian.Uint32(propsBuf[16:20]), + Name: cstrFromBytes(propsBuf[20:276]), + Extensions: probeVulkanDeviceExtensions(pEnumExts, pd), + } + out = append(out, probe) + } + return out +} + +func probeVulkanDeviceExtensions(pEnumExts *syscall.LazyProc, pd uintptr) map[string]bool { + var extCount uint32 + res, _, _ := pEnumExts.Call(pd, 0, uintptr(unsafe.Pointer(&extCount)), 0) + if (int32(res) != vkSuccess && int32(res) != vkIncomplete) || extCount == 0 { + return nil + } + if extCount > 2048 { + extCount = 2048 + } + exts := make([]vkExtensionProperties, extCount) + res, _, _ = pEnumExts.Call( + pd, + 0, + uintptr(unsafe.Pointer(&extCount)), + uintptr(unsafe.Pointer(&exts[0])), + ) + if int32(res) != vkSuccess && int32(res) != vkIncomplete { + return nil + } + m := make(map[string]bool, extCount) + for i := uint32(0); i < extCount; i++ { + if name := cstrFromBytes(exts[i].ExtensionName[:]); name != "" { + m[name] = true + } + } + return m +} + +func cstrFromBytes(b []byte) string { + if idx := bytes.IndexByte(b, 0); idx >= 0 { + b = b[:idx] + } + return string(b) +} diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go index 98fd497..9dd70d6 100644 --- a/internal/i18n/i18n.go +++ b/internal/i18n/i18n.go @@ -192,7 +192,18 @@ var catalog = map[Locale]map[string]string{ "doctor.whpx.unsupported": "非 Windows 宿主(当前处于跨平台开发模式)", "doctor.gpu": "Vulkan 显卡列表", "doctor.gpu.none": "未检测到已注册的 Vulkan ICD 显卡驱动", - "doctor.gpu.recommended": "推荐独显", + "doctor.gpu.recommended": "推荐", + "doctor.gpu.compat.supported": "支持", + "doctor.gpu.compat.warn": "已知兼容性风险", + "doctor.gpu.compat.unsupported": "不支持加速", + "doctor.gpu.compat.unknown": "未完成 Vulkan 实测", + "doctor.gpu.warn.amd_legacy": "AMD Vega/Polaris 在 Windows 闭源驱动下存在上游已知黑屏/设备丢失问题(%s),建议使用其他独显或在虚拟机设置改用 VMware SVGA", + "doctor.gpu.warn.amd_rdna2": "该 AMD 显卡在 Windows 下存在上游已知设备丢失风险(%s),若黑屏/卡死请升级驱动或临时改用 VMware SVGA", + "doctor.gpu.err.vulkan_too_old": "Vulkan 版本 %s 低于 1.3 最低要求,请更新显卡驱动或改用 VMware SVGA", + "doctor.gpu.err.missing_ext": "缺少必需 Vulkan 扩展(%s),请更新显卡驱动或改用 VMware SVGA", + "doctor.gpu.err.vulkan_cpu": "软件渲染 Vulkan 实现不满足 vGPU 硬件加速要求,请改用 VMware SVGA", + "err.gpu_device_lost": "宿主显卡 Vulkan 设备丢失(ERROR_DEVICE_LOST)。请更新显卡驱动;若为 AMD Vega/Polaris 等受影响显卡,请改用其他独显或在设置中将虚拟显卡切为 VMware SVGA", + "err.gpu_vulkan_floor": "宿主显卡不满足 Reims vGPU 的 Vulkan 1.3 硬件要求。请更新显卡驱动,或在设置中将虚拟显卡切为 VMware SVGA(软件渲染)", "doctor.runtime": "便携运行时", "doctor.runtime.none": "尚未安装(运行 reims-go runtime install <压缩包> 导入)", "doctor.runtime.active": "当前激活:%s(%s)", @@ -287,7 +298,18 @@ var catalog = map[Locale]map[string]string{ "doctor.whpx.unsupported": "Non-Windows host (cross-platform dev mode)", "doctor.gpu": "Vulkan GPUs", "doctor.gpu.none": "No registered Vulkan ICD driver found", - "doctor.gpu.recommended": "Recommended discrete GPU", + "doctor.gpu.recommended": "Recommended", + "doctor.gpu.compat.supported": "Supported", + "doctor.gpu.compat.warn": "Known compatibility issue", + "doctor.gpu.compat.unsupported": "Unsupported for vGPU", + "doctor.gpu.compat.unknown": "Vulkan capabilities unverified", + "doctor.gpu.warn.amd_legacy": "AMD Vega/Polaris on Windows hits known upstream black-screen/device-loss issues (%s); prefer another discrete GPU or switch the VM to VMware SVGA", + "doctor.gpu.warn.amd_rdna2": "This AMD GPU hits known Windows device-loss issues upstream (%s); update drivers or switch temporarily to VMware SVGA if it freezes", + "doctor.gpu.err.vulkan_too_old": "Vulkan %s is below the required 1.3 floor; update your GPU driver or use VMware SVGA", + "doctor.gpu.err.missing_ext": "Missing required Vulkan extensions (%s); update your GPU driver or use VMware SVGA", + "doctor.gpu.err.vulkan_cpu": "Software Vulkan implementation does not meet the vGPU floor; use VMware SVGA instead", + "err.gpu_device_lost": "Host Vulkan GPU device lost (ERROR_DEVICE_LOST). Update GPU drivers; on affected AMD Vega/Polaris GPUs, switch to another discrete GPU or use VMware SVGA in VM Settings", + "err.gpu_vulkan_floor": "Host GPU does not meet Reims vGPU's Vulkan 1.3 requirements. Update GPU drivers or switch graphics to VMware SVGA (software rendering) in VM Settings", "doctor.runtime": "Portable Runtime", "doctor.runtime.none": "Not installed (run `reims-go runtime install `)", "doctor.runtime.active": "Active: %s (%s)",