From f96d78be14c542cfee866fc35805985108135ddf Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 07:37:44 +0800 Subject: [PATCH 01/10] fix(guesttools): propagate fallback sync deletions --- .gitattributes | 1 + frontend/src/components/VMPage.tsx | 4 +- frontend/wailsjs/go/models.ts | 2 + internal/app/stats_flow.go | 11 +- internal/guesttools/clipboard_agent_test.go | 8 +- internal/guesttools/file_sync.go | 378 ++++++++++++++++++++ internal/guesttools/file_sync.sh | 213 +++++++++++ internal/guesttools/file_sync_test.go | 101 ++++++ internal/guesttools/image.go | 73 +--- internal/guesttools/server.go | 209 +---------- 10 files changed, 723 insertions(+), 277 deletions(-) create mode 100644 internal/guesttools/file_sync.go create mode 100644 internal/guesttools/file_sync.sh create mode 100644 internal/guesttools/file_sync_test.go diff --git a/.gitattributes b/.gitattributes index 8083b67..3ab406d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,3 @@ *.patch -text *.diff -text +internal/guesttools/file_sync.sh text eol=lf diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index e8b60ea..c14b3c5 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -853,7 +853,9 @@ export const VMPage: React.FC = ({ const gtConnected = stats?.guest_tools_connected ?? detail.guest_tools_connected ?? false const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || '' const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false - const needsUpgrade = gtConnected && (detail.guest_tools_agent_version ?? 0) > 0 && (detail.guest_tools_agent_version ?? 0) < 3 + const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0 + const minimumAgentVersion = gtMountMode === 'sync' ? 7 : 3 + const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < minimumAgentVersion // Plugin switched off: show the state and hide controls that would only fail. const gtOff = !!detail.guest_tools_disabled diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 9883e88..c0d44a9 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -411,6 +411,7 @@ export namespace app { uptime_seconds: number; guest_tools_connected: boolean; guest_tools_mount_mode?: string; + guest_tools_agent_version?: number; guest_tools_sleep_guard: boolean; static createFrom(source: any = {}) { @@ -435,6 +436,7 @@ export namespace app { this.uptime_seconds = source["uptime_seconds"]; this.guest_tools_connected = source["guest_tools_connected"]; this.guest_tools_mount_mode = source["guest_tools_mount_mode"]; + this.guest_tools_agent_version = source["guest_tools_agent_version"]; this.guest_tools_sleep_guard = source["guest_tools_sleep_guard"]; } } diff --git a/internal/app/stats_flow.go b/internal/app/stats_flow.go index 66be5f5..4192d6a 100644 --- a/internal/app/stats_flow.go +++ b/internal/app/stats_flow.go @@ -27,9 +27,11 @@ type VMStats struct { DiskBackingBroken bool `json:"disk_backing_broken,omitempty"` DiskBackingDepthWarn bool `json:"disk_backing_depth_warn,omitempty"` UptimeSeconds int64 `json:"uptime_seconds"` - GuestToolsConnected bool `json:"guest_tools_connected"` - GuestToolsMountMode string `json:"guest_tools_mount_mode,omitempty"` - GuestToolsSleepGuard bool `json:"guest_tools_sleep_guard"` + + GuestToolsConnected bool `json:"guest_tools_connected"` + GuestToolsMountMode string `json:"guest_tools_mount_mode,omitempty"` + GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"` + GuestToolsSleepGuard bool `json:"guest_tools_sleep_guard"` } func resolveVMDiskPath(d reims.VMDetail) string { @@ -53,7 +55,7 @@ func resolveVMDiskPath(d reims.VMDetail) string { } // GetVMStats samples QEMU CPU/memory usage (when running), disk actual vs -// virtual capacity, and live Guest Tools 2.0 connection state. +// virtual capacity, and live Guest Tools status. func (a *App) GetVMStats(name string) (VMStats, error) { stats := VMStats{Name: name} c, err := a.client() @@ -114,6 +116,7 @@ func (a *App) GetVMStats(name string) (VMStats, error) { st := srv.Status(name, 15*time.Second) stats.GuestToolsConnected = st.Connected stats.GuestToolsMountMode = st.MountMode + stats.GuestToolsAgentVersion = st.AgentVersion stats.GuestToolsSleepGuard = st.SleepActive } return stats, nil diff --git a/internal/guesttools/clipboard_agent_test.go b/internal/guesttools/clipboard_agent_test.go index 666e80c..cf5fd8f 100644 --- a/internal/guesttools/clipboard_agent_test.go +++ b/internal/guesttools/clipboard_agent_test.go @@ -4,6 +4,7 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "strings" "testing" ) @@ -19,8 +20,11 @@ func TestGuestAgentClipboardScript(t *testing.T) { agent := string(GuestAgentScript()) start := strings.Index(agent, "read_local_clipboard() {") end := strings.Index(agent, "sync_files() {") - if start < 0 || end <= start || !strings.Contains(agent, "agent_version\\\":6") { - t.Fatal("missing generated clipboard code or agent version 6") + if start < 0 || end <= start { + t.Fatal("missing generated clipboard code") + } + if !regexp.MustCompile(`agent_version\\":([6-9]|[1-9][0-9]+)\}`).MatchString(agent) { + t.Fatal("clipboard sync requires agent version 6 or newer") } if !strings.Contains(agent[start:end], `-H "Content-Type: $ct" ${1+"$@"}`) { t.Fatal("POST must guard empty positional arguments under Bash 3.2 set -u") diff --git a/internal/guesttools/file_sync.go b/internal/guesttools/file_sync.go new file mode 100644 index 0000000..76ba4d8 --- /dev/null +++ b/internal/guesttools/file_sync.go @@ -0,0 +1,378 @@ +package guesttools + +import ( + "crypto/sha256" + "errors" + "fmt" + "io" + "io/fs" + "net/http" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "time" +) + +const ( + syncScopeHeader = "X-Reims-Sync-Scope" + syncDigestHeader = "X-Reims-File-SHA256" +) + +func syncFileScope(token, root string) string { + return fmt.Sprintf("%x", sha256.Sum256([]byte(token+"\n"+root))) +} + +func syncFileTag(info fs.FileInfo) string { + return fmt.Sprintf("\"%d-%d\"", info.ModTime().UnixNano(), info.Size()) +} + +func isIgnoredSharedName(name string) bool { + return name == "" || strings.HasPrefix(name, ".") +} + +func validSyncFileName(name string) bool { + return strings.TrimSpace(name) == name && !strings.ContainsAny(name, "\t\r\n") +} + +// sharedFilePath returns the one relative path used by both the legacy copy +// endpoints and the versioned sync operations. +func sharedFilePath(name string) (string, error) { + name = strings.TrimSpace(name) + parts := strings.FieldsFunc(name, func(r rune) bool { return r == '/' }) + if len(parts) == 0 || len(parts) > MaxSharedDepth || strings.HasPrefix(name, "/") { + return "", errors.New("invalid relative path") + } + for _, part := range parts { + if isIgnoredSharedName(part) || strings.ContainsAny(part, "\x00:\\<>|\"?*") { + return "", errors.New("invalid path segment") + } + } + rel := strings.Join(parts, "/") + if !filepath.IsLocal(filepath.FromSlash(rel)) { + return "", errors.New("invalid relative path") + } + return rel, nil +} + +func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) { + vm := s.authenticate(r) + if vm == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if r.Method != http.MethodGet { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + versioned := r.URL.Query().Get("sync") == "1" + if vm.sharedDir == "" { + if versioned { + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + } + return + } + root, err := filepath.Abs(vm.sharedDir) + if err != nil { + http.Error(w, "shared directory unavailable", http.StatusInternalServerError) + return + } + if !versioned { + if err := os.MkdirAll(root, 0o755); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + } + type entry struct { + name string + info fs.FileInfo + } + var files []entry + err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if p == root { + if versioned && err == nil && !d.IsDir() { + return fs.ErrInvalid + } + return err + } + if err != nil { + return nil + } + if isIgnoredSharedName(d.Name()) || d.Type()&os.ModeSymlink != 0 { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + rel, err := filepath.Rel(root, p) + if err != nil { + return nil + } + name := filepath.ToSlash(rel) + if strings.Count(name, "/")+1 > MaxSharedDepth { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + if d.IsDir() || (versioned && !validSyncFileName(name)) { + return nil + } + info, err := d.Info() + if err != nil || !info.Mode().IsRegular() || info.Size() > MaxUploadBytes { + return nil + } + if len(files) == MaxSharedFiles { + return fs.SkipAll + } + files = append(files, entry{name, info}) + return nil + }) + if versioned { + if err != nil { + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + return + } + w.Header().Set(syncScopeHeader, syncFileScope(vm.token, root)) + } + sort.Slice(files, func(i, j int) bool { return files[i].name < files[j].name }) + w.Header().Set("Content-Type", "text/tab-separated-values; charset=utf-8") + for _, file := range files { + _, _ = fmt.Fprintf(w, "%d\t%d\t", file.info.ModTime().Unix(), file.info.Size()) + if versioned { + _, _ = fmt.Fprintf(w, "%s\t", syncFileTag(file.info)) + } + _, _ = fmt.Fprintln(w, file.name) + } +} + +func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) { + vm := s.authenticate(r) + if vm == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + rawName := r.URL.Query().Get("path") + name, err := sharedFilePath(rawName) + if err != nil || vm.sharedDir == "" { + http.Error(w, "invalid shared file path", http.StatusBadRequest) + return + } + dir, err := filepath.Abs(vm.sharedDir) + if err != nil { + http.Error(w, "shared directory unavailable", http.StatusInternalServerError) + return + } + scope := r.Header.Get(syncScopeHeader) + if scope != "" && (!validSyncFileName(rawName) || scope != syncFileScope(vm.token, dir)) { + http.Error(w, "shared directory or file path changed", http.StatusPreconditionFailed) + return + } + switch r.Method { + case http.MethodHead, http.MethodDelete: + if scope == "" { + http.Error(w, "sync scope required", http.StatusPreconditionRequired) + return + } + fallthrough + case http.MethodGet: + s.readSharedFile(w, r, dir, name, scope != "") + case http.MethodPut, http.MethodPost: + s.writeSharedFile(w, r, filepath.Join(dir, filepath.FromSlash(name)), scope != "") + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} + +func matchSyncFile(r *http.Request, info fs.FileInfo) bool { + if tag := r.Header.Get("If-Match"); tag != "" { + return info != nil && info.Mode().IsRegular() && syncFileTag(info) == tag + } + return r.Header.Get("If-None-Match") != "*" || info == nil +} + +// A path replaced by a symlink or directory is a conflict rather than a +// missing file. Missing files are the only ones that propagate a deletion. +func statSharedFile(root *os.Root, name string) (fs.FileInfo, error) { + for i, ch := range name { + if ch != '/' { + continue + } + info, err := root.Lstat(name[:i]) + if err != nil { + return nil, err + } + if !info.IsDir() { + return nil, fs.ErrInvalid + } + } + info, err := root.Lstat(name) + if err == nil && !info.Mode().IsRegular() { + return nil, fs.ErrInvalid + } + return info, err +} + +func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, dir, name string, versioned bool) { + deleting := r.Method == http.MethodDelete + expectedDigest := r.Header.Get(syncDigestHeader) + if deleting && (r.Header.Get("If-Match") == "" || expectedDigest == "") { + http.Error(w, "file revision required", http.StatusPreconditionRequired) + return + } + + root, err := os.OpenRoot(dir) + if err != nil { + switch { + case versioned: + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + case errors.Is(err, fs.ErrNotExist): + http.NotFound(w, r) + default: + http.Error(w, "shared directory unavailable", http.StatusInternalServerError) + } + return + } + defer root.Close() + info, err := statSharedFile(root, name) + switch { + case errors.Is(err, fs.ErrNotExist): + http.NotFound(w, r) + return + case errors.Is(err, fs.ErrInvalid): + status := http.StatusBadRequest + if versioned { + status = http.StatusConflict + } + http.Error(w, "path is not a regular file", status) + return + case err != nil: + http.Error(w, "file unavailable", http.StatusInternalServerError) + return + case versioned && !matchSyncFile(r, info): + http.Error(w, "file changed", http.StatusPreconditionFailed) + return + } + + tag := syncFileTag(info) + if !deleting { + w.Header().Set("ETag", tag) + } + head := r.Method == http.MethodHead + if head && r.URL.Query().Get("sha256") != "1" { + return + } + if (head || deleting) && info.Size() > MaxUploadBytes { + http.Error(w, "file exceeds sync size limit", http.StatusRequestEntityTooLarge) + return + } + file, err := root.Open(name) + if err != nil { + http.Error(w, "file unavailable", http.StatusInternalServerError) + return + } + opened, err := file.Stat() + if err != nil || !opened.Mode().IsRegular() || syncFileTag(opened) != tag { + _ = file.Close() + http.Error(w, "file changed", http.StatusPreconditionFailed) + return + } + if r.Method == http.MethodGet { + defer file.Close() + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("X-File-Mtime", strconv.FormatInt(info.ModTime().Unix(), 10)) + w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10)) + _, _ = io.Copy(w, file) + return + } + + h := sha256.New() + n, err := io.Copy(h, io.LimitReader(file, info.Size()+1)) + _ = file.Close() + if err != nil || n != info.Size() { + http.Error(w, "file changed", http.StatusPreconditionFailed) + return + } + digest := fmt.Sprintf("%x", h.Sum(nil)) + if head { + w.Header().Set(syncDigestHeader, digest) + return + } + s.fileMu.Lock() + defer s.fileMu.Unlock() + current, err := statSharedFile(root, name) + if digest != expectedDigest || err != nil || !os.SameFile(opened, current) || !matchSyncFile(r, current) { + http.Error(w, "file changed", http.StatusPreconditionFailed) + return + } + if r.Context().Err() == nil { + if err := root.Remove(name); err != nil { + http.Error(w, "file deletion failed", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusNoContent) + } +} + +func (s *Server) writeSharedFile(w http.ResponseWriter, r *http.Request, full string, versioned bool) { + dir := filepath.Dir(full) + if err := os.MkdirAll(dir, 0o755); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + tmp, err := os.CreateTemp(dir, ".reims-upload-*") + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + defer os.Remove(tmp.Name()) + h := sha256.New() + var dst io.Writer = tmp + if versioned { + dst = io.MultiWriter(tmp, h) + } + n, copyErr := io.Copy(dst, io.LimitReader(r.Body, MaxUploadBytes+1)) + closeErr := tmp.Close() + switch { + case n > MaxUploadBytes: + http.Error(w, "file exceeds 256 MiB limit", http.StatusRequestEntityTooLarge) + return + case copyErr != nil || closeErr != nil: + http.Error(w, "write failed", http.StatusInternalServerError) + return + } + if ts, err := strconv.ParseInt(r.URL.Query().Get("mtime"), 10, 64); err == nil && ts > 0 { + t := time.Unix(ts, 0) + _ = os.Chtimes(tmp.Name(), t, t) + } + s.fileMu.Lock() + defer s.fileMu.Unlock() + var uploadedTag string + if versioned { + info, err := os.Lstat(full) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + http.Error(w, "file unavailable", http.StatusInternalServerError) + return + } + if !matchSyncFile(r, info) { + http.Error(w, "file changed", http.StatusPreconditionFailed) + return + } + uploaded, err := os.Stat(tmp.Name()) + if err != nil { + http.Error(w, "uploaded file unavailable", http.StatusInternalServerError) + return + } + uploadedTag = syncFileTag(uploaded) + } + if err := os.Rename(tmp.Name(), full); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + if versioned { + w.Header().Set("ETag", uploadedTag) + w.Header().Set(syncDigestHeader, fmt.Sprintf("%x", h.Sum(nil))) + } + w.WriteHeader(http.StatusOK) +} diff --git a/internal/guesttools/file_sync.sh b/internal/guesttools/file_sync.sh new file mode 100644 index 0000000..f6ecf65 --- /dev/null +++ b/internal/guesttools/file_sync.sh @@ -0,0 +1,213 @@ +# Keep confirmed pairs outside the share, scoped to the VM and host directory. +sync_files() { + [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 + [ -d "$SHARE_SYNC" ] && [ ! -L "$SHARE_SYNC" ] || return 0 + + sync_remote="$TMP_DIR/sync-remote.tsv" + sync_local="$TMP_DIR/sync-local.tsv" + sync_headers="$TMP_DIR/sync-headers" + sync_plan="$TMP_DIR/sync-plan.tsv" + sync_delta="$TMP_DIR/sync-delta.tsv" + sync_state=/dev/null + if ! sync_request -fsS -m 5 -D "$sync_headers" -o "$sync_remote" "$REIMS_HOST_URL/v1/files?sync=1" 2>/dev/null; then + return 0 + fi + sync_scope=$(sync_header X-Reims-Sync-Scope) + case "$sync_scope" in + "") ;; + *[!0-9a-f]*) return 0 ;; + *) sync_state="$APP_DIR/file-sync-$sync_scope.tsv" ;; + esac + sync_previous="$sync_state" + [ -f "$sync_state" ] || sync_previous=/dev/null + + if ! find "$SHARE_SYNC"/. -name '.*' ! -name . -prune -o -type f -exec /bin/sh -c ' + root=$1 + tab=$2 + shift 2 + newline=$(printf "\nx") + newline=${newline%x} + cr=$(printf "\r") + for file do + rel=${file#"$root"/./} + case "$rel" in *"$tab"*|*"$newline"*|*"$cr"*) continue ;; esac + row=$(stat -f "%m${tab}%z${tab}%Fm:%Fc:%i:%z" "$file") || exit 1 + printf "%s\t%s\n" "$row" "$rel" + done + ' sh "$SHARE_SYNC" "$TAB" {} + > "$sync_local" 2>/dev/null; then + return 0 + fi + + # A missing path is a deletion only after a confirmed pair has existed. + # If the remaining copy changed, preserve it using the usual copy rules. + awk -F '\t' -v extended="$sync_scope" ' + BEGIN { OFS = FS } + FILENAME == ARGV[1] { + previousLocal[$4] = $1; previousRemote[$4] = $2; state[$4] = $3; paths[$4] = 1 + } + FILENAME == ARGV[2] { + p = extended == "" ? $3 : $4 + if (p != "") { + remoteTime[p] = $1; remoteSize[p] = $2; remote[p] = extended == "" ? "-" : $3; paths[p] = 1 + } + } + FILENAME == ARGV[3] && $4 != "" { + localTime[$4] = $1; localSize[$4] = $2; local[$4] = $3; paths[$4] = 1 + } + END { + for (p in paths) { + l = p in local; r = p in remote + paired = state[p] != "" && state[p] != "different" + op = "" + if (l && r) { + if (remoteTime[p] + 0 > localTime[p] + 2) op = "download" + else if (localTime[p] + 0 > remoteTime[p] + 2 && localSize[p] <= 268435456) op = "upload" + else if (extended != "" && localTime[p] == remoteTime[p] && localSize[p] == remoteSize[p] && + (local[p] != previousLocal[p] || remote[p] != previousRemote[p])) op = "verify" + } else if (r) { + op = paired && remote[p] == previousRemote[p] ? "delete-host" : "download" + } else if (l) { + if (paired && local[p] == previousLocal[p]) op = "delete-guest" + else if (localSize[p] <= 268435456) op = "upload" + } else { + op = "forget" + } + if (op != "") { + localRevision = l ? local[p] : "-" + remoteRevision = r ? remote[p] : "-" + localMtime = l ? localTime[p] : "-" + digest = state[p] != "" ? state[p] : "-" + print op, localRevision, remoteRevision, localMtime, digest, p + } + } + } + ' "$sync_previous" "$sync_remote" "$sync_local" > "$sync_plan" || return 0 + + : > "$sync_delta" || return 0 + sync_verify_left=8 + while IFS="$TAB" read -r sync_op sync_guest_rev sync_host_rev sync_guest_time sync_digest sync_rel; do + sync_apply_file + done < "$sync_plan" + if [ "$sync_state" != /dev/null ]; then + awk -F '\t' ' + $1 == "-" { delete rows[$4]; next } + { rows[$4] = $0 } + END { for (p in rows) print rows[p] } + ' "$sync_previous" "$sync_delta" > "$TMP_DIR/sync-state.next" && + mv -f "$TMP_DIR/sync-state.next" "$sync_state" + fi +} + +sync_request() { + curl -H "Authorization: Bearer $REIMS_TOKEN" "$@" +} + +sync_header() { + awk -v name="$1:" 'tolower($1) == tolower(name) { sub(/\r$/, "", $2); print $2; exit }' "$sync_headers" +} + +sync_guest_revision() { + sync_check=$1 + while [ "$sync_check" != "$SHARE_SYNC" ]; do + [ ! -L "$sync_check" ] || return 1 + sync_check=${sync_check%/*} + done + if [ -f "$1" ]; then + stat -f '%Fm:%Fc:%i:%z' "$1" 2>/dev/null + elif [ ! -e "$1" ]; then + printf '%s\n' '-' + fi +} + +sync_record() { + [ -n "$1" ] && [ -n "$2" ] && [ -n "$3" ] || return 0 + printf '%s\t%s\t%s\t%s\n' "$1" "$2" "$3" "$sync_rel" >> "$sync_delta" +} + +sync_apply_file() { + case "/$sync_rel/" in //*|*/../*|*/./*|*//*) return ;; esac + sync_target="$SHARE_SYNC/$sync_rel" + [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] || return 0 + + sync_url="$REIMS_HOST_URL/v1/file?path=$(urlencode "$sync_rel")" + if [ -n "$sync_scope" ]; then + set -- -H "X-Reims-Sync-Scope: $sync_scope" + if [ "$sync_host_rev" != - ]; then + set -- "$@" -H "If-Match: $sync_host_rev" + fi + else + set -- + fi + + case "$sync_op" in + delete-host) + sync_status=$(sync_request -sS -m 60 "$@" -H "X-Reims-File-SHA256: $sync_digest" -X DELETE \ + -o /dev/null -w '%{http_code}' "$sync_url" 2>/dev/null) || return 0 + case "$sync_status" in + 204) sync_record - - -; return ;; + 412) sync_op=download ;; + *) return 0 ;; + esac + ;; + delete-guest|forget) + # A partial host listing cannot confirm that a file was deleted. + sync_status=$(sync_request -sS -m 10 "$@" -I -o /dev/null -w '%{http_code}' "$sync_url" 2>/dev/null) || return 0 + [ "$sync_status" = 404 ] || return 0 + if [ "$sync_op" = "forget" ]; then + sync_record - - - + return + fi + sync_actual=$(hash_file "$sync_target") + [ -n "$sync_actual" ] && [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] || return 0 + if [ "$sync_actual" = "$sync_digest" ]; then + rm "$sync_target" && sync_record - - - + return + fi + sync_op=upload + ;; + esac + + case "$sync_op" in + download) + sync_part="$TMP_DIR/sync-download.part" + if sync_request -fsS -m 60 "$@" -D "$sync_headers" -o "$sync_part" "$sync_url" 2>/dev/null; then + sync_download_digest="" + if [ -n "$sync_scope" ]; then + sync_download_digest=$(hash_file "$sync_part") + fi + if sync_stamp=$(TZ=UTC date -r "$(sync_header X-File-Mtime)" '+%Y%m%d%H%M.%S' 2>/dev/null); then + TZ=UTC touch -t "$sync_stamp" "$sync_part" 2>/dev/null || true + fi + if [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] && + mkdir -p "$(dirname "$sync_target")" && mv -f "$sync_part" "$sync_target"; then + sync_record "$(sync_guest_revision "$sync_target")" "$(sync_header ETag)" "$sync_download_digest" + fi + fi + rm -f "$sync_part" + ;; + upload) + if [ -n "$sync_scope" ] && [ "$sync_host_rev" = - ]; then + set -- "$@" -H 'If-None-Match: *' + fi + if sync_request -fsS -m 60 "$@" -X PUT --data-binary "@$sync_target" -D "$sync_headers" -o /dev/null \ + "$sync_url&mtime=$sync_guest_time" 2>/dev/null && + [ -n "$sync_scope" ] && [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ]; then + sync_record "$sync_guest_rev" "$(sync_header ETag)" "$(sync_header X-Reims-File-SHA256)" + fi + ;; + verify) + # Bound initial migration work when adopting pre-existing copies. + [ "$sync_verify_left" -gt 0 ] || return 0 + sync_verify_left=$((sync_verify_left - 1)) + if sync_request -fsS -m 15 "$@" -I -D "$sync_headers" -o /dev/null "$sync_url&sha256=1" 2>/dev/null; then + sync_host_hash=$(sync_header X-Reims-File-SHA256) + sync_guest_hash=$(hash_file "$sync_target") + if [ -n "$sync_host_hash" ] && [ -n "$sync_guest_hash" ] && + [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ]; then + [ "$sync_host_hash" = "$sync_guest_hash" ] || sync_host_hash=different + sync_record "$sync_guest_rev" "$sync_host_rev" "$sync_host_hash" + fi + fi + ;; + esac +} diff --git a/internal/guesttools/file_sync_test.go b/internal/guesttools/file_sync_test.go new file mode 100644 index 0000000..99b79e1 --- /dev/null +++ b/internal/guesttools/file_sync_test.go @@ -0,0 +1,101 @@ +package guesttools + +import ( + "context" + "crypto/sha256" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestFileSyncRequiresConfirmedRevisionAndContent(t *testing.T) { + root := t.TempDir() + shared := filepath.Join(root, "share") + srv := NewTransportServer(&memClipboard{}) + port, err := srv.Start(-1) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = srv.Close(context.Background()) }) + cfg, err := LoadOrCreateVMConfig(root, "sync-test", shared, port) + if err != nil { + t.Fatal(err) + } + srv.RegisterVM(cfg) + + request := func(method, path, body string, headers http.Header, want int) (http.Header, string) { + t.Helper() + req, err := http.NewRequest(method, fmt.Sprintf("http://127.0.0.1:%d%s", port, path), strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + if headers != nil { + req.Header = headers.Clone() + } + req.Header.Set("Authorization", "Bearer "+cfg.Token) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + b, err := io.ReadAll(resp.Body) + if err != nil || resp.StatusCode != want { + t.Fatalf("%s %s: status=%d, want=%d, body=%q, read error=%v", method, path, resp.StatusCode, want, b, err) + } + return resp.Header, string(b) + } + + const fileURL = "/v1/file?path=entry.txt" + const contents = "original" + digest := fmt.Sprintf("%x", sha256.Sum256([]byte(contents))) + list, _ := request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK) + scope := list.Get(syncScopeHeader) + if scope == "" { + t.Fatal("missing sync scope") + } + conditions := make(http.Header) + conditions.Set(syncScopeHeader, scope) + conditions.Set("If-None-Match", "*") + created, _ := request(http.MethodPut, fileURL+"&mtime=1700000000", contents, conditions, http.StatusOK) + tag := created.Get("ETag") + if tag == "" || created.Get(syncDigestHeader) != digest { + t.Fatalf("upload revision or digest missing: %v", created) + } + _, legacyList := request(http.MethodGet, "/v1/files", "", nil, http.StatusOK) + _, versionedList := request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK) + if legacyList != "1700000000\t8\tentry.txt\n" || + versionedList != "1700000000\t8\t"+tag+"\tentry.txt\n" { + t.Fatalf("unexpected file listings: legacy=%q, versioned=%q", legacyList, versionedList) + } + + request(http.MethodPut, fileURL, "overwritten", conditions, http.StatusPreconditionFailed) + conditions.Del("If-None-Match") + conditions.Set("If-Match", tag) + probed, _ := request(http.MethodHead, fileURL+"&sha256=1", "", conditions, http.StatusOK) + if probed.Get(syncDigestHeader) != digest { + t.Fatalf("unexpected digest: %v", probed) + } + request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionRequired) + conditions.Set(syncDigestHeader, digest) + conditions.Set("If-Match", "\"stale-revision\"") + request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionFailed) + conditions.Set("If-Match", tag) + request(http.MethodPut, fileURL+"&mtime=1700000000", "modified", nil, http.StatusOK) + request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionFailed) + _, got := request(http.MethodGet, fileURL, "", nil, http.StatusOK) + if got != "modified" { + t.Fatalf("modified copy was lost: %q", got) + } + conditions.Set(syncDigestHeader, fmt.Sprintf("%x", sha256.Sum256([]byte(got)))) + request(http.MethodDelete, fileURL, "", conditions, http.StatusNoContent) + request(http.MethodHead, fileURL, "", conditions, http.StatusNotFound) + if err := os.Remove(shared); err != nil { + t.Fatal(err) + } + request(http.MethodGet, "/v1/files?sync=1", "", conditions, http.StatusServiceUnavailable) + request(http.MethodHead, fileURL, "", conditions, http.StatusServiceUnavailable) +} diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 2cc945d..0a16051 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -2,6 +2,7 @@ package guesttools import ( "bytes" + _ "embed" "fmt" "io" "os" @@ -15,8 +16,11 @@ const ( InstallCommand = "sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command" ) +//go:embed file_sync.sh +var guestFileSync string + // BuildToolsDiskImage creates a small read-only HFS+ disk image ("REIMSTOOLS") -// containing the per-VM Bearer token config, Guest Tools 4 POSIX agent script +// containing the per-VM Bearer token config, Guest Tools POSIX agent script // (text + PNG image clipboard with long-poll, WebDAV live mount with fallback // sync, and caffeinate prevent-sleep daemon), plus install/uninstall/pmset scripts. func BuildToolsDiskImage(outPath string, cfg VMConfig) error { @@ -65,7 +69,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error { return installer.BuildHFSPlusDiskImage(outPath, ToolsVolumeName, files) } -// GuestAgentScript returns the Guest Tools 4 stock-macOS POSIX shell daemon +// GuestAgentScript returns the Guest Tools stock-macOS POSIX shell daemon // (no Xcode or Python required): // - Two-way UTF-8 text + PNG screenshot clipboard with server long-polling // - Zero-duplication WebDAV shared folder mount (~/Desktop/ReimsShare) with automatic sync fallback @@ -73,7 +77,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error { // - Live host-controlled prevent-sleep guard via `caffeinate -dims` (no sudo required) func GuestAgentScript() []byte { return []byte(`#!/bin/sh -# Reims Guest Tools 4: clipboard, WebDAV share, read-only Windows drives, prevent-sleep. +# Reims Guest Tools: clipboard, WebDAV share, read-only Windows drives, prevent-sleep. set -u # Force UTF-8 for macOS pbpaste/pbcopy under launchd (otherwise Simplified @@ -309,7 +313,7 @@ report_status() { curl -fsS -m 3 -X POST \ -H "Authorization: Bearer $REIMS_TOKEN" \ -H "Content-Type: application/json" \ - -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":6}" \ + -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":7}" \ "$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true } @@ -484,62 +488,7 @@ sync_clipboard() { esac } -sync_files() { - [ "$mount_mode" = "webdav" ] && return 0 - [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 - remote_list="$TMP_DIR/remote_files.tsv" - if ! curl -fsS -m 5 \ - -H "Authorization: Bearer $REIMS_TOKEN" \ - "$REIMS_HOST_URL/v1/files" -o "$remote_list" 2>/dev/null; then - return 0 - fi - - # 1. Host -> Guest (download new or strictly newer files) - while IFS="$TAB" read -r rmtime rsize rrel; do - [ -n "$rrel" ] || continue - local_path="$SHARE_SYNC/$rrel" - need_dl=0 - if [ ! -f "$local_path" ]; then - need_dl=1 - else - lmtime=$(stat -f '%m' "$local_path" 2>/dev/null || echo 0) - if [ "$rmtime" -gt $((lmtime + 2)) ]; then - need_dl=1 - fi - fi - if [ "$need_dl" -eq 1 ]; then - mkdir -p "$(dirname "$local_path")" - enc=$(urlencode "$rrel") - dl_tmp="$TMP_DIR/dl.part" - if curl -fsS -m 60 \ - -H "Authorization: Bearer $REIMS_TOKEN" \ - "$REIMS_HOST_URL/v1/file?path=$enc" -o "$dl_tmp" 2>/dev/null; then - mv -f "$dl_tmp" "$local_path" - touch -d "@$rmtime" "$local_path" 2>/dev/null || true - else - rm -f "$dl_tmp" - fi - fi - done <"$remote_list" - - # 2. Guest -> Host (upload new or strictly newer files) - find "$SHARE_SYNC" -type f ! -name '.*' ! -path '*/.*' 2>/dev/null | while IFS= read -r fpath; do - rel=${fpath#"$SHARE_SYNC/"} - [ -n "$rel" ] || continue - lmtime=$(stat -f '%m' "$fpath" 2>/dev/null || echo 0) - lsize=$(stat -f '%z' "$fpath" 2>/dev/null || echo 0) - [ "$lsize" -le 268435456 ] || continue - rmtime=$(awk -F '\t' -v p="$rel" '$3==p {print $1; exit}' "$remote_list") - [ -n "$rmtime" ] || rmtime=0 - if [ "$lmtime" -gt $((rmtime + 2)) ]; then - enc=$(urlencode "$rel") - curl -fsS -m 60 -X PUT \ - -H "Authorization: Bearer $REIMS_TOKEN" \ - --data-binary "@$fpath" \ - "$REIMS_HOST_URL/v1/file?path=$enc&mtime=$lmtime" >/dev/null 2>&1 || true - fi - done -} +` + guestFileSync + ` text_input_loop() { hdr="$TMP_DIR/txt_hdr" @@ -668,12 +617,12 @@ launchctl bootstrap "gui/$uid" "$PLIST" 2>/dev/null || launchctl load -w "$PLIST # Verify host bridge connectivity immediately. . "$APP_DIR/config" if curl -fsS -m 5 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/ping" >/dev/null 2>&1; then - echo "Reims Guest Tools 4 installed and connected!" + echo "Reims Guest Tools installed and connected!" echo "Clipboard: UTF-8 text + PNG screenshots (two-way)" echo "Shared folder: ~/Desktop/ReimsShare (WebDAV live mount, auto-fallback to sync)" echo "Prevent-sleep: controlled live from Reims-Go host UI" else - echo "Reims Guest Tools 4 installed (waiting for Windows host bridge at $REIMS_HOST_URL)..." + echo "Reims Guest Tools installed (waiting for Windows host bridge at $REIMS_HOST_URL)..." fi `) } diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 0d62b2f..bb5aacb 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -11,13 +11,10 @@ import ( "errors" "fmt" "io" - "io/fs" "net" "net/http" "os" - "path" "path/filepath" - "sort" "strconv" "strings" "sync" @@ -199,6 +196,7 @@ type registeredVM struct { // (reachable from QEMU SLIRP guests as http://10.0.2.2:). type Server struct { mu sync.RWMutex + fileMu sync.Mutex clipWriteMu sync.Mutex clip Clipboard vms map[string]*registeredVM // keyed by VM name @@ -1163,208 +1161,3 @@ func (s *Server) handleHostText(w http.ResponseWriter, r *http.Request) { } w.WriteHeader(http.StatusAccepted) } - -func isIgnoredSharedName(name string) bool { - return name == "" || strings.HasPrefix(name, ".") || strings.HasPrefix(name, "._") -} - -// resolveSharedPath validates a relative slash path and ensures the resulting -// path stays strictly inside rootDir (no .., absolute paths, drive letters, or -// symlink escapes). -func resolveSharedPath(rootDir, rel string) (string, error) { - if rootDir == "" { - return "", errors.New("shared directory not configured") - } - if strings.ContainsRune(rel, 0) || strings.Contains(rel, `\`) { - return "", errors.New("invalid path") - } - trimmed := strings.TrimSpace(rel) - if trimmed == "" || strings.HasPrefix(trimmed, "/") { - return "", errors.New("invalid relative path") - } - for _, rawSeg := range strings.Split(trimmed, "/") { - if rawSeg == ".." || rawSeg == "." { - return "", errors.New("path traversal not allowed") - } - } - clean := path.Clean("/" + trimmed) - clean = strings.TrimPrefix(clean, "/") - if clean == "" || clean == "." || strings.HasPrefix(clean, "..") { - return "", errors.New("invalid relative path") - } - parts := strings.Split(clean, "/") - if len(parts) > MaxSharedDepth { - return "", errors.New("path too deep") - } - for _, seg := range parts { - if seg == "" || seg == "." || seg == ".." || strings.ContainsAny(seg, `:\<>|"?*`) || isIgnoredSharedName(seg) { - return "", errors.New("invalid path segment") - } - } - rootAbs, err := filepath.Abs(rootDir) - if err != nil { - return "", err - } - full := filepath.Join(append([]string{rootAbs}, parts...)...) - relBack, err := filepath.Rel(rootAbs, full) - if err != nil || relBack == "." || strings.HasPrefix(relBack, "..") || filepath.IsAbs(relBack) { - return "", errors.New("path escapes shared root") - } - return full, nil -} - -func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) { - vm := s.authenticate(r) - if vm == nil { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - if r.Method != http.MethodGet { - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) - return - } - if vm.sharedDir == "" { - w.WriteHeader(http.StatusOK) - return - } - if err := os.MkdirAll(vm.sharedDir, 0o755); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - rootAbs, err := filepath.Abs(vm.sharedDir) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - type entry struct { - mtime int64 - size int64 - rel string - } - var list []entry - _ = filepath.WalkDir(rootAbs, func(p string, d fs.DirEntry, err error) error { - if err != nil { - return nil - } - if p == rootAbs { - return nil - } - name := d.Name() - if isIgnoredSharedName(name) { - if d.IsDir() { - return filepath.SkipDir - } - return nil - } - if d.Type()&os.ModeSymlink != 0 { - if d.IsDir() { - return filepath.SkipDir - } - return nil - } - rel, err := filepath.Rel(rootAbs, p) - if err != nil { - return nil - } - slash := filepath.ToSlash(rel) - if strings.Count(slash, "/")+1 > MaxSharedDepth { - if d.IsDir() { - return filepath.SkipDir - } - return nil - } - if d.IsDir() { - return nil - } - info, err := d.Info() - if err != nil || !info.Mode().IsRegular() || info.Size() > MaxUploadBytes { - return nil - } - if len(list) >= MaxSharedFiles { - return fs.SkipAll - } - list = append(list, entry{mtime: info.ModTime().Unix(), size: info.Size(), rel: slash}) - return nil - }) - sort.Slice(list, func(i, j int) bool { return list[i].rel < list[j].rel }) - w.Header().Set("Content-Type", "text/tab-separated-values; charset=utf-8") - for _, e := range list { - _, _ = fmt.Fprintf(w, "%d\t%d\t%s\n", e.mtime, e.size, e.rel) - } -} - -func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) { - vm := s.authenticate(r) - if vm == nil { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - rel := r.URL.Query().Get("path") - full, err := resolveSharedPath(vm.sharedDir, rel) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - switch r.Method { - case http.MethodGet: - info, err := os.Lstat(full) - if err != nil { - if os.IsNotExist(err) { - http.NotFound(w, r) - return - } - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - if !info.Mode().IsRegular() { - http.Error(w, "not a regular file", http.StatusBadRequest) - return - } - f, err := os.Open(full) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - defer f.Close() - w.Header().Set("X-File-Mtime", strconv.FormatInt(info.ModTime().Unix(), 10)) - w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10)) - w.Header().Set("Content-Type", "application/octet-stream") - _, _ = io.Copy(w, f) - case http.MethodPut, http.MethodPost: - if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - tmp, err := os.CreateTemp(filepath.Dir(full), ".reims-upload-*") - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - tmpName := tmp.Name() - n, copyErr := io.Copy(tmp, io.LimitReader(r.Body, MaxUploadBytes+1)) - closeErr := tmp.Close() - if copyErr != nil || closeErr != nil || n > MaxUploadBytes { - _ = os.Remove(tmpName) - if n > MaxUploadBytes { - http.Error(w, "file exceeds 256 MiB limit", http.StatusRequestEntityTooLarge) - return - } - http.Error(w, "write failed", http.StatusInternalServerError) - return - } - if mtimeStr := r.URL.Query().Get("mtime"); mtimeStr != "" { - if ts, perr := strconv.ParseInt(mtimeStr, 10, 64); perr == nil && ts > 0 { - t := time.Unix(ts, 0) - _ = os.Chtimes(tmpName, t, t) - } - } - if err := os.Rename(tmpName, full); err != nil { - _ = os.Remove(tmpName) - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - w.WriteHeader(http.StatusOK) - default: - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) - } -} From 585669e0b3eb34ce103e8a733b32e63b1e0e99c6 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 07:44:35 +0800 Subject: [PATCH 02/10] feat(patches): add Intel WHPX suspend and Win32 mapped-ram I/O patches --- patches/README.md | 18 + patches/qemu-intel-whpx-suspend.patch | 906 +++++++++++++++++++++++++ patches/qemu-win32-mapped-ram-io.patch | 727 ++++++++++++++++++++ patches/series.txt | 2 + 4 files changed, 1653 insertions(+) create mode 100644 patches/qemu-intel-whpx-suspend.patch create mode 100644 patches/qemu-win32-mapped-ram-io.patch diff --git a/patches/README.md b/patches/README.md index 695e20d..93189c4 100644 --- a/patches/README.md +++ b/patches/README.md @@ -30,6 +30,8 @@ | [`qemu-whpx-win10-startup-ipis.patch`](qemu-whpx-win10-startup-ipis.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 在 Win10 开启 `kernel-irqchip` 且多核启动时经 `WHvRequestInterrupt` 转发 INIT/SIPI,避免 XNU 从核卡死(依赖上一项) | 8/12 核冷启动通过;客体软重启待验证,待提 PR | | [`qemu-whpx-nested-virt-nonfatal.patch`](qemu-whpx-nested-virt-nonfatal.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 部分 Win11 宿主设置嵌套虚拟化属性返回 `0x80370302` 时改为警告并清零特性位,保留 `kernel-irqchip=on` 加速(依赖前两项) | 待编入 `alpha` 并在 Win11 真机验证后提 PR | | [`qemu-win32-coroutine-fiber-commit.patch`](qemu-win32-coroutine-fiber-commit.patch) | `vendor/qemu` (`util/coroutine-windows.c`) | 改用 `CreateFiberEx(64 KiB, 1 MiB, ...)` 将协程初始提交降至 1/16,并判空与检查 `IsThreadAFiber()`,避免高并发 I/O 时 `SwitchToFiber(NULL)` 崩溃 | `git apply --check` 通过;待编入 `alpha` 真机验证后提 PR | +| [`qemu-win32-mapped-ram-io.patch`](qemu-win32-mapped-ram-io.patch) | `vendor/qemu` (`io/channel*.c`, `migration/*.c`) | 为 Win32 `QIOChannelFile` 实现 `preadv`/`pwritev`(合并读写路径、零写保护与文件指针恢复),并解除 `mapped-ram` + `multifd` 文件快照在 Windows 下的 POSIX 限制 | Win11 WHPX 真机跨进程及真实宿主重启恢复实测通过;待提 PR | +| [`qemu-intel-whpx-suspend.patch`](qemu-intel-whpx-suspend.patch) | `vendor/qemu` (`accel/whpx/`, `target/i386/whpx/`, `hw/misc/applesmc.c`, `hw/display/reims-graphics-pci.c`, `migration/`) | 为 Intel x86-64 WHPX 实现停机文件挂起(限制在已暂停 VM 的 `MIG_MODE_NORMAL` + `file:` 迁移入口,保留非 `normal`/在线迁移与 `savevm` 拦截)、完整 LAPIC/x2APIC/TSC/AppleSMC 与 `reims-graphics-pci` VMState 保存恢复 | 7 项 QMP 闸门回归 + Win11 WHPX 真机解锁桌面同 PID Metal 读回及真实宿主重启通过;待提 PR | --- @@ -103,6 +105,22 @@ - **最小修复**:仅当磁盘为 `qcow2` 且本地可读有效头时,读取虚拟容量与 `cluster_bits` 计算 `virtual_size / cluster_size * 8` 向上取整至 MiB(上限 32 MiB),大于 8 MiB 时追加 `,l2-cache-size={mib}M`;不存在文件时静默忽略,不影响现有单元测试。 - **实测证据**(128 GiB 镜像 16 MiB L2 缓存):`rand-read-large`(热缓存)QEMU 块层平均读延迟从 128.5 μs 降至 70.6 μs(-45.1%),端到端耗时从 1,623.6 ms 降至 1,498.7 ms(-7.7%),仅增加 8 MiB 内存占用且无稳定性风险。 +### 9. `qemu-win32-mapped-ram-io.patch` +- **建议 PR 标题**:`io/channel-file & migration: support Win32 positioned vector I/O for mapped-ram file snapshots` +- **目标**:`steelbrain/qemu-reims-vgpu`(`io/channel-file.c`, `io/channel*.c`, `migration/file.c`, `migration/ram.c`, `migration/qemu-file.c`, `migration/channel-block.c`) +- **影响环境**:Windows 宿主使用 `mapped-ram` + `multifd` 执行停机文件挂起与恢复的场景。 +- **根因**:上游 `QIOChannelFile` 的 `preadv`/`pwritev` 仅在非 Win32 路径实现,`mapped-ram` 与 `multifd` 文件通道在 Windows 上直接受限。 +- **最小修复**:合并 Win32 定位读写公共逻辑(统一偏移校验、溢出安全分块、EOF/短写语义区分、零字节写入返回 `EIO` 防止死循环以及恢复原文件指针),并开放 Win32 `mapped-ram` + `multifd` 文件路径。 + +### 10. `qemu-intel-whpx-suspend.patch` +- **建议 PR 标题**:`whpx & reims-graphics-pci: support paused-VM file suspend and resume on Intel x86-64` +- **目标**:`steelbrain/qemu-reims-vgpu`(`accel/whpx/whpx-common.c`, `include/system/whpx-common.h`, `target/i386/whpx/whpx-all.c`, `target/i386/whpx/whpx-apic.c`, `hw/misc/applesmc.c`, `hw/display/reims-graphics-pci.c`, `migration/migration.c`, `migration/savevm.c`) +- **影响环境**:Intel x86-64 macOS 客体在 Windows WHPX 上的停机挂起至磁盘与跨进程/跨宿主重启恢复。 +- **最小修复**: + 1. 保留非 `MIG_MODE_NORMAL` 模式的 WHPX migration blocker,并在 `qmp_migrate()`、WHPX `MIG_EVENT_SETUP` 回调与 `save_snapshot()` 强制检查:仅放行已暂停 VM 的 `MIG_MODE_NORMAL` + `file:` 路径,拒绝运行中迁移、非 `file:` 传输、postcopy、background-snapshot、COLO 及 `savevm`。 + 2. 补齐 WHPX x86-64 vCPU/LAPIC/x2APIC/TSC 寄存器与 AppleSMC、`reims-graphics-pci` 设备 VMState 保存恢复回调(含损坏快照向 QMP 返回错误并保留挂起文件)。 +- **实测证据**:7 项 QMP 闸门回归全部通过;Windows 11 WHPX + RTX A5000 + Intel macOS 26.7.3 解锁桌面实测跨完整 QEMU 退出及真实 Windows 重启恢复,首帧 1920×1080 SHA-256 完全一致,原应用 PID / Metal 队列 / Private 资源读回 100% 匹配。 + --- ## 关注中的上游 PR 与演进 diff --git a/patches/qemu-intel-whpx-suspend.patch b/patches/qemu-intel-whpx-suspend.patch new file mode 100644 index 0000000..8bfda58 --- /dev/null +++ b/patches/qemu-intel-whpx-suspend.patch @@ -0,0 +1,906 @@ +diff --git a/accel/whpx/whpx-common.c b/accel/whpx/whpx-common.c +index 63e941496d055f1075e8e860b3785a179bb42edf..13bf3e890a93000e32fd0036fc1fde7a75c46eb4 100644 +--- a/accel/whpx/whpx-common.c ++++ b/accel/whpx/whpx-common.c +@@ -50,8 +50,14 @@ struct WHPDispatch whp_dispatch; + void whpx_flush_cpu_state(CPUState *cpu) + { + if (cpu->vcpu_dirty) { +- whpx_set_registers(cpu, WHPX_LEVEL_RUNTIME_STATE); ++ WHPXStateLevel level = (cpu->accel && cpu->accel->loadvm_pending) ++ ? WHPX_LEVEL_FULL_STATE ++ : WHPX_LEVEL_RUNTIME_STATE; ++ whpx_set_registers(cpu, level); + cpu->vcpu_dirty = false; ++ if (cpu->accel) { ++ cpu->accel->loadvm_pending = false; ++ } + } + } + +@@ -207,6 +213,19 @@ static void do_whpx_cpu_synchronize_pre_loadvm(CPUState *cpu, + run_on_cpu_data arg) + { + cpu->vcpu_dirty = true; ++ if (cpu->accel) { ++ cpu->accel->loadvm_pending = true; ++ } ++} ++ ++static void do_whpx_cpu_synchronize_post_loadvm(CPUState *cpu, ++ run_on_cpu_data arg) ++{ ++ if (cpu->accel && cpu->accel->loadvm_pending) { ++ whpx_set_registers(cpu, WHPX_LEVEL_FULL_STATE); ++ cpu->vcpu_dirty = false; ++ cpu->accel->loadvm_pending = false; ++ } + } + + /* +@@ -237,7 +256,36 @@ void whpx_cpu_synchronize_pre_loadvm(CPUState *cpu) + + static void whpx_pre_resume_vm(AccelState *as, bool step_pending) + { ++ CPUState *cpu; ++ bool any_loadvm = false; ++ + whpx_global.step_pending = step_pending; ++ ++ CPU_FOREACH(cpu) { ++ if (cpu->accel && cpu->accel->loadvm_pending) { ++ any_loadvm = true; ++ break; ++ } ++ } ++ if (any_loadvm) { ++ uint64_t max_tsc = 0; ++ CPU_FOREACH(cpu) { ++ uint64_t t = cpu_env(cpu)->tsc; ++ if (t > max_tsc) { ++ max_tsc = t; ++ } ++ } ++ if (whp_dispatch.WHvSuspendPartitionTime) { ++ whp_dispatch.WHvSuspendPartitionTime(whpx_global.partition); ++ } ++ CPU_FOREACH(cpu) { ++ if (cpu->accel && cpu->accel->loadvm_pending) { ++ cpu_env(cpu)->tsc = max_tsc; ++ run_on_cpu(cpu, do_whpx_cpu_synchronize_post_loadvm, ++ RUN_ON_CPU_NULL); ++ } ++ } ++ } + } + + /* +@@ -525,7 +573,7 @@ static void whpx_log_sync(MemoryListener *listener, + { + MemoryRegion *mr = section->mr; + +- if (!memory_region_is_ram(mr)) { ++ if (!memory_region_is_ram(mr) || !runstate_is_running()) { + return; + } + +diff --git a/hw/display/reims-graphics-pci.c b/hw/display/reims-graphics-pci.c +index db10858b65dc0447f7d0e660fca6f1acc3bb7473..976b5d4e3bd4d93d2e9a401fd494eeb2d8e6a442 100644 +--- a/hw/display/reims-graphics-pci.c ++++ b/hw/display/reims-graphics-pci.c +@@ -114,7 +114,9 @@ + #endif + #include "qapi/error.h" + #include "qapi/qapi-commands-ui.h" +-#include "migration/blocker.h" ++#include "migration/misc.h" ++#include "migration/vmstate.h" ++#include "migration/qemu-file-types.h" + #include "hw/core/qdev-properties.h" + #include "hw/pci/pci_device.h" + #include "hw/pci/msix.h" +@@ -232,6 +234,10 @@ struct ReimsGraphicsPCIState { + bool irqfd_made; /* the notifier is initialised */ + RvgGraphicsDevice *device; + VMChangeStateEntry *vm_state; /* the teardown at QEMU's quit */ ++ NotifierWithReturn mig_notifier; ++ bool mig_notifier_added; ++ bool mig_quiesced; ++ bool region_registered; + /* The displays, display i head i: the first `displays` of them. */ + ReimsGraphicsHead heads[RVG_GRAPHICS_DISPLAYS_MAX]; + ThreadPool *pool; /* where the consoles' reads of the displays run */ +@@ -283,7 +289,6 @@ struct ReimsGraphicsPCIState { + + QEMU_BUILD_BUG_ON(RVG_GRAPHICS_MSIX_VECTORS != 1); + +-static Error *reims_graphics_mig_blocker; + + /* ------ Interrupts ------ */ + +@@ -1388,6 +1393,7 @@ static bool reims_graphics_pool_add(ReimsGraphicsPCIState *s, + memory_region_init_ram_ptr(&piece->mr, OBJECT(piece), + "reims-graphics-pci.pool-piece", ask->size, + ask->host); ++ qemu_ram_unset_migratable(piece->mr.ram_block); + /* + * Inside the add's transaction: on its own, set_unmergeable commits + * (and renders every flat view) for a region that is in none yet. +@@ -2111,6 +2117,14 @@ static void reims_graphics_pci_teardown(ReimsGraphicsPCIState *s, bool quit) + ReimsGraphicsHead *head; + uint32_t i; + ++ if (s->mig_notifier_added) { ++ migration_remove_notifier(&s->mig_notifier); ++ s->mig_notifier_added = false; ++ } ++ if (s->region_registered) { ++ vmstate_unregister_ram(&s->region, DEVICE(dev)); ++ s->region_registered = false; ++ } + if (s->vm_state) { + qemu_del_vm_change_state_handler(s->vm_state); + s->vm_state = NULL; +@@ -2477,6 +2491,158 @@ static bool reims_graphics_linux_floor(Error **errp) + return true; + } + ++ ++static int reims_graphics_pci_mig_notify(NotifierWithReturn *notify, ++ MigrationEvent *e, Error **errp) ++{ ++ ReimsGraphicsPCIState *s = ++ container_of(notify, ReimsGraphicsPCIState, mig_notifier); ++ ++ if (!s->device) { ++ return 0; ++ } ++ switch (e->type) { ++ case MIG_EVENT_SETUP: ++ if (!s->mig_quiesced) { ++ RvgStatus status = rvg_graphics_device_quiesce(s->device); ++ if (status != RVG_OK) { ++ error_setg(errp, "%s: rvg_graphics_device_quiesce failed: %s", ++ TYPE_REIMS_GRAPHICS_PCI, rvg_status_message(status)); ++ return -1; ++ } ++ reims_graphics_pool_bh(s); ++ s->mig_quiesced = true; ++ } ++ break; ++ case MIG_EVENT_DONE: ++ case MIG_EVENT_FAILED: ++ if (s->mig_quiesced) { ++ rvg_graphics_device_unquiesce(s->device); ++ s->mig_quiesced = false; ++ } ++ break; ++ default: ++ break; ++ } ++ return 0; ++} ++ ++static int reims_graphics_vgpu_snapshot_put(QEMUFile *f, void *pv, size_t size, ++ const VMStateField *field, ++ JSONWriter *vmdesc) ++{ ++ ReimsGraphicsPCIState *s = pv; ++ uint8_t *data = NULL; ++ uintptr_t len = 0; ++ uintptr_t off = 0; ++ RvgStatus status; ++ ++ if (!s->device) { ++ qemu_put_be64(f, 0); ++ return 0; ++ } ++ status = rvg_graphics_device_snapshot_save(s->device, &data, &len); ++ if (status != RVG_OK) { ++ error_report("%s: rvg_graphics_device_snapshot_save failed: %s", ++ TYPE_REIMS_GRAPHICS_PCI, rvg_status_message(status)); ++ return -EIO; ++ } ++ qemu_put_be64(f, (uint64_t)len); ++ while (off < len) { ++ size_t chunk = (size_t)MIN(len - off, (uintptr_t)(1 * MiB)); ++ qemu_put_buffer(f, data + off, chunk); ++ off += chunk; ++ } ++ rvg_graphics_snapshot_free(data, len); ++ return qemu_file_get_error(f); ++} ++ ++static int reims_graphics_vgpu_snapshot_get(QEMUFile *f, void *pv, size_t size, ++ const VMStateField *field) ++{ ++ ReimsGraphicsPCIState *s = pv; ++ uint64_t len = qemu_get_be64(f); ++ uint8_t *buf = NULL; ++ uint64_t off = 0; ++ RvgStatus status; ++ ++ if (qemu_file_get_error(f)) { ++ return qemu_file_get_error(f); ++ } ++ if (len == 0) { ++ return 0; ++ } ++ if (len > (uint64_t)8 * GiB || !s->device) { ++ error_report("%s: invalid vgpu snapshot length %" PRIu64, ++ TYPE_REIMS_GRAPHICS_PCI, len); ++ return -EINVAL; ++ } ++ buf = g_try_malloc(len); ++ if (!buf) { ++ return -ENOMEM; ++ } ++ while (off < len) { ++ size_t chunk = (size_t)MIN(len - off, (uint64_t)(1 * MiB)); ++ size_t got = qemu_get_buffer(f, buf + off, chunk); ++ if (got != chunk) { ++ g_free(buf); ++ return -EIO; ++ } ++ off += got; ++ } ++ status = rvg_graphics_device_snapshot_load(s->device, buf, (size_t)len); ++ g_free(buf); ++ if (status != RVG_OK) { ++ error_report("%s: rvg_graphics_device_snapshot_load failed: %s", ++ TYPE_REIMS_GRAPHICS_PCI, rvg_status_message(status)); ++ return -EIO; ++ } ++ return 0; ++} ++ ++static const VMStateInfo vmstate_info_reims_vgpu_snapshot = { ++ .name = "reims-vgpu-snapshot", ++ .get = reims_graphics_vgpu_snapshot_get, ++ .put = reims_graphics_vgpu_snapshot_put, ++}; ++ ++static int reims_graphics_pci_post_load(void *opaque, int version_id) ++{ ++ ReimsGraphicsPCIState *s = opaque; ++ PCIDevice *dev = PCI_DEVICE(s); ++ ++ /* Synchronously map all restored Shared Pool pieces into guest GPA before cont. */ ++ reims_graphics_pool_bh(s); ++ ++ if (msix_enabled(dev)) { ++ if (s->irqfd_made) { ++ reims_graphics_pci_irqfd_enable(s); ++ } else if (s->msi_direct_made) { ++ reims_graphics_pci_direct_enable(s); ++ } ++ } ++ return 0; ++} ++ ++static const VMStateDescription vmstate_reims_graphics_pci = { ++ .name = TYPE_REIMS_GRAPHICS_PCI, ++ .version_id = 1, ++ .minimum_version_id = 1, ++ .post_load = reims_graphics_pci_post_load, ++ .fields = (const VMStateField[]) { ++ VMSTATE_PCI_DEVICE(parent_obj, ReimsGraphicsPCIState), ++ VMSTATE_MSIX(parent_obj, ReimsGraphicsPCIState), ++ { ++ .name = "reims_vgpu_snapshot", ++ .info = &vmstate_info_reims_vgpu_snapshot, ++ .flags = VMS_SINGLE, ++ .size = sizeof(ReimsGraphicsPCIState), ++ .offset = 0, ++ }, ++ VMSTATE_END_OF_LIST() ++ } ++}; ++ + static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp) + { + ReimsGraphicsPCIState *s = REIMS_GRAPHICS_PCI(dev); +@@ -2577,13 +2743,7 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp) + } + reims_graphics_pci_check_low_ram(); + +- if (reims_graphics_mig_blocker == NULL) { +- error_setg(&reims_graphics_mig_blocker, +- "Migration state blocked by reims-graphics-pci"); +- if (migrate_add_blocker(&reims_graphics_mig_blocker, errp) < 0) { +- return; +- } +- } ++ + + /* + * The guest's RAM, through which the GPU uses an IOSurface's own pages in +@@ -2707,6 +2867,8 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp) + base = rvg_graphics_device_region(s->device, &size); + memory_region_init_ram_ptr(&s->region, OBJECT(dev), + "reims-graphics-pci.region", size, base); ++ vmstate_register_ram(&s->region, DEVICE(dev)); ++ s->region_registered = true; + pci_register_bar(dev, RVG_GRAPHICS_PCI_BAR_REGION, + PCI_BASE_ADDRESS_SPACE_MEMORY | + PCI_BASE_ADDRESS_MEM_TYPE_64 | +@@ -2728,6 +2890,8 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp) + } + s->vm_state = qemu_add_vm_change_state_handler( + reims_graphics_pci_vm_state_change, s); ++ migration_add_notifier(&s->mig_notifier, reims_graphics_pci_mig_notify); ++ s->mig_notifier_added = true; + return; + + fail: +@@ -2795,6 +2959,7 @@ static void reims_graphics_pci_class_init(ObjectClass *klass, const void *data) + + rc->phases.hold = reims_graphics_pci_reset; + dc->desc = "reims-graphics GPU"; ++ dc->vmsd = &vmstate_reims_graphics_pci; + dc->hotpluggable = false; + set_bit(DEVICE_CATEGORY_DISPLAY, dc->categories); + device_class_set_props(dc, reims_graphics_pci_properties); +diff --git a/hw/misc/applesmc.c b/hw/misc/applesmc.c +index 84bcf4df0abb15ea73fc03ecc2a2c236ae4a7c8c..2dcc20aa0e28104f5d9fa2e2a4a5ffaee4648821 100644 +--- a/hw/misc/applesmc.c ++++ b/hw/misc/applesmc.c +@@ -37,6 +37,7 @@ + #include "qemu/error-report.h" + #include "qemu/module.h" + #include "qemu/timer.h" ++#include "migration/vmstate.h" + #include "qom/object.h" + #include "hw/acpi/acpi_aml_interface.h" + +@@ -108,7 +109,7 @@ struct AppleSMCState { + uint8_t status; + uint8_t status_1e; + uint8_t last_ret; +- char key[4]; ++ uint8_t key[4]; + uint8_t read_pos; + uint8_t data_len; + uint8_t data_pos; +@@ -407,11 +408,30 @@ static void build_applesmc_aml(AcpiDevAmlIf *adev, Aml *scope) + aml_append(scope, dev); + } + ++static const VMStateDescription vmstate_applesmc = { ++ .name = "applesmc", ++ .version_id = 1, ++ .minimum_version_id = 1, ++ .fields = (const VMStateField[]) { ++ VMSTATE_UINT8(cmd, AppleSMCState), ++ VMSTATE_UINT8(status, AppleSMCState), ++ VMSTATE_UINT8(status_1e, AppleSMCState), ++ VMSTATE_UINT8(last_ret, AppleSMCState), ++ VMSTATE_UINT8_ARRAY(key, AppleSMCState, 4), ++ VMSTATE_UINT8(read_pos, AppleSMCState), ++ VMSTATE_UINT8(data_len, AppleSMCState), ++ VMSTATE_UINT8(data_pos, AppleSMCState), ++ VMSTATE_UINT8_ARRAY(data, AppleSMCState, 255), ++ VMSTATE_END_OF_LIST() ++ } ++}; ++ + static void qdev_applesmc_class_init(ObjectClass *klass, const void *data) + { + DeviceClass *dc = DEVICE_CLASS(klass); + AcpiDevAmlIfClass *adevc = ACPI_DEV_AML_IF_CLASS(klass); + ++ dc->vmsd = &vmstate_applesmc; + dc->realize = applesmc_isa_realize; + dc->unrealize = applesmc_unrealize; + device_class_set_legacy_reset(dc, qdev_applesmc_isa_reset); +diff --git a/include/system/whpx-common.h b/include/system/whpx-common.h +index 79710e2fb3c96edda813fadbda5f8ceabcc5afac..a6fcbd2346b8e34a26f868a0ec19250a0fd268a6 100644 +--- a/include/system/whpx-common.h ++++ b/include/system/whpx-common.h +@@ -9,6 +9,7 @@ struct AccelCPUState { + bool ready_for_pic_interrupt; + uint64_t tpr; + bool interruption_pending; ++ bool loadvm_pending; + /* Must be the last field as it may have a tail */ + WHV_RUN_VP_EXIT_CONTEXT exit_ctx; + }; +diff --git a/migration/migration.c b/migration/migration.c +index 5686209ab11b263b20776d79df79baecd26c5970..f105f616d1dbc88daac2c573c9a95cd02305d9ab 100644 +--- a/migration/migration.c ++++ b/migration/migration.c +@@ -63,6 +63,7 @@ + #include "system/dirtylimit.h" + #include "qemu/sockets.h" + #include "system/kvm.h" ++#include "system/whpx.h" + #include "math.h" + + #define NOTIFIER_ELEM_INIT(array, elem) \ +@@ -2174,6 +2175,34 @@ void qmp_migrate(const char *uri, bool has_channels, + return; + } + ++ if (whpx_enabled()) { ++ if (has_resume && resume) { ++ error_setg(errp, "WHPX: migration resume is not supported"); ++ return; ++ } ++ if (migrate_mode() != MIG_MODE_NORMAL) { ++ error_setg(errp, "WHPX: only normal migration mode is supported"); ++ return; ++ } ++ if (runstate_is_running()) { ++ error_setg(errp, ++ "WHPX: live migration is not supported while the VM is running; stop the VM first"); ++ return; ++ } ++ if (main_ch->addr->transport != MIGRATION_ADDRESS_TYPE_FILE) { ++ error_setg(errp, ++ "WHPX: only stopped-VM file suspend (file: URI) is supported"); ++ return; ++ } ++ if (migrate_postcopy() || migrate_background_snapshot() || ++ migrate_colo() || migrate_dirty_bitmaps() || ++ migrate_return_path()) { ++ error_setg(errp, ++ "WHPX: unsupported migration capability for stopped-VM file suspend"); ++ return; ++ } ++ } ++ + if (!migrate_prepare(s, has_resume && resume, errp)) { + /* Error detected, put into errp */ + return; +diff --git a/migration/savevm.c b/migration/savevm.c +index fe94ba96e432c8555bcfc58d97f3830a86eaab60..2a1944010c595995f6d75d3cb4d6ca67525ec1fa 100644 +--- a/migration/savevm.c ++++ b/migration/savevm.c +@@ -64,6 +64,7 @@ + #include "system/runstate.h" + #include "system/system.h" + #include "system/xen.h" ++#include "system/whpx.h" + #include "migration/colo.h" + #include "qemu/bitmap.h" + #include "net/announce.h" +@@ -3317,6 +3318,12 @@ bool save_snapshot(const char *name, bool overwrite, const char *vmstate, + return false; + } + ++ if (whpx_enabled()) { ++ error_setg(errp, ++ "WHPX: internal VM snapshots are not supported; use stopped-VM file migration"); ++ return false; ++ } ++ + if (!replay_can_snapshot()) { + error_setg(errp, "Record/replay does not allow making snapshot " + "right now. Try once more later."); +diff --git a/target/i386/whpx/whpx-all.c b/target/i386/whpx/whpx-all.c +index f093b59c0f04e1cdf6a14172d3b059068e61ac00..30b64eb901dcb6d0781c87dfc4241e6b4abe635c 100644 +--- a/target/i386/whpx/whpx-all.c ++++ b/target/i386/whpx/whpx-all.c +@@ -32,6 +32,7 @@ + #include "qapi/qapi-types-common.h" + #include "qapi/qapi-type-infos-common.h" + #include "migration/blocker.h" ++#include "migration/misc.h" + #include "host-cpu.h" + #include "accel/accel-cpu-target.h" + #include +@@ -56,6 +57,24 @@ + #define HV_X64_MSR_VP_ASSIST_PAGE 0x40000073 + #define HV_X64_MSR_GUEST_IDLE 0x400000f0 + ++#define WHPX_MP_STATE_RUNNABLE 0 ++#define WHPX_MP_STATE_UNINITIALIZED 1 ++#define WHPX_MP_STATE_HALTED 3 ++ ++static void whpx_set_reg_optional(CPUState *cpu, WHV_REGISTER_NAME reg, ++ WHV_REGISTER_VALUE val) ++{ ++ whp_dispatch.WHvSetVirtualProcessorRegisters( ++ whpx_global.partition, cpu->cpu_index, ®, 1, &val); ++} ++ ++static bool whpx_get_reg_optional(CPUState *cpu, WHV_REGISTER_NAME reg, ++ WHV_REGISTER_VALUE *val) ++{ ++ return SUCCEEDED(whp_dispatch.WHvGetVirtualProcessorRegisters( ++ whpx_global.partition, cpu->cpu_index, ®, 1, val)); ++} ++ + static bool is_modern_os = true; + static bool whpx_msr_exits_available = true; + static bool whpx_forward_startup_ipis; +@@ -636,18 +655,8 @@ void whpx_set_registers(CPUState *cpu, WHPXStateLevel level) + whpx_set_reg(cpu, WHvX64RegisterCr8, cr8); + } + +- /* 8 Debug Registers - Skipped */ +- +- /* +- * Extended control registers needs to be handled separately depending +- * on whether xsave is supported/enabled or not. +- */ +- whpx_set_xcrs(cpu); +- +- if (whpx_is_xsave_enabled(cpu)) { +- whpx_set_xsave_state(cpu); +- } +- whpx_set_legacy_fp_registers(cpu, level); ++ /* 8 Debug Registers - restored below for FULL_STATE */ ++ /* XCR0/XSAVE/FP restored AFTER CR0/CR4/EFER are committed to WHPX */ + + /* MSRs */ + assert(whpx_register_names[idx] == WHvX64RegisterEfer); +@@ -694,10 +703,77 @@ void whpx_set_registers(CPUState *cpu, WHPXStateLevel level) + hr); + } + ++ if (level > WHPX_LEVEL_FAST_RUNTIME_STATE) { ++ whpx_set_xcrs(cpu); ++ if (!whpx_is_xsave_enabled(cpu) || whpx_set_xsave_state(cpu) != 0) { ++ whpx_set_legacy_fp_registers(cpu, level); ++ } ++ } ++ + if (level >= WHPX_LEVEL_FULL_STATE) { +- WHV_REGISTER_VALUE apic_base = {}; +- apic_base.Reg64 = cpu_get_apic_base(X86_CPU(cpu)->apic_state); +- whpx_set_reg(cpu, WHvX64RegisterApicBase, apic_base); ++ static const WHV_REGISTER_NAME dr_names[6] = { ++ WHvX64RegisterDr0, WHvX64RegisterDr1, WHvX64RegisterDr2, ++ WHvX64RegisterDr3, WHvX64RegisterDr6, WHvX64RegisterDr7, ++ }; ++ WHV_REGISTER_VALUE dr_vals[6] = { ++ { .Reg64 = env->dr[0] }, { .Reg64 = env->dr[1] }, ++ { .Reg64 = env->dr[2] }, { .Reg64 = env->dr[3] }, ++ { .Reg64 = env->dr[6] }, { .Reg64 = env->dr[7] }, ++ }; ++ whp_dispatch.WHvSetVirtualProcessorRegisters( ++ whpx->partition, cpu->cpu_index, dr_names, 6, dr_vals); ++ ++ WHV_REGISTER_VALUE v = {}; ++ v.Reg64 = env->tsc_aux; ++ whpx_set_reg_optional(cpu, WHvX64RegisterTscAux, v); ++ ++ /* Do not write WHvX64RegisterTscAdjust after WHvX64RegisterTsc, ++ * as MSR_IA32_TSC_ADJUST shifts the vCPU TSC offset in Hyper-V. */ ++ if (env->spec_ctrl) { ++ v.Reg64 = env->spec_ctrl; ++ whpx_set_reg_optional(cpu, WHvX64RegisterSpecCtrl, v); ++ } ++ if (env->mtrr_deftype) { ++ v.Reg64 = env->mtrr_deftype; ++ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrDefType, v); ++ for (i = 0; i < MSR_MTRRcap_VCNT; i++) { ++ v.Reg64 = env->mtrr_var[i].base; ++ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysBase0 + i, v); ++ v.Reg64 = env->mtrr_var[i].mask; ++ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysMask0 + i, v); ++ } ++ for (i = 0; i < 11; i++) { ++ v.Reg64 = env->mtrr_fixed[i]; ++ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrFix64k00000 + i, v); ++ } ++ } ++ ++ if (!whpx_irqchip_in_kernel()) { ++ WHV_REGISTER_VALUE apic_base = {}; ++ apic_base.Reg64 = cpu_get_apic_base(X86_CPU(cpu)->apic_state); ++ whpx_set_reg(cpu, WHvX64RegisterApicBase, apic_base); ++ } ++ ++ if (!whpx->tsc_deadline_refused) { ++ WHV_REGISTER_VALUE tsc_deadline = { .Reg64 = env->tsc_deadline }; ++ whpx_set_reg(cpu, WHvX64RegisterTscDeadline, tsc_deadline); ++ } ++ ++ if (whpx_irqchip_in_kernel()) { ++ WHV_REGISTER_VALUE activity = {}; ++ whpx_get_reg_optional(cpu, WHvRegisterInternalActivityState, &activity); ++ activity.InternalActivity.StartupSuspend = ++ (env->mp_state == WHPX_MP_STATE_UNINITIALIZED); ++ activity.InternalActivity.HaltSuspend = 0; ++ whpx_set_reg(cpu, WHvRegisterInternalActivityState, activity); ++ } ++ ++ { ++ WHV_REGISTER_VALUE intr_state = {}; ++ intr_state.InterruptState.InterruptShadow = ++ !!(env->hflags & HF_INHIBIT_IRQ_MASK); ++ whpx_set_reg_optional(cpu, WHvRegisterInterruptState, intr_state); ++ } + } + } + +@@ -940,6 +1016,9 @@ void whpx_get_registers(CPUState *cpu, WHPXStateLevel level) + } + + if (!env->tsc_valid) { ++ if (!runstate_is_running() && whp_dispatch.WHvSuspendPartitionTime) { ++ whp_dispatch.WHvSuspendPartitionTime(whpx->partition); ++ } + whpx_get_tsc(cpu); + env->tsc_valid = !runstate_is_running(); + } +@@ -1016,10 +1095,9 @@ void whpx_get_registers(CPUState *cpu, WHPXStateLevel level) + */ + whpx_get_xcrs(cpu); + +- if (whpx_is_xsave_enabled(cpu)) { +- whpx_get_xsave_state(cpu); ++ if (!whpx_is_xsave_enabled(cpu) || whpx_get_xsave_state(cpu) != 0) { ++ whpx_get_legacy_fp_registers(cpu, level); + } +- whpx_get_legacy_fp_registers(cpu, level); + + /* MSRs */ + assert(whpx_register_names[idx] == WHvX64RegisterEfer); +@@ -1051,11 +1129,83 @@ void whpx_get_registers(CPUState *cpu, WHPXStateLevel level) + + assert(idx == RTL_NUMBER_OF(whpx_register_names)); + ++ if (level >= WHPX_LEVEL_FULL_STATE) { ++ static const WHV_REGISTER_NAME dr_names[6] = { ++ WHvX64RegisterDr0, WHvX64RegisterDr1, WHvX64RegisterDr2, ++ WHvX64RegisterDr3, WHvX64RegisterDr6, WHvX64RegisterDr7, ++ }; ++ WHV_REGISTER_VALUE dr_vals[6] = {}; ++ if (SUCCEEDED(whp_dispatch.WHvGetVirtualProcessorRegisters( ++ whpx->partition, cpu->cpu_index, dr_names, 6, dr_vals))) { ++ env->dr[0] = dr_vals[0].Reg64; ++ env->dr[1] = dr_vals[1].Reg64; ++ env->dr[2] = dr_vals[2].Reg64; ++ env->dr[3] = dr_vals[3].Reg64; ++ env->dr[6] = dr_vals[4].Reg64; ++ env->dr[7] = dr_vals[5].Reg64; ++ } ++ ++ WHV_REGISTER_VALUE v = {}; ++ if (whpx_get_reg_optional(cpu, WHvX64RegisterTscAux, &v)) { ++ env->tsc_aux = v.Reg64; ++ } ++ if (whpx_get_reg_optional(cpu, WHvX64RegisterTscAdjust, &v)) { ++ env->tsc_adjust = v.Reg64; ++ } ++ if (whpx_get_reg_optional(cpu, WHvX64RegisterSpecCtrl, &v)) { ++ env->spec_ctrl = v.Reg64; ++ } ++ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrDefType, &v)) { ++ env->mtrr_deftype = v.Reg64; ++ for (i = 0; i < MSR_MTRRcap_VCNT; i++) { ++ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysBase0 + i, &v)) { ++ env->mtrr_var[i].base = v.Reg64; ++ } ++ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysMask0 + i, &v)) { ++ env->mtrr_var[i].mask = v.Reg64; ++ } ++ } ++ for (i = 0; i < 11; i++) { ++ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrFix64k00000 + i, &v)) { ++ env->mtrr_fixed[i] = v.Reg64; ++ } ++ } ++ } ++ if (!whpx->tsc_deadline_refused && ++ whpx_get_reg_optional(cpu, WHvX64RegisterTscDeadline, &v)) { ++ env->tsc_deadline = v.Reg64; ++ } ++ if (whpx_irqchip_in_kernel() && ++ whpx_get_reg_optional(cpu, WHvRegisterInternalActivityState, &v)) { ++ if (v.InternalActivity.StartupSuspend) { ++ env->mp_state = WHPX_MP_STATE_UNINITIALIZED; ++ } else if (v.InternalActivity.HaltSuspend) { ++ env->mp_state = WHPX_MP_STATE_HALTED; ++ } else { ++ env->mp_state = WHPX_MP_STATE_RUNNABLE; ++ } ++ } ++ if (whpx_get_reg_optional(cpu, WHvRegisterPendingInterruption, &v) && ++ v.PendingInterruption.InterruptionPending) { ++ warn_report("WHPX: vCPU %d saved with PendingInterruption type=%u vec=%u", ++ cpu->cpu_index, ++ (unsigned)v.PendingInterruption.InterruptionType, ++ (unsigned)v.PendingInterruption.InterruptionVector); ++ } ++ } ++ + if (whpx_irqchip_in_kernel()) { + whpx_apic_get(x86_cpu->apic_state); + } + + x86_update_hflags(env); ++ if (level >= WHPX_LEVEL_FULL_STATE) { ++ WHV_REGISTER_VALUE intr_state = {}; ++ if (whpx_get_reg_optional(cpu, WHvRegisterInterruptState, &intr_state) && ++ intr_state.InterruptState.InterruptShadow) { ++ env->hflags |= HF_INHIBIT_IRQ_MASK; ++ } ++ } + } + + static int emulate_instruction(CPUState *cpu, const uint8_t *insn_bytes, size_t insn_len) +@@ -2515,8 +2665,12 @@ int whpx_vcpu_run(CPUState *cpu) + + do { + if (cpu->vcpu_dirty) { +- whpx_set_registers(cpu, WHPX_LEVEL_RUNTIME_STATE); ++ WHPXStateLevel level = vcpu->loadvm_pending ++ ? WHPX_LEVEL_FULL_STATE ++ : WHPX_LEVEL_RUNTIME_STATE; ++ whpx_set_registers(cpu, level); + cpu->vcpu_dirty = false; ++ vcpu->loadvm_pending = false; + } + + if (exclusive_step_mode == WHPX_STEP_NONE) { +@@ -2982,6 +3136,28 @@ int whpx_vcpu_run(CPUState *cpu) + */ + + static Error *whpx_migration_blocker; ++static NotifierWithReturn whpx_migration_notifier; ++static bool whpx_migration_notifier_added; ++ ++static int whpx_migration_setup_notifier(NotifierWithReturn *notify, ++ MigrationEvent *e, Error **errp) ++{ ++ if (e->type != MIG_EVENT_SETUP) { ++ return 0; ++ } ++ if (runstate_is_running()) { ++ error_setg(errp, ++ "WHPX: live migration is not supported while the VM is running; stop the VM first"); ++ return -1; ++ } ++ if (migrate_mode() != MIG_MODE_NORMAL || ++ migrate_postcopy_ram() || migrate_background_snapshot()) { ++ error_setg(errp, ++ "WHPX: only stopped-VM normal file suspend is supported"); ++ return -1; ++ } ++ return 0; ++} + + static void whpx_cpu_update_state(void *opaque, bool running, RunState state) + { +@@ -3006,20 +3182,27 @@ int whpx_init_vcpu(CPUState *cpu) + UINT64 freq = 0; + int ret; + +- /* Add migration blockers for all unsupported features of the +- * Windows Hypervisor Platform ++ /* ++ * WHPX lacks dirty-page tracking, so live migration and non-normal modes ++ * remain blocked. Only stopped-VM normal file suspend (stop -> migrate -> ++ * quit) is permitted and enforced both at migration entry and on setup. + */ +- if (whpx_migration_blocker == NULL) { ++ if (!whpx_migration_blocker) { ++ unsigned non_normal_modes = (BIT(MIG_MODE__MAX) - 1) & ++ ~BIT(MIG_MODE_NORMAL); + error_setg(&whpx_migration_blocker, +- "State blocked due to missing dirty memory tracking support," +- "And some system register/state save-restore "); +- +- if (migrate_add_blocker(&whpx_migration_blocker, &local_error) < 0) { +- error_report_err(local_error); +- ret = -EINVAL; +- goto error; ++ "WHPX: migration mode is not supported (only stopped-VM normal file suspend)"); ++ migrate_add_blocker_modes(&whpx_migration_blocker, non_normal_modes, ++ &local_error); ++ if (local_error) { ++ error_propagate(&error_fatal, local_error); + } + } ++ if (!whpx_migration_notifier_added) { ++ migration_add_notifier(&whpx_migration_notifier, ++ whpx_migration_setup_notifier); ++ whpx_migration_notifier_added = true; ++ } + + vcpu = g_new0(AccelCPUState, 1); + +diff --git a/target/i386/whpx/whpx-apic.c b/target/i386/whpx/whpx-apic.c +index 547b1cd2671bb6b8fb5a826ab5af5ef89b0997be..75ecf48feb48b448cb39d5878d9bb86b0fa5746a 100644 +--- a/target/i386/whpx/whpx-apic.c ++++ b/target/i386/whpx/whpx-apic.c +@@ -35,13 +35,17 @@ static void whpx_put_apic_state(APICCommonState *s, + memset(kapic, 0, sizeof(*kapic)); + if (s->apicbase & MSR_IA32_APICBASE_EXTD) { + kapic->fields[0x2].data = s->initial_apic_id; ++ kapic->fields[0xd].data = ++ ((s->initial_apic_id & ~0xfu) << 12) | ++ (1u << (s->initial_apic_id & 0xfu)); ++ kapic->fields[0xe].data = 0; + } else { + kapic->fields[0x2].data = s->id << 24; ++ kapic->fields[0xd].data = s->log_dest << 24; ++ kapic->fields[0xe].data = s->dest_mode << 28 | 0x0fffffff; + } + kapic->fields[0x3].data = s->version | ((APIC_LVT_NB - 1) << 16); + kapic->fields[0x8].data = s->tpr; +- kapic->fields[0xd].data = s->log_dest << 24; +- kapic->fields[0xe].data = s->dest_mode << 28 | 0x0fffffff; + kapic->fields[0xf].data = s->spurious_vec; + for (i = 0; i < 8; i++) { + kapic->fields[0x10 + i].data = s->isr[i]; +@@ -212,10 +216,18 @@ static void whpx_apic_put(CPUState *cs, run_on_cpu_data data) + &kapic, + sizeof(kapic)); + if (FAILED(hr)) { ++ struct whpx_lapic_state cur = {}; ++ whp_dispatch.WHvGetVirtualProcessorInterruptControllerState2( ++ whpx_global.partition, cs->cpu_index, &cur, sizeof(cur), NULL); + fprintf(stderr, +- "WHvSetVirtualProcessorInterruptControllerState failed: %08lx\n", +- hr); +- ++ "WHvSetVirtualProcessorInterruptControllerState2 failed: %08lx cpu=%d apicbase=0x%llx\n", ++ hr, cs->cpu_index, (unsigned long long)s->apicbase); ++ for (int idx = 0; idx < 256; idx++) { ++ if (kapic.fields[idx].data || cur.fields[idx].data) { ++ fprintf(stderr, " lapic[0x%02x]: put=0x%08x cur=0x%08x\n", ++ idx, kapic.fields[idx].data, cur.fields[idx].data); ++ } ++ } + abort(); + } + } +@@ -224,8 +236,17 @@ void whpx_apic_get(APICCommonState *s) + { + CPUState *cpu = CPU(s->cpu); + struct whpx_lapic_state kapic; ++ WHV_REGISTER_NAME base_reg = WHvX64RegisterApicBase; ++ WHV_REGISTER_VALUE base_val = {}; ++ HRESULT hr; ++ ++ hr = whp_dispatch.WHvGetVirtualProcessorRegisters( ++ whpx_global.partition, cpu->cpu_index, &base_reg, 1, &base_val); ++ if (SUCCEEDED(hr)) { ++ s->apicbase = base_val.Reg64; ++ } + +- HRESULT hr = whp_dispatch.WHvGetVirtualProcessorInterruptControllerState2( ++ hr = whp_dispatch.WHvGetVirtualProcessorInterruptControllerState2( + whpx_global.partition, + cpu->cpu_index, + &kapic, +@@ -233,7 +254,7 @@ void whpx_apic_get(APICCommonState *s) + NULL); + if (FAILED(hr)) { + fprintf(stderr, +- "WHvSetVirtualProcessorInterruptControllerState failed: %08lx\n", ++ "WHvGetVirtualProcessorInterruptControllerState2 failed: %08lx\n", + hr); + + abort(); +@@ -242,6 +263,17 @@ void whpx_apic_get(APICCommonState *s) + whpx_get_apic_state(s, &kapic); + } + ++static void do_whpx_apic_get(CPUState *cs, run_on_cpu_data data) ++{ ++ APICCommonState *s = data.host_ptr; ++ whpx_apic_get(s); ++} ++ ++static void whpx_apic_pre_save(APICCommonState *s) ++{ ++ run_on_cpu(CPU(s->cpu), do_whpx_apic_get, RUN_ON_CPU_HOST_PTR(s)); ++} ++ + static void whpx_apic_post_load(APICCommonState *s) + { + run_on_cpu(CPU(s->cpu), whpx_apic_put, RUN_ON_CPU_HOST_PTR(s)); +@@ -379,6 +411,7 @@ static void whpx_apic_class_init(ObjectClass *klass, const void *data) + k->set_base = apic_set_base; + k->set_tpr = whpx_apic_set_tpr; + k->get_tpr = whpx_apic_get_tpr; ++ k->pre_save = whpx_apic_pre_save; + k->post_load = whpx_apic_post_load; + k->vapic_base_update = whpx_apic_vapic_base_update; + k->external_nmi = whpx_apic_external_nmi; diff --git a/patches/qemu-win32-mapped-ram-io.patch b/patches/qemu-win32-mapped-ram-io.patch new file mode 100644 index 0000000..61ebe21 --- /dev/null +++ b/patches/qemu-win32-mapped-ram-io.patch @@ -0,0 +1,727 @@ +diff --git a/include/io/channel.h b/include/io/channel.h +index 834ba7c30986dd48686705da5aa7197eb228cef7..87f751308d6fdd7b87e31be44fca07fe93501aba 100644 +--- a/include/io/channel.h ++++ b/include/io/channel.h +@@ -146,12 +146,12 @@ struct QIOChannelClass { + ssize_t (*io_pwritev)(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp); + ssize_t (*io_preadv)(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp); + int (*io_shutdown)(QIOChannel *ioc, + QIOChannelShutdown how, +@@ -160,8 +160,8 @@ struct QIOChannelClass { + bool enabled); + void (*io_set_delay)(QIOChannel *ioc, + bool enabled); +- off_t (*io_seek)(QIOChannel *ioc, +- off_t offset, ++ int64_t (*io_seek)(QIOChannel *ioc, ++ int64_t offset, + int whence, + Error **errp); + void (*io_set_aio_fd_handler)(QIOChannel *ioc, +@@ -579,7 +579,7 @@ int qio_channel_close(QIOChannel *ioc, + * + */ + ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov, +- size_t niov, off_t offset, Error **errp); ++ size_t niov, int64_t offset, Error **errp); + + /** + * qio_channel_pwrite +@@ -595,7 +595,7 @@ ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov, + * + */ + ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen, +- off_t offset, Error **errp); ++ int64_t offset, Error **errp); + + /** + * qio_channel_pwritev_all: +@@ -614,7 +614,7 @@ ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen, + int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp); + + /** +@@ -635,7 +635,7 @@ int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc, + const void *buf, + size_t buflen, +- off_t offset, ++ int64_t offset, + Error **errp); + + /** +@@ -656,7 +656,7 @@ int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc, + * + */ + ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov, +- size_t niov, off_t offset, Error **errp); ++ size_t niov, int64_t offset, Error **errp); + + /** + * qio_channel_pread +@@ -672,7 +672,7 @@ ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov, + * + */ + ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen, +- off_t offset, Error **errp); ++ int64_t offset, Error **errp); + + /** + * qio_channel_preadv_all_eof: +@@ -695,7 +695,7 @@ ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen, + int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp); + + /** +@@ -717,7 +717,7 @@ int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp); + + /** +@@ -741,7 +741,7 @@ int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc, + void *buf, + size_t buflen, +- off_t offset, ++ int64_t offset, + Error **errp); + + /** +@@ -763,7 +763,7 @@ int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_pread_all(QIOChannel *ioc, + void *buf, + size_t buflen, +- off_t offset, ++ int64_t offset, + Error **errp); + + /** +@@ -861,10 +861,10 @@ void qio_channel_set_cork(QIOChannel *ioc, + * Not all implementations will support this facility, + * so may report an error. + * +- * Returns: the new position on success, (off_t)-1 on failure ++ * Returns: the new position on success, (int64_t)-1 on failure + */ +-off_t qio_channel_io_seek(QIOChannel *ioc, +- off_t offset, ++int64_t qio_channel_io_seek(QIOChannel *ioc, ++ int64_t offset, + int whence, + Error **errp); + +diff --git a/include/system/ramblock.h b/include/system/ramblock.h +index 24c970d393e9cc3463fa46a9bcace7937e50fde4..981470f59d569181f859718942ecb9a855f33078 100644 +--- a/include/system/ramblock.h ++++ b/include/system/ramblock.h +@@ -68,7 +68,7 @@ struct RAMBlock { + * offset in the file pages belonging to this ramblock are saved, + * used only during migration to a file. + */ +- off_t bitmap_offset; ++ int64_t bitmap_offset; + uint64_t pages_offset; + + /* Bitmap of already received pages. Only used on destination side. */ +diff --git a/io/channel-buffer.c b/io/channel-buffer.c +index 189fa67ac21df8a8dff868a477a8021873bd22c7..873e80faeb8a8496ddb6fb0743a17ad599a60654 100644 +--- a/io/channel-buffer.c ++++ b/io/channel-buffer.c +@@ -124,8 +124,8 @@ static int qio_channel_buffer_set_blocking(QIOChannel *ioc G_GNUC_UNUSED, + } + + +-static off_t qio_channel_buffer_seek(QIOChannel *ioc, +- off_t offset, ++static int64_t qio_channel_buffer_seek(QIOChannel *ioc, ++ int64_t offset, + int whence, + Error **errp) + { +diff --git a/io/channel-file.c b/io/channel-file.c +index 2487adaea2ad7108310b94910153a4ffbf6eb094..2fb80f90e1c6251c1b2b493e8ebb6566b6b0b769 100644 +--- a/io/channel-file.c ++++ b/io/channel-file.c +@@ -27,6 +27,9 @@ + #include "qemu/module.h" + #include "qemu/sockets.h" + #include "trace.h" ++#ifdef WIN32 ++#include ++#endif + + QIOChannelFile * + qio_channel_file_new_fd(int fd) +@@ -42,7 +45,7 @@ qio_channel_file_new_fd(int fd) + + ioc->fd = fd; + +- if (lseek(fd, 0, SEEK_CUR) != (off_t)-1) { ++ if (lseek(fd, 0, SEEK_CUR) != (int64_t)-1) { + qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_SEEKABLE); + } + +@@ -74,6 +77,9 @@ qio_channel_file_new_path(const char *path, + + ioc = QIO_CHANNEL_FILE(object_new(TYPE_QIO_CHANNEL_FILE)); + ++#ifdef O_BINARY ++ flags |= O_BINARY; ++#endif + if (flags & O_CREAT) { + ioc->fd = qemu_create(path, flags & ~O_CREAT, mode, errp); + } else { +@@ -84,9 +90,18 @@ qio_channel_file_new_path(const char *path, + return NULL; + } + +- if (lseek(ioc->fd, 0, SEEK_CUR) != (off_t)-1) { ++ if (lseek(ioc->fd, 0, SEEK_CUR) != (int64_t)-1) { + qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_SEEKABLE); + } ++#ifdef WIN32 ++ if (flags & O_CREAT) { ++ HANDLE h = (HANDLE)_get_osfhandle(ioc->fd); ++ if (h != INVALID_HANDLE_VALUE && GetFileType(h) == FILE_TYPE_DISK) { ++ DWORD br = 0; ++ DeviceIoControl(h, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &br, NULL); ++ } ++ } ++#endif + + trace_qio_channel_file_new_path(ioc, path, flags, mode, ioc->fd); + +@@ -170,7 +185,7 @@ static ssize_t qio_channel_file_writev(QIOChannel *ioc, + static ssize_t qio_channel_file_preadv(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp) + { + QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); +@@ -196,7 +211,7 @@ static ssize_t qio_channel_file_preadv(QIOChannel *ioc, + static ssize_t qio_channel_file_pwritev(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp) + { + QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); +@@ -216,6 +231,125 @@ static ssize_t qio_channel_file_pwritev(QIOChannel *ioc, + } + return ret; + } ++#elif defined(WIN32) ++static ssize_t qio_channel_file_prw_win32(QIOChannel *ioc, ++ const struct iovec *iov, ++ size_t niov, ++ int64_t offset, ++ bool is_write, ++ Error **errp) ++{ ++ static const size_t max_chunk = 16U * 1024U * 1024U; ++ QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); ++ HANDLE h = (HANDLE)_get_osfhandle(fioc->fd); ++ LARGE_INTEGER zero = { .QuadPart = 0 }; ++ LARGE_INTEGER saved = { .QuadPart = 0 }; ++ bool have_saved = false; ++ uint64_t cur; ++ ssize_t total = 0; ++ ssize_t ret = -1; ++ size_t i = 0; ++ ++ if (offset < 0) { ++ error_setg_errno(errp, EINVAL, "Invalid negative offset for %s", ++ is_write ? "pwritev" : "preadv"); ++ return -1; ++ } ++ if (h == INVALID_HANDLE_VALUE) { ++ error_setg_errno(errp, EBADF, "Invalid file handle for %s", ++ is_write ? "pwritev" : "preadv"); ++ return -1; ++ } ++ ++ cur = (uint64_t)offset; ++ have_saved = SetFilePointerEx(h, zero, &saved, FILE_CURRENT); ++ ++ while (i < niov) { ++ uint8_t *base = (uint8_t *)iov[i].iov_base; ++ size_t run = iov[i].iov_len; ++ size_t j = i + 1; ++ ++ while (j < niov && (uint8_t *)iov[j].iov_base == base + run && ++ run < max_chunk && iov[j].iov_len <= max_chunk - run) { ++ run += iov[j].iov_len; ++ j++; ++ } ++ if (run == 0) { ++ i = j; ++ continue; ++ } ++ ++ size_t done = 0; ++ while (done < run) { ++ DWORD chunk = (DWORD)MIN(run - done, max_chunk); ++ DWORD xfer = 0; ++ OVERLAPPED ov; ++ BOOL ok; ++ ++ memset(&ov, 0, sizeof(ov)); ++ ov.Offset = (DWORD)(cur & 0xFFFFFFFFULL); ++ ov.OffsetHigh = (DWORD)(cur >> 32); ++ if (is_write) { ++ ok = WriteFile(h, base + done, chunk, &xfer, &ov); ++ } else { ++ ok = ReadFile(h, base + done, chunk, &xfer, &ov); ++ } ++ if (!ok) { ++ DWORD err = GetLastError(); ++ if (!is_write && err == ERROR_HANDLE_EOF) { ++ ret = total; ++ goto out; ++ } ++ error_setg_win32(errp, err, ++ is_write ? "Unable to pwritev to file" ++ : "Unable to preadv from file"); ++ goto out; ++ } ++ if (xfer == 0) { ++ if (!is_write || total > 0) { ++ ret = total; ++ goto out; ++ } ++ error_setg_errno(errp, EIO, "pwritev made no progress"); ++ goto out; ++ } ++ done += xfer; ++ cur += xfer; ++ total += xfer; ++ if (is_write && xfer < chunk) { ++ /* Preserve short-write semantics for caller retry/error handling. */ ++ ret = total; ++ goto out; ++ } ++ } ++ i = j; ++ } ++ ++ ret = total; ++out: ++ if (have_saved) { ++ SetFilePointerEx(h, saved, NULL, FILE_BEGIN); ++ } ++ return ret; ++} ++ ++static ssize_t qio_channel_file_preadv(QIOChannel *ioc, ++ const struct iovec *iov, ++ size_t niov, ++ int64_t offset, ++ Error **errp) ++{ ++ return qio_channel_file_prw_win32(ioc, iov, niov, offset, false, errp); ++} ++ ++static ssize_t qio_channel_file_pwritev(QIOChannel *ioc, ++ const struct iovec *iov, ++ size_t niov, ++ int64_t offset, ++ Error **errp) ++{ ++ return qio_channel_file_prw_win32(ioc, iov, niov, offset, true, errp); ++} + #endif /* CONFIG_PREADV */ + + static int qio_channel_file_set_blocking(QIOChannel *ioc, +@@ -223,7 +357,11 @@ static int qio_channel_file_set_blocking(QIOChannel *ioc, + Error **errp) + { + #ifdef WIN32 +- /* not implemented */ ++ QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); ++ if (enabled || ++ GetFileType((HANDLE)_get_osfhandle(fioc->fd)) == FILE_TYPE_DISK) { ++ return 0; ++ } + error_setg_errno(errp, errno, "Failed to set FD nonblocking"); + return -1; + #else +@@ -237,16 +375,20 @@ static int qio_channel_file_set_blocking(QIOChannel *ioc, + } + + +-static off_t qio_channel_file_seek(QIOChannel *ioc, +- off_t offset, ++static int64_t qio_channel_file_seek(QIOChannel *ioc, ++ int64_t offset, + int whence, + Error **errp) + { + QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); +- off_t ret; ++ int64_t ret; + ++#ifdef WIN32 ++ ret = (int64_t)_lseeki64(fioc->fd, (int64_t)offset, whence); ++#else + ret = lseek(fioc->fd, offset, whence); +- if (ret == (off_t)-1) { ++#endif ++ if (ret == (int64_t)-1) { + error_setg_errno(errp, errno, + "Unable to seek to offset %lld whence %d in file", + (long long int)offset, whence); +@@ -314,7 +456,7 @@ static void qio_channel_file_class_init(ObjectClass *klass, + ioc_klass->io_writev = qio_channel_file_writev; + ioc_klass->io_readv = qio_channel_file_readv; + ioc_klass->io_set_blocking = qio_channel_file_set_blocking; +-#ifdef CONFIG_PREADV ++#if defined(CONFIG_PREADV) || defined(WIN32) + ioc_klass->io_pwritev = qio_channel_file_pwritev; + ioc_klass->io_preadv = qio_channel_file_preadv; + #endif +diff --git a/io/channel-null.c b/io/channel-null.c +index 49f1c80a54e1337aa39010ef39a5ea5de4c5392f..2032d26b3c14a28fc36aedc8a3f0248a4701abb9 100644 +--- a/io/channel-null.c ++++ b/io/channel-null.c +@@ -105,9 +105,9 @@ qio_channel_null_set_blocking(QIOChannel *ioc G_GNUC_UNUSED, + } + + +-static off_t ++static int64_t + qio_channel_null_seek(QIOChannel *ioc G_GNUC_UNUSED, +- off_t offset G_GNUC_UNUSED, ++ int64_t offset G_GNUC_UNUSED, + int whence G_GNUC_UNUSED, + Error **errp G_GNUC_UNUSED) + { +diff --git a/io/channel.c b/io/channel.c +index 620256f310dbeb060113e71055246ca29431d13d..03d721ec0d699d7c9bcbf2866881d53d7e6b25c0 100644 +--- a/io/channel.c ++++ b/io/channel.c +@@ -450,7 +450,7 @@ GSource *qio_channel_add_watch_source(QIOChannel *ioc, + + + ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov, +- size_t niov, off_t offset, Error **errp) ++ size_t niov, int64_t offset, Error **errp) + { + QIOChannelClass *klass = QIO_CHANNEL_GET_CLASS(ioc); + +@@ -468,7 +468,7 @@ ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov, + } + + ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen, +- off_t offset, Error **errp) ++ int64_t offset, Error **errp) + { + struct iovec iov = { + .iov_base = buf, +@@ -481,7 +481,7 @@ ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen, + int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp) + { + int ret = -1; +@@ -519,7 +519,7 @@ int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc, + const void *buf, + size_t buflen, +- off_t offset, ++ int64_t offset, + Error **errp) + { + struct iovec iov = { .iov_base = (char *)buf, .iov_len = buflen }; +@@ -527,7 +527,7 @@ int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc, + } + + ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov, +- size_t niov, off_t offset, Error **errp) ++ size_t niov, int64_t offset, Error **errp) + { + QIOChannelClass *klass = QIO_CHANNEL_GET_CLASS(ioc); + +@@ -545,7 +545,7 @@ ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov, + } + + ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen, +- off_t offset, Error **errp) ++ int64_t offset, Error **errp) + { + struct iovec iov = { + .iov_base = buf, +@@ -558,7 +558,7 @@ ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen, + int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp) + { + int ret = -1; +@@ -609,7 +609,7 @@ int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp) + { + int ret = qio_channel_preadv_all_eof(ioc, iov, niov, offset, errp); +@@ -629,7 +629,7 @@ int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc, + void *buf, + size_t buflen, +- off_t offset, ++ int64_t offset, + Error **errp) + { + struct iovec iov = { .iov_base = buf, .iov_len = buflen }; +@@ -639,7 +639,7 @@ int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_pread_all(QIOChannel *ioc, + void *buf, + size_t buflen, +- off_t offset, ++ int64_t offset, + Error **errp) + { + struct iovec iov = { .iov_base = buf, .iov_len = buflen }; +@@ -696,8 +696,8 @@ int qio_channel_get_peerpid(QIOChannel *ioc, + return 0; + } + +-off_t qio_channel_io_seek(QIOChannel *ioc, +- off_t offset, ++int64_t qio_channel_io_seek(QIOChannel *ioc, ++ int64_t offset, + int whence, + Error **errp) + { +diff --git a/migration/channel-block.c b/migration/channel-block.c +index 9cf383d4b57728b2561dbb45afd44c72df15061b..8a0893fb7e4d4cb9e5e91d1418e99674f4562c23 100644 +--- a/migration/channel-block.c ++++ b/migration/channel-block.c +@@ -101,7 +101,7 @@ static ssize_t + qio_channel_block_preadv(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp) + { + QIOChannelBlock *bioc = QIO_CHANNEL_BLOCK(ioc); +@@ -122,7 +122,7 @@ static ssize_t + qio_channel_block_pwritev(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp) + { + QIOChannelBlock *bioc = QIO_CHANNEL_BLOCK(ioc); +@@ -152,9 +152,9 @@ qio_channel_block_set_blocking(QIOChannel *ioc, + } + + +-static off_t ++static int64_t + qio_channel_block_seek(QIOChannel *ioc, +- off_t offset, ++ int64_t offset, + int whence, + Error **errp) + { +@@ -169,7 +169,7 @@ qio_channel_block_seek(QIOChannel *ioc, + break; + case SEEK_END: + error_setg(errp, "Size of VMstate region is unknown"); +- return (off_t)-1; ++ return (int64_t)-1; + default: + g_assert_not_reached(); + } +diff --git a/migration/channel-block.h b/migration/channel-block.h +index 31673824e6971398b73f55cfb36a521ca0d91791..b2f6768f6ce5a058dc0a082ccd4d0d9297befd3f 100644 +--- a/migration/channel-block.h ++++ b/migration/channel-block.h +@@ -39,7 +39,7 @@ OBJECT_DECLARE_SIMPLE_TYPE(QIOChannelBlock, QIO_CHANNEL_BLOCK) + struct QIOChannelBlock { + QIOChannel parent; + BlockDriverState *bs; +- off_t offset; ++ int64_t offset; + }; + + +diff --git a/migration/file.c b/migration/file.c +index 8ba1de2006eed5a643b7394b9bc4c83cb8d9b4af..5419455d6d314e7529c20116b274d61ce1e38e99 100644 +--- a/migration/file.c ++++ b/migration/file.c +@@ -108,7 +108,11 @@ QIOChannel *file_connect_outgoing(MigrationState *s, + goto out; + } + ++#ifdef WIN32 ++ if (_chsize_s(fioc->fd, (int64_t)offset) != 0) { ++#else + if (ftruncate(fioc->fd, offset)) { ++#endif + error_setg_errno(errp, errno, + "failed to truncate migration file to offset %" PRIx64, + offset); +diff --git a/migration/multifd.h b/migration/multifd.h +index fbc35702b062fdc3213ce92baed35994f5967c2b..2ce94f07403fe1cbe1655728e13c58eeb53dbbe5 100644 +--- a/migration/multifd.h ++++ b/migration/multifd.h +@@ -133,7 +133,7 @@ struct MultiFDRecvData { + void *opaque; + size_t size; + /* for preadv */ +- off_t file_offset; ++ int64_t file_offset; + }; + + typedef struct { +diff --git a/migration/qemu-file.c b/migration/qemu-file.c +index df3f96fb24005d0fcf397bf8035b460a04eb2490..4aef4856599e83c6bb72012dbea3f163ab838add 100644 +--- a/migration/qemu-file.c ++++ b/migration/qemu-file.c +@@ -532,7 +532,7 @@ void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, size_t size) + } + + void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen, +- off_t pos) ++ int64_t pos) + { + Error *err = NULL; + +@@ -550,7 +550,7 @@ void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen, + } + + +-size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos, ++size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, int64_t pos, + Error **errp) + { + if (f->last_error) { +@@ -566,10 +566,10 @@ size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos, + return buflen; + } + +-void qemu_set_offset(QEMUFile *f, off_t off, int whence) ++void qemu_set_offset(QEMUFile *f, int64_t off, int whence) + { + Error *err = NULL; +- off_t ret; ++ int64_t ret; + + if (qemu_file_is_writable(f)) { + qemu_fflush(f); +@@ -580,20 +580,20 @@ void qemu_set_offset(QEMUFile *f, off_t off, int whence) + } + + ret = qio_channel_io_seek(f->ioc, off, whence, &err); +- if (ret == (off_t)-1) { ++ if (ret == (int64_t)-1) { + qemu_file_set_error_obj(f, -EIO, err); + } + } + +-off_t qemu_get_offset(QEMUFile *f) ++int64_t qemu_get_offset(QEMUFile *f) + { + Error *err = NULL; +- off_t ret; ++ int64_t ret; + + qemu_fflush(f); + + ret = qio_channel_io_seek(f->ioc, 0, SEEK_CUR, &err); +- if (ret == (off_t)-1) { ++ if (ret == (int64_t)-1) { + qemu_file_set_error_obj(f, -EIO, err); + } + return ret; +diff --git a/migration/qemu-file.h b/migration/qemu-file.h +index 966766788ddfb11e08eb8b059d43c69a66260818..c5d2a984611da615e8561866af954f6e778780bf 100644 +--- a/migration/qemu-file.h ++++ b/migration/qemu-file.h +@@ -72,11 +72,11 @@ QEMUFile *qemu_file_get_return_path(QEMUFile *f); + int qemu_fflush(QEMUFile *f); + bool qemu_file_set_blocking(QEMUFile *f, bool block, Error **errp); + int qemu_file_get_to_fd(QEMUFile *f, int fd, size_t size); +-void qemu_set_offset(QEMUFile *f, off_t off, int whence); +-off_t qemu_get_offset(QEMUFile *f); ++void qemu_set_offset(QEMUFile *f, int64_t off, int whence); ++int64_t qemu_get_offset(QEMUFile *f); + void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen, +- off_t pos); +-size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos, ++ int64_t pos); ++size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, int64_t pos, + Error **errp); + + QIOChannel *qemu_file_get_ioc(QEMUFile *file); +diff --git a/migration/ram.c b/migration/ram.c +index e6db3bf523855ee1ea20e79495326979f00d3192..410cfa6a1c2bfe84308d19c36bd8a00157226581 100644 +--- a/migration/ram.c ++++ b/migration/ram.c +@@ -1010,7 +1010,7 @@ static uint64_t physical_memory_sync_dirty_bitmap(RAMBlock *rb, + unsigned long *dest = rb->bmap; + + /* start address and length is aligned at the start of a word? */ +- if (((word * BITS_PER_LONG) << TARGET_PAGE_BITS) == ++ if ((((ram_addr_t)word * BITS_PER_LONG) << TARGET_PAGE_BITS) == + (start + rb->offset) && + !(length & ((BITS_PER_LONG << TARGET_PAGE_BITS) - 1))) { + int k; +@@ -4137,8 +4137,8 @@ static bool handle_zero_mapped_ram(RAMBlock *block, unsigned long from_bit_idx, + return true; + } + +- size = TARGET_PAGE_SIZE * (to_bit_idx - from_bit_idx); +- offset = from_bit_idx << TARGET_PAGE_BITS; ++ size = (size_t)TARGET_PAGE_SIZE * (to_bit_idx - from_bit_idx); ++ offset = ((ram_addr_t)from_bit_idx) << TARGET_PAGE_BITS; + host = host_from_ram_block_offset(block, offset); + if (!host) { + error_setg(errp, "zero page outside of ramblock %s range", +@@ -4172,8 +4172,8 @@ static bool read_ramblock_mapped_ram(QEMUFile *f, RAMBlock *block, + /* Non-zero pages */ + clear_bit_idx = find_next_zero_bit(bitmap, num_pages, set_bit_idx + 1); + +- unread = TARGET_PAGE_SIZE * (clear_bit_idx - set_bit_idx); +- offset = set_bit_idx << TARGET_PAGE_BITS; ++ unread = (size_t)TARGET_PAGE_SIZE * (clear_bit_idx - set_bit_idx); ++ offset = ((ram_addr_t)set_bit_idx) << TARGET_PAGE_BITS; + + while (unread > 0) { + host = host_from_ram_block_offset(block, offset); diff --git a/patches/series.txt b/patches/series.txt index 1de7565..b499927 100644 --- a/patches/series.txt +++ b/patches/series.txt @@ -14,3 +14,5 @@ vendor/qemu qemu-whpx-win10-compat.patch vendor/qemu qemu-whpx-win10-startup-ipis.patch vendor/qemu qemu-whpx-nested-virt-nonfatal.patch vendor/qemu qemu-win32-coroutine-fiber-commit.patch +vendor/qemu qemu-win32-mapped-ram-io.patch +vendor/qemu qemu-intel-whpx-suspend.patch From 347840490e1a75cf236063aa0c2b607fa672f33a Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 07:48:14 +0800 Subject: [PATCH 03/10] feat(patches): add reims-vgpu/metal2vulkan snapshot replay and build pipeline support --- .github/workflows/build-runtime.yml | 29 +- patches/README.md | 21 +- patches/metal2vulkan-snapshot-replay.patch | 525 +++ patches/reims-vgpu-cargo-lock.patch | 28 - patches/reims-vgpu-snapshot-replay.patch | 4309 ++++++++++++++++++++ patches/series.txt | 29 +- scripts/apply-patch-series.ps1 | 15 +- scripts/pack-runtime.ps1 | 86 +- 8 files changed, 4972 insertions(+), 70 deletions(-) create mode 100644 patches/metal2vulkan-snapshot-replay.patch delete mode 100644 patches/reims-vgpu-cargo-lock.patch create mode 100644 patches/reims-vgpu-snapshot-replay.patch diff --git a/.github/workflows/build-runtime.yml b/.github/workflows/build-runtime.yml index 6f6650d..376e939 100644 --- a/.github/workflows/build-runtime.yml +++ b/.github/workflows/build-runtime.yml @@ -142,6 +142,21 @@ jobs: if ($LASTEXITCODE) { throw 'reims-util fetch failed' } git -C $utilRepo checkout -q --detach FETCH_HEAD if ($LASTEXITCODE) { throw 'reims-util checkout failed' } + $m2vRepo = Join-Path $env:RUNNER_TEMP 'metal2vulkan' + $cargoToml = Get-Content -Raw -LiteralPath (Join-Path $work 'Cargo.toml') + if ($cargoToml -match 'metal2vulkan\s*=\s*\{[^}]*rev\s*=\s*"([0-9a-f]{40})"') { + $m2vRev = $Matches[1] + } else { + $lockTxt = Get-Content -Raw -LiteralPath (Join-Path $work 'Cargo.lock') + if ($lockTxt -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.toml or Cargo.lock' } + $m2vRev = $Matches[1] + } + git init -q $m2vRepo + if ($LASTEXITCODE) { throw 'metal2vulkan init failed' } + git -C $m2vRepo fetch -q --depth 1 https://github.com/steelbrain/metal2vulkan.git $m2vRev + if ($LASTEXITCODE) { throw 'metal2vulkan fetch failed' } + git -C $m2vRepo checkout -q --detach FETCH_HEAD + if ($LASTEXITCODE) { throw 'metal2vulkan checkout failed' } $short = (git -C $work rev-parse --short=7 HEAD).Trim() $releaseId = "$short${{ needs.resolve.outputs.suffix }}" "short=$short" >> $env:GITHUB_OUTPUT @@ -151,7 +166,7 @@ jobs: # conflict without touching the patch (AGENTS.md rule 4). $resultFile = Join-Path $env:RUNNER_TEMP 'patches.json' try { - pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -UtilRepo $utilRepo -ResultFile $resultFile + pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -UtilRepo $utilRepo -Metal2VulkanRepo $m2vRepo -ResultFile $resultFile $ok = $LASTEXITCODE -eq 0 } finally { if (Test-Path $resultFile) { @@ -163,11 +178,20 @@ jobs: } } if (-not $ok) { throw 'patch queue does not apply' } + $cargoHome = Join-Path $env:RUNNER_TEMP 'cargo' + $m2vFwd = $m2vRepo.Replace('\', '/') + $cargoCfg = @" + [patch."https://github.com/steelbrain/metal2vulkan"] + metal2vulkan = { path = "$m2vFwd/crates/metal2vulkan" } + metal2vulkan-runtime = { path = "$m2vFwd/crates/metal2vulkan-runtime" } + "@ -replace '(?m)^ ', '' + [IO.File]::WriteAllText((Join-Path $cargoHome 'config.toml'), ($cargoCfg.Replace("`r`n", "`n") + "`n"), [Text.UTF8Encoding]::new($false)) "UPSTREAM_DIR=$work" >> $env:GITHUB_ENV "REIMS_UTIL_DIR=$utilRepo" >> $env:GITHUB_ENV + "METAL2VULKAN_DIR=$m2vRepo" >> $env:GITHUB_ENV "SHORT_COMMIT=$short" >> $env:GITHUB_ENV "RELEASE_ID=$releaseId" >> $env:GITHUB_ENV - "CARGO_HOME=$(Join-Path $env:RUNNER_TEMP 'cargo')" >> $env:GITHUB_ENV + "CARGO_HOME=$cargoHome" >> $env:GITHUB_ENV "XDG_DATA_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-data')" >> $env:GITHUB_ENV "XDG_CACHE_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-cache')" >> $env:GITHUB_ENV @@ -200,6 +224,7 @@ jobs: & ./scripts/pack-runtime.ps1 ` -ReimsRepo $env:UPSTREAM_DIR ` -UtilRepo $env:REIMS_UTIL_DIR ` + -Metal2VulkanRepo $env:METAL2VULKAN_DIR ` -CargoHome $env:CARGO_HOME ` -QemuDir (Join-Path $env:XDG_DATA_HOME 'reims-ctl\qemu\current') ` -Msys2 '${{ steps.msys2.outputs.msys2-location }}' ` diff --git a/patches/README.md b/patches/README.md index 93189c4..cfe32b1 100644 --- a/patches/README.md +++ b/patches/README.md @@ -4,12 +4,12 @@ ## 维护原则 -1. **不长期维护 fork**:所有底层修复优先向相应上游仓库提交 PR。目标仓库包括 [`reims-vgpu`](https://github.com/steelbrain/reims-vgpu)、[`qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu) 和 [`reims-util`](https://github.com/steelbrain/reims-util)。 +1. **不长期维护 fork**:所有底层修复优先向相应上游仓库提交 PR。目标仓库包括 [`reims-vgpu`](https://github.com/steelbrain/reims-vgpu)、[`qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)、[`reims-util`](https://github.com/steelbrain/reims-util) 和 [`metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。 2. **人工提 PR,冲突即停**:更新上游基线时由 [`scripts/apply-patch-series.ps1`](../scripts/apply-patch-series.ps1) 按顺序执行 `git apply --check`。已合入上游(反向检查通过)的补丁会自动跳过并开 Issue 提醒退役;遇到冲突时立刻中止构建,不自动改写补丁。 3. **文件格式约束**:所有 `.patch` 文件必须为 **无 BOM、LF 行尾**(由 `.gitattributes` 中的 `*.patch -text` 约束),避免 `git apply` 在 Windows 上失败。 4. **来源透明与协议兼容**:每个运行时包的 `manifest.json` 与 `patches/` 目录必须如实记录实际应用的全部补丁及哈希;本目录补丁不适用根目录的 Apache-2.0,而是遵循目标上游兼容协议(详见 [`patches/LICENSE`](LICENSE))。 -本地构建时,`-UtilRepo` 指向 `reims-ctl` 固定版本的 `reims-util` 工作树。用相同的 MSYS2 CLANG64 工具链安装其中的 `reims-util` 后,把同一工作树传给打包脚本。 +本地构建时,`-UtilRepo` 指向 `reims-ctl` 固定版本的 `reims-util` 工作树,`-Metal2VulkanRepo` 指向 `reims-vgpu/Cargo.toml` 固定版本的 `metal2vulkan` 工作树(并通过 `$CARGO_HOME/config.toml` 的 `[patch."https://github.com/steelbrain/metal2vulkan"]` 覆盖,使 `reims-vgpu/Cargo.lock` 与上游保持逐字节一致)。用相同的 MSYS2 CLANG64 工具链构建后,把同一组工作树传给打包脚本。 --- @@ -19,13 +19,14 @@ | 补丁文件 | 目标仓库与路径 | 解决的问题 | 当前状态 | | :--- | :--- | :--- | :--- | -| [`reims-vgpu-cargo-lock.patch`](reims-vgpu-cargo-lock.patch) | `reims-vgpu` (`Cargo.lock`) | 补齐 `metal2vulkan` 三个 crate 的 `source` 锁定信息,使源码包与实际 Cargo 构建逐字节一致 | 仅用于构建可复现;上游补齐 `Cargo.lock` 后删除 | | [`reims-vgpu-win32-unicode-input.patch`](reims-vgpu-win32-unicode-input.patch) | `reims-vgpu` (`crates/reims-vgpu-window`) | 通过 `SDL_SetWindowsMessageHook` 在设置 `REIMS_GO_INPUT_URL`(仅限 `127.0.0.1`)时转发非物理按键的 `WM_CHAR`/`WM_UNICHAR`/`WM_IME_CHAR`,解决 Windows IME 与中文输入被吞 | 待编入 `alpha` 冒烟验证后提 PR | | [`reims-vgpu-display-fixed-mode.patch`](reims-vgpu-display-fixed-mode.patch) | `reims-vgpu` (`crates/reims-vgpu-window`, `crates/reims-vgpu`) | 新增 `REIMS_VGPU_WINDOW_FIXED_MODE=1` 将全屏/窗口物理尺寸与客体渲染分辨率解耦,按 `scale * (guest_w / drawable_w)` 推导有效 DPI,并在帧尺寸与目标区域不一致时自动走线性采样 GPU 着色器缩放(支持 4K 全屏 1.5× 超采样 `5120×2880` HiDPI) | `git apply --check` 在 `3731afd9` 通过;待编入 `alpha` 真机验证后提 PR | | [`reims-ctl-win32-random-bytes.patch`](reims-ctl-win32-random-bytes.patch) | `reims-vgpu` (`crates/reims-ctl/src/vm.rs`) | 修复 Windows 下打不开 `/dev/urandom` 时回退到低熵时间戳种子的缺陷,改用标准库 `RandomState`(底层调用 `ProcessPrng`)生成 MAC/ROM 随机字节 | `git apply --check` 通过;待编入 `alpha` 验证后提 PR | | [`reims-ctl-virtio-discard-iothread.patch`](reims-ctl-virtio-discard-iothread.patch) | `reims-vgpu` (`crates/reims-ctl/src/qemu.rs`) | 为 VirtIO 系统盘补齐 `discard=unmap`(与 NVMe 一致透传客体 TRIM)并启用独立 `-object iothread,id=io0`,避免块完成回调与 QEMU 主循环争抢 | `git apply --check` 在 `3731afd9` 与上游 `main` 均通过;真机实测与休眠唤醒通过,暂留 `patches/` 待编入 `alpha` 验证后提 PR | | [`reims-ctl-qcow2-l2-cache.patch`](reims-ctl-qcow2-l2-cache.patch) | `reims-vgpu` (`crates/reims-ctl/src/qemu.rs`) | 按 `qcow2` 文件头虚拟容量与簇大小计算全覆盖所需 `l2-cache-size`(上限 32 MiB,仅大于 8 MiB 默认值时追加),避免非 Linux 宿主默认 8 MiB 上限仅覆盖 64 GiB | `git apply --check` 在 `3731afd9` 与上游 `main` 均通过;128 GiB 镜像真机实测通过,暂留 `patches/` 待编入 `alpha` 验证后提 PR | +| [`reims-vgpu-snapshot-replay.patch`](reims-vgpu-snapshot-replay.patch) | `reims-vgpu` (`crates/reims-vgpu*`) | 实现 GPU 静止、实时对象日志与 `RVGSNAP1` 二进制编解码(含统一计数边界校验、因果父对象保留、`whole_library_key` 索引及未附着延迟 SurfaceCache 持久化)、显存与事件保存/重放及严格错误传播 | 单元测试、双进程 RTX A5000 Vulkan 测试及 Intel macOS 26.7.3 同 PID Metal 读回实测通过;待提 PR | | [`reims-util-parallel-offline-download.patch`](reims-util-parallel-offline-download.patch) | `reims-util` (`src/http.rs`, `src/installer.rs`) | 对有 Apple 分块校验数据的完整离线包并发请求四段,按顺序校验并写入镜像。分段读取失败时用原有单路下载继续 | 待编入 `alpha` 冒烟验证 | +| [`metal2vulkan-snapshot-replay.patch`](metal2vulkan-snapshot-replay.patch) | `metal2vulkan` (`crates/metal2vulkan-runtime/src/`) | 暴露 Private/Shared/Managed 缓冲与纹理(含多层/多 Mip)及事件计数的快照读出与精确地址/内容回写接口 | 随 `reims-vgpu-snapshot-replay.patch` 在干净 checkout 构建并实测通过;待提 PR | | [`qemu-whpx-win10-compat.patch`](qemu-whpx-win10-compat.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 修复 Windows 10 19045 上两处 WHPX 必现崩溃(探测 TSC deadline 污染主分区、`WHvResetPartition` 未判空) | 已在 Win10 19045 真机验证并随稳定运行时发布;待提 PR | | [`qemu-whpx-win10-startup-ipis.patch`](qemu-whpx-win10-startup-ipis.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 在 Win10 开启 `kernel-irqchip` 且多核启动时经 `WHvRequestInterrupt` 转发 INIT/SIPI,避免 XNU 从核卡死(依赖上一项) | 8/12 核冷启动通过;客体软重启待验证,待提 PR | | [`qemu-whpx-nested-virt-nonfatal.patch`](qemu-whpx-nested-virt-nonfatal.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 部分 Win11 宿主设置嵌套虚拟化属性返回 `0x80370302` 时改为警告并清零特性位,保留 `kernel-irqchip=on` 加速(依赖前两项) | 待编入 `alpha` 并在 Win11 真机验证后提 PR | @@ -121,6 +122,20 @@ 2. 补齐 WHPX x86-64 vCPU/LAPIC/x2APIC/TSC 寄存器与 AppleSMC、`reims-graphics-pci` 设备 VMState 保存恢复回调(含损坏快照向 QMP 返回错误并保留挂起文件)。 - **实测证据**:7 项 QMP 闸门回归全部通过;Windows 11 WHPX + RTX A5000 + Intel macOS 26.7.3 解锁桌面实测跨完整 QEMU 退出及真实 Windows 重启恢复,首帧 1920×1080 SHA-256 完全一致,原应用 PID / Metal 队列 / Private 资源读回 100% 匹配。 +### 11. `metal2vulkan-snapshot-replay.patch` +- **建议 PR 标题**:`runtime: add snapshot readback and exact-address restore hooks for buffers, textures, and events` +- **目标**:`steelbrain/metal2vulkan`(`crates/metal2vulkan-runtime/src/{block,device,event,floor,lib,memory,places}.rs`) +- **最小修复**:为 `metal2vulkan-runtime` 增加共享/私有池块分配恢复、Private 缓冲/纹理全子资源(含多 mip/slice)内容读回与回写、以及事件值读写接口,使上层 `reims-vgpu` 可在宿主进程重启后原位重建客体可见 GPU 地址与显存内容。 + +### 12. `reims-vgpu-snapshot-replay.patch` +- **建议 PR 标题**:`graphics & pool: add RVGSNAP1 device quiesce, live object log, and strict snapshot replay` +- **目标**:`steelbrain/reims-vgpu`(`crates/reims-vgpu*`) +- **最小修复**: + 1. 统一 `quiesce_device()` 静止流程(排空传输与编译任务、刷写表面缓存并等待 GPU 空闲),由 `reims-vgpu-c` 暴露保存/加载 C ABI 供 `reims-graphics-pci` VMState 调用。 + 2. 新增 `RVGSNAP1` 二进制快照编解码,由 `Dec::checked_count` / `read_vec` 在分配前统一按剩余字节和最小条目大小校验计数并校验尾部无多余字节。 + 3. 完整保存与回放共享/私有内存池、实时对象日志(含 `whole_library_key` 索引与因果父对象保留,避免 ARC 释放 `MTLLibrary` 后导致活跃管线回放失败)、事件计数、Private 缓冲/纹理与未附着延迟 `SurfaceCache`(含 VA-API P010 视频帧),任何关键对象或显存保存/恢复失败均向 QMP 返回错误且不解除静止。 +- **实测证据**:干净上游 checkout 通过 `reims-vgpu-graphics` 与 `reims-vgpu` 快照单元测试及 `reims-vgpu-c` 零警告 release 构建;RTX A5000 双进程 Vulkan 读回与 Intel macOS 26.7.3 解锁桌面跨进程同 PID Metal 读回(Buffer/Texture/Event/SharedEvent + 恢复后原队列继续 Compute 变异)100% 通过。 + --- ## 关注中的上游 PR 与演进 diff --git a/patches/metal2vulkan-snapshot-replay.patch b/patches/metal2vulkan-snapshot-replay.patch new file mode 100644 index 0000000..549eae8 --- /dev/null +++ b/patches/metal2vulkan-snapshot-replay.patch @@ -0,0 +1,525 @@ +diff --git a/crates/metal2vulkan-runtime/src/block.rs b/crates/metal2vulkan-runtime/src/block.rs +index 0ac77ecac0f3abb9e9b76fb82d17c3536e22f4f5..426d025513a2f04e97f31efa66d1632635f7254d 100644 +--- a/crates/metal2vulkan-runtime/src/block.rs ++++ b/crates/metal2vulkan-runtime/src/block.rs +@@ -54,6 +54,12 @@ impl Block { + Block { claim } + } + ++ /// Returns capture/replay address metadata for this block (if supported). ++ pub fn capture_info(&self) -> Option { ++ let (core, block) = self.held().ok()?; ++ core.pool.capture_info(&block.memory) ++ } ++ + /// Whether the block is of `core`'s device. + pub(crate) fn is_of(&self, core: &Arc) -> bool { + Weak::as_ptr(&self.claim.core) == Arc::as_ptr(core) +diff --git a/crates/metal2vulkan-runtime/src/device.rs b/crates/metal2vulkan-runtime/src/device.rs +index 8edf1f27202f9a19b19cc4a4484d1e31341b8ab1..68f79440cc7727f2fae6063756380fe7a85ce7f9 100644 +--- a/crates/metal2vulkan-runtime/src/device.rs ++++ b/crates/metal2vulkan-runtime/src/device.rs +@@ -273,6 +273,7 @@ pub(crate) struct Core { + /// every render pipeline takes its colour flag, and a draw reads an attachment of its pass + /// with the image in the feedback layout. + pub(crate) feedback_loop: bool, ++ pub(crate) capture_replay: bool, + /// `VK_EXT_device_fault`'s command, where device creation enabled it (where the device lists + /// it): a lost device's fault report, read once, at its first loss (`crate::fault`). + pub(crate) fault: Option, +@@ -860,6 +861,7 @@ impl Device { + ticks, + calibrated, + feedback_loop: capabilities.feedback_loop, ++ capture_replay: capabilities.buffer_device_address_capture_replay, + fault, + indirect, + attachment_reads: capabilities.attachment_reads, +@@ -1140,6 +1142,41 @@ impl Device { + /// allocation past the device's count; [`Limit::AllocationNotMapped`](crate::Limit::AllocationNotMapped) + /// where the consumer did not map the allocation the take made; [`Error::Vulkan`] where the + /// device is out of memory or lost; [`Error::Quiesced`]. ++ /// Whether Vulkan `bufferDeviceAddressCaptureReplay` is enabled on this device. ++ pub fn buffer_device_address_capture_replay(&self) -> bool { ++ self.shared.core.capture_replay ++ } ++ ++ /// Waits non-destructively until all in-flight GPU work has completed and retired. ++ pub fn wait_idle(&self) -> Result<(), Error> { ++ let core = &self.shared.core; ++ if core.closed() { ++ return Err(Error::Quiesced); ++ } ++ // Wait for submitted command buffers to retire on the completion thread. ++ let deadline = Instant::now() + Duration::from_secs(10); ++ while core.pool.in_flight() > 0 && Instant::now() < deadline { ++ std::thread::sleep(Duration::from_millis(1)); ++ } ++ // SAFETY: `device` is live and wait_idle synchronizes all host queues. ++ let _q = lock(&core.queues.runtime); ++ unsafe { core.device.device_wait_idle() }.map_err(Error::vulkan("vkDeviceWaitIdle"))?; ++ Ok(()) ++ } ++ ++ /// Replays a previously captured block at its exact Vulkan device address. ++ pub fn take_block_replayed(&self, capture: memory::BlockCaptureInfo) -> Result { ++ let core = &self.shared.core; ++ if core.closed() { ++ return Err(Error::Quiesced); ++ } ++ let memory = core.pool.take_replayed(core, capture, crate::counters::Site::take(capture.class))?; ++ let info = memory.info(); ++ let block = memory::Block::new(memory, Arc::clone(core)); ++ Ok(Block::claim(core, info, block)) ++ } ++ ++ /// Allocates a new GPU memory block of `class` and `len` bytes. + pub fn take_block(&self, class: MemoryClass, len: u64) -> Result { + let core = &self.shared.core; + if core.closed() { +diff --git a/crates/metal2vulkan-runtime/src/event.rs b/crates/metal2vulkan-runtime/src/event.rs +index fe95046625fb1d1c81e2925458c22c4dd3641197..8b47e5604f50dec0549733c515ce80e02dbe348e 100644 +--- a/crates/metal2vulkan-runtime/src/event.rs ++++ b/crates/metal2vulkan-runtime/src/event.rs +@@ -140,6 +140,35 @@ impl Event { + } + } + ++impl Event { ++ /// Reads the current signaled value of this timeline event (for checkpointing). ++ pub fn signaled_value(&self) -> u64 { ++ let inner = &self.inner; ++ let state = lock(&inner.state); ++ let floor = state.observed.max(state.floor); ++ inner.reached(None).map_or(floor, |reached| reached.max(floor)) ++ } ++ ++ /// Restores the timeline semaphore and CPU floor to `value` on a freshly created event. ++ pub fn restore_signaled_value(&self, value: u64) -> Result<(), Error> { ++ if value == 0 { ++ return Ok(()); ++ } ++ let inner = &self.inner; ++ let info = vk::SemaphoreSignalInfo::default() ++ .semaphore(inner.semaphore) ++ .value(value); ++ // SAFETY: `semaphore` is a live timeline semaphore on `inner.core.device`. ++ unsafe { inner.core.device.signal_semaphore(&info) } ++ .map_err(Error::vulkan("vkSignalSemaphore"))?; ++ let mut state = lock(&inner.state); ++ state.floor = state.floor.max(value); ++ state.observed = state.observed.max(value); ++ inner.changed.notify_all(); ++ Ok(()) ++ } ++} ++ + impl SharedEvent { + /// `signaledValue`: the higher of the semaphore's value and the host's floor, the semaphore's + /// value being one a host wait confirmed: a counter read finds it, and a wait with a timeout +diff --git a/crates/metal2vulkan-runtime/src/floor.rs b/crates/metal2vulkan-runtime/src/floor.rs +index 0e165934f4b7534d0a093b1a22bcd763a47db8d7..90c7f9e354af205aa5a6b2fbeb506e58fbba1ab8 100644 +--- a/crates/metal2vulkan-runtime/src/floor.rs ++++ b/crates/metal2vulkan-runtime/src/floor.rs +@@ -1079,6 +1079,8 @@ pub struct Capabilities { + /// [`ATTACHMENT_READ_EXTENSIONS`]: a draw reads an attachment through the attachment feedback + /// loop, the feedback layout its image moves to and the flag every render pipeline takes. + pub feedback_loop: bool, ++ /// Whether `bufferDeviceAddressCaptureReplay` is enabled for checkpoint/restore. ++ pub buffer_device_address_capture_replay: bool, + /// The features device creation enables: every one the floor requires, each of the optional, + /// step-rate, min-LOD, fill-mode, alpha-to-one, quad-control, pixel-interlock, linear-attachment + /// and fault-report ones the device reports, the attachment-read ones where +@@ -1425,6 +1427,10 @@ pub(crate) fn decide(device: &Queried) -> Result { + let Some((queue_family, _)) = family.filter(|_| missing.is_empty()) else { + return Err(BelowFloor { missing }); + }; ++ let capture_replay = reported.vulkan12.buffer_device_address_capture_replay == vk::TRUE; ++ if capture_replay { ++ features.vulkan12.buffer_device_address_capture_replay = vk::TRUE; ++ } + for feature in (OPTIONAL.iter().chain(STEP_RATES)) + .chain(MIN_LOD_CLAMPS) + .chain(FILL_MODES) +@@ -1491,6 +1497,7 @@ pub(crate) fn decide(device: &Queried) -> Result { + texel_offset_operand: features.maintenance8.maintenance8 == vk::TRUE, + attachment_reads, + feedback_loop, ++ buffer_device_address_capture_replay: capture_replay, + features, + extensions: DEVICE_EXTENSIONS + .iter() +diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs +index a2d59cc6f31eb64307c1a886fe7cf75f401511b1..557a1a4b213773df976895f703cd4c037ad2602b 100644 +--- a/crates/metal2vulkan-runtime/src/lib.rs ++++ b/crates/metal2vulkan-runtime/src/lib.rs +@@ -100,7 +100,7 @@ pub use host_bytes::HostBytes; + pub use import::ImportHandle; + pub use indirect::{IndirectCommandBuffer, IndirectCommandBufferDescriptor, IndirectCommandType}; + pub use instance::{Instance, PhysicalDevice}; +-pub use memory::{AllocationId, AllocationInfo, BlockId, BlockInfo, BlockMappings, MemoryClass}; ++pub use memory::{AllocationId, AllocationInfo, BlockCaptureInfo, BlockId, BlockInfo, BlockMappings, MemoryClass}; + /// `MTLLibrary`: the translator's, read from AIR or a metallib. + /// `MTLSamplerDescriptor`: the translator's. + pub use metal2vulkan::bind::SamplerDescriptor; +diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs +index 173e0858f2e6d07660cafd5f7893aee280f2dcdc..2864f4ba6b48a4892e6d9651548c75a4babcf395 100644 +--- a/crates/metal2vulkan-runtime/src/memory.rs ++++ b/crates/metal2vulkan-runtime/src/memory.rs +@@ -235,8 +235,28 @@ impl AllocationId { + /// device is torn down. It is a range of one allocation, whose one `VkBuffer`, with every buffer + /// usage and a device address, spans it; an imported or exported block is the whole of an + /// allocation of its own. Only an exported block is exportable. ++/// Capture/replay address metadata for restoring a block at its exact Vulkan device address. ++#[derive(Clone, Copy, Debug, PartialEq, Eq)] ++pub struct BlockCaptureInfo { ++ /// Storage mode (`Shared` or `Private`). ++ pub class: MemoryClass, ++ /// Full parent Vulkan allocation length in bytes. ++ pub alloc_len: u64, ++ /// Offset of this block inside its parent allocation. ++ pub offset: u64, ++ /// Block length in bytes. ++ pub len: u64, ++ /// Guest-visible `VkDeviceAddress` of this block's first byte. ++ pub gpu_address: u64, ++ /// Opaque capture address of the parent `VkBuffer`. ++ pub opaque_buffer_address: u64, ++ /// Opaque capture address of the parent `VkDeviceMemory`. ++ pub opaque_memory_address: u64, ++} ++ + #[non_exhaustive] + #[derive(Clone, Copy, Debug)] ++/// Metadata describing an allocated GPU memory block. + pub struct BlockInfo { + /// The block's number. + pub id: BlockId, +@@ -611,6 +631,10 @@ struct Allocation { + buffer: vk::Buffer, + /// The device address of its first byte. + address: u64, ++ /// Opaque capture address of `buffer` (0 if capture-replay unsupported). ++ opaque_buffer_address: u64, ++ /// Opaque capture address of `memory` (0 if capture-replay unsupported). ++ opaque_memory_address: u64, + len: u64, + mapping: Option, + device_local: bool, +@@ -823,6 +847,8 @@ struct State { + /// The internal the block-maker thread took up and is making ([`run`]). + making: Option, + stop: bool, ++ replaying: bool, ++ making_ahead: bool, + next_id: u32, + next_allocation: u32, + /// The allocations [`BlockMappings::map`] accepted whose unmap has not run. +@@ -952,6 +978,8 @@ impl Pool { + asked: [true; INTERNALS], + making: None, + stop: false, ++ replaying: false, ++ making_ahead: false, + next_id: 1, + next_allocation: 1, + mapped: HashSet::new(), +@@ -1368,6 +1396,158 @@ impl Pool { + } + } + ++ /// Returns capture/replay info for a pool block, if capture-replay is enabled. ++ pub(crate) fn capture_info(&self, memory: &Memory) -> Option { ++ if memory.own.is_some() { ++ return None; ++ } ++ let state = self.lock(); ++ let alloc = state.allocations[memory.class.index()] ++ .iter() ++ .find(|a| a.memory == memory.memory)?; ++ ++ Some(BlockCaptureInfo { ++ class: memory.class, ++ alloc_len: alloc.len, ++ offset: memory.base, ++ len: memory.len, ++ gpu_address: memory.address, ++ opaque_buffer_address: alloc.opaque_buffer_address, ++ opaque_memory_address: alloc.opaque_memory_address, ++ }) ++ } ++ ++ /// Replays a previously captured pool block at its exact Vulkan device address. ++ pub(crate) fn take_replayed( ++ &self, ++ core: &Core, ++ cap: BlockCaptureInfo, ++ site: Site, ++ ) -> Result { ++ let index = cap.class.index(); ++ // 1. Check if the parent allocation is already present (e.g. another sub-block restored it, ++ // or a pre-stocked idle reserve landed at the exact same address!). ++ { ++ let mut state = self.lock(); ++ if state.stop { ++ return Err(Error::Quiesced); ++ } ++ let id = number(&mut state)?; ++ let want_base = cap.gpu_address.saturating_sub(cap.offset); ++ if let Some(alloc) = state.allocations[index].iter_mut().find(|a| { ++ a.address == want_base ++ && a.opaque_buffer_address == cap.opaque_buffer_address ++ && a.opaque_memory_address == cap.opaque_memory_address ++ && a.len == cap.alloc_len ++ }) { ++ if alloc.free.take_at(cap.offset, cap.len) { ++ let carve = alloc.carve(cap.offset); ++ alloc.live += 1; ++ alloc.placed += cap.len; ++ alloc.ahead = false; ++ self.counters.rise_by(cap.class.placed_gauge(), cap.len); ++ self.settle(&mut state, cap.class); ++ self.changed.notify_all(); ++ return Ok(carve.block(id, cap.class, cap.len)); ++ } ++ } ++ } ++ // 2. Pause block-maker ahead allocations, wait for any in-flight ahead make, ++ // and purge idle reserve slabs so none collide with the target opaque VA! ++ let idle_allocs: Vec = { ++ let mut state = self.lock(); ++ state.replaying = true; ++ while state.making_ahead { ++ state = self.wait(state); ++ } ++ // Re-check if an ahead allocation that just finished landed at the exact target VA! ++ let want_base = cap.gpu_address.saturating_sub(cap.offset); ++ let hit = state.allocations[index].iter_mut().find_map(|a| { ++ if a.address == want_base ++ && a.opaque_buffer_address == cap.opaque_buffer_address ++ && a.opaque_memory_address == cap.opaque_memory_address ++ && a.len == cap.alloc_len ++ && a.free.take_at(cap.offset, cap.len) ++ { ++ let carve = a.carve(cap.offset); ++ a.live += 1; ++ a.placed += cap.len; ++ a.ahead = false; ++ Some(carve) ++ } else { ++ None ++ } ++ }); ++ if let Some(carve) = hit { ++ let id = number(&mut state)?; ++ state.replaying = false; ++ self.counters.rise_by(cap.class.placed_gauge(), cap.len); ++ self.settle(&mut state, cap.class); ++ self.changed.notify_all(); ++ return Ok(carve.block(id, cap.class, cap.len)); ++ } ++ let mut drained = Vec::new(); ++ for c in MemoryClass::ALL { ++ let ci = c.index(); ++ let mut kept = Vec::new(); ++ for a in state.allocations[ci].drain(..) { ++ if a.live == 0 { ++ drained.push(a); ++ } else { ++ kept.push(a); ++ } ++ } ++ state.allocations[ci] = kept; ++ self.settle(&mut state, c); ++ } ++ drained ++ }; ++ for a in idle_allocs { ++ free_idle(core, a); ++ } ++ // 3. Allocate at the exact captured opaque buffer + memory addresses. ++ let alloc_res = make_allocation_ex( ++ core, ++ cap.class, ++ cap.alloc_len, ++ Some(site), ++ Some((cap.opaque_buffer_address, cap.opaque_memory_address)), ++ ); ++ let mut allocation = match alloc_res { ++ Ok(a) => a, ++ Err(e) => { ++ let mut state = self.lock(); ++ state.replaying = false; ++ self.changed.notify_all(); ++ return Err(e); ++ } ++ }; ++ let mapped = self.map(&allocation, cap.class, true); ++ if !mapped { ++ free_allocation(core, allocation); ++ let mut state = self.lock(); ++ state.replaying = false; ++ self.changed.notify_all(); ++ return Err(Error::Limit(Limit::AllocationNotMapped { ++ class: cap.class, ++ len: cap.alloc_len, ++ })); ++ } ++ let ok = allocation.free.take_at(cap.offset, cap.len); ++ debug_assert!(ok, "fresh allocation must contain captured block range"); ++ let mut state = self.lock(); ++ let id = number(&mut state)?; ++ let memory = allocation.carve(cap.offset).block(id, cap.class, cap.len); ++ allocation.live = 1; ++ allocation.placed = cap.len; ++ state.allocations[index].push(allocation); ++ state.replaying = false; ++ self.counters.rise_by(cap.class.placed_gauge(), cap.len); ++ self.settle(&mut state, cap.class); ++ self.changed.notify_all(); ++ Ok(memory) ++ } ++ + /// Takes back a block taken with [`take`](Self::take): its bytes are a free range of its + /// allocation at once. + pub(crate) fn give_back(&self, memory: Memory) { +@@ -1788,12 +1968,16 @@ pub(crate) fn run(core: Arc) { + state = pool.lock(); + continue; + } +- let wanted = (MemoryClass::ALL.into_iter()) +- .find(|&class| !state.failed[class.index()] && !state.whole(class)); ++ let wanted = (!state.replaying).then(|| { ++ (MemoryClass::ALL.into_iter()) ++ .find(|&class| !state.failed[class.index()] && !state.whole(class)) ++ }).flatten(); + if let Some(class) = wanted { ++ state.making_ahead = true; + drop(state); + let made = ahead(&core, class); + state = pool.lock(); ++ state.making_ahead = false; + match made { + // Idle from now: the reserve, which the idle rule does not weigh. + Some(mut allocation) => { +@@ -2022,6 +2206,16 @@ fn make_allocation( + class: MemoryClass, + len: u64, + site: Option, ++) -> Result { ++ make_allocation_ex(core, class, len, site, None) ++} ++ ++fn make_allocation_ex( ++ core: &Core, ++ class: MemoryClass, ++ len: u64, ++ site: Option, ++ replay: Option<(u64, u64)>, + ) -> Result { + let device = &core.device; + let (id, freed_at) = { +@@ -2031,22 +2225,38 @@ fn make_allocation( + state.freed_at[class.index()], + ) + }; +- let info = vk::BufferCreateInfo::default() ++ let mut buf_opaque = vk::BufferOpaqueCaptureAddressCreateInfo::default() ++ .opaque_capture_address(replay.map_or(0, |(b, _)| b)); ++ let mut info = vk::BufferCreateInfo::default() + .size(len) + .usage(floor::BUFFER_USAGE) + .sharing_mode(vk::SharingMode::EXCLUSIVE); ++ if core.capture_replay { ++ info = info.flags(vk::BufferCreateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY); ++ if replay.is_some_and(|(b, _)| b != 0) { ++ info = info.push_next(&mut buf_opaque); ++ } ++ } + // SAFETY: the device is live, and the create info valid: `len` is at most its + // `maxBufferSize`. + let buffer = + unsafe { device.create_buffer(&info, None) }.map_err(Error::vulkan("vkCreateBuffer"))?; + // SAFETY: the buffer is the device's. + let requirements = unsafe { device.get_buffer_memory_requirements(buffer) }; +- let mut flags = +- vk::MemoryAllocateFlagsInfo::default().flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS); +- let allocate_info = vk::MemoryAllocateInfo::default() ++ let mut mem_flags = vk::MemoryAllocateFlags::DEVICE_ADDRESS; ++ if core.capture_replay { ++ mem_flags |= vk::MemoryAllocateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY; ++ } ++ let mut flags = vk::MemoryAllocateFlagsInfo::default().flags(mem_flags); ++ let mut mem_opaque = vk::MemoryOpaqueCaptureAddressAllocateInfo::default() ++ .opaque_capture_address(replay.map_or(0, |(_, m)| m)); ++ let mut allocate_info = vk::MemoryAllocateInfo::default() + .allocation_size(requirements.size.max(len)) + .memory_type_index(core.memory_type(class)) + .push_next(&mut flags); ++ if core.capture_replay && replay.is_some_and(|(_, m)| m != 0) { ++ allocate_info = allocate_info.push_next(&mut mem_opaque); ++ } + let bits = requirements.memory_type_bits; + // SAFETY: the floor chose the memory type for buffers of this usage on this device, and + // `bufferDeviceAddress` is enabled; a spill takes a type the buffer's requirements allow. +@@ -2065,6 +2275,8 @@ fn make_allocation( + memory, + buffer, + address: 0, ++ opaque_buffer_address: 0, ++ opaque_memory_address: 0, + len, + mapping: None, + device_local: !spilled && core.device_local & (1 << core.memory_type(class)) != 0, +@@ -2101,6 +2313,13 @@ fn make_allocation( + let of = vk::BufferDeviceAddressInfo::default().buffer(buffer); + // SAFETY: the buffer has device-address usage and is bound. + allocation.address = unsafe { device.get_buffer_device_address(&of) }; ++ if core.capture_replay { ++ allocation.opaque_buffer_address = ++ unsafe { device.get_buffer_opaque_capture_address(&of) }; ++ let mof = vk::DeviceMemoryOpaqueCaptureAddressInfo::default().memory(memory); ++ allocation.opaque_memory_address = ++ unsafe { device.get_device_memory_opaque_capture_address(&mof) }; ++ } + (core.spans).made( + buffer, + allocation.address, +diff --git a/crates/metal2vulkan-runtime/src/places.rs b/crates/metal2vulkan-runtime/src/places.rs +index 137fb5790de850552affd179497df69d9912266a..3d679bbaa5285e87d1639a7cc140e0025b49e84f 100644 +--- a/crates/metal2vulkan-runtime/src/places.rs ++++ b/crates/metal2vulkan-runtime/src/places.rs +@@ -248,6 +248,33 @@ impl Ranges { + Some(at) + } + ++ /// Takes the exact range `at..at + len` if it is completely free. ++ pub(crate) fn take_at(&mut self, at: u64, len: u64) -> bool { ++ let Some(stop) = at.checked_add(len) else { ++ return false; ++ }; ++ let Some(index) = self ++ .free ++ .iter() ++ .position(|&(start, end)| start <= at && stop <= end) ++ else { ++ return false; ++ }; ++ let (start, end) = self.free[index]; ++ match (start < at, stop < end) { ++ (false, false) => { ++ self.free.remove(index); ++ } ++ (true, false) => self.free[index] = (start, at), ++ (false, true) => self.free[index] = (stop, end), ++ (true, true) => { ++ self.free[index] = (start, at); ++ self.free.insert(index + 1, (stop, end)); ++ } ++ } ++ true ++ } ++ + /// Frees `offset..offset + len`, taken before, joining it to the free ranges beside it. + pub(crate) fn give(&mut self, offset: u64, len: u64) { + let end = offset + len; diff --git a/patches/reims-vgpu-cargo-lock.patch b/patches/reims-vgpu-cargo-lock.patch deleted file mode 100644 index 4efd9a2..0000000 --- a/patches/reims-vgpu-cargo-lock.patch +++ /dev/null @@ -1,28 +0,0 @@ -diff --git a/Cargo.lock b/Cargo.lock -index 106e75e..01bf052 100644 ---- a/Cargo.lock -+++ b/Cargo.lock -@@ -213,6 +213,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - [[package]] - name = "metal2vulkan" - version = "0.2.0" -+source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" - dependencies = [ - "ash", - "metal2vulkan-air", -@@ -223,6 +224,7 @@ dependencies = [ - [[package]] - name = "metal2vulkan-air" - version = "0.2.0" -+source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" - dependencies = [ - "sha2 0.11.1", - ] -@@ -230,6 +232,7 @@ dependencies = [ - [[package]] - name = "metal2vulkan-runtime" - version = "0.2.0" -+source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" - dependencies = [ - "ash", - "libc", diff --git a/patches/reims-vgpu-snapshot-replay.patch b/patches/reims-vgpu-snapshot-replay.patch new file mode 100644 index 0000000..95593fd --- /dev/null +++ b/patches/reims-vgpu-snapshot-replay.patch @@ -0,0 +1,4309 @@ +diff --git a/crates/reims-vgpu-c/src/graphics.rs b/crates/reims-vgpu-c/src/graphics.rs +index 89ab1d0bae44537dcbca5653ac5e6f0690dcdaee..fcb5067c345f9769c216a6756701e9a8fea2429b 100644 +--- a/crates/reims-vgpu-c/src/graphics.rs ++++ b/crates/reims-vgpu-c/src/graphics.rs +@@ -1180,5 +1180,124 @@ pub unsafe extern "C" fn rvg_graphics_device_cursor_position_at( + }) + } + ++ ++/// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings, ++/// drains pending compiles/workers, flushes dirty device-cached IOSurfaces back to Guest RAM, ++/// and waits for GPU idle. ++/// ++/// # Safety ++/// `device` is a live graphics device handle. ++#[unsafe(no_mangle)] ++pub unsafe extern "C" fn rvg_graphics_device_quiesce( ++ device: *mut RvgGraphicsDevice, ++) -> RvgStatus { ++ ffi::export(|| { ++ // SAFETY: the caller's contract. ++ let d = unsafe { live(device, "rvg_graphics_device_quiesce") }; ++ match d.device.quiesce() { ++ Ok(()) => RVG_OK, ++ Err(e) => status(e), ++ } ++ }) ++} ++ ++/// Resumes VBLANK and ring threads after a snapshot finishes or fails. ++/// ++/// # Safety ++/// `device` is a live graphics device handle. ++#[unsafe(no_mangle)] ++pub unsafe extern "C" fn rvg_graphics_device_unquiesce( ++ device: *mut RvgGraphicsDevice, ++) -> RvgStatus { ++ ffi::export(|| { ++ // SAFETY: the caller's contract. ++ let d = unsafe { live(device, "rvg_graphics_device_unquiesce") }; ++ d.device.unquiesce(); ++ RVG_OK ++ }) ++} ++ ++/// Serializes the full graphics device state into a heap-allocated buffer owned by the caller ++/// and released with [`rvg_graphics_snapshot_free`]. ++/// ++/// # Safety ++/// `device` is a live graphics device handle; `out_data` and `out_len` are valid non-null pointers. ++#[unsafe(no_mangle)] ++pub unsafe extern "C" fn rvg_graphics_device_snapshot_save( ++ device: *mut RvgGraphicsDevice, ++ out_data: *mut *mut u8, ++ out_len: *mut usize, ++) -> RvgStatus { ++ ffi::export(|| { ++ if out_data.is_null() || out_len.is_null() { ++ return RVG_ERR_INVALID_ARGUMENT; ++ } ++ // SAFETY: the caller's contract. ++ let d = unsafe { live(device, "rvg_graphics_device_snapshot_save") }; ++ match d.device.snapshot_save() { ++ Ok(bytes) => { ++ let mut boxed = bytes.into_boxed_slice(); ++ let len = boxed.len(); ++ let ptr = boxed.as_mut_ptr(); ++ std::mem::forget(boxed); ++ // SAFETY: non-null checked above. ++ unsafe { ++ *out_data = ptr; ++ *out_len = len; ++ } ++ RVG_OK ++ } ++ Err(e) => status(e), ++ } ++ }) ++} ++ ++/// Frees a snapshot buffer returned by [`rvg_graphics_device_snapshot_save`]. ++/// ++/// # Safety ++/// `data` and `len` must come from a single [`rvg_graphics_device_snapshot_save`] call and not ++/// be freed more than once. ++#[unsafe(no_mangle)] ++pub unsafe extern "C" fn rvg_graphics_snapshot_free(data: *mut u8, len: usize) { ++ ffi::export(|| { ++ if !data.is_null() { ++ // SAFETY: matches Box::<[u8]>::into_raw layout above. ++ unsafe { ++ let _ = Box::from_raw(std::ptr::slice_from_raw_parts_mut(data, len)); ++ } ++ } ++ }) ++} ++ ++/// Restores the full graphics device state from a snapshot buffer produced by ++/// [`rvg_graphics_device_snapshot_save`]. ++/// ++/// # Safety ++/// `device` is a live graphics device handle; `data` points to `len` readable bytes. ++#[unsafe(no_mangle)] ++pub unsafe extern "C" fn rvg_graphics_device_snapshot_load( ++ device: *mut RvgGraphicsDevice, ++ data: *const u8, ++ len: usize, ++) -> RvgStatus { ++ ffi::export(|| { ++ if data.is_null() && len > 0 { ++ return RVG_ERR_INVALID_ARGUMENT; ++ } ++ // SAFETY: the caller's contract. ++ let d = unsafe { live(device, "rvg_graphics_device_snapshot_load") }; ++ let slice = if len == 0 { ++ &[] ++ } else { ++ // SAFETY: caller's contract. ++ unsafe { std::slice::from_raw_parts(data, len) } ++ }; ++ match d.device.snapshot_load(slice) { ++ Ok(()) => RVG_OK, ++ Err(e) => status(e), ++ } ++ }) ++} ++ + #[cfg(test)] + mod tests; +diff --git a/crates/reims-vgpu-graphics/src/device.rs b/crates/reims-vgpu-graphics/src/device.rs +index ae1d87d621a121feff29ac4f427193f7bc129994..e17ccb80c0fba49246ae22fede135c3c8c51fb88 100644 +--- a/crates/reims-vgpu-graphics/src/device.rs ++++ b/crates/reims-vgpu-graphics/src/device.rs +@@ -1104,6 +1104,8 @@ pub(crate) struct Shared { + reset_owed: AtomicBool, + /// Set at the device's end. + ending: AtomicBool, ++ /// Set while quiesced for checkpointing. ++ quiesced: AtomicBool, + /// The control thread's own wake. + wake: Wake, + /// The host's doorbell file for ring 0, once given. +@@ -1874,6 +1876,7 @@ impl Device { + epoch: AtomicU64::new(0), + reset_owed: AtomicBool::new(false), + ending: AtomicBool::new(false), ++ quiesced: AtomicBool::new(false), + wake: Wake::new()?, + doorbell: OnceLock::new(), + submit: Mutex::new(Submit { +@@ -2119,6 +2122,26 @@ impl Device { + pub fn reset(&self) { + self.shared.reset(); + } ++ ++ /// Quiesces the device for stopped-VM checkpointing. ++ pub fn quiesce(&self) { ++ self.shared.quiesce(); ++ } ++ ++ /// Resumes VBLANK ticks and ring consumption after quiesce. ++ pub fn unquiesce(&self) { ++ self.shared.unquiesce(); ++ } ++ ++ /// Exports the quiescent device's BAR0/ring/display/queue/region state. ++ pub fn export_snapshot(&self) -> crate::snapshot::DeviceSnapshot { ++ self.shared.export_snapshot() ++ } ++ ++ /// Restores device state on a freshly created device (after QEMU restored BAR2). ++ pub fn import_snapshot(&self, snap: &crate::snapshot::DeviceSnapshot) -> Result<(), &'static str> { ++ self.shared.import_snapshot(snap) ++ } + } + + /// The `COMPLETE` a ring-0 command owes, which the host gives from any thread once it has carried +@@ -2577,6 +2600,219 @@ impl Shared { + /// The reset (the module doc). It waits for the message the control thread is taking, and + /// for a take of a queue's ring or a post onto one under way, none of which waits for the + /// host; the host is told on the control thread ([`Self::tell_reset`]). ++ fn quiesce(&self) { ++ self.quiesced.store(true, Ordering::Release); ++ self.wake.wake(); ++ let active_queues: Vec> = { ++ self.queues.lock().by_obj.values().cloned().collect() ++ }; ++ for q in &active_queues { ++ q.wake.wake(); ++ } ++ { ++ let _taking = self.taking.lock(); ++ } ++ self.take_messages(); ++ self.lanes.wait_idle(); ++ if self.control_handing.load(Ordering::Acquire) { ++ self.post_behind_control_handed(None); ++ } ++ for q in &active_queues { ++ let poster = self.queue_poster(q); ++ self.take_queue_messages(q, &poster); ++ if q.handing.load(Ordering::Acquire) { ++ self.post_handed(q); ++ } ++ } ++ self.lanes.wait_idle(); ++ } ++ ++ fn unquiesce(&self) { ++ self.quiesced.store(false, Ordering::Release); ++ self.wake.wake(); ++ let active_queues: Vec> = { ++ self.queues.lock().by_obj.values().cloned().collect() ++ }; ++ for q in &active_queues { ++ q.wake.wake(); ++ } ++ } ++ ++ fn export_snapshot(&self) -> crate::snapshot::DeviceSnapshot { ++ use crate::snapshot::{DeviceSnapshot, DisplaySnapshot, QueueSnapshot}; ++ let status = self.status.load(Ordering::Acquire); ++ let driver_features = self.driver_features.load(Ordering::Acquire); ++ let control_done = self.control_done.load(Ordering::Acquire); ++ let (control_submit_count, control_submit_broken) = { ++ let s = self.submit.lock(); ++ (s.consumer.consumed(), s.broken) ++ }; ++ let control_completion_count = self.completion.lock().produced(); ++ let vt_ring_count = self.vt_ring.lock().produced(); ++ let pages: Vec = self.pages.iter().map(|p| p.load(Ordering::Acquire)).collect(); ++ let displays: Vec = self ++ .displays ++ .iter() ++ .map(|d| { ++ let st = d.state.lock(); ++ DisplaySnapshot { ++ scanout: st.scanout, ++ vblank: st.vblank, ++ asleep: st.asleep, ++ refreshes: st.refreshes, ++ told: st.told, ++ changed: st.changed, ++ cursor_image: st.cursor_image.clone(), ++ } ++ }) ++ .collect(); ++ let region_blocks = self.region.export_blocks(); ++ let mut queue_list: Vec> = ++ self.queues.lock().by_obj.values().cloned().collect(); ++ queue_list.sort_by_key(|q| q.obj_id); ++ let queues: Vec = queue_list ++ .iter() ++ .map(|q| { ++ let s = q.submit.lock(); ++ let c = q.complete.lock(); ++ QueueSnapshot { ++ create_bytes: q.create.as_bytes().to_vec(), ++ flags: q.flags, ++ taken_seqno: q.taken_seqno.load(Ordering::Acquire), ++ taken_buffer_seqno: q.taken_buffer_seqno.load(Ordering::Acquire), ++ submit_count: s.consumer.consumed(), ++ submit_broken: s.broken, ++ complete_count: c.produced(), ++ } ++ }) ++ .collect(); ++ DeviceSnapshot { ++ status, ++ driver_features, ++ control_done, ++ control_submit_count, ++ control_submit_broken, ++ control_completion_count, ++ vt_ring_count, ++ pages, ++ displays, ++ region_blocks, ++ queues, ++ } ++ } ++ ++ fn import_snapshot(&self, snap: &crate::snapshot::DeviceSnapshot) -> Result<(), &'static str> { ++ self.quiesced.store(true, Ordering::Release); ++ self.region.import_blocks(&snap.region_blocks); ++ self.driver_features.store(snap.driver_features, Ordering::Release); ++ if snap.driver_features != 0 { ++ self.host.driver_ready(snap.driver_features); ++ } ++ let mut any_page = false; ++ for (dst, &val) in self.pages.iter().zip(snap.pages.iter()) { ++ dst.store(val, Ordering::Release); ++ if val != 0 { ++ any_page = true; ++ } ++ } ++ if any_page { ++ self.pages_bound.store(true, Ordering::Release); ++ } ++ { ++ let mut submit = self.submit.lock(); ++ submit.consumer.set_count(snap.control_submit_count); ++ submit.broken = snap.control_submit_broken; ++ submit.backlog.clear(); ++ } ++ self.control_done.store(snap.control_done, Ordering::Release); ++ self.completion.lock().set_count(snap.control_completion_count); ++ self.vt_ring.lock().set_count(snap.vt_ring_count); ++ self.reset_owed.store(false, Ordering::Release); ++ for (display, ds) in self.displays.iter().zip(snap.displays.iter()) { ++ { ++ let mut st = display.state.lock(); ++ st.scanout = ds.scanout; ++ st.vblank = ds.vblank; ++ st.asleep = ds.asleep; ++ st.refreshes = ds.refreshes; ++ st.told = ds.told; ++ st.changed = ds.changed; ++ st.cursor_image = ds.cursor_image.clone(); ++ } ++ display.screen.scanout(ds.scanout); ++ display.screen.cursor_image(ds.cursor_image.clone()); ++ display.screen.power(!ds.asleep); ++ } ++ self.status.store(snap.status, Ordering::Release); ++ let epoch = self.epoch.load(Ordering::Acquire); ++ for qs in &snap.queues { ++ let Ok(q) = RgfxQueueCreate::read_from_bytes(&qs.create_bytes) else { ++ return Err("malformed RgfxQueueCreate in snapshot"); ++ }; ++ let Some((submit_at, complete_at)) = self.validate_rings(&q) else { ++ return Err("queue rings invalid against restored BAR2 block ledger"); ++ }; ++ let Some(me) = self.weak_self.get().and_then(Weak::upgrade) else { ++ return Err("device weak_self missing"); ++ }; ++ let Some(wake) = Wake::new() else { ++ return Err("queue wake allocation failed"); ++ }; ++ let bell = if self.driver_took(RGFX_FEATURE_DOORBELL_ASKS) { ++ wake::bell() ++ } else { ++ None ++ }; ++ let mut consumer = Consumer::new(submit_at); ++ consumer.set_count(qs.submit_count); ++ let mut producer = Producer::new(complete_at); ++ producer.set_count(qs.complete_count); ++ let queue = Arc::new(QueueShared { ++ obj_id: q.obj_id, ++ context: (q.obj_id >> RGFX_CONTEXT_OBJ_ID_SHIFT) as u32, ++ create: q, ++ flags: qs.flags, ++ epoch, ++ ring_id: q.submit_offset, ++ vector: q.vector, ++ submit: Mutex::new(Submit { ++ consumer, ++ broken: qs.submit_broken, ++ backlog: Backlog::default(), ++ asleep: false, ++ }), ++ taken_seqno: AtomicU64::new(qs.taken_seqno), ++ taken_buffer_seqno: AtomicU64::new(qs.taken_buffer_seqno), ++ consuming: Mutex::new(None), ++ complete: Mutex::new(producer), ++ room: Room::default(), ++ full: AtomicBool::new(false), ++ untold: Mutex::new(Untold::default()), ++ handed: Mutex::new(Handed::default()), ++ handing: AtomicBool::new(false), ++ wake, ++ bell, ++ route: AtomicU64::new(0), ++ route_page: AtomicU32::new(u32::MAX), ++ ending: AtomicBool::new(false), ++ trip: trip::Queue::default(), ++ }); ++ { ++ let mut queues = self.queues.lock(); ++ queues.by_obj.insert(q.obj_id, Arc::clone(&queue)); ++ queues.by_ring.insert(q.submit_offset, Arc::clone(&queue)); ++ } ++ let service = Arc::clone(&queue); ++ std::thread::Builder::new() ++ .name(format!("reims-vgpu.graphics-queue-{:#x}", q.obj_id)) ++ .spawn(move || me.queue_service_restored(&service)) ++ .map_err(|_| "failed to spawn restored queue thread")?; ++ self.route(&queue); ++ self.host.queue_made(&self.queue_poster(&queue)); ++ } ++ Ok(()) ++ } ++ + fn reset(&self) { + self.status.store(RGFX_STATUS_RESET, Ordering::Release); + self.driver_features.store(0, Ordering::Release); +@@ -3254,6 +3490,10 @@ impl Shared { + /// The control thread (the module doc). + fn control_thread(&self) { + while !self.ending() { ++ if self.quiesced.load(Ordering::Acquire) { ++ self.wake.sleep_for(None, Some(Duration::from_millis(20))); ++ continue; ++ } + // The answers handed over to it, posted first, as a post onto the ring would. + if self.control_handing.load(Ordering::Acquire) { + self.post_behind_control_handed(None); +@@ -4438,6 +4678,23 @@ impl Shared { + /// A queue's service thread (the module doc): it takes the queue's submission ring with the + /// control thread's `consumer_idle` handshake, hands each message to the host, and sleeps on + /// the queue's own wake, woken by its doorbell or its end. ++ fn queue_service_restored(&self, queue: &Arc) { ++ let poster = self.queue_poster(queue); ++ self.queue_loop(queue, &poster); ++ self.close_handed(queue); ++ if !self.ending() && self.epoch.load(Ordering::Acquire) == queue.epoch { ++ let destroy = RgfxObjectDestroy { ++ header: RgfxMsgHeader { ++ r#type: RGFX_CMD_OBJECT_DESTROY, ++ size: size_of::() as u32, ++ seqno: 0, ++ }, ++ obj_id: queue.obj_id, ++ }; ++ self.host.stage3_message(&poster, destroy.as_bytes()); ++ } ++ } ++ + fn queue_service(&self, queue: &Arc) { + let poster = self.queue_poster(queue); + // The host makes the queue's handle first, so a command buffer on it can name it. +@@ -4464,6 +4721,10 @@ impl Shared { + /// The loop of a queue's service thread: take, then sleep, until the queue or the device ends. + fn queue_loop(&self, queue: &Arc, poster: &CompletionPoster) { + while !self.ending() && !queue.ended() { ++ if self.quiesced.load(Ordering::Acquire) { ++ queue.wake.sleep_for(None, Some(Duration::from_millis(20))); ++ continue; ++ } + // The records handed over to it, posted first, as far as its ring has room: those + // left wait for its next look, while it takes the guest's buffers meanwhile. + if queue.handing.load(Ordering::Acquire) { +@@ -5074,6 +5335,9 @@ impl Shared { + /// that sees it ([`Self::displays_seen`]) alone: a guest that did not take + /// [`RGFX_FEATURE_MULTI_DISPLAY`] gets none of a display but 0's. + pub(crate) fn refresh(&self, id: u32, now: u64) { ++ if self.quiesced.load(Ordering::Acquire) { ++ return; ++ } + let Some(display) = self.displays.get(id as usize) else { + return; + }; +diff --git a/crates/reims-vgpu-graphics/src/device/lanes.rs b/crates/reims-vgpu-graphics/src/device/lanes.rs +index 110cbb6a4cbaf7e2450fa7040d365c3de73d9026..12b201509a9f574c8ed20f831e04d4961e66e541 100644 +--- a/crates/reims-vgpu-graphics/src/device/lanes.rs ++++ b/crates/reims-vgpu-graphics/src/device/lanes.rs +@@ -1035,6 +1035,19 @@ impl Lanes { + } + } + ++ /// Waits until no lane is running or has queued jobs (or the device ends). ++ pub(super) fn wait_idle(&self) { ++ let mut state = self.state.lock(); ++ while !state.ended ++ && state ++ .lanes ++ .values() ++ .any(|lane| lane.running.is_some() || !lane.jobs.is_empty()) ++ { ++ self.moved.wait(&mut state); ++ } ++ } ++ + /// The device ended: the lanes' threads go at their next look, and so do those that wait for + /// a lane. + pub(super) fn end(&self) { +diff --git a/crates/reims-vgpu-graphics/src/lib.rs b/crates/reims-vgpu-graphics/src/lib.rs +index ae8a328435c264e712b4d34e5153cdfcce1ca55b..40214d647726016d9aabbcc21122b3931e18493f 100644 +--- a/crates/reims-vgpu-graphics/src/lib.rs ++++ b/crates/reims-vgpu-graphics/src/lib.rs +@@ -31,6 +31,7 @@ pub mod keep; + pub mod managed; + pub mod ops; + pub mod region; ++pub mod snapshot; + mod ring; + // The trip line's histograms are a host diagnostic: cbindgen leaves the module out of the wire header. + /// cbindgen:ignore +diff --git a/crates/reims-vgpu-graphics/src/region.rs b/crates/reims-vgpu-graphics/src/region.rs +index c6032c91cb349f4a9c5e22931f46908de2eef86b..e986d707926a9d0ac524abc9499ae013bfca1442 100644 +--- a/crates/reims-vgpu-graphics/src/region.rs ++++ b/crates/reims-vgpu-graphics/src/region.rs +@@ -60,6 +60,19 @@ pub struct Region { + } + + /// A block's size and who holds it. ++/// Serializable snapshot of a granted or shared BAR2 region block. ++#[derive(Clone, Debug, PartialEq, Eq)] ++pub struct RegionBlockSnapshot { ++ /// Byte offset inside BAR2. ++ pub offset: u64, ++ /// Block size in bytes. ++ pub size: u64, ++ /// Context IDs holding this block. ++ pub holders: Vec, ++ /// Whether this block was shared (`BLOCK_SHARE`). ++ pub shared: bool, ++} ++ + #[derive(Clone, Debug, PartialEq, Eq)] + struct Held { + size: u64, +@@ -213,6 +226,37 @@ impl Region { + } + + /// No block is anyone's any more (the device's reset): the kext grants them again. ++ /// Exports all currently granted/shared BAR2 blocks for checkpointing. ++ pub fn export_blocks(&self) -> Vec { ++ let blocks = self.blocks.lock(); ++ blocks ++ .iter() ++ .map(|(&offset, held)| RegionBlockSnapshot { ++ offset, ++ size: held.size, ++ holders: held.holders.clone(), ++ shared: held.shared, ++ }) ++ .collect() ++ } ++ ++ /// Replaces the BAR2 block ledger from a checkpoint. ++ pub fn import_blocks(&self, snap: &[RegionBlockSnapshot]) { ++ let mut blocks = self.blocks.lock(); ++ blocks.clear(); ++ for b in snap { ++ blocks.insert( ++ b.offset, ++ Held { ++ size: b.size, ++ holders: b.holders.clone(), ++ shared: b.shared, ++ }, ++ ); ++ } ++ } ++ ++ /// Revokes all active BAR2 region grants prior to snapshot restore. + pub fn revoke_all(&self) { + self.blocks.lock().clear(); + } +diff --git a/crates/reims-vgpu-graphics/src/ring.rs b/crates/reims-vgpu-graphics/src/ring.rs +index 36585f35100fa121406d92c019f8172755a5cb18..12f3f11703ab5175cd90f0e6a919bb8fda017a97 100644 +--- a/crates/reims-vgpu-graphics/src/ring.rs ++++ b/crates/reims-vgpu-graphics/src/ring.rs +@@ -202,6 +202,11 @@ impl Consumer { + self.count + } + ++ /// Restores the host's consumed byte count from a checkpoint (BAR2 already holds header). ++ pub(crate) fn set_count(&mut self, count: u64) { ++ self.count = count; ++ } ++ + /// The guest's published count (the ring's producer), read with an acquire load. + pub(crate) fn published_count(&self, region: &Region) -> u64 { + region +@@ -555,6 +560,16 @@ impl Producer { + } + + /// Back to a ring nothing has passed through ([`RingAt::initialize`]), `consumer_idle` 0. ++ /// Returns the host's published byte count. ++ pub(crate) fn produced(&self) -> u64 { ++ self.count ++ } ++ ++ /// Restores the host's published byte count from a checkpoint (BAR2 already holds header). ++ pub(crate) fn set_count(&mut self, count: u64) { ++ self.count = count; ++ } ++ + pub(crate) fn reset(&mut self, region: &Region) { + self.count = 0; + self.at.initialize(region, false); +diff --git a/crates/reims-vgpu-graphics/src/snapshot.rs b/crates/reims-vgpu-graphics/src/snapshot.rs +new file mode 100644 +index 0000000000000000000000000000000000000000..00ddc52e940a6cd246a777ee74073007e91ad006 +--- /dev/null ++++ b/crates/reims-vgpu-graphics/src/snapshot.rs +@@ -0,0 +1,293 @@ ++//! Binary snapshot codec for [`Device`](crate::Device) state (Layer B). ++ ++use crate::display::{CursorImage, Mode, Scanout}; ++use crate::region::RegionBlockSnapshot; ++ ++/// Serializable display state. ++#[derive(Clone, Debug, PartialEq, Eq)] ++pub struct DisplaySnapshot { ++ /// Active BAR2 scanout, if any. ++ pub scanout: Option, ++ /// Whether VBLANK delivery is enabled. ++ pub vblank: bool, ++ /// Whether the panel is off (`SET_DISPLAY_POWER`). ++ pub asleep: bool, ++ /// Refresh counter since reset. ++ pub refreshes: u64, ++ /// Last mode told to the guest. ++ pub told: Option, ++ /// Whether a `DISPLAY_CHANGED` event is owed. ++ pub changed: bool, ++ /// Current guest cursor image, if any. ++ pub cursor_image: Option, ++} ++ ++/// Serializable per-command-queue ring state. ++#[derive(Clone, Debug, PartialEq, Eq)] ++pub struct QueueSnapshot { ++ /// Raw `RgfxQueueCreate` wire message bytes. ++ pub create_bytes: Vec, ++ /// Accepted `RGFX_QUEUE_*` flags. ++ pub flags: u32, ++ /// Highest message seqno taken off the queue's submission ring. ++ pub taken_seqno: u64, ++ /// Highest command-buffer seqno taken off the queue's submission ring. ++ pub taken_buffer_seqno: u64, ++ /// Host consumer byte count on the queue's submission ring. ++ pub submit_count: u64, ++ /// Whether the queue's submission ring was marked broken. ++ pub submit_broken: bool, ++ /// Host producer byte count on the queue's completion ring. ++ pub complete_count: u64, ++} ++ ++/// Complete serializable snapshot of `reims_vgpu_graphics::Device` (BAR0/rings/displays/queues). ++#[derive(Clone, Debug, PartialEq, Eq)] ++pub struct DeviceSnapshot { ++ /// `STATUS` register value. ++ pub status: u32, ++ /// Negotiated `DRIVER_FEATURES` bitmask. ++ pub driver_features: u64, ++ /// Control submission ring `control_done` count. ++ pub control_done: u64, ++ /// Control submission ring consumer byte count. ++ pub control_submit_count: u64, ++ /// Whether control submission ring is broken. ++ pub control_submit_broken: bool, ++ /// Control completion ring producer byte count. ++ pub control_completion_count: u64, ++ /// VideoToolbox ring producer byte count. ++ pub vt_ring_count: u64, ++ /// Doorbell page context bindings (`RGFX_REG_DOORBELL_PAGE_BIND`). ++ pub pages: Vec, ++ /// Per-display state. ++ pub displays: Vec, ++ /// Active BAR2 granted/shared blocks. ++ pub region_blocks: Vec, ++ /// Active per-queue rings. ++ pub queues: Vec, ++} ++ ++fn put_u8(o: &mut Vec, v: u8) { o.push(v); } ++fn put_u32(o: &mut Vec, v: u32) { o.extend_from_slice(&v.to_le_bytes()); } ++fn put_u64(o: &mut Vec, v: u64) { o.extend_from_slice(&v.to_le_bytes()); } ++fn put_bytes(o: &mut Vec, b: &[u8]) { ++ put_u64(o, b.len() as u64); ++ o.extend_from_slice(b); ++} ++ ++fn get_u8(i: &mut &[u8]) -> Option { ++ let (&b, rest) = i.split_first()?; ++ *i = rest; ++ Some(b) ++} ++fn get_u32(i: &mut &[u8]) -> Option { ++ if i.len() < 4 { return None; } ++ let (a, rest) = i.split_at(4); ++ *i = rest; ++ Some(u32::from_le_bytes(a.try_into().ok()?)) ++} ++fn get_u64(i: &mut &[u8]) -> Option { ++ if i.len() < 8 { return None; } ++ let (a, rest) = i.split_at(8); ++ *i = rest; ++ Some(u64::from_le_bytes(a.try_into().ok()?)) ++} ++fn get_bytes(i: &mut &[u8]) -> Option> { ++ let n = usize::try_from(get_u64(i)?).ok()?; ++ if i.len() < n { return None; } ++ let (a, rest) = i.split_at(n); ++ *i = rest; ++ Some(a.to_vec()) ++} ++fn checked_count(i: &mut &[u8], min_item_bytes: usize) -> Option { ++ let count = usize::try_from(get_u32(i)?).ok()?; ++ let min_bytes = min_item_bytes.max(1); ++ if count > i.len() / min_bytes { ++ return None; ++ } ++ Some(count) ++} ++fn read_vec( ++ i: &mut &[u8], ++ min_item_bytes: usize, ++ mut f: impl FnMut(&mut &[u8]) -> Option, ++) -> Option> { ++ let count = checked_count(i, min_item_bytes)?; ++ let mut out = Vec::with_capacity(count); ++ for _ in 0..count { ++ out.push(f(i)?); ++ } ++ Some(out) ++} ++ ++impl DeviceSnapshot { ++ /// Encodes this device snapshot into `out`. ++ pub fn encode(&self, o: &mut Vec) { ++ put_u32(o, 1); ++ put_u32(o, self.status); ++ put_u64(o, self.driver_features); ++ put_u64(o, self.control_done); ++ put_u64(o, self.control_submit_count); ++ put_u8(o, u8::from(self.control_submit_broken)); ++ put_u64(o, self.control_completion_count); ++ put_u64(o, self.vt_ring_count); ++ ++ put_u32(o, self.pages.len() as u32); ++ for &p in &self.pages { put_u32(o, p); } ++ ++ put_u32(o, self.displays.len() as u32); ++ for d in &self.displays { ++ match d.scanout { ++ Some(s) => { ++ put_u8(o, 1); ++ put_u32(o, s.width); put_u32(o, s.height); ++ put_u32(o, s.stride); put_u64(o, s.offset); ++ } ++ None => put_u8(o, 0), ++ } ++ put_u8(o, u8::from(d.vblank)); ++ put_u8(o, u8::from(d.asleep)); ++ put_u64(o, d.refreshes); ++ match d.told { ++ Some(m) => { ++ put_u8(o, 1); ++ put_u32(o, m.width); put_u32(o, m.height); ++ put_u32(o, m.refresh_mhz); put_u32(o, m.scale_120ths); ++ } ++ None => put_u8(o, 0), ++ } ++ put_u8(o, u8::from(d.changed)); ++ match &d.cursor_image { ++ Some(c) => { ++ put_u8(o, 1); ++ put_u32(o, c.width); put_u32(o, c.height); ++ put_u32(o, c.hot_spot.0); put_u32(o, c.hot_spot.1); ++ put_bytes(o, &c.rgba); ++ } ++ None => put_u8(o, 0), ++ } ++ } ++ ++ put_u32(o, self.region_blocks.len() as u32); ++ for b in &self.region_blocks { ++ put_u64(o, b.offset); put_u64(o, b.size); ++ put_u8(o, u8::from(b.shared)); ++ put_u32(o, b.holders.len() as u32); ++ for &h in &b.holders { put_u32(o, h); } ++ } ++ ++ put_u32(o, self.queues.len() as u32); ++ for q in &self.queues { ++ put_bytes(o, &q.create_bytes); ++ put_u32(o, q.flags); ++ put_u64(o, q.taken_seqno); ++ put_u64(o, q.taken_buffer_seqno); ++ put_u64(o, q.submit_count); ++ put_u8(o, u8::from(q.submit_broken)); ++ put_u64(o, q.complete_count); ++ } ++ } ++ ++ /// Decodes a device snapshot from `i`. ++ pub fn decode(i: &mut &[u8]) -> Option { ++ if get_u32(i)? != 1 { return None; } ++ let status = get_u32(i)?; ++ let driver_features = get_u64(i)?; ++ let control_done = get_u64(i)?; ++ let control_submit_count = get_u64(i)?; ++ let control_submit_broken = get_u8(i)? != 0; ++ let control_completion_count = get_u64(i)?; ++ let vt_ring_count = get_u64(i)?; ++ ++ let pages = read_vec(i, 4, get_u32)?; ++ let displays = read_vec(i, 14, |i| { ++ let scanout = if get_u8(i)? != 0 { ++ Some(Scanout { ++ width: get_u32(i)?, height: get_u32(i)?, ++ stride: get_u32(i)?, offset: get_u64(i)?, ++ }) ++ } else { None }; ++ let vblank = get_u8(i)? != 0; ++ let asleep = get_u8(i)? != 0; ++ let refreshes = get_u64(i)?; ++ let told = if get_u8(i)? != 0 { ++ Some(Mode { ++ width: get_u32(i)?, height: get_u32(i)?, ++ refresh_mhz: get_u32(i)?, scale_120ths: get_u32(i)?, ++ }) ++ } else { None }; ++ let changed = get_u8(i)? != 0; ++ let cursor_image = if get_u8(i)? != 0 { ++ Some(CursorImage { ++ width: get_u32(i)?, height: get_u32(i)?, ++ hot_spot: (get_u32(i)?, get_u32(i)?), ++ rgba: get_bytes(i)?, ++ }) ++ } else { None }; ++ Some(DisplaySnapshot { scanout, vblank, asleep, refreshes, told, changed, cursor_image }) ++ })?; ++ let region_blocks = read_vec(i, 21, |i| { ++ let offset = get_u64(i)?; ++ let size = get_u64(i)?; ++ let shared = get_u8(i)? != 0; ++ let holders = read_vec(i, 4, get_u32)?; ++ Some(RegionBlockSnapshot { offset, size, holders, shared }) ++ })?; ++ let queues = read_vec(i, 45, |i| { ++ Some(QueueSnapshot { ++ create_bytes: get_bytes(i)?, ++ flags: get_u32(i)?, ++ taken_seqno: get_u64(i)?, ++ taken_buffer_seqno: get_u64(i)?, ++ submit_count: get_u64(i)?, ++ submit_broken: get_u8(i)? != 0, ++ complete_count: get_u64(i)?, ++ }) ++ })?; ++ ++ Some(DeviceSnapshot { ++ status, driver_features, control_done, ++ control_submit_count, control_submit_broken, ++ control_completion_count, vt_ring_count, ++ pages, displays, region_blocks, queues, ++ }) ++ } ++} ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ ++ #[test] ++ fn decode_rejects_oversized_counts_without_allocating() { ++ // Minimal valid header (version=1 + fixed scalar fields = 49 bytes). ++ let mut base = Vec::new(); ++ let empty = DeviceSnapshot { ++ status: 1, ++ driver_features: 2, ++ control_done: 3, ++ control_submit_count: 4, ++ control_submit_broken: false, ++ control_completion_count: 5, ++ vt_ring_count: 6, ++ pages: vec![], ++ displays: vec![], ++ region_blocks: vec![], ++ queues: vec![], ++ }; ++ empty.encode(&mut base); ++ let mut s = base.as_slice(); ++ assert_eq!(DeviceSnapshot::decode(&mut s), Some(empty)); ++ assert!(s.is_empty()); ++ ++ // Overwrite each of the 4 top-level collection counts with u32::MAX. ++ // Header length before pages count: 4 + 4 + 8 + 8 + 8 + 1 + 8 + 8 = 49. ++ for offset in [49usize, 53, 57, 61] { ++ let mut bad = base.clone(); ++ bad[offset..offset + 4].copy_from_slice(&u32::MAX.to_le_bytes()); ++ let mut sl = bad.as_slice(); ++ assert!(DeviceSnapshot::decode(&mut sl).is_none(), "offset {offset} must fail"); ++ } ++ } ++} +diff --git a/crates/reims-vgpu-vulkan/src/core/platform/device.rs b/crates/reims-vgpu-vulkan/src/core/platform/device.rs +index 50b24be4d3d3cfb3a3305694ef8e948d7c41b72d..e737f7260b9407aa886eec0370af670b1519c806 100644 +--- a/crates/reims-vgpu-vulkan/src/core/platform/device.rs ++++ b/crates/reims-vgpu-vulkan/src/core/platform/device.rs +@@ -564,4 +564,44 @@ pub trait GpuDevice: Handle { + &self, + desc: &FullComputePipelineDesc<'_, P>, + ) -> Result, NsErrorText>; ++ ++ /// Waits for all submitted GPU work on this device to complete without tearing down the device. ++ fn wait_idle(&self) {} ++ ++ /// Reads the current timeline value of a non-shared `MTLEvent` (0 if unsupported). ++ fn event_signaled_value(&self, _event: &P::Event) -> u64 { ++ 0 ++ } ++ ++ /// Restores a non-shared `MTLEvent`'s timeline value across host process restart. ++ fn event_restore_signaled_value(&self, _event: &P::Event, _value: u64) -> bool { ++ true ++ } ++ ++ /// Reads the contents of a standalone GPU buffer (Shared/Managed/Private) for snapshotting. ++ /// Returns `Ok(None)` if the buffer has no backed contents or this platform does not support ++ /// readback; returns `Err(...)` if a GPU transfer fails. ++ fn read_standalone_buffer(&self, _buffer: &P::Buffer) -> Result>, &'static str> { ++ Ok(None) ++ } ++ ++ /// Restores the contents of a standalone GPU buffer from snapshot bytes. ++ fn write_standalone_buffer(&self, _buffer: &P::Buffer, _data: &[u8]) -> bool { ++ false ++ } ++ ++ /// Reads all mip levels and array/cube slices of a standalone GPU texture into packed bytes. ++ /// Returns `Ok(None)` for non-transferable formats (MSAA, Memoryless, depth/stencil) or on ++ /// platforms without readback; returns `Err(...)` if a GPU transfer fails. ++ fn read_standalone_texture( ++ &self, ++ _texture: &P::Texture, ++ ) -> Result>, &'static str> { ++ Ok(None) ++ } ++ ++ /// Uploads packed mip/slice bytes back into a standalone GPU texture. ++ fn write_standalone_texture(&self, _texture: &P::Texture, _data: &[u8]) -> bool { ++ false ++ } + } +diff --git a/crates/reims-vgpu-vulkan/src/rt_platform/device.rs b/crates/reims-vgpu-vulkan/src/rt_platform/device.rs +index 2a87bbc65e5c2093e3d1c06b1abbd297abbcc7da..4df542484ffe702a5837a5dd7f765bbb50e07531 100644 +--- a/crates/reims-vgpu-vulkan/src/rt_platform/device.rs ++++ b/crates/reims-vgpu-vulkan/src/rt_platform/device.rs +@@ -2625,6 +2625,327 @@ impl GpuDevice for RtObj { + crate::recorder::rec_done!(recorded_call, recorded_answer); + recorded_answer + } ++ ++ fn wait_idle(&self) { ++ let _ = self.rt().wait_idle(); ++ } ++ ++ fn event_signaled_value(&self, event: &::Event) -> u64 { ++ event.signaled_value() ++ } ++ ++ fn event_restore_signaled_value( ++ &self, ++ event: &::Event, ++ value: u64, ++ ) -> bool { ++ if value > 0 { ++ event.restore_signaled_value(value).is_ok() ++ } else { ++ true ++ } ++ } ++ ++ fn read_standalone_buffer( ++ &self, ++ buffer: &::Buffer, ++ ) -> Result>, &'static str> { ++ let Some(rt_buf) = buffer.made_rt() else { ++ return Ok(None); ++ }; ++ let len = rt_buf.length(); ++ if len == 0 { ++ return Ok(Some(Vec::new())); ++ } ++ if let Some(ptr) = rt_buf.contents() { ++ return Ok(Some(unsafe { ++ std::slice::from_raw_parts(ptr.as_ptr(), len as usize).to_vec() ++ })); ++ } ++ let rt = self.rt(); ++ let alloc_len = (len.max(4096) + 4095) & !4095; ++ let stage = rt ++ .take_block(rt::MemoryClass::Shared, alloc_len) ++ .map_err(|_| "standalone buffer readback: staging take_block failed")?; ++ let res = (|| -> Result, &'static str> { ++ let dst_buf = rt ++ .new_buffer(stage.id, 0, len, None) ++ .map_err(|_| "standalone buffer readback: staging new_buffer failed")?; ++ let q = rt ++ .new_command_queue(4) ++ .map_err(|_| "standalone buffer readback: new_command_queue failed")?; ++ let cb = q ++ .command_buffer() ++ .map_err(|_| "standalone buffer readback: command_buffer failed")?; ++ let mut blit = cb ++ .blit_command_encoder() ++ .map_err(|_| "standalone buffer readback: blit_command_encoder failed")?; ++ blit.copy_from_buffer_to_buffer(rt_buf, 0, &dst_buf, 0, len) ++ .map_err(|_| "standalone buffer readback: copy_from_buffer_to_buffer failed")?; ++ blit.end_encoding(); ++ cb.commit() ++ .map_err(|_| "standalone buffer readback: commit failed")?; ++ cb.wait_until_completed() ++ .map_err(|_| "standalone buffer readback: wait_until_completed failed")?; ++ let ptr = stage ++ .contents ++ .ok_or("standalone buffer readback: staging block not host-mapped")?; ++ let out = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), len as usize).to_vec() }; ++ drop(dst_buf); ++ Ok(out) ++ })(); ++ let _ = rt.release_block(stage); ++ res.map(Some) ++ } ++ ++ fn write_standalone_buffer( ++ &self, ++ buffer: &::Buffer, ++ data: &[u8], ++ ) -> bool { ++ let Some(rt_buf) = buffer.made_rt() else { ++ return false; ++ }; ++ let len = rt_buf.length(); ++ if data.len() as u64 != len { ++ return false; ++ } ++ if len == 0 { ++ return true; ++ } ++ if let Some(ptr) = rt_buf.contents() { ++ unsafe { ++ std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), len as usize); ++ } ++ let _ = rt_buf.did_modify_range(0, len); ++ return true; ++ } ++ let rt = self.rt(); ++ let alloc_len = (len.max(4096) + 4095) & !4095; ++ let Ok(stage) = rt.take_block(rt::MemoryClass::Shared, alloc_len) else { ++ return false; ++ }; ++ if let Some(ptr) = stage.contents { ++ unsafe { ++ std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), len as usize); ++ } ++ } else { ++ let _ = rt.release_block(stage); ++ return false; ++ } ++ let ok = (|| -> Result<(), rt::Error> { ++ let src_buf = rt.new_buffer(stage.id, 0, len, None)?; ++ let q = rt.new_command_queue(4)?; ++ let cb = q.command_buffer()?; ++ let mut blit = cb.blit_command_encoder()?; ++ blit.copy_from_buffer_to_buffer(&src_buf, 0, rt_buf, 0, len)?; ++ blit.end_encoding(); ++ cb.commit()?; ++ cb.wait_until_completed()?; ++ drop(src_buf); ++ Ok(()) ++ })() ++ .is_ok(); ++ let _ = rt.release_block(stage); ++ ok ++ } ++ ++ fn read_standalone_texture( ++ &self, ++ texture: &::Texture, ++ ) -> Result>, &'static str> { ++ let rt_tex = texture.rt(); ++ let desc = rt_tex.descriptor(); ++ let Some((plan, total)) = texture_copy_plan(self.rt(), desc) else { ++ return Ok(None); ++ }; ++ if total == 0 { ++ return Ok(Some(Vec::new())); ++ } ++ let rt = self.rt(); ++ let alloc_len = (total.max(4096) + 4095) & !4095; ++ let stage = rt ++ .take_block(rt::MemoryClass::Shared, alloc_len) ++ .map_err(|_| "standalone texture readback: staging take_block failed")?; ++ let res = (|| -> Result, &'static str> { ++ let dst_buf = rt ++ .new_buffer(stage.id, 0, total, None) ++ .map_err(|_| "standalone texture readback: staging new_buffer failed")?; ++ let q = rt ++ .new_command_queue(4) ++ .map_err(|_| "standalone texture readback: new_command_queue failed")?; ++ let cb = q ++ .command_buffer() ++ .map_err(|_| "standalone texture readback: command_buffer failed")?; ++ let mut blit = cb ++ .blit_command_encoder() ++ .map_err(|_| "standalone texture readback: blit_command_encoder failed")?; ++ for step in &plan { ++ blit.copy_from_texture_to_buffer( ++ rt_tex, ++ rt::TexturePlace { ++ slice: step.slice, ++ level: step.level, ++ origin: [0, 0, 0], ++ }, ++ step.size, ++ &dst_buf, ++ rt::BufferLayout { ++ offset: step.offset, ++ bytes_per_row: step.bytes_per_row, ++ bytes_per_image: step.bytes_per_image, ++ }, ++ ) ++ .map_err(|_| "standalone texture readback: copy_from_texture_to_buffer failed")?; ++ } ++ blit.end_encoding(); ++ cb.commit() ++ .map_err(|_| "standalone texture readback: commit failed")?; ++ cb.wait_until_completed() ++ .map_err(|_| "standalone texture readback: wait_until_completed failed")?; ++ let ptr = stage ++ .contents ++ .ok_or("standalone texture readback: staging block not host-mapped")?; ++ let out = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), total as usize).to_vec() }; ++ drop(dst_buf); ++ Ok(out) ++ })(); ++ let _ = rt.release_block(stage); ++ res.map(Some) ++ } ++ ++ fn write_standalone_texture( ++ &self, ++ texture: &::Texture, ++ data: &[u8], ++ ) -> bool { ++ let rt_tex = texture.rt(); ++ let desc = rt_tex.descriptor(); ++ let Some((plan, total)) = texture_copy_plan(self.rt(), desc) else { ++ return false; ++ }; ++ if data.len() as u64 != total { ++ return false; ++ } ++ if total == 0 { ++ return true; ++ } ++ let rt = self.rt(); ++ let alloc_len = (total.max(4096) + 4095) & !4095; ++ let Ok(stage) = rt.take_block(rt::MemoryClass::Shared, alloc_len) else { ++ return false; ++ }; ++ if let Some(ptr) = stage.contents { ++ unsafe { ++ std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), total as usize); ++ } ++ } else { ++ let _ = rt.release_block(stage); ++ return false; ++ } ++ let ok = (|| -> Result<(), rt::Error> { ++ let src_buf = rt.new_buffer(stage.id, 0, total, None)?; ++ let q = rt.new_command_queue(4)?; ++ let cb = q.command_buffer()?; ++ let mut blit = cb.blit_command_encoder()?; ++ for step in &plan { ++ blit.copy_from_buffer( ++ &src_buf, ++ rt::BufferLayout { ++ offset: step.offset, ++ bytes_per_row: step.bytes_per_row, ++ bytes_per_image: step.bytes_per_image, ++ }, ++ step.size, ++ rt_tex, ++ rt::TexturePlace { ++ slice: step.slice, ++ level: step.level, ++ origin: [0, 0, 0], ++ }, ++ )?; ++ } ++ blit.end_encoding(); ++ cb.commit()?; ++ cb.wait_until_completed()?; ++ drop(src_buf); ++ Ok(()) ++ })() ++ .is_ok(); ++ let _ = rt.release_block(stage); ++ ok ++ } ++} ++ ++struct TextureCopyStep { ++ slice: u32, ++ level: u32, ++ size: [u32; 3], ++ offset: u64, ++ bytes_per_row: u64, ++ bytes_per_image: u64, ++} ++ ++fn texture_copy_plan( ++ rt: &rt::Device, ++ desc: &rt::TextureDescriptor, ++) -> Option<(Vec, u64)> { ++ if desc.sample_count > 1 || desc.storage_mode == rt::StorageMode::Memoryless { ++ return None; ++ } ++ let raw_fmt = u64::from(desc.pixel_format.as_raw()); ++ if (250..=262).contains(&raw_fmt) { ++ return None; ++ } ++ let info = rt.pixel_format_info(u64::from(desc.pixel_format.as_raw())); ++ let block_bytes = info.words[0]; ++ if block_bytes == 0 { ++ return None; ++ } ++ let (block_w, block_h, block_d) = if info.flags & 0x400 != 0 { ++ (info.words[1].max(1), info.words[2].max(1), info.words[3].max(1)) ++ } else { ++ (1, 1, 1) ++ }; ++ let slices = match desc.texture_type { ++ rt::TextureType::Cube | rt::TextureType::CubeArray => desc.array_length.checked_mul(6)?, ++ rt::TextureType::Type3D => 1, ++ _ => desc.array_length.max(1), ++ }; ++ let levels = desc.mipmap_level_count.max(1); ++ let mut plan = Vec::with_capacity((slices as usize).saturating_mul(levels as usize)); ++ let mut offset: u64 = 0; ++ for slice in 0..slices { ++ for level in 0..levels { ++ let w = (desc.width >> level).max(1); ++ let h = match desc.texture_type { ++ rt::TextureType::Type1D | rt::TextureType::Type1DArray => 1, ++ _ => (desc.height >> level).max(1), ++ }; ++ let d = match desc.texture_type { ++ rt::TextureType::Type3D => (desc.depth >> level).max(1), ++ _ => 1, ++ }; ++ let bx = u64::from(w).div_ceil(block_w); ++ let by = u64::from(h).div_ceil(block_h); ++ let bz = u64::from(d).div_ceil(block_d); ++ let raw_bpr = bx.checked_mul(block_bytes)?; ++ let bpr = (raw_bpr + 15) & !15; ++ let bpi = bpr.checked_mul(by)?; ++ let step_bytes = bpi.checked_mul(bz)?; ++ offset = (offset + 15) & !15; ++ plan.push(TextureCopyStep { ++ slice, ++ level, ++ size: [w, h, d], ++ offset, ++ bytes_per_row: bpr, ++ bytes_per_image: bpi, ++ }); ++ offset = offset.checked_add(step_bytes)?; ++ } ++ } ++ Some((plan, offset)) + } + + /// The identity of `device` ([`answers::identity`]): rt's linear and texture-buffer alignments +diff --git a/crates/reims-vgpu/src/graphics.rs b/crates/reims-vgpu/src/graphics.rs +index 8cac38c823e4bbd3d76eafa0ac3bc2f3461bd5f4..a4715175ae46687face600f1ed683c4c628570c0 100644 +--- a/crates/reims-vgpu/src/graphics.rs ++++ b/crates/reims-vgpu/src/graphics.rs +@@ -93,7 +93,8 @@ use reims_vgpu_graphics::wire::{ + RGFX_FEATURE_TEXTURE_DID_MODIFY_DATA, RGFX_FEATURE_UNCHANGING_PAGES, + RGFX_FEATURE_UNSHARED_QUEUES, RGFX_FEATURE_UPLOADS_WRITTEN, RGFX_FEATURE_VT_MESSAGES, + RGFX_RESOURCE_ID_CHUNK, RGFX_RESOURCE_ID_CHUNKS, RGFX_STATUS_INVALID_ARGUMENT, +- RGFX_STATUS_NOT_FOUND, RGFX_STATUS_OK, RGFX_STATUS_REFUSED, RGFX_VIDEO_CAPS_CODECS, ++ RGFX_STATUS_CACHE, RGFX_STATUS_NOT_FOUND, RGFX_STATUS_OK, RGFX_STATUS_REFUSED, ++ RGFX_VIDEO_CAPS_CODECS, + RGFX_VIDEO_CAPS_OFFSET, RGFX_VIDEO_CAPS_OUTPUT_CACHED, RGFX_VIDEO_CAPS_VERSION, + RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_CODEC_HEVC, RGFX_VIDEO_CODEC_VP9, RGFX_VIDEO_DECODE, + RGFX_VIDEO_H264_BASELINE, RGFX_VIDEO_H264_HIGH, RGFX_VIDEO_H264_MAIN, RGFX_VIDEO_HEVC_MAIN, +@@ -190,6 +191,7 @@ mod present; + mod read; + mod rt_window; + mod sink; ++mod snapshot; + mod slow_answers; + mod summary; + mod trip; +@@ -1035,6 +1037,7 @@ impl GraphicsDevice

{ + let clock = Arc::clone(&platform); + create_waits::CreateWaits::new(Box::new(move || clock.clock().now_mono())) + }, ++ live_log: snapshot::LiveLog::new(count), + }); + let cursors: Vec> = (0..count) + .map(|display| { +@@ -1350,6 +1353,242 @@ impl GraphicsDevice

{ + (self.cursors.get(display as usize)).map_or((0, 0), |cursor| cursor.position()) + }) + } ++ ++ fn quiesce_device(&self) -> Option>> { ++ self.device.quiesce(); ++ if let Some(pool) = &self.pool { ++ pool.quiesce(); ++ } ++ let control = self.ending.upgrade()?; ++ control.pool.wait_idle(); ++ control.icb_worker.flush(); ++ let decoder = control.decoder(); ++ decoder.flush_workers(); ++ decoder.flush_all_surface_caches(&control.device); ++ control.device.wait_idle(); ++ Some(control) ++ } ++ ++ /// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings, ++ /// drains pending compiles and workers, flushes dirty device-cached IOSurfaces back to Guest ++ /// RAM, and waits for GPU idle. ++ pub fn quiesce(&self) -> Result<(), Error> { ++ entry::run(|_| { ++ let _ = self.quiesce_device(); ++ Ok(()) ++ }) ++ } ++ ++ /// Resumes VBLANK and ring service threads after a snapshot completes or aborts. ++ pub fn unquiesce(&self) { ++ entry::run(|_| { ++ self.device.unquiesce(); ++ }); ++ } ++ ++ /// Serializes the full graphics device state (device rings/displays/queues, Shared Pool, ++ /// Private Blocks + VRAM, live Metal/Vulkan objects, timeline events, and standalone GPU ++ /// buffers/textures) into a portable byte blob for suspend-to-disk. ++ pub fn snapshot_save(&self) -> Result, Error> { ++ entry::run(|_| { ++ let t0 = std::time::Instant::now(); ++ let control = self.quiesce_device().ok_or(Error::HostResources)?; ++ let decoder = control.decoder(); ++ ++ let mut device_snapshot = Vec::new(); ++ self.device.export_snapshot().encode(&mut device_snapshot); ++ let shared_pool = self.pool.as_ref().map(|p| p.export_snapshot()).transpose()?; ++ let private_blocks = control.private_blocks.export_snapshot()?; ++ let id_chunks = decoder.export_id_chunks(); ++ let (live_records, surface_pages, standalone_tex_set, presented_surfaces) = ++ control.live_log.export(); ++ ++ let mut known_ranges: Vec<(u64, u64)> = Vec::new(); ++ if let Some(sp) = &shared_pool { ++ for piece in &sp.pieces { ++ if piece.gpu_address != 0 { ++ known_ranges.push((piece.gpu_address, piece.len)); ++ } ++ } ++ } ++ for pb in &private_blocks.blocks { ++ if pb.gpu_address != 0 { ++ known_ranges.push((pb.gpu_address, pb.len)); ++ } ++ } ++ let live_values = decoder ++ .export_live_values(&control.device, &known_ranges, &standalone_tex_set) ++ .map_err(|_| Error::HostResources)?; ++ let mut standalone_textures: Vec = standalone_tex_set.into_iter().collect(); ++ standalone_textures.sort_unstable(); ++ ++ let snap = snapshot::VgpuSnapshot { ++ device_snapshot, ++ shared_pool, ++ private_blocks, ++ id_chunks, ++ surface_pages, ++ live_records, ++ standalone_textures, ++ presented_surfaces, ++ live_values, ++ }; ++ let t_exp = t0.elapsed(); ++ let n_tex = snap.live_values.textures.len(); ++ let tex_bytes: usize = snap.live_values.textures.iter().map(|(_, b)| b.len()).sum(); ++ let n_caches = snap.live_values.surface_caches.len(); ++ let cache_bytes: usize = snap ++ .live_values ++ .surface_caches ++ .iter() ++ .map(|(_, b)| b.len()) ++ .sum(); ++ let encoded = snap.encode(); ++ log::info!( ++ target: "reims_vgpu::graphics", ++ "snapshot_save done in {:.2}s (export={:.2}s): total={} B, textures={} ({:.1} MiB), unattached_caches={} ({:.1} MiB)", ++ t0.elapsed().as_secs_f64(), ++ t_exp.as_secs_f64(), ++ encoded.len(), ++ n_tex, ++ tex_bytes as f64 / (1024.0 * 1024.0), ++ n_caches, ++ cache_bytes as f64 / (1024.0 * 1024.0), ++ ); ++ Ok(encoded) ++ }) ++ } ++ ++ /// Restores the full graphics device state from a snapshot produced by [`Self::snapshot_save`] ++ /// in a fresh host process. ++ pub fn snapshot_load(&self, data: &[u8]) -> Result<(), Error> { ++ entry::run(|_| { ++ let snap = snapshot::VgpuSnapshot::decode(data).ok_or(Error::InvalidArgument)?; ++ let mut dev_slice: &[u8] = &snap.device_snapshot; ++ let dev_snap = reims_vgpu_graphics::snapshot::DeviceSnapshot::decode(&mut dev_slice) ++ .ok_or(Error::InvalidArgument)?; ++ if !dev_slice.is_empty() { ++ return Err(Error::InvalidArgument); ++ } ++ let control = self.ending.upgrade().ok_or(Error::HostResources)?; ++ ++ // Keep device rings and VBLANK paused until full object table replay finishes. ++ // Any error below returns without unquiescing so partial restores never report success. ++ self.device.quiesce(); ++ ++ match (&self.pool, &snap.shared_pool) { ++ (Some(pool), Some(ps)) => pool.import_snapshot(ps)?, ++ (None, Some(ps)) if !ps.pieces.is_empty() => return Err(Error::HostResources), ++ _ => {} ++ } ++ control.private_blocks.import_snapshot(&snap.private_blocks)?; ++ ++ self.device.import_snapshot(&dev_snap).map_err(|_| Error::InvalidArgument)?; ++ control ++ .decoder() ++ .set_managed_at_copy(dev_snap.driver_features & RGFX_FEATURE_MANAGED_AT_COPY != 0); ++ ++ { ++ let decoder = control.decoder(); ++ decoder.import_id_chunks(&snap.id_chunks); ++ for sp in &snap.surface_pages { ++ decoder ++ .replay_surface_pages( ++ &control.device, ++ &sp.pages, ++ &sp.runs, ++ sp.flags, ++ sp.layout, ++ ) ++ .map_err(|_| Error::HostResources)?; ++ } ++ } ++ ++ let mut records = snap.live_records; ++ records.sort_by_key(|r| r.seq); ++ for rec in &records { ++ control.replay_record(rec)?; ++ } ++ ++ let n_surface_pages = snap.surface_pages.len(); ++ let n_records = records.len(); ++ let standalone_set: std::collections::HashSet = ++ snap.standalone_textures.into_iter().collect(); ++ control.live_log.restore( ++ records, ++ snap.surface_pages, ++ standalone_set, ++ snap.presented_surfaces.clone(), ++ ); ++ ++ // Wait for any replay-time buffer zeroing to finish, then upload exact saved memory! ++ control.device.wait_idle(); ++ if let (Some(pool), Some(ps)) = (&self.pool, &snap.shared_pool) { ++ pool.restore_bytes(ps)?; ++ } ++ control.private_blocks.restore_bytes(&snap.private_blocks)?; ++ ++ { ++ let decoder = control.decoder(); ++ decoder ++ .import_live_values(&control.device, &snap.live_values) ++ .map_err(|_| Error::HostResources)?; ++ for qs in &dev_snap.queues { ++ let q = reims_vgpu_graphics::wire::RgfxQueueCreate::read_from_bytes( ++ &qs.create_bytes, ++ ) ++ .map_err(|_| Error::InvalidArgument)?; ++ let watermark = qs.taken_seqno.max(qs.taken_buffer_seqno); ++ if watermark > 0 { ++ log::info!( ++ target: "reims_vgpu::graphics", ++ "restoring queue {:#x} watermark={watermark} (taken={} buf={})", ++ q.obj_id, qs.taken_seqno, qs.taken_buffer_seqno ++ ); ++ decoder.restore_queue_watermark(q.obj_id, watermark); ++ control.presents.restore_finished(q.obj_id, watermark); ++ } ++ } ++ for (display, &iosurface_id) in snap.presented_surfaces.iter().enumerate() { ++ if iosurface_id == 0 { ++ continue; ++ } ++ let presented = control.presented.get(display).ok_or(Error::InvalidArgument)?; ++ let found = decoder.surface_present(iosurface_id).ok_or_else(|| { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "snapshot_load: presented surface {iosurface_id} for display {display} missing after replay" ++ ); ++ Error::HostResources ++ })?; ++ let shown = presented.hold( ++ found.texture, ++ found.view, ++ found.span, ++ found.queued, ++ ); ++ let _ = presented.swap(iosurface_id, Some(shown)); ++ } ++ } ++ ++ log::info!( ++ target: "reims_vgpu::graphics", ++ "snapshot_load summary: dev_queues={} surface_pages={} records={} presented={:?} events={} shared_events={} bufs={} texs={} caches={}", ++ dev_snap.queues.len(), ++ n_surface_pages, ++ n_records, ++ snap.presented_surfaces, ++ snap.live_values.events.len(), ++ snap.live_values.shared_events.len(), ++ snap.live_values.buffers.len(), ++ snap.live_values.textures.len(), ++ snap.live_values.surface_caches.len(), ++ ); ++ control.device.wait_idle(); ++ self.device.unquiesce(); ++ Ok(()) ++ }) ++ } + } + + impl Drop for GraphicsDevice

{ +@@ -1543,6 +1782,7 @@ struct GraphicsControl { + /// The pipeline creates waiting for their replies, timed for the counts line + /// (`create_waits`): from their take ([`Self::handle_stage3`]) to their reply's post. + create_waits: create_waits::CreateWaits, ++ live_log: snapshot::LiveLog, + } + + /// The longest `COMMAND_BUFFER` message, in bytes, that is walked and committed on its queue's +@@ -2196,6 +2436,7 @@ impl GraphicsControl

{ + self.pending.cancel_context(context); + let (dropped, closed) = decoder.close_tables(&self.device, context); + self.pool.context_closed(context); ++ self.live_log.close_context(context); + self.presents.context_gone(context); + self.queue_sinks + .write() +@@ -2286,6 +2527,7 @@ impl GraphicsControl

{ + } + // And every Private block, the objects in them dropped. + self.private_blocks.reset(); ++ self.live_log.reset(); + self.presents.reset(); + self.queue_sinks.write().clear(); + for color in &self.colors { +@@ -2348,6 +2590,7 @@ impl GraphicsControl

{ + answer.answer(RGFX_STATUS_REFUSED); + return; + } ++ self.live_log.forget_surface_pages(release.offset); + // Once no display shows or draws a surface over the block, with what was in flight then. + let m = Arc::clone(&marks); + let in_flight = decoder.in_flight_read(release.context); +@@ -2648,6 +2891,10 @@ impl GraphicsControl

{ + let _carried = me.reset_gate.read_recursive(); + let status = (me.decoder()) + .carry_out_surface_pages(&me.device, &pages, &runs, flags, layout, &settle); ++ if matches!(status, Some(RGFX_STATUS_OK | RGFX_STATUS_CACHE)) { ++ me.live_log ++ .record_surface_pages(pages, runs.clone(), flags, layout); ++ } + // Where the guest took IMPORT_ADDRESSES_LATER, answered now, with no address, + // before the view is made and given one below. + let answer = match status { +@@ -2746,6 +2993,197 @@ impl GraphicsControl

{ + /// ([`Host::command_buffer`]), which goes to the buffer's lane as it is, with `claim`, its + /// queue's claim on its messages, which a buffer carried out here lets go once begun + /// ([`Self::carry_out`]). ++ /// Synchronously replays one recorded stage-3 object creation or persistent mutation ++ /// during [`GraphicsDevice::snapshot_load`] without emitting wire completion replies. ++ fn replay_record(&self, rec: &snapshot::LogRecord) -> Result<(), Error> { ++ let mut decoder = self ++ .decoders ++ .sender(Some(rec.context), Sinks::default()); ++ match rec.msg_type { ++ snapshot::LOG_TAG_ASSEMBLED_LIBRARY => { ++ let guest_key: Option = if rec.bytes.is_empty() { ++ None ++ } else { ++ Some( ++ rec.bytes ++ .as_slice() ++ .try_into() ++ .map_err(|_| Error::InvalidArgument)?, ++ ) ++ }; ++ let job = decoder.prepare_library_bytes( ++ rec.obj_id, ++ rec.inline_bytes.clone(), ++ guest_key, ++ ); ++ let made = refusing(|| make_library::

(&self.device, &job)).map_err(|raise| { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "replay_record: library seq={} obj={:#x} raised: {raise}", ++ rec.seq, rec.obj_id ++ ); ++ Error::HostResources ++ })?; ++ let status = decoder.finish_library(made); ++ if status != RGFX_STATUS_OK { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "replay_record: library seq={} obj={:#x} failed status={status}", ++ rec.seq, rec.obj_id ++ ); ++ return Err(Error::HostResources); ++ } ++ Ok(()) ++ } ++ RGFX_CMD_LIBRARY_LOOKUP => { ++ let (_, status) = decoder.lookup_library(&rec.bytes); ++ if status != RGFX_STATUS_OK { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "replay_record: library lookup seq={} obj={:#x} failed status={status}", ++ rec.seq, rec.obj_id ++ ); ++ return Err(Error::HostResources); ++ } ++ Ok(()) ++ } ++ RGFX_CMD_RENDER_PIPELINE_CREATE ++ | RGFX_CMD_MESH_RENDER_PIPELINE_CREATE ++ | RGFX_CMD_COMPUTE_PIPELINE_CREATE => { ++ let job = decoder.prepare_pipeline(&rec.bytes).map_err(|e| { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "replay_record: prepare_pipeline seq={} obj={:#x} failed: {e:?}", ++ rec.seq, rec.obj_id ++ ); ++ Error::HostResources ++ })?; ++ let seen_from = job.seen_from; ++ let (compiled, _) = ++ stage::making(|| compile_refusing::

(&self.device, job)); ++ let _ = compiled.finish(0); ++ let ok = compiled.is_made(); ++ decoder.finish_pipeline_if(compiled, Some(seen_from), || true); ++ if !ok { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "replay_record: pipeline compile seq={} type={:#x} obj={:#x} refused", ++ rec.seq, rec.msg_type, rec.obj_id ++ ); ++ return Err(Error::HostResources); ++ } ++ Ok(()) ++ } ++ RGFX_CMD_RATE_MAP_CREATE | RGFX_CMD_RATE_MAP_RESET => { ++ let reset = rec.msg_type == RGFX_CMD_RATE_MAP_RESET; ++ match refusing(|| decoder.rate_map_state(&self.device, &rec.bytes, reset)) { ++ Ok(Some(st)) if st.status == RGFX_STATUS_OK => Ok(()), ++ other => { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "replay_record: rate_map seq={} obj={:#x} failed: {other:?}", ++ rec.seq, rec.obj_id ++ ); ++ Err(Error::HostResources) ++ } ++ } ++ } ++ RGFX_CMD_FUNCTION_HANDLE_CREATE | RGFX_CMD_FUNCTION_TABLE_CREATE => { ++ match refusing(|| decoder.function_pointer_state(&rec.bytes)) { ++ Ok(Some(st)) if st.status == RGFX_STATUS_OK => Ok(()), ++ other => { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "replay_record: function_pointer seq={} obj={:#x} failed: {other:?}", ++ rec.seq, rec.obj_id ++ ); ++ Err(Error::HostResources) ++ } ++ } ++ } ++ RGFX_CMD_DYNAMIC_LIBRARY_CREATE => { ++ match refusing(|| decoder.dynamic_library_create(&self.device, &rec.bytes)) { ++ Ok(Some((_, RGFX_STATUS_OK))) => Ok(()), ++ other => { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "replay_record: dynamic_library seq={} obj={:#x} failed: {other:?}", ++ rec.seq, rec.obj_id ++ ); ++ Err(Error::HostResources) ++ } ++ } ++ } ++ RGFX_CMD_SHARED_EVENT_NAME => { ++ let listen_queue = RgfxSharedEventName::read_from_prefix(&rec.bytes) ++ .map_err(|_| Error::InvalidArgument)? ++ .0 ++ .listen_queue_obj_id; ++ let listen = self.presents.queue_poster(listen_queue).map(|ring| { ++ Arc::new(move |m: &RgfxEventSignalled| ring.try_post(m.as_bytes())) ++ as ListenSink ++ }); ++ let (_, status) = decoder.name_shared_event(&rec.bytes, listen); ++ if status != RGFX_STATUS_OK { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "replay_record: shared_event_name seq={} obj={:#x} failed status={status}", ++ rec.seq, rec.obj_id ++ ); ++ return Err(Error::HostResources); ++ } ++ Ok(()) ++ } ++ RGFX_CMD_SHARED_EVENT_IMPORT => { ++ let listen_queue = RgfxSharedEventName::read_from_prefix(&rec.bytes) ++ .map_err(|_| Error::InvalidArgument)? ++ .0 ++ .listen_queue_obj_id; ++ let listen = self.presents.queue_poster(listen_queue).map(|ring| { ++ Arc::new(move |m: &RgfxEventSignalled| ring.try_post(m.as_bytes())) ++ as ListenSink ++ }); ++ match decoder.import_shared_event(&rec.bytes, listen) { ++ Some(v) if v.status == RGFX_STATUS_OK => Ok(()), ++ other => { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "replay_record: shared_event_import seq={} obj={:#x} failed: {other:?}", ++ rec.seq, rec.obj_id ++ ); ++ Err(Error::HostResources) ++ } ++ } ++ } ++ _ => match refusing(|| decoder.decode(&self.device, &rec.bytes)) { ++ Ok(Ok(())) => { ++ log::debug!( ++ target: "reims_vgpu::graphics", ++ "replay_record: seq={} ctx={} type={:#x} obj={:#x} -> Ok", ++ rec.seq, rec.context, rec.msg_type, rec.obj_id ++ ); ++ Ok(()) ++ } ++ Ok(Err(e)) => { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "replay_record: seq={} ctx={} type={:#x} obj={:#x} decode error: {e:?}", ++ rec.seq, rec.context, rec.msg_type, rec.obj_id ++ ); ++ Err(Error::HostResources) ++ } ++ Err(raise) => { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "replay_record: seq={} ctx={} type={:#x} obj={:#x} raised: {raise}", ++ rec.seq, rec.context, rec.msg_type, rec.obj_id ++ ); ++ Err(Error::HostResources) ++ } ++ }, ++ } ++ } ++ + fn handle_stage3( + self: &Arc, + poster: &CompletionPoster, +@@ -2753,6 +3191,7 @@ impl GraphicsControl

{ + claim: Option<&mut QueueClaim<'_>>, + ) { + let message: &[u8] = &bytes; ++ self.live_log.record_stage3(sender_context(poster, message), message); + let r#type = RgfxMsgHeader::read_from_prefix(message).map_or(0, |(h, _)| h.r#type); + // A queue's command buffer taken from its ring: the presents' late-show lines keep when + // the host first saw it (`present`). +@@ -3632,6 +4071,10 @@ impl GraphicsControl

{ + "library lookup (object {obj_id:#x}, {size} bytes): {}", + if status == RGFX_STATUS_OK { "hit" } else { "miss" } + ); ++ if status == RGFX_STATUS_OK { ++ self.live_log ++ .record_library_lookup(sender_context(poster, message), message); ++ } + if let Some(seqno) = seqno { + poster.post(complete(seqno, status).as_bytes()); + } +@@ -4141,7 +4584,15 @@ impl GraphicsControl

{ + .prepare_library(message) + }); + let job = match start { +- LibraryStart::Make(job) => job, ++ LibraryStart::Make(job) => { ++ self.live_log.record_library( ++ sender_context(poster, message), ++ job.obj_id, ++ job.bytes.clone(), ++ job.guest_key, ++ ); ++ job ++ } + LibraryStart::Chunk => return, + LibraryStart::Refused { error, answer } => { + let (ty, seqno, obj_id) = message_identity(message); +@@ -4214,6 +4665,7 @@ impl GraphicsControl

{ + return; + }; + if iosurface_id == 0 { ++ self.live_log.record_present(display, 0); + let color = staging.lock().take(); + self.presents + .present(display, 0, None, color, answer, Vec::new(), None); +@@ -4245,6 +4697,7 @@ impl GraphicsControl

{ + owner, + queued, + }) => { ++ self.live_log.record_present(display, iosurface_id); + // The process that made the texture over the surface the display shows owns the + // scanout (WindowServer): its compiles go first. + self.pool.favour(owner); +@@ -4788,6 +5241,7 @@ fn vt_decoders(caps: &RgfxVideoCaps) -> Vec { + /// gate's ([`reims_vgpu_vulkan::exit_gate`]): the process's exit waits for it, and one called + /// once the exit began parks its thread for good, on any thread but the exiting one (as an entry + /// does, [`entry`]'s module doc). ++#[track_caller] + fn stepped(f: impl FnOnce() -> T) -> T { + let Some(_step) = reims_vgpu_vulkan::exit_gate::step() else { + reims_vgpu_vulkan::exit_gate::stay() +diff --git a/crates/reims-vgpu/src/graphics/compile.rs b/crates/reims-vgpu/src/graphics/compile.rs +index 1c5bb492f943fe8ba303b6ac5c0af130efb41243..8813dc8627b78e865730c9d084765c6a83006d42 100644 +--- a/crates/reims-vgpu/src/graphics/compile.rs ++++ b/crates/reims-vgpu/src/graphics/compile.rs +@@ -582,6 +582,17 @@ impl CompilePool { + self.close(); + } + ++ /// Waits until all queued and running compile jobs have finished. ++ pub(crate) fn wait_idle(&self) { ++ let mut state = self.shared.state.lock(); ++ while state.waiting() > 0 ++ || state.running.values().copied().sum::() > 0 ++ || state.prepasses_running > 0 ++ { ++ self.shared.waiting.wait(&mut state); ++ } ++ } ++ + /// Ends the threads once nothing waits; later compiles run where they are handed over. + fn close(&self) { + self.shared.state.lock().closed = true; +@@ -672,10 +683,8 @@ fn run(shared: &Shared, queued: Queued) { + ms(ended.saturating_duration_since(started)), + ); + shared.state.lock().ended(of.context(), of.kind); +- // A thread that found the pre-passes' makes at their most may take the next now. +- if of.kind == CompileKind::Prepass { +- shared.waiting.notify_one(); +- } ++ // Wake waiters (pre-pass limit or snapshot quiesce wait_idle). ++ shared.waiting.notify_all(); + reims_vgpu_vulkan::os::make_ended(ended.saturating_duration_since(started)); + } + +diff --git a/crates/reims-vgpu/src/graphics/decode/library.rs b/crates/reims-vgpu/src/graphics/decode/library.rs +index 8c626c80aefb48b6f36e828a2d911021213a4bc4..f426f5365fdd5f996cff52d90b168d94c6719139 100644 +--- a/crates/reims-vgpu/src/graphics/decode/library.rs ++++ b/crates/reims-vgpu/src/graphics/decode/library.rs +@@ -402,9 +402,9 @@ pub(crate) struct LibraryJob { + pub(crate) obj_id: u64, + /// The create's seqno, which its `COMPLETE` carries. + pub(crate) seqno: u64, +- bytes: Vec, ++ pub(crate) bytes: Vec, + /// The key the guest sent with the bytes. +- guest_key: Option, ++ pub(crate) guest_key: Option, + slot: Arc>, + /// The device's resets when it was prepared. + resets: u64, +@@ -697,6 +697,29 @@ impl GraphicsDecoder

{ + }) + } + ++ /// Prepares a [`LibraryJob`] directly from snapshotted library bytes for silent replay. ++ pub(crate) fn prepare_library_bytes( ++ &self, ++ obj_id: u64, ++ bytes: Vec, ++ guest_key: Option, ++ ) -> LibraryJob

{ ++ let slot = LibrarySlot::new(); ++ let resets = { ++ let mut libraries = self.shared.libraries.lock(); ++ libraries.making.insert(obj_id, Arc::clone(&slot)); ++ libraries.resets ++ }; ++ LibraryJob { ++ obj_id, ++ seqno: 0, ++ bytes, ++ guest_key, ++ slot, ++ resets, ++ } ++ } ++ + /// One `LIBRARY_FROM_REGION` chunk: its bytes are copied out once (so the platform parses + /// memory the guest cannot change under it), its ack is written so the guest may reuse the + /// block, and the library's whole bytes are handed back once the chunks reach its length. A +diff --git a/crates/reims-vgpu/src/graphics/decode/mod.rs b/crates/reims-vgpu/src/graphics/decode/mod.rs +index b39feceac6e4360b1a678c40d5468e5a893fc44a..8929bacedd1a1dc3f248c7a11c3816e8044e973e 100644 +--- a/crates/reims-vgpu/src/graphics/decode/mod.rs ++++ b/crates/reims-vgpu/src/graphics/decode/mod.rs +@@ -220,6 +220,7 @@ mod helpers; + mod icb; + mod lane; + mod library; ++pub(crate) use library::whole_key as whole_library_key; + mod managed; + mod pipeline_key; + pub(crate) mod prepass; +@@ -264,6 +265,7 @@ pub(crate) use library::verified_key as test_key; + #[cfg(test)] + pub(crate) use library::whole_key as test_whole_key; + use library::{Libraries, LibraryRef}; ++pub(crate) use library::LibraryKey; + pub(crate) use library::{LibraryJob, LibraryStart, MadeLibrary, complete, make_library}; + use managed::{STORAGE_MODE_MANAGED, storage_mode}; + pub(crate) use pipeline_key::PipelineKey; +@@ -608,6 +610,16 @@ fn new_sampler( + /// A host handle for one guest object, by kind. Later increments read these to + /// bind resources into command buffers; this slice only inserts them on a create + /// and drops them on a destroy. ++/// Live dynamic values captured from active GPU objects during a snapshot. ++#[derive(Clone, Debug, Default)] ++pub(crate) struct LiveValues { ++ pub(crate) events: Vec<(u64, u64)>, ++ pub(crate) shared_events: Vec<(u64, u64)>, ++ pub(crate) buffers: Vec<(u64, Vec)>, ++ pub(crate) textures: Vec<(u64, Vec)>, ++ pub(crate) surface_caches: Vec<(u64, Vec)>, ++} ++ + enum ObjHandle { + Event(P::Event), + Fence(P::Fence), +@@ -3538,6 +3550,285 @@ impl GraphicsDecoder

{ + } + + /// The objects the tables hold (for the tests). ++ /// Flushes all background decoder workers (surface, let-go, close, video) for quiesce. ++ pub(crate) fn flush_workers(&self) { ++ self.shared.surface_worker.flush(); ++ self.shared.close_worker.flush(); ++ self.shared.let_go_worker.flush(); ++ self.shared.video_worker.flush(); ++ } ++ ++ /// Synchronously downloads every live device-cached IOSurface back to Guest RAM. ++ pub(crate) fn flush_all_surface_caches(&self, device: &P::Device) { ++ use reims_vgpu_vulkan::core::sync::Condvar; ++ let blocks = self.surface_caches.attached_live_blocks(); ++ for block in blocks { ++ let pair = Arc::new((Mutex::new(false), Condvar::new())); ++ let p_done = Arc::clone(&pair); ++ let p_fail = Arc::clone(&pair); ++ self.surface_download( ++ device, ++ block, ++ Box::new(move || { ++ *p_done.0.lock() = true; ++ p_done.1.notify_all(); ++ }), ++ Box::new(move |_| { ++ *p_fail.0.lock() = true; ++ p_fail.1.notify_all(); ++ }), ++ ); ++ let mut done = pair.0.lock(); ++ while !*done { ++ pair.1.wait(&mut done); ++ } ++ } ++ } ++ ++ /// Exports the resource-ID small-chunk grant table (0 = ungranted, ctx + 1 = granted to ctx). ++ pub(crate) fn export_id_chunks(&self) -> Vec { ++ self.shared ++ .id_chunks ++ .lock() ++ .iter() ++ .map(|c| c.map_or(0, |ctx| ctx.wrapping_add(1))) ++ .collect() ++ } ++ ++ /// Restores the resource-ID small-chunk grant table. ++ pub(crate) fn import_id_chunks(&self, chunks: &[u32]) { ++ let mut guard = self.shared.id_chunks.lock(); ++ let n = guard.len().min(chunks.len()); ++ for i in 0..n { ++ guard[i] = if chunks[i] == 0 { ++ None ++ } else { ++ Some(chunks[i].wrapping_sub(1)) ++ }; ++ } ++ } ++ ++ /// Replays a `SURFACE_PAGES` registration synchronously without sending a wire reply. ++ /// Restores pre-suspend seqno watermarks for a restored command queue. ++ pub(crate) fn restore_queue_watermark(&self, queue: u64, seqno: u64) { ++ self.shared ++ .surface_order ++ .lock() ++ .restore_queue_watermark(queue, seqno); ++ } ++ ++ pub(crate) fn replay_surface_pages( ++ &self, ++ device: &P::Device, ++ pages: &reims_vgpu_graphics::wire::RgfxSurfacePages, ++ runs: &[reims_vgpu_graphics::wire::RgfxPageRun], ++ flags: u32, ++ layout: Option, ++ ) -> Result<(), &'static str> { ++ let settle = self.begin_surface_pages(pages.block_offset); ++ let status = self.carry_out_surface_pages(device, pages, runs, flags, layout, &settle); ++ drop(settle); ++ match status { ++ Some(RGFX_STATUS_OK | RGFX_STATUS_CACHE) => Ok(()), ++ other => { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "snapshot replay: SURFACE_PAGES block {:#x} failed with status={other:?}", ++ pages.block_offset ++ ); ++ Err("surface_pages replay failed") ++ } ++ } ++ } ++ ++ /// Exports live GPU values (Events, SharedEvents, standalone Buffers & Textures) while quiesced. ++ pub(crate) fn export_live_values( ++ &self, ++ device: &P::Device, ++ known_ranges: &[(u64, u64)], ++ standalone_tex_ids: &std::collections::HashSet, ++ ) -> Result { ++ let mut values = LiveValues::default(); ++ let mut first_err: Option<&'static str> = None; ++ let mut contexts: Vec>> = ++ self.shared.contexts.lock().values().cloned().collect(); ++ contexts.sort_by_key(|c| c.id); ++ let in_known = |addr: u64| -> bool { ++ addr != 0 ++ && known_ranges ++ .iter() ++ .any(|&(base, len)| addr >= base && addr < base.saturating_add(len)) ++ }; ++ for ctx in contexts { ++ ctx.for_each_live(|id, entry| { ++ if first_err.is_some() { ++ return; ++ } ++ match &entry.handle { ++ ObjHandle::Event(ev) => { ++ let val = device.event_signaled_value(ev); ++ if val > 0 { ++ values.events.push((id, val)); ++ } ++ } ++ ObjHandle::SharedEvent(se) => { ++ let val = se.signaled_value(); ++ if val > 0 { ++ values.shared_events.push((id, val)); ++ } ++ } ++ ObjHandle::Buffer(buf) => { ++ if entry.span.is_none() ++ && entry.ram.is_none() ++ && !entry.over_cache ++ && !entry.over_view ++ && !in_known(buf.gpu_address()) ++ { ++ match device.read_standalone_buffer(buf) { ++ Ok(Some(bytes)) => values.buffers.push((id, bytes)), ++ Ok(None) => {} ++ Err(e) => { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "snapshot_save: buffer {id:#x} readback failed: {e}" ++ ); ++ first_err = Some(e); ++ } ++ } ++ } ++ } ++ ObjHandle::Texture(tex) => { ++ let is_deferred_cache = (entry.over_cache || entry.shape.is_some()) ++ && !entry.over_view ++ && entry ++ .span ++ .is_some_and(|(at, _)| self.surface_caches.lock().has(at)); ++ let is_standalone = standalone_tex_ids.contains(&id) ++ && !entry.over_cache ++ && !entry.over_view; ++ if is_standalone || is_deferred_cache { ++ match device.read_standalone_texture(tex) { ++ Ok(Some(bytes)) => values.textures.push((id, bytes)), ++ Ok(None) => {} ++ Err(e) => { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "snapshot_save: texture {id:#x} readback failed: {e}" ++ ); ++ first_err = Some(e); ++ } ++ } ++ } ++ } ++ _ => {} ++ } ++ }); ++ if let Some(e) = first_err { ++ return Err(e); ++ } ++ } ++ values.surface_caches = self.surface_caches.export_unattached(device)?; ++ Ok(values) ++ } ++ ++ /// Restores live GPU values onto objects previously replayed into the decoder tables. ++ pub(crate) fn import_live_values( ++ &self, ++ device: &P::Device, ++ values: &LiveValues, ++ ) -> Result<(), &'static str> { ++ for &(id, val) in &values.events { ++ let ctx = self ++ .context_state(context_of(id)) ++ .ok_or("snapshot_load: missing context for event")?; ++ let ok = ctx ++ .with_live(id, |entry| match &entry.handle { ++ ObjHandle::Event(ev) => device.event_restore_signaled_value(ev, val), ++ _ => false, ++ }) ++ .unwrap_or(false); ++ if !ok { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "snapshot_load: failed to restore event {id:#x} value={val}" ++ ); ++ return Err("snapshot_load: event value restore failed"); ++ } ++ } ++ for &(id, val) in &values.shared_events { ++ let ctx = self ++ .context_state(context_of(id)) ++ .ok_or("snapshot_load: missing context for shared event")?; ++ let ok = ctx ++ .with_live(id, |entry| match &entry.handle { ++ ObjHandle::SharedEvent(se) => se.set_signaled_value(val).is_ok(), ++ _ => false, ++ }) ++ .unwrap_or(false); ++ if !ok { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "snapshot_load: failed to restore shared event {id:#x} value={val}" ++ ); ++ return Err("snapshot_load: shared event value restore failed"); ++ } ++ } ++ for (id, bytes) in &values.buffers { ++ let ctx = self ++ .context_state(context_of(*id)) ++ .ok_or("snapshot_load: missing context for buffer")?; ++ let ok = ctx ++ .with_live(*id, |entry| match &entry.handle { ++ ObjHandle::Buffer(buf) => device.write_standalone_buffer(buf, bytes), ++ _ => false, ++ }) ++ .unwrap_or(false); ++ if !ok { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "snapshot_load: failed to restore buffer {id:#x} ({} bytes)", ++ bytes.len() ++ ); ++ return Err("snapshot_load: buffer upload failed"); ++ } ++ } ++ self.surface_caches ++ .import_unattached(device, &values.surface_caches)?; ++ for (id, bytes) in &values.textures { ++ let ctx = self ++ .context_state(context_of(*id)) ++ .ok_or("snapshot_load: missing context for texture")?; ++ let ok = ctx ++ .with_live(*id, |entry| match &entry.handle { ++ ObjHandle::Texture(tex) => { ++ if !device.write_standalone_texture(tex, bytes) { ++ return false; ++ } ++ if let Some((block, _)) = entry.span ++ && (entry.over_cache || entry.shape.is_some()) ++ { ++ let shape_id = entry.shape.as_ref().map(|s| s.reference.id()); ++ self.surface_caches ++ .lock() ++ .mark_restored_texture(block, shape_id); ++ } ++ true ++ } ++ _ => false, ++ }) ++ .unwrap_or(false); ++ if !ok { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "snapshot_load: failed to restore texture {id:#x} ({} bytes)", ++ bytes.len() ++ ); ++ return Err("snapshot_load: texture upload failed"); ++ } ++ } ++ Ok(()) ++ } ++ + #[cfg(any(test, feature = "testkit"))] + pub fn object_count(&self) -> usize { + let contexts: Vec>> = +@@ -6539,6 +6830,11 @@ impl CompiledPipeline

{ + } + } + ++ /// Whether compilation produced a live pipeline handle (not refused). ++ pub(crate) fn is_made(&self) -> bool { ++ self.handle.is_some() ++ } ++ + /// A made pipeline and its reflection. + fn made(obj_id: u64, handle: ObjHandle

, reflection: RgfxPipelineReflection) -> Self { + CompiledPipeline { +diff --git a/crates/reims-vgpu/src/graphics/decode/surface_cache.rs b/crates/reims-vgpu/src/graphics/decode/surface_cache.rs +index 27e49048da96c560f0cdafe794a526fec2186f08..e57b0ce603eb3b4ad28803102c92a09793ba252f 100644 +--- a/crates/reims-vgpu/src/graphics/decode/surface_cache.rs ++++ b/crates/reims-vgpu/src/graphics/decode/surface_cache.rs +@@ -3589,6 +3589,18 @@ impl SurfaceCaches

{ + .map(|c| c.length) + } + ++ /// Marks a deferred cache (and optional shape) as populated after snapshot texture restore. ++ pub(crate) fn mark_restored_texture(&mut self, block: u64, shape_id: Option) { ++ if let Some(cache) = self.by_block.get_mut(&block) { ++ cache.written = true; ++ cache.first_fill = None; ++ cache.zeros = false; ++ if let Some(id) = shape_id { ++ cache.shapes.mark_restored(id); ++ } ++ } ++ } ++ + /// The cache of the block `m` names where the block has no view: a deferred block's while its + /// pages are not named, or where they are copied, and a cache made with its pages copied + /// ([`Caches::make_copied`]); where the block's size holds the `m.block_size` bytes `m` names +@@ -8337,6 +8349,171 @@ impl Caches

{ + /// `trace`: `done` once the pages hold the cache, or `failed` where the platform raised at + /// the copy. + #[allow(clippy::too_many_arguments)] // the download's, and its trace ++ /// Returns all currently tracked surface cache block offsets for pre-snapshot flushing. ++ pub(crate) fn attached_live_blocks(&self) -> Vec { ++ self.lock() ++ .by_block ++ .iter() ++ .filter(|(_, c)| c.pages.is_some()) ++ .map(|(&block, _)| block) ++ .collect() ++ } ++ ++ /// Exports GPU buffer contents for deferred IOSurface device caches whose guest pages ++ /// are not named (`pages.is_none()`), flushing any dirty per-shape textures into the ++ /// cache's backing buffer first so VA-API decoded video frames and unattached WindowServer ++ /// surfaces survive suspend/resume intact. ++ pub(crate) fn export_unattached( ++ &self, ++ device: &P::Device, ++ ) -> Result)>, &'static str> { ++ let need_mem: Vec = { ++ let state = self.lock(); ++ state ++ .by_block ++ .values() ++ .filter(|c| { ++ c.pages.is_none() ++ && !c.device.memory_made() ++ && c.shapes.iter().any(|s| s.dirty) ++ }) ++ .map(|c| c.device.clone_ref()) ++ .collect() ++ }; ++ self.make_memory(need_mem, MemoryFor::WriteBack); ++ ++ let mut flushed_any = false; ++ { ++ let mut state = self.lock(); ++ let dirty_blocks: Vec = state ++ .by_block ++ .iter() ++ .filter(|(_, c)| c.pages.is_none() && c.shapes.iter().any(|s| s.dirty)) ++ .map(|(&b, _)| b) ++ .collect(); ++ if !dirty_blocks.is_empty() { ++ if !state ++ .make_transfer(device) ++ .map_err(|_| "snapshot_save: surface cache transfer init failed")? ++ { ++ return Err("snapshot_save: surface cache transfer queue unavailable"); ++ } ++ for block in dirty_blocks { ++ let cb_opt = { ++ let transfer = state ++ .transfer ++ .as_mut() ++ .ok_or("snapshot_save: surface cache transfer missing")?; ++ transfer ++ .queue ++ .command_buffer(ON) ++ .map_err(|_| "snapshot_save: surface cache command buffer failed")? ++ }; ++ let Some(cb) = cb_opt else { ++ return Err("snapshot_save: surface cache command buffer unavailable"); ++ }; ++ let Some(cache) = state.by_block.get_mut(&block) else { ++ continue; ++ }; ++ if !cache.copy_through(MemoryFor::WriteBack) { ++ return Err("snapshot_save: deferred surface cache allocation failed"); ++ } ++ let back = shapes::write_back::

(&cb, &cache.device, &cache.shapes, |s| { ++ s.dirty ++ }) ++ .map_err(|_| "snapshot_save: surface cache shape write_back failed")?; ++ cache.wrote_shapes(&back); ++ state.owed_commits.push(cb); ++ flushed_any = true; ++ } ++ } ++ } ++ if flushed_any { ++ device.wait_idle(); ++ } ++ ++ let mut to_read: Vec<(u64, P::Buffer)> = { ++ let state = self.lock(); ++ state ++ .by_block ++ .iter() ++ .filter(|(_, c)| c.pages.is_none() && c.device.memory_made()) ++ .map(|(&block, c)| (block, c.device.clone_ref())) ++ .collect() ++ }; ++ to_read.sort_by_key(|(block, _)| *block); ++ ++ let mut out = Vec::with_capacity(to_read.len()); ++ for (block, buf) in to_read { ++ match device.read_standalone_buffer(&buf)? { ++ Some(bytes) => out.push((block, bytes)), ++ None => return Err("snapshot_save: unattached surface cache buffer unreadable"), ++ } ++ } ++ Ok(out) ++ } ++ ++ /// Restores GPU buffer contents for deferred unattached IOSurface device caches. ++ pub(crate) fn import_unattached( ++ &self, ++ device: &P::Device, ++ entries: &[(u64, Vec)], ++ ) -> Result<(), &'static str> { ++ if entries.is_empty() { ++ return Ok(()); ++ } ++ let targets: Vec<(u64, P::Buffer)> = { ++ let state = self.lock(); ++ let mut out = Vec::with_capacity(entries.len()); ++ for (block, _) in entries { ++ let cache = state ++ .by_block ++ .get(block) ++ .ok_or("snapshot_load: missing unattached surface cache")?; ++ out.push((*block, cache.device.clone_ref())); ++ } ++ out ++ }; ++ let need_mem: Vec = targets ++ .iter() ++ .filter(|(_, b)| !b.memory_made()) ++ .map(|(_, b)| b.clone_ref()) ++ .collect(); ++ self.make_memory(need_mem, MemoryFor::Fill); ++ ++ for ((block, buf), (_, bytes)) in targets.iter().zip(entries.iter()) { ++ if !buf.memory_made() { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "snapshot_load: failed to allocate memory for unattached surface cache {block:#x}" ++ ); ++ return Err("snapshot_load: surface cache memory allocation failed"); ++ } ++ if !device.write_standalone_buffer(buf, bytes) { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "snapshot_load: failed to upload unattached surface cache {block:#x} ({} bytes)", ++ bytes.len() ++ ); ++ return Err("snapshot_load: surface cache upload failed"); ++ } ++ } ++ ++ let mut state = self.lock(); ++ for (block, _) in entries { ++ if let Some(cache) = state.by_block.get_mut(block) { ++ let _ = cache.copy_through(MemoryFor::Fill); ++ cache.written = true; ++ cache.first_fill = None; ++ cache.zeros = false; ++ cache.lacks = false; ++ cache.changed = Changed::All; ++ cache.shapes.mark_owed_all(); ++ } ++ } ++ Ok(()) ++ } ++ + pub(crate) fn download( + &self, + device: &P::Device, +diff --git a/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs b/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs +index eef3c5ef0e1297204a7344bc10eea333182b5ac1..f98695af9b83e699b9f7e87219baf9eb2246b3a6 100644 +--- a/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs ++++ b/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs +@@ -914,6 +914,23 @@ impl ShapeTable { + shape.map(|s| s.dirty = true).is_some() + } + ++ /// Marks a shape whose pixels were directly uploaded during snapshot restore as valid & dirty. ++ pub(crate) fn mark_restored(&mut self, id: u64) { ++ if let Some(s) = self.shapes.iter_mut().find(|s| s.id() == id) { ++ s.owed = false; ++ s.dirty = true; ++ s.cleared = false; ++ } ++ } ++ ++ pub(crate) fn mark_owed_all(&mut self) { ++ for s in &mut self.shapes { ++ s.owed = true; ++ s.cleared = false; ++ s.clean(); ++ } ++ } ++ + /// A video command buffer wrote the buffer, its decodes' pictures, not the images: every + /// shape owes a fill from it, its own write before the buffer's lost (the decode writes its + /// planes whole, and a write it does not cover was copied into the buffer before it ran); +diff --git a/crates/reims-vgpu/src/graphics/decode/surface_order.rs b/crates/reims-vgpu/src/graphics/decode/surface_order.rs +index ad08151f5256e959c46bf08f79cff98b0140b70e..c315b96ed11d9116e1c54e118f33d417a419795b 100644 +--- a/crates/reims-vgpu/src/graphics/decode/surface_order.rs ++++ b/crates/reims-vgpu/src/graphics/decode/surface_order.rs +@@ -292,6 +292,17 @@ impl Marks { + self.done.load(Ordering::Acquire), + ) + } ++ ++ /// Advances all per-queue watermarks to `seqno` after snapshot restore (all pre-suspend work ++ /// finished during quiesce). ++ pub(crate) fn restore_watermark(&self, seqno: u64) { ++ self.taken.fetch_max(seqno, Ordering::SeqCst); ++ self.signalled.fetch_max(seqno, Ordering::SeqCst); ++ self.committed.fetch_max(seqno, Ordering::SeqCst); ++ self.done.fetch_max(seqno, Ordering::SeqCst); ++ self.commit.begin(seqno); ++ self.commit.raise(seqno); ++ } + } + + /// A signal a command buffer carries: its queue's `done` rises to `seqno` once it finishes. +@@ -862,6 +873,19 @@ impl SurfaceOrder

{ + q.buffers = Some(buffers); + } + ++ /// Restores a queue's commit/surface-order watermarks and timeline event value after snapshot load. ++ pub(crate) fn restore_queue_watermark(&mut self, queue: u64, seqno: u64) { ++ if seqno == 0 { ++ return; ++ } ++ if let Some(q) = self.queues.get(&queue) { ++ q.marks.restore_watermark(seqno); ++ if let Some(ev) = &q.event { ++ let _ = ev.set_signaled_value(seqno); ++ } ++ } ++ } ++ + /// What a removal from context `context`'s table waits for before its entry is let go of + /// ([`super::tables`], "After the buffers posted before it"): each queue of the context the + /// decoder made and that has not ended, whose ring published a command buffer its commit mark +diff --git a/crates/reims-vgpu/src/graphics/present.rs b/crates/reims-vgpu/src/graphics/present.rs +index a1fc887bd509b6c90d82b7a134be162bfc7a6ccc..20e3f7496d65d713e518ebe0d1e3e43748770766 100644 +--- a/crates/reims-vgpu/src/graphics/present.rs ++++ b/crates/reims-vgpu/src/graphics/present.rs +@@ -272,6 +272,16 @@ impl PresentQueue

{ + self.state.lock().queues.insert(queue, poster); + } + ++ /// Advances the finished watermark for a restored queue so pre-suspend surface writers never stall. ++ pub(crate) fn restore_finished(&self, queue: u64, seqno: u64) { ++ if seqno == 0 { ++ return; ++ } ++ let mut st = self.state.lock(); ++ let done = st.finished.entry(queue).or_insert(0); ++ *done = (*done).max(seqno); ++ } ++ + /// Shows IOSurface `id`'s `texture` (`None`: the scanout) on display `display`, with the + /// colour stages `color` sets, once each command buffer in `writers` has finished, and + /// `fill`, its surface's device cache's fill, where it has one, and every present of the +diff --git a/crates/reims-vgpu/src/graphics/snapshot.rs b/crates/reims-vgpu/src/graphics/snapshot.rs +new file mode 100644 +index 0000000000000000000000000000000000000000..70a3cec742ef2a3c75d074749593fe6f58f37067 +--- /dev/null ++++ b/crates/reims-vgpu/src/graphics/snapshot.rs +@@ -0,0 +1,1151 @@ ++//! Full GPU device snapshot (`LiveLog` + `RVGSNAP1` binary codec) for suspend-to-disk & resume. ++ ++use std::collections::{BTreeMap, HashMap, HashSet}; ++ ++use reims_vgpu_graphics::wire::{ ++ RGFX_CMD_BUFFER_AT_OFFSET, RGFX_CMD_BUFFER_CREATE, RGFX_CMD_BUFFER_ESCAPED, ++ RGFX_CMD_BUFFER_MANAGED_AT_OFFSET, RGFX_CMD_BUFFER_OVER_HOST_MEMORY, ++ RGFX_CMD_BUFFER_OVER_PAGES, RGFX_CMD_BUFFER_OVER_SURFACE_PAGES, ++ RGFX_CMD_COMPUTE_PIPELINE_CREATE, RGFX_CMD_DEPTH_STENCIL_CREATE, ++ RGFX_CMD_DYNAMIC_LIBRARY_CREATE, RGFX_CMD_EVENT_CREATE, RGFX_CMD_FENCE_CREATE, ++ RGFX_CMD_FUNCTION_HANDLE_CREATE, RGFX_CMD_FUNCTION_TABLE_CREATE, ++ RGFX_CMD_FUNCTION_TABLE_SET, RGFX_CMD_HEAP_CREATE, RGFX_CMD_HEAP_OVER_HOST_MEMORY, ++ RGFX_CMD_HEAP_OVER_PAGES, RGFX_CMD_HEAP_OVER_POOL, RGFX_CMD_ICB_CREATE, ++ RGFX_CMD_ICB_SLOTS, RGFX_CMD_ICB_SLOTS_IN_PAGES, RGFX_CMD_ICB_WRITE, ++ RGFX_CMD_LIBRARY_LOOKUP, RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER, RGFX_CMD_MANAGED_BUFFER_CREATE, ++ RGFX_CMD_MANAGED_TEXTURE_CREATE, RGFX_CMD_MESH_RENDER_PIPELINE_CREATE, ++ RGFX_CMD_OBJECT_DESTROY, RGFX_CMD_QUEUE_CREATE, RGFX_CMD_RATE_MAP_CREATE, ++ RGFX_CMD_RATE_MAP_RESET, RGFX_CMD_RENDER_PIPELINE_CREATE, RGFX_CMD_SAMPLER_CREATE, ++ RGFX_CMD_SHARED_EVENT_CREATE, RGFX_CMD_SHARED_EVENT_IMPORT, RGFX_CMD_SHARED_EVENT_NAME, ++ RGFX_CMD_SHARED_EVENT_UNNAME, RGFX_CMD_TEXTURE_CREATE, RGFX_CMD_TEXTURE_FROM_BUFFER, ++ RGFX_CMD_TEXTURE_FROM_IOSURFACE, RGFX_CMD_TEXTURE_VIEW, RGFX_SURFACE_PAGES_ATTACH, ++ RgfxComputePipelineCreate, RgfxDynamicLibraryCreate, RgfxFunctionHandleCreate, ++ RgfxFunctionTableSet, RgfxLibraryLookup, RgfxLinearTextureFromBuffer, RgfxLinkedFunction, ++ RgfxMeshRenderPipelineCreate, RgfxMsgHeader, RgfxObjectDestroy, RgfxPageRun, ++ RgfxPipelineLibrary, RgfxRenderPipelineCreate, RgfxSharedEventImport, RgfxSharedEventName, ++ RgfxSharedEventUnname, RgfxSurfacePages, RgfxSurfacePagesLayout, RgfxTextureCreate, ++ RgfxTextureFromBuffer, RgfxTextureView, ++}; ++use reims_vgpu_vulkan::core::sync::Mutex; ++use zerocopy::{FromBytes, IntoBytes}; ++ ++use crate::pool::{ ++ BlockCapture, MemoryClass, PoolCarveSnapshot, PoolPieceSnapshot, PoolSnapshot, ++ PrivateBlockSnapshot, PrivateBlocksSnapshot, ++}; ++ ++use super::decode::{LibraryKey, LiveValues}; ++ ++pub(crate) const SNAPSHOT_MAGIC: &[u8; 8] = b"RVGSNAP1"; ++pub(crate) const SNAPSHOT_VERSION: u32 = 1; ++ ++/// Synthetic tag stored in [`LogRecord::msg_type`] for assembled libraries (covers both inline ++/// `LIBRARY_CREATE` and chunked `LIBRARY_FROM_REGION`). ++pub(crate) const LOG_TAG_ASSEMBLED_LIBRARY: u32 = 0xFFFF_0001; ++ ++/// A recorded live object creation or persistent state mutation. ++#[derive(Clone, Debug)] ++pub(crate) struct LogRecord { ++ pub(crate) seq: u64, ++ pub(crate) context: u32, ++ pub(crate) obj_id: u64, ++ pub(crate) msg_type: u32, ++ /// Raw wire message bytes (or for `LOG_TAG_ASSEMBLED_LIBRARY`, optional 32-byte key if present). ++ pub(crate) bytes: Vec, ++ /// Assembled library bytes (for `LOG_TAG_ASSEMBLED_LIBRARY`), empty otherwise. ++ pub(crate) inline_bytes: Vec, ++} ++ ++/// Recorded `SURFACE_PAGES` registration for an active shared guest-RAM block. ++#[derive(Clone, Debug)] ++pub(crate) struct SurfacePagesRecord { ++ pub(crate) pages: RgfxSurfacePages, ++ pub(crate) runs: Vec, ++ pub(crate) flags: u32, ++ pub(crate) layout: Option, ++} ++ ++#[derive(Default)] ++struct LiveLogState { ++ next_seq: u64, ++ records: Vec, ++ surface_pages: BTreeMap>, ++ standalone_textures: HashSet, ++ presented_surfaces: Vec, ++ library_bytes_by_key: HashMap>, ++} ++ ++/// Records live guest GPU object creations & persistent mutations so a fresh host process can ++/// reconstruct the exact Metal/Vulkan object table without re-executing past draws or dispatches. ++pub(crate) struct LiveLog { ++ state: Mutex, ++} ++ ++impl LiveLog { ++ pub(crate) fn new(displays: usize) -> Self { ++ Self { ++ state: Mutex::new(LiveLogState { ++ presented_surfaces: vec![0; displays], ++ ..LiveLogState::default() ++ }), ++ } ++ } ++ ++ pub(crate) fn record_stage3(&self, context: u32, message: &[u8]) { ++ let Ok((hdr, _)) = RgfxMsgHeader::read_from_prefix(message) else { ++ return; ++ }; ++ match hdr.r#type { ++ RGFX_CMD_OBJECT_DESTROY => { ++ if let Ok((m, _)) = RgfxObjectDestroy::read_from_prefix(message) { ++ let mut st = self.state.lock(); ++ st.standalone_textures.remove(&m.obj_id); ++ let prev_destroy = st ++ .records ++ .iter() ++ .rposition(|r| { ++ r.obj_id == m.obj_id && r.msg_type == RGFX_CMD_OBJECT_DESTROY ++ }); ++ let search_from = prev_destroy.map_or(0, |i| i + 1); ++ let Some(inc_rel) = st.records[search_from..] ++ .iter() ++ .position(|r| r.obj_id == m.obj_id) ++ else { ++ return; ++ }; ++ let inc_start = search_from + inc_rel; ++ let inc_seq = st.records[inc_start].seq; ++ let mut named_events: Vec = Vec::new(); ++ for r in &st.records[inc_start..] { ++ if r.obj_id == m.obj_id && r.msg_type == RGFX_CMD_SHARED_EVENT_NAME { ++ if let Ok((n, _)) = RgfxSharedEventName::read_from_prefix(&r.bytes) { ++ named_events.push(n.name); ++ } ++ } ++ } ++ let referenced = st.records[inc_start + 1..].iter().any(|r| { ++ if r.obj_id == m.obj_id { ++ return false; ++ } ++ if record_parent_ids(r).contains(&m.obj_id) { ++ return true; ++ } ++ if !named_events.is_empty() && r.msg_type == RGFX_CMD_SHARED_EVENT_IMPORT { ++ if let Ok((imp, _)) = RgfxSharedEventImport::read_from_prefix(&r.bytes) ++ { ++ return named_events.contains(&imp.name); ++ } ++ } ++ false ++ }); ++ if referenced { ++ let seq = st.next_seq; ++ st.next_seq = st.next_seq.wrapping_add(1); ++ st.records.push(LogRecord { ++ seq, ++ context, ++ obj_id: m.obj_id, ++ msg_type: RGFX_CMD_OBJECT_DESTROY, ++ bytes: message.to_vec(), ++ inline_bytes: Vec::new(), ++ }); ++ } else { ++ st.records ++ .retain(|r| !(r.obj_id == m.obj_id && r.seq >= inc_seq)); ++ } ++ } ++ } ++ RGFX_CMD_SHARED_EVENT_UNNAME => { ++ if let Ok((m, _)) = RgfxSharedEventUnname::read_from_prefix(message) { ++ let mut st = self.state.lock(); ++ let name_pos = st.records.iter().rposition(|r| { ++ r.msg_type == RGFX_CMD_SHARED_EVENT_NAME ++ && RgfxSharedEventName::read_from_prefix(&r.bytes) ++ .is_ok_and(|(n, _)| n.name == m.name) ++ }); ++ let Some(pos) = name_pos else { ++ return; ++ }; ++ let imported = st.records[pos + 1..].iter().any(|r| { ++ r.msg_type == RGFX_CMD_SHARED_EVENT_IMPORT ++ && RgfxSharedEventImport::read_from_prefix(&r.bytes) ++ .is_ok_and(|(imp, _)| imp.name == m.name) ++ }); ++ if imported { ++ let seq = st.next_seq; ++ st.next_seq = st.next_seq.wrapping_add(1); ++ st.records.push(LogRecord { ++ seq, ++ context, ++ obj_id: 0, ++ msg_type: RGFX_CMD_SHARED_EVENT_UNNAME, ++ bytes: message.to_vec(), ++ inline_bytes: Vec::new(), ++ }); ++ } else { ++ st.records.remove(pos); ++ } ++ } ++ } ++ ty if is_persistent_stage3(ty) => { ++ let obj_id = message ++ .get(16..24) ++ .and_then(|b| b.try_into().ok()) ++ .map(u64::from_le_bytes) ++ .unwrap_or(0); ++ let mut st = self.state.lock(); ++ if matches!( ++ ty, ++ RGFX_CMD_TEXTURE_CREATE ++ | RGFX_CMD_MANAGED_TEXTURE_CREATE ++ | RGFX_CMD_TEXTURE_FROM_BUFFER ++ | RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER ++ ) && obj_id != 0 ++ { ++ st.standalone_textures.insert(obj_id); ++ } ++ let seq = st.next_seq; ++ st.next_seq = st.next_seq.wrapping_add(1); ++ st.records.push(LogRecord { ++ seq, ++ context, ++ obj_id, ++ msg_type: ty, ++ bytes: message.to_vec(), ++ inline_bytes: Vec::new(), ++ }); ++ } ++ _ => {} ++ } ++ } ++ ++ pub(crate) fn record_library( ++ &self, ++ context: u32, ++ obj_id: u64, ++ bytes: Vec, ++ guest_key: Option, ++ ) { ++ let mut st = self.state.lock(); ++ if let Some(k) = guest_key { ++ st.library_bytes_by_key.insert(k, bytes.clone()); ++ if let Some(wk) = super::decode::whole_library_key(&bytes) ++ && wk != k ++ { ++ st.library_bytes_by_key.insert(wk, bytes.clone()); ++ } ++ } ++ let seq = st.next_seq; ++ st.next_seq = st.next_seq.wrapping_add(1); ++ st.records.push(LogRecord { ++ seq, ++ context, ++ obj_id, ++ msg_type: LOG_TAG_ASSEMBLED_LIBRARY, ++ bytes: guest_key.map(|k| k.to_vec()).unwrap_or_default(), ++ inline_bytes: bytes, ++ }); ++ } ++ ++ pub(crate) fn record_library_lookup(&self, context: u32, message: &[u8]) { ++ let Ok((m, _)) = RgfxLibraryLookup::read_from_prefix(message) else { ++ return; ++ }; ++ let mut st = self.state.lock(); ++ let seq = st.next_seq; ++ st.next_seq = st.next_seq.wrapping_add(1); ++ if let Some(inline_bytes) = st.library_bytes_by_key.get(&m.key).cloned() { ++ st.records.push(LogRecord { ++ seq, ++ context, ++ obj_id: m.obj_id, ++ msg_type: LOG_TAG_ASSEMBLED_LIBRARY, ++ bytes: m.key.to_vec(), ++ inline_bytes, ++ }); ++ } else { ++ st.records.push(LogRecord { ++ seq, ++ context, ++ obj_id: m.obj_id, ++ msg_type: RGFX_CMD_LIBRARY_LOOKUP, ++ bytes: message.to_vec(), ++ inline_bytes: Vec::new(), ++ }); ++ } ++ } ++ ++ pub(crate) fn record_surface_pages( ++ &self, ++ pages: RgfxSurfacePages, ++ runs: Vec, ++ flags: u32, ++ layout: Option, ++ ) { ++ let rec = SurfacePagesRecord { ++ pages, ++ runs, ++ flags, ++ layout, ++ }; ++ let mut st = self.state.lock(); ++ if flags & RGFX_SURFACE_PAGES_ATTACH != 0 { ++ st.surface_pages.entry(pages.block_offset).or_default().push(rec); ++ } else { ++ st.surface_pages.insert(pages.block_offset, vec![rec]); ++ } ++ } ++ ++ pub(crate) fn forget_surface_pages(&self, block_offset: u64) { ++ self.state.lock().surface_pages.remove(&block_offset); ++ } ++ ++ pub(crate) fn record_present(&self, display: usize, iosurface_id: u32) { ++ let mut st = self.state.lock(); ++ if let Some(slot) = st.presented_surfaces.get_mut(display) { ++ *slot = iosurface_id; ++ } ++ } ++ ++ pub(crate) fn close_context(&self, context: u32) { ++ let mut st = self.state.lock(); ++ let removed: HashSet = st ++ .records ++ .iter() ++ .filter(|r| r.context == context) ++ .map(|r| r.obj_id) ++ .collect(); ++ st.records.retain(|r| r.context != context); ++ st.standalone_textures.retain(|id| !removed.contains(id)); ++ st.surface_pages.retain(|_, v| { ++ v.retain(|sp| sp.pages.context != context); ++ !v.is_empty() ++ }); ++ } ++ ++ pub(crate) fn reset(&self) { ++ let mut st = self.state.lock(); ++ st.records.clear(); ++ st.surface_pages.clear(); ++ st.standalone_textures.clear(); ++ for slot in &mut st.presented_surfaces { ++ *slot = 0; ++ } ++ } ++ ++ pub(crate) fn export( ++ &self, ++ ) -> ( ++ Vec, ++ Vec, ++ HashSet, ++ Vec, ++ ) { ++ let st = self.state.lock(); ++ ( ++ compact_records(&st.records), ++ st.surface_pages.values().flatten().cloned().collect(), ++ st.standalone_textures.clone(), ++ st.presented_surfaces.clone(), ++ ) ++ } ++ ++ pub(crate) fn restore( ++ &self, ++ records: Vec, ++ surface_pages: Vec, ++ standalone_textures: HashSet, ++ presented_surfaces: Vec, ++ ) { ++ let mut st = self.state.lock(); ++ let max_seq = records.iter().map(|r| r.seq).max().unwrap_or(0); ++ st.next_seq = max_seq.wrapping_add(1); ++ st.library_bytes_by_key.clear(); ++ for r in &records { ++ if r.msg_type == LOG_TAG_ASSEMBLED_LIBRARY ++ && r.bytes.len() == 32 ++ && !r.inline_bytes.is_empty() ++ && let Ok(k) = <[u8; 32]>::try_from(r.bytes.as_slice()) ++ { ++ st.library_bytes_by_key.insert(k, r.inline_bytes.clone()); ++ if let Some(wk) = super::decode::whole_library_key(&r.inline_bytes) ++ && wk != k ++ { ++ st.library_bytes_by_key.insert(wk, r.inline_bytes.clone()); ++ } ++ } ++ } ++ st.records = records; ++ st.surface_pages.clear(); ++ for sp in surface_pages { ++ st.surface_pages.entry(sp.pages.block_offset).or_default().push(sp); ++ } ++ st.standalone_textures = standalone_textures; ++ let n = st.presented_surfaces.len().min(presented_surfaces.len()); ++ st.presented_surfaces[..n].copy_from_slice(&presented_surfaces[..n]); ++ } ++} ++ ++fn is_persistent_stage3(ty: u32) -> bool { ++ matches!( ++ ty, ++ RGFX_CMD_EVENT_CREATE ++ | RGFX_CMD_FENCE_CREATE ++ | RGFX_CMD_SHARED_EVENT_CREATE ++ | RGFX_CMD_SHARED_EVENT_IMPORT ++ | RGFX_CMD_SHARED_EVENT_NAME ++ | RGFX_CMD_QUEUE_CREATE ++ | RGFX_CMD_DYNAMIC_LIBRARY_CREATE ++ | RGFX_CMD_SAMPLER_CREATE ++ | RGFX_CMD_DEPTH_STENCIL_CREATE ++ | RGFX_CMD_BUFFER_CREATE ++ | RGFX_CMD_BUFFER_OVER_HOST_MEMORY ++ | RGFX_CMD_BUFFER_OVER_SURFACE_PAGES ++ | RGFX_CMD_BUFFER_OVER_PAGES ++ | RGFX_CMD_BUFFER_MANAGED_AT_OFFSET ++ | RGFX_CMD_MANAGED_BUFFER_CREATE ++ | RGFX_CMD_BUFFER_AT_OFFSET ++ | RGFX_CMD_BUFFER_ESCAPED ++ | RGFX_CMD_HEAP_CREATE ++ | RGFX_CMD_HEAP_OVER_HOST_MEMORY ++ | RGFX_CMD_HEAP_OVER_POOL ++ | RGFX_CMD_HEAP_OVER_PAGES ++ | RGFX_CMD_TEXTURE_CREATE ++ | RGFX_CMD_MANAGED_TEXTURE_CREATE ++ | RGFX_CMD_TEXTURE_VIEW ++ | RGFX_CMD_TEXTURE_FROM_BUFFER ++ | RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER ++ | RGFX_CMD_TEXTURE_FROM_IOSURFACE ++ | RGFX_CMD_RENDER_PIPELINE_CREATE ++ | RGFX_CMD_MESH_RENDER_PIPELINE_CREATE ++ | RGFX_CMD_COMPUTE_PIPELINE_CREATE ++ | RGFX_CMD_ICB_CREATE ++ | RGFX_CMD_ICB_WRITE ++ | RGFX_CMD_ICB_SLOTS ++ | RGFX_CMD_ICB_SLOTS_IN_PAGES ++ | RGFX_CMD_RATE_MAP_CREATE ++ | RGFX_CMD_RATE_MAP_RESET ++ | RGFX_CMD_FUNCTION_HANDLE_CREATE ++ | RGFX_CMD_FUNCTION_TABLE_CREATE ++ | RGFX_CMD_FUNCTION_TABLE_SET ++ ) ++} ++ ++fn push_linked_libraries(out: &mut Vec, bytes: &[u8], offset: u32, count: u32) { ++ let Ok(start) = usize::try_from(offset) else { ++ return; ++ }; ++ let Ok(n) = usize::try_from(count) else { ++ return; ++ }; ++ let elem = std::mem::size_of::(); ++ for i in 0..n { ++ let Some(at) = i.checked_mul(elem).and_then(|d| start.checked_add(d)) else { ++ break; ++ }; ++ let Some(slice) = bytes.get(at..) else { ++ break; ++ }; ++ let Ok((lf, _)) = RgfxLinkedFunction::read_from_prefix(slice) else { ++ break; ++ }; ++ if lf.library_obj_id != 0 { ++ out.push(lf.library_obj_id); ++ } ++ } ++} ++ ++fn push_pipeline_libraries(out: &mut Vec, bytes: &[u8], end_of_fixed: usize, count: u32) { ++ let Ok(n) = usize::try_from(count) else { ++ return; ++ }; ++ let elem = std::mem::size_of::(); ++ let Some(total) = n.checked_mul(elem) else { ++ return; ++ }; ++ let Some(start) = bytes.len().checked_sub(total) else { ++ return; ++ }; ++ if start < end_of_fixed { ++ return; ++ } ++ for i in 0..n { ++ let Some(slice) = bytes.get(start + i * elem..) else { ++ break; ++ }; ++ let Ok((pl, _)) = RgfxPipelineLibrary::read_from_prefix(slice) else { ++ break; ++ }; ++ if pl.obj_id != 0 { ++ out.push(pl.obj_id); ++ } ++ } ++} ++ ++/// Returns all parent object IDs referenced when replaying `rec`. ++fn record_parent_ids(rec: &LogRecord) -> Vec { ++ let mut out = Vec::new(); ++ let b = &rec.bytes; ++ match rec.msg_type { ++ RGFX_CMD_RENDER_PIPELINE_CREATE => { ++ if let Ok((m, _)) = RgfxRenderPipelineCreate::read_from_prefix(b) { ++ if m.vertex_library_obj_id != 0 { ++ out.push(m.vertex_library_obj_id); ++ } ++ if m.fragment_library_obj_id != 0 { ++ out.push(m.fragment_library_obj_id); ++ } ++ push_linked_libraries(&mut out, b, m.vertex_linked_offset, m.vertex_linked_count); ++ push_linked_libraries( ++ &mut out, ++ b, ++ m.fragment_linked_offset, ++ m.fragment_linked_count, ++ ); ++ } ++ } ++ RGFX_CMD_MESH_RENDER_PIPELINE_CREATE => { ++ if let Ok((m, _)) = RgfxMeshRenderPipelineCreate::read_from_prefix(b) { ++ if m.object_library_obj_id != 0 { ++ out.push(m.object_library_obj_id); ++ } ++ if m.mesh_library_obj_id != 0 { ++ out.push(m.mesh_library_obj_id); ++ } ++ if m.fragment_library_obj_id != 0 { ++ out.push(m.fragment_library_obj_id); ++ } ++ push_linked_libraries(&mut out, b, m.object_linked_offset, m.object_linked_count); ++ push_linked_libraries(&mut out, b, m.mesh_linked_offset, m.mesh_linked_count); ++ push_linked_libraries( ++ &mut out, ++ b, ++ m.fragment_linked_offset, ++ m.fragment_linked_count, ++ ); ++ } ++ } ++ RGFX_CMD_COMPUTE_PIPELINE_CREATE => { ++ if let Ok((m, _)) = RgfxComputePipelineCreate::read_from_prefix(b) { ++ if m.function_library_obj_id != 0 { ++ out.push(m.function_library_obj_id); ++ } ++ push_linked_libraries(&mut out, b, m.linked_offset, m.linked_count); ++ push_pipeline_libraries( ++ &mut out, ++ b, ++ std::mem::size_of::(), ++ m.library_count, ++ ); ++ } ++ } ++ RGFX_CMD_DYNAMIC_LIBRARY_CREATE => { ++ if let Ok((m, _)) = RgfxDynamicLibraryCreate::read_from_prefix(b) ++ && m.library_obj_id != 0 ++ { ++ out.push(m.library_obj_id); ++ } ++ } ++ RGFX_CMD_FUNCTION_HANDLE_CREATE => { ++ if let Ok((m, _)) = RgfxFunctionHandleCreate::read_from_prefix(b) { ++ if m.pipeline_obj_id != 0 { ++ out.push(m.pipeline_obj_id); ++ } ++ if m.function.library_obj_id != 0 { ++ out.push(m.function.library_obj_id); ++ } ++ } ++ } ++ RGFX_CMD_FUNCTION_TABLE_SET => { ++ if let Ok((m, rest)) = RgfxFunctionTableSet::read_from_prefix(b) { ++ let count = m.count as usize; ++ for chunk in rest.chunks_exact(8).take(count) { ++ if let Ok(arr) = <[u8; 8]>::try_from(chunk) { ++ let id = u64::from_le_bytes(arr); ++ if id != 0 { ++ out.push(id); ++ } ++ } ++ } ++ } ++ } ++ RGFX_CMD_TEXTURE_VIEW => { ++ if let Ok((m, _)) = RgfxTextureView::read_from_prefix(b) ++ && m.parent_obj_id != 0 ++ { ++ out.push(m.parent_obj_id); ++ } ++ } ++ RGFX_CMD_TEXTURE_CREATE => { ++ if let Ok((m, _)) = RgfxTextureCreate::read_from_prefix(b) ++ && m.heap_obj_id != 0 ++ { ++ out.push(m.heap_obj_id); ++ } ++ } ++ RGFX_CMD_TEXTURE_FROM_BUFFER => { ++ if let Ok((m, _)) = RgfxTextureFromBuffer::read_from_prefix(b) ++ && m.buffer_obj_id != 0 ++ { ++ out.push(m.buffer_obj_id); ++ } ++ } ++ RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER => { ++ if let Ok((m, _)) = RgfxLinearTextureFromBuffer::read_from_prefix(b) ++ && m.buffer_obj_id != 0 ++ { ++ out.push(m.buffer_obj_id); ++ } ++ } ++ RGFX_CMD_SHARED_EVENT_NAME => { ++ if let Ok((m, _)) = RgfxSharedEventName::read_from_prefix(b) ++ && m.listen_queue_obj_id != 0 ++ { ++ out.push(m.listen_queue_obj_id); ++ } ++ } ++ RGFX_CMD_SHARED_EVENT_IMPORT => { ++ if let Ok((m, _)) = RgfxSharedEventImport::read_from_prefix(b) ++ && m.listen_queue_obj_id != 0 ++ { ++ out.push(m.listen_queue_obj_id); ++ } ++ } ++ _ => {} ++ } ++ out ++} ++ ++/// Drops destroyed incarnations that are no longer transitively referenced by any live object. ++fn compact_records(records: &[LogRecord]) -> Vec { ++ let mut active_inc: HashMap = HashMap::new(); ++ let mut active_name_inc: HashMap = HashMap::new(); ++ let mut destroyed: Vec = Vec::new(); ++ let mut deps: Vec> = Vec::new(); ++ let mut rec_inc: Vec> = Vec::with_capacity(records.len()); ++ ++ for r in records { ++ match r.msg_type { ++ RGFX_CMD_OBJECT_DESTROY => { ++ if let Some(inc) = active_inc.remove(&r.obj_id) { ++ destroyed[inc] = true; ++ rec_inc.push(Some(inc)); ++ } else { ++ rec_inc.push(None); ++ } ++ } ++ RGFX_CMD_SHARED_EVENT_UNNAME => { ++ let inc = RgfxSharedEventUnname::read_from_prefix(&r.bytes) ++ .ok() ++ .and_then(|(m, _)| active_name_inc.remove(&m.name)); ++ rec_inc.push(inc); ++ } ++ _ => { ++ let inc = if r.obj_id != 0 { ++ *active_inc.entry(r.obj_id).or_insert_with(|| { ++ let id = destroyed.len(); ++ destroyed.push(false); ++ deps.push(Vec::new()); ++ id ++ }) ++ } else { ++ let id = destroyed.len(); ++ destroyed.push(false); ++ deps.push(Vec::new()); ++ id ++ }; ++ for pid in record_parent_ids(r) { ++ if let Some(&pinc) = active_inc.get(&pid) ++ && pinc != inc ++ { ++ deps[inc].push(pinc); ++ } ++ } ++ if r.msg_type == RGFX_CMD_SHARED_EVENT_NAME { ++ if let Ok((m, _)) = RgfxSharedEventName::read_from_prefix(&r.bytes) { ++ active_name_inc.insert(m.name, inc); ++ } ++ } else if r.msg_type == RGFX_CMD_SHARED_EVENT_IMPORT { ++ if let Ok((m, _)) = RgfxSharedEventImport::read_from_prefix(&r.bytes) ++ && let Some(&ninc) = active_name_inc.get(&m.name) ++ && ninc != inc ++ { ++ deps[inc].push(ninc); ++ } ++ } ++ rec_inc.push(Some(inc)); ++ } ++ } ++ } ++ ++ let mut keep = vec![false; destroyed.len()]; ++ let mut stack: Vec = Vec::new(); ++ for (inc, &is_dead) in destroyed.iter().enumerate() { ++ if !is_dead { ++ keep[inc] = true; ++ stack.push(inc); ++ } ++ } ++ while let Some(inc) = stack.pop() { ++ for &pinc in &deps[inc] { ++ if !keep[pinc] { ++ keep[pinc] = true; ++ stack.push(pinc); ++ } ++ } ++ } ++ ++ records ++ .iter() ++ .zip(rec_inc) ++ .filter_map(|(r, inc)| inc.filter(|&i| keep[i]).map(|_| r.clone())) ++ .collect() ++} ++ ++/// Complete serialized snapshot of a [`super::GraphicsDevice`]. ++pub(crate) struct VgpuSnapshot { ++ pub(crate) device_snapshot: Vec, ++ pub(crate) shared_pool: Option, ++ pub(crate) private_blocks: PrivateBlocksSnapshot, ++ pub(crate) id_chunks: Vec, ++ pub(crate) surface_pages: Vec, ++ pub(crate) live_records: Vec, ++ pub(crate) standalone_textures: Vec, ++ pub(crate) presented_surfaces: Vec, ++ pub(crate) live_values: LiveValues, ++} ++ ++struct Enc(Vec); ++ ++impl Enc { ++ fn u8(&mut self, v: u8) { ++ self.0.push(v); ++ } ++ fn u32(&mut self, v: u32) { ++ self.0.extend_from_slice(&v.to_le_bytes()); ++ } ++ fn u64(&mut self, v: u64) { ++ self.0.extend_from_slice(&v.to_le_bytes()); ++ } ++ fn bytes(&mut self, b: &[u8]) { ++ self.u64(b.len() as u64); ++ self.0.extend_from_slice(b); ++ } ++ fn capture(&mut self, c: Option) { ++ match c { ++ None => self.u8(0), ++ Some(c) => { ++ self.u8(1); ++ self.u8(match c.class { ++ MemoryClass::Shared => 0, ++ MemoryClass::Private => 1, ++ }); ++ self.u64(c.alloc_len); ++ self.u64(c.offset); ++ self.u64(c.len); ++ self.u64(c.gpu_address); ++ self.u64(c.opaque_buffer_address); ++ self.u64(c.opaque_memory_address); ++ } ++ } ++ } ++} ++ ++struct Dec<'a> { ++ buf: &'a [u8], ++ pos: usize, ++} ++ ++impl<'a> Dec<'a> { ++ fn remaining(&self) -> usize { ++ self.buf.len().saturating_sub(self.pos) ++ } ++ fn take(&mut self, n: usize) -> Option<&'a [u8]> { ++ let end = self.pos.checked_add(n)?; ++ let s = self.buf.get(self.pos..end)?; ++ self.pos = end; ++ Some(s) ++ } ++ fn checked_count(&mut self, min_item_bytes: usize) -> Option { ++ let count = usize::try_from(self.u32()?).ok()?; ++ let min_bytes = min_item_bytes.max(1); ++ if count > self.remaining() / min_bytes { ++ return None; ++ } ++ Some(count) ++ } ++ fn read_vec( ++ &mut self, ++ min_item_bytes: usize, ++ mut f: impl FnMut(&mut Self) -> Option, ++ ) -> Option> { ++ let count = self.checked_count(min_item_bytes)?; ++ let mut out = Vec::with_capacity(count); ++ for _ in 0..count { ++ out.push(f(self)?); ++ } ++ Some(out) ++ } ++ fn u8(&mut self) -> Option { ++ Some(self.take(1)?[0]) ++ } ++ fn u32(&mut self) -> Option { ++ Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?)) ++ } ++ fn u64(&mut self) -> Option { ++ Some(u64::from_le_bytes(self.take(8)?.try_into().ok()?)) ++ } ++ fn bytes(&mut self) -> Option> { ++ let n = usize::try_from(self.u64()?).ok()?; ++ Some(self.take(n)?.to_vec()) ++ } ++ fn capture(&mut self) -> Option> { ++ match self.u8()? { ++ 0 => Some(None), ++ 1 => { ++ let class = match self.u8()? { ++ 0 => MemoryClass::Shared, ++ 1 => MemoryClass::Private, ++ _ => return None, ++ }; ++ Some(Some(BlockCapture { ++ class, ++ alloc_len: self.u64()?, ++ offset: self.u64()?, ++ len: self.u64()?, ++ gpu_address: self.u64()?, ++ opaque_buffer_address: self.u64()?, ++ opaque_memory_address: self.u64()?, ++ })) ++ } ++ _ => None, ++ } ++ } ++} ++ ++impl VgpuSnapshot { ++ pub(crate) fn encode(&self) -> Vec { ++ let mut e = Enc(Vec::with_capacity(64 * 1024)); ++ e.0.extend_from_slice(SNAPSHOT_MAGIC); ++ e.u32(SNAPSHOT_VERSION); ++ e.bytes(&self.device_snapshot); ++ ++ match &self.shared_pool { ++ None => e.u8(0), ++ Some(pool) => { ++ e.u8(1); ++ e.u64(pool.serial); ++ e.u32(pool.pieces.len() as u32); ++ for p in &pool.pieces { ++ e.u64(p.gpa); ++ e.u64(p.len); ++ e.u64(p.gpu_address); ++ e.capture(p.capture); ++ e.bytes(&p.bytes); ++ } ++ e.u32(pool.carves.len() as u32); ++ for c in &pool.carves { ++ e.u64(c.gpa); ++ e.u32(c.context); ++ e.u64(c.len); ++ e.u64(c.serial); ++ e.u64(c.gpu_address); ++ e.u8(u8::from(c.picked_address)); ++ } ++ } ++ } ++ ++ e.u64(self.private_blocks.serial); ++ e.u32(self.private_blocks.blocks.len() as u32); ++ for b in &self.private_blocks.blocks { ++ e.u64(b.gpu_address); ++ e.u32(b.context); ++ e.u64(b.len); ++ e.u64(b.serial); ++ e.capture(b.capture); ++ e.bytes(&b.bytes); ++ } ++ ++ e.u32(self.id_chunks.len() as u32); ++ for &c in &self.id_chunks { ++ e.u32(c); ++ } ++ ++ e.u32(self.surface_pages.len() as u32); ++ for sp in &self.surface_pages { ++ e.bytes(sp.pages.as_bytes()); ++ e.u32(sp.runs.len() as u32); ++ for r in &sp.runs { ++ e.bytes(r.as_bytes()); ++ } ++ e.u32(sp.flags); ++ match &sp.layout { ++ None => e.u8(0), ++ Some(l) => { ++ e.u8(1); ++ e.bytes(l.as_bytes()); ++ } ++ } ++ } ++ ++ e.u32(self.live_records.len() as u32); ++ for r in &self.live_records { ++ e.u64(r.seq); ++ e.u32(r.context); ++ e.u64(r.obj_id); ++ e.u32(r.msg_type); ++ e.bytes(&r.bytes); ++ e.bytes(&r.inline_bytes); ++ } ++ ++ e.u32(self.standalone_textures.len() as u32); ++ for &id in &self.standalone_textures { ++ e.u64(id); ++ } ++ ++ e.u32(self.presented_surfaces.len() as u32); ++ for &id in &self.presented_surfaces { ++ e.u32(id); ++ } ++ ++ e.u32(self.live_values.events.len() as u32); ++ for &(id, val) in &self.live_values.events { ++ e.u64(id); ++ e.u64(val); ++ } ++ e.u32(self.live_values.shared_events.len() as u32); ++ for &(id, val) in &self.live_values.shared_events { ++ e.u64(id); ++ e.u64(val); ++ } ++ e.u32(self.live_values.buffers.len() as u32); ++ for (id, bytes) in &self.live_values.buffers { ++ e.u64(*id); ++ e.bytes(bytes); ++ } ++ e.u32(self.live_values.textures.len() as u32); ++ for (id, bytes) in &self.live_values.textures { ++ e.u64(*id); ++ e.bytes(bytes); ++ } ++ e.u32(self.live_values.surface_caches.len() as u32); ++ for (block, bytes) in &self.live_values.surface_caches { ++ e.u64(*block); ++ e.bytes(bytes); ++ } ++ e.0 ++ } ++ ++ pub(crate) fn decode(data: &[u8]) -> Option { ++ let mut d = Dec { buf: data, pos: 0 }; ++ if d.take(8)? != SNAPSHOT_MAGIC { ++ return None; ++ } ++ if d.u32()? != SNAPSHOT_VERSION { ++ return None; ++ } ++ let device_snapshot = d.bytes()?; ++ ++ let shared_pool = match d.u8()? { ++ 0 => None, ++ 1 => { ++ let serial = d.u64()?; ++ let pieces = d.read_vec(33, |d| { ++ Some(PoolPieceSnapshot { ++ gpa: d.u64()?, ++ len: d.u64()?, ++ gpu_address: d.u64()?, ++ capture: d.capture()?, ++ bytes: d.bytes()?, ++ }) ++ })?; ++ let carves = d.read_vec(37, |d| { ++ Some(PoolCarveSnapshot { ++ gpa: d.u64()?, ++ context: d.u32()?, ++ len: d.u64()?, ++ serial: d.u64()?, ++ gpu_address: d.u64()?, ++ picked_address: d.u8()? != 0, ++ }) ++ })?; ++ Some(PoolSnapshot { ++ serial, ++ pieces, ++ carves, ++ }) ++ } ++ _ => return None, ++ }; ++ ++ let pb_serial = d.u64()?; ++ let blocks = d.read_vec(37, |d| { ++ Some(PrivateBlockSnapshot { ++ gpu_address: d.u64()?, ++ context: d.u32()?, ++ len: d.u64()?, ++ serial: d.u64()?, ++ capture: d.capture()?, ++ bytes: d.bytes()?, ++ }) ++ })?; ++ let private_blocks = PrivateBlocksSnapshot { ++ serial: pb_serial, ++ blocks, ++ }; ++ ++ let id_chunks = d.read_vec(4, Dec::u32)?; ++ ++ let surface_pages = d.read_vec(17, |d| { ++ let pages_b = d.bytes()?; ++ let (pages, _) = RgfxSurfacePages::read_from_prefix(&pages_b).ok()?; ++ let runs = d.read_vec(8 + std::mem::size_of::(), |d| { ++ let rb = d.bytes()?; ++ let (r, _) = RgfxPageRun::read_from_prefix(&rb).ok()?; ++ Some(r) ++ })?; ++ let flags = d.u32()?; ++ let layout = match d.u8()? { ++ 0 => None, ++ 1 => { ++ let lb = d.bytes()?; ++ let (l, _) = RgfxSurfacePagesLayout::read_from_prefix(&lb).ok()?; ++ Some(l) ++ } ++ _ => return None, ++ }; ++ Some(SurfacePagesRecord { ++ pages, ++ runs, ++ flags, ++ layout, ++ }) ++ })?; ++ ++ let live_records = d.read_vec(40, |d| { ++ Some(LogRecord { ++ seq: d.u64()?, ++ context: d.u32()?, ++ obj_id: d.u64()?, ++ msg_type: d.u32()?, ++ bytes: d.bytes()?, ++ inline_bytes: d.bytes()?, ++ }) ++ })?; ++ ++ let standalone_textures = d.read_vec(8, Dec::u64)?; ++ let presented_surfaces = d.read_vec(4, Dec::u32)?; ++ ++ let live_values = LiveValues { ++ events: d.read_vec(16, |d| Some((d.u64()?, d.u64()?)))?, ++ shared_events: d.read_vec(16, |d| Some((d.u64()?, d.u64()?)))?, ++ buffers: d.read_vec(16, |d| Some((d.u64()?, d.bytes()?)))?, ++ textures: d.read_vec(16, |d| Some((d.u64()?, d.bytes()?)))?, ++ surface_caches: d.read_vec(16, |d| Some((d.u64()?, d.bytes()?)))?, ++ }; ++ if d.remaining() != 0 { ++ return None; ++ } ++ ++ Some(VgpuSnapshot { ++ device_snapshot, ++ shared_pool, ++ private_blocks, ++ id_chunks, ++ surface_pages, ++ live_records, ++ standalone_textures, ++ presented_surfaces, ++ live_values, ++ }) ++ } ++} ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ ++ fn empty_snapshot() -> VgpuSnapshot { ++ VgpuSnapshot { ++ device_snapshot: Vec::new(), ++ shared_pool: Some(PoolSnapshot { ++ serial: 1, ++ pieces: Vec::new(), ++ carves: Vec::new(), ++ }), ++ private_blocks: PrivateBlocksSnapshot { ++ serial: 2, ++ blocks: Vec::new(), ++ }, ++ id_chunks: Vec::new(), ++ surface_pages: Vec::new(), ++ live_records: Vec::new(), ++ standalone_textures: Vec::new(), ++ presented_surfaces: Vec::new(), ++ live_values: LiveValues::default(), ++ } ++ } ++ ++ #[test] ++ fn decode_rejects_oversized_counts_and_trailing_bytes() { ++ let encoded = empty_snapshot().encode(); ++ assert!(VgpuSnapshot::decode(&encoded).is_some()); ++ ++ let mut with_tail = encoded.clone(); ++ with_tail.push(0xAA); ++ assert!(VgpuSnapshot::decode(&with_tail).is_none()); ++ ++ assert_eq!(encoded.len(), 89); ++ for offset in [29usize, 33, 45, 49, 53, 57, 61, 65, 69, 73, 77, 81, 85] { ++ let mut bad = encoded.clone(); ++ bad[offset..offset + 4].copy_from_slice(&u32::MAX.to_le_bytes()); ++ assert!( ++ VgpuSnapshot::decode(&bad).is_none(), ++ "oversized count at offset {offset} must fail cleanly" ++ ); ++ } ++ } ++ ++ #[test] ++ fn live_log_retains_destroyed_parent_library_for_live_pipeline() { ++ let log = LiveLog::new(1); ++ let ctx = 7u32; ++ ++ // Create two libraries: obj 10 (needed by pipeline 20) and obj 11 (unused). ++ let lib_bytes = b"MTLB_DUMMY_PAYLOAD".to_vec(); ++ log.record_library(ctx, 10, lib_bytes.clone(), Some([0x11; 32])); ++ log.record_library(ctx, 11, lib_bytes, Some([0x22; 32])); ++ ++ // Create a compute pipeline (obj 20) referencing library 10. ++ let mut pipe = zerocopy::FromZeros::new_zeroed(); ++ let pipe_ref: &mut RgfxComputePipelineCreate = &mut pipe; ++ pipe_ref.header.r#type = RGFX_CMD_COMPUTE_PIPELINE_CREATE; ++ pipe_ref.header.size = std::mem::size_of::() as u32; ++ pipe_ref.obj_id = 20; ++ pipe_ref.function_library_obj_id = 10; ++ log.record_stage3(ctx, pipe_ref.as_bytes()); ++ ++ // Destroy both libraries (e.g. ARC releasing MTLLibrary after compiling pipeline). ++ for dead in [10u64, 11u64] { ++ let mut d = zerocopy::FromZeros::new_zeroed(); ++ let d_ref: &mut RgfxObjectDestroy = &mut d; ++ d_ref.header.r#type = RGFX_CMD_OBJECT_DESTROY; ++ d_ref.header.size = std::mem::size_of::() as u32; ++ d_ref.obj_id = dead; ++ log.record_stage3(ctx, d_ref.as_bytes()); ++ } ++ ++ let (records, _, _, _) = log.export(); ++ let summary: Vec<(u64, u32)> = records.iter().map(|r| (r.obj_id, r.msg_type)).collect(); ++ // Library 10 and its trailing destroy must be kept so pipeline 20 can replay; ++ // unused library 11 and its destroy must be compacted away. ++ assert_eq!( ++ summary, ++ vec![ ++ (10, LOG_TAG_ASSEMBLED_LIBRARY), ++ (20, RGFX_CMD_COMPUTE_PIPELINE_CREATE), ++ (10, RGFX_CMD_OBJECT_DESTROY), ++ ] ++ ); ++ } ++} +diff --git a/crates/reims-vgpu/src/pool.rs b/crates/reims-vgpu/src/pool.rs +index e915869056a8c7ac9f81f2a5b7d18b90290c542c..58deecf094f39ab8f8d3aaf6b988ed3c43a3937c 100644 +--- a/crates/reims-vgpu/src/pool.rs ++++ b/crates/reims-vgpu/src/pool.rs +@@ -85,6 +85,7 @@ + mod addresses; + mod host_blocks; + mod private_blocks; ++pub(crate) use private_blocks::{PrivateBlockSnapshot, PrivateBlocksSnapshot}; + mod rt_blocks; + mod takes; + +@@ -309,6 +310,47 @@ pub enum BlockError { + + /// Where the pool's blocks come from (metal2vulkan-runtime's `Device::take_block` and + /// `release_block`). ++/// Capture/replay address metadata for a pool or private block. ++#[derive(Clone, Copy, Debug, PartialEq, Eq)] ++pub struct BlockCapture { ++ pub class: MemoryClass, ++ pub alloc_len: u64, ++ pub offset: u64, ++ pub len: u64, ++ pub gpu_address: u64, ++ pub opaque_buffer_address: u64, ++ pub opaque_memory_address: u64, ++} ++ ++/// Snapshot of a single live Shared Pool piece mapped into Guest GPA. ++#[derive(Clone, Debug)] ++pub struct PoolPieceSnapshot { ++ pub gpa: u64, ++ pub len: u64, ++ pub gpu_address: u64, ++ pub capture: Option, ++ pub bytes: Vec, ++} ++ ++/// Snapshot of a context's carved sub-block inside a Shared Pool piece. ++#[derive(Clone, Debug)] ++pub struct PoolCarveSnapshot { ++ pub gpa: u64, ++ pub context: u32, ++ pub len: u64, ++ pub serial: u64, ++ pub gpu_address: u64, ++ pub picked_address: bool, ++} ++ ++/// Complete snapshot of the Shared Pool. ++#[derive(Clone, Debug, Default)] ++pub struct PoolSnapshot { ++ pub serial: u64, ++ pub pieces: Vec, ++ pub carves: Vec, ++} ++ + pub trait BlockSource: Send + Sync { + /// A block of `class` at least `len` long ([`BlockInfo::len`]). Waits only when no block is + /// ready. +@@ -317,6 +359,27 @@ pub trait BlockSource: Send + Sync { + /// any more: it goes back to the ready set, with its id, address and host mapping, or is + /// freed. + fn release_block(&self, block: BlockId) -> Result<(), BlockError>; ++ ++ /// Returns capture/replay metadata for a live block, if supported. ++ fn capture_block(&self, _block: BlockId) -> Option { ++ None ++ } ++ ++ /// Replays a previously captured block at its exact Vulkan device address. ++ fn take_block_replayed(&self, _cap: BlockCapture) -> Result { ++ Err(BlockError::OutOfMemory) ++ } ++ ++ /// Reads back raw VRAM bytes of a Private block (via GPU staging blit). ++ /// Returns `Ok(None)` when the source has no GPU-backed VRAM (unit-test fakes). ++ fn read_private_block(&self, _block: BlockId) -> Result>, BlockError> { ++ Ok(None) ++ } ++ ++ /// Uploads raw VRAM bytes into a Private block (via GPU staging blit). ++ fn write_private_block(&self, _block: BlockId, _data: &[u8]) -> Result<(), BlockError> { ++ Ok(()) ++ } + } + + /// The guest physical range the host reserved for the pool, with no RAM under it. +@@ -1087,6 +1150,146 @@ impl Pool { + dead_code, + reason = "the guest's side of the pool (its ring messages) calls it once it lands" + )] ++ /// Waits until in-flight pool take workers and zeroer are idle. ++ pub(crate) fn quiesce(&self) { ++ let deadline = std::time::Instant::now() + Duration::from_secs(5); ++ loop { ++ let busy = { ++ let st = self.shared.state.lock(); ++ st.workers > 0 || st.zeroer || st.serving > 0 || !st.asks.is_empty() ++ }; ++ if !busy || std::time::Instant::now() >= deadline { ++ break; ++ } ++ std::thread::sleep(Duration::from_millis(2)); ++ } ++ } ++ ++ /// Exports all live Shared Pool pieces (with raw bytes & BDA capture metadata) and carves. ++ pub(crate) fn export_snapshot(&self) -> Result { ++ self.quiesce(); ++ let st = self.shared.state.lock(); ++ let source = st.source.clone(); ++ let mut pieces = Vec::new(); ++ for (&gpa, p) in &st.pieces { ++ if !matches!(p.mapped, Mapped::Live | Mapped::Adding) { ++ continue; ++ } ++ let cap = source.as_ref().and_then(|s| s.capture_block(p.block.id)); ++ let ptr = p.block.contents.ok_or(Error::HostResources)?; ++ let bytes = unsafe { ++ std::slice::from_raw_parts(ptr.as_ptr(), p.block.len as usize).to_vec() ++ }; ++ pieces.push(PoolPieceSnapshot { ++ gpa, ++ len: p.block.len, ++ gpu_address: p.block.gpu_address, ++ capture: cap, ++ bytes, ++ }); ++ } ++ let carves = takes::export_carves(&st.carves); ++ Ok(PoolSnapshot { ++ serial: st.serial, ++ pieces, ++ carves, ++ }) ++ } ++ ++ /// Restores Shared Pool pieces at their exact GPAs and Vulkan BDAs, and asks host to map them. ++ pub(crate) fn import_snapshot(&self, snap: &PoolSnapshot) -> Result<(), Error> { ++ self.quiesce(); ++ let source = { ++ let st = self.shared.state.lock(); ++ st.source.clone() ++ }; ++ let Some(source) = source else { ++ return if snap.pieces.is_empty() { ++ Ok(()) ++ } else { ++ Err(Error::HostResources) ++ }; ++ }; ++ // First release any pre-existing empty pieces if any (fresh device has none). ++ let mut restored_pieces: Vec<(u64, BlockInfo)> = Vec::with_capacity(snap.pieces.len()); ++ for ps in &snap.pieces { ++ let blk = if let Some(cap) = ps.capture { ++ source ++ .take_block_replayed(cap) ++ .map_err(|_| Error::HostResources)? ++ } else { ++ source ++ .take_block(MemoryClass::Shared, ps.len) ++ .map_err(|_| Error::HostResources)? ++ }; ++ let ptr = blk.contents.ok_or(Error::HostResources)?; ++ if ps.bytes.len() as u64 != blk.len { ++ return Err(Error::InvalidArgument); ++ } ++ unsafe { ++ std::ptr::copy_nonoverlapping(ps.bytes.as_ptr(), ptr.as_ptr(), ps.bytes.len()); ++ } ++ restored_pieces.push((ps.gpa, blk)); ++ } ++ { ++ let mut st = self.shared.state.lock(); ++ st.serial = st.serial.max(snap.serial); ++ for (gpa, blk) in &restored_pieces { ++ let piece_carves = snap ++ .carves ++ .iter() ++ .filter(|c| c.gpa >= *gpa && c.gpa < *gpa + blk.len) ++ .count() as u64; ++ st.by_block.insert(blk.id, *gpa); ++ st.pieces.insert( ++ *gpa, ++ Piece { ++ block: *blk, ++ mapped: Mapped::Adding, ++ empty_since: if piece_carves == 0 { ++ Some((self.shared.now)()) ++ } else { ++ None ++ }, ++ holds: 0, ++ kept: Arc::new(()), ++ carves: piece_carves, ++ zeros: takes::Ranges::new(), ++ zero_pending: false, ++ going: None, ++ }, ++ ); ++ } ++ let state = &mut *st; ++ takes::import_carves(&mut state.carves, &mut state.addresses, &snap.carves); ++ } ++ for (gpa, blk) in &restored_pieces { ++ if let Some(ptr) = blk.contents { ++ (self.shared.host.add)(*gpa, ptr.as_ptr(), blk.len); ++ } ++ } ++ self.shared.wake(); ++ Ok(()) ++ } ++ ++ /// Re-copies snapshotted Shared Pool piece bytes after LiveLog replay (so any `new_buffer` ++ /// zero-initialization during replay cannot clobber saved guest/GPU contents). ++ pub(crate) fn restore_bytes(&self, snap: &PoolSnapshot) -> Result<(), Error> { ++ let st = self.shared.state.lock(); ++ for ps in &snap.pieces { ++ let piece = st.pieces.get(&ps.gpa).ok_or(Error::HostResources)?; ++ let ptr = piece.block.contents.ok_or(Error::HostResources)?; ++ if ps.bytes.len() as u64 != piece.block.len { ++ return Err(Error::InvalidArgument); ++ } ++ unsafe { ++ std::ptr::copy_nonoverlapping(ps.bytes.as_ptr(), ptr.as_ptr(), ps.bytes.len()); ++ } ++ } ++ Ok(()) ++ } ++ ++ #[cfg(any(test, feature = "testkit"))] + pub fn live(&self) -> Vec<(u64, u64)> { + let st = self.shared.state.lock(); + (st.pieces.iter()) +diff --git a/crates/reims-vgpu/src/pool/private_blocks.rs b/crates/reims-vgpu/src/pool/private_blocks.rs +index ebe6e77b899a55b102dc0d9fc07b9d57a315c44e..5a42f97cb40d4b3d067b9283d1e2232a7eecc6a5 100644 +--- a/crates/reims-vgpu/src/pool/private_blocks.rs ++++ b/crates/reims-vgpu/src/pool/private_blocks.rs +@@ -139,6 +139,24 @@ pub(crate) struct HeldRef { + } + + /// A context's block. ++/// Serializable snapshot of a single Private GPU-address block and its VRAM contents. ++#[derive(Clone, Debug)] ++pub(crate) struct PrivateBlockSnapshot { ++ pub(crate) gpu_address: u64, ++ pub(crate) context: u32, ++ pub(crate) len: u64, ++ pub(crate) serial: u64, ++ pub(crate) capture: Option, ++ pub(crate) bytes: Vec, ++} ++ ++/// Complete snapshot of all contexts' Private blocks. ++#[derive(Clone, Debug, Default)] ++pub(crate) struct PrivateBlocksSnapshot { ++ pub(crate) serial: u64, ++ pub(crate) blocks: Vec, ++} ++ + #[derive(Debug)] + struct Held { + context: u32, +@@ -437,6 +455,128 @@ impl PrivateBlocks { + + /// The device's reset: every take not yet answered ends unanswered, and every block is freed + /// at once, its objects already dropped. ++ /// Waits until in-flight private take workers are idle, then exports all held Private blocks + VRAM. ++ pub(crate) fn export_snapshot(&self) -> Result { ++ let deadline = std::time::Instant::now() + Duration::from_secs(5); ++ loop { ++ let busy = { ++ let st = self.inner.state.lock(); ++ st.takers.values().any(|t| t.busy || !t.jobs.is_empty()) ++ }; ++ if !busy { ++ break; ++ } ++ if std::time::Instant::now() >= deadline { ++ return Err(super::Error::HostResources); ++ } ++ std::thread::sleep(Duration::from_millis(2)); ++ } ++ let entries: Vec<(u64, u32, u64, u64, Option)> = { ++ let st = self.inner.state.lock(); ++ st.held ++ .iter() ++ .filter(|(_, h)| !h.going) ++ .map(|(&addr, h)| (addr, h.context, h.len, h.serial, h.block)) ++ .collect() ++ }; ++ let serial = self.inner.state.lock().serial; ++ let mut blocks = Vec::with_capacity(entries.len()); ++ for (gpu_address, context, len, bserial, block_id) in entries { ++ let (capture, bytes) = match (&self.inner.source, block_id) { ++ (Some(src), Some(bid)) => { ++ let cap = src.capture_block(bid); ++ let raw = src ++ .read_private_block(bid) ++ .map_err(|_| super::Error::HostResources)? ++ .unwrap_or_default(); ++ (cap, raw) ++ } ++ (Some(_), None) => return Err(super::Error::HostResources), ++ (None, _) => (None, Vec::new()), ++ }; ++ blocks.push(PrivateBlockSnapshot { ++ gpu_address, ++ context, ++ len, ++ serial: bserial, ++ capture, ++ bytes, ++ }); ++ } ++ Ok(PrivateBlocksSnapshot { serial, blocks }) ++ } ++ ++ /// Restores Private blocks at their exact Vulkan BDAs and uploads saved VRAM contents. ++ pub(crate) fn import_snapshot(&self, snap: &PrivateBlocksSnapshot) -> Result<(), super::Error> { ++ let mut restored = Vec::with_capacity(snap.blocks.len()); ++ for b in &snap.blocks { ++ let block_id = if let Some(src) = &self.inner.source { ++ let info = if let Some(cap) = b.capture { ++ src.take_block_replayed(cap) ++ .map_err(|_| super::Error::HostResources)? ++ } else { ++ src.take_block(MemoryClass::Private, b.len) ++ .map_err(|_| super::Error::HostResources)? ++ }; ++ Some(info.id) ++ } else { ++ None ++ }; ++ restored.push((b, block_id)); ++ } ++ let mut st = self.inner.state.lock(); ++ st.serial = st.serial.max(snap.serial); ++ st.held.clear(); ++ for (b, block_id) in restored { ++ st.held.insert( ++ b.gpu_address, ++ Held { ++ context: b.context, ++ len: b.len, ++ serial: b.serial, ++ going: false, ++ block: block_id, ++ }, ++ ); ++ } ++ Ok(()) ++ } ++ ++ /// Uploads snapshotted Private Block VRAM bytes after LiveLog object replay (so `new_buffer` ++ /// zeroing during replay never clobbers restored Private VRAM). ++ pub(crate) fn restore_bytes(&self, snap: &PrivateBlocksSnapshot) -> Result<(), super::Error> { ++ let Some(src) = &self.inner.source else { ++ if snap.blocks.iter().any(|b| !b.bytes.is_empty()) { ++ return Err(super::Error::HostResources); ++ } ++ return Ok(()); ++ }; ++ let ids: Vec<(BlockId, &[u8])> = { ++ let st = self.inner.state.lock(); ++ let mut out = Vec::with_capacity(snap.blocks.len()); ++ for b in &snap.blocks { ++ if b.bytes.is_empty() { ++ continue; ++ } ++ let held = st ++ .held ++ .get(&b.gpu_address) ++ .ok_or(super::Error::HostResources)?; ++ if b.bytes.len() as u64 != held.len { ++ return Err(super::Error::InvalidArgument); ++ } ++ let id = held.block.ok_or(super::Error::HostResources)?; ++ out.push((id, b.bytes.as_slice())); ++ } ++ out ++ }; ++ for (id, bytes) in ids { ++ src.write_private_block(id, bytes) ++ .map_err(|_| super::Error::HostResources)?; ++ } ++ Ok(()) ++ } ++ + pub(crate) fn reset(&self) { + let (released, ended) = { + let mut state = self.inner.state.lock(); +diff --git a/crates/reims-vgpu/src/pool/rt_blocks.rs b/crates/reims-vgpu/src/pool/rt_blocks.rs +index ea0ae46f22cbaaeca83f3b205d5bd34ab02fb10d..91676ea8ef346cc4f35dea1c79c6c9e51a33d943 100644 +--- a/crates/reims-vgpu/src/pool/rt_blocks.rs ++++ b/crates/reims-vgpu/src/pool/rt_blocks.rs +@@ -42,7 +42,7 @@ use parking_lot::Mutex; + use reims_vgpu_vulkan::core::trace; + use reims_vgpu_vulkan::rt_platform::{RtDevice, RtObj}; + +-use super::{BlockError, BlockId, BlockInfo, BlockSource, MemoryClass}; ++use super::{BlockCapture, BlockError, BlockId, BlockInfo, BlockSource, MemoryClass}; + + /// The pool's blocks from an rt device, with the handle of each one handed out. + pub(crate) struct RtBlocks { +@@ -144,6 +144,153 @@ impl BlockSource for RtBlocks { + // be; rt drops the handle all the same. + (self.device.rt().release_block(handle)).map_err(|_| BlockError::NotHeld) + } ++ ++ fn capture_block(&self, block: BlockId) -> Option { ++ let held = self.held.lock(); ++ let h = held.get(&block)?; ++ let cap = h.capture_info()?; ++ Some(BlockCapture { ++ class: match cap.class { ++ rt::MemoryClass::Private => MemoryClass::Private, ++ rt::MemoryClass::Shared => MemoryClass::Shared, ++ }, ++ alloc_len: cap.alloc_len, ++ offset: cap.offset, ++ len: cap.len, ++ gpu_address: cap.gpu_address, ++ opaque_buffer_address: cap.opaque_buffer_address, ++ opaque_memory_address: cap.opaque_memory_address, ++ }) ++ } ++ ++ fn take_block_replayed(&self, cap: BlockCapture) -> Result { ++ let rt_cap = rt::BlockCaptureInfo { ++ class: match cap.class { ++ MemoryClass::Private => rt::MemoryClass::Private, ++ MemoryClass::Shared => rt::MemoryClass::Shared, ++ }, ++ alloc_len: cap.alloc_len, ++ offset: cap.offset, ++ len: cap.len, ++ gpu_address: cap.gpu_address, ++ opaque_buffer_address: cap.opaque_buffer_address, ++ opaque_memory_address: cap.opaque_memory_address, ++ }; ++ let block = self ++ .device ++ .rt() ++ .take_block_replayed(rt_cap) ++ .map_err(|_| BlockError::OutOfMemory)?; ++ let Some(gpu_address) = block.gpu_address else { ++ let _ = self.device.rt().release_block(block); ++ return Err(BlockError::OutOfMemory); ++ }; ++ let info = BlockInfo { ++ id: BlockId(block.id.get()), ++ class: cap.class, ++ len: block.len, ++ gpu_address, ++ contents: block.contents, ++ }; ++ self.known.know(block.clone()); ++ self.held.lock().insert(info.id, block); ++ Ok(info) ++ } ++ ++ fn read_private_block(&self, block: BlockId) -> Result>, BlockError> { ++ let handle = self ++ .held ++ .lock() ++ .get(&block) ++ .cloned() ++ .ok_or(BlockError::NotHeld)?; ++ let len = handle.len; ++ if len == 0 { ++ return Ok(Some(Vec::new())); ++ } ++ let rt = self.device.rt(); ++ let stage = rt ++ .take_block(rt::MemoryClass::Shared, len) ++ .map_err(|_| BlockError::OutOfMemory)?; ++ let res = (|| -> Result, BlockError> { ++ let src_buf = rt ++ .new_buffer(handle.id, 0, len, None) ++ .map_err(|_| BlockError::OutOfMemory)?; ++ let dst_buf = rt ++ .new_buffer(stage.id, 0, len, None) ++ .map_err(|_| BlockError::OutOfMemory)?; ++ let q = rt ++ .new_command_queue(4) ++ .map_err(|_| BlockError::OutOfMemory)?; ++ let cb = q.command_buffer().map_err(|_| BlockError::OutOfMemory)?; ++ let mut blit = cb ++ .blit_command_encoder() ++ .map_err(|_| BlockError::OutOfMemory)?; ++ blit.copy_from_buffer_to_buffer(&src_buf, 0, &dst_buf, 0, len) ++ .map_err(|_| BlockError::OutOfMemory)?; ++ blit.end_encoding(); ++ cb.commit().map_err(|_| BlockError::OutOfMemory)?; ++ cb.wait_until_completed() ++ .map_err(|_| BlockError::OutOfMemory)?; ++ let ptr = stage.contents.ok_or(BlockError::OutOfMemory)?; ++ let bytes = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), len as usize).to_vec() }; ++ drop(dst_buf); ++ drop(src_buf); ++ Ok(bytes) ++ })(); ++ let _ = rt.release_block(stage); ++ res.map(Some) ++ } ++ ++ fn write_private_block(&self, block: BlockId, data: &[u8]) -> Result<(), BlockError> { ++ let handle = self ++ .held ++ .lock() ++ .get(&block) ++ .cloned() ++ .ok_or(BlockError::NotHeld)?; ++ let len = handle.len; ++ if data.len() as u64 != len { ++ return Err(BlockError::OutOfMemory); ++ } ++ if len == 0 { ++ return Ok(()); ++ } ++ let rt = self.device.rt(); ++ let stage = rt ++ .take_block(rt::MemoryClass::Shared, len) ++ .map_err(|_| BlockError::OutOfMemory)?; ++ let res = (|| -> Result<(), BlockError> { ++ let ptr = stage.contents.ok_or(BlockError::OutOfMemory)?; ++ unsafe { ++ std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), len as usize); ++ } ++ let src_buf = rt ++ .new_buffer(stage.id, 0, len, None) ++ .map_err(|_| BlockError::OutOfMemory)?; ++ let dst_buf = rt ++ .new_buffer(handle.id, 0, len, None) ++ .map_err(|_| BlockError::OutOfMemory)?; ++ let q = rt ++ .new_command_queue(4) ++ .map_err(|_| BlockError::OutOfMemory)?; ++ let cb = q.command_buffer().map_err(|_| BlockError::OutOfMemory)?; ++ let mut blit = cb ++ .blit_command_encoder() ++ .map_err(|_| BlockError::OutOfMemory)?; ++ blit.copy_from_buffer_to_buffer(&src_buf, 0, &dst_buf, 0, len) ++ .map_err(|_| BlockError::OutOfMemory)?; ++ blit.end_encoding(); ++ cb.commit().map_err(|_| BlockError::OutOfMemory)?; ++ cb.wait_until_completed() ++ .map_err(|_| BlockError::OutOfMemory)?; ++ drop(dst_buf); ++ drop(src_buf); ++ Ok(()) ++ })(); ++ let _ = rt.release_block(stage); ++ res ++ } + } + + impl Drop for RtBlocks { +diff --git a/crates/reims-vgpu/src/pool/takes.rs b/crates/reims-vgpu/src/pool/takes.rs +index d724a3413c17940834fae97b41cb025089b6e164..1c9ea6db4f9d47e151454c128caf41ea5254c383 100644 +--- a/crates/reims-vgpu/src/pool/takes.rs ++++ b/crates/reims-vgpu/src/pool/takes.rs +@@ -191,6 +191,47 @@ enum GpuAddress { + Picked(u64), + } + ++pub(super) fn export_carves(carves: &BTreeMap) -> Vec { ++ carves ++ .iter() ++ .filter(|(_, c)| matches!(c.state, Carving::Held)) ++ .map(|(&gpa, c)| super::PoolCarveSnapshot { ++ gpa, ++ context: c.context, ++ len: c.len, ++ serial: c.serial, ++ gpu_address: c.gpu_address.get(), ++ picked_address: matches!(c.gpu_address, GpuAddress::Picked(_)), ++ }) ++ .collect() ++} ++ ++pub(super) fn import_carves( ++ carves: &mut BTreeMap, ++ _addresses: &mut super::addresses::HostAddresses, ++ snap: &[super::PoolCarveSnapshot], ++) { ++ carves.clear(); ++ for c in snap { ++ let gpu_address = if c.picked_address { ++ GpuAddress::Picked(c.gpu_address) ++ } else { ++ GpuAddress::OfBlock(c.gpu_address) ++ }; ++ carves.insert( ++ c.gpa, ++ Carve { ++ context: c.context, ++ len: c.len, ++ serial: c.serial, ++ state: Carving::Held, ++ gpu_address, ++ zero: Vec::new(), ++ }, ++ ); ++ } ++} ++ + impl GpuAddress { + fn get(self) -> u64 { + match self { diff --git a/patches/series.txt b/patches/series.txt index b499927..0b43011 100644 --- a/patches/series.txt +++ b/patches/series.txt @@ -1,18 +1,19 @@ # Patch queue, in the order the patches are applied (see patches/README.md). # One patch per line: . -# Targets are "reims-vgpu", "vendor/qemu", and "reims-util". +# Targets are "reims-vgpu", "vendor/qemu", "reims-util", and "metal2vulkan". # CI (build-runtime.yml via scripts/apply-patch-series.ps1) and # scripts/pack-runtime.ps1 both read this file; add or retire patches here. -reims-vgpu reims-vgpu-cargo-lock.patch -reims-vgpu reims-vgpu-win32-unicode-input.patch -reims-vgpu reims-vgpu-display-fixed-mode.patch -reims-vgpu reims-ctl-win32-random-bytes.patch -reims-vgpu reims-ctl-virtio-discard-iothread.patch -reims-vgpu reims-ctl-qcow2-l2-cache.patch -reims-util reims-util-parallel-offline-download.patch -vendor/qemu qemu-whpx-win10-compat.patch -vendor/qemu qemu-whpx-win10-startup-ipis.patch -vendor/qemu qemu-whpx-nested-virt-nonfatal.patch -vendor/qemu qemu-win32-coroutine-fiber-commit.patch -vendor/qemu qemu-win32-mapped-ram-io.patch -vendor/qemu qemu-intel-whpx-suspend.patch +reims-vgpu reims-vgpu-win32-unicode-input.patch +reims-vgpu reims-vgpu-display-fixed-mode.patch +reims-vgpu reims-ctl-win32-random-bytes.patch +reims-vgpu reims-ctl-virtio-discard-iothread.patch +reims-vgpu reims-ctl-qcow2-l2-cache.patch +reims-vgpu reims-vgpu-snapshot-replay.patch +reims-util reims-util-parallel-offline-download.patch +metal2vulkan metal2vulkan-snapshot-replay.patch +vendor/qemu qemu-whpx-win10-compat.patch +vendor/qemu qemu-whpx-win10-startup-ipis.patch +vendor/qemu qemu-whpx-nested-virt-nonfatal.patch +vendor/qemu qemu-win32-coroutine-fiber-commit.patch +vendor/qemu qemu-win32-mapped-ram-io.patch +vendor/qemu qemu-intel-whpx-suspend.patch diff --git a/scripts/apply-patch-series.ps1 b/scripts/apply-patch-series.ps1 index e04aeaa..7f6ef99 100644 --- a/scripts/apply-patch-series.ps1 +++ b/scripts/apply-patch-series.ps1 @@ -16,23 +16,25 @@ was really applied, AGENTS.md rule 5) and report merged or conflicting patches. .EXAMPLE - pwsh -File scripts/apply-patch-series.ps1 -ReimsRepo $env:RUNNER_TEMP\reims-vgpu -UtilRepo $env:RUNNER_TEMP\reims-util -ResultFile patches.json + pwsh -File scripts/apply-patch-series.ps1 -ReimsRepo $env:RUNNER_TEMP\reims-vgpu -UtilRepo $env:RUNNER_TEMP\reims-util -Metal2VulkanRepo $env:RUNNER_TEMP\metal2vulkan -ResultFile patches.json #> [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$ReimsRepo, [string]$ResultFile = '', - [string]$UtilRepo = '' + [string]$UtilRepo = '', + [string]$Metal2VulkanRepo = '' ) $ErrorActionPreference = 'Stop' $repoRoot = Split-Path -Parent $PSScriptRoot $patchesDir = Join-Path $repoRoot 'patches' $repositories = @{ - 'reims-vgpu' = $ReimsRepo - 'vendor/qemu' = Join-Path $ReimsRepo 'vendor\qemu' - 'reims-util' = $UtilRepo + 'reims-vgpu' = $ReimsRepo + 'vendor/qemu' = Join-Path $ReimsRepo 'vendor\qemu' + 'reims-util' = $UtilRepo + 'metal2vulkan' = $Metal2VulkanRepo } function Read-PatchSeries { @@ -59,6 +61,9 @@ $series = @(Read-PatchSeries) if (-not $UtilRepo -and $series.Target -contains 'reims-util') { throw 'Pass -UtilRepo with a checkout at the reims-util revision pinned by reims-ctl.' } +if (-not $Metal2VulkanRepo -and $series.Target -contains 'metal2vulkan') { + throw 'Pass -Metal2VulkanRepo with a checkout at the metal2vulkan revision pinned by reims-vgpu.' +} foreach ($p in $series) { $file = Join-Path $patchesDir $p.Name diff --git a/scripts/pack-runtime.ps1 b/scripts/pack-runtime.ps1 index 40928b9..1294bb7 100644 --- a/scripts/pack-runtime.ps1 +++ b/scripts/pack-runtime.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Pack a portable reims-vgpu runtime for Windows x64, its matching source package, and SHA256SUMS.txt, ready to publish as a GitHub Release. @@ -29,13 +29,14 @@ .EXAMPLE pwsh -File scripts/pack-runtime.ps1 -Channel alpha - pwsh -File scripts/pack-runtime.ps1 -Patches reims-vgpu-cargo-lock.patch,qemu-whpx-win10-compat.patch + pwsh -File scripts/pack-runtime.ps1 -Patches reims-vgpu-snapshot-replay.patch,metal2vulkan-snapshot-replay.patch,qemu-whpx-win10-compat.patch #> [CmdletBinding(PositionalBinding = $false)] param( - [string]$ReimsRepo = 'D:\DevTools\reims-vgpu', - [string]$UtilRepo = '', - [string]$CargoHome = 'D:\DevTools\cargo', + [string]$ReimsRepo = 'D:\DevTools\reims-vgpu', + [string]$UtilRepo = '', + [string]$Metal2VulkanRepo = '', + [string]$CargoHome = 'D:\DevTools\cargo', [string]$QemuDir = 'D:\Data\macos-vm-lab\reims\data\reims-ctl\qemu\current', [string]$Msys2 = 'D:\DevTools\msys64', [string]$OutDir = 'D:\Data\reims-go\releases', @@ -139,19 +140,35 @@ if (-not $utilTree) { throw "reims-util source at $utilCommit not found" } $actualUtil = git -C $utilTree rev-parse HEAD if ($LASTEXITCODE -ne 0 -or $actualUtil -ne $utilCommit) { throw "reims-util checkout must be at $utilCommit" } -# metal2vulkan's git rev as built (Cargo.lock in the build tree). -$lock = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.lock') -if ($lock -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.lock' } -$m2vCommit = $Matches[1] +# metal2vulkan's pinned commit (workspace Cargo.toml, falling back to Cargo.lock). +$cargoToml = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.toml') +if ($cargoToml -match 'metal2vulkan\s*=\s*\{[^}]*rev\s*=\s*"([0-9a-f]{40})"') { + $m2vCommit = $Matches[1] +} else { + $lock = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.lock') + if ($lock -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.toml or Cargo.lock' } + $m2vCommit = $Matches[1] +} +$m2vTree = if ($Metal2VulkanRepo) { + (Resolve-Path -LiteralPath $Metal2VulkanRepo).Path +} else { + Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'metal2vulkan-*' -ErrorAction SilentlyContinue | + ForEach-Object { Join-Path $_.FullName $m2vCommit.Substring(0, 7) } | + Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +} +if (-not $m2vTree) { throw "metal2vulkan source at $m2vCommit not found (pass -Metal2VulkanRepo or check $checkouts)" } +$actualM2v = (git -C $m2vTree rev-parse HEAD).Trim() +if ($LASTEXITCODE -ne 0 -or $actualM2v -ne $m2vCommit) { throw "metal2vulkan checkout must be at $m2vCommit (got $actualM2v)" } $qemuVersionLine = (& $qemuExe --version | Select-Object -First 1).Trim() $utilVersionLine = (& $utilExe --version | Select-Object -First 1).Trim() # ── 2. Patches must equal the build tree's diffs ───────────── $repositories = @{ - 'reims-vgpu' = $ReimsRepo - 'vendor/qemu' = $qemuRepo - 'reims-util' = $utilTree + 'reims-vgpu' = $ReimsRepo + 'vendor/qemu' = $qemuRepo + 'reims-util' = $utilTree + 'metal2vulkan' = $m2vTree } $series = @(foreach ($line in Get-Content -LiteralPath (Join-Path $patchesDir 'series.txt')) { $t = $line.Trim() @@ -257,6 +274,20 @@ foreach ($targetName in $byTarget.Keys) { Write-Host "Expected patch stack diff --stat:`n$expStat" throw "Patch stack ($(($group | ForEach-Object { $_.Name }) -join ', ')) does not match the build tree's diff in $repo. Stop: don't edit patches automatically (AGENTS.md rule 4)." } + # Also verify newly created (untracked) files added by patches byte-for-byte. + $addedFiles = @(& git -C $verifyDir ls-files --others --exclude-standard | Where-Object { $_ }) + foreach ($rel in $addedFiles) { + $expPath = Join-Path $verifyDir ($rel -replace '/', '\') + $treePath = Join-Path $repo ($rel -replace '/', '\') + if (-not (Test-Path -LiteralPath $treePath -PathType Leaf)) { + throw "Patch stack expected new file $rel in $repo, but it is missing." + } + $expText = [IO.File]::ReadAllText($expPath).Replace("`r`n", "`n") + $treeText = [IO.File]::ReadAllText($treePath).Replace("`r`n", "`n") + if ($treeText -cne $expText) { + throw "New file $rel in $repo does not match the declared patch stack. Stop: don't edit patches automatically (AGENTS.md rule 4)." + } + } } finally { if (Test-Path -LiteralPath $verifyDir) { Remove-Item -Recurse -Force -LiteralPath $verifyDir } } @@ -273,8 +304,10 @@ $otherCtl = Get-Undeclared $ReimsRepo 'reims-vgpu' @('--ignore-submodules=all' $otherQemu = Get-Undeclared $qemuRepo 'vendor/qemu' @('--untracked-files=no') $utilStatusArgs = if ($UtilRepo) { '--untracked-files=all' } else { '--untracked-files=no' } $otherUtil = Get-Undeclared $utilTree 'reims-util' @($utilStatusArgs) -if ($otherCtl.Count -or $otherQemu.Count -or $otherUtil.Count) { - throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu + $otherUtil -join "`n")" +$m2vStatusArgs = if ($Metal2VulkanRepo) { '--untracked-files=all' } else { '--untracked-files=no' } +$otherM2v = Get-Undeclared $m2vTree 'metal2vulkan' @($m2vStatusArgs) +if ($otherCtl.Count -or $otherQemu.Count -or $otherUtil.Count -or $otherM2v.Count) { + throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu + $otherUtil + $otherM2v -join "`n")" } $bundleName = "reims-runtime-win-x64-$id" @@ -306,7 +339,7 @@ if (Test-Path -LiteralPath (Join-Path $patchesDir 'LICENSE')) { Copy-Item -LiteralPath (Join-Path $patchesDir 'LICENSE') -Destination "$bundleDir\patches\LICENSE" } # The order the patches above were applied in (only those really applied). -Write-Utf8 "$bundleDir\patches\series.txt" ((($patchSpecs | ForEach-Object { '{0,-11} {1}' -f $_.Target, $_.Name }) -join "`n") + "`n") +Write-Utf8 "$bundleDir\patches\series.txt" ((($patchSpecs | ForEach-Object { '{0,-12} {1}' -f $_.Target, $_.Name }) -join "`n") + "`n") $licenses = @{ 'reims-vgpu-LICENSE.txt' = (Join-Path $ReimsRepo 'LICENSE') 'qemu-COPYING.txt' = (Join-Path $qemuRepo 'COPYING') @@ -388,8 +421,6 @@ Get-ChildItem -LiteralPath (Join-Path $qemuRepo 'subprojects') -Directory | Where-Object { $_.Name -ne 'packagecache' -and -not (Test-Path -LiteralPath (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\$($_.Name)")) } | ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\") -Recurse -Force } -$m2vTree = Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'metal2vulkan-*' | ForEach-Object { Join-Path $_.FullName $m2vCommit.Substring(0, 7) } | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 -if (-not $m2vTree) { throw "metal2vulkan source at $m2vCommit not found under $checkouts" } Export-GitTree $utilTree $utilCommit (Join-Path $srcDir "reims-util-$($utilCommit.Substring(0, 7))") Export-GitTree $m2vTree $m2vCommit (Join-Path $srcDir "metal2vulkan-$($m2vCommit.Substring(0, 7))") foreach ($extra in @( @@ -411,6 +442,23 @@ New-Item -ItemType Directory -Force -Path "$srcDir\patches" | Out-Null Copy-Item -Path "$bundleDir\patches\*" -Destination "$srcDir\patches\" Copy-Item -LiteralPath "$bundleDir\MSYS2-PACKAGES.txt" -Destination "$srcDir\MSYS2-PACKAGES.txt" Copy-Item -LiteralPath "$bundleDir\NOTICE.md" -Destination "$srcDir\NOTICE.md" +$m2vBuildSteps = if ($byTarget.Contains('metal2vulkan')) { + $m2vDir = "metal2vulkan-$($m2vCommit.Substring(0, 7))" + $m2vApply = ($byTarget['metal2vulkan'] | ForEach-Object { " git -C $m2vDir apply `"`$(pwd)/patches/$($_.Name)`"" }) -join "`n" +@" + +Before running ``scripts/install-ctl.sh``, apply the ``metal2vulkan`` patches +and point Cargo at the patched checkout via ```$CARGO_HOME/config.toml``: + +$m2vApply + cat >> "`${CARGO_HOME:-`$HOME/.cargo}/config.toml" < Date: Tue, 1 Dec 2026 08:05:05 +0800 Subject: [PATCH 04/10] feat: integrate Intel VM suspend and instant resume across backend, CLI, and UI --- frontend/src/App.tsx | 58 +++- frontend/src/components/Sidebar.tsx | 28 +- frontend/src/components/TitleMenus.tsx | 15 +- frontend/src/components/VMPage.tsx | 111 ++++++-- frontend/src/i18n/domains/vm.gen.ts | 38 +++ frontend/src/i18n/keys.gen.ts | 19 ++ frontend/src/styles/app.css | 5 + frontend/src/types.ts | 3 +- frontend/src/ui/controls.tsx | 5 +- frontend/wailsjs/go/app/App.d.ts | 6 + frontend/wailsjs/go/app/App.js | 12 + frontend/wailsjs/go/models.ts | 66 +++++ internal/app/app.go | 48 +++- internal/app/clone_flow.go | 3 + internal/app/disk_flow.go | 6 + internal/app/snapshot_flow.go | 3 + internal/app/suspend_flow.go | 356 +++++++++++++++++++++++++ internal/app/suspend_flow_test.go | 58 ++++ internal/cli/cli.go | 36 ++- internal/cli/start.go | 4 + internal/cli/suspend.go | 179 +++++++++++++ internal/driver/reims/reims.go | 9 +- internal/driver/reims/suspend.go | 240 +++++++++++++++++ internal/driver/reims/suspend_test.go | 114 ++++++++ internal/i18n/catalog_gen.go | 52 ++++ internal/qmp/client.go | 24 +- internal/qmp/migrate.go | 275 +++++++++++++++++++ internal/qmp/migrate_test.go | 229 ++++++++++++++++ internal/runtime/kinds.go | 10 + internal/runtime/kinds_test.go | 35 +++ internal/tray/tray.go | 126 +++++++-- internal/tray/tray_test.go | 33 ++- internal/vmstart/vmstart.go | 5 + locales/en-US/native.json | 72 +++++ locales/en-US/vm.json | 19 ++ locales/zh-CN/native.json | 72 +++++ locales/zh-CN/vm.json | 19 ++ 37 files changed, 2311 insertions(+), 82 deletions(-) create mode 100644 internal/app/suspend_flow.go create mode 100644 internal/app/suspend_flow_test.go create mode 100644 internal/cli/suspend.go create mode 100644 internal/driver/reims/suspend.go create mode 100644 internal/driver/reims/suspend_test.go create mode 100644 internal/qmp/migrate.go create mode 100644 internal/qmp/migrate_test.go diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 2f43c0b..ceda025 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -41,6 +41,9 @@ const errText = (e: unknown) => parseAppError(e).summary const failKey: Record = { start: 'failStart', + suspend: 'failSuspend', + resume: 'failResume', + discardSuspend: 'failDiscardSuspend', focus: 'failFocus', fullscreen: 'failFullscreen', screenshot: 'failScreenshot', @@ -85,6 +88,7 @@ export const App: React.FC = () => { const [affinityTarget, setAffinityTarget] = useState(null) const [affinityVersion, setAffinityVersion] = useState(0) const [deleteTarget, setDeleteTarget] = useState(null) + const [discardSuspendTarget, setDiscardSuspendTarget] = useState(null) const [cloneSource, setCloneSource] = useState(null) const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState(null) const [sendTextTarget, setSendTextTarget] = useState(null) @@ -331,6 +335,15 @@ export const App: React.FC = () => { const effectiveState = selectedVM ? (state?.transitions[selectedVM.name] ?? selectedVM.state) : '' const pending = selectedVM ? (state?.pending_changes[selectedVM.name] ?? []) : [] const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime + const activeManifest = state?.active_runtime?.manifest + const canSuspend = Boolean( + activeManifest?.capabilities?.some((c) => c.toLowerCase() === 'vm-suspend') + || ( + activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('win32-mapped-ram-io')) + && activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('intel-whpx-suspend')) + && activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('reims-vgpu-snapshot-replay')) + ), + ) onTaskRef.current = (task: Task) => { if (task.kind === 'app-update' && task.status === 'failed' && !notifiedTasks.current.has(task.id)) { @@ -667,6 +680,9 @@ export const App: React.FC = () => { } switch (action) { case 'start': return runVMAction(name, action, () => api.StartVM(name)) + case 'suspend': return runVMAction(name, action, () => api.SuspendVM(name), tr('toastSuspended', { name })) + case 'resume': return runVMAction(name, action, () => api.ResumeVM(name), tr('toastResumed', { name })) + case 'discardSuspend': return setDiscardSuspendTarget(name) case 'focus': return api.FocusVMWindow(name).catch((e) => fail(tr('failFocus'), e)) case 'fullscreen': return runVMAction(name, action, async () => { @@ -705,23 +721,25 @@ export const App: React.FC = () => { } const onSidebarContextAction = (name: string, action: VMAction | 'settings') => { + const vm = vms.find((v) => v.name === name) + const st = state?.transitions[name] ?? vm?.state ?? 'stopped' if (action === 'settings') { + if (st === 'suspended' || st === 'suspending' || st === 'resuming') return setSelected(name) api.GetVMDetail(name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e)) return } - const vm = vms.find((v) => v.name === name) - const st = state?.transitions[name] ?? vm?.state ?? 'stopped' onVMActionFor(name, action, st === 'running') } - // The state's own main action (Start, or Show Window while running), shared by + // The state's own main action (Start, Resume while suspended, or Show Window while running), shared by // Ctrl+Enter and a double-click in the sidebar. const primaryAction = (name: string) => { const vm = vms.find((v) => v.name === name) if (!vm || activeVMBusy(name)) return const st = state?.transitions[name] ?? vm.state if (st === 'stopped') onVMActionFor(name, 'start', false) + else if (st === 'suspended') onVMActionFor(name, 'resume', false) else if (st === 'running') onVMActionFor(name, 'focus', true) } @@ -731,6 +749,12 @@ export const App: React.FC = () => { if (name) runVMAction(name, 'delete', () => api.DeleteVM(name, keepFiles), tr('toastDeleted', { name })) } + const confirmDiscardSuspend = () => { + const name = discardSuspendTarget + setDiscardSuspendTarget(null) + if (name) runVMAction(name, 'discardSuspend', () => api.DiscardSuspend(name), tr('toastDiscardSuspend', { name })) + } + const confirmOnlineRecovery = () => { const name = onlineRecoveryTarget setOnlineRecoveryTarget(null) @@ -859,11 +883,11 @@ export const App: React.FC = () => { const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {}) shortcutRef.current = (e: KeyboardEvent) => { if (!e.ctrlKey || e.altKey || e.metaKey) return - if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return + if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return const k = e.key.toLowerCase() if (k === 'n') { e.preventDefault(); openWizard() } - else if (k === ',' && detail) { e.preventDefault(); setShowSettings(true) } + else if (k === ',' && detail && effectiveState !== 'suspended' && effectiveState !== 'suspending' && effectiveState !== 'resuming') { e.preventDefault(); setShowSettings(true) } else if (k === 'l') { e.preventDefault(); toggleLogs() } else if (k === 'b' && !showSetup) { e.preventDefault(); toggleSidebar() } else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(selectedVM.name) } @@ -950,10 +974,11 @@ export const App: React.FC = () => { state: effectiveState, busy: Object.prototype.hasOwnProperty.call(busy, selectedVM.name), graphics: detail?.name === selectedVM.name ? detail.graphics : undefined, + canSuspend, } : null} onNewVM={openWizard} onVMAction={onVMAction} - onVMSettings={() => { if (detail) setShowSettings(true) }} + onVMSettings={() => { if (detail && effectiveState !== 'suspended') setShowSettings(true) }} onVMDelete={() => { if (selectedVM) setDeleteTarget(selectedVM.name) }} onNavigate={setSelected} onOpenURL={(url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) }} @@ -1019,6 +1044,7 @@ export const App: React.FC = () => { busyActions={busy} selected={selected} hostReady={hostReady} + canSuspend={canSuspend} onSelect={setSelected} displayNames={displayNames} macosMajors={macosMajors} @@ -1077,6 +1103,7 @@ export const App: React.FC = () => { onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [selectedVM.name]: n }))} macosMajor={macosMajors[selectedVM.name] ?? null} state={effectiveState} + canSuspend={canSuspend} guideActive={state.active_guides?.includes(selectedVM.name) ?? false} installGuideEnabled={!!state.install_guide_enabled} detail={detail} @@ -1281,6 +1308,25 @@ export const App: React.FC = () => { setDeleteTarget(null)} onConfirm={confirmDelete} /> )} + {discardSuspendTarget && ( + setDiscardSuspendTarget(null)} + > +

+

{tr('discardSuspendDesc')}

+
+
+ + + + + +
+ + )} + {cloneSource && ( selected: string hostReady: boolean + /** Whether the active runtime supports VM suspend/resume. */ + canSuspend?: boolean onSelect: (id: string) => void /** VM name → display name (its note); empty or missing shows the name. */ displayNames?: Record @@ -44,7 +46,7 @@ interface Props { } export const Sidebar: React.FC = ({ - locale, vms, transitions, busyActions = {}, selected, hostReady, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot, + locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot, }) => { const tr = (k: I18nKey) => t(locale, k) const listRef = useRef(null) @@ -118,7 +120,8 @@ export const Sidebar: React.FC = ({ const st = transitions[vm.name] ?? vm.state const running = st === 'running' const stopped = st === 'stopped' - const transitioning = st === 'starting' || st === 'stopping' + const suspended = st === 'suspended' + const transitioning = st === 'starting' || st === 'stopping' || st === 'suspending' || st === 'resuming' const busyAction = Object.prototype.hasOwnProperty.call(busyActions, vm.name) ? busyActions[vm.name] : undefined const vmBusy = !!busyAction const label = displayNames[vm.name] || vm.name @@ -159,6 +162,16 @@ export const Sidebar: React.FC = ({ {tr('start')} )} + {suspended && ( + <> + onVMContextAction(vm.name, 'resume')}> + {tr('resume')} + + onVMContextAction(vm.name, 'discardSuspend')}> + {tr('discardSuspend')} + + + )} {running && ( <> onVMContextAction(vm.name, 'focus')}> @@ -170,6 +183,11 @@ export const Sidebar: React.FC = ({ onVMContextAction(vm.name, 'screenshot')}> {tr('copyScreenshot')} + {canSuspend && ( + onVMContextAction(vm.name, 'suspend')}> + {tr('suspend')} + + )} onVMContextAction(vm.name, 'stop')}> {tr('stop')} @@ -184,7 +202,7 @@ export const Sidebar: React.FC = ({ )} - onVMContextAction(vm.name, 'settings')}> + onVMContextAction(vm.name, 'settings')}> {tr('settingsEllipsis')} onVMContextAction(vm.name, 'openSharedFolder')}> @@ -199,7 +217,7 @@ export const Sidebar: React.FC = ({ {tr('openFolder')} - onVMContextAction(vm.name, 'delete')}> + onVMContextAction(vm.name, 'delete')}> {tr('delete')} diff --git a/frontend/src/components/TitleMenus.tsx b/frontend/src/components/TitleMenus.tsx index 79560e4..4253d95 100644 --- a/frontend/src/components/TitleMenus.tsx +++ b/frontend/src/components/TitleMenus.tsx @@ -27,7 +27,7 @@ interface Props { canDark?: boolean onThemeMode: (mode: ThemeMode) => void /** The selected VM and its current state, or null on the system pages. */ - vm: { name: string; state: string; busy: boolean; graphics?: string } | null + vm: { name: string; state: string; busy: boolean; graphics?: string; canSuspend?: boolean } | null onNewVM: () => void onVMAction: (action: VMAction) => void onVMSettings: () => void @@ -62,7 +62,8 @@ export const TitleMenus: React.FC = ({ const running = vm?.state === 'running' const stopped = vm?.state === 'stopped' - const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' + const suspended = vm?.state === 'suspended' + const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming' const vmBusy = !vm || vm.busy const canFullscreen = running && vm?.graphics !== 'vmware-svga' const stats = useVMStats(canFullscreen && vm ? vm.name : null, running) @@ -218,17 +219,21 @@ export const TitleMenus: React.FC = ({ {running ? item(tr('showWindow'), () => onVMAction('focus'), { shortcut: 'Ctrl+Enter', disabled: vmBusy }) - : item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })} + : suspended + ? item(tr('resume'), () => onVMAction('resume'), { shortcut: 'Ctrl+Enter', disabled: vmBusy }) + : item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })} {item(fullscreenLabel, () => onVMAction('fullscreen'), { disabled: vmBusy || !canFullscreen })} + {item(tr('suspend'), () => onVMAction('suspend'), { disabled: vmBusy || !running || !vm?.canSuspend })} {item(tr('stop'), () => onVMAction('stop'), { disabled: vmBusy || !running })} {item(tr('restart'), () => onVMAction('restart'), { disabled: vmBusy || !running })} {item(tr('copyScreenshot'), () => onVMAction('screenshot'), { disabled: vmBusy || !running })} - {item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm })} + {item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm || suspended || transitioning })} {item(tr('openFolder'), () => onVMAction('openFolder'), { disabled: !vm })} + {suspended && item(tr('discardSuspend'), () => onVMAction('discardSuspend'), { danger: true, disabled: vmBusy })} {item(tr('forceStop'), () => onVMAction('forceStop'), { danger: true, disabled: !vm || !(running || transitioning) })} - {item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || transitioning })} + {item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || suspended || transitioning })} ))} {menu('view', tr('menuView'), ( diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index e8b60ea..f42998f 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -27,6 +27,7 @@ import { Minimize2, Monitor, Network, + Pause, Pencil, Play, Plus, @@ -55,6 +56,9 @@ import { VersionArt } from './VersionArt' export type VMAction = | 'start' + | 'suspend' + | 'resume' + | 'discardSuspend' | 'stop' | 'forceStop' | 'restart' @@ -92,6 +96,8 @@ interface Props { /** macOS major version (26, 15, …) for the artwork shown before a first frame; null if unknown. */ macosMajor: number | null state: string + /** Whether the active runtime supports VM suspend/resume. */ + canSuspend?: boolean /** Whether the native VM-window installation guide is currently active for this boot. */ guideActive: boolean /** Whether the builtin.install-guide plugin is enabled. */ @@ -132,13 +138,14 @@ interface Spec { } export const VMPage: React.FC = ({ - locale, name, displayName, onDisplayNameSaved, macosMajor, state, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, + locale, name, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const busy = busyAction !== undefined const running = state === 'running' + const suspended = state === 'suspended' const installing = !!detail && (detail.has_installer || detail.recovery_mode) - const transitioning = state === 'starting' || state === 'stopping' + const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming' // Polled here rather than in App so each tick re-renders only this page. const stats = useVMStats(name, running) @@ -318,7 +325,7 @@ export const VMPage: React.FC = ({ } // One primary action per state (docs/design-guidelines.md §4): Start while - // stopped, Show Window while running. Ctrl+Enter triggers it (App.tsx). + // stopped, Resume while suspended, Show Window while running. Ctrl+Enter triggers it (App.tsx). let primary: React.ReactNode = null let secondary: React.ReactNode = null if (state === 'stopped') { @@ -329,10 +336,27 @@ export const VMPage: React.FC = ({ ) + } else if (suspended) { + primary = ( + + + + ) + secondary = ( + + ) } else if (state === 'starting') { primary = } else if (state === 'stopping') { primary = + } else if (state === 'suspending') { + primary = + } else if (state === 'resuming') { + primary = } else if (running) { const showLabel = tr(guideActive ? 'showInstallGuide' : 'showWindow') primary = ( @@ -343,7 +367,14 @@ export const VMPage: React.FC = ({ ) secondary = ( - + <> + {canSuspend && ( + + )} + + ) } else if (state === 'broken') { primary = @@ -413,6 +444,11 @@ export const VMPage: React.FC = ({ : <> {tr('enterFullscreen')}} )} + {canSuspend && ( + onAction('suspend')}> + {tr('suspend')} + + )} onAction('restart')}> {tr('restart')} @@ -431,15 +467,15 @@ export const VMPage: React.FC = ({ {detail && ( <> {installing ? ( - onAction('finishInstall')}> + onAction('finishInstall')}> {tr('finishInstall')} ) : ( <> - onAction('enterRecovery')}> + onAction('enterRecovery')}> {tr('enterRecovery')} - onAction('cloneVM')}> + onAction('cloneVM')}> {tr('cloneVM')} @@ -478,12 +514,17 @@ export const VMPage: React.FC = ({ ))} + {suspended && ( + onAction('discardSuspend')}> + {tr('discardSuspend')} + + )} {(running || transitioning) && ( onAction('forceStop')}> {tr('forceStop')} )} - + {tr('delete')} @@ -563,11 +604,23 @@ export const VMPage: React.FC = ({ onCopy(rows.join('\n')) } - const pillClass = running ? ' is-running' : state === 'broken' ? ' is-broken' : transitioning ? ' is-busy' : '' + const pillClass = running ? ' is-running' : suspended ? ' is-suspended' : state === 'broken' ? ' is-broken' : transitioning ? ' is-busy' : '' const dropStyle = detail && !installing ? ({ '--wails-drop-target': 'drop' } as React.CSSProperties) : undefined + const formatSuspendTime = (iso?: string) => { + if (!iso) return '' + const ms = Date.parse(iso) + if (!Number.isFinite(ms)) return '' + try { + const loc = locale === 'en-XA' ? 'en-US' : locale + return new Intl.DateTimeFormat(loc, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(ms)) + } catch { + return '' + } + } + return (
{dropping && ( @@ -588,10 +641,10 @@ export const VMPage: React.FC = ({ thumb={thumb} art={} running={running} - startLabel={tr('start')} + startLabel={suspended ? tr('resume') : tr('start')} showLabel={tr('showWindow')} shotLabel={tr('copyScreenshot')} - onStart={state === 'stopped' && !busy ? () => onAction('start') : undefined} + onStart={!busy && (state === 'stopped' || suspended) ? () => onAction(suspended ? 'resume' : 'start') : undefined} onShow={running && !busy ? () => onAction('focus') : undefined} onScreenshot={running && !busy ? () => onAction('screenshot') : undefined} /> @@ -631,8 +684,10 @@ export const VMPage: React.FC = ({
{primary} {secondary} - - + + + + {menu}
@@ -667,6 +722,28 @@ export const VMPage: React.FC = ({
)} + {suspended && (() => { + const suspTime = formatSuspendTime(detail?.suspend_info?.created_at) + const suspSize = detail?.suspend_info?.vmstate_size + ? formatBytes(detail.suspend_info.vmstate_size, locale) + : (detail?.memory ? formatMemory(detail.memory, locale) : '—') + return ( +
+ + +
+ ) + })()} + {pending.length > 0 && (
@@ -1041,12 +1118,12 @@ export const VMPage: React.FC = ({ {tr('snapshotsTitle')} · {tr('snapshotHint')} - +
diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index ecfcaed..312faa3 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -24,6 +24,10 @@ export const vmZh: Record = { "diagBackingChainWarn": "当前系统盘 CoW 派生链深度为 {depth} 层(≥ 2),未分配簇读穿透会拖慢小文件 I/O,建议合并为独立镜像或基于基础镜像重新派生", "diagExternalDriveWarn": "数据目录在外置或网络盘上({dir}),读写会明显变慢", "diagHighMemWarn": "宿主内存已用 {pct}%,虚拟机可能会卡顿", + "discardSuspend": "放弃挂起状态", + "discardSuspendConfirm": "放弃并关机", + "discardSuspendDesc": "将删除已保存的内存与设备状态并回到关机状态,macOS 中尚未保存的工作会丢失,且无法撤销。", + "discardSuspendTitle": "放弃「{name}」的挂起状态?", "displayNameEdit": "点按以修改显示名称", "displayNameEditEllipsis": "修改显示名称…", "displayNameLabel": "显示名称", @@ -41,6 +45,7 @@ export const vmZh: Record = { "failAttachInstaller": "挂载镜像失败", "failCloneVM": "派生 CoW 副本失败", "failDelete": "删除失败", + "failDiscardSuspend": "放弃挂起状态失败", "failEject": "弹出安装盘失败", "failEnterRecovery": "进入恢复模式失败", "failExportDiagnostics": "导出排障日志失败", @@ -50,10 +55,12 @@ export const vmZh: Record = { "failGuestTools": "Guest Tools 操作失败", "failOpenFolder": "无法打开文件夹", "failRestart": "重启失败", + "failResume": "恢复失败", "failScreenshot": "截屏失败", "failSnapshot": "恢复点操作失败", "failStart": "启动失败", "failStop": "关机失败", + "failSuspend": "挂起失败", "failType": "键入失败", "failUpgradeNVMe": "升级到 NVMe 失败", "fieldAudio": "音频", @@ -111,6 +118,7 @@ export const vmZh: Record = { "pendingTitle": "下次启动生效", "pickRecoveryTitle": "选择离线镜像(.img / .dmg)", "restartToApply": "重启以应用", + "resume": "恢复", "sendText": "发送文本到虚拟机…", "sendTextConfirm": "发送 (Ctrl+Enter)", "sendTextDesc": "支持中文、Emoji、宿主机输入法与语音输入,按 Ctrl+Enter 发送到 macOS 当前输入框。", @@ -155,14 +163,23 @@ export const vmZh: Record = { "state_broken": "出错", "state_creating": "正在创建", "state_driver_unavailable": "驱动不可用", + "state_resuming": "恢复中", "state_running": "运行中", "state_starting": "启动中", "state_stopped": "已停止", "state_stopping": "停止中", + "state_suspended": "已挂起", + "state_suspending": "挂起中", + "suspend": "挂起", + "suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", + "suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", + "suspendedNoticeTitle": "已保存运行状态", + "suspendedSettingsHint": "请先恢复或放弃挂起状态后再修改配置", "techInfo": "技术信息", "toastCloned": "已派生 CoW 副本「{name}」", "toastDeleted": "已删除 {name}", "toastDiagExported": "已导出脱敏排障日志包 (.zip)", + "toastDiscardSuspend": "已放弃 {name} 的挂起状态", "toastEjected": "已弹出安装盘", "toastEnterRecovery": "已进入恢复模式,启动后可在引导菜单选 Recovery", "toastEnterRecoveryNextStart": "已准备进入恢复模式,重启后显示引导菜单", @@ -182,11 +199,13 @@ export const vmZh: Record = { "toastOnlineRecoveryStarted": "正在拉取在线恢复镜像(约 1 GB),完成后自动挂载", "toastPreventSleepOff": "已关闭 macOS 防休眠守护", "toastPreventSleepOn": "已开启 macOS 防休眠守护", + "toastResumed": "{name} 已恢复", "toastScreenshotCopied": "已复制虚拟机画面", "toastSnapshotCreated": "已创建恢复点 {name}", "toastSnapshotDeleted": "已删除恢复点 {name}", "toastSnapshotRestored": "已回滚到 {name}", "toastStopped": "{name} 已关机", + "toastSuspended": "{name} 已挂起", "toastTyped": "{n, plural, other {已键入 # 个字符}}", "toggleFullscreen": "切换全屏", "typeClipboard": "粘贴剪贴板到虚拟机", @@ -219,6 +238,10 @@ export const vmEn: Record = { "diagBackingChainWarn": "System disk CoW backing chain is {depth} layers deep (\u003e= 2); read-through slows small-file I/O — consider flattening or re-deriving from the base image", "diagExternalDriveWarn": "The data folder is on an external or network drive ({dir}); disk access will be slow", "diagHighMemWarn": "Host memory is {pct}% used; the VM may stutter", + "discardSuspend": "Discard saved state", + "discardSuspendConfirm": "Discard \u0026 Power Off", + "discardSuspendDesc": "Removes the saved memory and device state and returns the VM to powered off. Any unsaved work inside macOS will be lost and can’t be undone.", + "discardSuspendTitle": "Discard saved state for “{name}”?", "displayNameEdit": "Click to change the display name", "displayNameEditEllipsis": "Change Display Name…", "displayNameLabel": "Display name", @@ -236,6 +259,7 @@ export const vmEn: Record = { "failAttachInstaller": "Couldn’t attach the image", "failCloneVM": "Couldn’t create CoW clone", "failDelete": "Couldn’t delete", + "failDiscardSuspend": "Couldn’t discard saved state", "failEject": "Couldn’t eject the installer", "failEnterRecovery": "Couldn’t enter recovery mode", "failExportDiagnostics": "Couldn’t export diagnostics", @@ -245,10 +269,12 @@ export const vmEn: Record = { "failGuestTools": "Guest Tools operation failed", "failOpenFolder": "Couldn’t open the folder", "failRestart": "Couldn’t restart", + "failResume": "Couldn’t resume", "failScreenshot": "Screenshot failed", "failSnapshot": "Restore point failed", "failStart": "Couldn’t start", "failStop": "Couldn’t shut down", + "failSuspend": "Couldn’t suspend", "failType": "Couldn’t type into the VM", "failUpgradeNVMe": "Couldn’t upgrade to NVMe", "fieldAudio": "Audio", @@ -306,6 +332,7 @@ export const vmEn: Record = { "pendingTitle": "Applies on next start", "pickRecoveryTitle": "Choose an offline image (.img / .dmg)", "restartToApply": "Restart to apply", + "resume": "Resume", "sendText": "Send text to VM…", "sendTextConfirm": "Send (Ctrl+Enter)", "sendTextDesc": "Supports Chinese, emoji, host IME, and dictation. Press Ctrl+Enter to inject into the focused macOS field.", @@ -350,14 +377,23 @@ export const vmEn: Record = { "state_broken": "Error", "state_creating": "Creating", "state_driver_unavailable": "Driver unavailable", + "state_resuming": "Resuming", "state_running": "Running", "state_starting": "Starting", "state_stopped": "Stopped", "state_stopping": "Stopping", + "state_suspended": "Suspended", + "state_suspending": "Suspending", + "suspend": "Suspend", + "suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.", + "suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.", + "suspendedNoticeTitle": "Saved state ready", + "suspendedSettingsHint": "Resume or discard saved state before changing settings", "techInfo": "Technical details", "toastCloned": "CoW clone “{name}” created", "toastDeleted": "{name} deleted", "toastDiagExported": "Redacted diagnostics archive exported (.zip)", + "toastDiscardSuspend": "Discarded saved state for {name}", "toastEjected": "Installer ejected", "toastEnterRecovery": "Recovery mode ready — pick Recovery in OpenCore on next start", "toastEnterRecoveryNextStart": "Recovery mode ready — restart to open the boot menu", @@ -377,11 +413,13 @@ export const vmEn: Record = { "toastOnlineRecoveryStarted": "Downloading online recovery image (~1 GB); will attach when ready", "toastPreventSleepOff": "Prevent-sleep guard disabled", "toastPreventSleepOn": "Prevent-sleep guard enabled", + "toastResumed": "{name} resumed", "toastScreenshotCopied": "VM screenshot copied", "toastSnapshotCreated": "Created restore point {name}", "toastSnapshotDeleted": "Deleted restore point {name}", "toastSnapshotRestored": "Restored to {name}", "toastStopped": "{name} shut down", + "toastSuspended": "{name} suspended", "toastTyped": "{n, plural, one {Typed # character} other {Typed # characters}}", "toggleFullscreen": "Toggle full screen", "typeClipboard": "Send clipboard to VM", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 5b2752c..ffd4062 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -137,6 +137,10 @@ export type I18nKey = | "diagBackingChainWarn" | "diagExternalDriveWarn" | "diagHighMemWarn" + | "discardSuspend" + | "discardSuspendConfirm" + | "discardSuspendDesc" + | "discardSuspendTitle" | "diskCompactAction" | "diskCompactDesc" | "diskCompactDone" @@ -202,6 +206,7 @@ export type I18nKey = | "failCloneVM" | "failCreate" | "failDelete" + | "failDiscardSuspend" | "failDownload" | "failEject" | "failEnterRecovery" @@ -213,12 +218,14 @@ export type I18nKey = | "failGuestTools" | "failOpenFolder" | "failRestart" + | "failResume" | "failRuntime" | "failSSH" | "failScreenshot" | "failSnapshot" | "failStart" | "failStop" + | "failSuspend" | "failType" | "failUpgradeNVMe" | "fieldAudio" @@ -617,6 +624,7 @@ export type I18nKey = | "resolution" | "restart" | "restartToApply" + | "resume" | "runtimeAlpha" | "runtimeAlphaHint" | "runtimeChannel_alpha" @@ -740,10 +748,13 @@ export type I18nKey = | "state_broken" | "state_creating" | "state_driver_unavailable" + | "state_resuming" | "state_running" | "state_starting" | "state_stopped" | "state_stopping" + | "state_suspended" + | "state_suspending" | "statsCPU" | "statsDisk" | "statsDiskSub" @@ -774,6 +785,11 @@ export type I18nKey = | "summarySSH" | "summarySSHPort" | "summarySource" + | "suspend" + | "suspendedNoticeDesc" + | "suspendedNoticeDescWithTime" + | "suspendedNoticeTitle" + | "suspendedSettingsHint" | "taskAppUpdate" | "taskCreate" | "taskDownload" @@ -800,6 +816,7 @@ export type I18nKey = | "toastCreated" | "toastDeleted" | "toastDiagExported" + | "toastDiscardSuspend" | "toastDownloadPaused" | "toastEjected" | "toastEnterRecovery" @@ -822,6 +839,7 @@ export type I18nKey = | "toastPreventSleepOff" | "toastPreventSleepOn" | "toastQueueCanceled" + | "toastResumed" | "toastRuntimeReady" | "toastSSHConfigWritten" | "toastSSHUserSaved" @@ -832,6 +850,7 @@ export type I18nKey = | "toastSnapshotDeleted" | "toastSnapshotRestored" | "toastStopped" + | "toastSuspended" | "toastTyped" | "toggleFullscreen" | "typeClipboard" diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 9be43de..d8c5c50 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -292,6 +292,10 @@ h1, h2, h3, p { margin: 0; } .status { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; display: inline-block; } .status-running { background: var(--status-running); } .status-stopped { border: 1.5px solid var(--status-idle); } +.status-suspended { + width: 7px; height: 8px; border-radius: 0; + background: linear-gradient(90deg, var(--status-busy) 0 2.5px, transparent 2.5px 4.5px, var(--status-busy) 4.5px 7px); +} .status-busy { background: conic-gradient(var(--status-busy) 0 50%, transparent 50% 100%); border: 1.5px solid var(--status-busy); animation: pulse 1.4s ease-in-out infinite; } .status-warn { background: var(--status-busy); } .status-broken { background: var(--status-error); border-radius: 1.5px; transform: rotate(45deg); width: 7px; height: 7px; } @@ -366,6 +370,7 @@ h1, h2, h3, p { margin: 0; } .vm-hero-pill.is-running { background: var(--ok-soft); border-color: transparent; color: var(--ok-text); } +.vm-hero-pill.is-suspended, .vm-hero-pill.is-busy { background: var(--warn-soft); border-color: transparent; color: var(--warn-text); } diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 49822da..92b48b5 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -48,7 +48,7 @@ export type RemoteRuntime = Model & { } export type VMListItem = Model & { - state: 'running' | 'stopped' | 'broken' + state: 'running' | 'stopped' | 'suspended' | 'broken' } export type PendingChange = app.PendingChange @@ -63,6 +63,7 @@ export type AppState = Omit, 'config' | 'host' | 'optimizati } export type AppUpdateInfo = version.UpdateInfo +export type SuspendInfo = reims.SuspendInfo export type VMDetail = reims.VMDetail export type VMStats = app.VMStats export type DriveShareSettings = Model diff --git a/frontend/src/ui/controls.tsx b/frontend/src/ui/controls.tsx index c014fe2..f7db8c9 100644 --- a/frontend/src/ui/controls.tsx +++ b/frontend/src/ui/controls.tsx @@ -87,11 +87,12 @@ export const IconButton = React.forwardRef( ) IconButton.displayName = 'IconButton' -export type StatusKind = 'running' | 'stopped' | 'busy' | 'broken' | 'warn' +export type StatusKind = 'running' | 'stopped' | 'suspended' | 'busy' | 'broken' | 'warn' export function statusKind(state: string): StatusKind { if (state === 'running') return 'running' - if (state === 'starting' || state === 'stopping' || state === 'creating') return 'busy' + if (state === 'suspended') return 'suspended' + if (state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming' || state === 'creating') return 'busy' if (state === 'driver_unavailable') return 'warn' if (state === 'broken') return 'broken' return 'stopped' diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index e4d401a..ded8dce 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -47,6 +47,8 @@ export function DeleteSnapshot(arg1:string,arg2:string):Promise; export function DeleteVM(arg1:string,arg2:boolean):Promise; +export function DiscardSuspend(arg1:string):Promise; + export function DeliverFileToGuest(arg1:string):Promise; export function DeliverPathsToGuest(arg1:string,arg2:Array):Promise>; @@ -183,6 +185,8 @@ export function ResizeVMDisk(arg1:string,arg2:string):Promise; +export function ResumeVM(arg1:string):Promise; + export function RestoreSnapshot(arg1:string,arg2:string):Promise; export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise; @@ -225,6 +229,8 @@ export function SuggestDataRoots():Promise>; export function SuggestLanguagePack():Promise; +export function SuspendVM(arg1:string):Promise; + export function ToggleBorderless(arg1:string,arg2:boolean):Promise; export function ToggleVMFullscreen(arg1:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index 2de951a..da78976 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -78,6 +78,10 @@ export function DeleteVM(arg1, arg2) { return window['go']['app']['App']['DeleteVM'](arg1, arg2); } +export function DiscardSuspend(arg1) { + return window['go']['app']['App']['DiscardSuspend'](arg1); +} + export function DeliverFileToGuest(arg1) { return window['go']['app']['App']['DeliverFileToGuest'](arg1); } @@ -350,6 +354,10 @@ export function RestartVM(arg1) { return window['go']['app']['App']['RestartVM'](arg1); } +export function ResumeVM(arg1) { + return window['go']['app']['App']['ResumeVM'](arg1); +} + export function RestoreSnapshot(arg1, arg2) { return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2); } @@ -434,6 +442,10 @@ export function SuggestLanguagePack() { return window['go']['app']['App']['SuggestLanguagePack'](); } +export function SuspendVM(arg1) { + return window['go']['app']['App']['SuspendVM'](arg1); +} + export function ToggleBorderless(arg1, arg2) { return window['go']['app']['App']['ToggleBorderless'](arg1, arg2); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 9883e88..bd48390 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -2296,6 +2296,52 @@ export namespace reims { this.guest_lang = source["guest_lang"]; } } + export class SuspendInfo { + schema_version: number; + vm_name: string; + cpus: number; + memory: string; + graphics: string; + displays: number; + resolution: string; + disk_controller: string; + cpu_model?: string; + audio: boolean; + audio_backend?: string; + network: boolean; + ssh_port: number; + extra_args?: string; + runtime_commit: string; + vendor_qemu_commit?: string; + created_at: string; + vmstate_size: number; + + static createFrom(source: any = {}) { + return new SuspendInfo(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.schema_version = source["schema_version"]; + this.vm_name = source["vm_name"]; + this.cpus = source["cpus"]; + this.memory = source["memory"]; + this.graphics = source["graphics"]; + this.displays = source["displays"]; + this.resolution = source["resolution"]; + this.disk_controller = source["disk_controller"]; + this.cpu_model = source["cpu_model"]; + this.audio = source["audio"]; + this.audio_backend = source["audio_backend"]; + this.network = source["network"]; + this.ssh_port = source["ssh_port"]; + this.extra_args = source["extra_args"]; + this.runtime_commit = source["runtime_commit"]; + this.vendor_qemu_commit = source["vendor_qemu_commit"]; + this.created_at = source["created_at"]; + this.vmstate_size = source["vmstate_size"]; + } + } export class VMDetail { name: string; state: string; @@ -2337,6 +2383,7 @@ export namespace reims { guest_tools_disabled?: boolean; shared_dir?: string; guest_lang?: string; + suspend_info?: SuspendInfo; static createFrom(source: any = {}) { return new VMDetail(source); @@ -2384,7 +2431,26 @@ export namespace reims { this.guest_tools_disabled = source["guest_tools_disabled"]; this.shared_dir = source["shared_dir"]; this.guest_lang = source["guest_lang"]; + this.suspend_info = this.convertValues(source["suspend_info"], SuspendInfo); } + + convertValues(a: any, classs: any, asMap: boolean = false): any { + if (!a) { + return a; + } + if (a.slice && a.map) { + return (a as any[]).map(elem => this.convertValues(elem, classs)); + } else if ("object" === typeof a) { + if (asMap) { + for (const key of Object.keys(a)) { + a[key] = new classs(a[key]); + } + return a; + } + return new classs(a); + } + return a; + } } export class VMListItem { name: string; diff --git a/internal/app/app.go b/internal/app/app.go index 061e539..310bfdd 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -265,6 +265,7 @@ func (a *App) pollVMs(ctx context.Context) { if err != nil { continue } + enrichVMListStates(vms) watchExits(ctx, vms, exitWatched, a.wakePoll) type pinCandidate struct { name string @@ -291,7 +292,10 @@ func (a *App) pollVMs(ctx context.Context) { } } if tr, ok := a.transitions[vm.Name]; ok { - if (tr == "starting" && vm.State == "running") || (tr == "stopping" && vm.State == "stopped") { + if (tr == "starting" && vm.State == "running") || + (tr == "stopping" && vm.State == "stopped") || + (tr == "suspending" && (vm.State == "suspended" || vm.State == "stopped")) || + (tr == "resuming" && vm.State == "running") { delete(a.transitions, vm.Name) if vm.State == "stopped" { delete(a.pendingChanges, vm.Name) @@ -454,7 +458,12 @@ func (a *App) listVMsInternal(ctx context.Context) ([]reims.VMListItem, error) { if err != nil { return nil, err } - return c.List(ctx) + vms, err := c.List(ctx) + if err != nil { + return nil, err + } + enrichVMListStates(vms) + return vms, nil } // qemuImage is the executable reims-ctl reports as a running VM's PID. @@ -676,6 +685,7 @@ func (a *App) GetVMDetail(name string) (reims.VMDetail, error) { d.RecoveryMode = isRecoveryModeActive(d) a.populateGuestToolsDetail(&d) a.populateGuestLangDetail(&d) + a.populateSuspendDetail(&d) return d, nil } @@ -767,6 +777,7 @@ func (a *App) startTray() { }, GetSnapshot: func() tray.Snapshot { a.mu.Lock() + cfgCopy := *a.cfg loc := a.cfg.Locale cached := append([]reims.VMListItem(nil), a.lastVMs...) transitions := make(map[string]string, len(a.transitions)) @@ -774,6 +785,10 @@ func (a *App) startTray() { transitions[k] = v } a.mu.Unlock() + canSuspend := false + if active, err := rt.ResolveActive(&cfgCopy); err == nil && active != nil { + canSuspend = active.Manifest.HasCapability("vm-suspend") + } if len(cached) == 0 { if vms, err := a.listVMsInternal(context.Background()); err == nil { cached = vms @@ -797,9 +812,10 @@ func (a *App) startTray() { } effLoc := i18n.EffectiveLocale(loc) return tray.Snapshot{ - Locale: effLoc, - LocaleZh: effLoc == i18n.ZhCN, - VMs: items, + Locale: effLoc, + LocaleZh: effLoc == i18n.ZhCN, + CanSuspend: canSuspend, + VMs: items, } }, }) @@ -827,6 +843,12 @@ func (a *App) trayVMAction(name string, act tray.Action) { switch act { case tray.ActStart: err, failTitle = a.StartVM(name), i18n.M(loc, "tray.notify.start_fail", vars) + case tray.ActSuspend: + err, failTitle = a.SuspendVM(name), i18n.M(loc, "tray.notify.suspend_fail", vars) + case tray.ActResume: + err, failTitle = a.ResumeVM(name), i18n.M(loc, "tray.notify.resume_fail", vars) + case tray.ActDiscardSuspend: + err, failTitle = a.DiscardSuspend(name), i18n.M(loc, "tray.notify.discard_suspend_fail", vars) case tray.ActStop: err, failTitle = a.StopVM(name, false), i18n.M(loc, "tray.notify.stop_fail", vars) case tray.ActForceStop: @@ -878,7 +900,13 @@ func (a *App) SetDataRoot(dir string) error { curAppUpdateChannel := a.cfg.AppUpdateChannel curMinToTray := a.cfg.MinimizeToTray for _, v := range a.lastVMs { - if v.State == "running" || v.State == "starting" || v.State == "stopping" { + if v.State == "running" || v.State == "starting" || v.State == "stopping" || v.State == "suspending" || v.State == "resuming" { + a.mu.Unlock() + return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil) + } + } + for _, tr := range a.transitions { + if tr != "" { a.mu.Unlock() return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil) } @@ -1235,7 +1263,7 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) { a.mu.Lock() tr := a.transitions[name] a.mu.Unlock() - if tr == "stopping" { + if tr == "stopping" || tr == "suspending" { return } @@ -1313,6 +1341,7 @@ func stripLegacyManagedExtraArgs(extraArgs string) string { s := reims.StripGuestToolsArgs(extraArgs) s = reims.StripOfflineHelperArgs(s) s = qmp.StripLegacyWin10RebootArgs(s) + s = reims.StripIncomingDeferArgs(s) return strings.TrimSpace(s) } @@ -1322,6 +1351,10 @@ func (a *App) StartVM(name string) error { return err } c := prep.Client + curDetail, _ := c.Show(context.Background(), name) + if curDetail.State == "stopped" && reims.HasSuspendState(curDetail.Directory) { + return a.ResumeVM(name) + } a.mu.Lock() root := a.cfg.DataRoot tmpDir := a.cfg.TempDir() @@ -1331,7 +1364,6 @@ func (a *App) StartVM(name string) error { a.emitLog(name, "Start refused: "+err.Error()) return err } - curDetail, _ := c.Show(context.Background(), name) if err := prep.CheckMemory(curDetail.Memory, rep); err != nil { a.emitLog(name, "Start refused: "+err.Error()) return err diff --git a/internal/app/clone_flow.go b/internal/app/clone_flow.go index 42ca1d1..1ab10e6 100644 --- a/internal/app/clone_flow.go +++ b/internal/app/clone_flow.go @@ -46,6 +46,9 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error { if a.isVMRunning(ctx, c, sourceName, src) { return i18n.NewCodedError(loc, "E_VM_CLONE_RUNNING", "err.clone.source_running", i18n.Vars{"name": sourceName}, nil) } + if a.isVMSuspended(src) { + return i18n.NewCodedError(loc, "E_VM_CLONE_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": sourceName}, nil) + } if src.HasInstaller { return i18n.NewCodedError(loc, "E_VM_CLONE_RECOVERY", "err.clone.in_recovery", i18n.Vars{"name": sourceName}, nil) } diff --git a/internal/app/disk_flow.go b/internal/app/disk_flow.go index f1bf3cf..fc3e7ed 100644 --- a/internal/app/disk_flow.go +++ b/internal/app/disk_flow.go @@ -31,6 +31,9 @@ func (a *App) ResizeVMDisk(name, newSize string) (reims.DiskResizeResult, error) if a.isVMRunning(ctx, c, name, d) { return reims.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name) } + if a.isVMSuspended(d) { + return reims.DiskResizeResult{}, fmt.Errorf("resume or discard suspend state for %s before resizing its disk", name) + } diskPath := resolveVMDiskPath(d) if diskPath == "" { return reims.DiskResizeResult{}, fmt.Errorf("VM %s has no disk path", name) @@ -77,6 +80,9 @@ func (a *App) CompactVMDisk(name string) (reims.DiskCompactResult, error) { if a.isVMRunning(ctx, c, name, d) { return reims.DiskCompactResult{}, fmt.Errorf("stop %s before reclaiming disk space", name) } + if a.isVMSuspended(d) { + return reims.DiskCompactResult{}, fmt.Errorf("resume or discard suspend state for %s before reclaiming disk space", name) + } diskPath := resolveVMDiskPath(d) if diskPath == "" { return reims.DiskCompactResult{}, fmt.Errorf("VM %s has no disk path", name) diff --git a/internal/app/snapshot_flow.go b/internal/app/snapshot_flow.go index 306aa7b..426fc75 100644 --- a/internal/app/snapshot_flow.go +++ b/internal/app/snapshot_flow.go @@ -85,6 +85,9 @@ func (a *App) runSnapshotOp(name, flag, snapName, verb string) error { if a.isVMRunning(ctx, c, name, d) { return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_RUNNING", "err.snapshot.vm_running", i18n.Vars{"name": name}, nil) } + if a.isVMSuspended(d) { + return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil) + } diskPath := resolveVMDiskPath(d) if diskPath == "" { return i18n.NewCodedError(loc, "E_SNAPSHOT_NO_DISK", "err.clone.no_disk", i18n.Vars{"name": name}, nil) diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go new file mode 100644 index 0000000..dc9ee8c --- /dev/null +++ b/internal/app/suspend_flow.go @@ -0,0 +1,356 @@ +package app + +import ( + "context" + "fmt" + "io" + "os" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/plugin" + "github.com/Nwflower/reims-go/internal/plugin/builtin" + "github.com/Nwflower/reims-go/internal/qmp" + "github.com/Nwflower/reims-go/internal/vmstart" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" +) + +// enrichVMListStates overlays state="suspended" onto stopped VMs that have a +// complete suspend snapshot (suspend.vmstate + suspend.json) in their folder. +func enrichVMListStates(vms []reims.VMListItem) { + for i := range vms { + if vms[i].State == "stopped" && reims.HasSuspendState(vms[i].Dir) { + vms[i].State = "suspended" + } + } +} + +func (a *App) populateSuspendDetail(d *reims.VMDetail) { + if d == nil || d.Directory == "" { + return + } + if d.State == "stopped" && reims.HasSuspendState(d.Directory) { + d.State = "suspended" + if info, err := reims.ReadSuspendInfo(d.Directory); err == nil { + d.SuspendInfo = info + } + } +} + +func (a *App) isVMSuspended(d reims.VMDetail) bool { + return d.State == "suspended" || (d.State == "stopped" && reims.HasSuspendState(d.Directory)) +} + +// SuspendVM pauses a running Intel VM, saves its RAM, CPU, device, and vGPU +// state to suspend.vmstate, and cleanly exits QEMU so the host can close +// Reims-Go or reboot Windows and later resume instantaneously. +func (a *App) SuspendVM(name string) error { + loc := a.locale() + prep, err := a.prep(name) + if err != nil { + return err + } + if !prep.Runtime.Manifest.HasCapability("vm-suspend") { + return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + } + + a.mu.Lock() + if tr := a.transitions[name]; tr != "" { + a.mu.Unlock() + return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) + } + a.mu.Unlock() + + ctx := a.baseCtx() + c := prep.Client + d, err := c.Show(ctx, name) + if err != nil { + return err + } + if !a.isVMRunning(ctx, c, name, d) { + return i18n.NewCodedError(loc, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": name}, nil) + } + if d.Directory == "" { + return fmt.Errorf("VM %s has no directory", name) + } + if memGB, ok := reims.ParseSizeGB(d.Memory); ok { + dirRep := host.Inspect(d.Directory) + needGB := memGB + 1.0 + if dirRep.FreeDiskGB > 0 && dirRep.FreeDiskGB < needGB { + return i18n.NewCodedError(loc, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{ + "need": fmt.Sprintf("%.1f", needGB), + "avail": fmt.Sprintf("%.1f", dirRep.FreeDiskGB), + }, nil) + } + } + + oldPID := a.cachedVMPID(name) + a.cancelRebootWatcher(name) + stopVMMonitor(name) + + a.mu.Lock() + mgr := a.pluginMgr + gt := a.guestTools + a.transitions[name] = "suspending" + a.mu.Unlock() + if mgr != nil { + mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, plugin.VMEventPayload{ + VMName: name, + VMDir: d.Directory, + DriverID: builtin.IDDriverReimsMacOS, + }) + } + a.emitStateChanged() + + tmpPath := reims.SuspendStatePath(d.Directory) + ".tmp" + _ = os.Remove(tmpPath) + + a.emitLog(name, fmt.Sprintf("Suspending %s to disk (%s)...", name, reims.SuspendStateFileName)) + lastPct := -1 + err = qmp.SuspendToFile(ctx, d.Directory, tmpPath, func(p qmp.MigrateProgress) { + if p.Total > 0 { + pct := int(p.Transferred * 100 / p.Total) + if pct >= lastPct+25 || p.Status == "completed" { + lastPct = pct + a.emitLog(name, fmt.Sprintf("Suspend progress: %s (%d%%)", p.Status, pct)) + } + } + }) + if err != nil { + _ = os.Remove(tmpPath) + a.clearTransition(name) + a.emitLog(name, "Suspend error: "+err.Error()) + a.wakePoll() + a.emitStateChanged() + return err + } + + a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout) + + st, statErr := os.Stat(tmpPath) + if statErr != nil || st.Size() <= 0 { + _ = os.Remove(tmpPath) + a.clearTransition(name) + a.wakePoll() + a.emitStateChanged() + if statErr != nil { + return fmt.Errorf("suspend snapshot missing after save: %w", statErr) + } + return fmt.Errorf("suspend snapshot is empty after save") + } + + finalPath := reims.SuspendStatePath(d.Directory) + _ = os.Remove(finalPath) + if err := os.Rename(tmpPath, finalPath); err != nil { + _ = os.Remove(tmpPath) + a.clearTransition(name) + a.wakePoll() + a.emitStateChanged() + return fmt.Errorf("finalize suspend snapshot: %w", err) + } + + info := reims.BuildSuspendInfo(d, prep.Runtime, st.Size()) + if err := reims.WriteSuspendInfo(d.Directory, info); err != nil { + _ = reims.RemoveSuspendState(d.Directory) + a.clearTransition(name) + a.wakePoll() + a.emitStateChanged() + return fmt.Errorf("write suspend metadata: %w", err) + } + + if gt != nil { + gt.UnregisterVM(name) + } + if mgr != nil { + mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{ + VMName: name, + VMDir: d.Directory, + DriverID: builtin.IDDriverReimsMacOS, + }) + } + a.clearTransition(name) + a.emitLog(name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", name, float64(st.Size())/float64(1<<30))) + a.wakePoll() + a.emitStateChanged() + return nil +} + +// ResumeVM launches a fresh QEMU process in `-incoming defer` mode (via +// `reims-ctl set --extra-args`), restores the VM's RAM, CPU, devices, and vGPU +// state from suspend.vmstate, and resumes guest execution. On any restore +// failure, suspend.vmstate and suspend.json are preserved so the user can retry. +func (a *App) ResumeVM(name string) error { + loc := a.locale() + prep, err := a.prep(name) + if err != nil { + return err + } + if !prep.Runtime.Manifest.HasCapability("vm-suspend") { + return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + } + + a.mu.Lock() + root := a.cfg.DataRoot + if tr := a.transitions[name]; tr != "" { + a.mu.Unlock() + return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) + } + mgr := a.pluginMgr + a.mu.Unlock() + + ctx := a.baseCtx() + c := prep.Client + d, err := c.Show(ctx, name) + if err != nil { + return err + } + if a.isVMRunning(ctx, c, name, d) { + return fmt.Errorf("%s", i18n.T(loc, "vm.already_running", name)) + } + if !reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": name}, nil) + } + meta, err := reims.ReadSuspendInfo(d.Directory) + if err != nil { + return fmt.Errorf("read suspend metadata: %w", err) + } + if diffs := reims.ValidateSuspendCompatibility(*meta, d, prep.Runtime); len(diffs) > 0 { + return i18n.NewCodedError(loc, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{ + "diffs": strings.Join(diffs, ", "), + }, nil) + } + + rep := host.Inspect(root) + if err := prep.CheckWHPX(rep); err != nil { + a.emitLog(name, "Resume refused: "+err.Error()) + return err + } + if err := prep.CheckMemory(d.Memory, rep); err != nil { + a.emitLog(name, "Resume refused: "+err.Error()) + return err + } + + a.cancelRebootWatcher(name) + + if prep.Runtime.Manifest.HasCapability("win32-unicode-input") { + if env := a.inputBridgeEnv(name, d.Directory); len(env) > 0 { + c.Env = append(c.Env, env...) + } + } + if prep.Runtime.Manifest.HasCapability("display-fixed-mode") && + host.ShouldUseFixedGuestMode(d.Borderless, d.Resolution, rep.PrimaryDisplay) { + c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1") + } + + origExtraArgs := reims.StripIncomingDeferArgs(d.ExtraArgs) + incomingArgs := reims.MergeIncomingDeferArgs(origExtraArgs) + if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &incomingArgs}, io.Discard, io.Discard); err != nil { + return fmt.Errorf("prepare incoming extra-args: %w", err) + } + restoredExtra := false + restoreExtra := func() { + if restoredExtra { + return + } + restoredExtra = true + if rerr := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &origExtraArgs}, io.Discard, io.Discard); rerr != nil { + a.emitLog(name, "Warning: could not restore extra-args after incoming launch: "+rerr.Error()) + } + } + defer restoreExtra() + + a.mu.Lock() + a.transitions[name] = "resuming" + a.mu.Unlock() + a.emitStateChanged() + + startAt := time.Now() + w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) + a.emitLog(name, fmt.Sprintf("Resuming %s from %s...", name, reims.SuspendStateFileName)) + if err := c.Start(ctx, name, w, w); err != nil { + restoreExtra() + a.clearTransition(name) + a.emitLog(name, "Resume launch error: "+err.Error()) + a.wakePoll() + a.emitStateChanged() + return err + } + restoreExtra() + + if err := qmp.ResumeFromFile(ctx, d.Directory, reims.SuspendStatePath(d.Directory), nil); err != nil { + a.emitLog(name, "Resume snapshot error (suspend state preserved for retry): "+err.Error()) + // Clean up the paused incoming QEMU process without touching suspend.vmstate. + if qerr := qmp.QuitVM(context.Background(), d.Directory); qerr != nil { + _ = c.StopForce(context.Background(), name, io.Discard, io.Discard) + } + a.clearTransition(name) + a.wakePoll() + a.emitStateChanged() + return err + } + + if rerr := reims.RemoveSuspendState(d.Directory); rerr != nil { + a.emitLog(name, "Warning: could not remove consumed suspend files: "+rerr.Error()) + } + + if mgr != nil { + mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{ + VMName: name, + VMDir: d.Directory, + DriverID: builtin.IDDriverReimsMacOS, + }) + } + a.startVMMonitor(name, d, startAt) + a.clearTransition(name) + a.emitLog(name, fmt.Sprintf("Resumed %s in %.1fs", name, time.Since(startAt).Seconds())) + a.wakePoll() + a.emitStateChanged() + return nil +} + +// DiscardSuspend deletes a suspended VM's saved RAM/device snapshot so the VM +// returns to the ordinary stopped state (equivalent to powering off). +func (a *App) DiscardSuspend(name string) error { + loc := a.locale() + c, err := a.client() + if err != nil { + return err + } + a.mu.Lock() + if tr := a.transitions[name]; tr != "" { + a.mu.Unlock() + return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) + } + a.mu.Unlock() + + ctx := a.baseCtx() + d, err := c.Show(ctx, name) + if err != nil { + return err + } + if a.isVMRunning(ctx, c, name, d) { + return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": name}, nil) + } + if err := reims.RemoveSuspendState(d.Directory); err != nil { + return err + } + a.emitLog(name, "Discarded suspend state for "+name) + a.wakePoll() + a.emitStateChanged() + return nil +} + +func (a *App) clearTransition(name string) { + a.mu.Lock() + delete(a.transitions, name) + a.mu.Unlock() +} + +func (a *App) emitStateChanged() { + if a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + } +} diff --git a/internal/app/suspend_flow_test.go b/internal/app/suspend_flow_test.go new file mode 100644 index 0000000..686c25f --- /dev/null +++ b/internal/app/suspend_flow_test.go @@ -0,0 +1,58 @@ +package app + +import ( + "os" + "testing" + + "github.com/Nwflower/reims-go/internal/driver/reims" + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +func TestEnrichVMListStatesAndPopulateSuspendDetail(t *testing.T) { + suspendedDir := t.TempDir() + stoppedDir := t.TempDir() + + if err := os.WriteFile(reims.SuspendStatePath(suspendedDir), []byte("0123456789"), 0o644); err != nil { + t.Fatal(err) + } + if err := reims.WriteSuspendInfo(suspendedDir, reims.BuildSuspendInfo( + reims.VMDetail{Name: "mac-a", CPUs: 8, Memory: "8G", Graphics: "reims-vgpu"}, + rt.Installed{Commit: "3731afd"}, + 10, + )); err != nil { + t.Fatal(err) + } + + vms := []reims.VMListItem{ + {Name: "mac-a", Dir: suspendedDir, State: "stopped"}, + {Name: "mac-b", Dir: stoppedDir, State: "stopped"}, + {Name: "mac-c", Dir: suspendedDir, State: "running"}, + } + enrichVMListStates(vms) + if vms[0].State != "suspended" { + t.Fatalf("mac-a state = %q, want suspended", vms[0].State) + } + if vms[1].State != "stopped" { + t.Fatalf("mac-b state = %q, want stopped", vms[1].State) + } + if vms[2].State != "running" { + t.Fatalf("running VM must stay running, got %q", vms[2].State) + } + + a := &App{} + det := reims.VMDetail{Name: "mac-a", Directory: suspendedDir, State: "stopped"} + a.populateSuspendDetail(&det) + if det.State != "suspended" || det.SuspendInfo == nil || det.SuspendInfo.VMStateSize != 10 { + t.Fatalf("populateSuspendDetail failed: %+v", det) + } + if !a.isVMSuspended(det) { + t.Fatal("expected isVMSuspended=true") + } +} + +func TestStripLegacyManagedExtraArgsStripsIncomingDefer(t *testing.T) { + got := stripLegacyManagedExtraArgs("-machine kernel-irqchip=on -incoming defer") + if got != "-machine kernel-irqchip=on" { + t.Fatalf("stripLegacyManagedExtraArgs = %q", got) + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index cc733c6..5242e24 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -134,6 +134,9 @@ func printUsage(loc i18n.Locale) { "cli.usage.cmd_vm_compact", "cli.usage.cmd_vm_start", "cli.usage.cmd_vm_stop", + "cli.usage.cmd_vm_suspend", + "cli.usage.cmd_vm_resume", + "cli.usage.cmd_vm_discard_suspend", "cli.usage.cmd_vm_type", "cli.usage.cmd_inst_list", "cli.usage.cmd_inst_dl", @@ -370,7 +373,7 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error { func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error { if len(args) == 0 { - return fmt.Errorf("usage: reims-go vm ") + return fmt.Errorf("usage: reims-go vm ") } prep, err := vmstart.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) }) if err != nil { @@ -389,6 +392,13 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e fmt.Println(i18n.T(loc, "vm.empty")) return nil } + for i := range vms { + if st, _ := vms[i]["state"].(string); st == "stopped" { + if dir, _ := vms[i]["dir"].(string); reims.HasSuspendState(dir) { + vms[i]["state"] = "suspended" + } + } + } enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") return enc.Encode(vms) @@ -519,6 +529,9 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e AudioBackend: strings.TrimSpace(*audioBackend), GuestLang: strings.TrimSpace(*guestLang), } + if d, serr := client.Show(ctx, setOpts.Name); serr == nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_SET_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": setOpts.Name}, nil) + } if reims.HasCtlSetChanges(setOpts) { if err := client.Set(ctx, setOpts, os.Stdout, os.Stderr); err != nil { return err @@ -544,6 +557,21 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e return fmt.Errorf("usage: reims-go vm stop ") } return client.Stop(ctx, args[1], os.Stdout, os.Stderr) + case "suspend": + if len(args) < 2 { + return fmt.Errorf("usage: reims-go vm suspend ") + } + return suspendVM(ctx, cfg, prep, args[1]) + case "resume": + if len(args) < 2 { + return fmt.Errorf("usage: reims-go vm resume ") + } + return resumeVM(ctx, cfg, prep, args[1]) + case "discard-suspend": + if len(args) < 2 { + return fmt.Errorf("usage: reims-go vm discard-suspend ") + } + return discardSuspendVM(ctx, cfg, prep, args[1]) case "eject": if len(args) < 2 { return fmt.Errorf("usage: reims-go vm eject ") @@ -583,6 +611,9 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if d.State == "running" { return fmt.Errorf("%s", i18n.T(loc, "vm.resize.stop_first", args[1])) } + if reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_RESIZE_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil) + } diskPath := resolveCLIDiskPath(d) res, err := reims.ResizeDisk(ctx, active.QemuImgPath(), client.Env, diskPath, args[2], os.Stdout, os.Stderr) if err != nil { @@ -602,6 +633,9 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if d.State == "running" { return fmt.Errorf("%s", i18n.T(loc, "vm.compact.stop_first", args[1])) } + if reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_COMPACT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil) + } diskPath := resolveCLIDiskPath(d) res, err := reims.CompactDisk(ctx, active.QemuImgPath(), client.Env, diskPath, os.Stdout, os.Stderr) if err != nil { diff --git a/internal/cli/start.go b/internal/cli/start.go index d81ed1a..b6b215c 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -11,6 +11,7 @@ import ( "time" "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/plugin" @@ -49,6 +50,9 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s if viaWindow && windowHandoffWorks { return startInWindow(ctx, cfg, name) } + if d.State == "stopped" && reims.HasSuspendState(d.Directory) { + return resumeVM(ctx, cfg, prep, name) + } // Honour the core plugin's WHPX setting, as the window does. st := plugin.ReadState(cfg.DataRoot) diff --git a/internal/cli/suspend.go b/internal/cli/suspend.go new file mode 100644 index 0000000..e120f83 --- /dev/null +++ b/internal/cli/suspend.go @@ -0,0 +1,179 @@ +package cli + +import ( + "context" + "fmt" + "io" + "os" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/qmp" + "github.com/Nwflower/reims-go/internal/vmstart" +) + +func suspendVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { + loc := cfg.Locale + if !prep.Runtime.Manifest.HasCapability("vm-suspend") { + return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + } + d, err := prep.Client.Show(ctx, name) + if err != nil { + return err + } + if d.State != "running" { + return i18n.NewCodedError(loc, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": name}, nil) + } + if memGB, ok := reims.ParseSizeGB(d.Memory); ok { + dirRep := host.Inspect(d.Directory) + needGB := memGB + 1.0 + if dirRep.FreeDiskGB > 0 && dirRep.FreeDiskGB < needGB { + return i18n.NewCodedError(loc, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{ + "need": fmt.Sprintf("%.1f", needGB), + "avail": fmt.Sprintf("%.1f", dirRep.FreeDiskGB), + }, nil) + } + } + var oldPID int + if vms, lerr := prep.Client.List(ctx); lerr == nil { + for _, vm := range vms { + if vm.Name == name && vm.PID != nil && *vm.PID > 0 { + oldPID = *vm.PID + break + } + } + } + + tmpPath := reims.SuspendStatePath(d.Directory) + ".tmp" + _ = os.Remove(tmpPath) + fmt.Fprintf(os.Stderr, "Suspending %s to %s...\n", name, reims.SuspendStateFileName) + if err := qmp.SuspendToFile(ctx, d.Directory, tmpPath, nil); err != nil { + _ = os.Remove(tmpPath) + return err + } + if oldPID > 0 { + waitCtx, cancel := context.WithTimeout(ctx, 12*time.Second) + _ = host.WaitProcessExit(waitCtx, uint32(oldPID), "qemu-system-x86_64.exe") + cancel() + } + st, err := os.Stat(tmpPath) + if err != nil || st.Size() <= 0 { + _ = os.Remove(tmpPath) + if err != nil { + return err + } + return fmt.Errorf("suspend snapshot is empty after save") + } + finalPath := reims.SuspendStatePath(d.Directory) + _ = os.Remove(finalPath) + if err := os.Rename(tmpPath, finalPath); err != nil { + _ = os.Remove(tmpPath) + return err + } + if err := reims.WriteSuspendInfo(d.Directory, reims.BuildSuspendInfo(d, prep.Runtime, st.Size())); err != nil { + _ = reims.RemoveSuspendState(d.Directory) + return err + } + fmt.Printf("Suspended %s (%.2f GiB saved)\n", name, float64(st.Size())/float64(1<<30)) + return nil +} + +func resumeVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { + loc := cfg.Locale + if !prep.Runtime.Manifest.HasCapability("vm-suspend") { + return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + } + rep := host.Inspect(cfg.DataRoot) + d, err := prep.Client.Show(ctx, name) + if err != nil { + return err + } + if d.State == "running" { + return fmt.Errorf("%s", i18n.T(loc, "vm.already_running", name)) + } + if !reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": name}, nil) + } + meta, err := reims.ReadSuspendInfo(d.Directory) + if err != nil { + return err + } + if diffs := reims.ValidateSuspendCompatibility(*meta, d, prep.Runtime); len(diffs) > 0 { + return i18n.NewCodedError(loc, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{ + "diffs": strings.Join(diffs, ", "), + }, nil) + } + if err := prep.CheckWHPX(rep); err != nil { + return err + } + if err := prep.CheckMemory(d.Memory, rep); err != nil { + return err + } + + origExtraArgs := reims.StripIncomingDeferArgs(d.ExtraArgs) + incomingArgs := reims.MergeIncomingDeferArgs(origExtraArgs) + if err := prep.Client.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &incomingArgs}, io.Discard, io.Discard); err != nil { + return err + } + restored := false + restoreExtra := func() { + if restored { + return + } + restored = true + _ = prep.Client.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &origExtraArgs}, io.Discard, io.Discard) + } + defer restoreExtra() + + fmt.Fprintf(os.Stderr, "Resuming %s from %s...\n", name, reims.SuspendStateFileName) + startAt := time.Now() + if err := prep.Client.Start(ctx, name, os.Stdout, os.Stderr); err != nil { + restoreExtra() + return err + } + restoreExtra() + + if err := qmp.ResumeFromFile(ctx, d.Directory, reims.SuspendStatePath(d.Directory), nil); err != nil { + if qerr := qmp.QuitVM(context.Background(), d.Directory); qerr != nil { + _ = prep.Client.StopForce(context.Background(), name, io.Discard, io.Discard) + } + return err + } + _ = reims.RemoveSuspendState(d.Directory) + + if vms, lerr := prep.Client.List(ctx); lerr == nil { + for _, vm := range vms { + if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { + vmDir := vm.Dir + if vmDir == "" { + vmDir = d.Directory + } + if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, vmDir, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" { + fmt.Fprintln(os.Stderr, line) + } + } + } + } + fmt.Printf("Resumed %s in %.1fs\n", name, time.Since(startAt).Seconds()) + return nil +} + +func discardSuspendVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { + loc := cfg.Locale + d, err := prep.Client.Show(ctx, name) + if err != nil { + return err + } + if d.State == "running" { + return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": name}, nil) + } + if err := reims.RemoveSuspendState(d.Directory); err != nil { + return err + } + fmt.Printf("Discarded suspend state for %s\n", name) + return nil +} diff --git a/internal/driver/reims/reims.go b/internal/driver/reims/reims.go index 17dcc5d..06b51de 100644 --- a/internal/driver/reims/reims.go +++ b/internal/driver/reims/reims.go @@ -88,8 +88,9 @@ 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"` + SuspendInfo *SuspendInfo `json:"suspend_info,omitempty"` } type ValidationIssue struct { @@ -258,6 +259,10 @@ func ValidateSetLocalized(o SetOpts, current VMDetail, rep host.Report, loc i18n if strings.TrimSpace(o.Name) == "" { issues = append(issues, ValidationIssue{Field: "name", Code: "missing_name", Message: i18n.T(loc, "validate.missing_name")}) } + if current.State == "suspended" { + issues = append(issues, ValidationIssue{Field: "state", Code: "vm_suspended", Message: i18n.T(loc, "validate.vm_suspended")}) + return issues + } if o.CPUs != 0 && (o.CPUs < 1 || (rep.LogicalCPUs > 0 && o.CPUs > rep.LogicalCPUs)) { issues = append(issues, ValidationIssue{Field: "cpus", Code: "invalid_cpus", Message: i18n.T(loc, "validate.invalid_cpus", max(rep.LogicalCPUs, 1))}) } diff --git a/internal/driver/reims/suspend.go b/internal/driver/reims/suspend.go new file mode 100644 index 0000000..b4035d4 --- /dev/null +++ b/internal/driver/reims/suspend.go @@ -0,0 +1,240 @@ +package reims + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +const ( + // SuspendStateFileName holds the QEMU mapped-ram + device VMState snapshot. + SuspendStateFileName = "suspend.vmstate" + // SuspendMetaFileName records the hardware and runtime fingerprint used to + // create suspend.vmstate so incompatible resumes are caught before launch. + SuspendMetaFileName = "suspend.json" + // SuspendSchemaVersion is the current metadata schema version. + SuspendSchemaVersion = 1 +) + +// SuspendInfo describes a VM's saved suspend-to-disk state inside its VM folder. +type SuspendInfo struct { + SchemaVersion int `json:"schema_version"` + VMName string `json:"vm_name"` + CPUs int `json:"cpus"` + Memory string `json:"memory"` + Graphics string `json:"graphics"` + Displays int `json:"displays"` + Resolution string `json:"resolution"` + DiskController string `json:"disk_controller"` + CPUModel string `json:"cpu_model,omitempty"` + Audio bool `json:"audio"` + AudioBackend string `json:"audio_backend,omitempty"` + Network bool `json:"network"` + SSHPort int `json:"ssh_port"` + ExtraArgs string `json:"extra_args,omitempty"` + RuntimeCommit string `json:"runtime_commit"` + VendorQemuCommit string `json:"vendor_qemu_commit,omitempty"` + CreatedAt string `json:"created_at"` + VMStateSize int64 `json:"vmstate_size"` +} + +// SuspendStatePath returns the path to a VM's suspend snapshot file. +func SuspendStatePath(vmDir string) string { + return filepath.Join(vmDir, SuspendStateFileName) +} + +// SuspendMetaPath returns the path to a VM's suspend metadata JSON file. +func SuspendMetaPath(vmDir string) string { + return filepath.Join(vmDir, SuspendMetaFileName) +} + +// HasSuspendState reports whether vmDir contains a complete suspend snapshot +// (both a non-empty suspend.vmstate and its suspend.json metadata). +func HasSuspendState(vmDir string) bool { + if strings.TrimSpace(vmDir) == "" { + return false + } + st, err := os.Stat(SuspendStatePath(vmDir)) + if err != nil || st.IsDir() || st.Size() <= 0 { + return false + } + mst, err := os.Stat(SuspendMetaPath(vmDir)) + if err != nil || mst.IsDir() || mst.Size() <= 0 { + return false + } + return true +} + +// ReadSuspendInfo reads suspend.json from vmDir and refreshes VMStateSize from +// the actual suspend.vmstate file on disk. +func ReadSuspendInfo(vmDir string) (*SuspendInfo, error) { + b, err := os.ReadFile(SuspendMetaPath(vmDir)) + if err != nil { + return nil, err + } + var info SuspendInfo + if err := json.Unmarshal(b, &info); err != nil { + return nil, fmt.Errorf("parse %s: %w", SuspendMetaFileName, err) + } + if st, err := os.Stat(SuspendStatePath(vmDir)); err == nil && !st.IsDir() { + info.VMStateSize = st.Size() + } + return &info, nil +} + +// WriteSuspendInfo atomically writes suspend.json inside vmDir. +func WriteSuspendInfo(vmDir string, info SuspendInfo) error { + if info.SchemaVersion == 0 { + info.SchemaVersion = SuspendSchemaVersion + } + if info.CreatedAt == "" { + info.CreatedAt = time.Now().UTC().Format(time.RFC3339) + } + info.ExtraArgs = StripIncomingDeferArgs(info.ExtraArgs) + b, err := json.MarshalIndent(info, "", " ") + if err != nil { + return err + } + b = append(b, '\n') + tmp := SuspendMetaPath(vmDir) + ".tmp" + if err := os.WriteFile(tmp, b, 0o644); err != nil { + return err + } + return os.Rename(tmp, SuspendMetaPath(vmDir)) +} + +// BuildSuspendInfo snapshots a VM's hardware and runtime fingerprint for suspend.json. +func BuildSuspendInfo(d VMDetail, active rt.Installed, vmstateSize int64) SuspendInfo { + return SuspendInfo{ + SchemaVersion: SuspendSchemaVersion, + VMName: d.Name, + CPUs: d.CPUs, + Memory: strings.TrimSpace(d.Memory), + Graphics: strings.TrimSpace(d.Graphics), + Displays: d.Displays, + Resolution: strings.TrimSpace(d.Resolution), + DiskController: strings.TrimSpace(d.DiskController), + CPUModel: strings.TrimSpace(d.CPUModel), + Audio: d.Audio, + AudioBackend: strings.TrimSpace(d.AudioBackend), + Network: d.Network, + SSHPort: d.SSHPort, + ExtraArgs: StripIncomingDeferArgs(d.ExtraArgs), + RuntimeCommit: strings.TrimSpace(active.Commit), + VendorQemuCommit: strings.TrimSpace(active.Manifest.VendorQemuCommit), + CreatedAt: time.Now().UTC().Format(time.RFC3339), + VMStateSize: vmstateSize, + } +} + +// RemoveSuspendState deletes suspend.vmstate, suspend.json, and any partial +// temporary files inside vmDir. +func RemoveSuspendState(vmDir string) error { + if strings.TrimSpace(vmDir) == "" { + return nil + } + var firstErr error + for _, name := range []string{ + SuspendMetaFileName, + SuspendMetaFileName + ".tmp", + SuspendStateFileName, + SuspendStateFileName + ".tmp", + } { + if err := os.Remove(filepath.Join(vmDir, name)); err != nil && !os.IsNotExist(err) && firstErr == nil { + firstErr = err + } + } + return firstErr +} + +// ValidateSuspendCompatibility checks that the VM hardware and runtime match +// the fingerprint stored when the VM was suspended. Returns human-readable +// mismatch descriptions; an empty slice means compatible. +func ValidateSuspendCompatibility(meta SuspendInfo, cur VMDetail, active rt.Installed) []string { + var diffs []string + if meta.CPUs > 0 && cur.CPUs > 0 && meta.CPUs != cur.CPUs { + diffs = append(diffs, fmt.Sprintf("CPUs (%d -> %d)", meta.CPUs, cur.CPUs)) + } + if meta.Memory != "" && cur.Memory != "" && !strings.EqualFold(strings.TrimSpace(meta.Memory), strings.TrimSpace(cur.Memory)) { + diffs = append(diffs, fmt.Sprintf("Memory (%s -> %s)", meta.Memory, cur.Memory)) + } + if meta.Graphics != "" && cur.Graphics != "" && !strings.EqualFold(strings.TrimSpace(meta.Graphics), strings.TrimSpace(cur.Graphics)) { + diffs = append(diffs, fmt.Sprintf("Graphics (%s -> %s)", meta.Graphics, cur.Graphics)) + } + if meta.Displays > 0 && cur.Displays > 0 && meta.Displays != cur.Displays { + diffs = append(diffs, fmt.Sprintf("Displays (%d -> %d)", meta.Displays, cur.Displays)) + } + if meta.DiskController != "" && cur.DiskController != "" && !strings.EqualFold(strings.TrimSpace(meta.DiskController), strings.TrimSpace(cur.DiskController)) { + diffs = append(diffs, fmt.Sprintf("Disk controller (%s -> %s)", meta.DiskController, cur.DiskController)) + } + if meta.Audio != cur.Audio { + diffs = append(diffs, fmt.Sprintf("Audio (%v -> %v)", meta.Audio, cur.Audio)) + } + if meta.Network != cur.Network { + diffs = append(diffs, fmt.Sprintf("Network (%v -> %v)", meta.Network, cur.Network)) + } + if meta.VendorQemuCommit != "" && active.Manifest.VendorQemuCommit != "" && + !strings.EqualFold(strings.TrimSpace(meta.VendorQemuCommit), strings.TrimSpace(active.Manifest.VendorQemuCommit)) { + diffs = append(diffs, fmt.Sprintf("QEMU commit (%s -> %s)", shortRev(meta.VendorQemuCommit), shortRev(active.Manifest.VendorQemuCommit))) + } else if meta.RuntimeCommit != "" && active.Commit != "" && + !strings.EqualFold(strings.TrimSpace(meta.RuntimeCommit), strings.TrimSpace(active.Commit)) { + diffs = append(diffs, fmt.Sprintf("Runtime (%s -> %s)", meta.RuntimeCommit, active.Commit)) + } + return diffs +} + +func shortRev(rev string) string { + rev = strings.TrimSpace(rev) + if len(rev) > 8 { + return rev[:8] + } + return rev +} + +// HasIncomingDeferArg reports whether extraArgs contains `-incoming defer`. +func HasIncomingDeferArg(extraArgs string) bool { + tokens := splitShellTokens(extraArgs) + for i := 0; i < len(tokens); i++ { + tok := tokens[i] + if tok == "-incoming" && i+1 < len(tokens) && tokens[i+1] == "defer" { + return true + } + if tok == "-incoming=defer" { + return true + } + } + return false +} + +// StripIncomingDeferArgs removes any `-incoming defer` / `-incoming=defer` +// arguments from QEMU extra-args while leaving all other arguments intact. +func StripIncomingDeferArgs(existing string) string { + tokens := splitShellTokens(existing) + cleaned := make([]string, 0, len(tokens)) + for i := 0; i < len(tokens); i++ { + tok := tokens[i] + if tok == "-incoming" && i+1 < len(tokens) && tokens[i+1] == "defer" { + i++ + continue + } + if tok == "-incoming=defer" { + continue + } + cleaned = append(cleaned, tok) + } + return strings.Join(cleaned, " ") +} + +// MergeIncomingDeferArgs idempotently appends `-incoming defer` to extra-args. +func MergeIncomingDeferArgs(existing string) string { + base := StripIncomingDeferArgs(existing) + if base == "" { + return "-incoming defer" + } + return base + " -incoming defer" +} diff --git a/internal/driver/reims/suspend_test.go b/internal/driver/reims/suspend_test.go new file mode 100644 index 0000000..4401ca6 --- /dev/null +++ b/internal/driver/reims/suspend_test.go @@ -0,0 +1,114 @@ +package reims + +import ( + "os" + "strings" + "testing" + + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +func TestSuspendStateLifecycle(t *testing.T) { + dir := t.TempDir() + if HasSuspendState(dir) { + t.Fatal("empty dir should not have suspend state") + } + + // Only vmstate without meta -> incomplete. + if err := os.WriteFile(SuspendStatePath(dir), []byte("vmstate-bytes"), 0o644); err != nil { + t.Fatal(err) + } + if HasSuspendState(dir) { + t.Fatal("vmstate without suspend.json should not count as complete suspend state") + } + + active := rt.Installed{ + Commit: "3731afd-p9", + Manifest: rt.Manifest{ + VendorQemuCommit: "4571bc5fecb039e8cfd6837e077810fbe074e11b", + }, + } + detail := VMDetail{ + Name: "tahoe", + CPUs: 8, + Memory: "8G", + Graphics: "reims-vgpu", + Displays: 1, + Resolution: "1920x1080", + DiskController: "nvme", + Audio: true, + Network: true, + ExtraArgs: "-machine kernel-irqchip=on -incoming defer", + } + info := BuildSuspendInfo(detail, active, 13) + if err := WriteSuspendInfo(dir, info); err != nil { + t.Fatalf("WriteSuspendInfo: %v", err) + } + if !HasSuspendState(dir) { + t.Fatal("expected HasSuspendState=true after writing both files") + } + + got, err := ReadSuspendInfo(dir) + if err != nil { + t.Fatalf("ReadSuspendInfo: %v", err) + } + if got.VMStateSize != 13 || got.CPUs != 8 || got.ExtraArgs != "-machine kernel-irqchip=on" { + t.Fatalf("unexpected suspend info: %+v", got) + } + + // Compatible check passes. + if diffs := ValidateSuspendCompatibility(*got, detail, active); len(diffs) != 0 { + t.Fatalf("expected compatible, got %v", diffs) + } + + // Hardware and runtime mismatch checks trigger. + changedDetail := detail + changedDetail.CPUs = 12 + changedDetail.Memory = "16G" + changedRT := active + changedRT.Manifest.VendorQemuCommit = "deadbeef00000000000000000000000000000000" + diffs := ValidateSuspendCompatibility(*got, changedDetail, changedRT) + if len(diffs) != 3 { + t.Fatalf("expected 3 diffs, got %v", diffs) + } + + if err := RemoveSuspendState(dir); err != nil { + t.Fatalf("RemoveSuspendState: %v", err) + } + if HasSuspendState(dir) { + t.Fatal("expected HasSuspendState=false after RemoveSuspendState") + } +} + +func TestIncomingDeferArgsIdempotent(t *testing.T) { + if HasIncomingDeferArg("") || HasIncomingDeferArg("-machine q35") { + t.Fatal("unexpected HasIncomingDeferArg=true") + } + m := MergeIncomingDeferArgs(`-drive "id=x,file=C:/a b/c.img"`) + if !HasIncomingDeferArg(m) { + t.Fatalf("expected -incoming defer in %q", m) + } + if m2 := MergeIncomingDeferArgs(m); m2 != m { + t.Fatalf("MergeIncomingDeferArgs not idempotent: %q vs %q", m2, m) + } + if s := StripIncomingDeferArgs(m + " -incoming=defer"); s != `-drive "id=x,file=C:/a b/c.img"` { + t.Fatalf("StripIncomingDeferArgs = %q", s) + } +} + +func TestValidateSetRejectsSuspendedVM(t *testing.T) { + issues := ValidateSetLocalized( + SetOpts{Name: "tahoe", CPUs: 6}, + VMDetail{Name: "tahoe", State: "suspended", CPUs: 8, Memory: "8G"}, + host.Report{LogicalCPUs: 16, TotalRAMGB: 32}, + i18n.EnUS, + ) + if len(issues) == 0 || issues[0].Code != "vm_suspended" { + t.Fatalf("expected vm_suspended validation issue, got %+v", issues) + } + if !strings.Contains(strings.ToLower(issues[0].Message), "suspend") { + t.Fatalf("unexpected message: %q", issues[0].Message) + } +} diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 25560a6..edc8c67 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -45,11 +45,14 @@ var catalog = map[Locale]map[string]string{ "cli.usage.cmd_version": " version 查看当前版本", "cli.usage.cmd_vm_compact": " vm compact 停机回收 .qcow2 磁盘未用空间", "cli.usage.cmd_vm_create": " vm create [options] 创建 macOS 虚拟机(可指定目录/核数/内存/硬盘/显卡)", + "cli.usage.cmd_vm_discard_suspend": " vm discard-suspend 放弃已保存的挂起状态并回到关机状态", "cli.usage.cmd_vm_list": " vm list 列出已创建的虚拟机", "cli.usage.cmd_vm_resize": " vm resize <大小> 停机扩容虚拟磁盘(如 256G 或 +64G)", + "cli.usage.cmd_vm_resume": " vm resume 从磁盘挂起状态恢复虚拟机", "cli.usage.cmd_vm_set": " vm set [options] 修改虚拟机配置(下次启动生效)", "cli.usage.cmd_vm_start": " vm start 启动虚拟机:交给界面进程(未运行则在托盘拉起),带剪贴板与共享目录;指定 --data-root 时在本进程内启动", "cli.usage.cmd_vm_stop": " vm stop|eject 停止 / 弹出安装盘", + "cli.usage.cmd_vm_suspend": " vm suspend 挂起运行中的虚拟机至磁盘(退出后或重启宿主可秒级恢复)", "cli.usage.cmd_vm_type": " vm type [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)", "cli.usage.header": "reims-go - Windows 一站式免编译 reims-vgpu 启动器", "cli.usage.line_cmd": " reims-go [--lang ] [--data-root DIR] <命令> [参数]", @@ -134,6 +137,14 @@ var catalog = map[Locale]map[string]string{ "err.snapshot.qcow2_only": "恢复点仅支持 .qcow2 格式磁盘", "err.snapshot.qemu_img_failed": "恢复点操作未完成({snap})", "err.snapshot.vm_running": "请先停止「{name}」再创建、回滚或删除恢复点", + "err.suspend.action_blocked": "虚拟机「{name}」当前处于挂起状态,请先恢复并关机,或放弃挂起状态后再执行此操作", + "err.suspend.busy": "虚拟机「{name}」正在执行状态切换,请稍后再试", + "err.suspend.discard_running": "虚拟机「{name}」正在运行,无法放弃挂起状态", + "err.suspend.disk_space": "磁盘可用空间不足以保存挂起文件(需要约 {need} GB,当前可用 {avail} GB)", + "err.suspend.incompatible": "虚拟机硬件或运行时版本与挂起时不一致({diffs})。请恢复原配置/运行时,或放弃挂起状态后重新启动", + "err.suspend.not_found": "未找到「{name}」的完整挂起状态文件", + "err.suspend.not_running": "虚拟机「{name}」未在运行,无法挂起", + "err.suspend.unsupported_runtime": "当前激活的便携运行时尚未包含虚拟机挂起/恢复支持,请更新至包含挂起补丁的运行时版本", "err.update_changed": "已下载的更新文件被改动过,请重新下载", "err.update_dev_build": "开发版本不支持应用内更新", "err.update_no_asset": "这个版本没有提供 Windows 程序文件,请到发布页手动下载", @@ -429,35 +440,44 @@ var catalog = map[Locale]map[string]string{ "toastSSHUserSaved": "已保存 SSH 用户名", "toastSaved": "已保存", "toastSavedNextStart": "已保存,下次启动生效", + "tray.menu.discard_suspend": "放弃挂起状态(&X)", "tray.menu.force_stop": "强制关机(&F)", "tray.menu.new_vm": "新建虚拟机(&N)…", "tray.menu.open_in_app": "在 Reims-Go 中查看(&V)", "tray.menu.quit": "退出 Reims-Go(&Q)", "tray.menu.restart": "重启(&R)", + "tray.menu.resume": "恢复(&U)", "tray.menu.screenshot": "复制屏幕截图(&C)", "tray.menu.shared_folder": "打开共享文件夹(&H)", "tray.menu.show": "显示 Reims-Go(&O)", "tray.menu.show_window": "显示窗口(&W)", "tray.menu.start": "启动(&S)", "tray.menu.stop": "关机(&D)", + "tray.menu.suspend": "挂起(&P)", "tray.menu.toggle_fullscreen": "切换全屏", + "tray.notify.discard_suspend_fail": "无法放弃 {name} 的挂起状态", "tray.notify.focus_fail": "找不到 {name} 的窗口", "tray.notify.force_stop_fail": "无法强制关机 {name}", "tray.notify.fullscreen_fail": "无法切换 {name} 全屏", "tray.notify.restart_fail": "无法重启 {name}", + "tray.notify.resume_fail": "无法恢复 {name}", "tray.notify.screenshot_fail": "截图失败:{name}", "tray.notify.screenshot_ok": "已复制屏幕截图", "tray.notify.shared_fail": "无法打开共享文件夹", "tray.notify.start_fail": "无法启动 {name}", "tray.notify.stop_fail": "无法关机 {name}", + "tray.notify.suspend_fail": "无法挂起 {name}", "tray.running": "{count, plural, =1 {Reims-Go — 1 台虚拟机运行中} other {Reims-Go — # 台虚拟机运行中}}", "tray.running.many": "Reims-Go — {count} 台虚拟机运行中", "tray.running.one": "Reims-Go — 1 台虚拟机运行中", "tray.state.broken": "配置损坏", + "tray.state.resuming": "正在恢复…", "tray.state.running": "运行中", "tray.state.starting": "启动中…", "tray.state.stopped": "已停止", "tray.state.stopping": "正在关机…", + "tray.state.suspended": "已挂起", + "tray.state.suspending": "正在挂起…", "tray.state.unknown": "未知", "updateCancel": "取消下载", "updateCapsuleAvailable": "{v} 可用", @@ -498,6 +518,7 @@ var catalog = map[Locale]map[string]string{ "validate.missing_name": "虚拟机名称不能为空", "validate.missing_release": "请选择要离线安装的 macOS 版本", "validate.name_taken": "已存在名为 {name} 的虚拟机", + "validate.vm_suspended": "虚拟机当前处于挂起状态,请先恢复或放弃挂起状态后再修改配置", "viewLogs": "查看日志", "vm.already_running": "{name} 已在运行中", "vm.compact.done": "{name}:磁盘已瘦身 {before, number, .2} GB -> {after, number, .2} GB(回收 {saved, number, .2} GB)", @@ -557,11 +578,14 @@ var catalog = map[Locale]map[string]string{ "cli.usage.cmd_version": " version Show current version", "cli.usage.cmd_vm_compact": " vm compact Compact stopped .qcow2 disk to reclaim unused space", "cli.usage.cmd_vm_create": " vm create [options] Create a macOS VM (custom dir, CPUs, RAM, disk size, GPU)", + "cli.usage.cmd_vm_discard_suspend": " vm discard-suspend Discard a saved suspend state and return the VM to powered off", "cli.usage.cmd_vm_list": " vm list List virtual machines", "cli.usage.cmd_vm_resize": " vm resize Expand stopped VM disk (e.g. 256G or +64G)", + "cli.usage.cmd_vm_resume": " vm resume Resume a suspended VM from disk", "cli.usage.cmd_vm_set": " vm set [options] Update VM settings (applies on next start)", "cli.usage.cmd_vm_start": " vm start Start a VM in the Reims-Go window process (launched in the tray if needed),\n with clipboard and shared folders; with --data-root it starts in this process", "cli.usage.cmd_vm_stop": " vm stop|eject Stop / eject installer", + "cli.usage.cmd_vm_suspend": " vm suspend Suspend a running VM to disk for fast resume across restarts", "cli.usage.cmd_vm_type": " vm type [text] Type text into a running VM as US-keyboard keys (stdin if no text)", "cli.usage.header": "reims-go - Portable one-stop reims-vgpu launcher for Windows", "cli.usage.line_cmd": " reims-go [--lang ] [--data-root DIR] [args]", @@ -646,6 +670,14 @@ var catalog = map[Locale]map[string]string{ "err.snapshot.qcow2_only": "Restore points are only supported on .qcow2 disks", "err.snapshot.qemu_img_failed": "Restore point operation could not finish ({snap})", "err.snapshot.vm_running": "Stop “{name}” before creating, restoring or deleting a restore point", + "err.suspend.action_blocked": "VM “{name}” is suspended; resume and shut it down or discard its saved state before doing this", + "err.suspend.busy": "VM “{name}” is busy transitioning; try again in a moment", + "err.suspend.discard_running": "VM “{name}” is currently running; suspend state cannot be discarded", + "err.suspend.disk_space": "Not enough free disk space to save the suspend file (need about {need} GB, {avail} GB available)", + "err.suspend.incompatible": "VM hardware or runtime differs from when it was suspended ({diffs}). Restore the previous configuration/runtime or discard the saved state", + "err.suspend.not_found": "No complete suspend state found for “{name}”", + "err.suspend.not_running": "VM “{name}” is not running and cannot be suspended", + "err.suspend.unsupported_runtime": "The active portable runtime does not support VM suspend/resume; update to a runtime built with suspend support", "err.update_changed": "The downloaded update changed on disk; download it again", "err.update_dev_build": "In-app update is disabled in development builds", "err.update_no_asset": "This release has no Windows executable; download it from the release page", @@ -941,35 +973,44 @@ var catalog = map[Locale]map[string]string{ "toastSSHUserSaved": "Saved SSH username", "toastSaved": "Saved", "toastSavedNextStart": "Saved — applies on next start", + "tray.menu.discard_suspend": "Discard Saved Stat&e", "tray.menu.force_stop": "&Force Shut Down", "tray.menu.new_vm": "&New Virtual Machine…", "tray.menu.open_in_app": "Show in &Reims-Go", "tray.menu.quit": "&Quit Reims-Go", "tray.menu.restart": "&Restart", + "tray.menu.resume": "Res&ume", "tray.menu.screenshot": "&Copy Screenshot", "tray.menu.shared_folder": "Open S&hared Folder", "tray.menu.show": "&Show Reims-Go", "tray.menu.show_window": "Show &Window", "tray.menu.start": "&Start", "tray.menu.stop": "Shut &Down", + "tray.menu.suspend": "Sus&pend", "tray.menu.toggle_fullscreen": "Toggle full screen", + "tray.notify.discard_suspend_fail": "Couldn't discard saved state for {name}", "tray.notify.focus_fail": "Couldn't find the window of {name}", "tray.notify.force_stop_fail": "Couldn't force shut down {name}", "tray.notify.fullscreen_fail": "Couldn’t toggle full screen for {name}", "tray.notify.restart_fail": "Couldn't restart {name}", + "tray.notify.resume_fail": "Couldn't resume {name}", "tray.notify.screenshot_fail": "Screenshot failed: {name}", "tray.notify.screenshot_ok": "Screenshot copied", "tray.notify.shared_fail": "Couldn't open the shared folder", "tray.notify.start_fail": "Couldn't start {name}", "tray.notify.stop_fail": "Couldn't shut down {name}", + "tray.notify.suspend_fail": "Couldn't suspend {name}", "tray.running": "{count, plural, one {Reims-Go — # VM running} other {Reims-Go — # VMs running}}", "tray.running.many": "Reims-Go — {count} VMs running", "tray.running.one": "Reims-Go — 1 VM running", "tray.state.broken": "Broken", + "tray.state.resuming": "Resuming…", "tray.state.running": "Running", "tray.state.starting": "Starting…", "tray.state.stopped": "Stopped", "tray.state.stopping": "Shutting down…", + "tray.state.suspended": "Suspended", + "tray.state.suspending": "Suspending…", "tray.state.unknown": "Unknown", "updateCancel": "Cancel download", "updateCapsuleAvailable": "{v} available", @@ -1010,6 +1051,7 @@ var catalog = map[Locale]map[string]string{ "validate.missing_name": "VM name is required", "validate.missing_release": "Choose the macOS release to install offline", "validate.name_taken": "A VM named {name} already exists", + "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", "vm.compact.done": "{name}: compacted disk {before, number, .2} GB -> {after, number, .2} GB (reclaimed {saved, number, .2} GB)", @@ -1074,6 +1116,13 @@ var paramOrder = map[string][]string{ "err.plugin.system_locked": {"id"}, "err.snapshot.qemu_img_failed": {"snap"}, "err.snapshot.vm_running": {"name"}, + "err.suspend.action_blocked": {"name"}, + "err.suspend.busy": {"name"}, + "err.suspend.discard_running": {"name"}, + "err.suspend.disk_space": {"need", "avail"}, + "err.suspend.incompatible": {"diffs"}, + "err.suspend.not_found": {"name"}, + "err.suspend.not_running": {"name"}, "err.update_not_writable": {"dir"}, "err.vm_not_running": {"name"}, "err.vm_window_not_found": {"name"}, @@ -1145,13 +1194,16 @@ var paramOrder = map[string][]string{ "toastInstallerReady": {"v"}, "toastRuntimeReady": {"v"}, "toastSSHConfigWritten": {"alias"}, + "tray.notify.discard_suspend_fail": {"name"}, "tray.notify.focus_fail": {"name"}, "tray.notify.force_stop_fail": {"name"}, "tray.notify.fullscreen_fail": {"name"}, "tray.notify.restart_fail": {"name"}, + "tray.notify.resume_fail": {"name"}, "tray.notify.screenshot_fail": {"name"}, "tray.notify.start_fail": {"name"}, "tray.notify.stop_fail": {"name"}, + "tray.notify.suspend_fail": {"name"}, "tray.running": {"count"}, "tray.running.many": {"count"}, "updateCapsuleAvailable": {"v"}, diff --git a/internal/qmp/client.go b/internal/qmp/client.go index f593836..bc7ba3b 100644 --- a/internal/qmp/client.go +++ b/internal/qmp/client.go @@ -52,8 +52,15 @@ type qmpReply struct { Event string `json:"event"` } -// Query runs one command and waits for its JSON return value, skipping async events. +// Query runs one command with the default 5-second timeout and waits for its +// JSON return value, skipping async events. func (c *Conn) Query(command string, args any) (json.RawMessage, error) { + return c.QueryWithTimeout(command, args, 5*time.Second) +} + +// QueryWithTimeout runs one command and waits up to timeout for its JSON return +// value, skipping async events. +func (c *Conn) QueryWithTimeout(command string, args any, timeout time.Duration) (json.RawMessage, error) { req := map[string]any{"execute": command} if args != nil { req["arguments"] = args @@ -62,7 +69,10 @@ func (c *Conn) Query(command string, args any) (json.RawMessage, error) { if err != nil { return nil, err } - _ = c.nc.SetDeadline(time.Now().Add(5 * time.Second)) + if timeout <= 0 { + timeout = 5 * time.Second + } + _ = c.nc.SetDeadline(time.Now().Add(timeout)) if _, err := c.nc.Write(append(b, '\n')); err != nil { return nil, fmt.Errorf("QMP %s: %w", command, err) } @@ -84,8 +94,16 @@ func (c *Conn) Query(command string, args any) (json.RawMessage, error) { return nil, fmt.Errorf("QMP %s: connection closed", command) } -// Execute runs one command and waits for its reply, skipping async events. +// Execute runs one command with the default timeout and waits for its reply, +// skipping async events. func (c *Conn) Execute(command string, args any) error { _, err := c.Query(command, args) return err } + +// ExecuteWithTimeout runs one command and waits up to timeout for its reply, +// skipping async events. +func (c *Conn) ExecuteWithTimeout(command string, args any, timeout time.Duration) error { + _, err := c.QueryWithTimeout(command, args, timeout) + return err +} diff --git a/internal/qmp/migrate.go b/internal/qmp/migrate.go new file mode 100644 index 0000000..effe1d1 --- /dev/null +++ b/internal/qmp/migrate.go @@ -0,0 +1,275 @@ +package qmp + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "path/filepath" + "strings" + "time" +) + +const ( + // DefaultMultifdChannels is the parallel I/O channel count used for + // mapped-ram file snapshots on Windows. + DefaultMultifdChannels = 4 + + migratePollInterval = 200 * time.Millisecond + migrateCmdTimeout = 2 * time.Minute + migrateTotalTimeout = 15 * time.Minute +) + +// MigrateProgress carries the latest snapshot save/load progress from QMP +// `query-migrate`. +type MigrateProgress struct { + Status string `json:"status"` + Transferred int64 `json:"transferred"` + Remaining int64 `json:"remaining"` + Total int64 `json:"total"` + TotalTimeMs int64 `json:"total_time_ms"` +} + +type migrateInfo struct { + Status string `json:"status"` + ErrorDesc string `json:"error-desc"` + TotalTimeMs int64 `json:"total-time"` + RAM *struct { + Transferred int64 `json:"transferred"` + Remaining int64 `json:"remaining"` + Total int64 `json:"total"` + } `json:"ram"` +} + +type vmStatusReply struct { + Running bool `json:"running"` + Status string `json:"status"` +} + +// SuspendToFile pauses a running Intel VM via QMP, writes a mapped-ram + +// multifd file snapshot to vmstatePath, waits for completion, and shuts down +// QEMU cleanly via `quit`. +// +// If migration fails before reaching completion while the VM is merely paused +// (not postmigrate), SuspendToFile attempts to resume the guest with `cont` so +// the running VM is not left frozen. +func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress)) error { + c, err := Dial(ctx, "unix", SocketPath(vmDir)) + if err != nil { + return err + } + defer c.Close() + return suspendToFileConn(ctx, c, vmstatePath, onProgress) +} + +func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress)) error { + if err := c.ExecuteWithTimeout("stop", nil, 30*time.Second); err != nil { + return fmt.Errorf("pause VM before suspend: %w", err) + } + st, err := queryVMStatus(c) + if err != nil { + tryResumePaused(c) + return fmt.Errorf("verify paused state: %w", err) + } + if st.Running { + return fmt.Errorf("VM remained running after stop (status=%s)", st.Status) + } + + if err := configureMappedRAM(c); err != nil { + tryResumePaused(c) + return err + } + + args := map[string]any{ + "channels": fileChannels(vmstatePath), + } + if err := c.ExecuteWithTimeout("migrate", args, migrateCmdTimeout); err != nil { + tryResumePaused(c) + return fmt.Errorf("start snapshot save: %w", err) + } + + if err := waitMigrateDone(ctx, c, onProgress); err != nil { + tryResumePaused(c) + return fmt.Errorf("save snapshot: %w", err) + } + + // Migration completed (RUN_STATE_POSTMIGRATE): never send `cont` here; + // exit QEMU cleanly so the disk and WHPX partition close. + if err := c.ExecuteWithTimeout("quit", nil, 15*time.Second); err != nil { + // QEMU may close the QMP socket immediately upon receiving `quit`. + if !isConnClosedErr(err) { + return fmt.Errorf("quit QEMU after suspend: %w", err) + } + } + return nil +} + +// ResumeFromFile connects to a QEMU process started with `-incoming defer`, +// loads the mapped-ram + multifd file snapshot from vmstatePath, waits for +// completion, and resumes execution with `cont`. +// +// On any error, vmstatePath is left untouched so the caller can retry. +func ResumeFromFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress)) error { + c, err := dialMigrateConnWithRetry(ctx, "unix", SocketPath(vmDir), 10*time.Second) + if err != nil { + return err + } + defer c.Close() + return resumeFromFileConn(ctx, c, vmstatePath, onProgress) +} + +func resumeFromFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress)) error { + if err := configureMappedRAM(c); err != nil { + return err + } + args := map[string]any{ + "channels": fileChannels(vmstatePath), + "exit-on-error": false, + } + if err := c.ExecuteWithTimeout("migrate-incoming", args, migrateCmdTimeout); err != nil { + return fmt.Errorf("start snapshot restore: %w", err) + } + if err := waitMigrateDone(ctx, c, onProgress); err != nil { + return fmt.Errorf("restore snapshot: %w", err) + } + if err := c.ExecuteWithTimeout("cont", nil, 30*time.Second); err != nil { + return fmt.Errorf("resume VM execution after restore: %w", err) + } + return nil +} + +// QuitVM sends QMP `quit` to the VM's QMP socket (best-effort cleanup for a +// failed incoming-resume QEMU process). +func QuitVM(ctx context.Context, vmDir string) error { + c, err := Dial(ctx, "unix", SocketPath(vmDir)) + if err != nil { + return err + } + defer c.Close() + if err := c.ExecuteWithTimeout("quit", nil, 10*time.Second); err != nil && !isConnClosedErr(err) { + return err + } + return nil +} + +func configureMappedRAM(c *Conn) error { + caps := map[string]any{ + "capabilities": []map[string]any{ + {"capability": "mapped-ram", "state": true}, + {"capability": "multifd", "state": true}, + }, + } + if err := c.ExecuteWithTimeout("migrate-set-capabilities", caps, 15*time.Second); err != nil { + return fmt.Errorf("enable mapped-ram/multifd capabilities: %w", err) + } + params := map[string]any{ + "multifd-channels": DefaultMultifdChannels, + } + if err := c.ExecuteWithTimeout("migrate-set-parameters", params, 15*time.Second); err != nil { + return fmt.Errorf("set multifd-channels: %w", err) + } + return nil +} + +func fileChannels(vmstatePath string) []map[string]any { + return []map[string]any{ + { + "channel-type": "main", + "addr": map[string]any{ + "transport": "file", + "filename": filepath.Clean(vmstatePath), + "offset": 0, + }, + }, + } +} + +func queryVMStatus(c *Conn) (vmStatusReply, error) { + raw, err := c.QueryWithTimeout("query-status", nil, 15*time.Second) + if err != nil { + return vmStatusReply{}, err + } + var st vmStatusReply + if err := json.Unmarshal(raw, &st); err != nil { + return vmStatusReply{}, fmt.Errorf("parse query-status: %w", err) + } + return st, nil +} + +func tryResumePaused(c *Conn) { + st, err := queryVMStatus(c) + if err != nil || st.Running { + return + } + // Only resume when QEMU is still in ordinary paused state (never postmigrate). + if st.Status == "paused" { + _ = c.ExecuteWithTimeout("cont", nil, 10*time.Second) + } +} + +func waitMigrateDone(ctx context.Context, c *Conn, onProgress func(MigrateProgress)) error { + deadline := time.Now().Add(migrateTotalTimeout) + for { + if err := ctx.Err(); err != nil { + return err + } + if time.Now().After(deadline) { + return errors.New("timed out waiting for migration to finish") + } + raw, err := c.QueryWithTimeout("query-migrate", nil, migrateCmdTimeout) + if err != nil { + return err + } + var info migrateInfo + if err := json.Unmarshal(raw, &info); err != nil { + return fmt.Errorf("parse query-migrate: %w", err) + } + prog := MigrateProgress{ + Status: info.Status, + TotalTimeMs: info.TotalTimeMs, + } + if info.RAM != nil { + prog.Transferred = info.RAM.Transferred + prog.Remaining = info.RAM.Remaining + prog.Total = info.RAM.Total + } + if onProgress != nil { + onProgress(prog) + } + switch info.Status { + case "completed": + return nil + case "failed", "cancelled": + desc := strings.TrimSpace(info.ErrorDesc) + if desc != "" { + return fmt.Errorf("migration %s: %s", info.Status, desc) + } + return fmt.Errorf("migration %s", info.Status) + } + sleep(ctx, migratePollInterval) + } +} + +func dialMigrateConnWithRetry(ctx context.Context, network, addr string, timeout time.Duration) (*Conn, error) { + deadline := time.Now().Add(timeout) + var lastErr error + for { + c, err := Dial(ctx, network, addr) + if err == nil { + return c, nil + } + lastErr = err + if ctx.Err() != nil || time.Now().After(deadline) { + return nil, lastErr + } + sleep(ctx, 100*time.Millisecond) + } +} + +func isConnClosedErr(err error) bool { + if err == nil { + return false + } + s := strings.ToLower(err.Error()) + return strings.Contains(s, "connection closed") || strings.Contains(s, "eof") || strings.Contains(s, "wsarecv") || strings.Contains(s, "broken pipe") +} diff --git a/internal/qmp/migrate_test.go b/internal/qmp/migrate_test.go new file mode 100644 index 0000000..0c863d2 --- /dev/null +++ b/internal/qmp/migrate_test.go @@ -0,0 +1,229 @@ +package qmp + +import ( + "bufio" + "context" + "encoding/json" + "net" + "strings" + "sync" + "testing" +) + +type mockQMPReq struct { + Execute string `json:"execute"` + Arguments json.RawMessage `json:"arguments"` +} + +func startMockQMP(t *testing.T, handle func(req mockQMPReq) (reply map[string]any, closeAfter bool)) (string, func() []mockQMPReq) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen mock QMP: %v", err) + } + t.Cleanup(func() { _ = ln.Close() }) + + var mu sync.Mutex + var recorded []mockQMPReq + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + go func(nc net.Conn) { + defer nc.Close() + _, _ = nc.Write([]byte(`{"QMP":{"version":{"qemu":{"major":9,"minor":2,"micro":0}},"capabilities":[]}}` + "\n")) + sc := bufio.NewScanner(nc) + for sc.Scan() { + var req mockQMPReq + if err := json.Unmarshal(sc.Bytes(), &req); err != nil { + return + } + if req.Execute == "qmp_capabilities" { + _, _ = nc.Write([]byte(`{"return":{}}` + "\n")) + continue + } + mu.Lock() + recorded = append(recorded, req) + mu.Unlock() + reply, closeAfter := handle(req) + if reply != nil { + b, _ := json.Marshal(reply) + _, _ = nc.Write(append(b, '\n')) + } + if closeAfter { + return + } + } + }(conn) + } + }() + return ln.Addr().String(), func() []mockQMPReq { + mu.Lock() + defer mu.Unlock() + return append([]mockQMPReq(nil), recorded...) + } +} + +func TestSuspendToFileHappyPath(t *testing.T) { + polls := 0 + addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "stop", "migrate-set-capabilities", "migrate-set-parameters", "migrate": + return map[string]any{"return": map[string]any{}}, false + case "query-status": + return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false + case "query-migrate": + polls++ + if polls == 1 { + return map[string]any{"return": map[string]any{ + "status": "active", + "ram": map[string]any{"transferred": 1024, "remaining": 1024, "total": 2048}, + }}, false + } + return map[string]any{"return": map[string]any{ + "status": "completed", + "total-time": 4500, + "ram": map[string]any{"transferred": 2048, "remaining": 0, "total": 2048}, + }}, false + case "quit": + return map[string]any{"return": map[string]any{}}, true + default: + t.Errorf("unexpected QMP command: %s", req.Execute) + return map[string]any{"return": map[string]any{}}, false + } + }) + + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatalf("Dial: %v", err) + } + defer c.Close() + + var progress []MigrateProgress + if err := suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, func(p MigrateProgress) { + progress = append(progress, p) + }); err != nil { + t.Fatalf("suspendToFileConn: %v", err) + } + if len(progress) != 2 || progress[1].Status != "completed" { + t.Fatalf("unexpected progress: %+v", progress) + } + got := cmds() + var names []string + for _, r := range got { + names = append(names, r.Execute) + } + want := "stop,query-status,migrate-set-capabilities,migrate-set-parameters,migrate,query-migrate,query-migrate,quit" + if strings.Join(names, ",") != want { + t.Fatalf("commands = %q, want %q", strings.Join(names, ","), want) + } +} + +func TestSuspendToFileFailureResumesPausedVM(t *testing.T) { + addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "stop", "migrate-set-capabilities", "migrate-set-parameters", "cont": + return map[string]any{"return": map[string]any{}}, false + case "query-status": + return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false + case "migrate": + return map[string]any{"error": map[string]any{"class": "GenericError", "desc": "disk full"}}, false + default: + return map[string]any{"return": map[string]any{}}, false + } + }) + + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatalf("Dial: %v", err) + } + defer c.Close() + + err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil) + if err == nil || !strings.Contains(err.Error(), "disk full") { + t.Fatalf("expected disk full error, got %v", err) + } + var sawCont bool + for _, r := range cmds() { + if r.Execute == "cont" { + sawCont = true + } + if r.Execute == "quit" { + t.Fatal("must not quit QEMU when migrate fails") + } + } + if !sawCont { + t.Fatal("expected cont rollback when migrate fails while paused") + } +} + +func TestResumeFromFileHappyPath(t *testing.T) { + addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "migrate-set-capabilities", "migrate-set-parameters", "migrate-incoming", "cont": + return map[string]any{"return": map[string]any{}}, false + case "query-migrate": + return map[string]any{"return": map[string]any{"status": "completed", "total-time": 1900}}, false + default: + t.Errorf("unexpected QMP command: %s", req.Execute) + return map[string]any{"return": map[string]any{}}, false + } + }) + + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatalf("Dial: %v", err) + } + defer c.Close() + + if err := resumeFromFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil); err != nil { + t.Fatalf("resumeFromFileConn: %v", err) + } + got := cmds() + var names []string + var sawExitOnErrorFalse bool + for _, r := range got { + names = append(names, r.Execute) + if r.Execute == "migrate-incoming" && strings.Contains(string(r.Arguments), `"exit-on-error":false`) { + sawExitOnErrorFalse = true + } + } + want := "migrate-set-capabilities,migrate-set-parameters,migrate-incoming,query-migrate,cont" + if strings.Join(names, ",") != want { + t.Fatalf("commands = %q, want %q", strings.Join(names, ","), want) + } + if !sawExitOnErrorFalse { + t.Fatal("expected migrate-incoming to pass exit-on-error:false") + } +} + +func TestResumeFromFileFailedDoesNotCont(t *testing.T) { + addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "migrate-set-capabilities", "migrate-set-parameters", "migrate-incoming": + return map[string]any{"return": map[string]any{}}, false + case "query-migrate": + return map[string]any{"return": map[string]any{"status": "failed", "error-desc": "corrupt RVGSNAP1 snapshot"}}, false + default: + return map[string]any{"return": map[string]any{}}, false + } + }) + + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatalf("Dial: %v", err) + } + defer c.Close() + + err = resumeFromFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil) + if err == nil || !strings.Contains(err.Error(), "corrupt RVGSNAP1 snapshot") { + t.Fatalf("expected corrupt snapshot error, got %v", err) + } + for _, r := range cmds() { + if r.Execute == "cont" { + t.Fatal("must not issue cont when restore failed") + } + } +} diff --git a/internal/runtime/kinds.go b/internal/runtime/kinds.go index 97eeeb7..cf09333 100644 --- a/internal/runtime/kinds.go +++ b/internal/runtime/kinds.go @@ -152,6 +152,7 @@ func (m Manifest) EffectiveCapabilities() []string { for _, c := range m.Capabilities { add(c) } + var hasWin32MappedRAM, hasIntelWHPXSuspend, hasVGPUSnapshotReplay bool for _, p := range m.Patches { low := strings.ToLower(p.Name) switch { @@ -169,8 +170,17 @@ func (m Manifest) EffectiveCapabilities() []string { } case strings.Contains(low, "display-fixed-mode"): add("display-fixed-mode") + case strings.Contains(low, "win32-mapped-ram-io"): + hasWin32MappedRAM = true + case strings.Contains(low, "intel-whpx-suspend"): + hasIntelWHPXSuspend = true + case strings.Contains(low, "reims-vgpu-snapshot-replay"): + hasVGPUSnapshotReplay = true } } + if hasWin32MappedRAM && hasIntelWHPXSuspend && hasVGPUSnapshotReplay { + add("vm-suspend") + } return out } diff --git a/internal/runtime/kinds_test.go b/internal/runtime/kinds_test.go index 9e5bffd..2f2422b 100644 --- a/internal/runtime/kinds_test.go +++ b/internal/runtime/kinds_test.go @@ -85,6 +85,41 @@ func TestKindRegistryAndCapabilities(t *testing.T) { t.Fatalf("%s: HasCapability(win32-unicode-input) = %v, want %v", tc.name, got, tc.want) } } + + // vm-suspend requires all three runtime pieces (Win32 mapped-ram I/O, Intel WHPX suspend, + // and vGPU snapshot replay) unless explicitly declared in Capabilities. + for _, tc := range []struct { + name string + m Manifest + want bool + }{ + { + name: "partial-suspend-patches", + m: Manifest{Patches: []Patch{ + {Name: "qemu-win32-mapped-ram-io.patch"}, + {Name: "qemu-intel-whpx-suspend.patch"}, + }}, + want: false, + }, + { + name: "all-suspend-patches", + m: Manifest{Patches: []Patch{ + {Name: "qemu-win32-mapped-ram-io.patch"}, + {Name: "qemu-intel-whpx-suspend.patch"}, + {Name: "reims-vgpu-snapshot-replay.patch"}, + }}, + want: true, + }, + { + name: "explicit-vm-suspend-capability", + m: Manifest{Capabilities: []string{"vm-suspend"}}, + want: true, + }, + } { + if got := tc.m.HasCapability("vm-suspend"); got != tc.want { + t.Fatalf("%s: HasCapability(vm-suspend) = %v, want %v", tc.name, got, tc.want) + } + } } func TestMultiKindCoexistenceAndCompatibility(t *testing.T) { diff --git a/internal/tray/tray.go b/internal/tray/tray.go index a13a046..4523320 100644 --- a/internal/tray/tray.go +++ b/internal/tray/tray.go @@ -25,9 +25,10 @@ func (v VMItem) title() string { // Snapshot holds the live state read each time the user opens the tray menu. type Snapshot struct { - Locale i18n.Locale - LocaleZh bool // legacy fallback when Locale is empty - VMs []VMItem + Locale i18n.Locale + LocaleZh bool // legacy fallback when Locale is empty + CanSuspend bool + VMs []VMItem } // Action is a per-VM command picked from the tray menu. @@ -43,6 +44,9 @@ const ( ActSharedFolder ActOpenInApp ActToggleFullscreen + ActSuspend + ActResume + ActDiscardSuspend ) // Callbacks wires tray actions back into the Wails application. Each runs @@ -72,6 +76,7 @@ const ( dotNone dotKind = iota dotRunning dotStopped + dotSuspended dotBusy dotBroken ) @@ -91,8 +96,11 @@ type menuEntry struct { type texts struct { show, newVM, quit string start, stop, forceStop, restart, showWindow, shot string + suspend, resume, discardSuspend string shared, openInApp string - running, stopped, starting, stopping, broken, unknown string + running, stopped, suspended string + starting, stopping, suspending, resuming string + broken, unknown string toggleFullscreen string } @@ -107,23 +115,29 @@ func menuTexts(snap Snapshot) texts { } } return texts{ - show: i18n.T(loc, "tray.menu.show"), - newVM: i18n.T(loc, "tray.menu.new_vm"), - quit: i18n.T(loc, "tray.menu.quit"), - start: i18n.T(loc, "tray.menu.start"), - stop: i18n.T(loc, "tray.menu.stop"), - forceStop: i18n.T(loc, "tray.menu.force_stop"), - restart: i18n.T(loc, "tray.menu.restart"), - showWindow: i18n.T(loc, "tray.menu.show_window"), - shot: i18n.T(loc, "tray.menu.screenshot"), - shared: i18n.T(loc, "tray.menu.shared_folder"), - openInApp: i18n.T(loc, "tray.menu.open_in_app"), - running: i18n.T(loc, "tray.state.running"), - stopped: i18n.T(loc, "tray.state.stopped"), - starting: i18n.T(loc, "tray.state.starting"), - stopping: i18n.T(loc, "tray.state.stopping"), - broken: i18n.T(loc, "tray.state.broken"), - unknown: i18n.T(loc, "tray.state.unknown"), + show: i18n.T(loc, "tray.menu.show"), + newVM: i18n.T(loc, "tray.menu.new_vm"), + quit: i18n.T(loc, "tray.menu.quit"), + start: i18n.T(loc, "tray.menu.start"), + stop: i18n.T(loc, "tray.menu.stop"), + forceStop: i18n.T(loc, "tray.menu.force_stop"), + restart: i18n.T(loc, "tray.menu.restart"), + suspend: i18n.T(loc, "tray.menu.suspend"), + resume: i18n.T(loc, "tray.menu.resume"), + discardSuspend: i18n.T(loc, "tray.menu.discard_suspend"), + showWindow: i18n.T(loc, "tray.menu.show_window"), + shot: i18n.T(loc, "tray.menu.screenshot"), + shared: i18n.T(loc, "tray.menu.shared_folder"), + openInApp: i18n.T(loc, "tray.menu.open_in_app"), + running: i18n.T(loc, "tray.state.running"), + stopped: i18n.T(loc, "tray.state.stopped"), + suspended: i18n.T(loc, "tray.state.suspended"), + starting: i18n.T(loc, "tray.state.starting"), + stopping: i18n.T(loc, "tray.state.stopping"), + suspending: i18n.T(loc, "tray.state.suspending"), + resuming: i18n.T(loc, "tray.state.resuming"), + broken: i18n.T(loc, "tray.state.broken"), + unknown: i18n.T(loc, "tray.state.unknown"), toggleFullscreen: i18n.T(loc, "tray.menu.toggle_fullscreen"), } @@ -138,7 +152,7 @@ func decodeVMCmd(id int) (int, Action, bool) { } off := id - cmdVMBase act := Action(off % vmSlot) - if act < ActStart || act > ActToggleFullscreen { + if act < ActStart || act > ActDiscardSuspend { return 0, 0, false } return off / vmSlot, act, true @@ -174,13 +188,34 @@ func buildMenu(snap Snapshot) []menuEntry { sub = []menuEntry{ show, cmd(ActToggleFullscreen, t.toggleFullscreen), cmd(ActScreenshot, t.shot), cmd(ActSharedFolder, t.shared), sep, + } + if snap.CanSuspend { + sub = append(sub, cmd(ActSuspend, t.suspend)) + } + sub = append(sub, cmd(ActRestart, t.restart), cmd(ActStop, t.stop), cmd(ActForceStop, t.forceStop), sep, cmd(ActOpenInApp, t.openInApp), + ) + case "suspended": + dot, state = dotSuspended, t.suspended + resume := cmd(ActResume, t.resume) + resume.Default = true + sub = []menuEntry{ + resume, cmd(ActDiscardSuspend, t.discardSuspend), sep, + cmd(ActSharedFolder, t.shared), sep, + cmd(ActOpenInApp, t.openInApp), } - case "starting", "stopping": - dot, state = dotBusy, t.starting - if vm.State == "stopping" { + case "starting", "stopping", "suspending", "resuming": + dot = dotBusy + switch vm.State { + case "stopping": state = t.stopping + case "suspending": + state = t.suspending + case "resuming": + state = t.resuming + default: + state = t.starting } sub = []menuEntry{cmd(ActForceStop, t.forceStop), sep, cmd(ActOpenInApp, t.openInApp)} case "broken": @@ -209,6 +244,8 @@ func dotPixels(size int, kind dotKind) []byte { switch kind { case dotRunning: r, g, b = 0x30, 0xD1, 0x58 + case dotSuspended: + r, g, b = 0xFF, 0x9F, 0x0A case dotBusy: r, g, b = 0xFF, 0x9F, 0x0A case dotBroken: @@ -219,12 +256,49 @@ func dotPixels(size int, kind dotKind) []byte { return px } c := float64(size) / 2 + const ss = 4 // 4×4 supersampling for smooth edges + if kind == dotSuspended { + halfH := float64(size) * 0.28 + barW := maxf(1.8, float64(size)*0.15) + gap := maxf(1.2, float64(size)*0.12) + for y := 0; y < size; y++ { + for x := 0; x < size; x++ { + hits := 0 + for sy := 0; sy < ss; sy++ { + for sx := 0; sx < ss; sx++ { + dx := float64(x) + (float64(sx)+0.5)/ss - c + dy := float64(y) + (float64(sy)+0.5)/ss - c + adx := dx + if adx < 0 { + adx = -adx + } + ady := dy + if ady < 0 { + ady = -ady + } + if ady <= halfH && adx >= gap/2 && adx <= gap/2+barW { + hits++ + } + } + } + if hits == 0 { + continue + } + a := hits * 255 / (ss * ss) + off := (y*size + x) * 4 + px[off+0] = uint8(int(b) * a / 255) + px[off+1] = uint8(int(g) * a / 255) + px[off+2] = uint8(int(r) * a / 255) + px[off+3] = uint8(a) + } + } + return px + } outer := float64(size) * 0.28 // dot diameter ≈ 56% of the check-mark cell inner := 0.0 if kind == dotStopped { inner = outer - maxf(1.4, float64(size)*0.09) } - const ss = 4 // 4×4 supersampling for smooth edges for y := 0; y < size; y++ { for x := 0; x < size; x++ { hits := 0 diff --git a/internal/tray/tray_test.go b/internal/tray/tray_test.go index 7365594..ced0237 100644 --- a/internal/tray/tray_test.go +++ b/internal/tray/tray_test.go @@ -18,10 +18,11 @@ func findEntry(entries []menuEntry, label string) *menuEntry { } func TestBuildMenuPerState(t *testing.T) { - menu := buildMenu(Snapshot{LocaleZh: true, VMs: []VMItem{ + menu := buildMenu(Snapshot{LocaleZh: true, CanSuspend: true, VMs: []VMItem{ {Name: "macos-tahoe", Label: "日常", State: "running"}, {Name: "macos-dev", State: "stopped"}, {Name: "macos-busy", State: "starting"}, + {Name: "macos-sleep", State: "suspended"}, }}) if !menu[0].Default || menu[0].ID != cmdShow { t.Fatalf("first item should be the default Show, got %+v", menu[0]) @@ -40,6 +41,15 @@ func TestBuildMenuPerState(t *testing.T) { if len(run.Sub) < 2 || run.Sub[1].ID != vmCmd(0, ActToggleFullscreen) || run.Sub[1].Label != "切换全屏" || run.Sub[1].Default { t.Fatalf("running VM should offer Toggle Fullscreen after Show Window: %+v", run.Sub) } + var hasSuspend bool + for _, e := range run.Sub { + if e.ID == vmCmd(0, ActSuspend) { + hasSuspend = true + } + } + if !hasSuspend { + t.Fatalf("running VM with CanSuspend should offer Suspend: %+v", run.Sub) + } stop := findEntry(menu, "macos-dev\t已停止") if stop == nil || stop.Dot != dotStopped || stop.Sub[0].ID != vmCmd(1, ActStart) || !stop.Sub[0].Default { @@ -55,18 +65,23 @@ func TestBuildMenuPerState(t *testing.T) { if busy == nil || busy.Dot != dotBusy || busy.Sub[0].ID != vmCmd(2, ActForceStop) { t.Fatalf("starting VM should only offer force stop first: %+v", busy) } + + susp := findEntry(menu, "macos-sleep\t已挂起") + if susp == nil || susp.Dot != dotSuspended || susp.Sub[0].ID != vmCmd(3, ActResume) || !susp.Sub[0].Default { + t.Fatalf("suspended VM should default to Resume: %+v", susp) + } } func TestDecodeVMCmdRoundTrip(t *testing.T) { for i := 0; i < maxTrayVMs; i++ { - for act := ActStart; act <= ActToggleFullscreen; act++ { + for act := ActStart; act <= ActDiscardSuspend; act++ { gi, ga, ok := decodeVMCmd(vmCmd(i, act)) if !ok || gi != i || ga != act { t.Fatalf("vmCmd(%d,%d) decoded to (%d,%d,%v)", i, act, gi, ga, ok) } } } - for _, id := range []int{cmdShow, cmdQuit, cmdNewVM, cmdVMBase, vmCmd(0, ActToggleFullscreen+1), cmdVMBase + maxTrayVMs*vmSlot} { + for _, id := range []int{cmdShow, cmdQuit, cmdNewVM, cmdVMBase, vmCmd(0, ActDiscardSuspend+1), cmdVMBase + maxTrayVMs*vmSlot} { if _, _, ok := decodeVMCmd(id); ok { t.Fatalf("id %d should not decode as a VM command", id) } @@ -84,9 +99,15 @@ func TestDotPixels(t *testing.T) { if alpha(ring, size/2, size/2) != 0 { t.Fatal("stopped dot should be a ring with a clear centre") } - for i := 0; i < len(run); i += 4 { - if run[i] > run[i+3] || run[i+1] > run[i+3] || run[i+2] > run[i+3] { - t.Fatal("pixels must be premultiplied (colour ≤ alpha)") + paused := dotPixels(size, dotSuspended) + if alpha(paused, 0, 0) != 0 || alpha(paused, size/2-2, size/2) == 0 || alpha(paused, size/2+2, size/2) == 0 { + t.Fatal("suspended mark should draw two visible vertical pause bars") + } + for _, buf := range [][]byte{run, paused} { + for i := 0; i < len(buf); i += 4 { + if buf[i] > buf[i+3] || buf[i+1] > buf[i+3] || buf[i+2] > buf[i+3] { + t.Fatal("pixels must be premultiplied (colour ≤ alpha)") + } } } } diff --git a/internal/vmstart/vmstart.go b/internal/vmstart/vmstart.go index 6f85da2..6250d60 100644 --- a/internal/vmstart/vmstart.go +++ b/internal/vmstart/vmstart.go @@ -147,6 +147,11 @@ func waitForCommitMemory( // language preset and the WHPX nested-virtualization fallback. cur is updated // to match what was written through `reims-ctl set`. func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) { + if stripped := reims.StripIncomingDeferArgs(cur.ExtraArgs); stripped != cur.ExtraArgs { + if err := p.setExtraArgs(ctx, name, stripped); err == nil { + cur.ExtraArgs = stripped + } + } p.syncOfflineHelper(ctx, name, cur) p.syncRecoveryBootPicker(ctx, name, cur) p.ReplayGuestLang(ctx, cur.Directory) diff --git a/locales/en-US/native.json b/locales/en-US/native.json index a39e657..0b80880 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -407,6 +407,9 @@ "tray.menu.new_vm": "&New Virtual Machine…", "tray.menu.quit": "&Quit Reims-Go", "tray.menu.start": "&Start", + "tray.menu.suspend": "Sus&pend", + "tray.menu.resume": "Res&ume", + "tray.menu.discard_suspend": "Discard Saved Stat&e", "tray.menu.stop": "Shut &Down", "tray.menu.force_stop": "&Force Shut Down", "tray.menu.restart": "&Restart", @@ -417,8 +420,11 @@ "tray.menu.open_in_app": "Show in &Reims-Go", "tray.state.running": "Running", "tray.state.stopped": "Stopped", + "tray.state.suspended": "Suspended", "tray.state.starting": "Starting…", "tray.state.stopping": "Shutting down…", + "tray.state.suspending": "Suspending…", + "tray.state.resuming": "Resuming…", "tray.state.broken": "Broken", "tray.state.unknown": "Unknown", "tray.notify.start_fail": { @@ -427,6 +433,24 @@ "name" ] }, + "tray.notify.suspend_fail": { + "message": "Couldn't suspend {name}", + "$params": [ + "name" + ] + }, + "tray.notify.resume_fail": { + "message": "Couldn't resume {name}", + "$params": [ + "name" + ] + }, + "tray.notify.discard_suspend_fail": { + "message": "Couldn't discard saved state for {name}", + "$params": [ + "name" + ] + }, "tray.notify.stop_fail": { "message": "Couldn't shut down {name}", "$params": [ @@ -820,6 +844,9 @@ "cli.usage.cmd_vm_compact": " vm compact Compact stopped .qcow2 disk to reclaim unused space", "cli.usage.cmd_vm_start": " vm start Start a VM in the Reims-Go window process (launched in the tray if needed),\n with clipboard and shared folders; with --data-root it starts in this process", "cli.usage.cmd_vm_stop": " vm stop|eject Stop / eject installer", + "cli.usage.cmd_vm_suspend": " vm suspend Suspend a running VM to disk for fast resume across restarts", + "cli.usage.cmd_vm_resume": " vm resume Resume a suspended VM from disk", + "cli.usage.cmd_vm_discard_suspend": " vm discard-suspend Discard a saved suspend state and return the VM to powered off", "cli.usage.cmd_vm_type": " vm type [text] Type text into a running VM as US-keyboard keys (stdin if no text)", "cli.usage.cmd_inst_list": " installer list List offline macOS installers Apple offers (needs network)", "cli.usage.cmd_inst_dl": " installer download Download an offline installer (26.7.1, tahoe, latest; Ctrl+C pauses, rerun resumes)", @@ -954,6 +981,51 @@ }, "core.start.warn.whpx_irqchip_applied": "Host rejects nested-virtualization property; enabled kernel-irqchip=off automatically", "validate.invalid_guest_lang": "Invalid guest language code (expected format like zh-Hans:0 or en-US:0)", + "validate.vm_suspended": "Resume or discard the VM's suspended state before changing its settings", + "err.suspend.unsupported_runtime": "The active portable runtime does not support VM suspend/resume; update to a runtime built with suspend support", + "err.suspend.busy": { + "message": "VM “{name}” is busy transitioning; try again in a moment", + "$params": [ + "name" + ] + }, + "err.suspend.not_running": { + "message": "VM “{name}” is not running and cannot be suspended", + "$params": [ + "name" + ] + }, + "err.suspend.disk_space": { + "message": "Not enough free disk space to save the suspend file (need about {need} GB, {avail} GB available)", + "$params": [ + "need", + "avail" + ] + }, + "err.suspend.not_found": { + "message": "No complete suspend state found for “{name}”", + "$params": [ + "name" + ] + }, + "err.suspend.incompatible": { + "message": "VM hardware or runtime differs from when it was suspended ({diffs}). Restore the previous configuration/runtime or discard the saved state", + "$params": [ + "diffs" + ] + }, + "err.suspend.discard_running": { + "message": "VM “{name}” is currently running; suspend state cannot be discarded", + "$params": [ + "name" + ] + }, + "err.suspend.action_blocked": { + "message": "VM “{name}” is suspended; resume and shut it down or discard its saved state before doing this", + "$params": [ + "name" + ] + }, "err.dataroot.busy_vms": "Stop all running virtual machines before switching the data folder", "err.dataroot.busy_tasks": "Wait for active download or creation tasks to finish before switching the data folder", "font.script.zh_hant": "Traditional Chinese (繁體中文)", diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index b3b8382..f5bfc2c 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -43,9 +43,28 @@ "fieldVMName": "VM name", "state_running": "Running", "state_stopped": "Stopped", + "state_suspended": "Suspended", "state_starting": "Starting", "state_stopping": "Stopping", + "state_suspending": "Suspending", + "state_resuming": "Resuming", "state_broken": "Error", + "suspend": "Suspend", + "resume": "Resume", + "discardSuspend": "Discard saved state", + "discardSuspendTitle": "Discard saved state for “{name}”?", + "discardSuspendDesc": "Removes the saved memory and device state and returns the VM to powered off. Any unsaved work inside macOS will be lost and can’t be undone.", + "discardSuspendConfirm": "Discard & Power Off", + "suspendedNoticeTitle": "Saved state ready", + "suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.", + "suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.", + "suspendedSettingsHint": "Resume or discard saved state before changing settings", + "toastSuspended": "{name} suspended", + "toastResumed": "{name} resumed", + "toastDiscardSuspend": "Discarded saved state for {name}", + "failSuspend": "Couldn’t suspend", + "failResume": "Couldn’t resume", + "failDiscardSuspend": "Couldn’t discard saved state", "pendingTitle": "Applies on next start", "restartToApply": "Restart to apply", "guideTitle": "Recovery mode", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index ca93bef..b36a181 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -407,6 +407,9 @@ "tray.menu.new_vm": "新建虚拟机(&N)…", "tray.menu.quit": "退出 Reims-Go(&Q)", "tray.menu.start": "启动(&S)", + "tray.menu.suspend": "挂起(&P)", + "tray.menu.resume": "恢复(&U)", + "tray.menu.discard_suspend": "放弃挂起状态(&X)", "tray.menu.stop": "关机(&D)", "tray.menu.force_stop": "强制关机(&F)", "tray.menu.restart": "重启(&R)", @@ -417,8 +420,11 @@ "tray.menu.open_in_app": "在 Reims-Go 中查看(&V)", "tray.state.running": "运行中", "tray.state.stopped": "已停止", + "tray.state.suspended": "已挂起", "tray.state.starting": "启动中…", "tray.state.stopping": "正在关机…", + "tray.state.suspending": "正在挂起…", + "tray.state.resuming": "正在恢复…", "tray.state.broken": "配置损坏", "tray.state.unknown": "未知", "tray.notify.start_fail": { @@ -427,6 +433,24 @@ "name" ] }, + "tray.notify.suspend_fail": { + "message": "无法挂起 {name}", + "$params": [ + "name" + ] + }, + "tray.notify.resume_fail": { + "message": "无法恢复 {name}", + "$params": [ + "name" + ] + }, + "tray.notify.discard_suspend_fail": { + "message": "无法放弃 {name} 的挂起状态", + "$params": [ + "name" + ] + }, "tray.notify.stop_fail": { "message": "无法关机 {name}", "$params": [ @@ -820,6 +844,9 @@ "cli.usage.cmd_vm_compact": " vm compact 停机回收 .qcow2 磁盘未用空间", "cli.usage.cmd_vm_start": " vm start 启动虚拟机:交给界面进程(未运行则在托盘拉起),带剪贴板与共享目录;指定 --data-root 时在本进程内启动", "cli.usage.cmd_vm_stop": " vm stop|eject 停止 / 弹出安装盘", + "cli.usage.cmd_vm_suspend": " vm suspend 挂起运行中的虚拟机至磁盘(退出后或重启宿主可秒级恢复)", + "cli.usage.cmd_vm_resume": " vm resume 从磁盘挂起状态恢复虚拟机", + "cli.usage.cmd_vm_discard_suspend": " vm discard-suspend 放弃已保存的挂起状态并回到关机状态", "cli.usage.cmd_vm_type": " vm type [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)", "cli.usage.cmd_inst_list": " installer list 列出 Apple 提供的离线安装包版本(需联网)", "cli.usage.cmd_inst_dl": " installer download <版本> 下载离线安装包(如 26.7.1、tahoe、latest;Ctrl+C 暂停,再次运行续传)", @@ -954,6 +981,51 @@ }, "core.start.warn.whpx_irqchip_applied": "宿主拒绝了嵌套虚拟化属性,已自动启用 kernel-irqchip=off 兼容参数", "validate.invalid_guest_lang": "客户机系统语言标识格式无效(如 zh-Hans:0、en-US:0)", + "validate.vm_suspended": "虚拟机当前处于挂起状态,请先恢复或放弃挂起状态后再修改配置", + "err.suspend.unsupported_runtime": "当前激活的便携运行时尚未包含虚拟机挂起/恢复支持,请更新至包含挂起补丁的运行时版本", + "err.suspend.busy": { + "message": "虚拟机「{name}」正在执行状态切换,请稍后再试", + "$params": [ + "name" + ] + }, + "err.suspend.not_running": { + "message": "虚拟机「{name}」未在运行,无法挂起", + "$params": [ + "name" + ] + }, + "err.suspend.disk_space": { + "message": "磁盘可用空间不足以保存挂起文件(需要约 {need} GB,当前可用 {avail} GB)", + "$params": [ + "need", + "avail" + ] + }, + "err.suspend.not_found": { + "message": "未找到「{name}」的完整挂起状态文件", + "$params": [ + "name" + ] + }, + "err.suspend.incompatible": { + "message": "虚拟机硬件或运行时版本与挂起时不一致({diffs})。请恢复原配置/运行时,或放弃挂起状态后重新启动", + "$params": [ + "diffs" + ] + }, + "err.suspend.discard_running": { + "message": "虚拟机「{name}」正在运行,无法放弃挂起状态", + "$params": [ + "name" + ] + }, + "err.suspend.action_blocked": { + "message": "虚拟机「{name}」当前处于挂起状态,请先恢复并关机,或放弃挂起状态后再执行此操作", + "$params": [ + "name" + ] + }, "err.dataroot.busy_vms": "仍有虚拟机正在运行,请先全部关机后再切换数据目录", "err.dataroot.busy_tasks": "仍有后台下载或创建任务进行中,请等待任务结束或取消后再切换数据目录", "font.script.zh_hant": "繁体中文(繁體中文)", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index c50d9cf..3a68042 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -43,9 +43,28 @@ "fieldVMName": "虚拟机名称", "state_running": "运行中", "state_stopped": "已停止", + "state_suspended": "已挂起", "state_starting": "启动中", "state_stopping": "停止中", + "state_suspending": "挂起中", + "state_resuming": "恢复中", "state_broken": "出错", + "suspend": "挂起", + "resume": "恢复", + "discardSuspend": "放弃挂起状态", + "discardSuspendTitle": "放弃「{name}」的挂起状态?", + "discardSuspendDesc": "将删除已保存的内存与设备状态并回到关机状态,macOS 中尚未保存的工作会丢失,且无法撤销。", + "discardSuspendConfirm": "放弃并关机", + "suspendedNoticeTitle": "已保存运行状态", + "suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", + "suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", + "suspendedSettingsHint": "请先恢复或放弃挂起状态后再修改配置", + "toastSuspended": "{name} 已挂起", + "toastResumed": "{name} 已恢复", + "toastDiscardSuspend": "已放弃 {name} 的挂起状态", + "failSuspend": "挂起失败", + "failResume": "恢复失败", + "failDiscardSuspend": "放弃挂起状态失败", "pendingTitle": "下次启动生效", "restartToApply": "重启以应用", "guideTitle": "恢复模式", From 552d6e4cada0822749577053343b88296f42f41f Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 08:06:43 +0800 Subject: [PATCH 05/10] fix(guesttools): confine sync to the current shared folders --- internal/guesttools/file_sync.go | 164 ++++++++++++------ internal/guesttools/file_sync.sh | 12 +- .../guesttools/file_sync_identity_other.go | 12 ++ .../guesttools/file_sync_identity_unix.go | 18 ++ .../guesttools/file_sync_identity_windows.go | 16 ++ internal/guesttools/file_sync_test.go | 59 ++++++- 6 files changed, 223 insertions(+), 58 deletions(-) create mode 100644 internal/guesttools/file_sync_identity_other.go create mode 100644 internal/guesttools/file_sync_identity_unix.go create mode 100644 internal/guesttools/file_sync_identity_windows.go diff --git a/internal/guesttools/file_sync.go b/internal/guesttools/file_sync.go index 76ba4d8..ad6733d 100644 --- a/internal/guesttools/file_sync.go +++ b/internal/guesttools/file_sync.go @@ -1,6 +1,7 @@ package guesttools import ( + "crypto/rand" "crypto/sha256" "errors" "fmt" @@ -8,6 +9,7 @@ import ( "io/fs" "net/http" "os" + "path" "path/filepath" "sort" "strconv" @@ -20,8 +22,38 @@ const ( syncDigestHeader = "X-Reims-File-SHA256" ) -func syncFileScope(token, root string) string { - return fmt.Sprintf("%x", sha256.Sum256([]byte(token+"\n"+root))) +func syncFileScope(token string, root *os.Root) (string, error) { + // A replacement directory at the same path must start fresh sync history. + dir, err := root.Open(".") + if err != nil { + return "", err + } + defer dir.Close() + id, err := sharedDirectoryID(dir) + if err != nil { + return "", err + } + return fmt.Sprintf("%x", sha256.Sum256([]byte(token+"\n"+root.Name()+"\n"+id))), nil +} + +func openSharedRoot(dir string) (*os.Root, error) { + info, err := os.Lstat(dir) + if err != nil { + return nil, err + } + if !info.IsDir() { + return nil, fs.ErrInvalid + } + root, err := os.OpenRoot(dir) + if err != nil { + return nil, err + } + opened, err := root.Stat(".") + if err != nil || !os.SameFile(info, opened) { + _ = root.Close() + return nil, errors.New("shared directory changed") + } + return root, nil } func syncFileTag(info fs.FileInfo) string { @@ -73,27 +105,38 @@ func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) { } return } - root, err := filepath.Abs(vm.sharedDir) + dir, err := filepath.Abs(vm.sharedDir) if err != nil { http.Error(w, "shared directory unavailable", http.StatusInternalServerError) return } if !versioned { - if err := os.MkdirAll(root, 0o755); err != nil { + if err := os.MkdirAll(dir, 0o755); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } + root, err := openSharedRoot(dir) + if err != nil { + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + return + } + defer root.Close() + var scope string + if versioned { + scope, err = syncFileScope(vm.token, root) + if err != nil { + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + return + } + } type entry struct { name string info fs.FileInfo } var files []entry - err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { - if p == root { - if versioned && err == nil && !d.IsDir() { - return fs.ErrInvalid - } + err = fs.WalkDir(root.FS(), ".", func(name string, d fs.DirEntry, err error) error { + if name == "." { return err } if err != nil { @@ -105,11 +148,6 @@ func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) { } return nil } - rel, err := filepath.Rel(root, p) - if err != nil { - return nil - } - name := filepath.ToSlash(rel) if strings.Count(name, "/")+1 > MaxSharedDepth { if d.IsDir() { return filepath.SkipDir @@ -134,7 +172,7 @@ func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) { http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) return } - w.Header().Set(syncScopeHeader, syncFileScope(vm.token, root)) + w.Header().Set(syncScopeHeader, scope) } sort.Slice(files, func(i, j int) bool { return files[i].name < files[j].name }) w.Header().Set("Content-Type", "text/tab-separated-values; charset=utf-8") @@ -165,23 +203,49 @@ func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) { return } scope := r.Header.Get(syncScopeHeader) - if scope != "" && (!validSyncFileName(rawName) || scope != syncFileScope(vm.token, dir)) { - http.Error(w, "shared directory or file path changed", http.StatusPreconditionFailed) - return - } + writing := r.Method == http.MethodPut || r.Method == http.MethodPost switch r.Method { case http.MethodHead, http.MethodDelete: if scope == "" { http.Error(w, "sync scope required", http.StatusPreconditionRequired) return } - fallthrough - case http.MethodGet: - s.readSharedFile(w, r, dir, name, scope != "") - case http.MethodPut, http.MethodPost: - s.writeSharedFile(w, r, filepath.Join(dir, filepath.FromSlash(name)), scope != "") + case http.MethodGet, http.MethodPut, http.MethodPost: default: http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + if scope == "" && writing { + if err := os.MkdirAll(dir, 0o755); err != nil { + http.Error(w, "shared directory unavailable", http.StatusInternalServerError) + return + } + } + root, err := openSharedRoot(dir) + if err != nil { + if scope == "" && !writing && errors.Is(err, fs.ErrNotExist) { + http.NotFound(w, r) + } else { + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + } + return + } + defer root.Close() + if scope != "" { + current, err := syncFileScope(vm.token, root) + if err != nil { + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + return + } + if !validSyncFileName(rawName) || scope != current { + http.Error(w, "shared directory or file path changed", http.StatusPreconditionFailed) + return + } + } + if writing { + s.writeSharedFile(w, r, root, name, scope != "") + } else { + s.readSharedFile(w, r, root, name, scope != "") } } @@ -214,7 +278,7 @@ func statSharedFile(root *os.Root, name string) (fs.FileInfo, error) { return info, err } -func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, dir, name string, versioned bool) { +func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, root *os.Root, name string, versioned bool) { deleting := r.Method == http.MethodDelete expectedDigest := r.Header.Get(syncDigestHeader) if deleting && (r.Header.Get("If-Match") == "" || expectedDigest == "") { @@ -222,19 +286,6 @@ func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, dir, nam return } - root, err := os.OpenRoot(dir) - if err != nil { - switch { - case versioned: - http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) - case errors.Is(err, fs.ErrNotExist): - http.NotFound(w, r) - default: - http.Error(w, "shared directory unavailable", http.StatusInternalServerError) - } - return - } - defer root.Close() info, err := statSharedFile(root, name) switch { case errors.Is(err, fs.ErrNotExist): @@ -315,18 +366,19 @@ func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, dir, nam } } -func (s *Server) writeSharedFile(w http.ResponseWriter, r *http.Request, full string, versioned bool) { - dir := filepath.Dir(full) - if err := os.MkdirAll(dir, 0o755); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) +func (s *Server) writeSharedFile(w http.ResponseWriter, r *http.Request, root *os.Root, name string, versioned bool) { + dir := path.Dir(name) + if err := root.MkdirAll(dir, 0o755); err != nil { + http.Error(w, "upload directory unavailable", http.StatusInternalServerError) return } - tmp, err := os.CreateTemp(dir, ".reims-upload-*") + tmpName := path.Join(dir, ".reims-upload-"+rand.Text()) + tmp, err := root.OpenFile(tmpName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) + http.Error(w, "upload file unavailable", http.StatusInternalServerError) return } - defer os.Remove(tmp.Name()) + defer root.Remove(tmpName) h := sha256.New() var dst io.Writer = tmp if versioned { @@ -344,30 +396,34 @@ func (s *Server) writeSharedFile(w http.ResponseWriter, r *http.Request, full st } if ts, err := strconv.ParseInt(r.URL.Query().Get("mtime"), 10, 64); err == nil && ts > 0 { t := time.Unix(ts, 0) - _ = os.Chtimes(tmp.Name(), t, t) + _ = root.Chtimes(tmpName, t, t) } s.fileMu.Lock() defer s.fileMu.Unlock() + info, err := statSharedFile(root, name) + if errors.Is(err, fs.ErrInvalid) { + http.Error(w, "path is not a regular file", http.StatusConflict) + return + } + if err != nil && !errors.Is(err, fs.ErrNotExist) { + http.Error(w, "file unavailable", http.StatusInternalServerError) + return + } var uploadedTag string if versioned { - info, err := os.Lstat(full) - if err != nil && !errors.Is(err, fs.ErrNotExist) { - http.Error(w, "file unavailable", http.StatusInternalServerError) - return - } if !matchSyncFile(r, info) { http.Error(w, "file changed", http.StatusPreconditionFailed) return } - uploaded, err := os.Stat(tmp.Name()) + uploaded, err := root.Stat(tmpName) if err != nil { http.Error(w, "uploaded file unavailable", http.StatusInternalServerError) return } uploadedTag = syncFileTag(uploaded) } - if err := os.Rename(tmp.Name(), full); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) + if err := root.Rename(tmpName, name); err != nil { + http.Error(w, "publish uploaded file failed", http.StatusInternalServerError) return } if versioned { diff --git a/internal/guesttools/file_sync.sh b/internal/guesttools/file_sync.sh index f6ecf65..58397ca 100644 --- a/internal/guesttools/file_sync.sh +++ b/internal/guesttools/file_sync.sh @@ -1,7 +1,7 @@ -# Keep confirmed pairs outside the share, scoped to the VM and host directory. +# Keep confirmed pairs scoped to the current shared directories on both sides. sync_files() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 - [ -d "$SHARE_SYNC" ] && [ ! -L "$SHARE_SYNC" ] || return 0 + sync_guest_root=$(sync_guest_root_id) || return 0 sync_remote="$TMP_DIR/sync-remote.tsv" sync_local="$TMP_DIR/sync-local.tsv" @@ -16,7 +16,7 @@ sync_files() { case "$sync_scope" in "") ;; *[!0-9a-f]*) return 0 ;; - *) sync_state="$APP_DIR/file-sync-$sync_scope.tsv" ;; + *) sync_state="$APP_DIR/file-sync-$sync_scope-$sync_guest_root.tsv" ;; esac sync_previous="$sync_state" [ -f "$sync_state" ] || sync_previous=/dev/null @@ -106,7 +106,13 @@ sync_header() { awk -v name="$1:" 'tolower($1) == tolower(name) { sub(/\r$/, "", $2); print $2; exit }' "$sync_headers" } +sync_guest_root_id() { + [ -d "$SHARE_SYNC" ] && [ ! -L "$SHARE_SYNC" ] && + stat -f '%d-%i-%B' "$SHARE_SYNC" 2>/dev/null +} + sync_guest_revision() { + [ "$(sync_guest_root_id)" = "$sync_guest_root" ] || return 1 sync_check=$1 while [ "$sync_check" != "$SHARE_SYNC" ]; do [ ! -L "$sync_check" ] || return 1 diff --git a/internal/guesttools/file_sync_identity_other.go b/internal/guesttools/file_sync_identity_other.go new file mode 100644 index 0000000..4c0ec4e --- /dev/null +++ b/internal/guesttools/file_sync_identity_other.go @@ -0,0 +1,12 @@ +//go:build !windows && !unix + +package guesttools + +import ( + "errors" + "os" +) + +func sharedDirectoryID(*os.File) (string, error) { + return "", errors.ErrUnsupported +} diff --git a/internal/guesttools/file_sync_identity_unix.go b/internal/guesttools/file_sync_identity_unix.go new file mode 100644 index 0000000..fa2d0b5 --- /dev/null +++ b/internal/guesttools/file_sync_identity_unix.go @@ -0,0 +1,18 @@ +//go:build unix + +package guesttools + +import ( + "fmt" + "os" + "syscall" +) + +func sharedDirectoryID(dir *os.File) (string, error) { + info, err := dir.Stat() + if err != nil { + return "", err + } + stat := info.Sys().(*syscall.Stat_t) + return fmt.Sprintf("%x:%x", stat.Dev, stat.Ino), nil +} diff --git a/internal/guesttools/file_sync_identity_windows.go b/internal/guesttools/file_sync_identity_windows.go new file mode 100644 index 0000000..5545b15 --- /dev/null +++ b/internal/guesttools/file_sync_identity_windows.go @@ -0,0 +1,16 @@ +package guesttools + +import ( + "fmt" + "os" + "syscall" +) + +func sharedDirectoryID(dir *os.File) (string, error) { + var info syscall.ByHandleFileInformation + if err := syscall.GetFileInformationByHandle(syscall.Handle(dir.Fd()), &info); err != nil { + return "", err + } + return fmt.Sprintf("%x:%08x%08x:%x", info.VolumeSerialNumber, info.FileIndexHigh, + info.FileIndexLow, info.CreationTime.Nanoseconds()), nil +} diff --git a/internal/guesttools/file_sync_test.go b/internal/guesttools/file_sync_test.go index 99b79e1..b6ba2a8 100644 --- a/internal/guesttools/file_sync_test.go +++ b/internal/guesttools/file_sync_test.go @@ -3,11 +3,15 @@ package guesttools import ( "context" "crypto/sha256" + "errors" "fmt" "io" "net/http" + "net/http/httptest" "os" + "os/exec" "path/filepath" + "runtime" "strings" "testing" ) @@ -93,9 +97,62 @@ func TestFileSyncRequiresConfirmedRevisionAndContent(t *testing.T) { conditions.Set(syncDigestHeader, fmt.Sprintf("%x", sha256.Sum256([]byte(got)))) request(http.MethodDelete, fileURL, "", conditions, http.StatusNoContent) request(http.MethodHead, fileURL, "", conditions, http.StatusNotFound) - if err := os.Remove(shared); err != nil { + if err := os.Rename(shared, filepath.Join(root, "old-share")); err != nil { t.Fatal(err) } request(http.MethodGet, "/v1/files?sync=1", "", conditions, http.StatusServiceUnavailable) request(http.MethodHead, fileURL, "", conditions, http.StatusServiceUnavailable) + srv.RegisterVM(cfg) + list, _ = request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK) + newScope := list.Get(syncScopeHeader) + if newScope == "" || newScope == scope { + t.Fatalf("recreated share must have a new scope: %q", newScope) + } + request(http.MethodHead, fileURL, "", conditions, http.StatusPreconditionFailed) + request(http.MethodPut, fileURL, "stale upload", conditions, http.StatusPreconditionFailed) + conditions = http.Header{syncScopeHeader: {newScope}} + request(http.MethodHead, fileURL, "", conditions, http.StatusNotFound) + request(http.MethodPut, "/v1/file?path=nested/file.txt", contents, conditions, http.StatusOK) + _, got = request(http.MethodGet, "/v1/file?path=nested/file.txt", "", conditions, http.StatusOK) + if got != contents { + t.Fatalf("nested file contents: %q", got) + } +} + +func TestFileSyncConfinesUploadToShare(t *testing.T) { + shared, outside := t.TempDir(), t.TempDir() + link := filepath.Join(shared, "linked") + if err := os.Symlink(outside, link); err != nil { + if runtime.GOOS != "windows" { + t.Skipf("directory symlink unavailable: %v", err) + } + output, err := exec.Command("cmd.exe", "/c", "mklink", "/J", link, outside).CombinedOutput() + if err != nil { + t.Fatalf("create test junction: %v: %s", err, output) + } + } + srv := NewTransportServer(&memClipboard{}) + token := strings.Repeat("a", 64) + srv.RegisterVM(VMConfig{VMName: "sync-test", Token: token, SharedDir: shared}) + list := httptest.NewRequest(http.MethodGet, "/v1/files?sync=1", nil) + list.Header.Set("Authorization", "Bearer "+token) + listed := httptest.NewRecorder() + srv.handleListFiles(listed, list) + scope := listed.Header().Get(syncScopeHeader) + if listed.Code != http.StatusOK || scope == "" { + t.Fatalf("listing failed: %d: %s", listed.Code, listed.Body) + } + for _, version := range []string{"", scope} { + req := httptest.NewRequest(http.MethodPut, "/v1/file?path=linked/upload.txt", strings.NewReader("test upload")) + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set(syncScopeHeader, version) + res := httptest.NewRecorder() + srv.handleFile(res, req) + if res.Code < http.StatusBadRequest { + t.Fatalf("upload through an out-of-share link succeeded: %d", res.Code) + } + if _, err := os.Stat(filepath.Join(outside, "upload.txt")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("upload escaped share: %v", err) + } + } } From 790a42912e68d7c66583fd27a4edadad24031c47 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 08:22:58 +0800 Subject: [PATCH 06/10] fix(installer): expand home paths from reims-ctl show --- internal/config/config.go | 16 ++++++++++++++ internal/driver/reims/reims.go | 5 +++-- internal/driver/reims/reims_test.go | 21 +++++++++++++++++++ internal/installguide/progress.go | 6 +++++- internal/installguide/session_windows_test.go | 15 +++++++++++++ 5 files changed, 60 insertions(+), 3 deletions(-) diff --git a/internal/config/config.go b/internal/config/config.go index 347ea29..fbaae72 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "runtime" + "strings" "github.com/Nwflower/reims-go/internal/i18n" ) @@ -53,6 +54,21 @@ func DefaultDataRoot() string { return filepath.Join(home, "reims-go-data") } +// ExpandHomePath resolves a leading ~ for the current user. +func ExpandHomePath(path string) string { + if path != "~" && !strings.HasPrefix(path, "~/") && !strings.HasPrefix(path, `~\`) { + return path + } + home, err := os.UserHomeDir() + if err != nil { + return path + } + if path == "~" { + return home + } + return filepath.Join(home, path[2:]) +} + // CurrentDataRoot is the data folder in effect: REIMS_GO_DATA_ROOT, else the // folder chosen at first launch (LocationPath), else DefaultDataRoot. func CurrentDataRoot() string { diff --git a/internal/driver/reims/reims.go b/internal/driver/reims/reims.go index 17dcc5d..4785cac 100644 --- a/internal/driver/reims/reims.go +++ b/internal/driver/reims/reims.go @@ -548,6 +548,7 @@ func parseDisplayCount(v string) int { } // ParseShow parses the text output of `reims-ctl show ` while redacting MAC addresses. +// Paths under the user's home are abbreviated upstream (3731afd, cli.rs:1117,1189-1192). func ParseShow(name, text string) VMDetail { d := VMDetail{ Name: name, @@ -577,7 +578,7 @@ func ParseShow(name, text string) VMDetail { case "kind": d.Kind = v case "directory": - d.Directory = v + d.Directory = config.ExpandHomePath(v) case "cpus": d.CPUs, _ = strconv.Atoi(v) case "memory": @@ -622,7 +623,7 @@ func ParseShow(name, text string) VMDetail { d.HasOpenCore = v != "" case "installer": d.HasInstaller = v != "" && !strings.EqualFold(v, "none") - d.InstallerPath = v + d.InstallerPath = config.ExpandHomePath(v) case "cpu model": d.CPUModel = v case "audio": diff --git a/internal/driver/reims/reims_test.go b/internal/driver/reims/reims_test.go index 3f11d31..e399834 100644 --- a/internal/driver/reims/reims_test.go +++ b/internal/driver/reims/reims_test.go @@ -1,6 +1,7 @@ package reims import ( + "path/filepath" "reflect" "strings" "testing" @@ -63,6 +64,26 @@ func TestParseShowRedactsMACAndDetectsInstaller(t *testing.T) { } } +func TestParseShowExpandsHomeRelativePaths(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + vm := filepath.Join("Documents", "MacEmu", "data", "reims-ctl", "vms", "macos-15") + image := filepath.Join("Documents", "MacEmu", "data", "reims-ctl", "installers", "macOS-Sequoia-15.7-offline-installer.img") + tilde := "~" + string(filepath.Separator) + d := ParseShow("macos-15", " directory "+tilde+vm+"\n installer "+tilde+image+"\n") + if want := filepath.Join(home, vm); d.Directory != want { + t.Errorf("VM directory = %q, want %q", d.Directory, want) + } + if want := filepath.Join(home, image); !d.HasInstaller || d.InstallerPath != want { + t.Errorf("installer attached = %t, path = %q, want attached at %q", d.HasInstaller, d.InstallerPath, want) + } + d = ParseShow("macos-15", " directory ~\n installer none\n") + if d.Directory != home || d.HasInstaller { + t.Errorf("VM directory = %q, want %q, installer attached = %t, want false", d.Directory, home, d.HasInstaller) + } +} + func TestOfflineCreateTurnsNetworkOff(t *testing.T) { args, err := BuildCreateArgs(CreateOpts{Name: "m1", MacOS: "26.7.3", Offline: true}) if err != nil { diff --git a/internal/installguide/progress.go b/internal/installguide/progress.go index f03ff4e..ca44f8f 100644 --- a/internal/installguide/progress.go +++ b/internal/installguide/progress.go @@ -6,6 +6,8 @@ import ( "os" "path/filepath" "strings" + + "github.com/Nwflower/reims-go/internal/config" ) const progressFile = ".reims-go-install-guide.json" @@ -55,7 +57,9 @@ func (g *Guide) Resume(dir, media string, recovery bool) bool { return recovery } if recovery { - if cp.Kind == g.Kind && strings.EqualFold(cp.Media, media) && cp.Step.recoveryStep(g.Kind) { + // Older checkpoints may contain the abbreviated installer path from show. + sameMedia := strings.EqualFold(config.ExpandHomePath(cp.Media), media) + if cp.Kind == g.Kind && sameMedia && cp.Step.recoveryStep(g.Kind) { g.initial = cp.Step } return true diff --git a/internal/installguide/session_windows_test.go b/internal/installguide/session_windows_test.go index 4e9edef..b6040ff 100644 --- a/internal/installguide/session_windows_test.go +++ b/internal/installguide/session_windows_test.go @@ -2,6 +2,7 @@ package installguide import ( "errors" + "path/filepath" "testing" "time" ) @@ -148,3 +149,17 @@ func TestGuideKeepsMediaAndVMProgressSeparate(t *testing.T) { t.Fatal("clone inherited source disk preparation") } } + +func TestGuideResumesWithExpandedInstallerPath(t *testing.T) { + home := t.TempDir() + t.Setenv("USERPROFILE", home) + dir := t.TempDir() + g := Guide{Name: "macos-15", Kind: Offline, PID: 33} + g.Resume(dir, `~\macOS-15-offline-installer.img`, true) + if err := g.save(command, 0); err != nil { + t.Fatal(err) + } + if !g.Resume(dir, filepath.Join(home, "macOS-15-offline-installer.img"), true) || g.initial != command { + t.Fatalf("guide resumed at %s, want %s", g.initial, command) + } +} From 4cc4b6c02c4a256e80fdf62ac8d66f70dadadad7 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 08:37:30 +0800 Subject: [PATCH 07/10] fix: make Intel VM suspend and resume transactional --- internal/app/app.go | 47 ++- internal/app/suspend_flow.go | 287 ++++-------------- internal/app/suspend_flow_test.go | 17 +- internal/cli/cli.go | 20 +- internal/cli/start.go | 10 +- internal/cli/suspend.go | 154 ++-------- internal/driver/reims/suspend.go | 65 ++-- internal/driver/reims/suspend_lock_other.go | 26 ++ internal/driver/reims/suspend_lock_windows.go | 39 +++ internal/driver/reims/suspend_test.go | 15 +- internal/driver/reims/suspend_transaction.go | 185 +++++++++++ .../driver/reims/suspend_transaction_test.go | 89 ++++++ internal/qmp/media.go | 59 ++++ internal/qmp/migrate.go | 24 +- internal/qmp/migrate_test.go | 79 ++++- internal/vmstart/suspend.go | 198 ++++++++++++ 16 files changed, 892 insertions(+), 422 deletions(-) create mode 100644 internal/driver/reims/suspend_lock_other.go create mode 100644 internal/driver/reims/suspend_lock_windows.go create mode 100644 internal/driver/reims/suspend_transaction.go create mode 100644 internal/driver/reims/suspend_transaction_test.go create mode 100644 internal/qmp/media.go create mode 100644 internal/vmstart/suspend.go diff --git a/internal/app/app.go b/internal/app/app.go index 310bfdd..048e2eb 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -220,7 +220,7 @@ func (a *App) shutdown(ctx context.Context) { // stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`. // Start, stop and delete call wakePoll so their result shows up at once. const ( - pollBusy = 2 * time.Second + pollBusy = 2 * time.Second // Exits are caught at once by watchExits and GUI actions call wakePoll, so // the steady tick only has to notice VMs started or removed elsewhere (CLI). pollSteady = 10 * time.Second @@ -682,13 +682,17 @@ func (a *App) GetVMDetail(name string) (reims.VMDetail, error) { if err != nil { return d, err } - d.RecoveryMode = isRecoveryModeActive(d) - a.populateGuestToolsDetail(&d) - a.populateGuestLangDetail(&d) - a.populateSuspendDetail(&d) + a.populateVMDetail(&d) return d, nil } +func (a *App) populateVMDetail(d *reims.VMDetail) { + d.RecoveryMode = isRecoveryModeActive(*d) + a.populateGuestToolsDetail(d) + a.populateGuestLangDetail(d) + a.populateSuspendDetail(d) +} + func (a *App) SetLocale(raw string) error { a.mu.Lock() a.cfg.Locale = i18n.ParsePreference(raw) @@ -1091,10 +1095,16 @@ func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) { } func (a *App) ApplyVMSettings(opts reims.SetOpts) error { - cur, err := a.GetVMDetail(opts.Name) + c, err := a.client() if err != nil { return err } + cur, release, err := vmstart.LockVM(a.baseCtx(), c, opts.Name) + if err != nil { + return err + } + defer release() + a.populateVMDetail(&cur) a.mu.Lock() root := a.cfg.DataRoot loc := a.cfg.Locale @@ -1102,10 +1112,6 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error { if issues := reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc); len(issues) > 0 { return fmt.Errorf("%s", issues[0].Message) } - c, err := a.client() - if err != nil { - return err - } w := vmstart.LineWriter(func(line string) { a.emitLog(opts.Name, line) }) if reims.HasCtlSetChanges(opts) { if err := c.Set(context.Background(), opts, w, w); err != nil { @@ -1351,9 +1357,13 @@ func (a *App) StartVM(name string) error { return err } c := prep.Client - curDetail, _ := c.Show(context.Background(), name) + curDetail, release, err := vmstart.LockVM(a.baseCtx(), c, name) + if err != nil { + return err + } + defer release() if curDetail.State == "stopped" && reims.HasSuspendState(curDetail.Directory) { - return a.ResumeVM(name) + return a.resumeLocked(prep, curDetail) } a.mu.Lock() root := a.cfg.DataRoot @@ -1502,6 +1512,11 @@ func (a *App) StopVM(name string, force bool) error { if err != nil { return err } + _, release, err := vmstart.LockVM(a.baseCtx(), c, name) + if err != nil { + return err + } + defer release() a.cancelRebootWatcher(name) stopVMMonitor(name) a.mu.Lock() @@ -1570,6 +1585,14 @@ func (a *App) EjectInstaller(name string) error { if err != nil { return err } + d, release, err := vmstart.LockVM(a.baseCtx(), c, name) + if err != nil { + return err + } + defer release() + if a.isVMSuspended(d) { + return i18n.NewCodedError(a.locale(), "E_VM_EJECT_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil) + } w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) a.emitLog(name, "Ejecting installer from "+name+"...") if err := c.Eject(context.Background(), name, w, w); err != nil { diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index dc9ee8c..90abdc0 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -1,11 +1,7 @@ package app import ( - "context" "fmt" - "io" - "os" - "strings" "time" "github.com/Nwflower/reims-go/internal/driver/reims" @@ -18,8 +14,6 @@ import ( wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) -// enrichVMListStates overlays state="suspended" onto stopped VMs that have a -// complete suspend snapshot (suspend.vmstate + suspend.json) in their folder. func enrichVMListStates(vms []reims.VMListItem) { for i := range vms { if vms[i].State == "stopped" && reims.HasSuspendState(vms[i].Dir) { @@ -29,10 +23,7 @@ func enrichVMListStates(vms []reims.VMListItem) { } func (a *App) populateSuspendDetail(d *reims.VMDetail) { - if d == nil || d.Directory == "" { - return - } - if d.State == "stopped" && reims.HasSuspendState(d.Directory) { + if d != nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) { d.State = "suspended" if info, err := reims.ReadSuspendInfo(d.Directory); err == nil { d.SuspendInfo = info @@ -44,73 +35,33 @@ func (a *App) isVMSuspended(d reims.VMDetail) bool { return d.State == "suspended" || (d.State == "stopped" && reims.HasSuspendState(d.Directory)) } -// SuspendVM pauses a running Intel VM, saves its RAM, CPU, device, and vGPU -// state to suspend.vmstate, and cleanly exits QEMU so the host can close -// Reims-Go or reboot Windows and later resume instantaneously. +// SuspendVM saves a VM's running state and closes its QEMU process. func (a *App) SuspendVM(name string) error { - loc := a.locale() prep, err := a.prep(name) if err != nil { return err } - if !prep.Runtime.Manifest.HasCapability("vm-suspend") { - return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) - } - - a.mu.Lock() - if tr := a.transitions[name]; tr != "" { - a.mu.Unlock() - return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) - } - a.mu.Unlock() - ctx := a.baseCtx() - c := prep.Client - d, err := c.Show(ctx, name) + d, release, err := vmstart.LockVM(ctx, prep.Client, name) if err != nil { return err } - if !a.isVMRunning(ctx, c, name, d) { - return i18n.NewCodedError(loc, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": name}, nil) + defer release() + end, err := a.beginSuspendTransition(name, "suspending") + if err != nil { + return err } - if d.Directory == "" { - return fmt.Errorf("VM %s has no directory", name) - } - if memGB, ok := reims.ParseSizeGB(d.Memory); ok { - dirRep := host.Inspect(d.Directory) - needGB := memGB + 1.0 - if dirRep.FreeDiskGB > 0 && dirRep.FreeDiskGB < needGB { - return i18n.NewCodedError(loc, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{ - "need": fmt.Sprintf("%.1f", needGB), - "avail": fmt.Sprintf("%.1f", dirRep.FreeDiskGB), - }, nil) - } - } - - oldPID := a.cachedVMPID(name) - a.cancelRebootWatcher(name) - stopVMMonitor(name) + defer end() a.mu.Lock() - mgr := a.pluginMgr - gt := a.guestTools - a.transitions[name] = "suspending" + mgr, gt := a.pluginMgr, a.guestTools a.mu.Unlock() + event := plugin.VMEventPayload{VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS} if mgr != nil { - mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, plugin.VMEventPayload{ - VMName: name, - VMDir: d.Directory, - DriverID: builtin.IDDriverReimsMacOS, - }) + mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, event) } - a.emitStateChanged() - - tmpPath := reims.SuspendStatePath(d.Directory) + ".tmp" - _ = os.Remove(tmpPath) - - a.emitLog(name, fmt.Sprintf("Suspending %s to disk (%s)...", name, reims.SuspendStateFileName)) lastPct := -1 - err = qmp.SuspendToFile(ctx, d.Directory, tmpPath, func(p qmp.MigrateProgress) { + info, err := prep.SuspendSnapshot(ctx, d, func(p qmp.MigrateProgress) { if p.Total > 0 { pct := int(p.Transferred * 100 / p.Total) if pct >= lastPct+25 || p.Status == "completed" { @@ -120,221 +71,84 @@ func (a *App) SuspendVM(name string) error { } }) if err != nil { - _ = os.Remove(tmpPath) - a.clearTransition(name) a.emitLog(name, "Suspend error: "+err.Error()) - a.wakePoll() - a.emitStateChanged() return err } - - a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout) - - st, statErr := os.Stat(tmpPath) - if statErr != nil || st.Size() <= 0 { - _ = os.Remove(tmpPath) - a.clearTransition(name) - a.wakePoll() - a.emitStateChanged() - if statErr != nil { - return fmt.Errorf("suspend snapshot missing after save: %w", statErr) - } - return fmt.Errorf("suspend snapshot is empty after save") - } - - finalPath := reims.SuspendStatePath(d.Directory) - _ = os.Remove(finalPath) - if err := os.Rename(tmpPath, finalPath); err != nil { - _ = os.Remove(tmpPath) - a.clearTransition(name) - a.wakePoll() - a.emitStateChanged() - return fmt.Errorf("finalize suspend snapshot: %w", err) - } - - info := reims.BuildSuspendInfo(d, prep.Runtime, st.Size()) - if err := reims.WriteSuspendInfo(d.Directory, info); err != nil { - _ = reims.RemoveSuspendState(d.Directory) - a.clearTransition(name) - a.wakePoll() - a.emitStateChanged() - return fmt.Errorf("write suspend metadata: %w", err) - } - + a.cancelRebootWatcher(name) + stopVMMonitor(name) if gt != nil { gt.UnregisterVM(name) } if mgr != nil { - mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{ - VMName: name, - VMDir: d.Directory, - DriverID: builtin.IDDriverReimsMacOS, - }) + mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, event) } - a.clearTransition(name) - a.emitLog(name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", name, float64(st.Size())/float64(1<<30))) - a.wakePoll() - a.emitStateChanged() + a.emitLog(name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", name, float64(info.VMStateSize)/float64(1<<30))) return nil } -// ResumeVM launches a fresh QEMU process in `-incoming defer` mode (via -// `reims-ctl set --extra-args`), restores the VM's RAM, CPU, devices, and vGPU -// state from suspend.vmstate, and resumes guest execution. On any restore -// failure, suspend.vmstate and suspend.json are preserved so the user can retry. +// ResumeVM restores a suspended VM with its original media and devices. func (a *App) ResumeVM(name string) error { - loc := a.locale() prep, err := a.prep(name) if err != nil { return err } - if !prep.Runtime.Manifest.HasCapability("vm-suspend") { - return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + d, release, err := vmstart.LockVM(a.baseCtx(), prep.Client, name) + if err != nil { + return err } + defer release() + return a.resumeLocked(prep, d) +} + +func (a *App) resumeLocked(prep *vmstart.Prep, d reims.VMDetail) error { + name := d.Name + end, err := a.beginSuspendTransition(name, "resuming") + if err != nil { + return err + } + defer end() a.mu.Lock() - root := a.cfg.DataRoot - if tr := a.transitions[name]; tr != "" { - a.mu.Unlock() - return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) - } - mgr := a.pluginMgr + root, mgr := a.cfg.DataRoot, a.pluginMgr a.mu.Unlock() - - ctx := a.baseCtx() - c := prep.Client - d, err := c.Show(ctx, name) - if err != nil { - return err - } - if a.isVMRunning(ctx, c, name, d) { - return fmt.Errorf("%s", i18n.T(loc, "vm.already_running", name)) - } - if !reims.HasSuspendState(d.Directory) { - return i18n.NewCodedError(loc, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": name}, nil) - } - meta, err := reims.ReadSuspendInfo(d.Directory) - if err != nil { - return fmt.Errorf("read suspend metadata: %w", err) - } - if diffs := reims.ValidateSuspendCompatibility(*meta, d, prep.Runtime); len(diffs) > 0 { - return i18n.NewCodedError(loc, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{ - "diffs": strings.Join(diffs, ", "), - }, nil) - } - rep := host.Inspect(root) - if err := prep.CheckWHPX(rep); err != nil { - a.emitLog(name, "Resume refused: "+err.Error()) - return err - } - if err := prep.CheckMemory(d.Memory, rep); err != nil { - a.emitLog(name, "Resume refused: "+err.Error()) - return err - } - a.cancelRebootWatcher(name) - if prep.Runtime.Manifest.HasCapability("win32-unicode-input") { - if env := a.inputBridgeEnv(name, d.Directory); len(env) > 0 { - c.Env = append(c.Env, env...) - } + prep.Client.Env = append(prep.Client.Env, a.inputBridgeEnv(name, d.Directory)...) } if prep.Runtime.Manifest.HasCapability("display-fixed-mode") && host.ShouldUseFixedGuestMode(d.Borderless, d.Resolution, rep.PrimaryDisplay) { - c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1") + prep.Client.Env = append(prep.Client.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1") } - origExtraArgs := reims.StripIncomingDeferArgs(d.ExtraArgs) - incomingArgs := reims.MergeIncomingDeferArgs(origExtraArgs) - if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &incomingArgs}, io.Discard, io.Discard); err != nil { - return fmt.Errorf("prepare incoming extra-args: %w", err) - } - restoredExtra := false - restoreExtra := func() { - if restoredExtra { - return - } - restoredExtra = true - if rerr := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &origExtraArgs}, io.Discard, io.Discard); rerr != nil { - a.emitLog(name, "Warning: could not restore extra-args after incoming launch: "+rerr.Error()) - } - } - defer restoreExtra() - - a.mu.Lock() - a.transitions[name] = "resuming" - a.mu.Unlock() - a.emitStateChanged() - startAt := time.Now() - w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) - a.emitLog(name, fmt.Sprintf("Resuming %s from %s...", name, reims.SuspendStateFileName)) - if err := c.Start(ctx, name, w, w); err != nil { - restoreExtra() - a.clearTransition(name) - a.emitLog(name, "Resume launch error: "+err.Error()) - a.wakePoll() - a.emitStateChanged() + out := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) + if err := prep.ResumeSnapshot(a.baseCtx(), d, rep, out, out); err != nil { + a.emitLog(name, "Resume error: "+err.Error()) return err } - restoreExtra() - - if err := qmp.ResumeFromFile(ctx, d.Directory, reims.SuspendStatePath(d.Directory), nil); err != nil { - a.emitLog(name, "Resume snapshot error (suspend state preserved for retry): "+err.Error()) - // Clean up the paused incoming QEMU process without touching suspend.vmstate. - if qerr := qmp.QuitVM(context.Background(), d.Directory); qerr != nil { - _ = c.StopForce(context.Background(), name, io.Discard, io.Discard) - } - a.clearTransition(name) - a.wakePoll() - a.emitStateChanged() - return err - } - - if rerr := reims.RemoveSuspendState(d.Directory); rerr != nil { - a.emitLog(name, "Warning: could not remove consumed suspend files: "+rerr.Error()) - } - if mgr != nil { mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{ - VMName: name, - VMDir: d.Directory, - DriverID: builtin.IDDriverReimsMacOS, + VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS, }) } a.startVMMonitor(name, d, startAt) - a.clearTransition(name) a.emitLog(name, fmt.Sprintf("Resumed %s in %.1fs", name, time.Since(startAt).Seconds())) - a.wakePoll() - a.emitStateChanged() return nil } -// DiscardSuspend deletes a suspended VM's saved RAM/device snapshot so the VM -// returns to the ordinary stopped state (equivalent to powering off). +// DiscardSuspend deletes a stopped VM's saved execution state. func (a *App) DiscardSuspend(name string) error { - loc := a.locale() c, err := a.client() if err != nil { return err } - a.mu.Lock() - if tr := a.transitions[name]; tr != "" { - a.mu.Unlock() - return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) - } - a.mu.Unlock() - - ctx := a.baseCtx() - d, err := c.Show(ctx, name) + d, release, err := vmstart.LockVM(a.baseCtx(), c, name) if err != nil { return err } - if a.isVMRunning(ctx, c, name, d) { - return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": name}, nil) - } - if err := reims.RemoveSuspendState(d.Directory); err != nil { + defer release() + if err := vmstart.DiscardSnapshot(a.locale(), d); err != nil { return err } a.emitLog(name, "Discarded suspend state for "+name) @@ -343,10 +157,23 @@ func (a *App) DiscardSuspend(name string) error { return nil } -func (a *App) clearTransition(name string) { +func (a *App) beginSuspendTransition(name, state string) (func(), error) { a.mu.Lock() - delete(a.transitions, name) + loc := a.cfg.Locale + if a.transitions[name] != "" { + a.mu.Unlock() + return nil, i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) + } + a.transitions[name] = state a.mu.Unlock() + a.emitStateChanged() + return func() { + a.mu.Lock() + delete(a.transitions, name) + a.mu.Unlock() + a.wakePoll() + a.emitStateChanged() + }, nil } func (a *App) emitStateChanged() { diff --git a/internal/app/suspend_flow_test.go b/internal/app/suspend_flow_test.go index 686c25f..a102794 100644 --- a/internal/app/suspend_flow_test.go +++ b/internal/app/suspend_flow_test.go @@ -2,6 +2,7 @@ package app import ( "os" + "path/filepath" "testing" "github.com/Nwflower/reims-go/internal/driver/reims" @@ -12,14 +13,20 @@ func TestEnrichVMListStatesAndPopulateSuspendDetail(t *testing.T) { suspendedDir := t.TempDir() stoppedDir := t.TempDir() - if err := os.WriteFile(reims.SuspendStatePath(suspendedDir), []byte("0123456789"), 0o644); err != nil { + if err := os.WriteFile(reims.SuspendStatePath(suspendedDir)+".tmp", []byte("0123456789"), 0o600); err != nil { t.Fatal(err) } - if err := reims.WriteSuspendInfo(suspendedDir, reims.BuildSuspendInfo( - reims.VMDetail{Name: "mac-a", CPUs: 8, Memory: "8G", Graphics: "reims-vgpu"}, + media := filepath.Join(suspendedDir, "disk.qcow2") + for _, path := range []string{media, filepath.Join(suspendedDir, "vm.toml")} { + if err := os.WriteFile(path, []byte("state"), 0o600); err != nil { + t.Fatal(err) + } + } + if _, err := reims.SealSuspend( + reims.VMDetail{Name: "mac-a", Directory: suspendedDir, CPUs: 8, Memory: "8G", Graphics: "reims-vgpu"}, rt.Installed{Commit: "3731afd"}, - 10, - )); err != nil { + []string{media}, + ); err != nil { t.Fatal(err) } diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 5242e24..27e6c07 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -529,7 +529,12 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e AudioBackend: strings.TrimSpace(*audioBackend), GuestLang: strings.TrimSpace(*guestLang), } - if d, serr := client.Show(ctx, setOpts.Name); serr == nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) { + d, release, err := vmstart.LockVM(ctx, client, setOpts.Name) + if err != nil { + return err + } + defer release() + if d.State == "stopped" && reims.HasSuspendState(d.Directory) { return i18n.NewCodedError(loc, "E_SET_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": setOpts.Name}, nil) } if reims.HasCtlSetChanges(setOpts) { @@ -556,6 +561,11 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if len(args) < 2 { return fmt.Errorf("usage: reims-go vm stop ") } + _, release, err := vmstart.LockVM(ctx, client, args[1]) + if err != nil { + return err + } + defer release() return client.Stop(ctx, args[1], os.Stdout, os.Stderr) case "suspend": if len(args) < 2 { @@ -576,6 +586,14 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if len(args) < 2 { return fmt.Errorf("usage: reims-go vm eject ") } + d, release, err := vmstart.LockVM(ctx, client, args[1]) + if err != nil { + return err + } + defer release() + if d.State == "stopped" && reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_VM_EJECT_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil) + } return client.Eject(ctx, args[1], os.Stdout, os.Stderr) case "type": // Paste as keystrokes: the text argument, else stdin. diff --git a/internal/cli/start.go b/internal/cli/start.go index b6b215c..3cbf862 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -50,8 +50,16 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s if viaWindow && windowHandoffWorks { return startInWindow(ctx, cfg, name) } + d, release, err := vmstart.LockVM(ctx, prep.Client, name) + if err != nil { + return err + } + defer release() + if d.State == "running" { + return fmt.Errorf("%s", i18n.T(cfg.Locale, "vm.already_running", name)) + } if d.State == "stopped" && reims.HasSuspendState(d.Directory) { - return resumeVM(ctx, cfg, prep, name) + return resumeLocked(ctx, cfg, prep, d, rep) } // Honour the core plugin's WHPX setting, as the window does. diff --git a/internal/cli/suspend.go b/internal/cli/suspend.go index e120f83..08ced68 100644 --- a/internal/cli/suspend.go +++ b/internal/cli/suspend.go @@ -3,175 +3,67 @@ package cli import ( "context" "fmt" - "io" "os" - "strings" "time" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/host" - "github.com/Nwflower/reims-go/internal/i18n" - "github.com/Nwflower/reims-go/internal/qmp" "github.com/Nwflower/reims-go/internal/vmstart" ) -func suspendVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { - loc := cfg.Locale - if !prep.Runtime.Manifest.HasCapability("vm-suspend") { - return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) - } - d, err := prep.Client.Show(ctx, name) +func suspendVM(ctx context.Context, _ *config.Config, prep *vmstart.Prep, name string) error { + d, release, err := vmstart.LockVM(ctx, prep.Client, name) if err != nil { return err } - if d.State != "running" { - return i18n.NewCodedError(loc, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": name}, nil) - } - if memGB, ok := reims.ParseSizeGB(d.Memory); ok { - dirRep := host.Inspect(d.Directory) - needGB := memGB + 1.0 - if dirRep.FreeDiskGB > 0 && dirRep.FreeDiskGB < needGB { - return i18n.NewCodedError(loc, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{ - "need": fmt.Sprintf("%.1f", needGB), - "avail": fmt.Sprintf("%.1f", dirRep.FreeDiskGB), - }, nil) - } - } - var oldPID int - if vms, lerr := prep.Client.List(ctx); lerr == nil { - for _, vm := range vms { - if vm.Name == name && vm.PID != nil && *vm.PID > 0 { - oldPID = *vm.PID - break - } - } - } + defer release() - tmpPath := reims.SuspendStatePath(d.Directory) + ".tmp" - _ = os.Remove(tmpPath) fmt.Fprintf(os.Stderr, "Suspending %s to %s...\n", name, reims.SuspendStateFileName) - if err := qmp.SuspendToFile(ctx, d.Directory, tmpPath, nil); err != nil { - _ = os.Remove(tmpPath) + info, err := prep.SuspendSnapshot(ctx, d, nil) + if err != nil { return err } - if oldPID > 0 { - waitCtx, cancel := context.WithTimeout(ctx, 12*time.Second) - _ = host.WaitProcessExit(waitCtx, uint32(oldPID), "qemu-system-x86_64.exe") - cancel() - } - st, err := os.Stat(tmpPath) - if err != nil || st.Size() <= 0 { - _ = os.Remove(tmpPath) - if err != nil { - return err - } - return fmt.Errorf("suspend snapshot is empty after save") - } - finalPath := reims.SuspendStatePath(d.Directory) - _ = os.Remove(finalPath) - if err := os.Rename(tmpPath, finalPath); err != nil { - _ = os.Remove(tmpPath) - return err - } - if err := reims.WriteSuspendInfo(d.Directory, reims.BuildSuspendInfo(d, prep.Runtime, st.Size())); err != nil { - _ = reims.RemoveSuspendState(d.Directory) - return err - } - fmt.Printf("Suspended %s (%.2f GiB saved)\n", name, float64(st.Size())/float64(1<<30)) + fmt.Printf("Suspended %s (%.2f GiB saved)\n", name, float64(info.VMStateSize)/float64(1<<30)) return nil } func resumeVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { - loc := cfg.Locale - if !prep.Runtime.Manifest.HasCapability("vm-suspend") { - return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) - } - rep := host.Inspect(cfg.DataRoot) - d, err := prep.Client.Show(ctx, name) + d, release, err := vmstart.LockVM(ctx, prep.Client, name) if err != nil { return err } - if d.State == "running" { - return fmt.Errorf("%s", i18n.T(loc, "vm.already_running", name)) - } - if !reims.HasSuspendState(d.Directory) { - return i18n.NewCodedError(loc, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": name}, nil) - } - meta, err := reims.ReadSuspendInfo(d.Directory) - if err != nil { - return err - } - if diffs := reims.ValidateSuspendCompatibility(*meta, d, prep.Runtime); len(diffs) > 0 { - return i18n.NewCodedError(loc, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{ - "diffs": strings.Join(diffs, ", "), - }, nil) - } - if err := prep.CheckWHPX(rep); err != nil { - return err - } - if err := prep.CheckMemory(d.Memory, rep); err != nil { - return err - } + defer release() + return resumeLocked(ctx, cfg, prep, d, host.Inspect(cfg.DataRoot)) +} - origExtraArgs := reims.StripIncomingDeferArgs(d.ExtraArgs) - incomingArgs := reims.MergeIncomingDeferArgs(origExtraArgs) - if err := prep.Client.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &incomingArgs}, io.Discard, io.Discard); err != nil { - return err - } - restored := false - restoreExtra := func() { - if restored { - return - } - restored = true - _ = prep.Client.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &origExtraArgs}, io.Discard, io.Discard) - } - defer restoreExtra() - - fmt.Fprintf(os.Stderr, "Resuming %s from %s...\n", name, reims.SuspendStateFileName) +func resumeLocked(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, d reims.VMDetail, rep host.Report) error { + fmt.Fprintf(os.Stderr, "Resuming %s from %s...\n", d.Name, reims.SuspendStateFileName) startAt := time.Now() - if err := prep.Client.Start(ctx, name, os.Stdout, os.Stderr); err != nil { - restoreExtra() + if err := prep.ResumeSnapshot(ctx, d, rep, os.Stdout, os.Stderr); err != nil { return err } - restoreExtra() - - if err := qmp.ResumeFromFile(ctx, d.Directory, reims.SuspendStatePath(d.Directory), nil); err != nil { - if qerr := qmp.QuitVM(context.Background(), d.Directory); qerr != nil { - _ = prep.Client.StopForce(context.Background(), name, io.Discard, io.Discard) - } - return err - } - _ = reims.RemoveSuspendState(d.Directory) - - if vms, lerr := prep.Client.List(ctx); lerr == nil { + if vms, err := prep.Client.List(ctx); err == nil { for _, vm := range vms { - if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - vmDir := vm.Dir - if vmDir == "" { - vmDir = d.Directory - } - if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, vmDir, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" { - fmt.Fprintln(os.Stderr, line) - } + if vm.Name != d.Name || vm.State != "running" || vm.PID == nil || *vm.PID <= 0 { + continue + } + if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, d.Directory, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" { + fmt.Fprintln(os.Stderr, line) } } } - fmt.Printf("Resumed %s in %.1fs\n", name, time.Since(startAt).Seconds()) + fmt.Printf("Resumed %s in %.1fs\n", d.Name, time.Since(startAt).Seconds()) return nil } func discardSuspendVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { - loc := cfg.Locale - d, err := prep.Client.Show(ctx, name) + d, release, err := vmstart.LockVM(ctx, prep.Client, name) if err != nil { return err } - if d.State == "running" { - return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": name}, nil) - } - if err := reims.RemoveSuspendState(d.Directory); err != nil { + defer release() + if err := vmstart.DiscardSnapshot(cfg.Locale, d); err != nil { return err } fmt.Printf("Discarded suspend state for %s\n", name) diff --git a/internal/driver/reims/suspend.go b/internal/driver/reims/suspend.go index b4035d4..202565f 100644 --- a/internal/driver/reims/suspend.go +++ b/internal/driver/reims/suspend.go @@ -18,7 +18,7 @@ const ( // create suspend.vmstate so incompatible resumes are caught before launch. SuspendMetaFileName = "suspend.json" // SuspendSchemaVersion is the current metadata schema version. - SuspendSchemaVersion = 1 + SuspendSchemaVersion = 2 ) // SuspendInfo describes a VM's saved suspend-to-disk state inside its VM folder. @@ -56,24 +56,46 @@ func SuspendMetaPath(vmDir string) string { // HasSuspendState reports whether vmDir contains a complete suspend snapshot // (both a non-empty suspend.vmstate and its suspend.json metadata). func HasSuspendState(vmDir string) bool { + state, _ := suspendFiles(vmDir) + return state != "" +} + +func suspendFiles(vmDir string) (state, meta string) { if strings.TrimSpace(vmDir) == "" { - return false + return "", "" } - st, err := os.Stat(SuspendStatePath(vmDir)) - if err != nil || st.IsDir() || st.Size() <= 0 { - return false + state, meta = SuspendStatePath(vmDir), SuspendMetaPath(vmDir) + nonEmpty := func(path string) bool { + st, err := os.Stat(path) + return err == nil && st.Mode().IsRegular() && st.Size() > 0 } - mst, err := os.Stat(SuspendMetaPath(vmDir)) - if err != nil || mst.IsDir() || mst.Size() <= 0 { - return false + if nonEmpty(meta) { + if nonEmpty(state) { + return state, meta + } + return "", "" } - return true + // A staged record is written only after the full state file was + // synced. Preserve that pair if either of the publication steps fails. + if nonEmpty(meta + ".tmp") { + if nonEmpty(state) { + return state, meta + ".tmp" + } + if nonEmpty(state + ".tmp") { + return state + ".tmp", meta + ".tmp" + } + } + return "", "" } // ReadSuspendInfo reads suspend.json from vmDir and refreshes VMStateSize from // the actual suspend.vmstate file on disk. func ReadSuspendInfo(vmDir string) (*SuspendInfo, error) { - b, err := os.ReadFile(SuspendMetaPath(vmDir)) + state, meta := suspendFiles(vmDir) + if state == "" { + return nil, os.ErrNotExist + } + b, err := os.ReadFile(meta) if err != nil { return nil, err } @@ -81,33 +103,12 @@ func ReadSuspendInfo(vmDir string) (*SuspendInfo, error) { if err := json.Unmarshal(b, &info); err != nil { return nil, fmt.Errorf("parse %s: %w", SuspendMetaFileName, err) } - if st, err := os.Stat(SuspendStatePath(vmDir)); err == nil && !st.IsDir() { + if st, err := os.Stat(state); err == nil { info.VMStateSize = st.Size() } return &info, nil } -// WriteSuspendInfo atomically writes suspend.json inside vmDir. -func WriteSuspendInfo(vmDir string, info SuspendInfo) error { - if info.SchemaVersion == 0 { - info.SchemaVersion = SuspendSchemaVersion - } - if info.CreatedAt == "" { - info.CreatedAt = time.Now().UTC().Format(time.RFC3339) - } - info.ExtraArgs = StripIncomingDeferArgs(info.ExtraArgs) - b, err := json.MarshalIndent(info, "", " ") - if err != nil { - return err - } - b = append(b, '\n') - tmp := SuspendMetaPath(vmDir) + ".tmp" - if err := os.WriteFile(tmp, b, 0o644); err != nil { - return err - } - return os.Rename(tmp, SuspendMetaPath(vmDir)) -} - // BuildSuspendInfo snapshots a VM's hardware and runtime fingerprint for suspend.json. func BuildSuspendInfo(d VMDetail, active rt.Installed, vmstateSize int64) SuspendInfo { return SuspendInfo{ diff --git a/internal/driver/reims/suspend_lock_other.go b/internal/driver/reims/suspend_lock_other.go new file mode 100644 index 0000000..06f45df --- /dev/null +++ b/internal/driver/reims/suspend_lock_other.go @@ -0,0 +1,26 @@ +//go:build !windows + +package reims + +import ( + "errors" + "fmt" + "os" + "syscall" +) + +func lockVMFile(f *os.File) error { + err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) + if errors.Is(err, syscall.EWOULDBLOCK) { + return ErrVMOperationBusy + } + return err +} + +func mediaFileID(path string, info os.FileInfo) (uint64, uint64, error) { + st, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return 0, 0, fmt.Errorf("file identity unavailable for %s", path) + } + return uint64(st.Dev), uint64(st.Ino), nil +} diff --git a/internal/driver/reims/suspend_lock_windows.go b/internal/driver/reims/suspend_lock_windows.go new file mode 100644 index 0000000..251f78a --- /dev/null +++ b/internal/driver/reims/suspend_lock_windows.go @@ -0,0 +1,39 @@ +//go:build windows + +package reims + +import ( + "errors" + "os" + + "golang.org/x/sys/windows" +) + +func lockVMFile(f *os.File) error { + err := windows.LockFileEx(windows.Handle(f.Fd()), + windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, + 0, 1, 0, new(windows.Overlapped)) + if errors.Is(err, windows.ERROR_LOCK_VIOLATION) || errors.Is(err, windows.ERROR_IO_PENDING) { + return ErrVMOperationBusy + } + return err +} + +func mediaFileID(path string, _ os.FileInfo) (uint64, uint64, error) { + name, err := windows.UTF16PtrFromString(path) + if err != nil { + return 0, 0, err + } + handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, + windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, + windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0) + if err != nil { + return 0, 0, err + } + defer windows.CloseHandle(handle) + var info windows.ByHandleFileInformation + if err := windows.GetFileInformationByHandle(handle, &info); err != nil { + return 0, 0, err + } + return uint64(info.VolumeSerialNumber), uint64(info.FileIndexHigh)<<32 | uint64(info.FileIndexLow), nil +} diff --git a/internal/driver/reims/suspend_test.go b/internal/driver/reims/suspend_test.go index 4401ca6..b285d49 100644 --- a/internal/driver/reims/suspend_test.go +++ b/internal/driver/reims/suspend_test.go @@ -2,6 +2,7 @@ package reims import ( "os" + "path/filepath" "strings" "testing" @@ -17,7 +18,7 @@ func TestSuspendStateLifecycle(t *testing.T) { } // Only vmstate without meta -> incomplete. - if err := os.WriteFile(SuspendStatePath(dir), []byte("vmstate-bytes"), 0o644); err != nil { + if err := os.WriteFile(SuspendStatePath(dir)+".tmp", []byte("vmstate-bytes"), 0o644); err != nil { t.Fatal(err) } if HasSuspendState(dir) { @@ -32,6 +33,7 @@ func TestSuspendStateLifecycle(t *testing.T) { } detail := VMDetail{ Name: "tahoe", + Directory: dir, CPUs: 8, Memory: "8G", Graphics: "reims-vgpu", @@ -42,9 +44,14 @@ func TestSuspendStateLifecycle(t *testing.T) { Network: true, ExtraArgs: "-machine kernel-irqchip=on -incoming defer", } - info := BuildSuspendInfo(detail, active, 13) - if err := WriteSuspendInfo(dir, info); err != nil { - t.Fatalf("WriteSuspendInfo: %v", err) + media := filepath.Join(dir, "disk.qcow2") + for _, path := range []string{media, filepath.Join(dir, "vm.toml")} { + if err := os.WriteFile(path, []byte("state"), 0o600); err != nil { + t.Fatal(err) + } + } + if _, err := SealSuspend(detail, active, []string{media}); err != nil { + t.Fatalf("SealSuspend: %v", err) } if !HasSuspendState(dir) { t.Fatal("expected HasSuspendState=true after writing both files") diff --git a/internal/driver/reims/suspend_transaction.go b/internal/driver/reims/suspend_transaction.go new file mode 100644 index 0000000..63d914a --- /dev/null +++ b/internal/driver/reims/suspend_transaction.go @@ -0,0 +1,185 @@ +package reims + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +var ErrVMOperationBusy = errors.New("another operation holds the VM lock") + +// LockVMOperation serializes GUI and CLI operations on the same VM directory. +// The lock file stays in place so contenders always lock the same inode. +func LockVMOperation(vmDir string) (func(), error) { + if strings.TrimSpace(vmDir) == "" { + return nil, fmt.Errorf("VM directory is required") + } + f, err := os.OpenFile(filepath.Join(vmDir, ".reims-go-vm-operation.lock"), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return nil, err + } + if err := lockVMFile(f); err != nil { + _ = f.Close() + return nil, err + } + return func() { _ = f.Close() }, nil +} + +type mediaFingerprint struct { + Path string `json:"path"` + Volume uint64 `json:"volume"` + FileID uint64 `json:"file_id"` + Size int64 `json:"size"` + MTime int64 `json:"mtime_ns"` +} + +type suspendRecord struct { + SuspendInfo + ConfigHash string `json:"config_sha256"` + Media []mediaFingerprint `json:"media"` +} + +func fingerprintMedia(path string) (mediaFingerprint, error) { + st, err := os.Stat(path) + if err != nil { + return mediaFingerprint{}, err + } + if !st.Mode().IsRegular() { + return mediaFingerprint{}, fmt.Errorf("attached path is not a regular file: %s", path) + } + volume, id, err := mediaFileID(path, st) + if err != nil { + return mediaFingerprint{}, err + } + return mediaFingerprint{Path: path, Volume: volume, FileID: id, Size: st.Size(), MTime: st.ModTime().UnixNano()}, nil +} + +func suspendConfigHash(vmDir string) (string, error) { + data, err := os.ReadFile(filepath.Join(vmDir, "vm.toml")) + if err != nil { + return "", err + } + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]), nil +} + +// SealSuspend publishes a completed migration as the only usable snapshot. +// Every failure leaves the migration file available and the sender still alive. +func SealSuspend(d VMDetail, active rt.Installed, paths []string) (SuspendInfo, error) { + if len(paths) == 0 { + return SuspendInfo{}, fmt.Errorf("cannot seal a snapshot without attached media") + } + dir := d.Directory + tmp := SuspendStatePath(dir) + ".tmp" + state, err := os.OpenFile(tmp, os.O_RDWR, 0) + if err != nil { + return SuspendInfo{}, err + } + st, err := state.Stat() + if err == nil && (!st.Mode().IsRegular() || st.Size() == 0) { + err = fmt.Errorf("suspend snapshot is empty or is not a regular file") + } + if err == nil { + err = state.Sync() + } + if err := errors.Join(err, state.Close()); err != nil { + return SuspendInfo{}, err + } + configHash, err := suspendConfigHash(dir) + if err != nil { + return SuspendInfo{}, err + } + record := suspendRecord{ + SuspendInfo: BuildSuspendInfo(d, active, st.Size()), + ConfigHash: configHash, + Media: make([]mediaFingerprint, 0, len(paths)), + } + for _, path := range paths { + item, err := fingerprintMedia(path) + if err != nil { + return SuspendInfo{}, fmt.Errorf("fingerprint attached media: %w", err) + } + record.Media = append(record.Media, item) + } + metaTmp := SuspendMetaPath(dir) + ".tmp" + if err := stageSuspendRecord(metaTmp, record); err != nil { + return SuspendInfo{}, err + } + if err := os.Rename(tmp, SuspendStatePath(dir)); err != nil { + return SuspendInfo{}, err + } + if err := os.Rename(metaTmp, SuspendMetaPath(dir)); err != nil { + return SuspendInfo{}, err + } + return record.SuspendInfo, nil +} + +func stageSuspendRecord(path string, record suspendRecord) error { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + return err + } + enc := json.NewEncoder(f) + enc.SetIndent("", " ") + err = enc.Encode(record) + if err == nil { + err = f.Sync() + } + return errors.Join(err, f.Close()) +} + +// ValidateSuspendFiles checks contents and identities before starting incoming +// QEMU and returns the expected media paths for validation before load. +func ValidateSuspendFiles(d VMDetail, active rt.Installed) (string, []string, error) { + state, meta := suspendFiles(d.Directory) + if state == "" { + return "", nil, os.ErrNotExist + } + data, err := os.ReadFile(meta) + if err != nil { + return "", nil, err + } + var record suspendRecord + if err := json.Unmarshal(data, &record); err != nil { + return "", nil, err + } + if record.SchemaVersion != SuspendSchemaVersion || record.ConfigHash == "" || len(record.Media) == 0 { + return "", nil, fmt.Errorf("snapshot has no supported VM and media fingerprint") + } + st, err := os.Stat(state) + if err != nil { + return "", nil, err + } + if !st.Mode().IsRegular() || st.Size() <= 0 || st.Size() != record.VMStateSize { + return "", nil, fmt.Errorf("snapshot file size changed") + } + diffs := ValidateSuspendCompatibility(record.SuspendInfo, d, active) + configHash, err := suspendConfigHash(d.Directory) + if err != nil { + return "", nil, err + } + if configHash != record.ConfigHash { + diffs = append(diffs, "VM configuration changed") + } + paths := make([]string, 0, len(record.Media)) + for _, expected := range record.Media { + current, err := fingerprintMedia(expected.Path) + if err != nil || current != expected { + diffs = append(diffs, fmt.Sprintf("attached media changed (%s)", expected.Path)) + } + paths = append(paths, expected.Path) + } + if len(diffs) > 0 { + return "", nil, errors.New(strings.Join(diffs, ", ")) + } + slices.Sort(paths) + return state, paths, nil +} diff --git a/internal/driver/reims/suspend_transaction_test.go b/internal/driver/reims/suspend_transaction_test.go new file mode 100644 index 0000000..7c9a845 --- /dev/null +++ b/internal/driver/reims/suspend_transaction_test.go @@ -0,0 +1,89 @@ +package reims + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +func TestVMOperationLockExcludesAnotherHandle(t *testing.T) { + dir := t.TempDir() + release, err := LockVMOperation(dir) + if err != nil { + t.Fatal(err) + } + if _, err = LockVMOperation(dir); !errors.Is(err, ErrVMOperationBusy) { + t.Fatalf("second lock = %v, want busy", err) + } + release() + release, err = LockVMOperation(dir) + if err != nil { + t.Fatal(err) + } + release() +} + +func TestSuspendTransactionRejectsChangedBackingFile(t *testing.T) { + dir := t.TempDir() + top := filepath.Join(dir, "disk.qcow2") + base := filepath.Join(dir, "base.qcow2") + for _, path := range []string{top, base, filepath.Join(dir, "vm.toml"), SuspendStatePath(dir) + ".tmp"} { + if err := os.WriteFile(path, []byte("test data"), 0o600); err != nil { + t.Fatal(err) + } + } + d := VMDetail{Name: "test", Directory: dir, CPUs: 2, Memory: "4G"} + runtime := rt.Installed{Commit: "test"} + if _, err := SealSuspend(d, runtime, []string{top, base}); err != nil { + t.Fatal(err) + } + if _, _, err := ValidateSuspendFiles(d, runtime); err != nil { + t.Fatal(err) + } + st, err := os.Stat(base) + if err != nil { + t.Fatal(err) + } + if err := os.Rename(base, base+".old"); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(base, []byte("test data"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(base, st.ModTime(), st.ModTime()); err != nil { + t.Fatal(err) + } + if _, _, err := ValidateSuspendFiles(d, runtime); err == nil || !strings.Contains(err.Error(), "base.qcow2") { + t.Fatalf("replaced backing file not detected: %v", err) + } +} + +func TestSuspendTransactionKeepsSealedFilesWhenPublicationFails(t *testing.T) { + dir := t.TempDir() + media := filepath.Join(dir, "OVMF_VARS.fd") + stagedState := SuspendStatePath(dir) + ".tmp" + for _, path := range []string{media, filepath.Join(dir, "vm.toml"), stagedState} { + if err := os.WriteFile(path, []byte("test state"), 0o600); err != nil { + t.Fatal(err) + } + } + if err := os.Mkdir(SuspendMetaPath(dir), 0o700); err != nil { + t.Fatal(err) + } + d := VMDetail{Name: "test", Directory: dir} + runtime := rt.Installed{Commit: "test"} + if _, err := SealSuspend(d, runtime, []string{media}); err == nil { + t.Fatal("expected publication to fail") + } + if !HasSuspendState(dir) { + t.Fatal("published state and staged metadata should be recoverable") + } + state, paths, err := ValidateSuspendFiles(d, runtime) + if err != nil || state != SuspendStatePath(dir) || len(paths) != 1 || paths[0] != media { + t.Fatalf("recoverable snapshot = %q, %v, %v", state, paths, err) + } +} diff --git a/internal/qmp/media.go b/internal/qmp/media.go new file mode 100644 index 0000000..0656310 --- /dev/null +++ b/internal/qmp/media.go @@ -0,0 +1,59 @@ +package qmp + +import ( + "encoding/json" + "fmt" + "path/filepath" + "slices" + "strings" +) + +// AttachedFiles lists the inserted image and backing files for each block +// device. QEMU's resolved image names include the real pflash and CD drives. +func (c *Conn) AttachedFiles(vmDir string) ([]string, error) { + raw, err := c.Query("query-block", nil) + if err != nil { + return nil, err + } + type image struct { + Filename string `json:"filename"` + Backing *image `json:"backing-image"` + } + var devices []struct { + Device string `json:"device"` + Inserted *struct { + Image *image `json:"image"` + Backing string `json:"backing_file"` + } `json:"inserted"` + } + if err := json.Unmarshal(raw, &devices); err != nil { + return nil, fmt.Errorf("decode query-block: %w", err) + } + var paths []string + for _, d := range devices { + if d.Inserted == nil { + continue + } + if d.Inserted.Image == nil || (d.Inserted.Backing != "" && d.Inserted.Image.Backing == nil) { + return nil, fmt.Errorf("cannot identify the complete attached disk or backing chain") + } + for img := d.Inserted.Image; img != nil; img = img.Backing { + if img.Filename == "" { + return nil, fmt.Errorf("block device has no filename") + } + name := img.Filename + if strings.HasPrefix(name, "json:") { + return nil, fmt.Errorf("block device %s uses a non-persistent or unresolvable image; eject it before suspending", d.Device) + } + if !filepath.IsAbs(name) { + name = filepath.Join(vmDir, name) + } + paths = append(paths, filepath.Clean(name)) + } + } + if len(paths) == 0 { + return nil, fmt.Errorf("no attached media reported by QEMU") + } + slices.Sort(paths) + return slices.Compact(paths), nil +} diff --git a/internal/qmp/migrate.go b/internal/qmp/migrate.go index effe1d1..0e42803 100644 --- a/internal/qmp/migrate.go +++ b/internal/qmp/migrate.go @@ -53,16 +53,20 @@ type vmStatusReply struct { // If migration fails before reaching completion while the VM is merely paused // (not postmigrate), SuspendToFile attempts to resume the guest with `cont` so // the running VM is not left frozen. -func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress)) error { +func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress), seal func([]string) error) error { c, err := Dial(ctx, "unix", SocketPath(vmDir)) if err != nil { return err } defer c.Close() - return suspendToFileConn(ctx, c, vmstatePath, onProgress) + paths, err := c.AttachedFiles(vmDir) + if err != nil { + return err + } + return suspendToFileConn(ctx, c, vmstatePath, onProgress, func(*Conn) error { return seal(paths) }) } -func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress)) error { +func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress), seal func(*Conn) error) error { if err := c.ExecuteWithTimeout("stop", nil, 30*time.Second); err != nil { return fmt.Errorf("pause VM before suspend: %w", err) } @@ -92,6 +96,13 @@ func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgr tryResumePaused(c) return fmt.Errorf("save snapshot: %w", err) } + if seal != nil { + if err := seal(c); err != nil { + // The source still owns the session. Leave it paused and retain + // the completed file if publishing the save failed. + return fmt.Errorf("seal snapshot before exiting QEMU: %w", err) + } + } // Migration completed (RUN_STATE_POSTMIGRATE): never send `cont` here; // exit QEMU cleanly so the disk and WHPX partition close. @@ -109,12 +120,17 @@ func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgr // completion, and resumes execution with `cont`. // // On any error, vmstatePath is left untouched so the caller can retry. -func ResumeFromFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress)) error { +func ResumeFromFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress), checkMedia func(*Conn) error) error { c, err := dialMigrateConnWithRetry(ctx, "unix", SocketPath(vmDir), 10*time.Second) if err != nil { return err } defer c.Close() + if checkMedia != nil { + if err := checkMedia(c); err != nil { + return err + } + } return resumeFromFileConn(ctx, c, vmstatePath, onProgress) } diff --git a/internal/qmp/migrate_test.go b/internal/qmp/migrate_test.go index 0c863d2..99aa261 100644 --- a/internal/qmp/migrate_test.go +++ b/internal/qmp/migrate_test.go @@ -4,12 +4,87 @@ import ( "bufio" "context" "encoding/json" + "errors" "net" + "path/filepath" + "slices" "strings" "sync" "testing" ) +func TestAttachedFiles(t *testing.T) { + vmDir := t.TempDir() + disk := filepath.Join(vmDir, "disk.qcow2") + parent := filepath.Join(vmDir, "base.qcow2") + addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + if req.Execute != "query-block" { + t.Errorf("unexpected command: %s", req.Execute) + } + return map[string]any{"return": []map[string]any{ + {"device": "disk", "inserted": map[string]any{"image": map[string]any{ + "filename": disk, "backing-image": map[string]any{"filename": parent}, + }}}, + {"device": "empty", "inserted": nil}, + }}, false + }) + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatal(err) + } + defer c.Close() + got, err := c.AttachedFiles(vmDir) + if err != nil || !slices.Equal(got, []string{parent, disk}) { + t.Fatalf("attached files = %v, %v", got, err) + } +} + +func TestAttachedFilesRejectsTemporaryOverlay(t *testing.T) { + addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + return map[string]any{"return": []map[string]any{ + {"device": "installer", "inserted": map[string]any{"image": map[string]any{ + "filename": "json:temporary disk descriptor", + }}}, + }}, false + }) + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if _, err := c.AttachedFiles(t.TempDir()); err == nil || !strings.Contains(err.Error(), "installer uses a non-persistent") { + t.Fatalf("temporary installer overlay = %v", err) + } +} + +func TestSuspendSealFailureDoesNotQuitSource(t *testing.T) { + addr, recorded := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "query-status": + return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false + case "query-migrate": + return map[string]any{"return": map[string]any{"status": "completed"}}, false + case "quit": + t.Error("QEMU would exit with an unsealed snapshot") + } + return map[string]any{"return": map[string]any{}}, false + }) + ctx := context.Background() + c, err := Dial(ctx, "tcp", addr) + if err != nil { + t.Fatal(err) + } + defer c.Close() + sealErr := errors.New("unable to publish state") + if err := suspendToFileConn(ctx, c, "test.vmstate", nil, func(*Conn) error { return sealErr }); !errors.Is(err, sealErr) { + t.Fatalf("suspend error = %v", err) + } + cmds := recorded() + if len(cmds) == 0 || cmds[len(cmds)-1].Execute != "query-migrate" { + t.Fatalf("unexpected commands: %+v", cmds) + } +} + type mockQMPReq struct { Execute string `json:"execute"` Arguments json.RawMessage `json:"arguments"` @@ -104,7 +179,7 @@ func TestSuspendToFileHappyPath(t *testing.T) { var progress []MigrateProgress if err := suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, func(p MigrateProgress) { progress = append(progress, p) - }); err != nil { + }, nil); err != nil { t.Fatalf("suspendToFileConn: %v", err) } if len(progress) != 2 || progress[1].Status != "completed" { @@ -141,7 +216,7 @@ func TestSuspendToFileFailureResumesPausedVM(t *testing.T) { } defer c.Close() - err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil) + err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil, nil) if err == nil || !strings.Contains(err.Error(), "disk full") { t.Fatalf("expected disk full error, got %v", err) } diff --git a/internal/vmstart/suspend.go b/internal/vmstart/suspend.go new file mode 100644 index 0000000..958030f --- /dev/null +++ b/internal/vmstart/suspend.go @@ -0,0 +1,198 @@ +package vmstart + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "slices" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/qmp" +) + +// LockVM reads the VM again after locking its directory so that another +// process cannot change the state between inspection and operation. +func LockVM(ctx context.Context, c *reims.Client, name string) (reims.VMDetail, func(), error) { + d, err := c.Show(ctx, name) + if err != nil { + return d, nil, err + } + release, err := reims.LockVMOperation(d.Directory) + if errors.Is(err, reims.ErrVMOperationBusy) { + return d, nil, i18n.NewCodedError(c.Locale, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) + } + if err != nil { + return d, nil, err + } + cur, err := c.Show(ctx, name) + if err == nil && cur.Directory != d.Directory { + err = fmt.Errorf("VM directory changed while waiting to operate on %s", name) + } + if err != nil { + release() + return cur, nil, err + } + return cur, release, nil +} + +func (p *Prep) checkSuspendRuntime(d reims.VMDetail) error { + kind := strings.ToLower(d.Kind) + if !p.Runtime.Manifest.HasCapability("vm-suspend") || strings.Contains(kind, "arm64") || strings.Contains(kind, "aarch64") { + return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + } + return nil +} + +// SuspendSnapshot saves and publishes a VM snapshot while the caller holds +// LockVM. The source exits only after the snapshot and metadata are durable. +func (p *Prep) SuspendSnapshot(ctx context.Context, d reims.VMDetail, progress func(qmp.MigrateProgress)) (reims.SuspendInfo, error) { + var info reims.SuspendInfo + if err := p.checkSuspendRuntime(d); err != nil { + return info, err + } + pid, err := vmPID(ctx, p.Client, d.Name) + if err != nil { + return info, err + } + if pid == 0 { + return info, i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": d.Name}, nil) + } + if memGB, ok := reims.ParseSizeGB(d.Memory); ok { + if avail := host.Inspect(d.Directory).FreeDiskGB; avail > 0 && avail < memGB+1 { + return info, i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{ + "need": fmt.Sprintf("%.1f", memGB+1), "avail": fmt.Sprintf("%.1f", avail), + }, nil) + } + } + state := reims.SuspendStatePath(d.Directory) + tmp := state + ".tmp" + meta := reims.SuspendMetaPath(d.Directory) + for _, path := range []string{state, tmp, meta, meta + ".tmp"} { + if _, err := os.Lstat(path); !os.IsNotExist(err) { + if err != nil { + return info, err + } + return info, fmt.Errorf("previous suspend data still exists: %s", path) + } + } + err = qmp.SuspendToFile(ctx, d.Directory, tmp, progress, func(paths []string) error { + var err error + info, err = reims.SealSuspend(d, p.Runtime, paths) + return err + }) + if err != nil { + return info, err + } + waitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second) + defer cancel() + if err := host.WaitProcessExit(waitCtx, uint32(pid), "qemu-system-x86_64.exe"); err != nil { + if !errors.Is(err, errors.ErrUnsupported) { + return info, err + } + for { + cur, err := vmPID(waitCtx, p.Client, d.Name) + if err != nil || cur == 0 { + return info, err + } + select { + case <-waitCtx.Done(): + return info, waitCtx.Err() + case <-time.After(100 * time.Millisecond): + } + } + } + return info, nil +} + +// ResumeSnapshot owns the incoming launch and snapshot consumption while +// the caller holds LockVM. The original configuration must be restored +// before guest execution can continue. +func (p *Prep) ResumeSnapshot(ctx context.Context, d reims.VMDetail, rep host.Report, out, stderr io.Writer) error { + if err := p.checkSuspendRuntime(d); err != nil { + return err + } + if d.State == "running" { + return fmt.Errorf("%s", i18n.T(p.Client.Locale, "vm.already_running", d.Name)) + } + if !reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": d.Name}, nil) + } + state, paths, err := reims.ValidateSuspendFiles(d, p.Runtime) + if err != nil { + return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{"diffs": err.Error()}, err) + } + if err := p.CheckWHPX(rep); err != nil { + return err + } + if err := p.CheckMemory(d.Memory, rep); err != nil { + return err + } + c := p.Client + incoming := reims.MergeIncomingDeferArgs(d.ExtraArgs) + if err := c.Set(ctx, reims.SetOpts{Name: d.Name, ExtraArgs: &incoming}, out, stderr); err != nil { + return err + } + startErr := c.Start(ctx, d.Name, out, stderr) + restoreCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) + restoreErr := c.Set(restoreCtx, reims.SetOpts{Name: d.Name, ExtraArgs: &d.ExtraArgs}, out, stderr) + cancel() + if restoreErr != nil { + restoreErr = fmt.Errorf("restore original VM start arguments: %w", restoreErr) + } + if err := errors.Join(startErr, restoreErr); err != nil { + p.stopFailedIncoming(ctx, d) + return err + } + err = qmp.ResumeFromFile(ctx, d.Directory, state, nil, func(conn *qmp.Conn) error { + attached, err := conn.AttachedFiles(d.Directory) + if err != nil { + return err + } + if !slices.Equal(paths, attached) { + return fmt.Errorf("incoming QEMU opened different media from the saved VM") + } + return nil + }) + if err != nil { + p.stopFailedIncoming(ctx, d) + return err + } + if err := reims.RemoveSuspendState(d.Directory); err != nil { + p.log("Warning: could not remove consumed suspend files: " + err.Error()) + } + return nil +} + +func (p *Prep) stopFailedIncoming(ctx context.Context, d reims.VMDetail) { + cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second) + defer cancel() + if err := qmp.QuitVM(cleanup, d.Directory); err != nil { + _ = p.Client.StopForce(cleanup, d.Name, io.Discard, io.Discard) + } +} + +func DiscardSnapshot(loc i18n.Locale, d reims.VMDetail) error { + if d.State == "running" { + return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": d.Name}, nil) + } + return reims.RemoveSuspendState(d.Directory) +} + +func vmPID(ctx context.Context, c *reims.Client, name string) (int, error) { + vms, err := c.List(ctx) + if err != nil { + return 0, err + } + for _, vm := range vms { + if vm.Name == name && vm.State == "running" && vm.PID != nil { + return *vm.PID, nil + } + } + return 0, nil +} From a32fe323abd9797a269c10f8f851b3ce61ca193d Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 08:54:22 +0800 Subject: [PATCH 08/10] fix: preserve force stop and recover incomplete VM suspend attempts --- internal/app/app.go | 2 +- internal/app/clone_flow.go | 4 +- internal/app/disk_flow.go | 7 +- internal/app/guesttools_flow.go | 9 ++- internal/app/install_flow.go | 12 ++-- internal/app/snapshot_flow.go | 4 +- internal/app/suspend_flow.go | 19 +++++- internal/cli/cli.go | 8 ++- internal/qmp/client.go | 16 +++-- internal/qmp/migrate.go | 108 ++++++++++++++++++++++++++----- internal/qmp/migrate_test.go | 80 ++++++++++++++++++++++- internal/qmp/watcher.go | 27 +++++++- internal/qmp/watcher_test.go | 17 +++++ internal/vmstart/suspend.go | 35 +++++++++- internal/vmstart/suspend_test.go | 48 ++++++++++++++ 15 files changed, 348 insertions(+), 48 deletions(-) create mode 100644 internal/vmstart/suspend_test.go diff --git a/internal/app/app.go b/internal/app/app.go index 048e2eb..f9a0183 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -1512,7 +1512,7 @@ func (a *App) StopVM(name string, force bool) error { if err != nil { return err } - _, release, err := vmstart.LockVM(a.baseCtx(), c, name) + release, err := vmstart.LockVMForStop(a.baseCtx(), c, name, force) if err != nil { return err } diff --git a/internal/app/clone_flow.go b/internal/app/clone_flow.go index 1ab10e6..92b1741 100644 --- a/internal/app/clone_flow.go +++ b/internal/app/clone_flow.go @@ -39,10 +39,12 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error { c := reims.NewClient(&cfgCopy, *active) ctx := a.baseCtx() - src, err := a.GetVMDetail(sourceName) + src, release, err := vmstart.LockVM(ctx, c, sourceName) if err != nil { return err } + defer release() + a.populateVMDetail(&src) if a.isVMRunning(ctx, c, sourceName, src) { return i18n.NewCodedError(loc, "E_VM_CLONE_RUNNING", "err.clone.source_running", i18n.Vars{"name": sourceName}, nil) } diff --git a/internal/app/disk_flow.go b/internal/app/disk_flow.go index fc3e7ed..5f455d4 100644 --- a/internal/app/disk_flow.go +++ b/internal/app/disk_flow.go @@ -7,6 +7,7 @@ import ( "github.com/Nwflower/reims-go/internal/driver/reims" rt "github.com/Nwflower/reims-go/internal/runtime" + "github.com/Nwflower/reims-go/internal/vmstart" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) @@ -24,10 +25,11 @@ func (a *App) ResizeVMDisk(name, newSize string) (reims.DiskResizeResult, error) c := reims.NewClient(&cfgCopy, *active) ctx := a.baseCtx() - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockVM(ctx, c, name) if err != nil { return reims.DiskResizeResult{}, err } + defer release() if a.isVMRunning(ctx, c, name, d) { return reims.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name) } @@ -73,10 +75,11 @@ func (a *App) CompactVMDisk(name string) (reims.DiskCompactResult, error) { c := reims.NewClient(&cfgCopy, *active) ctx := a.baseCtx() - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockVM(ctx, c, name) if err != nil { return reims.DiskCompactResult{}, err } + defer release() if a.isVMRunning(ctx, c, name, d) { return reims.DiskCompactResult{}, fmt.Errorf("stop %s before reclaiming disk space", name) } diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index 6cfe72b..2f3da20 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -225,13 +225,11 @@ func (a *App) AttachGuestTools(name string) error { if err != nil { return err } - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name) if err != nil { return err } - if d.Directory == "" { - return fmt.Errorf("VM %s has no directory", name) - } + defer release() srv, port, err := a.ensureGuestToolsBridge() if err != nil { return err @@ -281,10 +279,11 @@ func (a *App) DetachGuestTools(name string) error { if err != nil { return err } - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name) if err != nil { return err } + defer release() stripped := reims.StripGuestToolsArgs(d.ExtraArgs) ctx := context.Background() w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) diff --git a/internal/app/install_flow.go b/internal/app/install_flow.go index 10f979a..8f2f678 100644 --- a/internal/app/install_flow.go +++ b/internal/app/install_flow.go @@ -80,10 +80,11 @@ func (a *App) EnterRecovery(name string) error { if err != nil { return err } - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name) if err != nil { return err } + defer release() w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) ctx := context.Background() @@ -126,10 +127,11 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) { if err != nil { return "", err } - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name) if err != nil { return "", err } + defer release() path := strings.TrimSpace(installerPath) if path == "" { path, err = a.pickCachedRecoveryInstaller() @@ -232,10 +234,11 @@ func (a *App) FinishInstall(name string) error { if err != nil { return err } - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name) if err != nil { return err } + defer release() w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) ctx := context.Background() @@ -325,10 +328,11 @@ func (a *App) UpgradeDiskToNVMe(name string) error { if err != nil { return err } - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name) if err != nil { return err } + defer release() if d.HasInstaller { return errors.New("exit recovery mode (eject installer) before switching disk controller") } diff --git a/internal/app/snapshot_flow.go b/internal/app/snapshot_flow.go index 426fc75..0c4b3dd 100644 --- a/internal/app/snapshot_flow.go +++ b/internal/app/snapshot_flow.go @@ -9,6 +9,7 @@ import ( "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/i18n" rt "github.com/Nwflower/reims-go/internal/runtime" + "github.com/Nwflower/reims-go/internal/vmstart" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) @@ -78,10 +79,11 @@ func (a *App) runSnapshotOp(name, flag, snapName, verb string) error { c := reims.NewClient(&cfgCopy, *active) ctx := a.baseCtx() - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockVM(ctx, c, name) if err != nil { return err } + defer release() if a.isVMRunning(ctx, c, name, d) { return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_RUNNING", "err.snapshot.vm_running", i18n.Vars{"name": name}, nil) } diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index 90abdc0..8cfd783 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -2,6 +2,7 @@ package app import ( "fmt" + "os" "time" "github.com/Nwflower/reims-go/internal/driver/reims" @@ -109,10 +110,20 @@ func (a *App) resumeLocked(prep *vmstart.Prep, d reims.VMDetail) error { defer end() a.mu.Lock() - root, mgr := a.cfg.DataRoot, a.pluginMgr + root, tmpDir, mgr := a.cfg.DataRoot, a.cfg.TempDir(), a.pluginMgr a.mu.Unlock() rep := host.Inspect(root) - a.cancelRebootWatcher(name) + var qmpAddr string + if d.State == "stopped" && reims.HasSuspendState(d.Directory) && rep.NeedsColdRebootWorkaround { + sockPath := qmp.RebootSocketPath(d.Directory, tmpDir, name) + if qmp.HasWin10RebootUnixArgs(d.ExtraArgs, sockPath) { + a.cancelRebootWatcher(name) + if err := os.Remove(sockPath); err != nil && !os.IsNotExist(err) { + return fmt.Errorf("remove stale reboot socket: %w", err) + } + qmpAddr = "unix:" + sockPath + } + } if prep.Runtime.Manifest.HasCapability("win32-unicode-input") { prep.Client.Env = append(prep.Client.Env, a.inputBridgeEnv(name, d.Directory)...) } @@ -129,8 +140,10 @@ func (a *App) resumeLocked(prep *vmstart.Prep, d reims.VMDetail) error { } if mgr != nil { mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{ - VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS, + VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS, QMPAddr: qmpAddr, }) + } else if qmpAddr != "" { + a.watchWin10ColdReboot(name, qmpAddr) } a.startVMMonitor(name, d, startAt) a.emitLog(name, fmt.Sprintf("Resumed %s in %.1fs", name, time.Since(startAt).Seconds())) diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 27e6c07..aa74164 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -561,7 +561,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if len(args) < 2 { return fmt.Errorf("usage: reims-go vm stop ") } - _, release, err := vmstart.LockVM(ctx, client, args[1]) + release, err := vmstart.LockVMForStop(ctx, client, args[1], false) if err != nil { return err } @@ -622,10 +622,11 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if len(args) < 3 { return fmt.Errorf("usage: reims-go vm resize (e.g. 256G or +64G)") } - d, err := client.Show(ctx, args[1]) + d, release, err := vmstart.LockVM(ctx, client, args[1]) if err != nil { return err } + defer release() if d.State == "running" { return fmt.Errorf("%s", i18n.T(loc, "vm.resize.stop_first", args[1])) } @@ -644,10 +645,11 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if len(args) < 2 { return fmt.Errorf("usage: reims-go vm compact ") } - d, err := client.Show(ctx, args[1]) + d, release, err := vmstart.LockVM(ctx, client, args[1]) if err != nil { return err } + defer release() if d.State == "running" { return fmt.Errorf("%s", i18n.T(loc, "vm.compact.stop_first", args[1])) } diff --git a/internal/qmp/client.go b/internal/qmp/client.go index bc7ba3b..360e448 100644 --- a/internal/qmp/client.go +++ b/internal/qmp/client.go @@ -45,13 +45,17 @@ func (c *Conn) Close() error { return c.nc.Close() } type qmpReply struct { Return json.RawMessage `json:"return"` - Error *struct { - Class string `json:"class"` - Desc string `json:"desc"` - } `json:"error"` - Event string `json:"event"` + Error *commandError `json:"error"` + Event string `json:"event"` } +type commandError struct { + Class string `json:"class"` + Desc string `json:"desc"` +} + +func (e *commandError) Error() string { return e.Class + ": " + e.Desc } + // Query runs one command with the default 5-second timeout and waits for its // JSON return value, skipping async events. func (c *Conn) Query(command string, args any) (json.RawMessage, error) { @@ -82,7 +86,7 @@ func (c *Conn) QueryWithTimeout(command string, args any, timeout time.Duration) continue } if r.Error != nil { - return nil, fmt.Errorf("QMP %s: %s: %s", command, r.Error.Class, r.Error.Desc) + return nil, fmt.Errorf("QMP %s: %w", command, r.Error) } if r.Return != nil { return append(json.RawMessage(nil), r.Return...), nil diff --git a/internal/qmp/migrate.go b/internal/qmp/migrate.go index 0e42803..69b2ef8 100644 --- a/internal/qmp/migrate.go +++ b/internal/qmp/migrate.go @@ -46,6 +46,27 @@ type vmStatusReply struct { Status string `json:"status"` } +// ErrIncompleteSuspend marks a save that QEMU rejected, failed, or cancelled. +// The caller may remove its staging file once QEMU no longer writes to it. +var ErrIncompleteSuspend = errors.New("incomplete suspend snapshot") + +type migrationFailure struct { + status string + desc string +} + +func (e *migrationFailure) Error() string { + if e.desc != "" { + return fmt.Sprintf("migration %s: %s", e.status, e.desc) + } + return "migration " + e.status +} + +// A timeout or a dropped connection can hide a completed migration. +type unknownSuspendOutcome struct{ error } + +func (e *unknownSuspendOutcome) Unwrap() error { return e.error } + // SuspendToFile pauses a running Intel VM via QMP, writes a mapped-ram + // multifd file snapshot to vmstatePath, waits for completion, and shuts down // QEMU cleanly via `quit`. @@ -54,7 +75,11 @@ type vmStatusReply struct { // (not postmigrate), SuspendToFile attempts to resume the guest with `cont` so // the running VM is not left frozen. func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress), seal func([]string) error) error { - c, err := Dial(ctx, "unix", SocketPath(vmDir)) + if seal == nil { + return errors.New("suspend snapshot requires a seal callback") + } + addr := SocketPath(vmDir) + c, err := Dial(ctx, "unix", addr) if err != nil { return err } @@ -63,7 +88,21 @@ func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress fu if err != nil { return err } - return suspendToFileConn(ctx, c, vmstatePath, onProgress, func(*Conn) error { return seal(paths) }) + err = suspendToFileConn(ctx, c, vmstatePath, onProgress, func(*Conn) error { return seal(paths) }) + var unknown *unknownSuspendOutcome + if errors.As(err, &unknown) { + _ = c.Close() + cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 8*time.Second) + defer cancel() + fresh, dialErr := dialMigrateConnWithRetry(cleanup, "unix", addr, 3*time.Second) + if dialErr == nil { + defer fresh.Close() + if cancelIncompleteSuspend(cleanup, fresh) { + return fmt.Errorf("%w: %w", ErrIncompleteSuspend, err) + } + } + } + return err } func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress), seal func(*Conn) error) error { @@ -88,13 +127,21 @@ func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgr "channels": fileChannels(vmstatePath), } if err := c.ExecuteWithTimeout("migrate", args, migrateCmdTimeout); err != nil { - tryResumePaused(c) - return fmt.Errorf("start snapshot save: %w", err) + var rejected *commandError + if errors.As(err, &rejected) { + tryResumePaused(c) + return fmt.Errorf("%w: start snapshot save: %w", ErrIncompleteSuspend, err) + } + return &unknownSuspendOutcome{fmt.Errorf("start snapshot save: %w", err)} } if err := waitMigrateDone(ctx, c, onProgress); err != nil { - tryResumePaused(c) - return fmt.Errorf("save snapshot: %w", err) + var failed *migrationFailure + if errors.As(err, &failed) { + tryResumePaused(c) + return fmt.Errorf("%w: save snapshot: %w", ErrIncompleteSuspend, err) + } + return &unknownSuspendOutcome{fmt.Errorf("save snapshot: %w", err)} } if seal != nil { if err := seal(c); err != nil { @@ -223,6 +270,43 @@ func tryResumePaused(c *Conn) { } } +func cancelIncompleteSuspend(ctx context.Context, c *Conn) bool { + cancelSent := false + for ctx.Err() == nil { + info, err := queryMigration(c, 2*time.Second) + if err != nil { + return false + } + switch info.Status { + case "failed", "cancelled": + tryResumePaused(c) + return true + case "completed", "none", "": + return false + } + if !cancelSent { + // Completion can race cancellation. Check the terminal status + // even if QEMU rejects the cancel request. + _ = c.ExecuteWithTimeout("migrate_cancel", nil, 2*time.Second) + cancelSent = true + } + sleep(ctx, migratePollInterval) + } + return false +} + +func queryMigration(c *Conn, timeout time.Duration) (migrateInfo, error) { + var info migrateInfo + raw, err := c.QueryWithTimeout("query-migrate", nil, timeout) + if err != nil { + return info, err + } + if err := json.Unmarshal(raw, &info); err != nil { + return info, fmt.Errorf("parse query-migrate: %w", err) + } + return info, nil +} + func waitMigrateDone(ctx context.Context, c *Conn, onProgress func(MigrateProgress)) error { deadline := time.Now().Add(migrateTotalTimeout) for { @@ -232,14 +316,10 @@ func waitMigrateDone(ctx context.Context, c *Conn, onProgress func(MigrateProgre if time.Now().After(deadline) { return errors.New("timed out waiting for migration to finish") } - raw, err := c.QueryWithTimeout("query-migrate", nil, migrateCmdTimeout) + info, err := queryMigration(c, migrateCmdTimeout) if err != nil { return err } - var info migrateInfo - if err := json.Unmarshal(raw, &info); err != nil { - return fmt.Errorf("parse query-migrate: %w", err) - } prog := MigrateProgress{ Status: info.Status, TotalTimeMs: info.TotalTimeMs, @@ -256,11 +336,7 @@ func waitMigrateDone(ctx context.Context, c *Conn, onProgress func(MigrateProgre case "completed": return nil case "failed", "cancelled": - desc := strings.TrimSpace(info.ErrorDesc) - if desc != "" { - return fmt.Errorf("migration %s: %s", info.Status, desc) - } - return fmt.Errorf("migration %s", info.Status) + return &migrationFailure{status: info.Status, desc: strings.TrimSpace(info.ErrorDesc)} } sleep(ctx, migratePollInterval) } diff --git a/internal/qmp/migrate_test.go b/internal/qmp/migrate_test.go index 99aa261..4a1b8bb 100644 --- a/internal/qmp/migrate_test.go +++ b/internal/qmp/migrate_test.go @@ -11,8 +11,84 @@ import ( "strings" "sync" "testing" + "time" ) +func TestSuspendToFileRequiresSeal(t *testing.T) { + if err := SuspendToFile(context.Background(), t.TempDir(), "state", nil, nil); err == nil || + !strings.Contains(err.Error(), "seal callback") { + t.Fatalf("suspend without a seal callback: %v", err) + } +} + +func TestSuspendMigrationFailedBeforeSeal(t *testing.T) { + addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + reply := map[string]any{} + switch req.Execute { + case "query-status": + reply["status"] = "paused" + reply["running"] = false + case "query-migrate": + reply["status"] = "failed" + reply["error-desc"] = "write failed" + case "quit": + t.Error("QEMU would exit after an incomplete save") + } + return map[string]any{"return": reply}, false + }) + ctx := context.Background() + c, err := Dial(ctx, "tcp", addr) + if err != nil { + t.Fatal(err) + } + defer c.Close() + err = suspendToFileConn(ctx, c, "state.tmp", nil, func(*Conn) error { + t.Error("an incomplete save reached seal") + return nil + }) + if !errors.Is(err, ErrIncompleteSuspend) || !strings.Contains(err.Error(), "write failed") { + t.Fatalf("incomplete save = %v", err) + } +} + +func TestCancelIncompleteSuspendRechecksTerminalStatus(t *testing.T) { + for _, terminal := range []string{"cancelled", "completed"} { + t.Run(terminal, func(t *testing.T) { + cancelled := false + addr, recorded := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "query-migrate": + status := "active" + if cancelled { + status = terminal + } + return map[string]any{"return": map[string]any{"status": status}}, false + case "migrate_cancel": + cancelled = true + case "query-status": + return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false + } + return map[string]any{"return": map[string]any{}}, false + }) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + c, err := Dial(ctx, "tcp", addr) + if err != nil { + t.Fatal(err) + } + defer c.Close() + want := terminal == "cancelled" + if got := cancelIncompleteSuspend(ctx, c); got != want { + t.Fatalf("safe discard = %t, want %t", got, want) + } + cmds := recorded() + if sawCont := len(cmds) > 0 && cmds[len(cmds)-1].Execute == "cont"; sawCont != want { + t.Fatalf("unexpected rollback commands: %v", cmds) + } + }) + } +} + func TestAttachedFiles(t *testing.T) { vmDir := t.TempDir() disk := filepath.Join(vmDir, "disk.qcow2") @@ -76,7 +152,7 @@ func TestSuspendSealFailureDoesNotQuitSource(t *testing.T) { } defer c.Close() sealErr := errors.New("unable to publish state") - if err := suspendToFileConn(ctx, c, "test.vmstate", nil, func(*Conn) error { return sealErr }); !errors.Is(err, sealErr) { + if err := suspendToFileConn(ctx, c, "test.vmstate", nil, func(*Conn) error { return sealErr }); !errors.Is(err, sealErr) || errors.Is(err, ErrIncompleteSuspend) { t.Fatalf("suspend error = %v", err) } cmds := recorded() @@ -217,7 +293,7 @@ func TestSuspendToFileFailureResumesPausedVM(t *testing.T) { defer c.Close() err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil, nil) - if err == nil || !strings.Contains(err.Error(), "disk full") { + if !errors.Is(err, ErrIncompleteSuspend) || !strings.Contains(err.Error(), "disk full") { t.Fatalf("expected disk full error, got %v", err) } var sawCont bool diff --git a/internal/qmp/watcher.go b/internal/qmp/watcher.go index bd46a2a..6c004b6 100644 --- a/internal/qmp/watcher.go +++ b/internal/qmp/watcher.go @@ -89,9 +89,7 @@ func MergeWin10RebootUnixArgs(existing, sockPath string) string { } cleaned = append(cleaned, tok) } - escaped := strings.ReplaceAll(sockPath, ",", ",,") - escaped = strings.ReplaceAll(escaped, `\`, `/`) - qmpVal := fmt.Sprintf("unix:%s,server=on,wait=off", escaped) + qmpVal := win10RebootUnixTarget(sockPath) if strings.ContainsAny(qmpVal, " \t") { qmpVal = `"` + strings.ReplaceAll(qmpVal, `"`, `\"`) + `"` } @@ -99,6 +97,29 @@ func MergeWin10RebootUnixArgs(existing, sockPath string) string { return strings.Join(cleaned, " ") } +func win10RebootUnixTarget(sockPath string) string { + escaped := strings.ReplaceAll(sockPath, ",", ",,") + escaped = strings.ReplaceAll(escaped, "\\", "/") + return "unix:" + escaped + ",server=on,wait=off" +} + +// HasWin10RebootUnixArgs checks for the private socket Reims-Go configured, +// without accepting other monitors declared in extra-args. +func HasWin10RebootUnixArgs(extraArgs, sockPath string) bool { + tokens := splitShellTokens(extraArgs) + want := win10RebootUnixTarget(sockPath) + var noReboot, socket bool + for i, token := range tokens { + if token == "-no-reboot" { + noReboot = true + } + if token == "-qmp" && i+1 < len(tokens) && strings.Trim(tokens[i+1], "'\"") == want { + socket = true + } + } + return noReboot && socket +} + func isManagedQMPTarget(arg string) bool { arg = strings.Trim(arg, "'\"") if !strings.HasSuffix(arg, ",server=on,wait=off") { diff --git a/internal/qmp/watcher_test.go b/internal/qmp/watcher_test.go index 5e93da5..8d3d0b2 100644 --- a/internal/qmp/watcher_test.go +++ b/internal/qmp/watcher_test.go @@ -10,6 +10,23 @@ import ( "time" ) +func TestHasWin10RebootUnixArgs(t *testing.T) { + sock := "D:\\VM data\\group,1\\reims-go-reboot.sock" + args := MergeWin10RebootUnixArgs("-machine q35", sock) + if !HasWin10RebootUnixArgs(args, sock) { + t.Fatal("saved socket with escaped comma and quoted path was not recognized") + } + if HasWin10RebootUnixArgs(strings.ReplaceAll(args, "-no-reboot", ""), sock) { + t.Fatal("recognized a monitor without the cold-reboot flag") + } + if HasWin10RebootUnixArgs(args, "D:/other/reims-go-reboot.sock") { + t.Fatal("recognized a different monitor") + } + if HasWin10RebootUnixArgs("-no-reboot -qmp tcp:127.0.0.1:45555,server=on,wait=off", sock) { + t.Fatal("recognized a legacy TCP monitor") + } +} + func TestMergeWin10RebootUnixArgs(t *testing.T) { got := MergeWin10RebootUnixArgs("", `D:\Data\reims-go\vms\m0\reims-go-reboot.sock`) want := "-no-reboot -qmp unix:D:/Data/reims-go/vms/m0/reims-go-reboot.sock,server=on,wait=off" diff --git a/internal/vmstart/suspend.go b/internal/vmstart/suspend.go index 958030f..f1566c1 100644 --- a/internal/vmstart/suspend.go +++ b/internal/vmstart/suspend.go @@ -41,6 +41,30 @@ func LockVM(ctx context.Context, c *reims.Client, name string) (reims.VMDetail, return cur, release, nil } +// LockMutableVM protects configuration and media updates and rejects updates +// while a published suspend state depends on the current configuration. +func LockMutableVM(ctx context.Context, c *reims.Client, name string) (reims.VMDetail, func(), error) { + d, release, err := LockVM(ctx, c, name) + if err != nil { + return d, nil, err + } + if reims.HasSuspendState(d.Directory) { + release() + return d, nil, i18n.NewCodedError(c.Locale, "E_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil) + } + return d, release, nil +} + +// LockVMForStop serializes graceful shutdown. Emergency shutdown is also +// the escape path for a stalled operation that already holds the lock. +func LockVMForStop(ctx context.Context, c *reims.Client, name string, force bool) (func(), error) { + if force { + return func() {}, nil + } + _, release, err := LockVM(ctx, c, name) + return release, err +} + func (p *Prep) checkSuspendRuntime(d reims.VMDetail) error { kind := strings.ToLower(d.Kind) if !p.Runtime.Manifest.HasCapability("vm-suspend") || strings.Contains(kind, "arm64") || strings.Contains(kind, "aarch64") { @@ -87,7 +111,7 @@ func (p *Prep) SuspendSnapshot(ctx context.Context, d reims.VMDetail, progress f return err }) if err != nil { - return info, err + return info, cleanupSuspendAttempt(tmp, err) } waitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second) defer cancel() @@ -110,6 +134,15 @@ func (p *Prep) SuspendSnapshot(ctx context.Context, d reims.VMDetail, progress f return info, nil } +func cleanupSuspendAttempt(tmp string, err error) error { + if errors.Is(err, qmp.ErrIncompleteSuspend) { + if removeErr := os.Remove(tmp); removeErr != nil && !os.IsNotExist(removeErr) { + return errors.Join(err, fmt.Errorf("remove incomplete snapshot: %w", removeErr)) + } + } + return err +} + // ResumeSnapshot owns the incoming launch and snapshot consumption while // the caller holds LockVM. The original configuration must be restored // before guest execution can continue. diff --git a/internal/vmstart/suspend_test.go b/internal/vmstart/suspend_test.go new file mode 100644 index 0000000..0d28b48 --- /dev/null +++ b/internal/vmstart/suspend_test.go @@ -0,0 +1,48 @@ +package vmstart + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/Nwflower/reims-go/internal/qmp" +) + +func TestForceStopDoesNotWaitForVMInspectionOrLock(t *testing.T) { + // A forced stop must not ask reims-ctl to show the VM before it can + // invoke stop --force. A stalled owner may also be holding its lock. + release, err := LockVMForStop(context.Background(), nil, "stalled", true) + if err != nil { + t.Fatal(err) + } + release() +} + +func TestCleanupSuspendAttempt(t *testing.T) { + for _, tt := range []struct { + name string + err error + keep bool + }{ + {"migration failed", fmt.Errorf("%w: disk full", qmp.ErrIncompleteSuspend), false}, + {"seal failed", errors.New("could not publish suspend metadata"), true}, + {"unknown outcome", errors.New("connection closed"), true}, + } { + t.Run(tt.name, func(t *testing.T) { + tmp := filepath.Join(t.TempDir(), "suspend.vmstate.tmp") + if err := os.WriteFile(tmp, []byte("snapshot data"), 0o600); err != nil { + t.Fatal(err) + } + if err := cleanupSuspendAttempt(tmp, tt.err); !errors.Is(err, tt.err) { + t.Fatalf("cleanup lost the save error: %v", err) + } + _, err := os.Stat(tmp) + if tt.keep && err != nil || !tt.keep && !os.IsNotExist(err) { + t.Fatalf("stat after cleanup = %v, want keep=%t", err, tt.keep) + } + }) + } +} From 5f8d96a40179a522f30e01b6f95411e7bf840a0b Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 09:05:57 +0800 Subject: [PATCH 09/10] fix(ui): align suspend confirmation and single-line toasts --- frontend/src/App.tsx | 4 ++-- frontend/src/styles/app.css | 7 +++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index ceda025..9f9c55c 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1314,8 +1314,8 @@ export const App: React.FC = () => { closeLabel={tr('close')} onClose={() => setDiscardSuspendTarget(null)} > -
-

{tr('discardSuspendDesc')}

+
+

{tr('discardSuspendDesc')}

diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index d8c5c50..7e628f1 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -909,6 +909,7 @@ button.status-issue + .status-metric { margin-left: 6px; } .dialog-title { font-size: var(--fs-16); font-weight: var(--fw-strong); letter-spacing: -0.01em; text-wrap: balance; } .dialog-desc { font-size: var(--fs-13); color: var(--text-2); margin-top: 2px; } .dialog-body { padding: 20px 22px; overflow-y: auto; overscroll-behavior: contain; flex: 1; display: flex; flex-direction: column; gap: var(--sp-4); } +.dialog-body > .dialog-desc:only-child { margin-top: 0; } .dialog-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); } .dialog.sm .dialog-body { padding: 22px 22px 14px; gap: var(--sp-3); } .dialog.sm .dialog-foot { border-top: none; justify-content: flex-end; padding-top: 0; padding-bottom: 20px; } @@ -957,8 +958,10 @@ button.status-issue + .status-metric { margin-left: 6px; } .toast[data-swipe="cancel"] { transform: translateX(0); transition: transform var(--dur) var(--ease-out); } .toast[data-swipe="end"] { animation: toast-swipe-out var(--dur-fast) var(--ease-out) both; } :root[dir="rtl"] .toast[data-swipe="end"] { animation: toast-swipe-out-rtl var(--dur-fast) var(--ease-out) both; } -.toast-main-row { display: flex; align-items: flex-start; gap: var(--sp-3); width: 100%; min-width: 0; } -.toast-main-row > svg { margin-top: 2px; flex-shrink: 0; } +.toast-main-row { display: flex; align-items: center; gap: var(--sp-3); width: 100%; min-width: 0; } +.toast-main-row > svg { flex-shrink: 0; } +.toast-main-row:has(.toast-desc) { align-items: flex-start; } +.toast-main-row:has(.toast-desc) > svg { margin-top: 2px; } .toast.ok .toast-main-row > svg { color: var(--status-running); } .toast.error .toast-main-row > svg { color: var(--status-error); } .toast-text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; } From 003821a28aaccfe708ddd566043121ca69799033 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 09:14:02 +0800 Subject: [PATCH 10/10] fix(ui): refine VM suspend actions and confirmation --- docs/design-guidelines.md | 9 ++-- frontend/src/App.tsx | 41 +++++++---------- frontend/src/components/DeleteDialog.tsx | 42 ++++++----------- frontend/src/components/Sidebar.tsx | 5 ++- frontend/src/components/TitleMenus.tsx | 5 ++- frontend/src/components/VMPage.tsx | 57 +++++++++++++----------- frontend/src/i18n/domains/vm.gen.ts | 4 ++ frontend/src/i18n/keys.gen.ts | 2 + frontend/src/styles/app.css | 1 - frontend/src/ui/dialog.tsx | 32 ++++++++++++- frontend/src/wails.ts | 1 + frontend/wailsjs/go/models.ts | 2 + internal/app/app.go | 7 ++- internal/i18n/catalog_gen.go | 6 ++- internal/tray/tray.go | 24 ++++++---- internal/tray/tray_test.go | 15 +++++++ locales/en-US/native.json | 3 +- locales/en-US/vm.json | 2 + locales/zh-CN/native.json | 3 +- locales/zh-CN/vm.json | 2 + 20 files changed, 161 insertions(+), 102 deletions(-) diff --git a/docs/design-guidelines.md b/docs/design-guidelines.md index 1e75b1c..481e3fb 100644 --- a/docs/design-guidelines.md +++ b/docs/design-guidelines.md @@ -20,7 +20,7 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台 | :--- | :--- | | **声明式配置** | 一台虚拟机对应一份声明式配置,界面只编辑配置项,不让用户直接拼 QEMU 命令行参数。 | | **先校验,后保存** | 保存前在 Go 端完成前置校验(CPU 核数、可用提交内存上限、Vulkan ICD 路径存在性、切换磁盘控制器前是否已弹出安装盘),非法值在提交前拦截。 | -| **随时可编辑,标明生效时机** | 无论虚拟机运行与否,设置面板均可打开编辑;每项设置明确标注生效时机。运行中保存「下次启动生效」的修改时,详情页汇总待生效项并提供「重启以应用」。 | +| **标明设置的生效时机** | 虚拟机运行中或已停止时可编辑设置。每项设置明确标注生效时机。运行中保存「下次启动生效」的修改时,详情页汇总待生效项并提供「重启以应用」。 | **写入约束**:凡属于上游 `reims-ctl` 管理的配置项,一律通过 `reims-ctl set` 写入,不直接改写 `vm.toml`,确保上游校验与 OpenCore 重建逻辑照常生效。 @@ -55,11 +55,14 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台 | **正在创建** | 创建流程进行中 | 无(展示分步进度) | 取消创建 | | **已停止** | 上游 `stopped` | **启动** | 设置、恢复点、更多(派生副本、扩容/回收、打开目录、删除) | | **正在启动** | 发起 `start` 至 `running` | 启动中(忙碌态,禁用) | 设置、强制关机 | -| **运行中** | 上游 `running` | **显示 VM 窗口** | 关机、截屏、设置、更多(重启、强制关机、发送文本、进入/退出恢复模式、导出排障包) | +| **运行中** | 上游 `running` | **显示 VM 窗口** | 挂起(需支持此功能的内核)、关机、截屏、设置、更多(重启、强制关机、发送文本、进入/退出恢复模式、导出排障包) | | **正在停止** | 发起 `stop` 至 `stopped` | 停止中(忙碌态,禁用) | 强制关机 | +| **正在挂起** | 正在保存运行状态 | 挂起中(忙碌态,禁用) | 强制关机 | +| **已挂起** | 运行状态已保存到磁盘 | **恢复**(需支持此功能的内核) | 更多(放弃挂起状态、打开目录) | +| **正在恢复** | 正在从磁盘恢复运行状态 | 恢复中(忙碌态,禁用) | 强制关机 | | **配置损坏** | 上游 `broken` | **查看问题** | 打开目录、删除 | -- 暂不提供暂停或运行中热快照状态(`paused` / `saving` / `restoring`),直到上游验证 `reims-vgpu` 显存与设备状态序列化。 +- 已挂起时,恢复或放弃挂起状态后才可修改配置、管理磁盘和安装或弹出 Guest Tools。切换到不支持挂起的内核时,禁用恢复并提示用户切换内核。放弃挂起状态须经破坏性操作确认框确认。 - 禁用按钮不占据主操作位置;状态变化时直接切换为当前最合适的主操作。 --- diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 9f9c55c..11d5d38 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -20,7 +20,7 @@ import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFo import { latestVMStats, refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats' import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types' import { Button, Tip, TooltipProvider } from './ui/controls' -import { Modal } from './ui/dialog' +import { ConfirmDialog, Modal } from './ui/dialog' import { Toaster, useToasts } from './ui/toast' import { api, events, OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from './wails' @@ -335,15 +335,7 @@ export const App: React.FC = () => { const effectiveState = selectedVM ? (state?.transitions[selectedVM.name] ?? selectedVM.state) : '' const pending = selectedVM ? (state?.pending_changes[selectedVM.name] ?? []) : [] const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime - const activeManifest = state?.active_runtime?.manifest - const canSuspend = Boolean( - activeManifest?.capabilities?.some((c) => c.toLowerCase() === 'vm-suspend') - || ( - activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('win32-mapped-ram-io')) - && activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('intel-whpx-suspend')) - && activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('reims-vgpu-snapshot-replay')) - ), - ) + const canSuspend = state?.can_suspend ?? false onTaskRef.current = (task: Task) => { if (task.kind === 'app-update' && task.status === 'failed' && !notifiedTasks.current.has(task.id)) { @@ -669,6 +661,7 @@ export const App: React.FC = () => { } const onVMActionFor = (name: string, action: VMAction, isRunning: boolean) => { + if (!canSuspend && (action === 'suspend' || action === 'resume')) return const activeBusy = activeVMBusy(name) if ( activeBusy @@ -905,7 +898,11 @@ export const App: React.FC = () => { useEffect(() => { const offSelect = events.onTraySelectVM((name) => { setSelected(name) }) const offNew = events.onTrayNewVM(() => { openWizardRef.current() }) - return () => { offSelect(); offNew() } + const offDiscard = events.onTrayDiscardSuspend((name) => { + setSelected(name) + setDiscardSuspendTarget(name) + }) + return () => { offSelect(); offNew(); offDiscard() } }, []) // Native Wails file drag-and-drop delivery into the selected VM's shared folder. @@ -1309,22 +1306,14 @@ export const App: React.FC = () => { )} {discardSuspendTarget && ( - setDiscardSuspendTarget(null)} - > -
-

{tr('discardSuspendDesc')}

-
-
- - - - - -
-
+ description={tr('discardSuspendDesc')} + cancelLabel={tr('cancel')} + confirmLabel={tr('discardSuspendConfirm')} + onCancel={() => setDiscardSuspendTarget(null)} + onConfirm={confirmDiscardSuspend} + /> )} {cloneSource && ( diff --git a/frontend/src/components/DeleteDialog.tsx b/frontend/src/components/DeleteDialog.tsx index fd2e4b8..50943b1 100644 --- a/frontend/src/components/DeleteDialog.tsx +++ b/frontend/src/components/DeleteDialog.tsx @@ -1,7 +1,7 @@ -import * as Alert from '@radix-ui/react-alert-dialog' import React, { useState } from 'react' import { t } from '../i18n' import { Locale } from '../types' +import { ConfirmDialog } from '../ui/dialog' interface Props { locale: Locale @@ -13,32 +13,18 @@ interface Props { export const DeleteDialog: React.FC = ({ locale, name, onCancel, onConfirm }) => { const [keepFiles, setKeepFiles] = useState(false) return ( - { if (!open) onCancel() }}> - - - -
- {t(locale, 'deleteTitle', { name })} - - {t(locale, keepFiles ? 'deleteDescKeep' : 'deleteDesc')} - - -
-
- - - - - - -
-
-
-
+ onConfirm(keepFiles)} + > + + ) } diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index c6bdd41..850dc2e 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -25,7 +25,7 @@ interface Props { selected: string hostReady: boolean /** Whether the active runtime supports VM suspend/resume. */ - canSuspend?: boolean + canSuspend: boolean onSelect: (id: string) => void /** VM name → display name (its note); empty or missing shows the name. */ displayNames?: Record @@ -164,9 +164,10 @@ export const Sidebar: React.FC = ({ )} {suspended && ( <> - onVMContextAction(vm.name, 'resume')}> + onVMContextAction(vm.name, 'resume')}> {tr('resume')} + {!canSuspend && {tr('resumeUnavailable')}} onVMContextAction(vm.name, 'discardSuspend')}> {tr('discardSuspend')} diff --git a/frontend/src/components/TitleMenus.tsx b/frontend/src/components/TitleMenus.tsx index 4253d95..477d11b 100644 --- a/frontend/src/components/TitleMenus.tsx +++ b/frontend/src/components/TitleMenus.tsx @@ -27,7 +27,7 @@ interface Props { canDark?: boolean onThemeMode: (mode: ThemeMode) => void /** The selected VM and its current state, or null on the system pages. */ - vm: { name: string; state: string; busy: boolean; graphics?: string; canSuspend?: boolean } | null + vm: { name: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean } | null onNewVM: () => void onVMAction: (action: VMAction) => void onVMSettings: () => void @@ -220,8 +220,9 @@ export const TitleMenus: React.FC = ({ {running ? item(tr('showWindow'), () => onVMAction('focus'), { shortcut: 'Ctrl+Enter', disabled: vmBusy }) : suspended - ? item(tr('resume'), () => onVMAction('resume'), { shortcut: 'Ctrl+Enter', disabled: vmBusy }) + ? item(tr('resume'), () => onVMAction('resume'), { shortcut: vm?.canSuspend ? 'Ctrl+Enter' : undefined, disabled: vmBusy || !vm?.canSuspend }) : item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })} + {suspended && !vm?.canSuspend && {tr('resumeUnavailable')}} {item(fullscreenLabel, () => onVMAction('fullscreen'), { disabled: vmBusy || !canFullscreen })} {item(tr('suspend'), () => onVMAction('suspend'), { disabled: vmBusy || !running || !vm?.canSuspend })} {item(tr('stop'), () => onVMAction('stop'), { disabled: vmBusy || !running })} diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index f42998f..cf1adb0 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -41,7 +41,7 @@ import { Upload, UserRound, } from 'lucide-react' -import React, { useEffect, useRef, useState } from 'react' +import React, { useEffect, useId, useRef, useState } from 'react' import { I18nKey, locText, t } from '../i18n' import { controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel, @@ -97,7 +97,7 @@ interface Props { macosMajor: number | null state: string /** Whether the active runtime supports VM suspend/resume. */ - canSuspend?: boolean + canSuspend: boolean /** Whether the native VM-window installation guide is currently active for this boot. */ guideActive: boolean /** Whether the builtin.install-guide plugin is enabled. */ @@ -144,6 +144,9 @@ export const VMPage: React.FC = ({ const busy = busyAction !== undefined const running = state === 'running' const suspended = state === 'suspended' + const guestToolsLocked = suspended || state === 'suspending' || state === 'resuming' + const resumeHintId = useId() + const guestToolsHintId = useId() const installing = !!detail && (detail.has_installer || detail.recovery_mode) const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming' // Polled here rather than in App so each tick re-renders only this page. @@ -338,17 +341,19 @@ export const VMPage: React.FC = ({ ) } else if (suspended) { primary = ( - - ) - secondary = ( - - ) } else if (state === 'starting') { primary = } else if (state === 'stopping') { @@ -444,11 +449,6 @@ export const VMPage: React.FC = ({ : <> {tr('enterFullscreen')}} )} - {canSuspend && ( - onAction('suspend')}> - {tr('suspend')} - - )} onAction('restart')}> {tr('restart')} @@ -644,7 +644,7 @@ export const VMPage: React.FC = ({ startLabel={suspended ? tr('resume') : tr('start')} showLabel={tr('showWindow')} shotLabel={tr('copyScreenshot')} - onStart={!busy && (state === 'stopped' || suspended) ? () => onAction(suspended ? 'resume' : 'start') : undefined} + onStart={!busy && (state === 'stopped' || (suspended && canSuspend)) ? () => onAction(suspended ? 'resume' : 'start') : undefined} onShow={running && !busy ? () => onAction('focus') : undefined} onScreenshot={running && !busy ? () => onAction('screenshot') : undefined} /> @@ -738,6 +738,7 @@ export const VMPage: React.FC = ({ ? tr('suspendedNoticeDescWithTime', { time: suspTime, size: suspSize }) : tr('suspendedNoticeDesc', { size: suspSize })}
+ {!canSuspend && {tr('resumeUnavailable')}}
@@ -933,6 +934,10 @@ export const VMPage: React.FC = ({ const needsUpgrade = gtConnected && (detail.guest_tools_agent_version ?? 0) > 0 && (detail.guest_tools_agent_version ?? 0) < 3 // Plugin switched off: show the state and hide controls that would only fail. const gtOff = !!detail.guest_tools_disabled + const gtAttached = detail.guest_tools_attached + const showToolsAction = !gtOff && (gtAttached || !gtConnected || needsUpgrade) + const toolsAction = gtAttached ? 'detachGuestTools' : 'attachGuestTools' + const toolsActionLabel = gtAttached ? 'detachGuestTools' : needsUpgrade ? 'gtUpdate' : 'gtInstall' // One status word per state; how files are shared goes in the tooltip. let gtTone: 'ok' | 'warn' | 'idle' = 'idle' @@ -1045,20 +1050,20 @@ export const VMPage: React.FC = ({
+ {suspended && showToolsAction && ( + {tr('suspendedGuestToolsHint')} + )}
- {gtOff ? null : detail.guest_tools_attached ? ( - - ) : (!gtConnected || needsUpgrade) && ( + {showToolsAction && ( )}
diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index 312faa3..1a97e4e 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -119,6 +119,7 @@ export const vmZh: Record = { "pickRecoveryTitle": "选择离线镜像(.img / .dmg)", "restartToApply": "重启以应用", "resume": "恢复", + "resumeUnavailable": "切换到支持挂起的内核后可恢复", "sendText": "发送文本到虚拟机…", "sendTextConfirm": "发送 (Ctrl+Enter)", "sendTextDesc": "支持中文、Emoji、宿主机输入法与语音输入,按 Ctrl+Enter 发送到 macOS 当前输入框。", @@ -171,6 +172,7 @@ export const vmZh: Record = { "state_suspended": "已挂起", "state_suspending": "挂起中", "suspend": "挂起", + "suspendedGuestToolsHint": "恢复或放弃挂起状态后可更改", "suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", "suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", "suspendedNoticeTitle": "已保存运行状态", @@ -333,6 +335,7 @@ export const vmEn: Record = { "pickRecoveryTitle": "Choose an offline image (.img / .dmg)", "restartToApply": "Restart to apply", "resume": "Resume", + "resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM", "sendText": "Send text to VM…", "sendTextConfirm": "Send (Ctrl+Enter)", "sendTextDesc": "Supports Chinese, emoji, host IME, and dictation. Press Ctrl+Enter to inject into the focused macOS field.", @@ -385,6 +388,7 @@ export const vmEn: Record = { "state_suspended": "Suspended", "state_suspending": "Suspending", "suspend": "Suspend", + "suspendedGuestToolsHint": "Resume or discard saved state to make changes", "suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.", "suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.", "suspendedNoticeTitle": "Saved state ready", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index ffd4062..9ee8854 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -625,6 +625,7 @@ export type I18nKey = | "restart" | "restartToApply" | "resume" + | "resumeUnavailable" | "runtimeAlpha" | "runtimeAlphaHint" | "runtimeChannel_alpha" @@ -786,6 +787,7 @@ export type I18nKey = | "summarySSHPort" | "summarySource" | "suspend" + | "suspendedGuestToolsHint" | "suspendedNoticeDesc" | "suspendedNoticeDescWithTime" | "suspendedNoticeTitle" diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 7e628f1..6710013 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -909,7 +909,6 @@ button.status-issue + .status-metric { margin-left: 6px; } .dialog-title { font-size: var(--fs-16); font-weight: var(--fw-strong); letter-spacing: -0.01em; text-wrap: balance; } .dialog-desc { font-size: var(--fs-13); color: var(--text-2); margin-top: 2px; } .dialog-body { padding: 20px 22px; overflow-y: auto; overscroll-behavior: contain; flex: 1; display: flex; flex-direction: column; gap: var(--sp-4); } -.dialog-body > .dialog-desc:only-child { margin-top: 0; } .dialog-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); } .dialog.sm .dialog-body { padding: 22px 22px 14px; gap: var(--sp-3); } .dialog.sm .dialog-foot { border-top: none; justify-content: flex-end; padding-top: 0; padding-bottom: 20px; } diff --git a/frontend/src/ui/dialog.tsx b/frontend/src/ui/dialog.tsx index 7ce95d4..16ddcdc 100644 --- a/frontend/src/ui/dialog.tsx +++ b/frontend/src/ui/dialog.tsx @@ -1,7 +1,37 @@ +import * as Alert from '@radix-ui/react-alert-dialog' import * as RDialog from '@radix-ui/react-dialog' import { X } from 'lucide-react' import React from 'react' -import { IconButton } from './controls' +import { Button, IconButton } from './controls' + +interface ConfirmDialogProps { + title: string + description: string + cancelLabel: string + confirmLabel: string + onCancel: () => void + onConfirm: () => void + children?: React.ReactNode +} + +export const ConfirmDialog: React.FC = ({ title, description, cancelLabel, confirmLabel, onCancel, onConfirm, children }) => ( + { if (!open) onCancel() }}> + + + +
+ {title} + {description} + {children} +
+
+ + +
+
+
+
+) interface Props { title: string diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index 184007d..182aaa8 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -180,6 +180,7 @@ export const events = { // Tray menu (internal/app/app.go trayVMAction): "Show in Reims-Go" and "New VM…". onTraySelectVM: (cb: (name: string) => void) => eventsOn('reims:tray-select-vm', cb), onTrayNewVM: (cb: () => void) => eventsOn('reims:tray-new-vm', cb), + onTrayDiscardSuspend: (cb: (name: string) => void) => eventsOn('reims:tray-discard-suspend', cb), // Renderer health watchdog & crash reporting (internal/app/ui_health.go). onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb), emitUIPong: () => eventsEmit('reims:ui-pong'), diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index bd48390..2423b4e 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -6,6 +6,7 @@ export namespace app { optimizations: host.Optimization[]; runtimes: runtime.Installed[]; active_runtime?: runtime.Installed; + can_suspend: boolean; vms: reims.VMListItem[]; transitions: Record; pending_changes: Record>; @@ -30,6 +31,7 @@ export namespace app { this.optimizations = this.convertValues(source["optimizations"], host.Optimization); this.runtimes = this.convertValues(source["runtimes"], runtime.Installed); this.active_runtime = this.convertValues(source["active_runtime"], runtime.Installed); + this.can_suspend = source["can_suspend"]; this.vms = this.convertValues(source["vms"], reims.VMListItem); this.transitions = source["transitions"]; this.pending_changes = this.convertValues(source["pending_changes"], Array, true); diff --git a/internal/app/app.go b/internal/app/app.go index f9a0183..9c035eb 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -43,6 +43,7 @@ type AppState struct { Optimizations []host.Optimization `json:"optimizations"` Runtimes []rt.Installed `json:"runtimes"` ActiveRuntime *rt.Installed `json:"active_runtime,omitempty"` + CanSuspend bool `json:"can_suspend"` VMs []reims.VMListItem `json:"vms"` Transitions map[string]string `json:"transitions"` PendingChanges map[string][]PendingChange `json:"pending_changes"` @@ -658,6 +659,7 @@ func (a *App) GetState() AppState { Optimizations: opts, Runtimes: runtimes, ActiveRuntime: active, + CanSuspend: active != nil && active.Manifest.HasCapability("vm-suspend"), VMs: vms, Transitions: trCopy, PendingChanges: pcCopy, @@ -852,7 +854,10 @@ func (a *App) trayVMAction(name string, act tray.Action) { case tray.ActResume: err, failTitle = a.ResumeVM(name), i18n.M(loc, "tray.notify.resume_fail", vars) case tray.ActDiscardSuspend: - err, failTitle = a.DiscardSuspend(name), i18n.M(loc, "tray.notify.discard_suspend_fail", vars) + a.ShowMainWindow() + if a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "reims:tray-discard-suspend", name) + } case tray.ActStop: err, failTitle = a.StopVM(name, false), i18n.M(loc, "tray.notify.stop_fail", vars) case tray.ActForceStop: diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index edc8c67..61dcba3 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -440,13 +440,14 @@ var catalog = map[Locale]map[string]string{ "toastSSHUserSaved": "已保存 SSH 用户名", "toastSaved": "已保存", "toastSavedNextStart": "已保存,下次启动生效", - "tray.menu.discard_suspend": "放弃挂起状态(&X)", + "tray.menu.discard_suspend": "放弃挂起状态…(&X)", "tray.menu.force_stop": "强制关机(&F)", "tray.menu.new_vm": "新建虚拟机(&N)…", "tray.menu.open_in_app": "在 Reims-Go 中查看(&V)", "tray.menu.quit": "退出 Reims-Go(&Q)", "tray.menu.restart": "重启(&R)", "tray.menu.resume": "恢复(&U)", + "tray.menu.resume_unavailable": "恢复(当前内核不支持挂起)", "tray.menu.screenshot": "复制屏幕截图(&C)", "tray.menu.shared_folder": "打开共享文件夹(&H)", "tray.menu.show": "显示 Reims-Go(&O)", @@ -973,13 +974,14 @@ var catalog = map[Locale]map[string]string{ "toastSSHUserSaved": "Saved SSH username", "toastSaved": "Saved", "toastSavedNextStart": "Saved — applies on next start", - "tray.menu.discard_suspend": "Discard Saved Stat&e", + "tray.menu.discard_suspend": "Discard Saved Stat&e…", "tray.menu.force_stop": "&Force Shut Down", "tray.menu.new_vm": "&New Virtual Machine…", "tray.menu.open_in_app": "Show in &Reims-Go", "tray.menu.quit": "&Quit Reims-Go", "tray.menu.restart": "&Restart", "tray.menu.resume": "Res&ume", + "tray.menu.resume_unavailable": "Resume (runtime lacks suspend support)", "tray.menu.screenshot": "&Copy Screenshot", "tray.menu.shared_folder": "Open S&hared Folder", "tray.menu.show": "&Show Reims-Go", diff --git a/internal/tray/tray.go b/internal/tray/tray.go index 4523320..41f3cbc 100644 --- a/internal/tray/tray.go +++ b/internal/tray/tray.go @@ -94,15 +94,17 @@ type menuEntry struct { } type texts struct { - show, newVM, quit string - start, stop, forceStop, restart, showWindow, shot string - suspend, resume, discardSuspend string - shared, openInApp string - running, stopped, suspended string - starting, stopping, suspending, resuming string - broken, unknown string + show, newVM, quit string + start, stop, forceStop, restart, showWindow, shot string + suspend, resume, discardSuspend string + shared, openInApp string + running, stopped, suspended string + starting, stopping, suspending, resuming string + broken, unknown string toggleFullscreen string + + resumeUnavailable string } func menuTexts(snap Snapshot) texts { @@ -140,6 +142,8 @@ func menuTexts(snap Snapshot) texts { unknown: i18n.T(loc, "tray.state.unknown"), toggleFullscreen: i18n.T(loc, "tray.menu.toggle_fullscreen"), + + resumeUnavailable: i18n.T(loc, "tray.menu.resume_unavailable"), } } @@ -199,7 +203,11 @@ func buildMenu(snap Snapshot) []menuEntry { case "suspended": dot, state = dotSuspended, t.suspended resume := cmd(ActResume, t.resume) - resume.Default = true + resume.Default = snap.CanSuspend + if !snap.CanSuspend { + resume.Label = t.resumeUnavailable + resume.Disabled = true + } sub = []menuEntry{ resume, cmd(ActDiscardSuspend, t.discardSuspend), sep, cmd(ActSharedFolder, t.shared), sep, diff --git a/internal/tray/tray_test.go b/internal/tray/tray_test.go index ced0237..b08ff95 100644 --- a/internal/tray/tray_test.go +++ b/internal/tray/tray_test.go @@ -72,6 +72,21 @@ func TestBuildMenuPerState(t *testing.T) { } } +func TestSuspendedVMWithoutCompatibleRuntime(t *testing.T) { + menu := buildMenu(Snapshot{LocaleZh: true, VMs: []VMItem{{Name: "macos-sleep", State: "suspended"}}}) + vm := findEntry(menu, "macos-sleep\t已挂起") + if vm == nil { + t.Fatal("suspended VM is missing from the tray menu") + } + resume := vm.Sub[0] + if resume.ID != vmCmd(0, ActResume) || !resume.Disabled || resume.Default || resume.Label != "恢复(当前内核不支持挂起)" { + t.Fatalf("resume should be disabled and explain why: %+v", resume) + } + if discard := vm.Sub[1]; discard.ID != vmCmd(0, ActDiscardSuspend) || discard.Disabled { + t.Fatalf("discard should remain available: %+v", discard) + } +} + func TestDecodeVMCmdRoundTrip(t *testing.T) { for i := 0; i < maxTrayVMs; i++ { for act := ActStart; act <= ActDiscardSuspend; act++ { diff --git a/locales/en-US/native.json b/locales/en-US/native.json index 0b80880..0fdcee5 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -409,7 +409,8 @@ "tray.menu.start": "&Start", "tray.menu.suspend": "Sus&pend", "tray.menu.resume": "Res&ume", - "tray.menu.discard_suspend": "Discard Saved Stat&e", + "tray.menu.resume_unavailable": "Resume (runtime lacks suspend support)", + "tray.menu.discard_suspend": "Discard Saved Stat&e…", "tray.menu.stop": "Shut &Down", "tray.menu.force_stop": "&Force Shut Down", "tray.menu.restart": "&Restart", diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index f5bfc2c..6f2f87e 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -51,6 +51,7 @@ "state_broken": "Error", "suspend": "Suspend", "resume": "Resume", + "resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM", "discardSuspend": "Discard saved state", "discardSuspendTitle": "Discard saved state for “{name}”?", "discardSuspendDesc": "Removes the saved memory and device state and returns the VM to powered off. Any unsaved work inside macOS will be lost and can’t be undone.", @@ -59,6 +60,7 @@ "suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.", "suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.", "suspendedSettingsHint": "Resume or discard saved state before changing settings", + "suspendedGuestToolsHint": "Resume or discard saved state to make changes", "toastSuspended": "{name} suspended", "toastResumed": "{name} resumed", "toastDiscardSuspend": "Discarded saved state for {name}", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index b36a181..91ce361 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -409,7 +409,8 @@ "tray.menu.start": "启动(&S)", "tray.menu.suspend": "挂起(&P)", "tray.menu.resume": "恢复(&U)", - "tray.menu.discard_suspend": "放弃挂起状态(&X)", + "tray.menu.resume_unavailable": "恢复(当前内核不支持挂起)", + "tray.menu.discard_suspend": "放弃挂起状态…(&X)", "tray.menu.stop": "关机(&D)", "tray.menu.force_stop": "强制关机(&F)", "tray.menu.restart": "重启(&R)", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index 3a68042..a8ab8f3 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -51,6 +51,7 @@ "state_broken": "出错", "suspend": "挂起", "resume": "恢复", + "resumeUnavailable": "切换到支持挂起的内核后可恢复", "discardSuspend": "放弃挂起状态", "discardSuspendTitle": "放弃「{name}」的挂起状态?", "discardSuspendDesc": "将删除已保存的内存与设备状态并回到关机状态,macOS 中尚未保存的工作会丢失,且无法撤销。", @@ -59,6 +60,7 @@ "suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", "suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", "suspendedSettingsHint": "请先恢复或放弃挂起状态后再修改配置", + "suspendedGuestToolsHint": "恢复或放弃挂起状态后可更改", "toastSuspended": "{name} 已挂起", "toastResumed": "{name} 已恢复", "toastDiscardSuspend": "已放弃 {name} 的挂起状态",