| 1 | |
| 2 | |
| 3 | |
| 4 | package qemu |
| 5 | |
| 6 | import ( |
| 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 | |
| 43 | type Config struct { |
| 44 | Name string |
| 45 | InstanceDir string |
| 46 | LimaYAML *limatype.LimaYAML |
| 47 | SSHLocalPort int |
| 48 | SSHAddress string |
| 49 | VirtioGA bool |
| 50 | |
| 51 | |
| 52 | UsernetQEMUSock string |
| 53 | |
| 54 | |
| 55 | |
| 56 | UsernetDgram *os.File |
| 57 | } |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | func 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 | |
| 76 | h, s = "8.2.1", "8.2.1" |
| 77 | default: |
| 78 | |
| 79 | |
| 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 | |
| 86 | |
| 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 | |
| 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 | |
| 99 | func 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 | |
| 111 | |
| 112 | |
| 113 | func 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 | |
| 154 | func 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 | |
| 163 | func 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 | |
| 178 | func 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 | |
| 190 | func Del(ctx context.Context, cfg Config, run bool, tag string) error { |
| 191 | if run { |
| 192 | out, err := sendHmpCommand(cfg, "delvm", tag) |
| 193 | |
| 194 | if out != "" { |
| 195 | logrus.Warnf("output: %s", strings.TrimSpace(out)) |
| 196 | } |
| 197 | return err |
| 198 | } |
| 199 | |
| 200 | _, err := execImgCommand(ctx, cfg, "snapshot", "-d", tag) |
| 201 | return err |
| 202 | } |
| 203 | |
| 204 | func Save(ctx context.Context, cfg Config, run bool, tag string) error { |
| 205 | if run { |
| 206 | out, err := sendHmpCommand(cfg, "savevm", tag) |
| 207 | |
| 208 | if out != "" { |
| 209 | logrus.Warnf("output: %s", strings.TrimSpace(out)) |
| 210 | } |
| 211 | return err |
| 212 | } |
| 213 | |
| 214 | _, err := execImgCommand(ctx, cfg, "snapshot", "-c", tag) |
| 215 | return err |
| 216 | } |
| 217 | |
| 218 | func Load(ctx context.Context, cfg Config, run bool, tag string) error { |
| 219 | if run { |
| 220 | out, err := sendHmpCommand(cfg, "loadvm", tag) |
| 221 | |
| 222 | if out != "" { |
| 223 | logrus.Warnf("output: %s", strings.TrimSpace(out)) |
| 224 | } |
| 225 | return err |
| 226 | } |
| 227 | |
| 228 | _, err := execImgCommand(ctx, cfg, "snapshot", "-a", tag) |
| 229 | return err |
| 230 | } |
| 231 | |
| 232 | |
| 233 | func 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 | |
| 244 | args := []string{"snapshot", "-l"} |
| 245 | out, err := execImgCommand(ctx, cfg, args...) |
| 246 | if err == nil { |
| 247 | |
| 248 | out = strings.Replace(out, "Snapshot list:\n", "", 1) |
| 249 | } |
| 250 | return out, err |
| 251 | } |
| 252 | |
| 253 | func 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 | |
| 273 | |
| 274 | func 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 | |
| 297 | type features struct { |
| 298 | |
| 299 | |
| 300 | |
| 301 | AccelHelp []byte |
| 302 | |
| 303 | |
| 304 | |
| 305 | NetdevHelp []byte |
| 306 | |
| 307 | |
| 308 | |
| 309 | MachineHelp []byte |
| 310 | |
| 311 | |
| 312 | |
| 313 | CPUHelp []byte |
| 314 | } |
| 315 | |
| 316 | func 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 | |
| 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 | |
| 336 | |
| 337 | |
| 338 | func 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 | |
| 347 | if stdout.Len() == 0 { |
| 348 | return stderr.Bytes(), nil |
| 349 | } |
| 350 | return stdout.Bytes(), nil |
| 351 | } |
| 352 | |
| 353 | |
| 354 | |
| 355 | |
| 356 | |
| 357 | |
| 358 | |
| 359 | |
| 360 | |
| 361 | func adjustMemBytesDarwinARM64HVF(memBytes int64, accel string) int64 { |
| 362 | const safeSize = 3 * 1024 * 1024 * 1024 |
| 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 | |
| 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 | |
| 393 | func qemuMachine(arch limatype.Arch) string { |
| 394 | if arch == limatype.X8664 { |
| 395 | return "q35" |
| 396 | } |
| 397 | return "virt" |
| 398 | } |
| 399 | |
| 400 | |
| 401 | func audioDevice() string { |
| 402 | switch runtime.GOOS { |
| 403 | case "darwin": |
| 404 | return "coreaudio" |
| 405 | case "linux": |
| 406 | return "pa" |
| 407 | case "windows": |
| 408 | return "dsound" |
| 409 | } |
| 410 | return "oss" |
| 411 | } |
| 412 | |
| 413 | func defaultCPUType(qemuVersion *semver.Version) limatype.CPUType { |
| 414 | |
| 415 | |
| 416 | |
| 417 | defaultX8664 := "max" |
| 418 | if runtime.GOOS == "windows" && runtime.GOARCH == "amd64" { |
| 419 | |
| 420 | |
| 421 | |
| 422 | |
| 423 | TODO: |
| 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 | |
| 442 | |
| 443 | cpuType[arch] += ",-avx512vl" |
| 444 | |
| 445 | |
| 446 | |
| 447 | |
| 448 | cpuType[arch] += ",-pdpe1gb" |
| 449 | } |
| 450 | } |
| 451 | return cpuType |
| 452 | } |
| 453 | |
| 454 | func 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 | |
| 462 | |
| 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 | |
| 487 | func Cmdline(ctx context.Context, cfg Config) (exe string, args []string, err error) { |
| 488 | return cmdline(ctx, cfg, nil) |
| 489 | } |
| 490 | |
| 491 | func 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 575 | switch *y.Arch { |
| 576 | case limatype.X8664: |
| 577 | switch accel { |
| 578 | case "tcg": |
| 579 | |
| 580 | args = appendArgsIfNoConflict(args, "-machine", "q35,vmport=off") |
| 581 | |
| 582 | |
| 583 | |
| 584 | |
| 585 | args = appendArgsIfNoConflict(args, "-accel", "tcg,thread=multi,tb-size=512") |
| 586 | |
| 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 | |
| 600 | |
| 601 | |
| 602 | |
| 603 | |
| 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 | |
| 618 | args = appendArgsIfNoConflict(args, "-smp", |
| 619 | fmt.Sprintf("%d,sockets=1,cores=%d,threads=1", *y.CPUs, *y.CPUs)) |
| 620 | |
| 621 | |
| 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 | |
| 663 | args = append(args, "-drive", "if=pflash,format=raw,readonly=on,file="+strings.ReplaceAll(firmware, ",", ",,")) |
| 664 | } |
| 665 | } |
| 666 | |
| 667 | |
| 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 | |
| 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 | |
| 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 | |
| 711 | if isWindowsBootDone(cfg) { |
| 712 | break |
| 713 | } |
| 714 | |
| 715 | |
| 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 | |
| 736 | |
| 737 | |
| 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 | |
| 752 | switch *y.OS { |
| 753 | case limatype.WINDOWS: |
| 754 | |
| 755 | if isWindowsBootDone(cfg) { |
| 756 | break |
| 757 | } |
| 758 | |
| 759 | |
| 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 | |
| 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 | |
| 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 | |
| 806 | |
| 807 | firstUsernetIndex := limayaml.FirstUsernetIndex(y) |
| 808 | switch { |
| 809 | case firstUsernetIndex == -1 && cfg.UsernetQEMUSock != "" && runtime.GOOS == "windows": |
| 810 | |
| 811 | |
| 812 | |
| 813 | |
| 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 | |
| 820 | |
| 821 | |
| 822 | |
| 823 | |
| 824 | |
| 825 | |
| 826 | |
| 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 | |
| 843 | |
| 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 | |
| 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 | |
| 900 | args = append(args, "-device", "virtio-rng-pci") |
| 901 | |
| 902 | |
| 903 | input := "mouse" |
| 904 | |
| 905 | |
| 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 | |
| 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 | |
| 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 | |
| 947 | input = "tablet" |
| 948 | } |
| 949 | args = appendArgsIfNoConflict(args, "-display", display) |
| 950 | } |
| 951 | |
| 952 | if *y.Video.Display != "none" { |
| 953 | switch *y.Arch { |
| 954 | FIXME: |
| 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 | |
| 968 | |
| 969 | |
| 970 | args = append(args, "-vga", "none") |
| 971 | } |
| 972 | |
| 973 | |
| 974 | args = append(args, "-parallel", "none") |
| 975 | |
| 976 | |
| 977 | |
| 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 | |
| 991 | |
| 992 | |
| 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 | |
| 1009 | |
| 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 | |
| 1022 | serialvMaxPorts := 1 |
| 1023 | if *y.Arch == limatype.S390X { |
| 1024 | serialvMaxPorts++ |
| 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 | |
| 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 | |
| 1051 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 1089 | func 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) |
| 1103 | usrDir := filepath.Dir(binDir) |
| 1104 | userLocalDir := filepath.Join(homeDir, ".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 | |
| 1147 | |
| 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 | |
| 1163 | func 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 | |
| 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 | |
| 1179 | func 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 | |
| 1191 | func qemuEdk2Arch(arch limatype.Arch) string { |
| 1192 | if arch == limatype.RISCV64 { |
| 1193 | return "riscv" |
| 1194 | } |
| 1195 | return qemuArch(arch) |
| 1196 | } |
| 1197 | |
| 1198 | func 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 | |
| 1218 | var hvSupport = sync.OnceValues(func() (string, error) { |
| 1219 | return osutil.Sysctl(context.TODO(), "kern.hv_support") |
| 1220 | }) |
| 1221 | |
| 1222 | func 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 | |
| 1249 | func 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 | |
| 1257 | func 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 | |
| 1288 | func 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 | |
| 1298 | func 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 | |
| 1313 | func 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) |
| 1326 | localDir := filepath.Dir(binDir) |
| 1327 | userLocalDir := filepath.Join(homeDir, ".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 | |
| 1333 | |
| 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), |
| 1341 | filepath.Join(localDir, relativePath), |
| 1342 | filepath.Join(binDir, relativePathWin), |
| 1343 | } |
| 1344 | |
| 1345 | switch arch { |
| 1346 | case limatype.X8664: |
| 1347 | |
| 1348 | |
| 1349 | candidates = append(candidates, "/usr/share/edk2/x64/OVMF_CODE.4m.fd") |
| 1350 | |
| 1351 | candidates = append(candidates, "/usr/share/OVMF/OVMF_CODE.fd") |
| 1352 | candidates = append(candidates, "/usr/share/OVMF/OVMF_CODE_4M.fd") |
| 1353 | |
| 1354 | candidates = append(candidates, "/usr/share/edk2/ovmf/OVMF_CODE.fd") |
| 1355 | |
| 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 | |
| 1360 | |
| 1361 | candidates = append(candidates, "/usr/share/edk2/aarch64/QEMU_CODE.fd") |
| 1362 | |
| 1363 | |
| 1364 | candidates = append(candidates, "/usr/share/AAVMF/AAVMF_CODE.fd") |
| 1365 | |
| 1366 | candidates = append(candidates, "/usr/share/qemu-efi-aarch64/QEMU_EFI.fd") |
| 1367 | case limatype.ARMV7L: |
| 1368 | |
| 1369 | |
| 1370 | candidates = append(candidates, "/usr/share/edk2/arm/QEMU_CODE.fd") |
| 1371 | |
| 1372 | |
| 1373 | candidates = append(candidates, "/usr/share/AAVMF/AAVMF32_CODE.fd") |
| 1374 | case limatype.RISCV64: |
| 1375 | |
| 1376 | candidates = append(candidates, "/usr/share/qemu-efi-riscv64/RISCV_VIRT_CODE.fd") |
| 1377 | |
| 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 | |
| 1396 | var hasSMEDarwin = sync.OnceValue(func() bool { |
| 1397 | if runtime.GOOS != "darwin" || runtime.GOARCH != "arm64" { |
| 1398 | return false |
| 1399 | } |
| 1400 | |
| 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 | |
| 1408 | func hasHostCPU(qemuVersion *semver.Version) bool { |
| 1409 | switch runtime.GOOS { |
| 1410 | case "darwin": |
| 1411 | if hasSMEDarwin() { |
| 1412 | |
| 1413 | |
| 1414 | |
| 1415 | |
| 1416 | |
| 1417 | |
| 1418 | |
| 1419 | |
| 1420 | |
| 1421 | |
| 1422 | |
| 1423 | |
| 1424 | return false |
| 1425 | } |
| 1426 | return true |
| 1427 | case "linux": |
| 1428 | return true |
| 1429 | case "windows": |
| 1430 | |
| 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 | |
| 1439 | return false |
| 1440 | } |
| 1441 | |
| 1442 | |
| 1443 | func 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 | } |