File: driver_qemu_templates.go

package info (click to toggle)
incus 6.0.5-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 24,428 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (975 lines) | stat: -rw-r--r-- 22,689 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
package drivers

import (
	"fmt"
	"sort"
	"strings"

	"github.com/lxc/incus/v6/internal/server/instance/drivers/cfg"
	"github.com/lxc/incus/v6/shared/osarch"
	"github.com/lxc/incus/v6/shared/resources"
)

func writeHeader(sb *strings.Builder, comment string, name string) {
	if comment != "" {
		fmt.Fprintf(sb, "# %s\n", comment)
	}

	fmt.Fprintf(sb, "[%s]\n", name)
}

func writeEntry(sb *strings.Builder, key string, value string) {
	if value != "" {
		fmt.Fprintf(sb, "%s = \"%s\"\n", key, value)
	}
}

func qemuStringifyCfg(conf ...cfg.Section) *strings.Builder {
	sb := &strings.Builder{}

	for _, section := range conf {
		writeHeader(sb, section.Comment, section.Name)

		for key, value := range section.Entries {
			writeEntry(sb, key, value)
		}

		sb.WriteString("\n")
	}

	return sb
}

// qemuStringifyCfgPredictably is only there to ensure tests reproducibility.
func qemuStringifyCfgPredictably(conf ...cfg.Section) *strings.Builder {
	sb := &strings.Builder{}

	for _, section := range conf {
		writeHeader(sb, section.Comment, section.Name)

		keys := make([]string, 0, len(section.Entries))
		for key := range section.Entries {
			keys = append(keys, key)
		}

		sort.Strings(keys)
		for _, key := range keys {
			writeEntry(sb, key, section.Entries[key])
		}

		sb.WriteString("\n")
	}

	return sb
}

func qemuMachineType(architecture int) string {
	var machineType string

	switch architecture {
	case osarch.ARCH_64BIT_INTEL_X86:
		machineType = "q35"
	case osarch.ARCH_64BIT_ARMV8_LITTLE_ENDIAN:
		machineType = "virt"
	case osarch.ARCH_64BIT_POWERPC_LITTLE_ENDIAN:
		machineType = "pseries"
	case osarch.ARCH_64BIT_S390_BIG_ENDIAN:
		machineType = "s390-ccw-virtio"
	}

	return machineType
}

type qemuBaseOpts struct {
	architecture int
	iommu        bool
	definition   string
}

func qemuBase(opts *qemuBaseOpts) []cfg.Section {
	machineType := qemuMachineType(opts.architecture)
	gicVersion := ""
	capLargeDecr := ""

	switch opts.architecture {
	case osarch.ARCH_64BIT_ARMV8_LITTLE_ENDIAN:
		gicVersion = "max"
	case osarch.ARCH_64BIT_POWERPC_LITTLE_ENDIAN:
		capLargeDecr = "off"
	}

	if opts.definition != "" {
		machineType = opts.definition
	}

	sections := []cfg.Section{{
		Name:    "machine",
		Comment: "Machine",
		Entries: map[string]string{
			"graphics":       "off",
			"type":           machineType,
			"gic-version":    gicVersion,
			"cap-large-decr": capLargeDecr,
			"accel":          "kvm",
			"usb":            "off",
		},
	}}

	if opts.iommu {
		sections[0].Entries["kernel-irqchip"] = "split"
	}

	if opts.architecture == osarch.ARCH_64BIT_INTEL_X86 {
		sections = append(sections, []cfg.Section{{
			Name: "global",
			Entries: map[string]string{
				"driver":   "ICH9-LPC",
				"property": "disable_s3",
				"value":    "1",
			},
		}, {
			Name: "global",
			Entries: map[string]string{
				"driver":   "ICH9-LPC",
				"property": "disable_s4",
				"value":    "0",
			},
		}}...)
	}

	return append(
		sections,
		cfg.Section{
			Name:    "boot-opts",
			Entries: map[string]string{"strict": "on"},
		})
}

type qemuMemoryOpts struct {
	memSizeMB int64
	maxSizeMB int64
}

