-
Notifications
You must be signed in to change notification settings - Fork 164
/
kvm.go
1106 lines (990 loc) · 33 KB
/
kvm.go
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
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2017-2023 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package hypervisor
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"text/template"
"time"
zconfig "github.com/lf-edge/eve-api/go/config"
"github.com/lf-edge/eve/pkg/pillar/agentlog"
"github.com/lf-edge/eve/pkg/pillar/containerd"
"github.com/lf-edge/eve/pkg/pillar/types"
uuid "github.com/satori/go.uuid"
"github.com/sirupsen/logrus"
)
// KVMHypervisorName is a name of kvm hypervisor
const KVMHypervisorName = "kvm"
const minUringKernelTag = uint64((5 << 16) | (4 << 8) | (72 << 0))
// We build device model around PCIe topology according to best practices
// https://github.com/qemu/qemu/blob/master/docs/pcie.txt
// and
// https://libvirt.org/pci-hotplug.html
// Thus the only PCI devices plugged directly into the root (pci.0) bus are:
// 00:01.0 cirrus-vga
// 00:02.0 pcie-root-port for QEMU XHCI Host Controller
// 00:03.0 virtio-serial for hvc consoles and serial communications with the domain
// 00:0x.0 pcie-root-port for block or network device #x (where x > 2)
// 00:0y.0 virtio-9p-pci
//
// This makes everything but 9P volumes be separated from root pci bus
// and effectively hang off the bus of its own:
// 01:00.0 QEMU XHCI Host Controller (behind pcie-root-port 00:02.0)
// xx:00.0 block or network device #x (behind pcie-root-port 00:0x.0)
//
// It would be nice to figure out how to do the same with virtio-9p-pci
// eventually, but for now this is not a high priority.
//
// As discussed in https://edk2.groups.io/g/discuss/topic/windows_2019_vm_fails_to_boot/74465994
// I/O size exceeds the max SCSI I/O limitation(8M) of vhost-scsi in KVM
// we adjust max_sectors option (16384) to run Windows VM with vhost-scsi-pci and avoid errors like
// [ 259.573575] vhost_scsi_calc_sgls: requested sgl_count: 2649 exceeds pre-allocated max_sgls: 2048
const qemuConfTemplate = `# This file is automatically generated by domainmgr
[msg]
timestamp = "on"
[machine]
type = "{{.Machine}}"
dump-guest-core = "off"
{{- if .DomainStatus.CPUs }}
cpumask = "{{.DomainStatus.CPUs}}"
{{- end -}}
{{- if .DomainConfig.CPUsPinned }}
cpu-pin = "on"
{{- end -}}
{{- if eq .Machine "virt" }}
accel = "kvm:tcg"
gic-version = "host"
{{- end -}}
{{- if ne .Machine "virt" }}
accel = "kvm"
vmport = "off"
kernel-irqchip = "on"
{{- end -}}
{{- if .DomainConfig.BootLoader }}
firmware = "{{.DomainConfig.BootLoader}}"
{{- end -}}
{{- if .DomainConfig.Kernel }}
kernel = "{{.DomainConfig.Kernel}}"
{{- end -}}
{{- if .DomainConfig.Ramdisk }}
initrd = "{{.DomainConfig.Ramdisk}}"
{{- end -}}
{{- if .DomainConfig.DeviceTree }}
dtb = "{{.DomainConfig.DeviceTree}}"
{{- end -}}
{{- if .DomainConfig.ExtraArgs }}
append = "{{.DomainConfig.ExtraArgs}}"
{{ end }}
{{if ne .Machine "virt" }}
[global]
driver = "kvm-pit"
property = "lost_tick_policy"
value = "delay"
[global]
driver = "ICH9-LPC"
property = "disable_s3"
value = "1"
[global]
driver = "ICH9-LPC"
property = "disable_s4"
value = "1"
[rtc]
base = "localtime"
driftfix = "slew"
[device]
driver = "intel-iommu"
caching-mode = "on"
{{ end }}
[realtime]
mlock = "off"
[chardev "charmonitor"]
backend = "socket"
path = "` + kvmStateDir + `{{.DomainConfig.DisplayName}}/qmp"
server = "on"
wait = "off"
[mon "monitor"]
chardev = "charmonitor"
mode = "control"
[chardev "charlistener"]
backend = "socket"
path = "` + kvmStateDir + `{{.DomainConfig.DisplayName}}/listener.qmp"
server = "on"
wait = "off"
[mon "listener"]
chardev = "charlistener"
mode = "control"
[memory]
size = "{{.DomainConfig.Memory}}"
[smp-opts]
cpus = "{{.DomainConfig.VCpus}}"
sockets = "1"
cores = "{{.DomainConfig.VCpus}}"
threads = "1"
[device]
driver = "virtio-serial"
addr = "3"
[chardev "charserial0"]
backend = "socket"
mux = "on"
path = "` + kvmStateDir + `{{.DomainConfig.DisplayName}}/cons"
server = "on"
wait = "off"
logfile = "/dev/fd/1"
logappend = "on"
[device]
driver = "virtconsole"
chardev = "charserial0"
name = "org.lfedge.eve.console.0"
{{if .DomainConfig.IsOCIContainer}}
[chardev "charserial1"]
backend = "socket"
mux = "on"
path = "` + kvmStateDir + `{{.DomainConfig.DisplayName}}/prime-cons"
server = "on"
wait = "off"
logfile = "/dev/fd/1"
logappend = "on"
[device]
driver = "virtconsole"
chardev = "charserial1"
name = "org.lfedge.eve.console.prime"
{{- if .DomainConfig.EnableVncShimVM}}
[chardev "charserial2"]
backend = "vc"
[device]
driver = "virtconsole"
chardev = "charserial2"
name = "org.lfedge.eve.console.prime.forvnc"
{{- end -}}
{{end}}
{{if .DomainConfig.EnableVnc}}
[vnc "default"]
vnc = "0.0.0.0:{{if .DomainConfig.VncDisplay}}{{.DomainConfig.VncDisplay}}{{else}}0{{end}}"
to = "99"
{{- if .DomainConfig.VncPasswd}}
password = "on"
{{- end -}}
{{end}}
#[device "video0"]
# driver = "qxl-vga"
# ram_size = "67108864"
# vram_size = "67108864"
# vram64_size_mb = "0"
# vgamem_mb = "16"
# max_outputs = "1"
# bus = "pcie.0"
# addr = "0x1"
{{ if ne .DomainConfig.GPUConfig "" -}}
{{- if ne .Machine "virt" }}
[device "video0"]
driver = "VGA"
vgamem_mb = "16"
bus = "pcie.0"
addr = "0x1"
{{else}}
[device "video0"]
driver = "virtio-gpu-pci"
{{end}}
{{- end}}
[device "pci.2"]
driver = "pcie-root-port"
port = "12"
chassis = "2"
bus = "pcie.0"
addr = "0x2"
[device "usb"]
driver = "qemu-xhci"
p2 = "15"
p3 = "15"
bus = "pci.2"
addr = "0x0"
{{if ne .Machine "virt" }}
[device "input0"]
driver = "usb-tablet"
bus = "usb.0"
port = "1"
{{else}}
[device "input0"]
driver = "usb-kbd"
bus = "usb.0"
port = "1"
[device "input1"]
driver = "usb-mouse"
bus = "usb.0"
port = "2"
{{end}}`
const qemuDiskTemplate = `
{{if eq .Devtype "cdrom"}}
[drive "drive-sata0-{{.DiskID}}"]
file = "{{.FileLocation}}"
format = "{{.Format | Fmt}}"
if = "none"
media = "cdrom"
readonly = "on"
[device "sata0-{{.SATAId}}"]
drive = "drive-sata0-{{.DiskID}}"
{{- if eq .Machine "virt"}}
driver = "usb-storage"
{{else}}
driver = "ide-cd"
bus = "ide.{{.SATAId}}"
{{- end }}
{{else if eq .Devtype "9P"}}
[fsdev "fsdev{{.DiskID}}"]
fsdriver = "local"
security_model = "none"
multidevs = "remap"
path = "{{.FileLocation}}"
[device "fs{{.DiskID}}"]
driver = "virtio-9p-pci"
fsdev = "fsdev{{.DiskID}}"
mount_tag = "share_dir"
addr = "{{printf "0x%x" .PCIId}}"
{{else}}
[device "pci.{{.PCIId}}"]
driver = "pcie-root-port"
port = "1{{.PCIId}}"
chassis = "{{.PCIId}}"
bus = "pcie.0"
addr = "{{printf "0x%x" .PCIId}}"
{{if eq .WWN ""}}
[drive "drive-virtio-disk{{.DiskID}}"]
file = "{{.FileLocation}}"
format = "{{.Format | Fmt}}"
aio = "{{.AioType}}"
cache = "writeback"
if = "none"
{{if .ReadOnly}} readonly = "on"{{end}}
{{- if eq .Devtype "legacy"}}
[device "ahci.{{.PCIId}}"]
bus = "pci.{{.PCIId}}"
driver = "ahci"
[device "ahci-disk{{.DiskID}}"]
driver = "ide-hd"
bus = "ahci.{{.PCIId}}.0"
{{- else}}
[device "virtio-disk{{.DiskID}}"]
driver = "virtio-blk-pci"
scsi = "off"
bus = "pci.{{.PCIId}}"
addr = "0x0"
{{- end}}
drive = "drive-virtio-disk{{.DiskID}}"
{{- else}}
[device "vhost-disk{{.DiskID}}"]
driver = "vhost-scsi-pci"
max_sectors = "16384"
wwpn = "{{.WWN}}"
bus = "pci.{{.PCIId}}"
addr = "0x0"
num_queues = "{{.NumQueues}}"
{{- end}}
{{end}}`
const qemuNetTemplate = `
[device "pci.{{.PCIId}}"]
driver = "pcie-root-port"
port = "1{{.PCIId}}"
chassis = "{{.PCIId}}"
bus = "pcie.0"
multifunction = "on"
addr = "{{printf "0x%x" .PCIId}}"
[netdev "hostnet{{.NetID}}"]
type = "tap"
ifname = "{{.Vif}}"
br = "{{.Bridge}}"
script = "/etc/xen/scripts/qemu-ifup"
downscript = "no"
[device "net{{.NetID}}"]
driver = "{{.Driver}}"
netdev = "hostnet{{.NetID}}"
mac = "{{.Mac}}"
bus = "pci.{{.PCIId}}"
addr = "0x0"
{{- if and (eq .Driver "virtio-net-pci") (ne .MTU 0) }}
host_mtu = "{{.MTU}}"
{{- end}}
`
const qemuPciPassthruTemplate = `
[device "pci.{{.PCIId}}"]
driver = "pcie-root-port"
port = "1{{.PCIId}}"
chassis = "{{.PCIId}}"
bus = "pcie.0"
multifunction = "on"
addr = "{{printf "0x%x" .PCIId}}"
[device]
driver = "vfio-pci"
host = "{{.PciShortAddr}}"
bus = "pci.{{.PCIId}}"
addr = "0x0"
{{- if .Xvga }}
x-vga = "on"
{{- end -}}
{{- if .Xopregion }}
x-igd-opregion = "on"
{{- end -}}
`
const qemuSerialTemplate = `
[chardev "charserial-usr{{.ID}}"]
{{- if eq .Machine "virt"}}
backend = "serial"
{{- else}}
backend = "tty"
{{- end}}
path = "{{.SerialPortName}}"
[device "serial-usr{{.ID}}"]
{{- if eq .Machine "virt"}}
driver = "pci-serial"
{{- else}}
driver = "isa-serial"
{{- end}}
chardev = "charserial-usr{{.ID}}"
`
const qemuCANBusTemplate = `
[object "canbus{{.ID}}"]
qom-type = "can-bus"
[device "{{.IfName}}"]
driver = "kvaser_pci"
canbus = "canbus{{.ID}}"
[object "canhost{{.ID}}"]
qom-type = "can-host-socketcan"
canbus = "canbus{{.ID}}"
if = "{{.HostIfName}}"
`
const kvmStateDir = "/run/hypervisor/kvm/"
const sysfsVfioPciBind = "/sys/bus/pci/drivers/vfio-pci/bind"
const sysfsPciDriversProbe = "/sys/bus/pci/drivers_probe"
const vfioDriverPath = "/sys/bus/pci/drivers/vfio-pci"
// KvmContext is a KVM domains map 0-1 to anchor device model UNIX processes (qemu or firecracker)
// For every anchor process we maintain the following entry points in the
// /run/hypervisor/kvm/DOMAIN_NAME:
//
// pid - contains PID of the anchor process
// qmp - UNIX domain socket that allows us to talk to anchor process
// cons - symlink to /dev/pts/X that allows us to talk to the serial console of the domain
//
// In addition to that, we also maintain DOMAIN_NAME -> PID mapping in KvmContext, so we don't
// have to look things up in the filesystem all the time (this also allows us to filter domains
// that may be created by others)
type KvmContext struct {
ctrdContext
// for now the following is statically configured and can not be changed per domain
devicemodel string
dmExec string
dmArgs []string
dmCPUArgs []string
dmFmlCPUArgs []string
capabilities *types.Capabilities
}
func newKvm() Hypervisor {
ctrdCtx, err := initContainerd()
if err != nil {
logrus.Fatalf("couldn't initialize containerd (this should not happen): %v. Exiting.", err)
return nil // it really never returns on account of above
}
// later on we may want to pass device model machine type in DomainConfig directly;
// for now -- lets just pick a static device model based on the host architecture
// "-cpu host",
// -cpu IvyBridge-IBRS,ss=on,vmx=on,movbe=on,hypervisor=on,arat=on,tsc_adjust=on,mpx=on,rdseed=on,smap=on,clflushopt=on,sha-ni=on,umip=on,md-clear=on,arch-capabilities=on,xsaveopt=on,xsavec=on,xgetbv1=on,xsaves=on,pdpe1gb=on,3dnowprefetch=on,avx=off,f16c=off,hv_time,hv_relaxed,hv_vapic,hv_spinlocks=0x1fff
switch runtime.GOARCH {
case "arm64":
return KvmContext{
ctrdContext: *ctrdCtx,
devicemodel: "virt",
dmExec: "/usr/lib/xen/bin/qemu-system-aarch64",
dmArgs: []string{"-display", "none", "-S", "-no-user-config", "-nodefaults", "-no-shutdown", "-overcommit", "mem-lock=on", "-overcommit", "cpu-pm=on", "-serial", "chardev:charserial0"},
dmCPUArgs: []string{"-cpu", "host"},
dmFmlCPUArgs: []string{"-cpu", "host"},
}
case "amd64":
return KvmContext{
//nolint:godox // FIXME: Removing "-overcommit", "mem-lock=on", "-overcommit" for now, revisit it later as part of resource partitioning
ctrdContext: *ctrdCtx,
devicemodel: "pc-q35-3.1",
dmExec: "/usr/lib/xen/bin/qemu-system-x86_64",
dmArgs: []string{"-display", "none", "-S", "-no-user-config", "-nodefaults", "-no-shutdown", "-serial", "chardev:charserial0", "-no-hpet"},
dmCPUArgs: []string{"-cpu", "host"},
dmFmlCPUArgs: []string{"-cpu", "host,hv_time,hv_relaxed,hv_vendor_id=eveitis,hypervisor=off,kvm=off"},
}
}
return nil
}
// GetCapabilities returns capabilities of the kvm hypervisor
func (ctx KvmContext) GetCapabilities() (*types.Capabilities, error) {
if ctx.capabilities != nil {
return ctx.capabilities, nil
}
vtd, err := ctx.checkIOVirtualisation()
if err != nil {
return nil, fmt.Errorf("fail in check IOVirtualization: %v", err)
}
ctx.capabilities = &types.Capabilities{
HWAssistedVirtualization: true,
IOVirtualization: vtd,
CPUPinning: true,
UseVHost: true,
}
return ctx.capabilities, nil
}
// CountMemOverhead - returns the memory overhead estimation for a domain.
func (ctx KvmContext) CountMemOverhead(domainName string, domainUUID uuid.UUID, domainRAMSize int64, vmmMaxMem int64,
domainMaxCpus int64, domainVCpus int64, domainIoAdapterList []types.IoAdapter, aa *types.AssignableAdapters,
globalConfig *types.ConfigItemValueMap) (uint64, error) {
result, err := vmmOverhead(domainName, domainUUID, domainRAMSize, vmmMaxMem, domainMaxCpus, domainVCpus, domainIoAdapterList, aa, globalConfig)
return uint64(result), err
}
func (ctx KvmContext) checkIOVirtualisation() (bool, error) {
f, err := os.Open("/sys/kernel/iommu_groups")
if err == nil {
files, err := f.Readdirnames(0)
if err != nil {
return false, err
}
if len(files) != 0 {
return true, nil
}
}
return false, err
}
// Name returns the name of the kvm hypervisor
func (ctx KvmContext) Name() string {
return KVMHypervisorName
}
// Task returns either the kvm context or the containerd context depending on the domain status
func (ctx KvmContext) Task(status *types.DomainStatus) types.Task {
if status.VirtualizationMode == types.NOHYPER {
return ctx.ctrdContext
}
return ctx
}
func estimatedVMMOverhead(domainName string, aa *types.AssignableAdapters, domainAdapterList []types.IoAdapter,
domainUUID uuid.UUID, domainRAMSize int64, domainMaxCpus int64, domainVcpus int64) (int64, error) {
var overhead int64
mmioOverhead, err := mmioVMMOverhead(domainName, aa, domainAdapterList, domainUUID)
if err != nil {
return 0, logError("mmioVMMOverhead() failed for domain %s: %v",
domainName, err)
}
overhead = undefinedVMMOverhead() + ramVMMOverhead(domainRAMSize) +
qemuVMMOverhead() + cpuVMMOverhead(domainMaxCpus, domainVcpus) + mmioOverhead
return overhead, nil
}
func ramVMMOverhead(ramMemory int64) int64 {
// 0.224% of the total RAM allocated for VM in bytes
// this formula is precise and well explained in the following QEMU issue:
// https://gitlab.com/qemu-project/qemu/-/issues/1003
// This is a best case scenario because it assumes that all PTEs are allocated
// sequentially. In reality, there will be some fragmentation and the overhead
// for now 2.5% (~10x) is a good approximation until we have a better way to
// predict the memory usage of the VM.
return ramMemory * 1024 * 25 / 1000
}
// overhead for qemu binaries and libraries
func qemuVMMOverhead() int64 {
return 20 << 20 // Mb in bytes
}
// overhead for VMM memory mapped IO
// it fluctuates between 0.66 and 0.81 % of MMIO total size
// for all mapped devices. Set it to 1% to be on the safe side
// this can be a pretty big number for GPUs with very big
// aperture size (e.g. 64G for NVIDIA A40)
func mmioVMMOverhead(domainName string, aa *types.AssignableAdapters, domainAdapterList []types.IoAdapter,
domainUUID uuid.UUID) (int64, error) {
var pciAssignments []pciDevice
var mmioSize uint64
for _, adapter := range domainAdapterList {
logrus.Debugf("processing adapter %d %s\n", adapter.Type, adapter.Name)
aaList := aa.LookupIoBundleAny(adapter.Name)
// We reserved it in handleCreate so nobody could have stolen it
if len(aaList) == 0 {
return 0, logError("IoBundle disappeared %d %s for %s\n",
adapter.Type, adapter.Name, domainName)
}
for _, ib := range aaList {
if ib == nil {
continue
}
if ib.UsedByUUID != domainUUID {
return 0, logError("IoBundle not ours %s: %d %s for %s\n",
ib.UsedByUUID, adapter.Type, adapter.Name,
domainName)
}
if ib.PciLong != "" && ib.UsbAddr == "" {
logrus.Infof("Adding PCI device <%s>\n", ib.PciLong)
tap := pciDevice{pciLong: ib.PciLong, ioType: ib.Type}
pciAssignments = addNoDuplicatePCI(pciAssignments, tap)
}
}
}
for _, dev := range pciAssignments {
logrus.Infof("PCI device %s %d\n", dev.pciLong, dev.ioType)
// read the size of the PCI device aperture. Only GPU/VGA devices for now
if dev.ioType != types.IoOther && dev.ioType != types.IoHDMI {
continue
}
// skip bridges
isBridge, err := dev.isBridge()
if err != nil {
// do not treat as fatal error
logrus.Warnf("Can't read PCI device class, treat as bridge %s: %v\n",
dev.pciLong, err)
isBridge = true
}
if isBridge {
logrus.Infof("Skipping bridge %s\n", dev.pciLong)
continue
}
// read all resources of the PCI device
resources, err := dev.readResources()
if err != nil {
return 0, logError("Can't read PCI device resources %s: %v\n",
dev.pciLong, err)
}
// calculate the size of the MMIO region
for _, res := range resources {
if res.valid() && res.isMem() {
mmioSize += res.size()
}
}
}
// 1% of the total MMIO size in bytes
mmioOverhead := int64(mmioSize) / 100
logrus.Infof("MMIO size: %d / overhead: %d for %s", mmioSize, mmioOverhead, domainName)
return int64(mmioOverhead), nil
}
// each vCPU requires about 3MB of memory
func cpuVMMOverhead(maxCpus int64, vcpus int64) int64 {
cpus := maxCpus
if cpus == 0 {
cpus = vcpus
}
return cpus * (3 << 20) // Mb in bytes
}
// memory allocated by QEMU for its own purposes.
// statistical analysis did not revile any correlation between
// VM configuration (devices, nr of vcpus, etc) and this number
// however the size of disk space affects it. Probably some internal
// QEMU caches are allocated based on the size of the disk image.
// it requires more investigation.
func undefinedVMMOverhead() int64 {
return 350 << 20 // Mb in bytes
}
func vmmOverhead(domainName string, domainUUID uuid.UUID, domainRAMSize int64, vmmMaxMem int64, domainMaxCpus int64, domainVCpus int64, domainIoAdapterList []types.IoAdapter, aa *types.AssignableAdapters, globalConfig *types.ConfigItemValueMap) (int64, error) {
var overhead int64
// Fetch VMM max memory setting (aka vmm overhead)
overhead = vmmMaxMem << 10
// Global node setting has a higher priority
if globalConfig != nil {
VmmOverheadOverrideCfgItem, ok := globalConfig.GlobalSettings[types.VmmMemoryLimitInMiB]
if !ok {
return 0, logError("Missing key %s", string(types.VmmMemoryLimitInMiB))
}
if VmmOverheadOverrideCfgItem.IntValue > 0 {
overhead = int64(VmmOverheadOverrideCfgItem.IntValue) << 20
}
}
if overhead == 0 {
overhead, err := estimatedVMMOverhead(domainName, aa, domainIoAdapterList, domainUUID, domainRAMSize, domainMaxCpus, domainVCpus)
if err != nil {
return 0, logError("estimatedVMMOverhead() failed for domain %s: %v",
domainName, err)
}
return overhead, nil
}
return overhead, nil
}
// Setup sets up kvm
func (ctx KvmContext) Setup(status types.DomainStatus, config types.DomainConfig,
aa *types.AssignableAdapters, globalConfig *types.ConfigItemValueMap, file *os.File) error {
diskStatusList := status.DiskStatusList
domainName := status.DomainName
domainUUID := status.UUIDandVersion.UUID
// first lets build the domain config
if err := ctx.CreateDomConfig(domainName, config, status, diskStatusList,
aa, globalConfig, file); err != nil {
return logError("failed to build domain config: %v", err)
}
dmArgs := ctx.dmArgs
if config.VirtualizationMode == types.FML {
dmArgs = append(dmArgs, ctx.dmFmlCPUArgs...)
} else {
dmArgs = append(dmArgs, ctx.dmCPUArgs...)
}
if config.MetaDataType == types.MetaDataOpenStack {
// we need to set product_name to support cloud-init
dmArgs = append(dmArgs, "-smbios", "type=1,product=OpenStack Compute")
}
os.MkdirAll(kvmStateDir+domainName, 0777)
args := []string{ctx.dmExec}
args = append(args, dmArgs...)
args = append(args, "-name", domainName,
"-uuid", domainUUID.String(),
"-readconfig", file.Name(),
"-pidfile", kvmStateDir+domainName+"/pid")
spec, err := ctx.setupSpec(&status, &config, status.OCIConfigDir)
if err != nil {
return logError("failed to load OCI spec for domain %s: %v", status.DomainName, err)
}
if err = spec.AddLoader("/containers/services/xen-tools"); err != nil {
return logError("failed to add kvm hypervisor loader to domain %s: %v", status.DomainName, err)
}
overhead, err := vmmOverhead(domainName, domainUUID, int64(config.Memory), int64(config.VMMMaxMem), int64(config.MaxCpus), int64(config.VCpus), config.IoAdapterList, aa, globalConfig)
if err != nil {
return logError("vmmOverhead() failed for domain %s: %v",
status.DomainName, err)
}
logrus.Debugf("Qemu overhead for domain %s is %d bytes", status.DomainName, overhead)
spec.AdjustMemLimit(config, overhead)
spec.Get().Process.Args = args
logrus.Infof("Hypervisor args: %v", args)
if err := spec.CreateContainer(true); err != nil {
return logError("Failed to create container for task %s from %v: %v", status.DomainName, config, err)
}
return nil
}
// Coalesce per-app `EnableVncShimVM` flag and global `debug.enable.vnc.shim.vm`
// debug flag, making sure we don't activate VNC for shim VM if VNC for
// this application is disabled.
func isVncShimVMEnabled(
globalConfig *types.ConfigItemValueMap, config types.DomainConfig) bool {
globalShimVnc := false
if globalConfig != nil {
item, ok := globalConfig.GlobalSettings[types.VncShimVMAccess]
globalShimVnc = ok && item.BoolValue
}
return config.EnableVnc && (config.EnableVncShimVM || globalShimVnc)
}
// CreateDomConfig creates a domain config (a qemu config file,
// typically named something like xen-%d.cfg)
func (ctx KvmContext) CreateDomConfig(domainName string,
config types.DomainConfig, status types.DomainStatus,
diskStatusList []types.DiskStatus, aa *types.AssignableAdapters,
globalConfig *types.ConfigItemValueMap, file *os.File) error {
tmplCtx := struct {
Machine string
types.DomainConfig
types.DomainStatus
}{ctx.devicemodel, config, status}
tmplCtx.DomainConfig.Memory = (config.Memory + 1023) / 1024
tmplCtx.DomainConfig.EnableVncShimVM =
isVncShimVMEnabled(globalConfig, config)
tmplCtx.DomainConfig.DisplayName = domainName
// render global device model settings
t, _ := template.New("qemu").Parse(qemuConfTemplate)
if err := t.Execute(file, tmplCtx); err != nil {
return logError("can't write to config file %s (%v)", file.Name(), err)
}
// render disk device model settings
diskContext := struct {
Machine string
PCIId, DiskID, SATAId, NumQueues int
AioType string
types.DiskStatus
}{Machine: ctx.devicemodel, PCIId: 4, DiskID: 0, SATAId: 0, AioType: "io_uring", NumQueues: config.VCpus}
t, _ = template.New("qemuDisk").
Funcs(template.FuncMap{"Fmt": func(f zconfig.Format) string { return strings.ToLower(f.String()) }}).
Parse(qemuDiskTemplate)
for _, ds := range diskStatusList {
if ds.Devtype == "" {
continue
}
if ds.Devtype == "AppCustom" {
// This is application custom data. It is forwarded to the VM
// differently - as a download url in zedrouter
continue
}
diskContext.DiskStatus = ds
if err := t.Execute(file, diskContext); err != nil {
return logError("can't write to config file %s (%v)", file.Name(), err)
}
if diskContext.Devtype == "cdrom" {
diskContext.SATAId = diskContext.SATAId + 1
} else {
diskContext.PCIId = diskContext.PCIId + 1
}
diskContext.DiskID = diskContext.DiskID + 1
}
// render network device model settings
netContext := struct {
PCIId, NetID int
Driver string
Mac, Bridge, Vif string
MTU uint16
}{PCIId: diskContext.PCIId, NetID: 0}
t, _ = template.New("qemuNet").Parse(qemuNetTemplate)
for _, net := range config.VifList {
netContext.Mac = net.Mac.String()
netContext.Bridge = net.Bridge
netContext.Vif = net.Vif
if config.VirtualizationMode == types.LEGACY {
netContext.Driver = "e1000"
} else {
netContext.Driver = "virtio-net-pci"
}
netContext.MTU = net.MTU
if err := t.Execute(file, netContext); err != nil {
return logError("can't write to config file %s (%v)", file.Name(), err)
}
netContext.PCIId = netContext.PCIId + 1
netContext.NetID = netContext.NetID + 1
}
// Gather all PCI assignments into a single line
var pciAssignments []pciDevice
// Gather all serial assignments into a single line
var serialAssignments []string
// Gather all CAN Bus assignments into a single line
canBusAssignments := make(map[string]string)
for _, adapter := range config.IoAdapterList {
logrus.Debugf("processing adapter %d %s\n", adapter.Type, adapter.Name)
list := aa.LookupIoBundleAny(adapter.Name)
// We reserved it in handleCreate so nobody could have stolen it
if len(list) == 0 {
logrus.Fatalf("IoBundle disappeared %d %s for %s\n",
adapter.Type, adapter.Name, domainName)
}
for _, ib := range list {
if ib == nil {
continue
}
if ib.UsedByUUID != config.UUIDandVersion.UUID {
logrus.Fatalf("IoBundle not ours %s: %d %s for %s\n",
ib.UsedByUUID, adapter.Type, adapter.Name,
domainName)
}
if ib.PciLong != "" && ib.UsbAddr == "" {
logrus.Infof("Adding PCI device <%v>\n", ib.PciLong)
tap := pciDevice{pciLong: ib.PciLong, ioType: ib.Type}
pciAssignments = addNoDuplicatePCI(pciAssignments, tap)
}
if ib.Serial != "" {
logrus.Infof("Adding serial <%s>\n", ib.Serial)
serialAssignments = addNoDuplicate(serialAssignments, ib.Serial)
}
if ib.Type == types.IoLCAN && ib.Ifname != "" {
var canIfName string
if ib.Logicallabel == "" {
canIfName = ib.Phylabel
} else {
canIfName = ib.Logicallabel
}
if canIfName != "" {
logrus.Infof("Adding CAN interface <%s>", canIfName)
if canBusAssignments[canIfName] == "" {
canBusAssignments[canIfName] = ib.Ifname
}
}
}
}
}
if len(pciAssignments) != 0 {
pciPTContext := struct {
PCIId int
PciShortAddr string
Xvga bool
Xopregion bool
}{PCIId: netContext.PCIId, PciShortAddr: "", Xvga: false, Xopregion: false}
t, _ = template.New("qemuPciPT").Parse(qemuPciPassthruTemplate)
for _, pa := range pciAssignments {
short := types.PCILongToShort(pa.pciLong)
pciPTContext.Xvga = pa.isVGA()
if vendor, err := pa.vid(); err == nil {
// check for Intel vendor
if vendor == "0x8086" {
if pciPTContext.Xvga {
// we set opregion for Intel vga
// https://github.com/qemu/qemu/blob/stable-5.0/docs/igd-assign.txt#L91-L96
pciPTContext.Xopregion = true
}
}
}
pciPTContext.PciShortAddr = short
if err := t.Execute(file, pciPTContext); err != nil {
return logError("can't write PCI Passthrough to config file %s (%v)", file.Name(), err)
}
pciPTContext.Xvga = false
pciPTContext.Xopregion = false
pciPTContext.PCIId = pciPTContext.PCIId + 1
}
}
if len(serialAssignments) != 0 {
serialPortContext := struct {
Machine string
SerialPortName string
ID int
}{Machine: ctx.devicemodel, SerialPortName: "", ID: 0}
t, _ = template.New("qemuSerial").Parse(qemuSerialTemplate)
for id, serial := range serialAssignments {
serialPortContext.SerialPortName = serial
fmt.Printf("id for serial is %d\n", id)
serialPortContext.ID = id
if err := t.Execute(file, serialPortContext); err != nil {
return logError("can't write serial assignment to config file %s (%v)", file.Name(), err)
}
}
}
if len(canBusAssignments) != 0 {
canIfContext := struct {
Machine string
IfName string
HostIfName string
ID int
}{Machine: ctx.devicemodel, IfName: "", HostIfName: "", ID: 0}
t, err := template.New("qemuCANBus").Parse(qemuCANBusTemplate)
if err != nil {
return logError("can't create CAN Bus configuration template: %v", err)
}
id := 0
for canIf, canHostIf := range canBusAssignments {
logrus.Infof("CAN interface %s connected to host CAN %s\n", canIf, canHostIf)
canIfContext.IfName = canIf
canIfContext.HostIfName = canHostIf
canIfContext.ID = id
id++
if err := t.Execute(file, canIfContext); err != nil {
return logError("can't write CAN Bus assignment to config file %s (%v)", file.Name(), err)
}
}
}
return nil
}
func waitForQmp(domainName string, available bool) error {
maxDelay := time.Second * 10
delay := time.Second
var waited time.Duration
var err error
for {
logrus.Infof("waitForQmp for %s %t: waiting for %v", domainName, available, delay)
if delay != 0 {
time.Sleep(delay)
waited += delay
}
sock := GetQmpExecutorSocket(domainName)
if _, err = getQemuStatus(sock); available == (err == nil) {
logrus.Infof("waitForQmp for %s %t done", domainName, available)
return nil
}
if waited > maxDelay {
// Give up
logrus.Warnf("waitForQmp for %s %t: giving up", domainName, available)
if available {
return logError("Giving up waiting to connect to QEMU Monitor Protocol socket %s from VM %s, error: %v", sock, domainName, err)
}
return logError("Giving up waiting to cleanup VM %s, QEMU Monitor Protocol socket %s is still available", domainName, sock)
}
delay = 2 * delay
if delay > time.Minute {
delay = time.Minute
}
}
}
// Start starts a domain
func (ctx KvmContext) Start(domainName string) error {
logrus.Infof("starting KVM domain %s", domainName)
if err := ctx.ctrdContext.Start(domainName); err != nil {
logrus.Errorf("couldn't start task for domain %s: %v", domainName, err)
return err
}
logrus.Infof("done launching qemu device model")
if err := waitForQmp(domainName, true); err != nil {
logrus.Errorf("Error waiting for Qmp for domain %s: %v", domainName, err)
return err
}
logrus.Infof("done launching qemu device model")
qmpFile := GetQmpExecutorSocket(domainName)
logrus.Debugf("starting qmpEventHandler")
logrus.Infof("Creating %s at %s", "qmpEventHandler", agentlog.GetMyStack())
go qmpEventHandler(getQmpListenerSocket(domainName), GetQmpExecutorSocket(domainName))
annotations, err := ctx.ctrdContext.Annotations(domainName)
if err != nil {