跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

qemu.go

1452 行 · 49.3 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package qemu
5
6import (
7 "bytes"
8 "context"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io/fs"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "regexp"
17 "runtime"
18 "slices"
19 "strconv"
20 "strings"
21 "sync"
22 "time"
23
24 "github.com/coreos/go-semver/semver"
25 "github.com/digitalocean/go-qemu/qmp"
26 "github.com/digitalocean/go-qemu/qmp/raw"
27 "github.com/docker/go-units"
28 "github.com/mattn/go-shellwords"
29 "github.com/sirupsen/logrus"
30
31 "github.com/lima-vm/lima/v2/pkg/fileutils"
32 "github.com/lima-vm/lima/v2/pkg/iso9660util"
33 "github.com/lima-vm/lima/v2/pkg/limatype"
34 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
35 "github.com/lima-vm/lima/v2/pkg/limayaml"
36 "github.com/lima-vm/lima/v2/pkg/networks"
37 "github.com/lima-vm/lima/v2/pkg/networks/usernet"
38 "github.com/lima-vm/lima/v2/pkg/osutil"
39 "github.com/lima-vm/lima/v2/pkg/qemuimgutil"
40 "github.com/lima-vm/lima/v2/pkg/store"
41)
42
43type Config struct {
44 Name string
45 InstanceDir string
46 LimaYAML *limatype.LimaYAML
47 SSHLocalPort int
48 SSHAddress string
49 VirtioGA bool
50 // UsernetQEMUSock is the QEMU socket of the instance's own gvisor
51 // netstack, used instead of slirp when set (see startUsernet).
52 UsernetQEMUSock string
53 // UsernetDgram is QEMU's end of a datagram socketpair whose other end the
54 // netstack serves, preferred to UsernetQEMUSock when QEMU has the dgram
55 // netdev (see dgramPair). Nil on Windows.
56 UsernetDgram *os.File
57}
58
59// minimumQemuVersion returns hardMin and softMin.
60//
61// hardMin is the hard minimum version of QEMU.
62// The driver immediately returns the error when QEMU is older than this version.
63//
64// softMin is the oldest recommended version of QEMU.
65// softMin must be >= hardMin.
66//
67// When updating this function, make sure to update
68// `website/content/en/docs/config/vmtype/qemu.md` too.
69func minimumQemuVersion() (hardMin, softMin semver.Version) {
70 var h, s string
71 switch runtime.GOOS {
72 case "darwin":
73 switch runtime.GOARCH {
74 case "arm64":
75 // https://gitlab.com/qemu-project/qemu/-/issues/1990
76 h, s = "8.2.1", "8.2.1"
77 default:
78 // The code specific to QEMU < 7.0 on macOS (https://github.com/lima-vm/lima/pull/703)
79 // was removed in https://github.com/lima-vm/lima/pull/3491
80 h, s = "7.0.0", "8.2.1"
81 }
82 case "windows":
83 h, s = "11.0.0", "11.0.0"
84 default:
85 // hardMin: Untested and maybe does not even work.
86 // softMin: Ubuntu 22.04's QEMU. The oldest version that can be easily tested on GitHub Actions.
87 h, s = "4.0.0", "6.2.0"
88 }
89 hardMin, softMin = *semver.New(h), *semver.New(s)
90 if softMin.LessThan(hardMin) {
91 // NOTREACHED
92 logrus.Fatalf("internal error: QEMU: soft minimum version %v must be >= hard minimum version %v",
93 softMin, hardMin)
94 }
95 return hardMin, softMin
96}
97
98// parseKVMNestedParam parses the `nested` module parameter of kvm_intel (bool: "Y"/"N") or kvm_amd (int: "1"/"0").
99func parseKVMNestedParam(s string) (bool, error) {
100 switch v := strings.TrimSpace(s); v {
101 case "Y", "y", "1":
102 return true, nil
103 case "N", "n", "0":
104 return false, nil
105 default:
106 return false, fmt.Errorf("unexpected value %#q of the `nested` parameter", v)
107 }
108}
109
110// EnsureDisk creates the VM disk from the downloaded image.
111// For ISO images, it renames the image to "iso" and creates an empty qcow2 disk.
112// For non-ISO images, it validates and renames the image to "disk".
113func EnsureDisk(ctx context.Context, cfg Config) error {
114 diskPath := filepath.Join(cfg.InstanceDir, filenames.Disk)
115 if _, err := os.Stat(diskPath); err == nil || !errors.Is(err, os.ErrNotExist) {
116 return err
117 }
118
119 imagePath := filepath.Join(cfg.InstanceDir, filenames.Image)
120 isISO, err := iso9660util.IsISO9660(imagePath)
121 if err != nil {
122 return err
123 }
124 imageInfo, err := qemuimgutil.GetInfo(ctx, imagePath)
125 if err != nil {
126 return fmt.Errorf("failed to get the information of %#q: %w", imagePath, err)
127 }
128 if err = qemuimgutil.AcceptableAsBaseDisk(imageInfo); err != nil {
129 return fmt.Errorf("file %#q is not acceptable as a disk image: %w", imagePath, err)
130 }
131 if imageInfo.Format == "" {
132 return fmt.Errorf("failed to inspect the format of %#q", imagePath)
133 }
134 if isISO {
135 isoPath := filepath.Join(cfg.InstanceDir, filenames.ISO)
136 if err = os.Rename(imagePath, isoPath); err != nil {
137 return err
138 }
139 diskSize, _ := units.RAMInBytes(*cfg.LimaYAML.Disk)
140 args := []string{"create", "-f", "qcow2", diskPath, strconv.Itoa(int(diskSize))}
141 cmd := exec.CommandContext(ctx, "qemu-img", args...)
142 if out, err := cmd.CombinedOutput(); err != nil {
143 _ = os.Rename(isoPath, imagePath)
144 return fmt.Errorf("failed to run %v: %#q: %w", cmd.Args, string(out), err)
145 }
146 } else {
147 if err = os.Rename(imagePath, diskPath); err != nil {
148 return err
149 }
150 }
151 return nil
152}
153
154func newQmpClient(cfg Config) (*qmp.SocketMonitor, error) {
155 qmpSock := filepath.Join(cfg.InstanceDir, filenames.QMPSock)
156 qmpClient, err := qmp.NewSocketMonitor("unix", qmpSock, 5*time.Second)
157 if err != nil {
158 return nil, err
159 }
160 return qmpClient, nil
161}
162
163func sendHmpCommand(cfg Config, cmd, tag string) (string, error) {
164 qmpClient, err := newQmpClient(cfg)
165 if err != nil {
166 return "", err
167 }
168 if err := qmpClient.Connect(); err != nil {
169 return "", err
170 }
171 defer func() { _ = qmpClient.Disconnect() }()
172 rawClient := raw.NewMonitor(qmpClient)
173 logrus.Infof("Sending HMP %s command", cmd)
174 hmc := fmt.Sprintf("%s %s", cmd, tag)
175 return rawClient.HumanMonitorCommand(hmc, nil)
176}
177
178func execImgCommand(ctx context.Context, cfg Config, args ...string) (string, error) {
179 diskPath := filepath.Join(cfg.InstanceDir, filenames.Disk)
180 args = append(args, diskPath)
181 logrus.Debugf("Running qemu-img %v command", args)
182 cmd := exec.CommandContext(ctx, "qemu-img", args...)
183 b, err := cmd.Output()
184 if err != nil {
185 return "", err
186 }
187 return string(b), err
188}
189
190func Del(ctx context.Context, cfg Config, run bool, tag string) error {
191 if run {
192 out, err := sendHmpCommand(cfg, "delvm", tag)
193 // there can still be output, even if no error!
194 if out != "" {
195 logrus.Warnf("output: %s", strings.TrimSpace(out))
196 }
197 return err
198 }
199 // -d deletes a snapshot
200 _, err := execImgCommand(ctx, cfg, "snapshot", "-d", tag)
201 return err
202}
203
204func Save(ctx context.Context, cfg Config, run bool, tag string) error {
205 if run {
206 out, err := sendHmpCommand(cfg, "savevm", tag)
207 // there can still be output, even if no error!
208 if out != "" {
209 logrus.Warnf("output: %s", strings.TrimSpace(out))
210 }
211 return err
212 }
213 // -c creates a snapshot
214 _, err := execImgCommand(ctx, cfg, "snapshot", "-c", tag)
215 return err
216}
217
218func Load(ctx context.Context, cfg Config, run bool, tag string) error {
219 if run {
220 out, err := sendHmpCommand(cfg, "loadvm", tag)
221 // there can still be output, even if no error!
222 if out != "" {
223 logrus.Warnf("output: %s", strings.TrimSpace(out))
224 }
225 return err
226 }
227 // -a applies a snapshot
228 _, err := execImgCommand(ctx, cfg, "snapshot", "-a", tag)
229 return err
230}
231
232// List returns a space-separated list of all snapshots, with header and newlines.
233func List(ctx context.Context, cfg Config, run bool) (string, error) {
234 if run {
235 out, err := sendHmpCommand(cfg, "info", "snapshots")
236 if err == nil {
237 out = strings.ReplaceAll(out, "\r", "")
238 out = strings.Replace(out, "List of snapshots present on all disks:\n", "", 1)
239 out = strings.Replace(out, "There is no snapshot available.\n", "", 1)
240 }
241 return out, err
242 }
243 // -l lists all snapshots
244 args := []string{"snapshot", "-l"}
245 out, err := execImgCommand(ctx, cfg, args...)
246 if err == nil {
247 // remove the redundant heading, result is not machine-parseable
248 out = strings.Replace(out, "Snapshot list:\n", "", 1)
249 }
250 return out, err
251}
252
253func argValue(args []string, key string) (string, bool) {
254 if !strings.HasPrefix(key, "-") {
255 panic(fmt.Errorf("got unexpected key %#q", key))
256 }
257 for i, s := range args {
258 if s == key {
259 if i == len(args)-1 {
260 return "", true
261 }
262 value := args[i+1]
263 if strings.HasPrefix(value, "-") {
264 return "", true
265 }
266 return value, true
267 }
268 }
269 return "", false
270}
271
272// appendArgsIfNoConflict can be used for: -cpu, -machine, -m, -boot ...
273// appendArgsIfNoConflict cannot be used for: -drive, -cdrom, ...
274func appendArgsIfNoConflict(args []string, k, v string) []string {
275 if !strings.HasPrefix(k, "-") {
276 panic(fmt.Errorf("got unexpected key %#q", k))
277 }
278 switch k {
279 case "-drive", "-cdrom", "-chardev", "-blockdev", "-netdev", "-device":
280 panic(fmt.Errorf("appendArgsIfNoConflict() must not be called with k=%#q", k))
281 }
282
283 if v == "" {
284 if _, ok := argValue(args, k); ok {
285 return args
286 }
287 return append(args, k)
288 }
289
290 if origV, ok := argValue(args, k); ok {
291 logrus.Warnf("Not adding QEMU argument %#q %#q, as it conflicts with %#q %#q", k, v, k, origV)
292 return args
293 }
294 return append(args, k, v)
295}
296
297type features struct {
298 // AccelHelp is the output of `qemu-system-x86_64 -accel help`
299 // e.g. "Accelerators supported in QEMU binary:\ntcg\nhax\nhvf\n"
300 // Not machine-readable, but checking strings.Contains() should be fine.
301 AccelHelp []byte
302 // NetdevHelp is the output of `qemu-system-x86_64 -netdev help`
303 // e.g. "Available netdev backend types:\nsocket\nhubport\ntap\nuser\nvde\nbridge\vhost-user\n"
304 // Not machine-readable, but checking strings.Contains() should be fine.
305 NetdevHelp []byte
306 // MachineHelp is the output of `qemu-system-x86_64 -machine help`
307 // e.g. "Supported machines are:\nakita...\n...virt-6.2...\n...virt-7.0...\n...\n"
308 // Not machine-readable, but checking strings.Contains() should be fine.
309 MachineHelp []byte
310 // CPUHelp is the output of `qemu-system-x86_64 -cpu help`
311 // e.g. "Available CPUs:\n...\nx86 base...\nx86 host...\n...\n"
312 // Not machine-readable, but checking strings.Contains() should be fine.
313 CPUHelp []byte
314}
315
316func inspectFeatures(ctx context.Context, exe, machine string) (*features, error) {
317 var f features
318 var err error
319 if f.AccelHelp, err = qemuHelp(ctx, exe, "-M", "none", "-accel", "help"); err != nil {
320 return nil, err
321 }
322 if f.NetdevHelp, err = qemuHelp(ctx, exe, "-M", "none", "-netdev", "help"); err != nil {
323 logrus.Warn(err)
324 }
325 if f.MachineHelp, err = qemuHelp(ctx, exe, "-machine", "help"); err != nil {
326 logrus.Warn(err)
327 }
328 // Avoid error: "No machine specified, and there is no default"
329 if f.CPUHelp, err = qemuHelp(ctx, exe, "-cpu", "help", "-machine", machine); err != nil {
330 logrus.Warn(err)
331 }
332 return &f, nil
333}
334
335// qemuHelp is what exe prints for args, a help request. Each one has its own
336// buffers: the features are searched as text, and one holding another's
337// output would match words that are not its own.
338func qemuHelp(ctx context.Context, exe string, args ...string) ([]byte, error) {
339 var stdout, stderr bytes.Buffer
340 cmd := exec.CommandContext(ctx, exe, args...)
341 cmd.Stdout = &stdout
342 cmd.Stderr = &stderr
343 if err := cmd.Run(); err != nil {
344 return nil, fmt.Errorf("failed to run %v: stdout=%#q, stderr=%#q", cmd.Args, stdout.String(), stderr.String())
345 }
346 // on older versions qemu will write "help" output to stderr
347 if stdout.Len() == 0 {
348 return stderr.Bytes(), nil
349 }
350 return stdout.Bytes(), nil
351}
352
353// adjustMemBytesDarwinARM64HVF adjusts the memory to be <= 3 GiB, only when the following conditions are met:
354//
355// - Host OS < macOS 12.4
356// - Host Arch == arm64
357// - Accel == hvf
358//
359// This adjustment is required for avoiding host kernel panic. The issue was fixed in macOS 12.4 Beta 1.
360// See https://github.com/lima-vm/lima/issues/795 https://gitlab.com/qemu-project/qemu/-/issues/903#note_911000975
361func adjustMemBytesDarwinARM64HVF(memBytes int64, accel string) int64 {
362 const safeSize = 3 * 1024 * 1024 * 1024 // 3 GiB
363 if memBytes <= safeSize {
364 return memBytes
365 }
366 if runtime.GOOS != "darwin" {
367 return memBytes
368 }
369 if runtime.GOARCH != "arm64" {
370 return memBytes
371 }
372 if accel != "hvf" {
373 return memBytes
374 }
375 macOSProductVersion, err := osutil.ProductVersion()
376 //nolint:staticcheck,nolintlint // SA4023: always true on Linux, but valid on macOS
377 if err != nil {
378 logrus.Warn(err)
379 return memBytes
380 }
381 if !macOSProductVersion.LessThan(*semver.New("12.4.0")) {
382 return memBytes
383 }
384 logrus.Warnf("Reducing the guest memory from %s to %s, to avoid host kernel panic on macOS <= 12.3; "+
385 "Please update macOS to 12.4 or later; "+
386 "See https://github.com/lima-vm/lima/issues/795 for the further background.",
387 units.BytesSize(float64(memBytes)), units.BytesSize(float64(safeSize)))
388 memBytes = safeSize
389 return memBytes
390}
391
392// qemuMachine returns string to use for -machine.
393func qemuMachine(arch limatype.Arch) string {
394 if arch == limatype.X8664 {
395 return "q35"
396 }
397 return "virt"
398}
399
400// audioDevice returns the default audio device.
401func audioDevice() string {
402 switch runtime.GOOS {
403 case "darwin":
404 return "coreaudio"
405 case "linux":
406 return "pa" // pulseaudio
407 case "windows":
408 return "dsound"
409 }
410 return "oss"
411}
412
413func defaultCPUType(qemuVersion *semver.Version) limatype.CPUType {
414 // x86_64 + TCG + max was previously unstable until 2021.
415 // https://bugzilla.redhat.com/show_bug.cgi?id=1999700
416 // https://bugs.launchpad.net/qemu/+bug/1748296
417 defaultX8664 := "max"
418 if runtime.GOOS == "windows" && runtime.GOARCH == "amd64" {
419 // https://github.com/lima-vm/lima/pull/3487#issuecomment-2846253560
420 // > #931 intentionally prevented the code from setting it to max when running on Windows,
421 // > and kept it at qemu64.
422 //
423 // TODO: remove this if "max" works with the latest qemu
424 defaultX8664 = "qemu64"
425 }
426 cpuType := map[limatype.Arch]string{
427 limatype.AARCH64: "max",
428 limatype.ARMV7L: "max",
429 limatype.X8664: defaultX8664,
430 limatype.PPC64LE: "max",
431 limatype.RISCV64: "max",
432 limatype.S390X: "max",
433 }
434 for arch := range cpuType {
435 if limatype.IsNativeArch(arch) && Accel(arch) != "tcg" {
436 if hasHostCPU(qemuVersion) {
437 cpuType[arch] = "host"
438 }
439 }
440 if arch == limatype.X8664 && runtime.GOOS == "darwin" {
441 // disable AVX-512, since it requires trapping instruction faults in guest
442 // Enterprise Linux requires either v2 (SSE4) or v3 (AVX2), but not yet v4.
443 cpuType[arch] += ",-avx512vl"
444
445 // Disable pdpe1gb on Intel Mac
446 // https://github.com/lima-vm/lima/issues/1485
447 // https://stackoverflow.com/a/72863744/5167443
448 cpuType[arch] += ",-pdpe1gb"
449 }
450 }
451 return cpuType
452}
453
454func resolveCPUType(y *limatype.LimaYAML, qemuVersion *semver.Version) string {
455 cpuType := defaultCPUType(qemuVersion)
456 var overrideCPUType bool
457 var qemuOpts limatype.QEMUOpts
458 if err := limayaml.Convert(y.VMOpts[limatype.QEMU], &qemuOpts, "vmOpts.qemu"); err != nil {
459 logrus.WithError(err).Warnf("Couldn't convert %#q", y.VMOpts[limatype.QEMU])
460 }
461 // WHPX uses qemu64 when host passthrough is unavailable. Preserve an
462 // explicit CPU model, including an explicitly requested bare qemu64.
463 if cpuType[*y.Arch] == "qemu64" && qemuOpts.CPUType[*y.Arch] == "" {
464 cpuType[*y.Arch] = whpxQEMU64()
465 }
466 for k, v := range qemuOpts.CPUType {
467 if !slices.Contains(limatype.ArchTypes, *y.Arch) {
468 logrus.Warnf("field `vmOpts.qemu.cpuType` uses unsupported arch %#q", k)
469 continue
470 }
471 if v != "" {
472 overrideCPUType = true
473 cpuType[k] = v
474 }
475 }
476 if overrideCPUType {
477 qemuOpts.CPUType = cpuType
478 if y.VMOpts == nil {
479 y.VMOpts = limatype.VMOpts{}
480 }
481 y.VMOpts[limatype.QEMU] = qemuOpts
482 }
483
484 return cpuType[*y.Arch]
485}
486
487func Cmdline(ctx context.Context, cfg Config) (exe string, args []string, err error) {
488 return cmdline(ctx, cfg, nil)
489}
490
491func cmdline(ctx context.Context, cfg Config, workingDir *string) (exe string, args []string, err error) {
492 y := cfg.LimaYAML
493 exe, args, err = Exe(*y.Arch)
494 if err != nil {
495 return "", nil, err
496 }
497
498 features, err := inspectFeatures(ctx, exe, qemuMachine(*y.Arch))
499 if err != nil {
500 return "", nil, err
501 }
502
503 version, err := getQemuVersion(ctx, exe)
504 if err != nil {
505 logrus.WithError(err).Warning("Failed to detect QEMU version")
506 } else {
507 logrus.Debugf("QEMU version %s detected", version.String())
508 hardMin, softMin := minimumQemuVersion()
509 if version.LessThan(hardMin) {
510 logrus.Fatalf("QEMU %v is too old, %v or later required", version, hardMin)
511 }
512 if version.LessThan(softMin) {
513 logrus.Warnf("QEMU %v is too old, %v or later is recommended", version, softMin)
514 }
515 var qemuOpts limatype.QEMUOpts
516 if err := limayaml.Convert(y.VMOpts[limatype.QEMU], &qemuOpts, "vmOpts.qemu"); err != nil {
517 logrus.WithError(err).Warnf("Couldn't convert %#q", y.VMOpts[limatype.QEMU])
518 }
519 if qemuOpts.MinimumVersion != nil && version.LessThan(*semver.New(*qemuOpts.MinimumVersion)) {
520 logrus.Fatalf("QEMU %v is too old, template requires %#q or later", version, *qemuOpts.MinimumVersion)
521 }
522 }
523
524 // Architecture
525 accel := Accel(*y.Arch)
526 if !strings.Contains(string(features.AccelHelp), accel) {
527 return "", nil, fmt.Errorf("accelerator %#q is not supported by %s", accel, exe)
528 }
529
530 // Memory
531 memBytes, err := units.RAMInBytes(*y.Memory)
532 if err != nil {
533 return "", nil, err
534 }
535 memBytes = adjustMemBytesDarwinARM64HVF(memBytes, accel)
536 args = appendArgsIfNoConflict(args, "-m", strconv.Itoa(int(memBytes>>20)))
537 // A balloon returns guest pages to the host without restarting the VM.
538 if *y.OS == limatype.LINUX {
539 args = append(args, "-device", "virtio-balloon")
540 }
541
542 if *y.MountType == limatype.VIRTIOFS {
543 args = appendArgsIfNoConflict(args, "-object",
544 fmt.Sprintf("memory-backend-file,id=virtiofs-shm,size=%s,mem-path=/dev/shm,share=on", strconv.Itoa(int(memBytes))))
545 args = appendArgsIfNoConflict(args, "-numa", "node,memdev=virtiofs-shm")
546 }
547
548 // CPU
549 cpu := resolveCPUType(y, version)
550 if runtime.GOOS == "darwin" && runtime.GOARCH == "amd64" {
551 switch {
552 case strings.HasPrefix(cpu, "host"), strings.HasPrefix(cpu, "max"):
553 if !strings.Contains(cpu, ",-pdpe1gb") {
554 logrus.Warnf("On Intel Mac, CPU type %#q typically needs `,-pdpe1gb` option (https://stackoverflow.com/a/72863744/5167443)", cpu)
555 }
556 }
557 }
558 // `qemu-system-ppc64 -help` does not show "max", but it is actually accepted
559 if cpu != "max" && !strings.Contains(string(features.CPUHelp), strings.Split(cpu, ",")[0]) {
560 return "", nil, fmt.Errorf("cpu %#q is not supported by %s", cpu, exe)
561 }
562 args = appendArgsIfNoConflict(args, "-cpu", cpu)
563
564 // Nested virtualization
565 nestedVirtEnabled := false
566 if y.NestedVirtualization != nil && *y.NestedVirtualization {
567 var err error
568 nestedVirtEnabled, err = nestedVirtualizationEnabled(*y.Arch, accel, cpu, version)
569 if err != nil {
570 return "", nil, err
571 }
572 }
573
574 // Machine
575 switch *y.Arch {
576 case limatype.X8664:
577 switch accel {
578 case "tcg":
579 // use q35 machine with vmware io port disabled.
580 args = appendArgsIfNoConflict(args, "-machine", "q35,vmport=off")
581 // use tcg accelerator with multi threading with 512MB translation block size
582 // https://qemu-project.gitlab.io/qemu/devel/multi-thread-tcg.html?highlight=tcg
583 // https://qemu-project.gitlab.io/qemu/system/invocation.html?highlight=tcg%20opts
584 // this will make sure each vCPU will be backed by 1 host user thread.
585 args = appendArgsIfNoConflict(args, "-accel", "tcg,thread=multi,tb-size=512")
586 // This will disable CPU S3/S4 state.
587 args = append(args, "-global", "ICH9-LPC.disable_s3=1")
588 args = append(args, "-global", "ICH9-LPC.disable_s4=1")
589 default:
590 args = appendQ35Machine(args, accel)
591 }
592 case limatype.AARCH64:
593 machine := "virt,accel=" + accel
594 if nestedVirtEnabled {
595 machine += ",virtualization=on"
596 }
597 args = appendArgsIfNoConflict(args, "-machine", machine)
598 case limatype.RISCV64:
599 // https://github.com/tianocore/edk2/blob/edk2-stable202408/OvmfPkg/RiscVVirt/README.md#test
600 // > Note: the `acpi=off` machine property is specified because Linux guest
601 // > support for ACPI (that is, the ACPI consumer side) is a work in progress.
602 // > Currently, `acpi=off` is recommended unless you are developing ACPI support
603 // > yourself.
604 machine := "virt,acpi=off,accel=" + accel
605 args = appendArgsIfNoConflict(args, "-machine", machine)
606 case limatype.ARMV7L:
607 machine := "virt,accel=" + accel
608 args = appendArgsIfNoConflict(args, "-machine", machine)
609 case limatype.PPC64LE:
610 machine := "pseries,accel=" + accel
611 args = appendArgsIfNoConflict(args, "-machine", machine)
612 case limatype.S390X:
613 machine := "s390-ccw-virtio,accel=" + accel
614 args = appendArgsIfNoConflict(args, "-machine", machine)
615 }
616
617 // SMP
618 args = appendArgsIfNoConflict(args, "-smp",
619 fmt.Sprintf("%d,sockets=1,cores=%d,threads=1", *y.CPUs, *y.CPUs))
620
621 // Firmware
622 legacyBIOS := *y.Firmware.LegacyBIOS
623 if legacyBIOS && *y.Arch != limatype.X8664 && *y.Arch != limatype.ARMV7L {
624 logrus.Warnf("field `firmware.legacyBIOS` is not supported for architecture %#q, ignoring", *y.Arch)
625 legacyBIOS = false
626 }
627 noFirmware := *y.Arch == limatype.PPC64LE || *y.Arch == limatype.S390X || legacyBIOS
628 if !noFirmware {
629 var firmware string
630 downloadedFirmware := filepath.Join(cfg.InstanceDir, filenames.QemuEfiCodeFD)
631 if _, stErr := os.Stat(downloadedFirmware); errors.Is(stErr, os.ErrNotExist) {
632 loop:
633 for _, f := range y.Firmware.Images {
634 switch f.VMType {
635 case "", limatype.QEMU:
636 if f.Arch == *y.Arch {
637 if _, err = fileutils.DownloadFile(ctx, downloadedFirmware, f.File, true, "UEFI code "+f.Location, *y.Arch, nil); err != nil {
638 logrus.WithError(err).Warnf("failed to download %#q", f.Location)
639 continue loop
640 }
641 firmware = downloadedFirmware
642 logrus.Infof("Using firmware %#q (downloaded from %#q)", firmware, f.Location)
643 break loop
644 }
645 }
646 }
647 } else {
648 firmware = downloadedFirmware
649 logrus.Infof("Using existing firmware (%#q)", firmware)
650 }
651 if firmware == "" {
652 firmware, err = getFirmware(exe, *y.Arch)
653 if err != nil {
654 return "", nil, err
655 }
656 logrus.Infof("Using system firmware (%#q)", firmware)
657 }
658 if firmware != "" {
659 if runtime.GOOS == "windows" && workingDir != nil {
660 firmware, *workingDir = windowsFirmwareArgument(firmware)
661 }
662 // Commas in -drive filenames are escaped by doubling them.
663 args = append(args, "-drive", "if=pflash,format=raw,readonly=on,file="+strings.ReplaceAll(firmware, ",", ",,"))
664 }
665 }
666
667 // Disk
668 diskPath := filepath.Join(cfg.InstanceDir, filenames.Disk)
669 isoPath := filepath.Join(cfg.InstanceDir, filenames.ISO)
670 extraDisks := []string{}
671 for _, d := range y.AdditionalDisks {
672 diskName := d.Name
673 disk, err := store.InspectDisk(diskName, d.FSType)
674 if err != nil {
675 logrus.Errorf("could not load disk %#q: %#q", diskName, err)
676 return "", nil, err
677 }
678
679 logrus.Infof("Mounting disk %#q on %#q", diskName, disk.MountPoint)
680 if err = disk.LockForInstance(cfg.InstanceDir); err != nil {
681 logrus.Errorf("could not attach disk %#q: %s", diskName, err)
682 return "", nil, err
683 }
684 dataDisk := filepath.Join(disk.Dir, filenames.DataDisk)
685 extraDisks = append(extraDisks, dataDisk)
686 }
687
688 virtioBlk := "virtio-blk-pci"
689 if *y.Arch == limatype.S390X {
690 // s390x uses CCW bus, not PCI
691 virtioBlk = "virtio-blk-ccw"
692 }
693
694 args = append(args, "-device", "qemu-xhci,id=usb-bus")
695
696 isoPresent := osutil.FileExists(isoPath)
697 if osutil.FileExists(diskPath) {
698 if isoPresent {
699 args = append(args, "-drive", fmt.Sprintf("file=%s,if=virtio,discard=on", diskPath))
700 } else {
701 // bootindex=1 fixes non-deterministic boot order when extra disks are present (#4936)
702 args = append(args, "-drive", fmt.Sprintf("file=%s,if=none,discard=on,id=boot-disk", diskPath))
703 args = append(args, "-device", fmt.Sprintf("%s,drive=boot-disk,bootindex=1", virtioBlk))
704 }
705 }
706 if isoPresent {
707 args = appendArgsIfNoConflict(args, "-boot", "order=d,splash-time=0,menu=on")
708 switch *y.OS {
709 case limatype.WINDOWS:
710 // We don't mount the ISO file if the Windows VM was already created before.
711 if isWindowsBootDone(cfg) {
712 break
713 }
714 // For aarch64, QEMU uses `virt` machine type but it doesn't recognize CDROM drive.
715 // In order to attach ISO files, we need to use USB devices instead.
716 if *y.Arch == limatype.AARCH64 {
717 args = append(args, "-device", "usb-kbd")
718 args = append(args, "-drive", fmt.Sprintf("file=%s,if=none,id=cd0,format=raw,media=cdrom,readonly=on", isoPath))
719 args = append(args, "-device", "usb-storage,drive=cd0")
720 } else {
721 args = append(args, "-drive", fmt.Sprintf("file=%s,format=raw,media=cdrom,readonly=on", isoPath))
722 }
723 default:
724 args = append(args, "-drive", fmt.Sprintf("file=%s,format=raw,media=cdrom,readonly=on", isoPath))
725 }
726 } else {
727 args = appendArgsIfNoConflict(args, "-boot", "order=c,splash-time=0,menu=on")
728 }
729
730 var winOpts limatype.WindowsOpts
731 if err := limayaml.Convert(y.OsOpts[limatype.WINDOWS], &winOpts, "osOpts.Windows"); err != nil {
732 return "", nil, err
733 }
734
735 // virtio-win must be mounted before cidata.iso otherwise
736 // autounattend.xml can't find virtio drivers.
737 // The ISO file is not mounted if the VM was already created.
738 if *y.OS == limatype.WINDOWS && len(winOpts.VirtioWin) > 0 && !isWindowsBootDone(cfg) {
739 if *y.Arch == limatype.AARCH64 {
740 args = append(args, "-drive", fmt.Sprintf("file=%s,if=none,id=cd1,format=raw,media=cdrom,readonly=on", filepath.Join(cfg.InstanceDir, filenames.VirtioWin)))
741 args = append(args, "-device", "usb-storage,drive=cd1")
742 } else {
743 args = append(args, "-drive", fmt.Sprintf("file=%s,format=raw,media=cdrom,readonly=on", filepath.Join(cfg.InstanceDir, filenames.VirtioWin)))
744 }
745 }
746
747 for _, extraDisk := range extraDisks {
748 args = append(args, "-drive", fmt.Sprintf("file=%s,if=virtio,discard=on", extraDisk))
749 }
750
751 // cloud-init
752 switch *y.OS {
753 case limatype.WINDOWS:
754 // cidata for Windows is not mounted if the VM was already created.
755 if isWindowsBootDone(cfg) {
756 break
757 }
758 // We can't use virtio-scsi for Windows's cidata, because autounattend in cidata installs virtio-win drivers.
759 // Until then, the VM can't detect virtio.
760 if *y.Arch == limatype.AARCH64 {
761 args = append(args, "-drive", fmt.Sprintf("file=%s,if=none,id=cd2,format=raw,media=cdrom,readonly=on", filepath.Join(cfg.InstanceDir, filenames.CIDataISO)))
762 args = append(args, "-device", "usb-storage,drive=cd2")
763 } else {
764 args = append(args, "-drive", fmt.Sprintf("file=%s,format=raw,media=cdrom,readonly=on", filepath.Join(cfg.InstanceDir, filenames.CIDataISO)))
765 }
766 default:
767 args = append(args,
768 "-drive", "id=cdrom0,if=none,format=raw,readonly=on,file="+filepath.Join(cfg.InstanceDir, filenames.CIDataISO),
769 "-device", "virtio-scsi,id=scsi0",
770 "-device", "scsi-cd,bus=scsi0.0,drive=cdrom0")
771 }
772
773 // Kernel
774 kernel := filepath.Join(cfg.InstanceDir, filenames.Kernel)
775 kernelCmdline := filepath.Join(cfg.InstanceDir, filenames.KernelCmdline)
776 initrd := filepath.Join(cfg.InstanceDir, filenames.Initrd)
777 if _, err := os.Stat(kernel); err == nil {
778 args = appendArgsIfNoConflict(args, "-kernel", kernel)
779 }
780 if b, err := os.ReadFile(kernelCmdline); err == nil {
781 args = appendArgsIfNoConflict(args, "-append", string(b))
782 }
783 if _, err := os.Stat(initrd); err == nil {
784 args = appendArgsIfNoConflict(args, "-initrd", initrd)
785 }
786
787 // TPM emulation.
788 if *y.TPM {
789 swtpmSock := filepath.Join(cfg.InstanceDir, filenames.SwtpmSock)
790 args = append(args, "-chardev", fmt.Sprintf("socket,id=chrtpm,path=%s", swtpmSock))
791 args = append(args, "-tpmdev", "emulator,id=tpm0,chardev=chrtpm")
792
793 var tpmDevice string
794 switch *y.Arch {
795 case limatype.X8664:
796 tpmDevice = "tpm-crb"
797 case limatype.AARCH64, limatype.ARMV7L, limatype.RISCV64:
798 tpmDevice = "tpm-tis-device"
799 default:
800 return "", nil, fmt.Errorf("TPM is not supported for architecture %#q", *y.Arch)
801 }
802 args = append(args, "-device", tpmDevice+",tpmdev=tpm0")
803 }
804
805 // Network
806 // Configure default usernetwork with limayaml.MACAddress(driver.Instance.Dir) for eth0 interface
807 firstUsernetIndex := limayaml.FirstUsernetIndex(y)
808 switch {
809 case firstUsernetIndex == -1 && cfg.UsernetQEMUSock != "" && runtime.GOOS == "windows":
810 // No file descriptor passing there (fd_connect): QEMU connects to the
811 // socket itself, which QEMU 7.2 or later can on Windows. The same
812 // stream as the socket netdev's, so the same abort on EAGAIN (see the
813 // dgram netdev below): Windows has no datagram unix sockets.
814 if !strings.Contains(string(features.NetdevHelp), "stream") {
815 return "", nil, errors.New("QEMU 7.2 or later is needed (its stream netdev)")
816 }
817 args = append(args, "-netdev", fmt.Sprintf("stream,id=net0,server=off,addr.type=unix,addr.path=%s", cfg.UsernetQEMUSock))
818 case firstUsernetIndex == -1 && cfg.UsernetDgram != nil && strings.Contains(string(features.NetdevHelp), "dgram"):
819 // Not the socket netdev below: it reads a length-prefixed stream, and
820 // QEMU (10.2.4 at least) aborts with `net_fill_rstate: Assertion
821 // 'size == 0' failed` when its recv() returns EAGAIN, which it
822 // meant to ignore (net_socket_send, and net_stream_data_send for the
823 // stream netdev, fall through to net_fill_rstate with size -1).
824 // Seen on Linux hosts, under sustained guest traffic. The dgram
825 // netdev ignores a failed recv() and has no framing to lose. It
826 // needs QEMU 7.2 or later.
827 args = append(args, "-netdev", "dgram,id=net0,local.type=fd,local.str={{ fd_dgram }}")
828 case firstUsernetIndex == -1 && cfg.UsernetQEMUSock != "":
829 args = append(args, "-netdev", fmt.Sprintf("socket,id=net0,fd={{ fd_connect %q }}", cfg.UsernetQEMUSock))
830 case firstUsernetIndex == -1:
831 args = append(args, "-netdev", fmt.Sprintf("user,id=net0,net=%s,dhcpstart=%s,hostfwd=tcp:%s:%d-:22",
832 networks.SlirpNetwork, networks.SlirpIPAddress, cfg.SSHAddress, cfg.SSHLocalPort))
833 default:
834 qemuSock, err := usernet.Sock(y.Networks[firstUsernetIndex].Lima, usernet.QEMUSock)
835 if err != nil {
836 return "", nil, err
837 }
838 args = append(args, "-netdev", fmt.Sprintf("socket,id=net0,fd={{ fd_connect %q }}", qemuSock))
839 }
840 virtioNet := "virtio-net-pci"
841 if *y.Arch == limatype.S390X {
842 // virtio-net-pci does not work on EL, while it works on Ubuntu
843 // https://github.com/lima-vm/lima/pull/3319/files#r1986388345
844 virtioNet = "virtio-net-ccw"
845 }
846 args = append(args, "-device", virtioNet+",netdev=net0,mac="+limayaml.MACAddress(cfg.InstanceDir))
847
848 for i, nw := range y.Networks {
849 if nw.Lima != "" {
850 nwCfg, err := networks.LoadConfig()
851 if err != nil {
852 return "", nil, err
853 }
854
855 // Handle usernet connections
856 isUsernet, err := nwCfg.Usernet(nw.Lima)
857 if err != nil {
858 return "", nil, err
859 }
860 if isUsernet {
861 if i == firstUsernetIndex {
862 continue
863 }
864 qemuSock, err := usernet.Sock(nw.Lima, usernet.QEMUSock)
865 if err != nil {
866 return "", nil, err
867 }
868 args = append(args, "-netdev", fmt.Sprintf("socket,id=net%d,fd={{ fd_connect %q }}", i+1, qemuSock))
869 args = append(args, "-device", fmt.Sprintf("%s,netdev=net%d,mac=%s", virtioNet, i+1, nw.MACAddress))
870 } else {
871 if runtime.GOOS != "darwin" {
872 return "", nil, fmt.Errorf("networks.yaml '%s' configuration is only supported on macOS right now", nw.Lima)
873 }
874 logrus.Debugf("Using socketVMNet (%#q)", nwCfg.Paths.SocketVMNet)
875 sock, err := networks.Sock(nw.Lima)
876 if err != nil {
877 return "", nil, err
878 }
879 if strings.Contains(string(features.NetdevHelp), "stream") {
880 netdev := fmt.Sprintf("stream,id=net%d,server=off,addr.type=unix,addr.path=%s", i+1, sock)
881 if !version.LessThan(*semver.New("9.2.0")) {
882 netdev += ",reconnect-ms=500"
883 } else if !version.LessThan(*semver.New("8.0.0")) {
884 netdev += ",reconnect=1"
885 }
886 args = append(args, "-netdev", netdev)
887 } else {
888 args = append(args, "-netdev", fmt.Sprintf("socket,id=net%d,fd={{ fd_connect %q }}", i+1, sock))
889 }
890 }
891 } else if nw.Socket != "" {
892 args = append(args, "-netdev", fmt.Sprintf("socket,id=net%d,fd={{ fd_connect %q }}", i+1, nw.Socket))
893 } else {
894 return "", nil, fmt.Errorf("invalid network spec %+v", nw)
895 }
896 args = append(args, "-device", fmt.Sprintf("%s,netdev=net%d,mac=%s", virtioNet, i+1, nw.MACAddress))
897 }
898
899 // virtio-rng-pci accelerates starting up the OS, according to https://wiki.gentoo.org/wiki/QEMU/Options
900 args = append(args, "-device", "virtio-rng-pci")
901
902 // Input
903 input := "mouse"
904
905 // Sound
906 if y.Audio.Device != nil && y.Audio.Interface != nil {
907 audioDev := *y.Audio.Device
908 audioInterface := *y.Audio.Interface
909
910 if audioDev == "" || audioDev == "none" {
911 args = append(args, "-audiodev", "none,id=snd0")
912 } else {
913 if audioDev == "default" {
914 audioDev = audioDevice()
915 }
916 args = append(args, "-audiodev", fmt.Sprintf("%s,id=snd0", audioDev))
917 if audioInterface == "" {
918 audioInterface = "hda"
919 }
920 switch audioInterface {
921 case "virtio":
922 minVirtioVersion := semver.New("8.2.0")
923 if version.LessThan(*minVirtioVersion) {
924 logrus.Warnf("virtio-sound requires QEMU 8.2.0 or newer. Falling back to intel-hda.")
925 // We append the HDA hardware directly here instead of mutating the variable
926 args = append(args, "-device", "ich9-intel-hda", "-device", "hda-output,audiodev=snd0")
927 } else {
928 args = append(args, "-device", "virtio-sound-pci,audiodev=snd0")
929 }
930 case "hda":
931 args = append(args,
932 "-device", "ich9-intel-hda",
933 "-device", "hda-output,audiodev=snd0",
934 )
935 default:
936 return "", nil, fmt.Errorf("unknown audio.interface %q", audioInterface)
937 }
938 }
939 }
940 // Graphics
941 if *y.Video.Display != "" {
942 display := *y.Video.Display
943 if display == "vnc" {
944 display += "=" + *y.Video.VNC.Display
945 display += ",password=on"
946 // use tablet to avoid double cursors
947 input = "tablet"
948 }
949 args = appendArgsIfNoConflict(args, "-display", display)
950 }
951
952 if *y.Video.Display != "none" {
953 switch *y.Arch {
954 // FIXME: use virtio-gpu on all the architectures
955 case limatype.X8664, limatype.RISCV64:
956 args = append(args, "-device", "virtio-vga")
957 default:
958 if *y.OS == limatype.WINDOWS {
959 args = append(args, "-device", "ramfb")
960 } else {
961 args = append(args, "-device", "virtio-gpu")
962 }
963 }
964 args = append(args, "-device", "virtio-keyboard-pci")
965 args = append(args, "-device", "virtio-"+input+"-pci")
966 } else {
967 // Suppress any machine-default VGA adapter so the guest needs no VGA
968 // ROM. Only x86_64's q35/pc attach one (a std-vga needing
969 // vgabios-stdvga.bin); on other architectures this is a no-op.
970 args = append(args, "-vga", "none")
971 }
972
973 // Parallel
974 args = append(args, "-parallel", "none")
975
976 // Serial (default)
977 // This is ttyS0 for Intel and RISC-V, ttyAMA0 for ARM.
978 serialSock := filepath.Join(cfg.InstanceDir, filenames.SerialSock)
979 if err := os.RemoveAll(serialSock); err != nil {
980 return "", nil, err
981 }
982 serialLog := filepath.Join(cfg.InstanceDir, filenames.SerialLog)
983 if err := os.RemoveAll(serialLog); err != nil {
984 return "", nil, err
985 }
986 const serialChardev = "char-serial"
987 args = append(args, "-chardev", fmt.Sprintf("socket,id=%s,path=%s,server=on,wait=off,logfile=%s", serialChardev, serialSock, serialLog))
988 args = append(args, "-serial", "chardev:"+serialChardev)
989
990 // Serial (PCI, ARM only)
991 // On ARM, the default serial is ttyAMA0, this PCI serial is ttyS0.
992 // https://gitlab.com/qemu-project/qemu/-/issues/1801#note_1494720586
993 switch *y.Arch {
994 case limatype.AARCH64, limatype.ARMV7L:
995 serialpSock := filepath.Join(cfg.InstanceDir, filenames.SerialPCISock)
996 if err := os.RemoveAll(serialpSock); err != nil {
997 return "", nil, err
998 }
999 serialpLog := filepath.Join(cfg.InstanceDir, filenames.SerialPCILog)
1000 if err := os.RemoveAll(serialpLog); err != nil {
1001 return "", nil, err
1002 }
1003 const serialpChardev = "char-serial-pci"
1004 args = append(args, "-chardev", fmt.Sprintf("socket,id=%s,path=%s,server=on,wait=off,logfile=%s", serialpChardev, serialpSock, serialpLog))
1005 args = append(args, "-device", "pci-serial,chardev="+serialpChardev)
1006 }
1007
1008 // Serial (virtio)
1009 // Skip it for Windows guest because we encountered a problem around vioser.sys.
1010 if *y.OS != limatype.WINDOWS {
1011 serialvSock := filepath.Join(cfg.InstanceDir, filenames.SerialVirtioSock)
1012 if err := os.RemoveAll(serialvSock); err != nil {
1013 return "", nil, err
1014 }
1015 serialvLog := filepath.Join(cfg.InstanceDir, filenames.SerialVirtioLog)
1016 if err := os.RemoveAll(serialvLog); err != nil {
1017 return "", nil, err
1018 }
1019 const serialvChardev = "char-serial-virtio"
1020 args = append(args, "-chardev", fmt.Sprintf("socket,id=%s,path=%s,server=on,wait=off,logfile=%s", serialvChardev, serialvSock, serialvLog))
1021 // max_ports=1 is required for https://github.com/lima-vm/lima/issues/1689 https://github.com/lima-vm/lima/issues/1691
1022 serialvMaxPorts := 1
1023 if *y.Arch == limatype.S390X {
1024 serialvMaxPorts++ // needed to avoid `virtio-serial-bus: Out-of-range port id specified, max. allowed: 0`
1025 }
1026 args = append(args, "-device", fmt.Sprintf("virtio-serial-pci,id=virtio-serial0,max_ports=%d", serialvMaxPorts))
1027 args = append(args, "-device", fmt.Sprintf("virtconsole,chardev=%s,id=console0", serialvChardev))
1028 }
1029
1030 // We also want to enable vsock here, but QEMU does not support vsock for macOS hosts
1031
1032 if *y.MountType == limatype.NINEP || *y.MountType == limatype.VIRTIOFS {
1033 for i, f := range y.Mounts {
1034 tag := limayaml.MountTag(f.Location, *f.MountPoint)
1035 if err := os.MkdirAll(f.Location, 0o755); err != nil {
1036 return "", nil, err
1037 }
1038
1039 switch *y.MountType {
1040 case limatype.NINEP:
1041 options := "local"
1042 options += fmt.Sprintf(",mount_tag=%s", tag)
1043 options += fmt.Sprintf(",path=%s", f.Location)
1044 options += fmt.Sprintf(",security_model=%s", *f.NineP.SecurityModel)
1045 if !*f.Writable {
1046 options += ",readonly=on"
1047 }
1048 args = append(args, "-virtfs", options)
1049 case limatype.VIRTIOFS:
1050 // Note that read-only mode is not supported on the QEMU/virtiofsd side yet:
1051 // https://gitlab.com/virtio-fs/virtiofsd/-/issues/97
1052 chardev := fmt.Sprintf("char-virtiofs-%d", i)
1053 vhostSock := filepath.Join(cfg.InstanceDir, fmt.Sprintf(filenames.VhostSock, i))
1054 args = append(args, "-chardev", fmt.Sprintf("socket,id=%s,path=%s", chardev, vhostSock))
1055
1056 options := "vhost-user-fs-pci"
1057 options += fmt.Sprintf(",queue-size=%d", *f.Virtiofs.QueueSize)
1058 options += fmt.Sprintf(",chardev=%s", chardev)
1059 options += fmt.Sprintf(",tag=%s", tag)
1060 args = append(args, "-device", options)
1061 }
1062 }
1063 }
1064
1065 // QMP
1066 qmpSock := filepath.Join(cfg.InstanceDir, filenames.QMPSock)
1067 if err := os.RemoveAll(qmpSock); err != nil {
1068 return "", nil, err
1069 }
1070 const qmpChardev = "char-qmp"
1071 args = append(args, "-chardev", fmt.Sprintf("socket,id=%s,path=%s,server=on,wait=off", qmpChardev, qmpSock))
1072 args = append(args, "-qmp", "chardev:"+qmpChardev)
1073
1074 if cfg.VirtioGA {
1075 // Guest agent via serialport
1076 guestSock := filepath.Join(cfg.InstanceDir, filenames.GuestAgentSock)
1077 args = append(args, "-chardev", fmt.Sprintf("socket,path=%s,server=on,wait=off,id=qga0", guestSock))
1078 args = append(args, "-device", "virtio-serial")
1079 args = append(args, "-device", "virtserialport,chardev=qga0,name="+filenames.VirtioPort)
1080 }
1081
1082 // QEMU process
1083 args = append(args, "-name", "lima-"+cfg.Name)
1084 args = append(args, "-pidfile", filepath.Join(cfg.InstanceDir, filenames.PIDFile(*y.VMType)))
1085
1086 return exe, args, nil
1087}
1088
1089func FindVirtiofsd(ctx context.Context, qemuExe string) (string, error) {
1090 type vhostUserBackend struct {
1091 BackendType string `json:"type"`
1092 Binary string `json:"binary"`
1093 }
1094
1095 homeDir, err := os.UserHomeDir()
1096 if err != nil {
1097 return "", err
1098 }
1099
1100 const relativePath = "share/qemu/vhost-user"
1101
1102 binDir := filepath.Dir(qemuExe) // "/usr/local/bin"
1103 usrDir := filepath.Dir(binDir) // "/usr/local"
1104 userLocalDir := filepath.Join(homeDir, ".local") // "$HOME/.local"
1105
1106 candidates := []string{
1107 filepath.Join(userLocalDir, relativePath),
1108 filepath.Join(usrDir, relativePath),
1109 }
1110
1111 if usrDir != "/usr" {
1112 candidates = append(candidates, filepath.Join("/usr", relativePath))
1113 }
1114
1115 for _, vhostCfgsDir := range candidates {
1116 logrus.Debugf("Checking vhost directory %s", vhostCfgsDir)
1117
1118 cfgEntries, err := os.ReadDir(vhostCfgsDir)
1119 if err != nil {
1120 logrus.Debugf("Failed to list vhost directory: %v", err)
1121 continue
1122 }
1123
1124 for _, cfgEntry := range cfgEntries {
1125 logrus.Debugf("Checking vhost vhostCfg %s", cfgEntry.Name())
1126 if !strings.HasSuffix(cfgEntry.Name(), ".json") {
1127 continue
1128 }
1129
1130 var vhostCfg vhostUserBackend
1131 contents, err := os.ReadFile(filepath.Join(vhostCfgsDir, cfgEntry.Name()))
1132 if err == nil {
1133 err = json.Unmarshal(contents, &vhostCfg)
1134 }
1135
1136 if err != nil {
1137 logrus.Warnf("Failed to load vhost-user config %s: %v", cfgEntry.Name(), err)
1138 continue
1139 }
1140 logrus.Debugf("%v", vhostCfg)
1141
1142 if vhostCfg.BackendType != "fs" {
1143 continue
1144 }
1145
1146 // Only rust virtiofsd supports --version, so use that to make sure this isn't
1147 // QEMU's virtiofsd, which requires running as root.
1148 cmd := exec.CommandContext(ctx, vhostCfg.Binary, "--version")
1149 output, err := cmd.CombinedOutput()
1150 if err != nil {
1151 logrus.Warnf("Failed to run %s --version (is this QEMU virtiofsd?): %s: %s",
1152 vhostCfg.Binary, err, output)
1153 continue
1154 }
1155
1156 return vhostCfg.Binary, nil
1157 }
1158 }
1159
1160 return "", errors.New("failed to locate virtiofsd")
1161}
1162
1163func VirtiofsdCmdline(cfg Config, mountIndex int) ([]string, error) {
1164 mount := cfg.LimaYAML.Mounts[mountIndex]
1165
1166 vhostSock := filepath.Join(cfg.InstanceDir, fmt.Sprintf(filenames.VhostSock, mountIndex))
1167 // qemu_driver has to wait for the socket to appear, so make sure any old ones are removed here.
1168 if err := os.Remove(vhostSock); err != nil && !errors.Is(err, fs.ErrNotExist) {
1169 logrus.Warnf("Failed to remove old vhost socket: %v", err)
1170 }
1171
1172 return []string{
1173 "--socket-path", vhostSock,
1174 "--shared-dir", mount.Location,
1175 }, nil
1176}
1177
1178// qemuArch returns the arch string used by qemu.
1179func qemuArch(arch limatype.Arch) string {
1180 switch arch {
1181 case limatype.ARMV7L:
1182 return "arm"
1183 case limatype.PPC64LE:
1184 return "ppc64"
1185 default:
1186 return arch
1187 }
1188}
1189
1190// qemuEdk2 returns the arch string used by `/usr/local/share/qemu/edk2-*-code.fd`.
1191func qemuEdk2Arch(arch limatype.Arch) string {
1192 if arch == limatype.RISCV64 {
1193 return "riscv"
1194 }
1195 return qemuArch(arch)
1196}
1197
1198func Exe(arch limatype.Arch) (exe string, args []string, err error) {
1199 exeBase := "qemu-system-" + qemuArch(arch)
1200 envK := "QEMU_SYSTEM_" + strings.ToUpper(qemuArch(arch))
1201 if envV := os.Getenv(envK); envV != "" {
1202 ss, err := shellwords.Parse(envV)
1203 if err != nil {
1204 return "", nil, fmt.Errorf("failed to parse %s value %#q: %w", envK, envV, err)
1205 }
1206 exeBase, args = ss[0], ss[1:]
1207 if len(args) != 0 {
1208 logrus.Warnf("Specifying args (%v) via $%s is supported only for debugging!", args, envK)
1209 }
1210 }
1211 exe, err = exec.LookPath(exeBase)
1212 if err != nil {
1213 return "", nil, err
1214 }
1215 return exe, args, nil
1216}
1217
1218var hvSupport = sync.OnceValues(func() (string, error) {
1219 return osutil.Sysctl(context.TODO(), "kern.hv_support")
1220})
1221
1222func Accel(arch limatype.Arch) string {
1223 if limatype.IsNativeArch(arch) {
1224 switch runtime.GOOS {
1225 case "darwin":
1226 s, err := hvSupport()
1227 if err != nil || s != "1" {
1228 logrus.WithError(err).Warn("Hypervisor API (kern.hv_support) is not available. Disabling HVF. Expect very poor performance.")
1229 return "tcg"
1230 }
1231 return "hvf"
1232 case "linux":
1233 if _, err := os.Stat("/dev/kvm"); err != nil {
1234 logrus.WithError(err).Warn("/dev/kvm is not available. Disabling KVM. Expect very poor performance.")
1235 return "tcg"
1236 }
1237 return "kvm"
1238 case "netbsd":
1239 return "nvmm"
1240 case "dragonfly":
1241 return "nvmm"
1242 case "windows":
1243 return "whpx"
1244 }
1245 }
1246 return "tcg"
1247}
1248
1249func findSwtpm() (string, error) {
1250 exe, err := exec.LookPath("swtpm")
1251 if err != nil {
1252 return "", fmt.Errorf("swtpm not found in PATH: %w (hint: install swtpm)", err)
1253 }
1254 return exe, nil
1255}
1256
1257func SwtpmCmdline(cfg Config) (exe string, args []string, err error) {
1258 if runtime.GOOS == "windows" {
1259 return "", nil, errors.New("swtpm is not supported on Windows host")
1260 }
1261
1262 swtpmExe, err := findSwtpm()
1263 if err != nil {
1264 return "", nil, err
1265 }
1266
1267 stateDir := filepath.Join(cfg.InstanceDir, filenames.SwtpmDir)
1268 if err := os.MkdirAll(stateDir, 0o700); err != nil {
1269 return "", nil, fmt.Errorf("failed to create swtpm state directory: %w", err)
1270 }
1271
1272 swtpmSock := filepath.Join(cfg.InstanceDir, filenames.SwtpmSock)
1273 _ = os.Remove(swtpmSock)
1274 _ = os.Remove(filepath.Join(stateDir, ".lock"))
1275
1276 args = []string{
1277 "socket",
1278 "--tpmstate", "dir=" + stateDir,
1279 "--ctrl", "type=unixio,path=" + swtpmSock,
1280 "--tpm2",
1281 "--terminate",
1282 "--log", "level=1",
1283 }
1284
1285 return swtpmExe, args, nil
1286}
1287
1288func parseQemuVersion(output string) (*semver.Version, error) {
1289 lines := strings.Split(output, "\n")
1290 regex := regexp.MustCompile(`^QEMU emulator version (\d+\.\d+\.\d+)`)
1291 matches := regex.FindStringSubmatch(lines[0])
1292 if len(matches) == 2 {
1293 return semver.New(matches[1]), nil
1294 }
1295 return &semver.Version{}, fmt.Errorf("failed to parse %v", output)
1296}
1297
1298func getQemuVersion(ctx context.Context, qemuExe string) (*semver.Version, error) {
1299 var (
1300 stdout bytes.Buffer
1301 stderr bytes.Buffer
1302 )
1303 cmd := exec.CommandContext(ctx, qemuExe, "--version")
1304 cmd.Stdout = &stdout
1305 cmd.Stderr = &stderr
1306 if err := cmd.Run(); err != nil {
1307 return nil, fmt.Errorf("failed to run %v: stdout=%#q, stderr=%#q", cmd.Args, stdout.String(), stderr.String())
1308 }
1309
1310 return parseQemuVersion(stdout.String())
1311}
1312
1313func getFirmware(qemuExe string, arch limatype.Arch) (string, error) {
1314 switch arch {
1315 case limatype.X8664, limatype.AARCH64, limatype.ARMV7L, limatype.RISCV64:
1316 default:
1317 return "", fmt.Errorf("unexpected architecture: %#q", arch)
1318 }
1319
1320 homeDir, err := os.UserHomeDir()
1321 if err != nil {
1322 return "", err
1323 }
1324
1325 binDir := filepath.Dir(qemuExe) // "/usr/local/bin"
1326 localDir := filepath.Dir(binDir) // "/usr/local"
1327 userLocalDir := filepath.Join(homeDir, ".local") // "$HOME/.local"
1328
1329 relativePath := fmt.Sprintf("share/qemu/edk2-%s-code.fd", qemuEdk2Arch(arch))
1330 relativePathWin := fmt.Sprintf("share/edk2-%s-code.fd", qemuEdk2Arch(arch))
1331 if runtime.GOOS == "windows" {
1332 // The firmware shipped beside QEMU belongs to that QEMU version.
1333 // Prefer it over an old manual copy in the user's .local directory.
1334 bundled := filepath.Join(binDir, relativePathWin)
1335 if _, err := os.Stat(bundled); err == nil || !errors.Is(err, os.ErrNotExist) {
1336 return bundled, err
1337 }
1338 }
1339 candidates := []string{
1340 filepath.Join(userLocalDir, relativePath), // XDG-like
1341 filepath.Join(localDir, relativePath), // macOS (homebrew)
1342 filepath.Join(binDir, relativePathWin), // Windows installer
1343 }
1344
1345 switch arch {
1346 case limatype.X8664:
1347 // Archlinux package "edk2-ovmf"
1348 // @see: https://archlinux.org/packages/extra/any/edk2-ovmf/files
1349 candidates = append(candidates, "/usr/share/edk2/x64/OVMF_CODE.4m.fd")
1350 // Debian package "ovmf"
1351 candidates = append(candidates, "/usr/share/OVMF/OVMF_CODE.fd")
1352 candidates = append(candidates, "/usr/share/OVMF/OVMF_CODE_4M.fd")
1353 // Fedora package "edk2-ovmf"
1354 candidates = append(candidates, "/usr/share/edk2/ovmf/OVMF_CODE.fd")
1355 // openSUSE package "qemu-ovmf-x86_64"
1356 candidates = append(candidates, "/usr/share/qemu/ovmf-x86_64.bin")
1357 candidates = append(candidates, "/usr/share/qemu/ovmf-x86_64-4m.bin")
1358 case limatype.AARCH64:
1359 // Archlinux package "edk2-aarch64"
1360 // @see: https://archlinux.org/packages/extra/any/edk2-aarch64/files
1361 candidates = append(candidates, "/usr/share/edk2/aarch64/QEMU_CODE.fd")
1362 // Debian package "qemu-efi-aarch64"
1363 // Fedora package "edk2-aarch64"
1364 candidates = append(candidates, "/usr/share/AAVMF/AAVMF_CODE.fd")
1365 // Debian package "qemu-efi-aarch64" (unpadded, backwards compatibility)
1366 candidates = append(candidates, "/usr/share/qemu-efi-aarch64/QEMU_EFI.fd")
1367 case limatype.ARMV7L:
1368 // Archlinux package "edk2-arm"
1369 // @see: https://archlinux.org/packages/extra/any/edk2-arm/files
1370 candidates = append(candidates, "/usr/share/edk2/arm/QEMU_CODE.fd")
1371 // Debian package "qemu-efi-arm"
1372 // Fedora package "edk2-arm"
1373 candidates = append(candidates, "/usr/share/AAVMF/AAVMF32_CODE.fd")
1374 case limatype.RISCV64:
1375 // Debian package "qemu-efi-riscv64"
1376 candidates = append(candidates, "/usr/share/qemu-efi-riscv64/RISCV_VIRT_CODE.fd")
1377 // Fedora package "edk2-riscv64"
1378 candidates = append(candidates, "/usr/share/edk2/riscv/RISCV_VIRT_CODE.fd")
1379 }
1380
1381 logrus.Debugf("firmware candidates = %v", candidates)
1382
1383 for _, f := range candidates {
1384 if _, err := os.Stat(f); err == nil {
1385 return f, nil
1386 }
1387 }
1388
1389 if arch == limatype.X8664 {
1390 return "", fmt.Errorf("could not find firmware for %#q (hint: try setting `firmware.legacyBIOS` to `true`)", arch)
1391 }
1392 qemuArch := strings.TrimPrefix(filepath.Base(qemuExe), "qemu-system-")
1393 return "", fmt.Errorf("could not find firmware for %#q (hint: try copying the `edk-%s-code.fd` firmware to $HOME/.local/share/qemu/)", arch, qemuArch)
1394}
1395
1396var hasSMEDarwin = sync.OnceValue(func() bool {
1397 if runtime.GOOS != "darwin" || runtime.GOARCH != "arm64" {
1398 return false
1399 }
1400 // golang.org/x/sys/cpu does not support inspecting the availability of SME yet
1401 s, err := osutil.Sysctl(context.Background(), "hw.optional.arm.FEAT_SME")
1402 if err != nil {
1403 logrus.WithError(err).Debug("failed to check hw.optional.arm.FEAT_SME")
1404 }
1405 return s == "1"
1406})
1407
1408func hasHostCPU(qemuVersion *semver.Version) bool {
1409 switch runtime.GOOS {
1410 case "darwin":
1411 if hasSMEDarwin() {
1412 // [2025-02-05]
1413 // SME is available since Apple M4 running macOS 15.2, but it was broken on macOS 15.2.
1414 // It has been fixed in 15.3.
1415 //
1416 // https://github.com/lima-vm/lima/issues/3032
1417 // https://gitlab.com/qemu-project/qemu/-/issues/2665
1418 // https://gitlab.com/qemu-project/qemu/-/issues/2721
1419
1420 // [2025-02-12]
1421 // SME got broken again after upgrading QEMU from 9.2.0 to 9.2.1 (Homebrew bottle).
1422 // Possibly this regression happened in some build process rather than in QEMU itself?
1423 // https://github.com/lima-vm/lima/issues/3226
1424 return false
1425 }
1426 return true
1427 case "linux":
1428 return true
1429 case "windows":
1430 // Should have been 11.1.0, but it contained a regression when running in nested virt
1431 if qemuVersion == nil || qemuVersion.LessThan(*semver.New("11.1.1")) {
1432 return false
1433 }
1434 return true
1435 case "netbsd":
1436 return false
1437 }
1438 // Not reached
1439 return false
1440}
1441
1442// isWindowsBootDone returns true if the Windows VM instance was already created and all installation was finished before.
1443func isWindowsBootDone(cfg Config) bool {
1444 if *cfg.LimaYAML.OS != limatype.WINDOWS {
1445 return false
1446 }
1447
1448 if _, err := os.Stat(filepath.Join(cfg.InstanceDir, filenames.WinDoneInstallation)); err != nil {
1449 return false
1450 }
1451 return true
1452}