func qemuMemory(opts *qemuMemoryOpts) []cfg.Section {
	// Sets fixed values for slots and maxmem to support memory hotplug.
	section := cfg.Section{
		Name:    "memory",
		Comment: "Memory",
		Entries: map[string]string{
			"size":   fmt.Sprintf("%dM", opts.memSizeMB),
			"maxmem": fmt.Sprintf("%dM", opts.maxSizeMB),
			// Some systems hit odd errors when using more than 8 hotplug slots.
			// That's even with maxmem capped at the total system memory.
			"slots": "8",
		},
	}

	// Disable hotplug when already at maximum.
	if section.Entries["size"] == section.Entries["maxmem"] {
		delete(section.Entries, "slots")
	}

	return []cfg.Section{section}
}

type qemuDevOpts struct {
	busName       string
	devBus        string
	devAddr       string
	multifunction bool
}

type qemuDevEntriesOpts struct {
	dev     qemuDevOpts
	pciName string
	ccwName string
}

func qemuDeviceEntries(opts *qemuDevEntriesOpts) map[string]string {
	entries := make(map[string]string)

	if opts.dev.busName == "pci" || opts.dev.busName == "pcie" {
		entries["driver"] = opts.pciName
		entries["bus"] = opts.dev.devBus
		entries["addr"] = opts.dev.devAddr
	} else if opts.dev.busName == "ccw" {
		entries["driver"] = opts.ccwName
	}

	if opts.dev.multifunction {
		entries["multifunction"] = "on"
	}

	return entries
}

type qemuSerialOpts struct {
	dev              qemuDevOpts
	charDevName      string
	ringbufSizeBytes int
}

func qemuSerial(opts *qemuSerialOpts) []cfg.Section {
	entriesOpts := qemuDevEntriesOpts{
		dev:     opts.dev,
		pciName: "virtio-serial-pci",
		ccwName: "virtio-serial-ccw",
	}

	return []cfg.Section{{
		Name:    `device "dev-qemu_serial"`,
		Comment: "Virtual serial bus",
		Entries: qemuDeviceEntries(&entriesOpts),
	}, {
		// Ring buffer used by the incus agent to report (write) its status to. Incus server will read
		// its content via QMP using "ringbuf-read" command.
		Name:    fmt.Sprintf(`chardev "%s"`, opts.charDevName),
		Comment: "Serial identifier",
		Entries: map[string]string{
			"backend": "ringbuf",
			"size":    fmt.Sprintf("%dB", opts.ringbufSizeBytes),
		},
	}, {
		// QEMU serial device connected to the above ring buffer.
		Name: `device "qemu_serial"`,
		Entries: map[string]string{
			"driver":  "virtserialport",
			"name":    "org.linuxcontainers.incus",
			"chardev": opts.charDevName,
			"bus":     "dev-qemu_serial.0",
		},
	}, {
		// Legacy QEMU serial device, not connected to any ring buffer. Its purpose is to
		// create a symlink in /dev/virtio-ports/, triggering a udev rule to start incus-agent.
		// This is necessary for backward compatibility with virtual machines lacking the
		// updated incus-agent-loader package, which includes updated udev rules and a systemd unit.
		Name: `device "qemu_serial_legacy"`,
		Entries: map[string]string{
			"driver": "virtserialport",
			"name":   "org.linuxcontainers.lxd",
			"bus":    "dev-qemu_serial.0",
		},
	}, {
		Name:    `chardev "qemu_spice-chardev"`,
		Comment: "Spice agent",
		Entries: map[string]string{
			"backend": "spicevmc",
			"name":    "vdagent",
		},
	}, {
		Name: `device "qemu_spice"`,
		Entries: map[string]string{
			"driver":  "virtserialport",
			"name":    "com.redhat.spice.0",
			"chardev": "qemu_spice-chardev",
			"bus":     "dev-qemu_serial.0",
		},
	}, {
		Name:    `chardev "qemu_spicedir-chardev"`,
		Comment: "Spice folder",
		Entries: map[string]string{
			"backend": "spiceport",
			"name":    "org.spice-space.webdav.0",
		},
	}, {
		Name: `device "qemu_spicedir"`,
		Entries: map[string]string{
			"driver":  "virtserialport",
			"name":    "org.spice-space.webdav.0",
			"chardev": "qemu_spicedir-chardev",
			"bus":     "dev-qemu_serial.0",
		},
	}}
}

