]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuServer/CPUConfig.pm
validate_cpu_conf: return config
[qemu-server.git] / PVE / QemuServer / CPUConfig.pm
1 package PVE::QemuServer::CPUConfig;
2
3 use strict;
4 use warnings;
5
6 use PVE::JSONSchema;
7 use PVE::Cluster qw(cfs_register_file cfs_read_file);
8 use PVE::QemuServer::Helpers qw(min_version);
9
10 use base qw(PVE::SectionConfig Exporter);
11
12 our @EXPORT_OK = qw(
13 print_cpu_device
14 get_cpu_options
15 );
16
17 # under certain race-conditions, this module might be loaded before pve-cluster
18 # has started completely, so ensure we don't prevent the FUSE mount with our dir
19 if (PVE::Cluster::check_cfs_is_mounted(1)) {
20 mkdir "/etc/pve/virtual-guest";
21 }
22
23 my $default_filename = "virtual-guest/cpu-models.conf";
24 cfs_register_file($default_filename,
25 sub { PVE::QemuServer::CPUConfig->parse_config(@_); },
26 sub { PVE::QemuServer::CPUConfig->write_config(@_); });
27
28 sub load_custom_model_conf {
29 return cfs_read_file($default_filename);
30 }
31
32 my $cpu_vendor_list = {
33 # Intel CPUs
34 486 => 'GenuineIntel',
35 pentium => 'GenuineIntel',
36 pentium2 => 'GenuineIntel',
37 pentium3 => 'GenuineIntel',
38 coreduo => 'GenuineIntel',
39 core2duo => 'GenuineIntel',
40 Conroe => 'GenuineIntel',
41 Penryn => 'GenuineIntel',
42 Nehalem => 'GenuineIntel',
43 'Nehalem-IBRS' => 'GenuineIntel',
44 Westmere => 'GenuineIntel',
45 'Westmere-IBRS' => 'GenuineIntel',
46 SandyBridge => 'GenuineIntel',
47 'SandyBridge-IBRS' => 'GenuineIntel',
48 IvyBridge => 'GenuineIntel',
49 'IvyBridge-IBRS' => 'GenuineIntel',
50 Haswell => 'GenuineIntel',
51 'Haswell-IBRS' => 'GenuineIntel',
52 'Haswell-noTSX' => 'GenuineIntel',
53 'Haswell-noTSX-IBRS' => 'GenuineIntel',
54 Broadwell => 'GenuineIntel',
55 'Broadwell-IBRS' => 'GenuineIntel',
56 'Broadwell-noTSX' => 'GenuineIntel',
57 'Broadwell-noTSX-IBRS' => 'GenuineIntel',
58 'Skylake-Client' => 'GenuineIntel',
59 'Skylake-Client-IBRS' => 'GenuineIntel',
60 'Skylake-Client-noTSX-IBRS' => 'GenuineIntel',
61 'Skylake-Server' => 'GenuineIntel',
62 'Skylake-Server-IBRS' => 'GenuineIntel',
63 'Skylake-Server-noTSX-IBRS' => 'GenuineIntel',
64 'Cascadelake-Server' => 'GenuineIntel',
65 'Cascadelake-Server-noTSX' => 'GenuineIntel',
66 KnightsMill => 'GenuineIntel',
67 'Icelake-Client' => 'GenuineIntel',
68 'Icelake-Client-noTSX' => 'GenuineIntel',
69 'Icelake-Server' => 'GenuineIntel',
70 'Icelake-Server-noTSX' => 'GenuineIntel',
71
72 # AMD CPUs
73 athlon => 'AuthenticAMD',
74 phenom => 'AuthenticAMD',
75 Opteron_G1 => 'AuthenticAMD',
76 Opteron_G2 => 'AuthenticAMD',
77 Opteron_G3 => 'AuthenticAMD',
78 Opteron_G4 => 'AuthenticAMD',
79 Opteron_G5 => 'AuthenticAMD',
80 EPYC => 'AuthenticAMD',
81 'EPYC-IBPB' => 'AuthenticAMD',
82 'EPYC-Rome' => 'AuthenticAMD',
83
84 # generic types, use vendor from host node
85 host => 'default',
86 kvm32 => 'default',
87 kvm64 => 'default',
88 qemu32 => 'default',
89 qemu64 => 'default',
90 max => 'default',
91 };
92
93 my @supported_cpu_flags = (
94 'pcid',
95 'spec-ctrl',
96 'ibpb',
97 'ssbd',
98 'virt-ssbd',
99 'amd-ssbd',
100 'amd-no-ssb',
101 'pdpe1gb',
102 'md-clear',
103 'hv-tlbflush',
104 'hv-evmcs',
105 'aes'
106 );
107 my $cpu_flag_supported_re = qr/([+-])(@{[join('|', @supported_cpu_flags)]})/;
108 my $cpu_flag_any_re = qr/([+-])([a-zA-Z0-9\-_\.]+)/;
109
110 our $qemu_cmdline_cpu_re = qr/^((?>[+-]?[\w\-\._=]+,?)+)$/;
111
112 my $cpu_fmt = {
113 cputype => {
114 description => "Emulated CPU type. Can be default or custom name (custom model names must be prefixed with 'custom-').",
115 type => 'string',
116 format_description => 'string',
117 default => 'kvm64',
118 default_key => 1,
119 optional => 1,
120 },
121 'reported-model' => {
122 description => "CPU model and vendor to report to the guest. Must be a QEMU/KVM supported model."
123 . " Only valid for custom CPU model definitions, default models will always report themselves to the guest OS.",
124 type => 'string',
125 enum => [ sort { lc("$a") cmp lc("$b") } keys %$cpu_vendor_list ],
126 default => 'kvm64',
127 optional => 1,
128 },
129 hidden => {
130 description => "Do not identify as a KVM virtual machine.",
131 type => 'boolean',
132 optional => 1,
133 default => 0
134 },
135 'hv-vendor-id' => {
136 type => 'string',
137 pattern => qr/[a-zA-Z0-9]{1,12}/,
138 format_description => 'vendor-id',
139 description => 'The Hyper-V vendor ID. Some drivers or programs inside Windows guests need a specific ID.',
140 optional => 1,
141 },
142 flags => {
143 description => "List of additional CPU flags separated by ';'."
144 . " Use '+FLAG' to enable, '-FLAG' to disable a flag."
145 . " Custom CPU models can specify any flag supported by"
146 . " QEMU/KVM, VM-specific flags must be from the following"
147 . " set for security reasons: @{[join(', ', @supported_cpu_flags)]}.",
148 format_description => '+FLAG[;-FLAG...]',
149 type => 'string',
150 pattern => qr/$cpu_flag_any_re(;$cpu_flag_any_re)*/,
151 optional => 1,
152 },
153 'phys-bits' => {
154 type => 'string',
155 format => 'pve-phys-bits',
156 format_description => '8-64|host',
157 description => "The physical memory address bits that are reported to"
158 . " the guest OS. Should be smaller or equal to the host's."
159 . " Set to 'host' to use value from host CPU, but note that"
160 . " doing so will break live migration to CPUs with other values.",
161 optional => 1,
162 },
163 };
164
165 PVE::JSONSchema::register_format('pve-phys-bits', \&parse_phys_bits);
166 sub parse_phys_bits {
167 my ($str, $noerr) = @_;
168
169 my $err_msg = "value must be an integer between 8 and 64 or 'host'\n";
170
171 if ($str !~ m/^(host|\d{1,2})$/) {
172 die $err_msg if !$noerr;
173 return undef;
174 }
175
176 if ($str =~ m/^\d+$/ && (int($str) < 8 || int($str) > 64)) {
177 die $err_msg if !$noerr;
178 return undef;
179 }
180
181 return $str;
182 }
183
184 # $cpu_fmt describes both the CPU config passed as part of a VM config, as well
185 # as the definition of a custom CPU model. There are some slight differences
186 # though, which we catch in the custom validation functions below.
187 PVE::JSONSchema::register_format('pve-cpu-conf', $cpu_fmt, \&validate_cpu_conf);
188 sub validate_cpu_conf {
189 my ($cpu) = @_;
190
191 # required, but can't be forced in schema since it's encoded in section
192 # header for custom models
193 die "CPU is missing cputype\n" if !$cpu->{cputype};
194
195 return $cpu;
196 }
197 PVE::JSONSchema::register_format('pve-vm-cpu-conf', $cpu_fmt, \&validate_vm_cpu_conf);
198 sub validate_vm_cpu_conf {
199 my ($cpu) = @_;
200
201 validate_cpu_conf($cpu);
202
203 my $cputype = $cpu->{cputype};
204
205 # a VM-specific config is only valid if the cputype exists
206 if (is_custom_model($cputype)) {
207 # dies on unknown model
208 get_custom_model($cputype);
209 } else {
210 die "Built-in cputype '$cputype' is not defined (missing 'custom-' prefix?)\n"
211 if !defined($cpu_vendor_list->{$cputype});
212 }
213
214 # in a VM-specific config, certain properties are limited/forbidden
215
216 die "VM-specific CPU flags must be a subset of: @{[join(', ', @supported_cpu_flags)]}\n"
217 if ($cpu->{flags} && $cpu->{flags} !~ m/$cpu_flag_supported_re(;$cpu_flag_supported_re)*/);
218
219 die "Property 'reported-model' not allowed in VM-specific CPU config.\n"
220 if defined($cpu->{'reported-model'});
221
222 return $cpu;
223 }
224
225 # Section config settings
226 my $defaultData = {
227 # shallow copy, since SectionConfig modifies propertyList internally
228 propertyList => { %$cpu_fmt },
229 };
230
231 sub private {
232 return $defaultData;
233 }
234
235 sub options {
236 return { %$cpu_fmt };
237 }
238
239 sub type {
240 return 'cpu-model';
241 }
242
243 sub parse_section_header {
244 my ($class, $line) = @_;
245
246 my ($type, $sectionId, $errmsg, $config) =
247 $class->SUPER::parse_section_header($line);
248
249 return undef if !$type;
250 return ($type, $sectionId, $errmsg, {
251 # name is given by section header, and we can always prepend 'custom-'
252 # since we're reading the custom CPU file
253 cputype => "custom-$sectionId",
254 });
255 }
256
257 sub write_config {
258 my ($class, $filename, $cfg) = @_;
259
260 mkdir "/etc/pve/virtual-guest";
261
262 for my $model (keys %{$cfg->{ids}}) {
263 my $model_conf = $cfg->{ids}->{$model};
264
265 die "internal error: tried saving built-in CPU model (or missing prefix): $model_conf->{cputype}\n"
266 if !is_custom_model($model_conf->{cputype});
267
268 die "internal error: tried saving custom cpumodel with cputype (ignoring prefix: $model_conf->{cputype}) not equal to \$cfg->ids entry ($model)\n"
269 if "custom-$model" ne $model_conf->{cputype};
270
271 # saved in section header
272 delete $model_conf->{cputype};
273 }
274
275 $class->SUPER::write_config($filename, $cfg);
276 }
277
278 sub add_cpu_json_properties {
279 my ($prop) = @_;
280
281 foreach my $opt (keys %$cpu_fmt) {
282 $prop->{$opt} = $cpu_fmt->{$opt};
283 }
284
285 return $prop;
286 }
287
288 sub get_cpu_models {
289 my ($include_custom) = @_;
290
291 my $models = [];
292
293 for my $default_model (keys %{$cpu_vendor_list}) {
294 push @$models, {
295 name => $default_model,
296 custom => 0,
297 vendor => $cpu_vendor_list->{$default_model},
298 };
299 }
300
301 return $models if !$include_custom;
302
303 my $conf = load_custom_model_conf();
304 for my $custom_model (keys %{$conf->{ids}}) {
305 my $reported_model = $conf->{ids}->{$custom_model}->{'reported-model'};
306 $reported_model //= $cpu_fmt->{'reported-model'}->{default};
307 my $vendor = $cpu_vendor_list->{$reported_model};
308 push @$models, {
309 name => "custom-$custom_model",
310 custom => 1,
311 vendor => $vendor,
312 };
313 }
314
315 return $models;
316 }
317
318 sub is_custom_model {
319 my ($cputype) = @_;
320 return $cputype =~ m/^custom-/;
321 }
322
323 # Use this to get a single model in the format described by $cpu_fmt.
324 # Allows names with and without custom- prefix.
325 sub get_custom_model {
326 my ($name, $noerr) = @_;
327
328 $name =~ s/^custom-//;
329 my $conf = load_custom_model_conf();
330
331 my $entry = $conf->{ids}->{$name};
332 if (!defined($entry)) {
333 die "Custom cputype '$name' not found\n" if !$noerr;
334 return undef;
335 }
336
337 my $model = {};
338 for my $property (keys %$cpu_fmt) {
339 if (my $value = $entry->{$property}) {
340 $model->{$property} = $value;
341 }
342 }
343
344 return $model;
345 }
346
347 # Print a QEMU device node for a given VM configuration for hotplugging CPUs
348 sub print_cpu_device {
349 my ($conf, $id) = @_;
350
351 my $kvm = $conf->{kvm} // 1;
352 my $cpu = $kvm ? "kvm64" : "qemu64";
353 if (my $cputype = $conf->{cpu}) {
354 my $cpuconf = PVE::JSONSchema::parse_property_string('pve-vm-cpu-conf', $cputype)
355 or die "Cannot parse cpu description: $cputype\n";
356 $cpu = $cpuconf->{cputype};
357
358 if (is_custom_model($cpu)) {
359 my $custom_cpu = get_custom_model($cpu);
360
361 $cpu = $custom_cpu->{'reported-model'} //
362 $cpu_fmt->{'reported-model'}->{default};
363 }
364 }
365
366 my $cores = $conf->{cores} || 1;
367
368 my $current_core = ($id - 1) % $cores;
369 my $current_socket = int(($id - 1 - $current_core)/$cores);
370
371 return "$cpu-x86_64-cpu,id=cpu$id,socket-id=$current_socket,core-id=$current_core,thread-id=0";
372 }
373
374 # Resolves multiple arrays of hashes representing CPU flags with metadata to a
375 # single string in QEMU "-cpu" compatible format. Later arrays have higher
376 # priority.
377 #
378 # Hashes take the following format:
379 # {
380 # aes => {
381 # op => "+", # defaults to "" if undefined
382 # reason => "to support AES acceleration", # for override warnings
383 # value => "" # needed for kvm=off (value: off) etc...
384 # },
385 # ...
386 # }
387 sub resolve_cpu_flags {
388 my $flags = {};
389
390 for my $hash (@_) {
391 for my $flag_name (keys %$hash) {
392 my $flag = $hash->{$flag_name};
393 my $old_flag = $flags->{$flag_name};
394
395 $flag->{op} //= "";
396 $flag->{reason} //= "unknown origin";
397
398 if ($old_flag) {
399 my $value_changed = (defined($flag->{value}) != defined($old_flag->{value})) ||
400 (defined($flag->{value}) && $flag->{value} ne $old_flag->{value});
401
402 if ($old_flag->{op} eq $flag->{op} && !$value_changed) {
403 $flags->{$flag_name}->{reason} .= " & $flag->{reason}";
404 next;
405 }
406
407 my $old = print_cpuflag_hash($flag_name, $flags->{$flag_name});
408 my $new = print_cpuflag_hash($flag_name, $flag);
409 warn "warning: CPU flag/setting $new overwrites $old\n";
410 }
411
412 $flags->{$flag_name} = $flag;
413 }
414 }
415
416 my $flag_str = '';
417 # sort for command line stability
418 for my $flag_name (sort keys %$flags) {
419 $flag_str .= ',';
420 $flag_str .= $flags->{$flag_name}->{op};
421 $flag_str .= $flag_name;
422 $flag_str .= "=$flags->{$flag_name}->{value}"
423 if $flags->{$flag_name}->{value};
424 }
425
426 return $flag_str;
427 }
428
429 sub print_cpuflag_hash {
430 my ($flag_name, $flag) = @_;
431 my $formatted = "'$flag->{op}$flag_name";
432 $formatted .= "=$flag->{value}" if defined($flag->{value});
433 $formatted .= "'";
434 $formatted .= " ($flag->{reason})" if defined($flag->{reason});
435 return $formatted;
436 }
437
438 sub parse_cpuflag_list {
439 my ($re, $reason, $flaglist) = @_;
440
441 my $res = {};
442 return $res if !$flaglist;
443
444 foreach my $flag (split(";", $flaglist)) {
445 if ($flag =~ $re) {
446 $res->{$2} = { op => $1, reason => $reason };
447 }
448 }
449
450 return $res;
451 }
452
453 # Calculate QEMU's '-cpu' argument from a given VM configuration
454 sub get_cpu_options {
455 my ($conf, $arch, $kvm, $kvm_off, $machine_version, $winversion, $gpu_passthrough) = @_;
456
457 my $cputype = $kvm ? "kvm64" : "qemu64";
458 if ($arch eq 'aarch64') {
459 $cputype = 'cortex-a57';
460 }
461
462 my $cpu = {};
463 my $custom_cpu;
464 my $hv_vendor_id;
465 if (my $cpu_prop_str = $conf->{cpu}) {
466 $cpu = PVE::JSONSchema::parse_property_string('pve-vm-cpu-conf', $cpu_prop_str)
467 or die "Cannot parse cpu description: $cpu_prop_str\n";
468
469 $cputype = $cpu->{cputype};
470
471 if (is_custom_model($cputype)) {
472 $custom_cpu = get_custom_model($cputype);
473
474 $cputype = $custom_cpu->{'reported-model'} //
475 $cpu_fmt->{'reported-model'}->{default};
476 $kvm_off = $custom_cpu->{hidden}
477 if defined($custom_cpu->{hidden});
478 $hv_vendor_id = $custom_cpu->{'hv-vendor-id'};
479 }
480
481 # VM-specific settings override custom CPU config
482 $kvm_off = $cpu->{hidden}
483 if defined($cpu->{hidden});
484 $hv_vendor_id = $cpu->{'hv-vendor-id'}
485 if defined($cpu->{'hv-vendor-id'});
486 }
487
488 my $pve_flags = get_pve_cpu_flags($conf, $kvm, $cputype, $arch,
489 $machine_version);
490
491 my $hv_flags = get_hyperv_enlightenments($winversion, $machine_version,
492 $conf->{bios}, $gpu_passthrough, $hv_vendor_id) if $kvm;
493
494 my $custom_cputype_flags = parse_cpuflag_list($cpu_flag_any_re,
495 "set by custom CPU model", $custom_cpu->{flags});
496
497 my $vm_flags = parse_cpuflag_list($cpu_flag_supported_re,
498 "manually set for VM", $cpu->{flags});
499
500 my $pve_forced_flags = {};
501 $pve_forced_flags->{'enforce'} = {
502 reason => "error if requested CPU settings not available",
503 } if $cputype ne 'host' && $kvm && $arch eq 'x86_64';
504 $pve_forced_flags->{'kvm'} = {
505 value => "off",
506 reason => "hide KVM virtualization from guest",
507 } if $kvm_off;
508
509 # $cputype is the "reported-model" for custom types, so we can just look up
510 # the vendor in the default list
511 my $cpu_vendor = $cpu_vendor_list->{$cputype};
512 if ($cpu_vendor) {
513 $pve_forced_flags->{'vendor'} = {
514 value => $cpu_vendor,
515 } if $cpu_vendor ne 'default';
516 } elsif ($arch ne 'aarch64') {
517 die "internal error"; # should not happen
518 }
519
520 my $cpu_str = $cputype;
521
522 # will be resolved in parameter order
523 $cpu_str .= resolve_cpu_flags($pve_flags, $hv_flags, $custom_cputype_flags,
524 $vm_flags, $pve_forced_flags);
525
526 my $phys_bits = '';
527 foreach my $conf ($custom_cpu, $cpu) {
528 next if !defined($conf);
529 my $conf_val = $conf->{'phys-bits'};
530 next if !$conf_val;
531 if ($conf_val eq 'host') {
532 $phys_bits = ",host-phys-bits=true";
533 } else {
534 $phys_bits = ",phys-bits=$conf_val";
535 }
536 }
537 $cpu_str .= $phys_bits;
538
539 return ('-cpu', $cpu_str);
540 }
541
542 # Some hardcoded flags required by certain configurations
543 sub get_pve_cpu_flags {
544 my ($conf, $kvm, $cputype, $arch, $machine_version) = @_;
545
546 my $pve_flags = {};
547 my $pve_msg = "set by PVE;";
548
549 $pve_flags->{'lahf_lm'} = {
550 op => '+',
551 reason => "$pve_msg to support Windows 8.1+",
552 } if $cputype eq 'kvm64' && $arch eq 'x86_64';
553
554 $pve_flags->{'x2apic'} = {
555 op => '-',
556 reason => "$pve_msg incompatible with Solaris",
557 } if $conf->{ostype} && $conf->{ostype} eq 'solaris';
558
559 $pve_flags->{'sep'} = {
560 op => '+',
561 reason => "$pve_msg to support Windows 8+ and improve Windows XP+",
562 } if $cputype eq 'kvm64' || $cputype eq 'kvm32';
563
564 $pve_flags->{'rdtscp'} = {
565 op => '-',
566 reason => "$pve_msg broken on AMD Opteron",
567 } if $cputype =~ m/^Opteron/;
568
569 if (min_version($machine_version, 2, 3) && $kvm && $arch eq 'x86_64') {
570 $pve_flags->{'kvm_pv_unhalt'} = {
571 op => '+',
572 reason => "$pve_msg to improve Linux guest spinlock performance",
573 };
574 $pve_flags->{'kvm_pv_eoi'} = {
575 op => '+',
576 reason => "$pve_msg to improve Linux guest interrupt performance",
577 };
578 }
579
580 return $pve_flags;
581 }
582
583 sub get_hyperv_enlightenments {
584 my ($winversion, $machine_version, $bios, $gpu_passthrough, $hv_vendor_id) = @_;
585
586 return if $winversion < 6;
587 return if $bios && $bios eq 'ovmf' && $winversion < 8;
588
589 my $flags = {};
590 my $default_reason = "automatic Hyper-V enlightenment for Windows";
591 my $flagfn = sub {
592 my ($flag, $value, $reason) = @_;
593 $flags->{$flag} = {
594 reason => $reason // $default_reason,
595 value => $value,
596 }
597 };
598
599 my $hv_vendor_set = defined($hv_vendor_id);
600 if ($gpu_passthrough || $hv_vendor_set) {
601 $hv_vendor_id //= 'proxmox';
602 $flagfn->('hv_vendor_id', $hv_vendor_id, $hv_vendor_set ?
603 "custom hv_vendor_id set" : "NVIDIA workaround for GPU passthrough");
604 }
605
606 if (min_version($machine_version, 2, 3)) {
607 $flagfn->('hv_spinlocks', '0x1fff');
608 $flagfn->('hv_vapic');
609 $flagfn->('hv_time');
610 } else {
611 $flagfn->('hv_spinlocks', '0xffff');
612 }
613
614 if (min_version($machine_version, 2, 6)) {
615 $flagfn->('hv_reset');
616 $flagfn->('hv_vpindex');
617 $flagfn->('hv_runtime');
618 }
619
620 if ($winversion >= 7) {
621 my $win7_reason = $default_reason . " 7 and higher";
622 $flagfn->('hv_relaxed', undef, $win7_reason);
623
624 if (min_version($machine_version, 2, 12)) {
625 $flagfn->('hv_synic', undef, $win7_reason);
626 $flagfn->('hv_stimer', undef, $win7_reason);
627 }
628
629 if (min_version($machine_version, 3, 1)) {
630 $flagfn->('hv_ipi', undef, $win7_reason);
631 }
632 }
633
634 return $flags;
635 }
636
637 sub get_cpu_from_running_vm {
638 my ($pid) = @_;
639
640 my $cmdline = PVE::QemuServer::Helpers::parse_cmdline($pid);
641 die "could not read commandline of running machine\n"
642 if !$cmdline->{cpu}->{value};
643
644 # sanitize and untaint value
645 $cmdline->{cpu}->{value} =~ $qemu_cmdline_cpu_re;
646 return $1;
647 }
648
649 __PACKAGE__->register();
650 __PACKAGE__->init();
651
652 1;