type qemuPCIeOpts struct {
	portName      string
	index         int
	devAddr       string
	multifunction bool
}

func qemuPCIe(opts *qemuPCIeOpts) []cfg.Section {
	entries := map[string]string{
		"driver":  "pcie-root-port",
		"bus":     "pcie.0",
		"addr":    opts.devAddr,
		"chassis": fmt.Sprintf("%d", opts.index),
	}

	if opts.multifunction {
		entries["multifunction"] = "on"
	}

	return []cfg.Section{{
		Name:    fmt.Sprintf(`device "%s"`, opts.portName),
		Entries: entries,
	}}
}

func qemuSCSI(opts *qemuDevOpts) []cfg.Section {
	entriesOpts := qemuDevEntriesOpts{
		dev:     *opts,
		pciName: "virtio-scsi-pci",
		ccwName: "virtio-scsi-ccw",
	}

	return []cfg.Section{{
		Name:    `device "qemu_scsi"`,
		Comment: "SCSI controller",
		Entries: qemuDeviceEntries(&entriesOpts),
	}}
}

func qemuBalloon(opts *qemuDevOpts) []cfg.Section {
	entriesOpts := qemuDevEntriesOpts{
		dev:     *opts,
		pciName: "virtio-balloon-pci",
		ccwName: "virtio-balloon-ccw",
	}

	return []cfg.Section{{
		Name:    `device "qemu_balloon"`,
		Comment: "Balloon driver",
		Entries: qemuDeviceEntries(&entriesOpts),
	}}
}

func qemuRNG(opts *qemuDevOpts) []cfg.Section {
	entries := qemuDeviceEntries(&qemuDevEntriesOpts{
		dev:     *opts,
		pciName: "virtio-rng-pci",
		ccwName: "virtio-rng-ccw",
	})
	entries["rng"] = "qemu_rng"

	return []cfg.Section{{
		Name:    `object "qemu_rng"`,
		Comment: "Random number generator",
		Entries: map[string]string{
			"qom-type": "rng-random",
			"filename": "/dev/urandom",
		},
	}, {
		Name:    `device "dev-qemu_rng"`,
		Entries: entries,
	}}
}

func qemuCoreInfo() []cfg.Section {
	return []cfg.Section{{
		Name:    `device "qemu_vmcoreinfo"`,
		Comment: "VM core info driver",
		Entries: map[string]string{"driver": "vmcoreinfo"},
	}}
}

func qemuIOMMU(opts *qemuDevOpts, isWindows bool) []cfg.Section {
	if isWindows {
		return []cfg.Section{{
			Name:    `device "intel-iommu"`,
			Comment: "IOMMU driver",
			Entries: map[string]string{
				"driver":       "intel-iommu",
				"intremap":     "on",
				"caching-mode": "on",
			},
		}}
	}

	entriesOpts := qemuDevEntriesOpts{
		dev:     *opts,
		pciName: "virtio-iommu-pci",
	}

	return []cfg.Section{{
		Name:    `device "qemu_iommu"`,
		Comment: "IOMMU driver",
		Entries: qemuDeviceEntries(&entriesOpts),
	}}
}

type qemuSevOpts struct {
	cbitpos         int
	reducedPhysBits int
	policy          string
	dhCertFD        string
	sessionDataFD   string
}

func qemuSEV(opts *qemuSevOpts) []cfg.Section {
	entries := map[string]string{
		"qom-type":          "sev-guest",
		"cbitpos":           fmt.Sprintf("%d", opts.cbitpos),
		"reduced-phys-bits": fmt.Sprintf("%d", opts.reducedPhysBits),
		"policy":            opts.policy,
	}

	if opts.dhCertFD != "" && opts.sessionDataFD != "" {
		entries["dh-cert-file"] = opts.dhCertFD
		entries["session-file"] = opts.sessionDataFD
	}

	return []cfg.Section{{
		Name:    `object "sev0"`,
		Comment: "Secure Encrypted Virtualization",
		Entries: entries,
	}}
}

type qemuVsockOpts struct {
	dev     qemuDevOpts
	vsockFD int
	vsockID uint32
}

func qemuVsock(opts *qemuVsockOpts) []cfg.Section {
	entries := qemuDeviceEntries(&qemuDevEntriesOpts{
		dev:     opts.dev,
		pciName: "vhost-vsock-pci",
		ccwName: "vhost-vsock-ccw",
	})
	entries["guest-cid"] = fmt.Sprintf("%d", opts.vsockID)
	entries["vhostfd"] = fmt.Sprintf("%d", opts.vsockFD)

	return []cfg.Section{{
		Name:    `device "qemu_vsock"`,
		Comment: "Vsock",
		Entries: entries,
	}}
}

type qemuGpuOpts struct {
	dev          qemuDevOpts
	architecture int
}

func qemuGPU(opts *qemuGpuOpts) []cfg.Section {
	var pciName string

	if opts.architecture == osarch.ARCH_64BIT_INTEL_X86 {
		pciName = "virtio-vga"
	} else {
		pciName = "virtio-gpu-pci"
	}

	entriesOpts := qemuDevEntriesOpts{
		dev:     opts.dev,
		pciName: pciName,
		ccwName: "virtio-gpu-ccw",
	}

	return []cfg.Section{{
		Name:    `device "qemu_gpu"`,
		Comment: "GPU",
		Entries: qemuDeviceEntries(&entriesOpts),
	}}
}

func qemuKeyboard(opts *qemuDevOpts) []cfg.Section {
	entriesOpts := qemuDevEntriesOpts{
		dev:     *opts,
		pciName: "virtio-keyboard-pci",
		ccwName: "virtio-keyboard-ccw",
	}

	return []cfg.Section{{
		Name:    `device "qemu_keyboard"`,
		Comment: "Input",
		Entries: qemuDeviceEntries(&entriesOpts),
	}}
}

func qemuTablet(opts *qemuDevOpts) []cfg.Section {
	entriesOpts := qemuDevEntriesOpts{
		dev:     *opts,
		pciName: "virtio-tablet-pci",
		ccwName: "virtio-tablet-ccw",
	}

	return []cfg.Section{{
		Name:    `device "qemu_tablet"`,
		Comment: "Input",
		Entries: qemuDeviceEntries(&entriesOpts),
	}}
}

type qemuNumaEntry struct {
	node   uint64
	socket uint64
	core   uint64
	thread uint64
}

type qemuCPUOpts struct {
	architecture        string
	cpuCount            int
	cpuRequested        int
	cpuSockets          int
	cpuCores            int
	cpuThreads          int
	cpuNumaNodes        []uint64
	cpuNumaMapping      []qemuNumaEntry
	cpuNumaHostNodes    []uint64
	hugepages           string
	memory              int64
	memoryHostNodes     []int64
	qemuMemObjectFormat string
}

func qemuCPUNumaHostNode(opts *qemuCPUOpts, index int) []cfg.Section {
	entries := make(map[string]string)

	if opts.hugepages != "" {
		entries["qom-type"] = "memory-backend-file"
		entries["mem-path"] = opts.hugepages
		entries["prealloc"] = "on"
		entries["discard-data"] = "on"
	} else {
		entries["qom-type"] = "memory-backend-memfd"
	}

	entries["size"] = fmt.Sprintf("%dM", opts.memory)

	return []cfg.Section{{
		Name:    fmt.Sprintf("object \"mem%d\"", index),
		Entries: entries,
	}, {
		Name: "numa",
		Entries: map[string]string{
			"type":   "node",
			"nodeid": fmt.Sprintf("%d", index),
			"memdev": fmt.Sprintf("mem%d", index),
		},
	}}
}

func qemuCPU(opts *qemuCPUOpts, pinning bool) []cfg.Section {
	entries := map[string]string{"cpus": fmt.Sprintf("%d", opts.cpuCount)}

	if pinning {
		entries["sockets"] = fmt.Sprintf("%d", opts.cpuSockets)
		entries["cores"] = fmt.Sprintf("%d", opts.cpuCores)
		entries["threads"] = fmt.Sprintf("%d", opts.cpuThreads)
	} else {
		cpu, err := resources.GetCPU()
		if err != nil {
			return nil
		}

		// Cap the max number of CPUs to 64 unless directly assigned more.
		maxCpus := 64
		if int(cpu.Total) < maxCpus {
			maxCpus = int(cpu.Total)
		} else if opts.cpuRequested > maxCpus {
			maxCpus = opts.cpuRequested
		} else if opts.cpuCount > maxCpus {
			maxCpus = opts.cpuCount
		}

		entries["maxcpus"] = fmt.Sprintf("%d", maxCpus)
	}

	sections := []cfg.Section{{
		Name:    "smp-opts",
		Comment: "CPU",
		Entries: entries,
	}}

	if opts.architecture != "x86_64" {
		return sections
	}

	if len(opts.cpuNumaHostNodes) == 0 {
		// Add one mem and one numa sections with index 0.
		numaHostNode := qemuCPUNumaHostNode(opts, 0)

		// Unconditionally append "share = "on" to the [object "mem0"] section
		numaHostNode[0].Entries["share"] = "on"

		// If NUMA memory restrictions are set, apply them.
		if len(opts.memoryHostNodes) > 0 {
			numaHostNode[0].Entries["policy"] = "bind"

			for index, element := range opts.memoryHostNodes {
				var hostNodesKey string
				if opts.qemuMemObjectFormat == "indexed" {
					hostNodesKey = fmt.Sprintf("host-nodes.%d", index)
				} else {
					hostNodesKey = "host-nodes"
				}

				numaHostNode[0].Entries[hostNodesKey] = fmt.Sprintf("%d", element)
			}
		}

		return append(sections, numaHostNode...)
	}

	for index, element := range opts.cpuNumaHostNodes {
		numaHostNode := qemuCPUNumaHostNode(opts, index)

		numaHostNode[0].Entries["policy"] = "bind"

		if opts.hugepages != "" {
			// append share = "on" only if hugepages is set
			numaHostNode[0].Entries["share"] = "on"
		}

		var hostNodesKey string
		if opts.qemuMemObjectFormat == "indexed" {
			hostNodesKey = "host-nodes.0"
		} else {
			hostNodesKey = "host-nodes"
		}

		numaHostNode[0].Entries[hostNodesKey] = fmt.Sprintf("%d", element)
		sections = append(sections, numaHostNode...)
	}

	for _, numa := range opts.cpuNumaMapping {
		sections = append(sections, cfg.Section{
			Name: "numa",
			Entries: map[string]string{
				"type":      "cpu",
				"node-id":   fmt.Sprintf("%d", numa.node),
				"socket-id": fmt.Sprintf("%d", numa.socket),
				"core-id":   fmt.Sprintf("%d", numa.core),
				"thread-id": fmt.Sprintf("%d", numa.thread),
			},
		})
	}

	return sections
}

type qemuControlSocketOpts struct {
	path string
}

func qemuControlSocket(opts *qemuControlSocketOpts) []cfg.Section {
	return []cfg.Section{{
		Name:    `chardev "monitor"`,
		Comment: "Qemu control",
		Entries: map[string]string{
			"backend": "socket",
			"path":    opts.path,
			"server":  "on",
			"wait":    "off",
		},
	}, {
		Name: "mon",
		Entries: map[string]string{
			"chardev": "monitor",
			"mode":    "control",
		},
	}}
}

func qemuConsole() []cfg.Section {
	return []cfg.Section{{
		Name:    `chardev "console"`,
		Comment: "Console",
		Entries: map[string]string{
			"backend": "ringbuf",
			"size":    "1048576",
		},
	}}
}

type qemuDriveFirmwareOpts struct {
	roPath    string
	nvramPath string
}

func qemuDriveFirmware(opts *qemuDriveFirmwareOpts) []cfg.Section {
	return []cfg.Section{{
		Name:    "drive",
		Comment: "Firmware (read only)",
		Entries: map[string]string{
			"file":     opts.roPath,
			"if":       "pflash",
			"format":   "raw",
			"unit":     "0",
			"readonly": "on",
		},
	}, {
		Name:    "drive",
		Comment: "Firmware settings (writable)",
		Entries: map[string]string{
			"file":   opts.nvramPath,
			"if":     "pflash",
			"format": "raw",
			"unit":   "1",
		},
	}}
}

type qemuHostDriveOpts struct {
	dev           qemuDevOpts
	name          string
	nameSuffix    string
	comment       string
	fsdriver      string
	mountTag      string
	securityModel string
	path          string
	sockFd        string
	readonly      bool
	protocol      string
}

func qemuHostDrive(opts *qemuHostDriveOpts) []cfg.Section {
	var driveSection cfg.Section
	var entries map[string]string
	deviceOpts := qemuDevEntriesOpts{dev: opts.dev}

	if opts.protocol == "9p" {
		var readonly string
		if opts.readonly {
			readonly = "on"
		} else {
			readonly = "off"
		}

		driveSection = cfg.Section{
			Name:    fmt.Sprintf(`fsdev "%s"`, opts.name),
			Comment: opts.comment,
			Entries: map[string]string{
				"fsdriver":       opts.fsdriver,
				"sock_fd":        opts.sockFd,
				"security_model": opts.securityModel,
				"readonly":       readonly,
				"path":           opts.path,
			},
		}

		deviceOpts.pciName = "virtio-9p-pci"
		deviceOpts.ccwName = "virtio-9p-ccw"
		entries = qemuDeviceEntries(&deviceOpts)
		entries["mount_tag"] = opts.mountTag
		entries["fsdev"] = opts.name
	} else if opts.protocol == "virtio-fs" {
		driveSection = cfg.Section{
			Name:    fmt.Sprintf(`chardev "%s"`, opts.name),
			Comment: opts.comment,
			Entries: map[string]string{
				"backend": "socket",
				"path":    opts.path,
			},
		}

		deviceOpts.pciName = "vhost-user-fs-pci"
		deviceOpts.ccwName = "vhost-user-fs-ccw"
		entries = qemuDeviceEntries(&deviceOpts)
		entries["tag"] = opts.mountTag
		entries["chardev"] = opts.name
	} else {
		return []cfg.Section{}
	}

	return []cfg.Section{
		driveSection,
		{
			Name:    fmt.Sprintf(`device "dev-%s%s-%s"`, opts.name, opts.nameSuffix, opts.protocol),
			Entries: entries,
		},
	}
}

type qemuDriveConfigOpts struct {
	name     string
	dev      qemuDevOpts
	protocol string
	path     string
}

func qemuDriveConfig(opts *qemuDriveConfigOpts) []cfg.Section {
	return qemuHostDrive(&qemuHostDriveOpts{
		dev: opts.dev,
		// Devices use "qemu_" prefix indicating that this is a internally named device.
		name:          fmt.Sprintf("qemu_%s", opts.name),
		nameSuffix:    "-drive",
		comment:       fmt.Sprintf("Shared %s drive (%s)", opts.name, opts.protocol),
		mountTag:      opts.name,
		protocol:      opts.protocol,
		fsdriver:      "local",
		readonly:      true,
		securityModel: "none",
		path:          opts.path,
	})
}

type qemuDriveDirOpts struct {
	dev      qemuDevOpts
	devName  string
	mountTag string
	path     string
	protocol string
	readonly bool
}

func qemuDriveDir(opts *qemuDriveDirOpts) []cfg.Section {
	return qemuHostDrive(&qemuHostDriveOpts{
		dev:           opts.dev,
		name:          fmt.Sprintf("incus_%s", opts.devName),
		comment:       fmt.Sprintf("%s drive (%s)", opts.devName, opts.protocol),
		mountTag:      opts.mountTag,
		protocol:      opts.protocol,
		fsdriver:      "local",
		readonly:      opts.readonly,
		path:          opts.path,
		securityModel: "passthrough",
	})
}

type qemuPCIPhysicalOpts struct {
	dev         qemuDevOpts
	devName     string
	pciSlotName string
}

func qemuPCIPhysical(opts *qemuPCIPhysicalOpts) []cfg.Section {
	deviceOpts := qemuDevEntriesOpts{
		dev:     opts.dev,
		pciName: "vfio-pci",
		ccwName: "vfio-ccw",
	}

	entries := qemuDeviceEntries(&deviceOpts)
	entries["host"] = opts.pciSlotName

	return []cfg.Section{{
		Name:    fmt.Sprintf(`device "%s%s"`, qemuDeviceIDPrefix, opts.devName),
		Comment: fmt.Sprintf(`PCI card ("%s" device)`, opts.devName),
		Entries: entries,
	}}
}

type qemuGPUDevPhysicalOpts struct {
	dev         qemuDevOpts
	devName     string
	pciSlotName string
	vgpu        string
	vga         bool
}

func qemuGPUDevPhysical(opts *qemuGPUDevPhysicalOpts) []cfg.Section {
	deviceOpts := qemuDevEntriesOpts{
		dev:     opts.dev,
		pciName: "vfio-pci",
		ccwName: "vfio-ccw",
	}

	entries := qemuDeviceEntries(&deviceOpts)

	if opts.vgpu != "" {
		sysfsdev := fmt.Sprintf("/sys/bus/mdev/devices/%s", opts.vgpu)
		entries["sysfsdev"] = sysfsdev
	} else {
		entries["host"] = opts.pciSlotName
	}

	if opts.vga {
		entries["x-vga"] = "on"
	}

	return []cfg.Section{{
		Name:    fmt.Sprintf(`device "%s%s"`, qemuDeviceIDPrefix, opts.devName),
		Comment: fmt.Sprintf(`GPU card ("%s" device)`, opts.devName),
		Entries: entries,
	}}
}

type qemuUSBOpts struct {
	devBus        string
	devAddr       string
	multifunction bool
	ports         int
}

func qemuUSB(opts *qemuUSBOpts) []cfg.Section {
	deviceOpts := qemuDevEntriesOpts{
		dev: qemuDevOpts{
			busName:       "pci",
			devAddr:       opts.devAddr,
			devBus:        opts.devBus,
			multifunction: opts.multifunction,
		},
		pciName: "qemu-xhci",
	}

	entries := qemuDeviceEntries(&deviceOpts)
	entries["p2"] = fmt.Sprintf("%d", opts.ports)
	entries["p3"] = fmt.Sprintf("%d", opts.ports)
	sections := []cfg.Section{{
		Name:    `device "qemu_usb"`,
		Comment: "USB controller",
		Entries: entries,
	}}

	for i := 1; i <= 3; i++ {
		chardev := fmt.Sprintf("qemu_spice-usb-chardev%d", i)
		sections = append(sections, []cfg.Section{{
			Name: fmt.Sprintf(`chardev "%s"`, chardev),
			Entries: map[string]string{
				"backend": "spicevmc",
				"name":    "usbredir",
			},
		}, {
			Name: fmt.Sprintf(`device "qemu_spice-usb%d"`, i),
			Entries: map[string]string{
				"driver":  "usb-redir",
				"chardev": chardev,
			},
		}}...)
	}

	return sections
}

type qemuTPMOpts struct {
	devName string
	path    string
	driver  string
}

func qemuTPM(opts *qemuTPMOpts) []cfg.Section {
	chardev := fmt.Sprintf("qemu_tpm-chardev_%s", opts.devName)
	tpmdev := fmt.Sprintf("qemu_tpm-tpmdev_%s", opts.devName)

	return []cfg.Section{{
		Name: fmt.Sprintf(`chardev "%s"`, chardev),
		Entries: map[string]string{
			"backend": "socket",
			"path":    opts.path,
		},
	}, {
		Name: fmt.Sprintf(`tpmdev "%s"`, tpmdev),
		Entries: map[string]string{
			"type":    "emulator",
			"chardev": chardev,
		},
	}, {
		Name: fmt.Sprintf(`device "%s%s"`, qemuDeviceIDPrefix, opts.devName),
		Entries: map[string]string{
			"driver": opts.driver,
			"tpmdev": tpmdev,
		},
	}}
}

type qemuVmgenIDOpts struct {
	guid string
}

func qemuVmgen(opts *qemuVmgenIDOpts) []cfg.Section {
	return []cfg.Section{{
		Name:    `device "vmgenid0"`,
		Comment: "VM Generation ID",
		Entries: map[string]string{
			"driver": "vmgenid",
			"guid":   opts.guid,
		},
	}}
}