]> git.proxmox.com Git - qemu-server.git/blame - PVE/QemuServer.pm
vm start: add warning about deprecated machine version
[qemu-server.git] / PVE / QemuServer.pm
CommitLineData
baa4f62d 1package PVE::QemuServer;
1e3baf05
DM
2
3use strict;
990fc5e2 4use warnings;
3ff84d6f 5
5da072fb
TL
6use Cwd 'abs_path';
7use Digest::SHA;
8use Fcntl ':flock';
9use Fcntl;
1e3baf05 10use File::Basename;
5da072fb 11use File::Copy qw(copy);
1e3baf05
DM
12use File::Path;
13use File::stat;
14use Getopt::Long;
5da072fb
TL
15use IO::Dir;
16use IO::File;
17use IO::Handle;
18use IO::Select;
19use IO::Socket::UNIX;
1e3baf05 20use IPC::Open3;
c971c4f2 21use JSON;
c3d15108 22use List::Util qw(first);
1f30ac3a 23use MIME::Base64;
5da072fb
TL
24use POSIX;
25use Storable qw(dclone);
f85951dc 26use Time::HiRes qw(gettimeofday usleep);
5da072fb 27use URI::Escape;
425441e6 28use UUID;
5da072fb 29
82841214 30use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file);
5b65b00d 31use PVE::CGroup;
83870398 32use PVE::CpuSet;
48cf040f 33use PVE::DataCenterConfig;
5da072fb 34use PVE::Exception qw(raise raise_param_exc);
3b56383b 35use PVE::Format qw(render_duration render_bytes);
81d6e4e1 36use PVE::GuestHelpers qw(safe_string_ne safe_num_ne safe_boolean_ne);
a52eb3c4
DC
37use PVE::Mapping::PCI;
38use PVE::Mapping::USB;
1e3baf05 39use PVE::INotify;
4df98f2f 40use PVE::JSONSchema qw(get_standard_option parse_property_string);
1e3baf05 41use PVE::ProcFSTools;
fbec3f89 42use PVE::PBSClient;
34e82fa2 43use PVE::RESTEnvironment qw(log_warn);
91bd6c90 44use PVE::RPCEnvironment;
5da072fb 45use PVE::Storage;
b71351a7 46use PVE::SysFSTools;
d04d6af1 47use PVE::Systemd;
82841214 48use PVE::Tools qw(run_command file_read_firstline file_get_contents dir_glob_foreach get_host_arch $IPV6RE);
5da072fb
TL
49
50use PVE::QMPClient;
51use PVE::QemuConfig;
0e32bf5b 52use PVE::QemuServer::Helpers qw(config_aware_timeout min_version windows_version);
5da072fb 53use PVE::QemuServer::Cloudinit;
5b65b00d 54use PVE::QemuServer::CGroup;
d786a274 55use PVE::QemuServer::CPUConfig qw(print_cpu_device get_cpu_options);
75748d44 56use PVE::QemuServer::Drive qw(is_valid_drivename drive_is_cloudinit drive_is_cdrom drive_is_read_only parse_drive print_drive);
2ea5fb7e 57use PVE::QemuServer::Machine;
7f8c8087 58use PVE::QemuServer::Memory qw(get_current_memory);
0a13e08e 59use PVE::QemuServer::Monitor qw(mon_cmd);
74c17b7a 60use PVE::QemuServer::PCI qw(print_pci_addr print_pcie_addr print_pcie_root_port parse_hostpci);
87b0f305 61use PVE::QemuServer::QMPHelpers qw(qemu_deviceadd qemu_devicedel qemu_objectadd qemu_objectdel);
0cf8d56c 62use PVE::QemuServer::USB;
1e3baf05 63
28e129cc
AD
64my $have_sdn;
65eval {
66 require PVE::Network::SDN::Zones;
67 $have_sdn = 1;
68};
69
102cf9d8 70my $EDK2_FW_BASE = '/usr/share/pve-edk2-firmware/';
96ed3574 71my $OVMF = {
b5099b4f 72 x86_64 => {
90b20b15
DC
73 '4m-no-smm' => [
74 "$EDK2_FW_BASE/OVMF_CODE_4M.fd",
75 "$EDK2_FW_BASE/OVMF_VARS_4M.fd",
76 ],
77 '4m-no-smm-ms' => [
78 "$EDK2_FW_BASE/OVMF_CODE_4M.fd",
79 "$EDK2_FW_BASE/OVMF_VARS_4M.ms.fd",
80 ],
b5099b4f
SR
81 '4m' => [
82 "$EDK2_FW_BASE/OVMF_CODE_4M.secboot.fd",
83 "$EDK2_FW_BASE/OVMF_VARS_4M.fd",
84 ],
85 '4m-ms' => [
86 "$EDK2_FW_BASE/OVMF_CODE_4M.secboot.fd",
87 "$EDK2_FW_BASE/OVMF_VARS_4M.ms.fd",
88 ],
c351659d
TL
89 # FIXME: These are legacy 2MB-sized images that modern OVMF doesn't supports to build
90 # anymore. how can we deperacate this sanely without breaking existing instances, or using
91 # older backups and snapshot?
b5099b4f
SR
92 default => [
93 "$EDK2_FW_BASE/OVMF_CODE.fd",
94 "$EDK2_FW_BASE/OVMF_VARS.fd",
95 ],
96 },
97 aarch64 => {
98 default => [
99 "$EDK2_FW_BASE/AAVMF_CODE.fd",
100 "$EDK2_FW_BASE/AAVMF_VARS.fd",
101 ],
102 },
96ed3574 103};
2ddc0a5c 104
7f0b5beb 105my $cpuinfo = PVE::ProcFSTools::read_cpuinfo();
1e3baf05 106
8d88a594
TL
107# Note about locking: we use flock on the config file protect against concurent actions.
108# Aditionaly, we have a 'lock' setting in the config file. This can be set to 'migrate',
109# 'backup', 'snapshot' or 'rollback'. Most actions are not allowed when such lock is set.
110# But you can ignore this kind of lock with the --skiplock flag.
1e3baf05 111
cf364f95
TL
112cfs_register_file(
113 '/qemu-server/',
114 \&parse_vm_config,
115 \&write_vm_config
116);
1e3baf05 117
3ea94c60
DM
118PVE::JSONSchema::register_standard_option('pve-qm-stateuri', {
119 description => "Some command save/restore state from this location.",
120 type => 'string',
121 maxLength => 128,
122 optional => 1,
123});
124
c6737ef1 125PVE::JSONSchema::register_standard_option('pve-qemu-machine', {
7bd9abd2 126 description => "Specifies the QEMU machine type.",
c6737ef1 127 type => 'string',
9471e48b 128 pattern => '(pc|pc(-i440fx)?-\d+(\.\d+)+(\+pve\d+)?(\.pxe)?|q35|pc-q35-\d+(\.\d+)+(\+pve\d+)?(\.pxe)?|virt(?:-\d+(\.\d+)+)?(\+pve\d+)?)',
c6737ef1
DC
129 maxLength => 40,
130 optional => 1,
131});
132
1a67f999 133# FIXME: remove in favor of just using the INotify one, it's cached there exactly the same way
38277afc
TL
134my $nodename_cache;
135sub nodename {
136 $nodename_cache //= PVE::INotify::nodename();
137 return $nodename_cache;
138}
1e3baf05 139
ec3582b5
WB
140my $watchdog_fmt = {
141 model => {
142 default_key => 1,
143 type => 'string',
144 enum => [qw(i6300esb ib700)],
145 description => "Watchdog type to emulate.",
146 default => 'i6300esb',
147 optional => 1,
148 },
149 action => {
150 type => 'string',
151 enum => [qw(reset shutdown poweroff pause debug none)],
152 description => "The action to perform if after activation the guest fails to poll the watchdog in time.",
153 optional => 1,
154 },
155};
156PVE::JSONSchema::register_format('pve-qm-watchdog', $watchdog_fmt);
157
9d66b397
SI
158my $agent_fmt = {
159 enabled => {
7bd9abd2 160 description => "Enable/disable communication with a QEMU Guest Agent (QGA) running in the VM.",
9d66b397
SI
161 type => 'boolean',
162 default => 0,
163 default_key => 1,
164 },
165 fstrim_cloned_disks => {
0a4aff09 166 description => "Run fstrim after moving a disk or migrating the VM.",
9d66b397
SI
167 type => 'boolean',
168 optional => 1,
93e21fd2
CH
169 default => 0,
170 },
171 'freeze-fs-on-backup' => {
172 description => "Freeze/thaw guest filesystems on backup for consistency.",
173 type => 'boolean',
174 optional => 1,
175 default => 1,
9d66b397 176 },
48657158
MD
177 type => {
178 description => "Select the agent type",
179 type => 'string',
180 default => 'virtio',
181 optional => 1,
182 enum => [qw(virtio isa)],
183 },
9d66b397
SI
184};
185
55655ebc
DC
186my $vga_fmt = {
187 type => {
188 description => "Select the VGA type.",
189 type => 'string',
190 default => 'std',
191 optional => 1,
192 default_key => 1,
6f070e39 193 enum => [qw(cirrus qxl qxl2 qxl3 qxl4 none serial0 serial1 serial2 serial3 std virtio virtio-gl vmware)],
55655ebc
DC
194 },
195 memory => {
196 description => "Sets the VGA memory (in MiB). Has no effect with serial display.",
197 type => 'integer',
198 optional => 1,
199 minimum => 4,
200 maximum => 512,
201 },
202};
203
6dbcb073
DC
204my $ivshmem_fmt = {
205 size => {
206 type => 'integer',
207 minimum => 1,
208 description => "The size of the file in MB.",
209 },
210 name => {
211 type => 'string',
212 pattern => '[a-zA-Z0-9\-]+',
213 optional => 1,
214 format_description => 'string',
215 description => "The name of the file. Will be prefixed with 'pve-shm-'. Default is the VMID. Will be deleted when the VM is stopped.",
216 },
217};
218
1448547f
AL
219my $audio_fmt = {
220 device => {
221 type => 'string',
222 enum => [qw(ich9-intel-hda intel-hda AC97)],
223 description => "Configure an audio device."
224 },
225 driver => {
226 type => 'string',
211785ee 227 enum => ['spice', 'none'],
1448547f
AL
228 default => 'spice',
229 optional => 1,
230 description => "Driver backend for the audio device."
231 },
232};
233
c4df18db
AL
234my $spice_enhancements_fmt = {
235 foldersharing => {
236 type => 'boolean',
237 optional => 1,
d282a24d 238 default => '0',
c4df18db
AL
239 description => "Enable folder sharing via SPICE. Needs Spice-WebDAV daemon installed in the VM."
240 },
241 videostreaming => {
242 type => 'string',
243 enum => ['off', 'all', 'filter'],
d282a24d 244 default => 'off',
c4df18db
AL
245 optional => 1,
246 description => "Enable video streaming. Uses compression for detected video streams."
247 },
248};
249
2cf61f33
SR
250my $rng_fmt = {
251 source => {
252 type => 'string',
253 enum => ['/dev/urandom', '/dev/random', '/dev/hwrng'],
254 default_key => 1,
8d88a594
TL
255 description => "The file on the host to gather entropy from. In most cases '/dev/urandom'"
256 ." should be preferred over '/dev/random' to avoid entropy-starvation issues on the"
257 ." host. Using urandom does *not* decrease security in any meaningful way, as it's"
258 ." still seeded from real entropy, and the bytes provided will most likely be mixed"
259 ." with real entropy on the guest as well. '/dev/hwrng' can be used to pass through"
260 ." a hardware RNG from the host.",
2cf61f33
SR
261 },
262 max_bytes => {
263 type => 'integer',
8d88a594
TL
264 description => "Maximum bytes of entropy allowed to get injected into the guest every"
265 ." 'period' milliseconds. Prefer a lower value when using '/dev/random' as source. Use"
266 ." `0` to disable limiting (potentially dangerous!).",
2cf61f33
SR
267 optional => 1,
268
8d88a594
TL
269 # default is 1 KiB/s, provides enough entropy to the guest to avoid boot-starvation issues
270 # (e.g. systemd etc...) while allowing no chance of overwhelming the host, provided we're
271 # reading from /dev/urandom
2cf61f33
SR
272 default => 1024,
273 },
274 period => {
275 type => 'integer',
8d88a594
TL
276 description => "Every 'period' milliseconds the entropy-injection quota is reset, allowing"
277 ." the guest to retrieve another 'max_bytes' of entropy.",
2cf61f33
SR
278 optional => 1,
279 default => 1000,
280 },
281};
282
26b443c8
TL
283my $meta_info_fmt = {
284 'ctime' => {
285 type => 'integer',
286 description => "The guest creation timestamp as UNIX epoch time",
287 minimum => 0,
288 optional => 1,
289 },
af2a1a1c
TL
290 'creation-qemu' => {
291 type => 'string',
292 description => "The QEMU (machine) version from the time this VM was created.",
293 pattern => '\d+(\.\d+)+',
294 optional => 1,
295 },
26b443c8
TL
296};
297
1e3baf05
DM
298my $confdesc = {
299 onboot => {
300 optional => 1,
301 type => 'boolean',
302 description => "Specifies whether a VM will be started during system bootup.",
303 default => 0,
304 },
305 autostart => {
306 optional => 1,
307 type => 'boolean',
308 description => "Automatic restart after crash (currently ignored).",
309 default => 0,
310 },
2ff09f52 311 hotplug => {
483ceeab
TL
312 optional => 1,
313 type => 'string', format => 'pve-hotplug-features',
314 description => "Selectively enable hotplug features. This is a comma separated list of"
94ec5e7c 315 ." hotplug features: 'network', 'disk', 'cpu', 'memory', 'usb' and 'cloudinit'. Use '0' to disable"
c60cad61
DC
316 ." hotplug completely. Using '1' as value is an alias for the default `network,disk,usb`."
317 ." USB hotplugging is possible for guests with machine version >= 7.1 and ostype l26 or"
318 ." windows > 7.",
b3c2bdd1 319 default => 'network,disk,usb',
2ff09f52 320 },
1e3baf05
DM
321 reboot => {
322 optional => 1,
323 type => 'boolean',
324 description => "Allow reboot. If set to '0' the VM exit on reboot.",
325 default => 1,
326 },
327 lock => {
328 optional => 1,
329 type => 'string',
330 description => "Lock/unlock the VM.",
159719e5 331 enum => [qw(backup clone create migrate rollback snapshot snapshot-delete suspending suspended)],
1e3baf05
DM
332 },
333 cpulimit => {
334 optional => 1,
c6f773b8 335 type => 'number',
52261945 336 description => "Limit of CPU usage.",
8d88a594
TL
337 verbose_description => "Limit of CPU usage.\n\nNOTE: If the computer has 2 CPUs, it has"
338 ." total of '2' CPU time. Value '0' indicates no CPU limit.",
1e3baf05 339 minimum => 0,
c6f773b8 340 maximum => 128,
483ceeab 341 default => 0,
1e3baf05
DM
342 },
343 cpuunits => {
344 optional => 1,
345 type => 'integer',
483ceeab 346 description => "CPU weight for a VM, will be clamped to [1, 10000] in cgroup v2.",
67498860
TL
347 verbose_description => "CPU weight for a VM. Argument is used in the kernel fair scheduler."
348 ." The larger the number is, the more CPU time this VM gets. Number is relative to"
349 ." weights of all the other running VMs.",
e65e35ca 350 minimum => 1,
237239bf 351 maximum => 262144,
67498860 352 default => 'cgroup v1: 1024, cgroup v2: 100',
1e3baf05
DM
353 },
354 memory => {
355 optional => 1,
7f8c8087
AD
356 type => 'string',
357 description => "Memory properties.",
358 format => $PVE::QemuServer::Memory::memory_fmt
1e3baf05 359 },
13a48620 360 balloon => {
483ceeab
TL
361 optional => 1,
362 type => 'integer',
252e2624 363 description => "Amount of target RAM for the VM in MiB. Using zero disables the ballon driver.",
8b1accf7
DM
364 minimum => 0,
365 },
366 shares => {
483ceeab
TL
367 optional => 1,
368 type => 'integer',
369 description => "Amount of memory shares for auto-ballooning. The larger the number is, the"
8d88a594
TL
370 ." more memory this VM gets. Number is relative to weights of all other running VMs."
371 ." Using zero disables auto-ballooning. Auto-ballooning is done by pvestatd.",
8b1accf7
DM
372 minimum => 0,
373 maximum => 50000,
374 default => 1000,
13a48620 375 },
1e3baf05
DM
376 keyboard => {
377 optional => 1,
378 type => 'string',
233fb336
DW
379 description => "Keyboard layout for VNC server. This option is generally not required and"
380 ." is often better handled from within the guest OS.",
e95fe75f 381 enum => PVE::Tools::kvmkeymaplist(),
aea47dd6 382 default => undef,
1e3baf05
DM
383 },
384 name => {
385 optional => 1,
7fabe17d 386 type => 'string', format => 'dns-name',
1e3baf05
DM
387 description => "Set a name for the VM. Only used on the configuration web interface.",
388 },
cdd20088
AD
389 scsihw => {
390 optional => 1,
391 type => 'string',
52261945 392 description => "SCSI controller model",
6731a4cf 393 enum => [qw(lsi lsi53c810 virtio-scsi-pci virtio-scsi-single megasas pvscsi)],
cdd20088
AD
394 default => 'lsi',
395 },
1e3baf05
DM
396 description => {
397 optional => 1,
398 type => 'string',
a200af10
TL
399 description => "Description for the VM. Shown in the web-interface VM's summary."
400 ." This is saved as comment inside the configuration file.",
401 maxLength => 1024 * 8,
1e3baf05
DM
402 },
403 ostype => {
404 optional => 1,
405 type => 'string',
483ceeab 406 enum => [qw(other wxp w2k w2k3 w2k8 wvista win7 win8 win10 win11 l24 l26 solaris)],
52261945
DM
407 description => "Specify guest operating system.",
408 verbose_description => <<EODESC,
409Specify guest operating system. This is used to enable special
410optimization/features for specific operating systems:
411
412[horizontal]
413other;; unspecified OS
414wxp;; Microsoft Windows XP
415w2k;; Microsoft Windows 2000
416w2k3;; Microsoft Windows 2003
417w2k8;; Microsoft Windows 2008
418wvista;; Microsoft Windows Vista
419win7;; Microsoft Windows 7
44c2a647 420win8;; Microsoft Windows 8/2012/2012r2
1f5828f2 421win10;; Microsoft Windows 10/2016/2019
179b9f1b 422win11;; Microsoft Windows 11/2022
52261945 423l24;; Linux 2.4 Kernel
ea0bc514 424l26;; Linux 2.6 - 6.X Kernel
52261945 425solaris;; Solaris/OpenSolaris/OpenIndiania kernel
1e3baf05
DM
426EODESC
427 },
428 boot => {
429 optional => 1,
2141a802 430 type => 'string', format => 'pve-qm-boot',
483ceeab
TL
431 description => "Specify guest boot order. Use the 'order=' sub-property as usage with no"
432 ." key or 'legacy=' is deprecated.",
1e3baf05
DM
433 },
434 bootdisk => {
435 optional => 1,
436 type => 'string', format => 'pve-qm-bootdisk',
2141a802 437 description => "Enable booting from specified disk. Deprecated: Use 'boot: order=foo;bar' instead.",
03e480fc 438 pattern => '(ide|sata|scsi|virtio)\d+',
1e3baf05
DM
439 },
440 smp => {
441 optional => 1,
442 type => 'integer',
443 description => "The number of CPUs. Please use option -sockets instead.",
444 minimum => 1,
445 default => 1,
446 },
447 sockets => {
448 optional => 1,
449 type => 'integer',
450 description => "The number of CPU sockets.",
451 minimum => 1,
452 default => 1,
453 },
454 cores => {
455 optional => 1,
456 type => 'integer',
457 description => "The number of cores per socket.",
458 minimum => 1,
459 default => 1,
460 },
8a010eae
AD
461 numa => {
462 optional => 1,
463 type => 'boolean',
1917695c 464 description => "Enable/disable NUMA.",
8a010eae
AD
465 default => 0,
466 },
7023f3ea
AD
467 hugepages => {
468 optional => 1,
469 type => 'string',
470 description => "Enable/disable hugepages memory.",
471 enum => [qw(any 2 1024)],
472 },
f36e9894
SR
473 keephugepages => {
474 optional => 1,
475 type => 'boolean',
476 default => 0,
4df98f2f
TL
477 description => "Use together with hugepages. If enabled, hugepages will not not be deleted"
478 ." after VM shutdown and can be used for subsequent starts.",
f36e9894 479 },
de9d1e55 480 vcpus => {
3bd18e48
AD
481 optional => 1,
482 type => 'integer',
de9d1e55 483 description => "Number of hotplugged vcpus.",
3bd18e48 484 minimum => 1,
de9d1e55 485 default => 0,
3bd18e48 486 },
1e3baf05
DM
487 acpi => {
488 optional => 1,
489 type => 'boolean',
490 description => "Enable/disable ACPI.",
491 default => 1,
492 },
bc84dcca 493 agent => {
ab6a046f 494 optional => 1,
7bd9abd2 495 description => "Enable/disable communication with the QEMU Guest Agent and its properties.",
9d66b397
SI
496 type => 'string',
497 format => $agent_fmt,
ab6a046f 498 },
1e3baf05
DM
499 kvm => {
500 optional => 1,
501 type => 'boolean',
502 description => "Enable/disable KVM hardware virtualization.",
503 default => 1,
504 },
505 tdf => {
506 optional => 1,
507 type => 'boolean',
8c559505
DM
508 description => "Enable/disable time drift fix.",
509 default => 0,
1e3baf05 510 },
19672434 511 localtime => {
1e3baf05
DM
512 optional => 1,
513 type => 'boolean',
8d88a594
TL
514 description => "Set the real time clock (RTC) to local time. This is enabled by default if"
515 ." the `ostype` indicates a Microsoft Windows OS.",
1e3baf05
DM
516 },
517 freeze => {
518 optional => 1,
519 type => 'boolean',
520 description => "Freeze CPU at startup (use 'c' monitor command to start execution).",
521 },
522 vga => {
523 optional => 1,
55655ebc
DC
524 type => 'string', format => $vga_fmt,
525 description => "Configure the VGA hardware.",
4df98f2f
TL
526 verbose_description => "Configure the VGA Hardware. If you want to use high resolution"
527 ." modes (>= 1280x1024x16) you may need to increase the vga memory option. Since QEMU"
528 ." 2.9 the default VGA display type is 'std' for all OS types besides some Windows"
529 ." versions (XP and older) which use 'cirrus'. The 'qxl' option enables the SPICE"
530 ." display server. For win* OS you can select how many independent displays you want,"
531 ." Linux guests can add displays them self.\nYou can also run without any graphic card,"
532 ." using a serial device as terminal.",
1e3baf05 533 },
0ea9541d
DM
534 watchdog => {
535 optional => 1,
536 type => 'string', format => 'pve-qm-watchdog',
52261945 537 description => "Create a virtual hardware watchdog device.",
4df98f2f
TL
538 verbose_description => "Create a virtual hardware watchdog device. Once enabled (by a guest"
539 ." action), the watchdog must be periodically polled by an agent inside the guest or"
540 ." else the watchdog will reset the guest (or execute the respective action specified)",
0ea9541d 541 },
1e3baf05
DM
542 startdate => {
543 optional => 1,
19672434 544 type => 'string',
1e3baf05 545 typetext => "(now | YYYY-MM-DD | YYYY-MM-DDTHH:MM:SS)",
4df98f2f
TL
546 description => "Set the initial date of the real time clock. Valid format for date are:"
547 ."'now' or '2006-06-17T16:01:21' or '2006-06-17'.",
1e3baf05
DM
548 pattern => '(now|\d{4}-\d{1,2}-\d{1,2}(T\d{1,2}:\d{1,2}:\d{1,2})?)',
549 default => 'now',
550 },
43574f73 551 startup => get_standard_option('pve-startup-order'),
68eda3ab
AD
552 template => {
553 optional => 1,
554 type => 'boolean',
555 description => "Enable/disable Template.",
556 default => 0,
557 },
1e3baf05
DM
558 args => {
559 optional => 1,
560 type => 'string',
52261945
DM
561 description => "Arbitrary arguments passed to kvm.",
562 verbose_description => <<EODESCR,
c7a8aad6 563Arbitrary arguments passed to kvm, for example:
1e3baf05 564
bda7ccb1 565args: -no-reboot -smbios 'type=0,vendor=FOO'
c7a8aad6
FG
566
567NOTE: this option is for experts only.
1e3baf05
DM
568EODESCR
569 },
570 tablet => {
571 optional => 1,
572 type => 'boolean',
573 default => 1,
52261945 574 description => "Enable/disable the USB tablet device.",
4df98f2f
TL
575 verbose_description => "Enable/disable the USB tablet device. This device is usually needed"
576 ." to allow absolute mouse positioning with VNC. Else the mouse runs out of sync with"
577 ." normal VNC clients. If you're running lots of console-only guests on one host, you"
578 ." may consider disabling this to save some context switches. This is turned off by"
579 ." default if you use spice (`qm set <vmid> --vga qxl`).",
1e3baf05
DM
580 },
581 migrate_speed => {
582 optional => 1,
583 type => 'integer',
584 description => "Set maximum speed (in MB/s) for migrations. Value 0 is no limit.",
585 minimum => 0,
586 default => 0,
587 },
588 migrate_downtime => {
589 optional => 1,
04432191 590 type => 'number',
1e3baf05
DM
591 description => "Set maximum tolerated downtime (in seconds) for migrations.",
592 minimum => 0,
04432191 593 default => 0.1,
1e3baf05
DM
594 },
595 cdrom => {
596 optional => 1,
b799312f 597 type => 'string', format => 'pve-qm-ide',
8485b9ba 598 typetext => '<volume>',
1e3baf05
DM
599 description => "This is an alias for option -ide2",
600 },
601 cpu => {
602 optional => 1,
603 description => "Emulated CPU type.",
604 type => 'string',
5d008ad3 605 format => 'pve-vm-cpu-conf',
1e3baf05 606 },
b7ba6b79
DM
607 parent => get_standard_option('pve-snapshot-name', {
608 optional => 1,
609 description => "Parent snapshot name. This is used internally, and should not be modified.",
610 }),
982c7f12
DM
611 snaptime => {
612 optional => 1,
613 description => "Timestamp for snapshots.",
614 type => 'integer',
615 minimum => 0,
616 },
18bfb361
DM
617 vmstate => {
618 optional => 1,
619 type => 'string', format => 'pve-volume-id',
4df98f2f
TL
620 description => "Reference to a volume which stores the VM state. This is used internally"
621 ." for snapshots.",
18bfb361 622 },
253624c7
FG
623 vmstatestorage => get_standard_option('pve-storage-id', {
624 description => "Default storage for VM state volumes/files.",
625 optional => 1,
626 }),
c6737ef1 627 runningmachine => get_standard_option('pve-qemu-machine', {
4df98f2f
TL
628 description => "Specifies the QEMU machine type of the running vm. This is used internally"
629 ." for snapshots.",
c6737ef1 630 }),
ea1c2110 631 runningcpu => {
4df98f2f
TL
632 description => "Specifies the QEMU '-cpu' parameter of the running vm. This is used"
633 ." internally for snapshots.",
ea1c2110
SR
634 optional => 1,
635 type => 'string',
636 pattern => $PVE::QemuServer::CPUConfig::qemu_cmdline_cpu_re,
637 format_description => 'QEMU -cpu parameter'
638 },
c6737ef1 639 machine => get_standard_option('pve-qemu-machine'),
d731ecbe
WB
640 arch => {
641 description => "Virtual processor architecture. Defaults to the host.",
642 optional => 1,
643 type => 'string',
644 enum => [qw(x86_64 aarch64)],
645 },
2796e7d5
DM
646 smbios1 => {
647 description => "Specify SMBIOS type 1 fields.",
648 type => 'string', format => 'pve-qm-smbios1',
5d004b00 649 maxLength => 512,
2796e7d5
DM
650 optional => 1,
651 },
cb0e4540
AG
652 protection => {
653 optional => 1,
654 type => 'boolean',
4df98f2f
TL
655 description => "Sets the protection flag of the VM. This will disable the remove VM and"
656 ." remove disk operations.",
cb0e4540
AG
657 default => 0,
658 },
3edb45e7 659 bios => {
a783c78e 660 optional => 1,
3edb45e7
DM
661 type => 'string',
662 enum => [ qw(seabios ovmf) ],
663 description => "Select BIOS implementation.",
664 default => 'seabios',
a783c78e 665 },
6ee499ff
DC
666 vmgenid => {
667 type => 'string',
668 pattern => '(?:[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}|[01])',
669 format_description => 'UUID',
4df98f2f
TL
670 description => "Set VM Generation ID. Use '1' to autogenerate on create or update, pass '0'"
671 ." to disable explicitly.",
672 verbose_description => "The VM generation ID (vmgenid) device exposes a 128-bit integer"
673 ." value identifier to the guest OS. This allows to notify the guest operating system"
674 ." when the virtual machine is executed with a different configuration (e.g. snapshot"
675 ." execution or creation from a template). The guest operating system notices the"
676 ." change, and is then able to react as appropriate by marking its copies of"
677 ." distributed databases as dirty, re-initializing its random number generator, etc.\n"
678 ."Note that auto-creation only works when done through API/CLI create or update methods"
679 .", but not when manually editing the config file.",
f7ed64e7 680 default => "1 (autogenerated)",
6ee499ff
DC
681 optional => 1,
682 },
9e784b11
DC
683 hookscript => {
684 type => 'string',
685 format => 'pve-volume-id',
686 optional => 1,
687 description => "Script that will be executed during various steps in the vms lifetime.",
688 },
6dbcb073
DC
689 ivshmem => {
690 type => 'string',
691 format => $ivshmem_fmt,
4df98f2f
TL
692 description => "Inter-VM shared memory. Useful for direct communication between VMs, or to"
693 ." the host.",
6dbcb073 694 optional => 1,
2e7b5925
AL
695 },
696 audio0 => {
697 type => 'string',
1448547f 698 format => $audio_fmt,
194b65f1 699 description => "Configure a audio device, useful in combination with QXL/Spice.",
2e7b5925
AL
700 optional => 1
701 },
c4df18db
AL
702 spice_enhancements => {
703 type => 'string',
704 format => $spice_enhancements_fmt,
705 description => "Configure additional enhancements for SPICE.",
706 optional => 1
707 },
b8e7068a
DC
708 tags => {
709 type => 'string', format => 'pve-tag-list',
710 description => 'Tags of the VM. This is only meta information.',
711 optional => 1,
712 },
2cf61f33
SR
713 rng0 => {
714 type => 'string',
715 format => $rng_fmt,
716 description => "Configure a VirtIO-based Random Number Generator.",
717 optional => 1,
718 },
26b443c8
TL
719 meta => {
720 type => 'string',
721 format => $meta_info_fmt,
722 description => "Some (read-only) meta-information about this guest.",
723 optional => 1,
724 },
83870398
DB
725 affinity => {
726 type => 'string', format => 'pve-cpuset',
326704e7 727 description => "List of host cores used to execute guest processes, for example: 0,5,8-11",
83870398
DB
728 optional => 1,
729 },
9ed7a77c
WB
730};
731
cb702ebe
DL
732my $cicustom_fmt = {
733 meta => {
734 type => 'string',
735 optional => 1,
4df98f2f
TL
736 description => 'Specify a custom file containing all meta data passed to the VM via"
737 ." cloud-init. This is provider specific meaning configdrive2 and nocloud differ.',
cb702ebe
DL
738 format => 'pve-volume-id',
739 format_description => 'volume',
740 },
741 network => {
742 type => 'string',
743 optional => 1,
eba285f5 744 description => 'To pass a custom file containing all network data to the VM via cloud-init.',
cb702ebe
DL
745 format => 'pve-volume-id',
746 format_description => 'volume',
747 },
748 user => {
749 type => 'string',
750 optional => 1,
eba285f5 751 description => 'To pass a custom file containing all user data to the VM via cloud-init.',
cb702ebe
DL
752 format => 'pve-volume-id',
753 format_description => 'volume',
754 },
101beafe 755 vendor => {
eba285f5
TL
756 type => 'string',
757 optional => 1,
758 description => 'To pass a custom file containing all vendor data to the VM via cloud-init.',
759 format => 'pve-volume-id',
760 format_description => 'volume',
101beafe 761 },
cb702ebe
DL
762};
763PVE::JSONSchema::register_format('pve-qm-cicustom', $cicustom_fmt);
764
92c02f6c 765# any new option might need to be added to $cloudinitoptions in PVE::API2::Qemu
9ed7a77c 766my $confdesc_cloudinit = {
41cd94a0
WB
767 citype => {
768 optional => 1,
769 type => 'string',
4df98f2f
TL
770 description => 'Specifies the cloud-init configuration format. The default depends on the'
771 .' configured operating system type (`ostype`. We use the `nocloud` format for Linux,'
772 .' and `configdrive2` for windows.',
545eec65 773 enum => ['configdrive2', 'nocloud', 'opennebula'],
41cd94a0 774 },
7b42f951
WB
775 ciuser => {
776 optional => 1,
777 type => 'string',
4df98f2f
TL
778 description => "cloud-init: User name to change ssh keys and password for instead of the"
779 ." image's configured default user.",
7b42f951
WB
780 },
781 cipassword => {
782 optional => 1,
783 type => 'string',
4df98f2f
TL
784 description => 'cloud-init: Password to assign the user. Using this is generally not'
785 .' recommended. Use ssh keys instead. Also note that older cloud-init versions do not'
786 .' support hashed passwords.',
7b42f951 787 },
efa3355d
LN
788 ciupgrade => {
789 optional => 1,
790 type => 'boolean',
178c355d 791 description => 'cloud-init: do an automatic package upgrade after the first boot.',
ec11b92a 792 default => 1,
efa3355d 793 },
cb702ebe
DL
794 cicustom => {
795 optional => 1,
796 type => 'string',
4df98f2f
TL
797 description => 'cloud-init: Specify custom files to replace the automatically generated'
798 .' ones at start.',
cb702ebe
DL
799 format => 'pve-qm-cicustom',
800 },
0c9a7596
AD
801 searchdomain => {
802 optional => 1,
803 type => 'string',
bd49ecb4 804 description => 'cloud-init: Sets DNS search domains for a container. Create will'
4df98f2f 805 .' automatically use the setting from the host if neither searchdomain nor nameserver'
bd49ecb4 806 .' are set.',
0c9a7596
AD
807 },
808 nameserver => {
809 optional => 1,
810 type => 'string', format => 'address-list',
bd49ecb4 811 description => 'cloud-init: Sets DNS server IP address for a container. Create will'
4df98f2f 812 .' automatically use the setting from the host if neither searchdomain nor nameserver'
bd49ecb4 813 .' are set.',
0c9a7596
AD
814 },
815 sshkeys => {
816 optional => 1,
817 type => 'string',
818 format => 'urlencoded',
1d1c4e1c 819 description => "cloud-init: Setup public SSH keys (one key per line, OpenSSH format).",
0c9a7596 820 },
1e3baf05
DM
821};
822
823# what about other qemu settings ?
824#cpu => 'string',
825#machine => 'string',
826#fda => 'file',
827#fdb => 'file',
828#mtdblock => 'file',
829#sd => 'file',
830#pflash => 'file',
831#snapshot => 'bool',
832#bootp => 'file',
833##tftp => 'dir',
834##smb => 'dir',
835#kernel => 'file',
836#append => 'string',
837#initrd => 'file',
838##soundhw => 'string',
839
840while (my ($k, $v) = each %$confdesc) {
841 PVE::JSONSchema::register_standard_option("pve-qm-$k", $v);
842}
843
5bdcf937 844my $MAX_NETS = 32;
bae179aa 845my $MAX_SERIAL_PORTS = 4;
1989a89c 846my $MAX_PARALLEL_PORTS = 3;
2ed5d572 847
0e32bf5b
FE
848for (my $i = 0; $i < $PVE::QemuServer::Memory::MAX_NUMA; $i++) {
849 $confdesc->{"numa$i"} = $PVE::QemuServer::Memory::numadesc;
2ed5d572 850}
1e3baf05 851
f7bc17ca
TL
852my $nic_model_list = [
853 'e1000',
854 'e1000-82540em',
855 'e1000-82544gc',
856 'e1000-82545em',
e83dd50a 857 'e1000e',
f7bc17ca
TL
858 'i82551',
859 'i82557b',
860 'i82559er',
861 'ne2k_isa',
862 'ne2k_pci',
863 'pcnet',
864 'rtl8139',
865 'virtio',
866 'vmxnet3',
867];
6b64503e 868my $nic_model_list_txt = join(' ', sort @$nic_model_list);
1e3baf05 869
52261945
DM
870my $net_fmt_bridge_descr = <<__EOD__;
871Bridge to attach the network device to. The Proxmox VE standard bridge
872is called 'vmbr0'.
873
874If you do not specify a bridge, we create a kvm user (NATed) network
875device, which provides DHCP and DNS services. The following addresses
876are used:
877
878 10.0.2.2 Gateway
879 10.0.2.3 DNS Server
880 10.0.2.4 SMB Server
881
882The DHCP server assign addresses to the guest starting from 10.0.2.15.
883__EOD__
884
cd9c34d1 885my $net_fmt = {
399d96db 886 macaddr => get_standard_option('mac-addr', {
4df98f2f
TL
887 description => "MAC address. That address must be unique withing your network. This is"
888 ." automatically generated if not specified.",
399d96db 889 }),
7f694a71
DM
890 model => {
891 type => 'string',
4df98f2f
TL
892 description => "Network Card Model. The 'virtio' model provides the best performance with"
893 ." very low CPU overhead. If your guest does not support this driver, it is usually"
894 ." best to use 'e1000'.",
7f694a71
DM
895 enum => $nic_model_list,
896 default_key => 1,
897 },
898 (map { $_ => { keyAlias => 'model', alias => 'macaddr' }} @$nic_model_list),
dbdcc5cd 899 bridge => get_standard_option('pve-bridge-id', {
52261945 900 description => $net_fmt_bridge_descr,
cd9c34d1 901 optional => 1,
dbdcc5cd 902 }),
cd9c34d1
WB
903 queues => {
904 type => 'integer',
66222265 905 minimum => 0, maximum => 64,
cd9c34d1 906 description => 'Number of packet queues to be used on the device.',
cd9c34d1
WB
907 optional => 1,
908 },
909 rate => {
910 type => 'number',
911 minimum => 0,
52261945 912 description => "Rate limit in mbps (megabytes per second) as floating point number.",
cd9c34d1
WB
913 optional => 1,
914 },
915 tag => {
916 type => 'integer',
9f41a659 917 minimum => 1, maximum => 4094,
cd9c34d1 918 description => 'VLAN tag to apply to packets on this interface.',
cd9c34d1
WB
919 optional => 1,
920 },
921 trunks => {
922 type => 'string',
923 pattern => qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/,
924 description => 'VLAN trunks to pass through this interface.',
7f694a71 925 format_description => 'vlanid[;vlanid...]',
cd9c34d1
WB
926 optional => 1,
927 },
928 firewall => {
929 type => 'boolean',
930 description => 'Whether this interface should be protected by the firewall.',
cd9c34d1
WB
931 optional => 1,
932 },
933 link_down => {
934 type => 'boolean',
52261945 935 description => 'Whether this interface should be disconnected (like pulling the plug).',
cd9c34d1
WB
936 optional => 1,
937 },
61a14cde
AD
938 mtu => {
939 type => 'integer',
940 minimum => 1, maximum => 65520,
0530177b 941 description => "Force MTU, for VirtIO only. Set to '1' to use the bridge MTU",
61a14cde
AD
942 optional => 1,
943 },
cd9c34d1 944};
52261945 945
1e3baf05
DM
946my $netdesc = {
947 optional => 1,
7f694a71 948 type => 'string', format => $net_fmt,
52261945 949 description => "Specify network devices.",
1e3baf05 950};
52261945 951
1e3baf05
DM
952PVE::JSONSchema::register_standard_option("pve-qm-net", $netdesc);
953
0c9a7596
AD
954my $ipconfig_fmt = {
955 ip => {
956 type => 'string',
957 format => 'pve-ipv4-config',
958 format_description => 'IPv4Format/CIDR',
959 description => 'IPv4 address in CIDR format.',
960 optional => 1,
961 default => 'dhcp',
962 },
963 gw => {
964 type => 'string',
965 format => 'ipv4',
966 format_description => 'GatewayIPv4',
967 description => 'Default gateway for IPv4 traffic.',
968 optional => 1,
969 requires => 'ip',
970 },
971 ip6 => {
972 type => 'string',
973 format => 'pve-ipv6-config',
974 format_description => 'IPv6Format/CIDR',
975 description => 'IPv6 address in CIDR format.',
976 optional => 1,
977 default => 'dhcp',
978 },
979 gw6 => {
980 type => 'string',
981 format => 'ipv6',
982 format_description => 'GatewayIPv6',
983 description => 'Default gateway for IPv6 traffic.',
984 optional => 1,
985 requires => 'ip6',
986 },
987};
988PVE::JSONSchema::register_format('pve-qm-ipconfig', $ipconfig_fmt);
989my $ipconfigdesc = {
990 optional => 1,
991 type => 'string', format => 'pve-qm-ipconfig',
992 description => <<'EODESCR',
993cloud-init: Specify IP addresses and gateways for the corresponding interface.
994
995IP addresses use CIDR notation, gateways are optional but need an IP of the same type specified.
996
4df98f2f
TL
997The special string 'dhcp' can be used for IP addresses to use DHCP, in which case no explicit
998gateway should be provided.
988be8d0
ML
999For IPv6 the special string 'auto' can be used to use stateless autoconfiguration. This requires
1000cloud-init 19.4 or newer.
0c9a7596 1001
4df98f2f
TL
1002If cloud-init is enabled and neither an IPv4 nor an IPv6 address is specified, it defaults to using
1003dhcp on IPv4.
0c9a7596
AD
1004EODESCR
1005};
1006PVE::JSONSchema::register_standard_option("pve-qm-ipconfig", $netdesc);
1007
1e3baf05
DM
1008for (my $i = 0; $i < $MAX_NETS; $i++) {
1009 $confdesc->{"net$i"} = $netdesc;
9ed7a77c
WB
1010 $confdesc_cloudinit->{"ipconfig$i"} = $ipconfigdesc;
1011}
1012
1013foreach my $key (keys %$confdesc_cloudinit) {
1014 $confdesc->{$key} = $confdesc_cloudinit->{$key};
1e3baf05
DM
1015}
1016
83870398
DB
1017PVE::JSONSchema::register_format('pve-cpuset', \&pve_verify_cpuset);
1018sub pve_verify_cpuset {
1019 my ($set_text, $noerr) = @_;
1020
1021 my ($count, $members) = eval { PVE::CpuSet::parse_cpuset($set_text) };
1022
1023 if ($@) {
1024 return if $noerr;
1025 die "unable to parse cpuset option\n";
1026 }
1027
1028 return PVE::CpuSet->new($members)->short_string();
1029}
1030
ffa42b86
DC
1031PVE::JSONSchema::register_format('pve-volume-id-or-qm-path', \&verify_volume_id_or_qm_path);
1032sub verify_volume_id_or_qm_path {
822c8a07
WB
1033 my ($volid, $noerr) = @_;
1034
6e55f579
FE
1035 return $volid if $volid eq 'none' || $volid eq 'cdrom';
1036
1037 return verify_volume_id_or_absolute_path($volid, $noerr);
1038}
1039
1040PVE::JSONSchema::register_format('pve-volume-id-or-absolute-path', \&verify_volume_id_or_absolute_path);
1041sub verify_volume_id_or_absolute_path {
1042 my ($volid, $noerr) = @_;
1043
1044 return $volid if $volid =~ m|^/|;
ffa42b86 1045
822c8a07
WB
1046 $volid = eval { PVE::JSONSchema::check_format('pve-volume-id', $volid, '') };
1047 if ($@) {
d1c1af4b 1048 return if $noerr;
822c8a07
WB
1049 die $@;
1050 }
1051 return $volid;
1052}
1053
bae179aa
DA
1054my $serialdesc = {
1055 optional => 1,
ca0cef26 1056 type => 'string',
1b0b51ed 1057 pattern => '(/dev/.+|socket)',
52261945
DM
1058 description => "Create a serial device inside the VM (n is 0 to 3)",
1059 verbose_description => <<EODESCR,
52261945
DM
1060Create a serial device inside the VM (n is 0 to 3), and pass through a
1061host serial device (i.e. /dev/ttyS0), or create a unix socket on the
1062host side (use 'qm terminal' to open a terminal connection).
bae179aa 1063
4df98f2f
TL
1064NOTE: If you pass through a host serial device, it is no longer possible to migrate such machines -
1065use with special care.
bae179aa 1066
52261945 1067CAUTION: Experimental! User reported problems with this option.
bae179aa
DA
1068EODESCR
1069};
bae179aa 1070
1989a89c
DA
1071my $paralleldesc= {
1072 optional => 1,
ca0cef26 1073 type => 'string',
9ecc8431 1074 pattern => '/dev/parport\d+|/dev/usb/lp\d+',
52261945
DM
1075 description => "Map host parallel devices (n is 0 to 2).",
1076 verbose_description => <<EODESCR,
19672434 1077Map host parallel devices (n is 0 to 2).
1989a89c 1078
4df98f2f
TL
1079NOTE: This option allows direct access to host hardware. So it is no longer possible to migrate such
1080machines - use with special care.
1989a89c 1081
52261945 1082CAUTION: Experimental! User reported problems with this option.
1989a89c
DA
1083EODESCR
1084};
1989a89c
DA
1085
1086for (my $i = 0; $i < $MAX_PARALLEL_PORTS; $i++) {
1087 $confdesc->{"parallel$i"} = $paralleldesc;
1088}
1089
bae179aa
DA
1090for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) {
1091 $confdesc->{"serial$i"} = $serialdesc;
1092}
1093
74c17b7a
SR
1094for (my $i = 0; $i < $PVE::QemuServer::PCI::MAX_HOSTPCI_DEVICES; $i++) {
1095 $confdesc->{"hostpci$i"} = $PVE::QemuServer::PCI::hostpcidesc;
040b06b7 1096}
1e3baf05 1097
e0fd2b2f
FE
1098for my $key (keys %{$PVE::QemuServer::Drive::drivedesc_hash}) {
1099 $confdesc->{$key} = $PVE::QemuServer::Drive::drivedesc_hash->{$key};
cdb0931f
DA
1100}
1101
0cf8d56c
DC
1102for (my $i = 0; $i < $PVE::QemuServer::USB::MAX_USB_DEVICES; $i++) {
1103 $confdesc->{"usb$i"} = $PVE::QemuServer::USB::usbdesc;
1e3baf05
DM
1104}
1105
5cfa9f5f
SR
1106my $boot_fmt = {
1107 legacy => {
1108 optional => 1,
1109 default_key => 1,
1110 type => 'string',
1111 description => "Boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)."
1112 . " Deprecated, use 'order=' instead.",
1113 pattern => '[acdn]{1,4}',
1114 format_description => "[acdn]{1,4}",
1115
1116 # note: this is also the fallback if boot: is not given at all
1117 default => 'cdn',
1118 },
1119 order => {
1120 optional => 1,
1121 type => 'string',
1122 format => 'pve-qm-bootdev-list',
1123 format_description => "device[;device...]",
1124 description => <<EODESC,
1125The guest will attempt to boot from devices in the order they appear here.
1126
1127Disks, optical drives and passed-through storage USB devices will be directly
1128booted from, NICs will load PXE, and PCIe devices will either behave like disks
1129(e.g. NVMe) or load an option ROM (e.g. RAID controller, hardware NIC).
1130
1131Note that only devices in this list will be marked as bootable and thus loaded
1132by the guest firmware (BIOS/UEFI). If you require multiple disks for booting
1133(e.g. software-raid), you need to specify all of them here.
1134
1135Overrides the deprecated 'legacy=[acdn]*' value when given.
1136EODESC
1137 },
1138};
1139PVE::JSONSchema::register_format('pve-qm-boot', $boot_fmt);
1140
1141PVE::JSONSchema::register_format('pve-qm-bootdev', \&verify_bootdev);
1142sub verify_bootdev {
1143 my ($dev, $noerr) = @_;
1144
f9dde219
SR
1145 my $special = $dev =~ m/^efidisk/ || $dev =~ m/^tpmstate/;
1146 return $dev if PVE::QemuServer::Drive::is_valid_drivename($dev) && !$special;
5cfa9f5f
SR
1147
1148 my $check = sub {
1149 my ($base) = @_;
1150 return 0 if $dev !~ m/^$base\d+$/;
1151 return 0 if !$confdesc->{$dev};
1152 return 1;
1153 };
1154
1155 return $dev if $check->("net");
1156 return $dev if $check->("usb");
1157 return $dev if $check->("hostpci");
1158
d1c1af4b 1159 return if $noerr;
5cfa9f5f
SR
1160 die "invalid boot device '$dev'\n";
1161}
1162
1163sub print_bootorder {
1164 my ($devs) = @_;
4c27b18c 1165 return "" if !@$devs;
5cfa9f5f
SR
1166 my $data = { order => join(';', @$devs) };
1167 return PVE::JSONSchema::print_property_string($data, $boot_fmt);
1168}
1169
1e3baf05
DM
1170my $kvm_api_version = 0;
1171
1172sub kvm_version {
1e3baf05
DM
1173 return $kvm_api_version if $kvm_api_version;
1174
808a65b5 1175 open my $fh, '<', '/dev/kvm' or return;
1e3baf05 1176
646f2df4
WB
1177 # 0xae00 => KVM_GET_API_VERSION
1178 $kvm_api_version = ioctl($fh, 0xae00, 0);
808a65b5 1179 close($fh);
1e3baf05 1180
646f2df4 1181 return $kvm_api_version;
1e3baf05
DM
1182}
1183
1476b99f
DC
1184my $kvm_user_version = {};
1185my $kvm_mtime = {};
1e3baf05
DM
1186
1187sub kvm_user_version {
1476b99f 1188 my ($binary) = @_;
1e3baf05 1189
1476b99f
DC
1190 $binary //= get_command_for_arch(get_host_arch()); # get the native arch by default
1191 my $st = stat($binary);
1e3baf05 1192
1476b99f
DC
1193 my $cachedmtime = $kvm_mtime->{$binary} // -1;
1194 return $kvm_user_version->{$binary} if $kvm_user_version->{$binary} &&
1195 $cachedmtime == $st->mtime;
1196
1197 $kvm_user_version->{$binary} = 'unknown';
1198 $kvm_mtime->{$binary} = $st->mtime;
1e3baf05 1199
09b11429
TL
1200 my $code = sub {
1201 my $line = shift;
1202 if ($line =~ m/^QEMU( PC)? emulator version (\d+\.\d+(\.\d+)?)(\.\d+)?[,\s]/) {
1476b99f 1203 $kvm_user_version->{$binary} = $2;
09b11429
TL
1204 }
1205 };
19672434 1206
1476b99f 1207 eval { run_command([$binary, '--version'], outfunc => $code); };
09b11429 1208 warn $@ if $@;
1e3baf05 1209
1476b99f 1210 return $kvm_user_version->{$binary};
1e3baf05
DM
1211
1212}
4df98f2f
TL
1213my sub extract_version {
1214 my ($machine_type, $version) = @_;
1215 $version = kvm_user_version() if !defined($version);
8eb73377 1216 return PVE::QemuServer::Machine::extract_version($machine_type, $version)
4df98f2f 1217}
1e3baf05 1218
db70021b
TL
1219sub kernel_has_vhost_net {
1220 return -c '/dev/vhost-net';
1221}
1e3baf05 1222
1e3baf05
DM
1223sub option_exists {
1224 my $key = shift;
1225 return defined($confdesc->{$key});
19672434 1226}
1e3baf05 1227
1e3baf05 1228my $cdrom_path;
1e3baf05
DM
1229sub get_cdrom_path {
1230
259470ee 1231 return $cdrom_path if defined($cdrom_path);
1e3baf05 1232
c3d15108
TL
1233 $cdrom_path = first { -l $_ } map { "/dev/cdrom$_" } ('', '1', '2');
1234
1235 if (!defined($cdrom_path)) {
490b7308
SS
1236 log_warn("no physical CD-ROM available, ignoring");
1237 $cdrom_path = '';
1238 }
259470ee
SS
1239
1240 return $cdrom_path;
1e3baf05
DM
1241}
1242
1243sub get_iso_path {
1244 my ($storecfg, $vmid, $cdrom) = @_;
1245
1246 if ($cdrom eq 'cdrom') {
1247 return get_cdrom_path();
1248 } elsif ($cdrom eq 'none') {
1249 return '';
1250 } elsif ($cdrom =~ m|^/|) {
1251 return $cdrom;
1252 } else {
6b64503e 1253 return PVE::Storage::path($storecfg, $cdrom);
1e3baf05
DM
1254 }
1255}
1256
1257# try to convert old style file names to volume IDs
1258sub filename_to_volume_id {
1259 my ($vmid, $file, $media) = @_;
1260
0c9a7596 1261 if (!($file eq 'none' || $file eq 'cdrom' ||
1e3baf05 1262 $file =~ m|^/dev/.+| || $file =~ m/^([^:]+):(.+)$/)) {
19672434 1263
d1c1af4b 1264 return if $file =~ m|/|;
19672434 1265
1e3baf05
DM
1266 if ($media && $media eq 'cdrom') {
1267 $file = "local:iso/$file";
1268 } else {
1269 $file = "local:$vmid/$file";
1270 }
1271 }
1272
1273 return $file;
1274}
1275
1276sub verify_media_type {
1277 my ($opt, $vtype, $media) = @_;
1278
1279 return if !$media;
1280
1281 my $etype;
1282 if ($media eq 'disk') {
a125592c 1283 $etype = 'images';
1e3baf05
DM
1284 } elsif ($media eq 'cdrom') {
1285 $etype = 'iso';
1286 } else {
1287 die "internal error";
1288 }
1289
1290 return if ($vtype eq $etype);
19672434 1291
1e3baf05
DM
1292 raise_param_exc({ $opt => "unexpected media type ($vtype != $etype)" });
1293}
1294
1295sub cleanup_drive_path {
1296 my ($opt, $storecfg, $drive) = @_;
1297
1298 # try to convert filesystem paths to volume IDs
1299
1300 if (($drive->{file} !~ m/^(cdrom|none)$/) &&
1301 ($drive->{file} !~ m|^/dev/.+|) &&
1302 ($drive->{file} !~ m/^([^:]+):(.+)$/) &&
19672434 1303 ($drive->{file} !~ m/^\d+$/)) {
1e3baf05 1304 my ($vtype, $volid) = PVE::Storage::path_to_volume_id($storecfg, $drive->{file});
4df98f2f
TL
1305 raise_param_exc({ $opt => "unable to associate path '$drive->{file}' to any storage"})
1306 if !$vtype;
1e3baf05
DM
1307 $drive->{media} = 'cdrom' if !$drive->{media} && $vtype eq 'iso';
1308 verify_media_type($opt, $vtype, $drive->{media});
1309 $drive->{file} = $volid;
1310 }
1311
1312 $drive->{media} = 'cdrom' if !$drive->{media} && $drive->{file} =~ m/^(cdrom|none)$/;
1313}
1314
b3c2bdd1
DM
1315sub parse_hotplug_features {
1316 my ($data) = @_;
1317
1318 my $res = {};
1319
1320 return $res if $data eq '0';
a1b7d579 1321
b3c2bdd1
DM
1322 $data = $confdesc->{hotplug}->{default} if $data eq '1';
1323
45827685 1324 foreach my $feature (PVE::Tools::split_list($data)) {
94ec5e7c 1325 if ($feature =~ m/^(network|disk|cpu|memory|usb|cloudinit)$/) {
b3c2bdd1
DM
1326 $res->{$1} = 1;
1327 } else {
596a0a20 1328 die "invalid hotplug feature '$feature'\n";
b3c2bdd1
DM
1329 }
1330 }
1331 return $res;
1332}
1333
1334PVE::JSONSchema::register_format('pve-hotplug-features', \&pve_verify_hotplug_features);
1335sub pve_verify_hotplug_features {
1336 my ($value, $noerr) = @_;
1337
1338 return $value if parse_hotplug_features($value);
1339
d1c1af4b 1340 return if $noerr;
b3c2bdd1
DM
1341
1342 die "unable to parse hotplug option\n";
1343}
1344
28ef82d3
DM
1345sub scsi_inquiry {
1346 my($fh, $noerr) = @_;
1347
1348 my $SG_IO = 0x2285;
1349 my $SG_GET_VERSION_NUM = 0x2282;
1350
1351 my $versionbuf = "\x00" x 8;
1352 my $ret = ioctl($fh, $SG_GET_VERSION_NUM, $versionbuf);
1353 if (!$ret) {
1354 die "scsi ioctl SG_GET_VERSION_NUM failoed - $!\n" if !$noerr;
d1c1af4b 1355 return;
28ef82d3 1356 }
97d62eb7 1357 my $version = unpack("I", $versionbuf);
28ef82d3
DM
1358 if ($version < 30000) {
1359 die "scsi generic interface too old\n" if !$noerr;
d1c1af4b 1360 return;
28ef82d3 1361 }
97d62eb7 1362
28ef82d3
DM
1363 my $buf = "\x00" x 36;
1364 my $sensebuf = "\x00" x 8;
f334aa3e 1365 my $cmd = pack("C x3 C x1", 0x12, 36);
97d62eb7 1366
28ef82d3
DM
1367 # see /usr/include/scsi/sg.h
1368 my $sg_io_hdr_t = "i i C C s I P P P I I i P C C C C S S i I I";
1369
f606d5bd
TL
1370 my $packet = pack(
1371 $sg_io_hdr_t, ord('S'), -3, length($cmd), length($sensebuf), 0, length($buf), $buf, $cmd, $sensebuf, 6000
1372 );
28ef82d3
DM
1373
1374 $ret = ioctl($fh, $SG_IO, $packet);
1375 if (!$ret) {
1376 die "scsi ioctl SG_IO failed - $!\n" if !$noerr;
d1c1af4b 1377 return;
28ef82d3 1378 }
97d62eb7 1379
28ef82d3
DM
1380 my @res = unpack($sg_io_hdr_t, $packet);
1381 if ($res[17] || $res[18]) {
1382 die "scsi ioctl SG_IO status error - $!\n" if !$noerr;
d1c1af4b 1383 return;
28ef82d3
DM
1384 }
1385
1386 my $res = {};
f606d5bd 1387 $res->@{qw(type removable vendor product revision)} = unpack("C C x6 A8 A16 A4", $buf);
28ef82d3 1388
f606d5bd
TL
1389 $res->{removable} = $res->{removable} & 128 ? 1 : 0;
1390 $res->{type} &= 0x1F;
09984754 1391
28ef82d3
DM
1392 return $res;
1393}
1394
1395sub path_is_scsi {
1396 my ($path) = @_;
1397
d1c1af4b 1398 my $fh = IO::File->new("+<$path") || return;
28ef82d3
DM
1399 my $res = scsi_inquiry($fh, 1);
1400 close($fh);
1401
1402 return $res;
1403}
1404
db656e5f 1405sub print_tabletdevice_full {
d559309f 1406 my ($conf, $arch) = @_;
b467f79a 1407
3392d6ca 1408 my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf);
db656e5f
DM
1409
1410 # we use uhci for old VMs because tablet driver was buggy in older qemu
d559309f 1411 my $usbbus;
2b938c7d 1412 if ($q35 || $arch eq 'aarch64') {
d559309f
WB
1413 $usbbus = 'ehci';
1414 } else {
1415 $usbbus = 'uhci';
1416 }
b467f79a 1417
db656e5f
DM
1418 return "usb-tablet,id=tablet,bus=$usbbus.0,port=1";
1419}
1420
d559309f 1421sub print_keyboarddevice_full {
6971c38e 1422 my ($conf, $arch) = @_;
d559309f 1423
d1c1af4b 1424 return if $arch ne 'aarch64';
d559309f
WB
1425
1426 return "usb-kbd,id=keyboard,bus=ehci.0,port=2";
1427}
1428
a183df68
TL
1429my sub get_drive_id {
1430 my ($drive) = @_;
1431 return "$drive->{interface}$drive->{index}";
1432}
1433
ca916ecc 1434sub print_drivedevice_full {
d559309f 1435 my ($storecfg, $conf, $vmid, $drive, $bridges, $arch, $machine_type) = @_;
ca916ecc
DA
1436
1437 my $device = '';
1438 my $maxdev = 0;
19672434 1439
a183df68 1440 my $drive_id = get_drive_id($drive);
ca916ecc 1441 if ($drive->{interface} eq 'virtio') {
4df98f2f
TL
1442 my $pciaddr = print_pci_addr("$drive_id", $bridges, $arch, $machine_type);
1443 $device = "virtio-blk-pci,drive=drive-$drive_id,id=${drive_id}${pciaddr}";
1444 $device .= ",iothread=iothread-$drive_id" if $drive->{iothread};
2ed36a41 1445 } elsif ($drive->{interface} eq 'scsi') {
6731a4cf 1446
ee034f5c 1447 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $drive);
2ed36a41
DM
1448 my $unit = $drive->{index} % $maxdev;
1449 my $devicetype = 'hd';
69bcf246
WB
1450 my $path = '';
1451 if (drive_is_cdrom($drive)) {
1452 $devicetype = 'cd';
29b19529 1453 } else {
69bcf246
WB
1454 if ($drive->{file} =~ m|^/|) {
1455 $path = $drive->{file};
1456 if (my $info = path_is_scsi($path)) {
8e3c33ab 1457 if ($info->{type} == 0 && $drive->{scsiblock}) {
69bcf246
WB
1458 $devicetype = 'block';
1459 } elsif ($info->{type} == 1) { # tape
1460 $devicetype = 'generic';
1461 }
1462 }
1463 } else {
1464 $path = PVE::Storage::path($storecfg, $drive->{file});
1465 }
1466
a034e3d6 1467 # for compatibility only, we prefer scsi-hd (#2408, #2355, #2380)
4df98f2f 1468 my $version = extract_version($machine_type, kvm_user_version());
a034e3d6 1469 if ($path =~ m/^iscsi\:\/\// &&
2ea5fb7e 1470 !min_version($version, 4, 1)) {
69bcf246
WB
1471 $devicetype = 'generic';
1472 }
1473 }
1474
ef88eaaa 1475 if (!$conf->{scsihw} || $conf->{scsihw} =~ m/^lsi/ || $conf->{scsihw} eq 'pvscsi') {
4df98f2f 1476 $device = "scsi-$devicetype,bus=$controller_prefix$controller.0,scsi-id=$unit";
69bcf246 1477 } else {
4df98f2f
TL
1478 $device = "scsi-$devicetype,bus=$controller_prefix$controller.0,channel=0,scsi-id=0"
1479 .",lun=$drive->{index}";
69bcf246 1480 }
4df98f2f 1481 $device .= ",drive=drive-$drive_id,id=$drive_id";
cdd20088 1482
6c875f9f
NC
1483 if ($drive->{ssd} && ($devicetype eq 'block' || $devicetype eq 'hd')) {
1484 $device .= ",rotation_rate=1";
1485 }
e741c516 1486 $device .= ",wwn=$drive->{wwn}" if $drive->{wwn};
6c875f9f
NC
1487
1488 } elsif ($drive->{interface} eq 'ide' || $drive->{interface} eq 'sata') {
e0fd2b2f 1489 my $maxdev = ($drive->{interface} eq 'sata') ? $PVE::QemuServer::Drive::MAX_SATA_DISKS : 2;
2ed36a41
DM
1490 my $controller = int($drive->{index} / $maxdev);
1491 my $unit = $drive->{index} % $maxdev;
b155086b
FE
1492
1493 # machine type q35 only supports unit=0 for IDE rather than 2 units. This wasn't handled
1494 # correctly before, so e.g. index=2 was mapped to controller=1,unit=0 rather than
1495 # controller=2,unit=0. Note that odd indices never worked, as they would be mapped to
1496 # unit=1, so to keep backwards compat for migration, it suffices to keep even ones as they
1497 # were before. Move odd ones up by 2 where they don't clash.
1498 if (PVE::QemuServer::Machine::machine_type_is_q35($conf) && $drive->{interface} eq 'ide') {
1499 $controller += 2 * ($unit % 2);
1500 $unit = 0;
1501 }
1502
2ed36a41
DM
1503 my $devicetype = ($drive->{media} && $drive->{media} eq 'cdrom') ? "cd" : "hd";
1504
6c875f9f
NC
1505 $device = "ide-$devicetype";
1506 if ($drive->{interface} eq 'ide') {
1507 $device .= ",bus=ide.$controller,unit=$unit";
1508 } else {
1509 $device .= ",bus=ahci$controller.$unit";
1510 }
4df98f2f 1511 $device .= ",drive=drive-$drive_id,id=$drive_id";
6c875f9f
NC
1512
1513 if ($devicetype eq 'hd') {
1514 if (my $model = $drive->{model}) {
1515 $model = URI::Escape::uri_unescape($model);
1516 $device .= ",model=$model";
1517 }
1518 if ($drive->{ssd}) {
1519 $device .= ",rotation_rate=1";
1520 }
0f2812c2 1521 }
e741c516 1522 $device .= ",wwn=$drive->{wwn}" if $drive->{wwn};
2ed36a41
DM
1523 } elsif ($drive->{interface} eq 'usb') {
1524 die "implement me";
1525 # -device ide-drive,bus=ide.1,unit=0,drive=drive-ide0-1-0,id=ide0-1-0
1526 } else {
1527 die "unsupported interface type";
ca916ecc
DA
1528 }
1529
3b408e82
DM
1530 $device .= ",bootindex=$drive->{bootindex}" if $drive->{bootindex};
1531
a70e7e6c
TL
1532 if (my $serial = $drive->{serial}) {
1533 $serial = URI::Escape::uri_unescape($serial);
1534 $device .= ",serial=$serial";
1535 }
1536
1537
ca916ecc
DA
1538 return $device;
1539}
1540
15b21acc 1541sub get_initiator_name {
46f58b5f 1542 my $initiator;
15b21acc 1543
d1c1af4b 1544 my $fh = IO::File->new('/etc/iscsi/initiatorname.iscsi') || return;
46f58b5f
DM
1545 while (defined(my $line = <$fh>)) {
1546 next if $line !~ m/^\s*InitiatorName\s*=\s*([\.\-:\w]+)/;
15b21acc
MR
1547 $initiator = $1;
1548 last;
1549 }
46f58b5f
DM
1550 $fh->close();
1551
15b21acc
MR
1552 return $initiator;
1553}
1554
eec9f9fe
FE
1555my sub storage_allows_io_uring_default {
1556 my ($scfg, $cache_direct) = @_;
1557
1558 # io_uring with cache mode writeback or writethrough on krbd will hang...
1559 return if $scfg && $scfg->{type} eq 'rbd' && $scfg->{krbd} && !$cache_direct;
1560
1561 # io_uring with cache mode writeback or writethrough on LVM will hang, without cache only
1562 # sometimes, just plain disable...
1563 return if $scfg && $scfg->{type} eq 'lvm';
1564
1565 # io_uring causes problems when used with CIFS since kernel 5.15
1566 # Some discussion: https://www.spinics.net/lists/linux-cifs/msg26734.html
1567 return if $scfg && $scfg->{type} eq 'cifs';
1568
1569 return 1;
1570}
1571
b7071d6c
FE
1572my sub drive_uses_cache_direct {
1573 my ($drive, $scfg) = @_;
1574
1575 my $cache_direct = 0;
1576
1577 if (my $cache = $drive->{cache}) {
1578 $cache_direct = $cache =~ /^(?:off|none|directsync)$/;
1579 } elsif (!drive_is_cdrom($drive) && !($scfg && $scfg->{type} eq 'btrfs' && !$scfg->{nocow})) {
1580 $cache_direct = 1;
1581 }
1582
1583 return $cache_direct;
1584}
1585
776c5f50 1586sub print_drive_commandline_full {
6d5673c3 1587 my ($storecfg, $vmid, $drive, $pbs_name, $io_uring) = @_;
1e3baf05 1588
d81f0f09
DM
1589 my $path;
1590 my $volid = $drive->{file};
5921764c 1591 my $format = $drive->{format};
a183df68 1592 my $drive_id = get_drive_id($drive);
370b05e7 1593
0fe779a6
WB
1594 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1595 my $scfg = $storeid ? PVE::Storage::storage_config($storecfg, $storeid) : undef;
1596
d81f0f09
DM
1597 if (drive_is_cdrom($drive)) {
1598 $path = get_iso_path($storecfg, $vmid, $volid);
a183df68 1599 die "$drive_id: cannot back cdrom drive with PBS snapshot\n" if $pbs_name;
d81f0f09 1600 } else {
d81f0f09
DM
1601 if ($storeid) {
1602 $path = PVE::Storage::path($storecfg, $volid);
5921764c 1603 $format //= qemu_img_format($scfg, $volname);
d81f0f09
DM
1604 } else {
1605 $path = $volid;
5921764c 1606 $format //= "raw";
d81f0f09
DM
1607 }
1608 }
1609
5921764c
SR
1610 my $is_rbd = $path =~ m/^rbd:/;
1611
1e3baf05 1612 my $opts = '';
5921764c 1613 my @qemu_drive_options = qw(heads secs cyls trans media cache rerror werror aio discard);
1e3baf05 1614 foreach my $o (@qemu_drive_options) {
5fc74861 1615 $opts .= ",$o=$drive->{$o}" if defined($drive->{$o});
19672434 1616 }
8a267708
DC
1617
1618 # snapshot only accepts on|off
1619 if (defined($drive->{snapshot})) {
1620 my $v = $drive->{snapshot} ? 'on' : 'off';
1621 $opts .= ",snapshot=$v";
1622 }
1623
1f91f7b4
TL
1624 if (defined($drive->{ro})) { # ro maps to QEMUs `readonly`, which accepts `on` or `off` only
1625 $opts .= ",readonly=" . ($drive->{ro} ? 'on' : 'off');
12e1d472
DC
1626 }
1627
fb8e95a2
WB
1628 foreach my $type (['', '-total'], [_rd => '-read'], [_wr => '-write']) {
1629 my ($dir, $qmpname) = @$type;
1630 if (my $v = $drive->{"mbps$dir"}) {
1631 $opts .= ",throttling.bps$qmpname=".int($v*1024*1024);
1632 }
1633 if (my $v = $drive->{"mbps${dir}_max"}) {
1634 $opts .= ",throttling.bps$qmpname-max=".int($v*1024*1024);
1635 }
1636 if (my $v = $drive->{"bps${dir}_max_length"}) {
1637 $opts .= ",throttling.bps$qmpname-max-length=$v";
1638 }
1639 if (my $v = $drive->{"iops${dir}"}) {
1640 $opts .= ",throttling.iops$qmpname=$v";
1641 }
1642 if (my $v = $drive->{"iops${dir}_max"}) {
8aca1654 1643 $opts .= ",throttling.iops$qmpname-max=$v";
fb8e95a2
WB
1644 }
1645 if (my $v = $drive->{"iops${dir}_max_length"}) {
8aca1654 1646 $opts .= ",throttling.iops$qmpname-max-length=$v";
fb8e95a2
WB
1647 }
1648 }
1649
5921764c
SR
1650 if ($pbs_name) {
1651 $format = "rbd" if $is_rbd;
a183df68
TL
1652 die "$drive_id: Proxmox Backup Server backed drive cannot auto-detect the format\n"
1653 if !$format;
5921764c
SR
1654 $opts .= ",format=alloc-track,file.driver=$format";
1655 } elsif ($format) {
1656 $opts .= ",format=$format";
1657 }
d81f0f09 1658
b7071d6c 1659 my $cache_direct = drive_uses_cache_direct($drive, $scfg);
b2ee900e 1660
b7071d6c 1661 $opts .= ",cache=none" if !$drive->{cache} && $cache_direct;
b2ee900e 1662
b2ee900e 1663 if (!$drive->{aio}) {
eec9f9fe 1664 if ($io_uring && storage_allows_io_uring_default($scfg, $cache_direct)) {
6d5673c3
SR
1665 # io_uring supports all cache modes
1666 $opts .= ",aio=io_uring";
b2ee900e 1667 } else {
6d5673c3
SR
1668 # aio native works only with O_DIRECT
1669 if($cache_direct) {
1670 $opts .= ",aio=native";
1671 } else {
1672 $opts .= ",aio=threads";
1673 }
b2ee900e
WB
1674 }
1675 }
11490cf2 1676
6e47c3b4
WB
1677 if (!drive_is_cdrom($drive)) {
1678 my $detectzeroes;
7d4e30f3 1679 if (defined($drive->{detect_zeroes}) && !$drive->{detect_zeroes}) {
6e47c3b4
WB
1680 $detectzeroes = 'off';
1681 } elsif ($drive->{discard}) {
1682 $detectzeroes = $drive->{discard} eq 'on' ? 'unmap' : 'on';
1683 } else {
1684 # This used to be our default with discard not being specified:
1685 $detectzeroes = 'on';
1686 }
5921764c
SR
1687
1688 # note: 'detect-zeroes' works per blockdev and we want it to persist
1689 # after the alloc-track is removed, so put it on 'file' directly
1690 my $dz_param = $pbs_name ? "file.detect-zeroes" : "detect-zeroes";
1691 $opts .= ",$dz_param=$detectzeroes" if $detectzeroes;
6e47c3b4 1692 }
f1e05305 1693
5921764c
SR
1694 if ($pbs_name) {
1695 $opts .= ",backing=$pbs_name";
1696 $opts .= ",auto-remove=on";
1697 }
1698
1699 # my $file_param = $pbs_name ? "file.file.filename" : "file";
1700 my $file_param = "file";
1701 if ($pbs_name) {
1702 # non-rbd drivers require the underlying file to be a seperate block
1703 # node, so add a second .file indirection
1704 $file_param .= ".file" if !$is_rbd;
1705 $file_param .= ".filename";
1706 }
1707 my $pathinfo = $path ? "$file_param=$path," : '';
1e3baf05 1708
3ebfcc86 1709 return "${pathinfo}if=none,id=drive-$drive->{interface}$drive->{index}$opts";
1e3baf05
DM
1710}
1711
5921764c
SR
1712sub print_pbs_blockdev {
1713 my ($pbs_conf, $pbs_name) = @_;
1714 my $blockdev = "driver=pbs,node-name=$pbs_name,read-only=on";
1715 $blockdev .= ",repository=$pbs_conf->{repository}";
2dda626d 1716 $blockdev .= ",namespace=$pbs_conf->{namespace}" if $pbs_conf->{namespace};
5921764c
SR
1717 $blockdev .= ",snapshot=$pbs_conf->{snapshot}";
1718 $blockdev .= ",archive=$pbs_conf->{archive}";
1719 $blockdev .= ",keyfile=$pbs_conf->{keyfile}" if $pbs_conf->{keyfile};
1720 return $blockdev;
1721}
1722
cc4d6182 1723sub print_netdevice_full {
0c03a390 1724 my ($vmid, $conf, $net, $netid, $bridges, $use_old_bios_files, $arch, $machine_type, $machine_version) = @_;
cc4d6182 1725
cc4d6182
DA
1726 my $device = $net->{model};
1727 if ($net->{model} eq 'virtio') {
1728 $device = 'virtio-net-pci';
1729 };
1730
d559309f 1731 my $pciaddr = print_pci_addr("$netid", $bridges, $arch, $machine_type);
5e2068d2 1732 my $tmpstr = "$device,mac=$net->{macaddr},netdev=$netid$pciaddr,id=$netid";
a9410357 1733 if ($net->{queues} && $net->{queues} > 1 && $net->{model} eq 'virtio'){
4df98f2f
TL
1734 # Consider we have N queues, the number of vectors needed is 2 * N + 2, i.e., one per in
1735 # and out of each queue plus one config interrupt and control vector queue
a9410357
AD
1736 my $vectors = $net->{queues} * 2 + 2;
1737 $tmpstr .= ",vectors=$vectors,mq=on";
0c03a390
AD
1738 if (min_version($machine_version, 7, 1)) {
1739 $tmpstr .= ",packed=on";
1740 }
a9410357 1741 }
620d6b32
AD
1742
1743 if (min_version($machine_version, 7, 1) && $net->{model} eq 'virtio'){
089aed81 1744 $tmpstr .= ",rx_queue_size=1024,tx_queue_size=256";
620d6b32
AD
1745 }
1746
cc4d6182 1747 $tmpstr .= ",bootindex=$net->{bootindex}" if $net->{bootindex} ;
ba9e1000 1748
0530177b
TL
1749 if (my $mtu = $net->{mtu}) {
1750 if ($net->{model} eq 'virtio' && $net->{bridge}) {
1751 my $bridge_mtu = PVE::Network::read_bridge_mtu($net->{bridge});
1752 if ($mtu == 1) {
1753 $mtu = $bridge_mtu;
1754 } elsif ($mtu < 576) {
1755 die "netdev $netid: MTU '$mtu' is smaller than the IP minimum MTU '576'\n";
1756 } elsif ($mtu > $bridge_mtu) {
1757 die "netdev $netid: MTU '$mtu' is bigger than the bridge MTU '$bridge_mtu'\n";
1758 }
1759 $tmpstr .= ",host_mtu=$mtu";
1760 } else {
1761 warn "WARN: netdev $netid: ignoring MTU '$mtu', not using VirtIO or no bridge configured.\n";
61a14cde 1762 }
61a14cde
AD
1763 }
1764
ba9e1000
DM
1765 if ($use_old_bios_files) {
1766 my $romfile;
1767 if ($device eq 'virtio-net-pci') {
1768 $romfile = 'pxe-virtio.rom';
1769 } elsif ($device eq 'e1000') {
1770 $romfile = 'pxe-e1000.rom';
e83dd50a
TL
1771 } elsif ($device eq 'e1000e') {
1772 $romfile = 'pxe-e1000e.rom';
ba9e1000
DM
1773 } elsif ($device eq 'ne2k') {
1774 $romfile = 'pxe-ne2k_pci.rom';
1775 } elsif ($device eq 'pcnet') {
1776 $romfile = 'pxe-pcnet.rom';
1777 } elsif ($device eq 'rtl8139') {
1778 $romfile = 'pxe-rtl8139.rom';
1779 }
1780 $tmpstr .= ",romfile=$romfile" if $romfile;
1781 }
1782
cc4d6182
DA
1783 return $tmpstr;
1784}
1785
1786sub print_netdev_full {
d559309f 1787 my ($vmid, $conf, $arch, $net, $netid, $hotplug) = @_;
cc4d6182
DA
1788
1789 my $i = '';
1790 if ($netid =~ m/^net(\d+)$/) {
1791 $i = int($1);
1792 }
1793
1794 die "got strange net id '$i'\n" if $i >= ${MAX_NETS};
1795
1796 my $ifname = "tap${vmid}i$i";
1797
1798 # kvm uses TUNSETIFF ioctl, and that limits ifname length
1799 die "interface name '$ifname' is too long (max 15 character)\n"
1800 if length($ifname) >= 16;
1801
1802 my $vhostparam = '';
6f0cb675 1803 if (is_native($arch)) {
db70021b 1804 $vhostparam = ',vhost=on' if kernel_has_vhost_net() && $net->{model} eq 'virtio';
6f0cb675 1805 }
cc4d6182
DA
1806
1807 my $vmname = $conf->{name} || "vm$vmid";
1808
a9410357 1809 my $netdev = "";
208ba94e 1810 my $script = $hotplug ? "pve-bridge-hotplug" : "pve-bridge";
a9410357 1811
cc4d6182 1812 if ($net->{bridge}) {
4df98f2f
TL
1813 $netdev = "type=tap,id=$netid,ifname=${ifname},script=/var/lib/qemu-server/$script"
1814 .",downscript=/var/lib/qemu-server/pve-bridgedown$vhostparam";
cc4d6182 1815 } else {
a9410357 1816 $netdev = "type=user,id=$netid,hostname=$vmname";
cc4d6182 1817 }
a9410357
AD
1818
1819 $netdev .= ",queues=$net->{queues}" if ($net->{queues} && $net->{model} eq 'virtio');
1820
1821 return $netdev;
cc4d6182 1822}
1e3baf05 1823
55655ebc
DC
1824my $vga_map = {
1825 'cirrus' => 'cirrus-vga',
1826 'std' => 'VGA',
1827 'vmware' => 'vmware-svga',
1828 'virtio' => 'virtio-vga',
6f070e39 1829 'virtio-gl' => 'virtio-vga-gl',
55655ebc
DC
1830};
1831
1832sub print_vga_device {
2ea5fb7e 1833 my ($conf, $vga, $arch, $machine_version, $machine, $id, $qxlnum, $bridges) = @_;
55655ebc
DC
1834
1835 my $type = $vga_map->{$vga->{type}};
86c9fafe 1836 if ($arch eq 'aarch64' && defined($type) && $type eq 'virtio-vga') {
d559309f
WB
1837 $type = 'virtio-gpu';
1838 }
55655ebc 1839 my $vgamem_mb = $vga->{memory};
6021c7a5
AL
1840
1841 my $max_outputs = '';
55655ebc
DC
1842 if ($qxlnum) {
1843 $type = $id ? 'qxl' : 'qxl-vga';
6021c7a5 1844
c5a4c92c 1845 if (!$conf->{ostype} || $conf->{ostype} =~ m/^(?:l\d\d)|(?:other)$/) {
6021c7a5 1846 # set max outputs so linux can have up to 4 qxl displays with one device
2ea5fb7e 1847 if (min_version($machine_version, 4, 1)) {
9e8976ea
TL
1848 $max_outputs = ",max_outputs=4";
1849 }
6021c7a5 1850 }
55655ebc 1851 }
6021c7a5 1852
55655ebc
DC
1853 die "no devicetype for $vga->{type}\n" if !$type;
1854
1855 my $memory = "";
1856 if ($vgamem_mb) {
6f070e39 1857 if ($vga->{type} =~ /^virtio/) {
55655ebc
DC
1858 my $bytes = PVE::Tools::convert_size($vgamem_mb, "mb" => "b");
1859 $memory = ",max_hostmem=$bytes";
1860 } elsif ($qxlnum) {
1861 # from https://www.spice-space.org/multiple-monitors.html
1862 $memory = ",vgamem_mb=$vga->{memory}";
1863 my $ram = $vgamem_mb * 4;
1864 my $vram = $vgamem_mb * 2;
1865 $memory .= ",ram_size_mb=$ram,vram_size_mb=$vram";
1866 } else {
1867 $memory = ",vgamem_mb=$vga->{memory}";
1868 }
1869 } elsif ($qxlnum && $id) {
1870 $memory = ",ram_size=67108864,vram_size=33554432";
1871 }
1872
789fe8e8
AL
1873 my $edidoff = "";
1874 if ($type eq 'VGA' && windows_version($conf->{ostype})) {
b5d32c6b 1875 $edidoff=",edid=off" if (!defined($conf->{bios}) || $conf->{bios} ne 'ovmf');
789fe8e8
AL
1876 }
1877
3392d6ca 1878 my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf);
55655ebc
DC
1879 my $vgaid = "vga" . ($id // '');
1880 my $pciaddr;
1881 if ($q35 && $vgaid eq 'vga') {
daadd5a4 1882 # the first display uses pcie.0 bus on q35 machines
d559309f 1883 $pciaddr = print_pcie_addr($vgaid, $bridges, $arch, $machine);
55655ebc 1884 } else {
d559309f 1885 $pciaddr = print_pci_addr($vgaid, $bridges, $arch, $machine);
55655ebc
DC
1886 }
1887
9f979d9f 1888 if ($vga->{type} eq 'virtio-gl') {
8884a8bf
TL
1889 my $base = '/usr/lib/x86_64-linux-gnu/lib';
1890 die "missing libraries for '$vga->{type}' detected! Please install 'libgl1' and 'libegl1'\n"
1891 if !-e "${base}EGL.so.1" || !-e "${base}GL.so.1";
9f979d9f 1892
8884a8bf
TL
1893 die "no DRM render node detected (/dev/dri/renderD*), no GPU? - needed for '$vga->{type}' display\n"
1894 if !PVE::Tools::dir_glob_regex('/dev/dri/', "renderD.*");
9f979d9f
SI
1895 }
1896
789fe8e8 1897 return "$type,id=${vgaid}${memory}${max_outputs}${pciaddr}${edidoff}";
55655ebc
DC
1898}
1899
1e3baf05
DM
1900# netX: e1000=XX:XX:XX:XX:XX:XX,bridge=vmbr0,rate=<mbps>
1901sub parse_net {
4ddd2ca2 1902 my ($data, $disable_mac_autogen) = @_;
1e3baf05 1903
4df98f2f 1904 my $res = eval { parse_property_string($net_fmt, $data) };
cd9c34d1
WB
1905 if ($@) {
1906 warn $@;
d1c1af4b 1907 return;
1e3baf05 1908 }
4ddd2ca2 1909 if (!defined($res->{macaddr}) && !$disable_mac_autogen) {
b5b99790
WB
1910 my $dc = PVE::Cluster::cfs_read_file('datacenter.cfg');
1911 $res->{macaddr} = PVE::Tools::random_ether_addr($dc->{mac_prefix});
1912 }
0c9a7596
AD
1913 return $res;
1914}
1915
1916# ipconfigX ip=cidr,gw=ip,ip6=cidr,gw6=ip
1917sub parse_ipconfig {
1918 my ($data) = @_;
1919
4df98f2f 1920 my $res = eval { parse_property_string($ipconfig_fmt, $data) };
0c9a7596
AD
1921 if ($@) {
1922 warn $@;
d1c1af4b 1923 return;
0c9a7596
AD
1924 }
1925
1926 if ($res->{gw} && !$res->{ip}) {
1927 warn 'gateway specified without specifying an IP address';
d1c1af4b 1928 return;
0c9a7596
AD
1929 }
1930 if ($res->{gw6} && !$res->{ip6}) {
1931 warn 'IPv6 gateway specified without specifying an IPv6 address';
d1c1af4b 1932 return;
0c9a7596
AD
1933 }
1934 if ($res->{gw} && $res->{ip} eq 'dhcp') {
1935 warn 'gateway specified together with DHCP';
d1c1af4b 1936 return;
0c9a7596
AD
1937 }
1938 if ($res->{gw6} && $res->{ip6} !~ /^$IPV6RE/) {
1939 # gw6 + auto/dhcp
1940 warn "IPv6 gateway specified together with $res->{ip6} address";
d1c1af4b 1941 return;
0c9a7596
AD
1942 }
1943
1944 if (!$res->{ip} && !$res->{ip6}) {
1945 return { ip => 'dhcp', ip6 => 'dhcp' };
1946 }
1947
1e3baf05
DM
1948 return $res;
1949}
1950
1951sub print_net {
1952 my $net = shift;
1953
cd9c34d1 1954 return PVE::JSONSchema::print_property_string($net, $net_fmt);
1e3baf05
DM
1955}
1956
1957sub add_random_macs {
1958 my ($settings) = @_;
1959
1960 foreach my $opt (keys %$settings) {
1961 next if $opt !~ m/^net(\d+)$/;
1962 my $net = parse_net($settings->{$opt});
1963 next if !$net;
1964 $settings->{$opt} = print_net($net);
1965 }
1966}
1967
055d554d
DM
1968sub vm_is_volid_owner {
1969 my ($storecfg, $vmid, $volid) = @_;
1970
1971 if ($volid !~ m|^/|) {
1972 my ($path, $owner);
1973 eval { ($path, $owner) = PVE::Storage::path($storecfg, $volid); };
1974 if ($owner && ($owner == $vmid)) {
1975 return 1;
1976 }
1977 }
1978
d1c1af4b 1979 return;
055d554d
DM
1980}
1981
055d554d
DM
1982sub vmconfig_register_unused_drive {
1983 my ($storecfg, $vmid, $conf, $drive) = @_;
1984
2d9ddec5
WB
1985 if (drive_is_cloudinit($drive)) {
1986 eval { PVE::Storage::vdisk_free($storecfg, $drive->{file}) };
1987 warn $@ if $@;
95a5135d 1988 delete $conf->{cloudinit};
2d9ddec5 1989 } elsif (!drive_is_cdrom($drive)) {
055d554d
DM
1990 my $volid = $drive->{file};
1991 if (vm_is_volid_owner($storecfg, $vmid, $volid)) {
8793d495 1992 PVE::QemuConfig->add_unused_volume($conf, $volid, $vmid);
055d554d
DM
1993 }
1994 }
1995}
1996
1f30ac3a 1997# smbios: [manufacturer=str][,product=str][,version=str][,serial=str][,uuid=uuid][,sku=str][,family=str][,base64=bool]
ff6ffe20 1998my $smbios1_fmt = {
bd27e851
WB
1999 uuid => {
2000 type => 'string',
2001 pattern => '[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}',
2002 format_description => 'UUID',
52261945 2003 description => "Set SMBIOS1 UUID.",
bd27e851
WB
2004 optional => 1,
2005 },
2006 version => {
2007 type => 'string',
1f30ac3a
CE
2008 pattern => '[A-Za-z0-9+\/]+={0,2}',
2009 format_description => 'Base64 encoded string',
52261945 2010 description => "Set SMBIOS1 version.",
bd27e851
WB
2011 optional => 1,
2012 },
2013 serial => {
2014 type => 'string',
1f30ac3a
CE
2015 pattern => '[A-Za-z0-9+\/]+={0,2}',
2016 format_description => 'Base64 encoded string',
52261945 2017 description => "Set SMBIOS1 serial number.",
bd27e851
WB
2018 optional => 1,
2019 },
2020 manufacturer => {
2021 type => 'string',
1f30ac3a
CE
2022 pattern => '[A-Za-z0-9+\/]+={0,2}',
2023 format_description => 'Base64 encoded string',
52261945 2024 description => "Set SMBIOS1 manufacturer.",
bd27e851
WB
2025 optional => 1,
2026 },
2027 product => {
2028 type => 'string',
1f30ac3a
CE
2029 pattern => '[A-Za-z0-9+\/]+={0,2}',
2030 format_description => 'Base64 encoded string',
52261945 2031 description => "Set SMBIOS1 product ID.",
bd27e851
WB
2032 optional => 1,
2033 },
2034 sku => {
2035 type => 'string',
1f30ac3a
CE
2036 pattern => '[A-Za-z0-9+\/]+={0,2}',
2037 format_description => 'Base64 encoded string',
52261945 2038 description => "Set SMBIOS1 SKU string.",
bd27e851
WB
2039 optional => 1,
2040 },
2041 family => {
2042 type => 'string',
1f30ac3a
CE
2043 pattern => '[A-Za-z0-9+\/]+={0,2}',
2044 format_description => 'Base64 encoded string',
52261945 2045 description => "Set SMBIOS1 family string.",
bd27e851
WB
2046 optional => 1,
2047 },
1f30ac3a
CE
2048 base64 => {
2049 type => 'boolean',
2050 description => 'Flag to indicate that the SMBIOS values are base64 encoded',
2051 optional => 1,
2052 },
2796e7d5
DM
2053};
2054
2796e7d5
DM
2055sub parse_smbios1 {
2056 my ($data) = @_;
2057
4df98f2f 2058 my $res = eval { parse_property_string($smbios1_fmt, $data) };
bd27e851 2059 warn $@ if $@;
2796e7d5
DM
2060 return $res;
2061}
2062
cd11416f
DM
2063sub print_smbios1 {
2064 my ($smbios1) = @_;
ff6ffe20 2065 return PVE::JSONSchema::print_property_string($smbios1, $smbios1_fmt);
cd11416f
DM
2066}
2067
ff6ffe20 2068PVE::JSONSchema::register_format('pve-qm-smbios1', $smbios1_fmt);
2796e7d5 2069
0ea9541d
DM
2070sub parse_watchdog {
2071 my ($value) = @_;
2072
d1c1af4b 2073 return if !$value;
0ea9541d 2074
4df98f2f 2075 my $res = eval { parse_property_string($watchdog_fmt, $value) };
ec3582b5 2076 warn $@ if $@;
0ea9541d
DM
2077 return $res;
2078}
2079
9d66b397 2080sub parse_guest_agent {
a2af1bbe 2081 my ($conf) = @_;
9d66b397 2082
a2af1bbe 2083 return {} if !defined($conf->{agent});
9d66b397 2084
a2af1bbe 2085 my $res = eval { parse_property_string($agent_fmt, $conf->{agent}) };
9d66b397
SI
2086 warn $@ if $@;
2087
2088 # if the agent is disabled ignore the other potentially set properties
2089 return {} if !$res->{enabled};
2090 return $res;
2091}
2092
a2af1bbe
TL
2093sub get_qga_key {
2094 my ($conf, $key) = @_;
2095 return undef if !defined($conf->{agent});
2096
2097 my $agent = parse_guest_agent($conf);
2098 return $agent->{$key};
2099}
2100
55655ebc
DC
2101sub parse_vga {
2102 my ($value) = @_;
2103
2104 return {} if !$value;
4df98f2f 2105 my $res = eval { parse_property_string($vga_fmt, $value) };
55655ebc
DC
2106 warn $@ if $@;
2107 return $res;
2108}
2109
2cf61f33
SR
2110sub parse_rng {
2111 my ($value) = @_;
2112
d1c1af4b 2113 return if !$value;
2cf61f33 2114
4df98f2f 2115 my $res = eval { parse_property_string($rng_fmt, $value) };
2cf61f33
SR
2116 warn $@ if $@;
2117 return $res;
2118}
2119
26b443c8
TL
2120sub parse_meta_info {
2121 my ($value) = @_;
2122
2123 return if !$value;
2124
2125 my $res = eval { parse_property_string($meta_info_fmt, $value) };
2126 warn $@ if $@;
2127 return $res;
2128}
2129
2130sub new_meta_info_string {
2131 my () = @_; # for now do not allow to override any value
2132
2133 return PVE::JSONSchema::print_property_string(
2134 {
af2a1a1c 2135 'creation-qemu' => kvm_user_version(),
26b443c8
TL
2136 ctime => "". int(time()),
2137 },
2138 $meta_info_fmt
2139 );
2140}
2141
cc181036
TL
2142sub qemu_created_version_fixups {
2143 my ($conf, $forcemachine, $kvmver) = @_;
2144
2145 my $meta = parse_meta_info($conf->{meta}) // {};
2146 my $forced_vers = PVE::QemuServer::Machine::extract_version($forcemachine);
2147
2148 # check if we need to apply some handling for VMs that always use the latest machine version but
2149 # had a machine version transition happen that affected HW such that, e.g., an OS config change
2150 # would be required (we do not want to pin machine version for non-windows OS type)
2151 if (
2152 (!defined($conf->{machine}) || $conf->{machine} =~ m/^(?:pc|q35|virt)$/) # non-versioned machine
2153 && (!defined($meta->{'creation-qemu'}) || !min_version($meta->{'creation-qemu'}, 6, 1)) # created before 6.1
2154 && (!$forced_vers || min_version($forced_vers, 6, 1)) # handle snapshot-rollback/migrations
2155 && min_version($kvmver, 6, 1) # only need to apply the change since 6.1
2156 ) {
2157 my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf);
2158 if ($q35 && $conf->{ostype} && $conf->{ostype} eq 'l26') {
2159 # this changed to default-on in Q 6.1 for q35 machines, it will mess with PCI slot view
2160 # and thus with the predictable interface naming of systemd
2161 return ['-global', 'ICH9-LPC.acpi-pci-hotplug-with-bridge-support=off'];
2162 }
2163 }
2164 return;
2165}
2166
1e3baf05
DM
2167# add JSON properties for create and set function
2168sub json_config_properties {
c1accf9d 2169 my ($prop, $with_disk_alloc) = @_;
1e3baf05 2170
5a08fb9c
TL
2171 my $skip_json_config_opts = {
2172 parent => 1,
2173 snaptime => 1,
2174 vmstate => 1,
2175 runningmachine => 1,
2176 runningcpu => 1,
26b443c8 2177 meta => 1,
5a08fb9c
TL
2178 };
2179
1e3baf05 2180 foreach my $opt (keys %$confdesc) {
5a08fb9c 2181 next if $skip_json_config_opts->{$opt};
c1accf9d
FE
2182
2183 if ($with_disk_alloc && is_valid_drivename($opt)) {
2184 $prop->{$opt} = $PVE::QemuServer::Drive::drivedesc_hash_with_alloc->{$opt};
2185 } else {
2186 $prop->{$opt} = $confdesc->{$opt};
2187 }
1e3baf05
DM
2188 }
2189
2190 return $prop;
2191}
2192
39051ac0
FE
2193# Properties that we can read from an OVF file
2194sub json_ovf_properties {
2195 my $prop = {};
2196
2197 for my $device (PVE::QemuServer::Drive::valid_drive_names()) {
2198 $prop->{$device} = {
2199 type => 'string',
2200 format => 'pve-volume-id-or-absolute-path',
2201 description => "Disk image that gets imported to $device",
2202 optional => 1,
2203 };
2204 }
2205
2206 $prop->{cores} = {
2207 type => 'integer',
2208 description => "The number of CPU cores.",
2209 optional => 1,
2210 };
2211 $prop->{memory} = {
2212 type => 'integer',
2213 description => "Amount of RAM for the VM in MB.",
2214 optional => 1,
2215 };
2216 $prop->{name} = {
2217 type => 'string',
2218 description => "Name of the VM.",
2219 optional => 1,
2220 };
2221
2222 return $prop;
2223}
2224
d41121fd
DM
2225# return copy of $confdesc_cloudinit to generate documentation
2226sub cloudinit_config_properties {
2227
2228 return dclone($confdesc_cloudinit);
2229}
2230
f16cf6c3
WB
2231sub cloudinit_pending_properties {
2232 my $p = {
2233 map { $_ => 1 } keys $confdesc_cloudinit->%*,
2234 name => 1,
2235 };
2236 $p->{"net$_"} = 1 for 0..($MAX_NETS-1);
2237 return $p;
2238}
2239
1e3baf05
DM
2240sub check_type {
2241 my ($key, $value) = @_;
2242
2243 die "unknown setting '$key'\n" if !$confdesc->{$key};
2244
2245 my $type = $confdesc->{$key}->{type};
2246
6b64503e 2247 if (!defined($value)) {
1e3baf05
DM
2248 die "got undefined value\n";
2249 }
2250
2251 if ($value =~ m/[\n\r]/) {
2252 die "property contains a line feed\n";
2253 }
2254
2255 if ($type eq 'boolean') {
19672434
DM
2256 return 1 if ($value eq '1') || ($value =~ m/^(on|yes|true)$/i);
2257 return 0 if ($value eq '0') || ($value =~ m/^(off|no|false)$/i);
2258 die "type check ('boolean') failed - got '$value'\n";
1e3baf05
DM
2259 } elsif ($type eq 'integer') {
2260 return int($1) if $value =~ m/^(\d+)$/;
2261 die "type check ('integer') failed - got '$value'\n";
04432191
AD
2262 } elsif ($type eq 'number') {
2263 return $value if $value =~ m/^(\d+)(\.\d+)?$/;
2264 die "type check ('number') failed - got '$value'\n";
1e3baf05
DM
2265 } elsif ($type eq 'string') {
2266 if (my $fmt = $confdesc->{$key}->{format}) {
1e3baf05 2267 PVE::JSONSchema::check_format($fmt, $value);
19672434
DM
2268 return $value;
2269 }
1e3baf05 2270 $value =~ s/^\"(.*)\"$/$1/;
19672434 2271 return $value;
1e3baf05
DM
2272 } else {
2273 die "internal error"
2274 }
2275}
2276
1e3baf05 2277sub destroy_vm {
75854662 2278 my ($storecfg, $vmid, $skiplock, $replacement_conf, $purge_unreferenced) = @_;
1e3baf05 2279
ffda963f 2280 my $conf = PVE::QemuConfig->load_config($vmid);
1e3baf05 2281
30fdf99c
SH
2282 if (!$skiplock && !PVE::QemuConfig->has_lock($conf, 'suspended')) {
2283 PVE::QemuConfig->check_lock($conf);
2284 }
1e3baf05 2285
5e67a2d2
DC
2286 if ($conf->{template}) {
2287 # check if any base image is still used by a linked clone
3ab0f925 2288 PVE::QemuConfig->foreach_volume_full($conf, { include_unused => 1 }, sub {
5e67a2d2 2289 my ($ds, $drive) = @_;
5e67a2d2
DC
2290 return if drive_is_cdrom($drive);
2291
2292 my $volid = $drive->{file};
5e67a2d2
DC
2293 return if !$volid || $volid =~ m|^/|;
2294
2295 die "base volume '$volid' is still in use by linked cloned\n"
2296 if PVE::Storage::volume_is_base_and_used($storecfg, $volid);
2297
2298 });
2299 }
2300
3e07c6d5 2301 my $volids = {};
ba1a1984 2302 my $remove_owned_drive = sub {
1e3baf05 2303 my ($ds, $drive) = @_;
9c52f5ed 2304 return if drive_is_cdrom($drive, 1);
1e3baf05
DM
2305
2306 my $volid = $drive->{file};
ff1a2432 2307 return if !$volid || $volid =~ m|^/|;
3e07c6d5 2308 return if $volids->{$volid};
1e3baf05 2309
6b64503e 2310 my ($path, $owner) = PVE::Storage::path($storecfg, $volid);
ff1a2432 2311 return if !$path || !$owner || ($owner != $vmid);
1e3baf05 2312
3e07c6d5 2313 $volids->{$volid} = 1;
a2f50f01 2314 eval { PVE::Storage::vdisk_free($storecfg, $volid) };
31b52247 2315 warn "Could not remove disk '$volid', check manually: $@" if $@;
ba1a1984
FE
2316 };
2317
2318 # only remove disks owned by this VM (referenced in the config)
2319 my $include_opts = {
2320 include_unused => 1,
2321 extra_keys => ['vmstate'],
2322 };
2323 PVE::QemuConfig->foreach_volume_full($conf, $include_opts, $remove_owned_drive);
2324
2325 for my $snap (values %{$conf->{snapshots}}) {
2326 next if !defined($snap->{vmstate});
2327 my $drive = PVE::QemuConfig->parse_volume('vmstate', $snap->{vmstate}, 1);
2328 next if !defined($drive);
2329 $remove_owned_drive->('vmstate', $drive);
2330 }
19672434 2331
3e07c6d5
FG
2332 PVE::QemuConfig->foreach_volume_full($conf->{pending}, $include_opts, $remove_owned_drive);
2333
75854662 2334 if ($purge_unreferenced) { # also remove unreferenced disk
d0ff75d9 2335 my $vmdisks = PVE::Storage::vdisk_list($storecfg, undef, $vmid, undef, 'images');
75854662
TL
2336 PVE::Storage::foreach_volid($vmdisks, sub {
2337 my ($volid, $sid, $volname, $d) = @_;
2338 eval { PVE::Storage::vdisk_free($storecfg, $volid) };
2339 warn $@ if $@;
2340 });
2341 }
dfda979e 2342
b04ea584 2343 if (defined $replacement_conf) {
8baf8bc7 2344 PVE::QemuConfig->write_config($vmid, $replacement_conf);
dfda979e
DJ
2345 } else {
2346 PVE::QemuConfig->destroy_config($vmid);
2347 }
1e3baf05
DM
2348}
2349
1e3baf05 2350sub parse_vm_config {
ad5812d8 2351 my ($filename, $raw, $strict) = @_;
1e3baf05 2352
d1c1af4b 2353 return if !defined($raw);
1e3baf05 2354
554ac7e7 2355 my $res = {
fc1ddcdc 2356 digest => Digest::SHA::sha1_hex($raw),
0d18dcfc 2357 snapshots => {},
0d732d16 2358 pending => {},
95a5135d 2359 cloudinit => {},
554ac7e7 2360 };
1e3baf05 2361
ad5812d8
FG
2362 my $handle_error = sub {
2363 my ($msg) = @_;
2364
2365 if ($strict) {
2366 die $msg;
2367 } else {
2368 warn $msg;
2369 }
2370 };
2371
19672434 2372 $filename =~ m|/qemu-server/(\d+)\.conf$|
1e3baf05
DM
2373 || die "got strange filename '$filename'";
2374
2375 my $vmid = $1;
2376
0d18dcfc 2377 my $conf = $res;
b0ec896e 2378 my $descr;
cbfc9d75
TL
2379 my $finish_description = sub {
2380 if (defined($descr)) {
2381 $descr =~ s/\s+$//;
2382 $conf->{description} = $descr;
2383 }
2384 $descr = undef;
2385 };
e297c490 2386 my $section = '';
0581fe4f 2387
0d18dcfc
DM
2388 my @lines = split(/\n/, $raw);
2389 foreach my $line (@lines) {
1e3baf05 2390 next if $line =~ m/^\s*$/;
be190583 2391
eab09f4e 2392 if ($line =~ m/^\[PENDING\]\s*$/i) {
e297c490 2393 $section = 'pending';
cbfc9d75 2394 $finish_description->();
e297c490 2395 $conf = $res->{$section} = {};
eab09f4e 2396 next;
95a5135d
AD
2397 } elsif ($line =~ m/^\[special:cloudinit\]\s*$/i) {
2398 $section = 'cloudinit';
eb9923f9 2399 $finish_description->();
95a5135d
AD
2400 $conf = $res->{$section} = {};
2401 next;
eab09f4e 2402
0d732d16 2403 } elsif ($line =~ m/^\[([a-z][a-z0-9_\-]+)\]\s*$/i) {
e297c490 2404 $section = $1;
cbfc9d75 2405 $finish_description->();
e297c490 2406 $conf = $res->{snapshots}->{$section} = {};
0d18dcfc
DM
2407 next;
2408 }
1e3baf05 2409
d1e7b922 2410 if ($line =~ m/^\#(.*)$/) {
b0ec896e 2411 $descr = '' if !defined($descr);
0581fe4f
DM
2412 $descr .= PVE::Tools::decode_text($1) . "\n";
2413 next;
2414 }
2415
1e3baf05 2416 if ($line =~ m/^(description):\s*(.*\S)\s*$/) {
b0ec896e 2417 $descr = '' if !defined($descr);
0581fe4f 2418 $descr .= PVE::Tools::decode_text($2);
0d18dcfc
DM
2419 } elsif ($line =~ m/snapstate:\s*(prepare|delete)\s*$/) {
2420 $conf->{snapstate} = $1;
1e3baf05
DM
2421 } elsif ($line =~ m/^(args):\s*(.*\S)\s*$/) {
2422 my $key = $1;
2423 my $value = $2;
0d18dcfc 2424 $conf->{$key} = $value;
ef824322 2425 } elsif ($line =~ m/^delete:\s*(.*\S)\s*$/) {
e297c490 2426 my $value = $1;
ef824322
DM
2427 if ($section eq 'pending') {
2428 $conf->{delete} = $value; # we parse this later
2429 } else {
ad5812d8 2430 $handle_error->("vm $vmid - property 'delete' is only allowed in [PENDING]\n");
eab09f4e 2431 }
15cf7698 2432 } elsif ($line =~ m/^([a-z][a-z_]*\d*):\s*(.+?)\s*$/) {
1e3baf05
DM
2433 my $key = $1;
2434 my $value = $2;
c229961a
TL
2435 if ($section eq 'cloudinit') {
2436 # ignore validation only used for informative purpose
2437 $conf->{$key} = $value;
2438 next;
2439 }
1e3baf05
DM
2440 eval { $value = check_type($key, $value); };
2441 if ($@) {
ad5812d8 2442 $handle_error->("vm $vmid - unable to parse value of '$key' - $@");
1e3baf05 2443 } else {
b799312f 2444 $key = 'ide2' if $key eq 'cdrom';
1e3baf05 2445 my $fmt = $confdesc->{$key}->{format};
b799312f 2446 if ($fmt && $fmt =~ /^pve-qm-(?:ide|scsi|virtio|sata)$/) {
1e3baf05
DM
2447 my $v = parse_drive($key, $value);
2448 if (my $volid = filename_to_volume_id($vmid, $v->{file}, $v->{media})) {
2449 $v->{file} = $volid;
71c58bb7 2450 $value = print_drive($v);
1e3baf05 2451 } else {
ad5812d8 2452 $handle_error->("vm $vmid - unable to parse value of '$key'\n");
1e3baf05
DM
2453 next;
2454 }
2455 }
2456
b799312f 2457 $conf->{$key} = $value;
1e3baf05 2458 }
f8d2a1ce 2459 } else {
ad5812d8 2460 $handle_error->("vm $vmid - unable to parse config: $line\n");
1e3baf05
DM
2461 }
2462 }
2463
cbfc9d75 2464 $finish_description->();
0d18dcfc 2465 delete $res->{snapstate}; # just to be sure
1e3baf05
DM
2466
2467 return $res;
2468}
2469
1858638f
DM
2470sub write_vm_config {
2471 my ($filename, $conf) = @_;
1e3baf05 2472
0d18dcfc
DM
2473 delete $conf->{snapstate}; # just to be sure
2474
1858638f
DM
2475 if ($conf->{cdrom}) {
2476 die "option ide2 conflicts with cdrom\n" if $conf->{ide2};
2477 $conf->{ide2} = $conf->{cdrom};
2478 delete $conf->{cdrom};
2479 }
1e3baf05
DM
2480
2481 # we do not use 'smp' any longer
1858638f
DM
2482 if ($conf->{sockets}) {
2483 delete $conf->{smp};
2484 } elsif ($conf->{smp}) {
2485 $conf->{sockets} = $conf->{smp};
2486 delete $conf->{cores};
2487 delete $conf->{smp};
1e3baf05
DM
2488 }
2489
ee2f90b1 2490 my $used_volids = {};
0d18dcfc 2491
ee2f90b1 2492 my $cleanup_config = sub {
ef824322 2493 my ($cref, $pending, $snapname) = @_;
1858638f 2494
ee2f90b1
DM
2495 foreach my $key (keys %$cref) {
2496 next if $key eq 'digest' || $key eq 'description' || $key eq 'snapshots' ||
95a5135d 2497 $key eq 'snapstate' || $key eq 'pending' || $key eq 'cloudinit';
ee2f90b1 2498 my $value = $cref->{$key};
ef824322
DM
2499 if ($key eq 'delete') {
2500 die "propertry 'delete' is only allowed in [PENDING]\n"
2501 if !$pending;
2502 # fixme: check syntax?
2503 next;
2504 }
ee2f90b1
DM
2505 eval { $value = check_type($key, $value); };
2506 die "unable to parse value of '$key' - $@" if $@;
1858638f 2507
ee2f90b1
DM
2508 $cref->{$key} = $value;
2509
74479ee9 2510 if (!$snapname && is_valid_drivename($key)) {
ed221350 2511 my $drive = parse_drive($key, $value);
ee2f90b1
DM
2512 $used_volids->{$drive->{file}} = 1 if $drive && $drive->{file};
2513 }
1e3baf05 2514 }
ee2f90b1
DM
2515 };
2516
2517 &$cleanup_config($conf);
ef824322
DM
2518
2519 &$cleanup_config($conf->{pending}, 1);
2520
ee2f90b1 2521 foreach my $snapname (keys %{$conf->{snapshots}}) {
15c6e277 2522 die "internal error: snapshot name '$snapname' is forbidden" if lc($snapname) eq 'pending';
ef824322 2523 &$cleanup_config($conf->{snapshots}->{$snapname}, undef, $snapname);
1e3baf05
DM
2524 }
2525
1858638f
DM
2526 # remove 'unusedX' settings if we re-add a volume
2527 foreach my $key (keys %$conf) {
2528 my $value = $conf->{$key};
ee2f90b1 2529 if ($key =~ m/^unused/ && $used_volids->{$value}) {
1858638f 2530 delete $conf->{$key};
1e3baf05 2531 }
1858638f 2532 }
be190583 2533
0d18dcfc 2534 my $generate_raw_config = sub {
b0ec896e 2535 my ($conf, $pending) = @_;
0581fe4f 2536
0d18dcfc
DM
2537 my $raw = '';
2538
2539 # add description as comment to top of file
b0ec896e
DM
2540 if (defined(my $descr = $conf->{description})) {
2541 if ($descr) {
2542 foreach my $cl (split(/\n/, $descr)) {
2543 $raw .= '#' . PVE::Tools::encode_text($cl) . "\n";
2544 }
2545 } else {
2546 $raw .= "#\n" if $pending;
2547 }
0d18dcfc
DM
2548 }
2549
2550 foreach my $key (sort keys %$conf) {
95a5135d 2551 next if $key =~ /^(digest|description|pending|cloudinit|snapshots)$/;
0d18dcfc
DM
2552 $raw .= "$key: $conf->{$key}\n";
2553 }
2554 return $raw;
2555 };
0581fe4f 2556
0d18dcfc 2557 my $raw = &$generate_raw_config($conf);
ef824322
DM
2558
2559 if (scalar(keys %{$conf->{pending}})){
2560 $raw .= "\n[PENDING]\n";
b0ec896e 2561 $raw .= &$generate_raw_config($conf->{pending}, 1);
ef824322
DM
2562 }
2563
1e1d6f58 2564 if (scalar(keys %{$conf->{cloudinit}}) && PVE::QemuConfig->has_cloudinit($conf)){
95a5135d
AD
2565 $raw .= "\n[special:cloudinit]\n";
2566 $raw .= &$generate_raw_config($conf->{cloudinit});
2567 }
2568
0d18dcfc
DM
2569 foreach my $snapname (sort keys %{$conf->{snapshots}}) {
2570 $raw .= "\n[$snapname]\n";
2571 $raw .= &$generate_raw_config($conf->{snapshots}->{$snapname});
1858638f 2572 }
1e3baf05 2573
1858638f
DM
2574 return $raw;
2575}
1e3baf05 2576
19672434 2577sub load_defaults {
1e3baf05
DM
2578
2579 my $res = {};
2580
2581 # we use static defaults from our JSON schema configuration
2582 foreach my $key (keys %$confdesc) {
2583 if (defined(my $default = $confdesc->{$key}->{default})) {
2584 $res->{$key} = $default;
2585 }
2586 }
19672434 2587
1e3baf05
DM
2588 return $res;
2589}
2590
2591sub config_list {
2592 my $vmlist = PVE::Cluster::get_vmlist();
2593 my $res = {};
2594 return $res if !$vmlist || !$vmlist->{ids};
2595 my $ids = $vmlist->{ids};
38277afc 2596 my $nodename = nodename();
1e3baf05 2597
1e3baf05
DM
2598 foreach my $vmid (keys %$ids) {
2599 my $d = $ids->{$vmid};
2600 next if !$d->{node} || $d->{node} ne $nodename;
5ee957cc 2601 next if !$d->{type} || $d->{type} ne 'qemu';
1e3baf05
DM
2602 $res->{$vmid}->{exists} = 1;
2603 }
2604 return $res;
2605}
2606
64e13401
DM
2607# test if VM uses local resources (to prevent migration)
2608sub check_local_resources {
2609 my ($conf, $noerr) = @_;
2610
ca6abacf 2611 my @loc_res = ();
a52eb3c4
DC
2612 my $mapped_res = [];
2613
2614 my $nodelist = PVE::Cluster::get_nodelist();
2615 my $pci_map = PVE::Mapping::PCI::config();
2616 my $usb_map = PVE::Mapping::USB::config();
2617
2618 my $missing_mappings_by_node = { map { $_ => [] } @$nodelist };
2619
2620 my $add_missing_mapping = sub {
2621 my ($type, $key, $id) = @_;
2622 for my $node (@$nodelist) {
2623 my $entry;
2624 if ($type eq 'pci') {
2625 $entry = PVE::Mapping::PCI::get_node_mapping($pci_map, $id, $node);
2626 } elsif ($type eq 'usb') {
2627 $entry = PVE::Mapping::USB::get_node_mapping($usb_map, $id, $node);
2628 }
2629 if (!scalar($entry->@*)) {
2630 push @{$missing_mappings_by_node->{$node}}, $key;
2631 }
2632 }
2633 };
19672434 2634
ca6abacf
TM
2635 push @loc_res, "hostusb" if $conf->{hostusb}; # old syntax
2636 push @loc_res, "hostpci" if $conf->{hostpci}; # old syntax
64e13401 2637
ca6abacf 2638 push @loc_res, "ivshmem" if $conf->{ivshmem};
6dbcb073 2639
0d29ab3b 2640 foreach my $k (keys %$conf) {
a52eb3c4
DC
2641 if ($k =~ m/^usb/) {
2642 my $entry = parse_property_string('pve-qm-usb', $conf->{$k});
2643 next if $entry->{host} =~ m/^spice$/i;
2644 if ($entry->{mapping}) {
2645 $add_missing_mapping->('usb', $k, $entry->{mapping});
2646 push @$mapped_res, $k;
2647 }
2648 }
2649 if ($k =~ m/^hostpci/) {
2650 my $entry = parse_property_string('pve-qm-hostpci', $conf->{$k});
2651 if ($entry->{mapping}) {
2652 $add_missing_mapping->('pci', $k, $entry->{mapping});
2653 push @$mapped_res, $k;
2654 }
2655 }
d44712fc
EK
2656 # sockets are safe: they will recreated be on the target side post-migrate
2657 next if $k =~ m/^serial/ && ($conf->{$k} eq 'socket');
ca6abacf 2658 push @loc_res, $k if $k =~ m/^(usb|hostpci|serial|parallel)\d+$/;
64e13401
DM
2659 }
2660
ca6abacf 2661 die "VM uses local resources\n" if scalar @loc_res && !$noerr;
64e13401 2662
a52eb3c4 2663 return wantarray ? (\@loc_res, $mapped_res, $missing_mappings_by_node) : \@loc_res;
64e13401
DM
2664}
2665
719893a9 2666# check if used storages are available on all nodes (use by migrate)
47152e2e
DM
2667sub check_storage_availability {
2668 my ($storecfg, $conf, $node) = @_;
2669
912792e2 2670 PVE::QemuConfig->foreach_volume($conf, sub {
47152e2e
DM
2671 my ($ds, $drive) = @_;
2672
2673 my $volid = $drive->{file};
2674 return if !$volid;
2675
2676 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
2677 return if !$sid;
2678
2679 # check if storage is available on both nodes
0d2db084
FE
2680 my $scfg = PVE::Storage::storage_check_enabled($storecfg, $sid);
2681 PVE::Storage::storage_check_enabled($storecfg, $sid, $node);
24b84b47 2682
3148f0b0
TL
2683 my ($vtype) = PVE::Storage::parse_volname($storecfg, $volid);
2684
2685 die "$volid: content type '$vtype' is not available on storage '$sid'\n"
2686 if !$scfg->{content}->{$vtype};
47152e2e
DM
2687 });
2688}
2689
719893a9
DM
2690# list nodes where all VM images are available (used by has_feature API)
2691sub shared_nodes {
2692 my ($conf, $storecfg) = @_;
2693
2694 my $nodelist = PVE::Cluster::get_nodelist();
2695 my $nodehash = { map { $_ => 1 } @$nodelist };
38277afc 2696 my $nodename = nodename();
be190583 2697
912792e2 2698 PVE::QemuConfig->foreach_volume($conf, sub {
719893a9
DM
2699 my ($ds, $drive) = @_;
2700
2701 my $volid = $drive->{file};
2702 return if !$volid;
2703
2704 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
2705 if ($storeid) {
2706 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
2707 if ($scfg->{disable}) {
2708 $nodehash = {};
2709 } elsif (my $avail = $scfg->{nodes}) {
2710 foreach my $node (keys %$nodehash) {
2711 delete $nodehash->{$node} if !$avail->{$node};
2712 }
2713 } elsif (!$scfg->{shared}) {
2714 foreach my $node (keys %$nodehash) {
2715 delete $nodehash->{$node} if $node ne $nodename
2716 }
2717 }
2718 }
2719 });
2720
2721 return $nodehash
2722}
2723
f25852c2
TM
2724sub check_local_storage_availability {
2725 my ($conf, $storecfg) = @_;
2726
2727 my $nodelist = PVE::Cluster::get_nodelist();
2728 my $nodehash = { map { $_ => {} } @$nodelist };
2729
912792e2 2730 PVE::QemuConfig->foreach_volume($conf, sub {
f25852c2
TM
2731 my ($ds, $drive) = @_;
2732
2733 my $volid = $drive->{file};
2734 return if !$volid;
2735
2736 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
2737 if ($storeid) {
2738 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
2739
2740 if ($scfg->{disable}) {
2741 foreach my $node (keys %$nodehash) {
32075a2c 2742 $nodehash->{$node}->{unavailable_storages}->{$storeid} = 1;
f25852c2
TM
2743 }
2744 } elsif (my $avail = $scfg->{nodes}) {
2745 foreach my $node (keys %$nodehash) {
2746 if (!$avail->{$node}) {
32075a2c 2747 $nodehash->{$node}->{unavailable_storages}->{$storeid} = 1;
f25852c2
TM
2748 }
2749 }
2750 }
2751 }
2752 });
2753
32075a2c
TL
2754 foreach my $node (values %$nodehash) {
2755 if (my $unavail = $node->{unavailable_storages}) {
2756 $node->{unavailable_storages} = [ sort keys %$unavail ];
2757 }
2758 }
2759
f25852c2
TM
2760 return $nodehash
2761}
2762
babf613a 2763# Compat only, use assert_config_exists_on_node and vm_running_locally where possible
1e3baf05 2764sub check_running {
7e8dcf2c 2765 my ($vmid, $nocheck, $node) = @_;
1e3baf05 2766
a20dc58a
FG
2767 # $nocheck is set when called during a migration, in which case the config
2768 # file might still or already reside on the *other* node
2769 # - because rename has already happened, and current node is source
2770 # - because rename hasn't happened yet, and current node is target
2771 # - because rename has happened, current node is target, but hasn't yet
2772 # processed it yet
babf613a
SR
2773 PVE::QemuConfig::assert_config_exists_on_node($vmid, $node) if !$nocheck;
2774 return PVE::QemuServer::Helpers::vm_running_locally($vmid);
1e3baf05
DM
2775}
2776
2777sub vzlist {
19672434 2778
1e3baf05
DM
2779 my $vzlist = config_list();
2780
d036e418 2781 my $fd = IO::Dir->new($PVE::QemuServer::Helpers::var_run_tmpdir) || return $vzlist;
1e3baf05 2782
19672434 2783 while (defined(my $de = $fd->read)) {
1e3baf05
DM
2784 next if $de !~ m/^(\d+)\.pid$/;
2785 my $vmid = $1;
6b64503e
DM
2786 next if !defined($vzlist->{$vmid});
2787 if (my $pid = check_running($vmid)) {
1e3baf05
DM
2788 $vzlist->{$vmid}->{pid} = $pid;
2789 }
2790 }
2791
2792 return $vzlist;
2793}
2794
b1a70cab
DM
2795our $vmstatus_return_properties = {
2796 vmid => get_standard_option('pve-vmid'),
2797 status => {
7bd9abd2 2798 description => "QEMU process status.",
b1a70cab
DM
2799 type => 'string',
2800 enum => ['stopped', 'running'],
2801 },
2802 maxmem => {
2803 description => "Maximum memory in bytes.",
2804 type => 'integer',
2805 optional => 1,
2806 renderer => 'bytes',
2807 },
2808 maxdisk => {
2809 description => "Root disk size in bytes.",
2810 type => 'integer',
2811 optional => 1,
2812 renderer => 'bytes',
2813 },
2814 name => {
2815 description => "VM name.",
2816 type => 'string',
2817 optional => 1,
2818 },
2819 qmpstatus => {
58542139 2820 description => "VM run state from the 'query-status' QMP monitor command.",
b1a70cab
DM
2821 type => 'string',
2822 optional => 1,
2823 },
2824 pid => {
2825 description => "PID of running qemu process.",
2826 type => 'integer',
2827 optional => 1,
2828 },
2829 uptime => {
2830 description => "Uptime.",
2831 type => 'integer',
2832 optional => 1,
2833 renderer => 'duration',
2834 },
2835 cpus => {
2836 description => "Maximum usable CPUs.",
2837 type => 'number',
2838 optional => 1,
2839 },
e6ed61b4 2840 lock => {
11efdfa5 2841 description => "The current config lock, if any.",
e6ed61b4
DC
2842 type => 'string',
2843 optional => 1,
b8e7068a
DC
2844 },
2845 tags => {
2846 description => "The current configured tags, if any",
2847 type => 'string',
2848 optional => 1,
2849 },
949112c3
FE
2850 'running-machine' => {
2851 description => "The currently running machine type (if running).",
2852 type => 'string',
2853 optional => 1,
2854 },
2855 'running-qemu' => {
2856 description => "The currently running QEMU version (if running).",
2857 type => 'string',
2858 optional => 1,
2859 },
b1a70cab
DM
2860};
2861
1e3baf05
DM
2862my $last_proc_pid_stat;
2863
03a33f30
DM
2864# get VM status information
2865# This must be fast and should not block ($full == false)
2866# We only query KVM using QMP if $full == true (this can be slow)
1e3baf05 2867sub vmstatus {
03a33f30 2868 my ($opt_vmid, $full) = @_;
1e3baf05
DM
2869
2870 my $res = {};
2871
19672434 2872 my $storecfg = PVE::Storage::config();
1e3baf05
DM
2873
2874 my $list = vzlist();
3618ee99
EK
2875 my $defaults = load_defaults();
2876
694fcad4 2877 my ($uptime) = PVE::ProcFSTools::read_proc_uptime(1);
1e3baf05 2878
ae4915a2
DM
2879 my $cpucount = $cpuinfo->{cpus} || 1;
2880
1e3baf05
DM
2881 foreach my $vmid (keys %$list) {
2882 next if $opt_vmid && ($vmid ne $opt_vmid);
2883
9f78b695 2884 my $conf = PVE::QemuConfig->load_config($vmid);
1e3baf05 2885
ad2cad72 2886 my $d = { vmid => int($vmid) };
8a0addab 2887 $d->{pid} = int($list->{$vmid}->{pid}) if $list->{$vmid}->{pid};
1e3baf05
DM
2888
2889 # fixme: better status?
2890 $d->{status} = $list->{$vmid}->{pid} ? 'running' : 'stopped';
2891
776c5f50 2892 my $size = PVE::QemuServer::Drive::bootdisk_size($storecfg, $conf);
af990afe
DM
2893 if (defined($size)) {
2894 $d->{disk} = 0; # no info available
1e3baf05
DM
2895 $d->{maxdisk} = $size;
2896 } else {
2897 $d->{disk} = 0;
2898 $d->{maxdisk} = 0;
2899 }
2900
3618ee99
EK
2901 $d->{cpus} = ($conf->{sockets} || $defaults->{sockets})
2902 * ($conf->{cores} || $defaults->{cores});
ae4915a2 2903 $d->{cpus} = $cpucount if $d->{cpus} > $cpucount;
d7c8364b 2904 $d->{cpus} = $conf->{vcpus} if $conf->{vcpus};
ae4915a2 2905
1e3baf05 2906 $d->{name} = $conf->{name} || "VM $vmid";
7f8c8087 2907 $d->{maxmem} = get_current_memory($conf->{memory})*(1024*1024);
1e3baf05 2908
8b1accf7 2909 if ($conf->{balloon}) {
4bdb0514 2910 $d->{balloon_min} = $conf->{balloon}*(1024*1024);
3618ee99
EK
2911 $d->{shares} = defined($conf->{shares}) ? $conf->{shares}
2912 : $defaults->{shares};
8b1accf7
DM
2913 }
2914
1e3baf05
DM
2915 $d->{uptime} = 0;
2916 $d->{cpu} = 0;
1e3baf05
DM
2917 $d->{mem} = 0;
2918
2919 $d->{netout} = 0;
2920 $d->{netin} = 0;
2921
2922 $d->{diskread} = 0;
2923 $d->{diskwrite} = 0;
2924
75a2a423 2925 $d->{template} = 1 if PVE::QemuConfig->is_template($conf);
4d8c851b 2926
8107b378 2927 $d->{serial} = 1 if conf_has_serial($conf);
e6ed61b4 2928 $d->{lock} = $conf->{lock} if $conf->{lock};
b8e7068a 2929 $d->{tags} = $conf->{tags} if defined($conf->{tags});
8107b378 2930
1e3baf05
DM
2931 $res->{$vmid} = $d;
2932 }
2933
2934 my $netdev = PVE::ProcFSTools::read_proc_net_dev();
2935 foreach my $dev (keys %$netdev) {
2936 next if $dev !~ m/^tap([1-9]\d*)i/;
2937 my $vmid = $1;
2938 my $d = $res->{$vmid};
2939 next if !$d;
19672434 2940
1e3baf05
DM
2941 $d->{netout} += $netdev->{$dev}->{receive};
2942 $d->{netin} += $netdev->{$dev}->{transmit};
604ea644
AD
2943
2944 if ($full) {
ad2cad72
FE
2945 $d->{nics}->{$dev}->{netout} = int($netdev->{$dev}->{receive});
2946 $d->{nics}->{$dev}->{netin} = int($netdev->{$dev}->{transmit});
604ea644
AD
2947 }
2948
1e3baf05
DM
2949 }
2950
1e3baf05
DM
2951 my $ctime = gettimeofday;
2952
2953 foreach my $vmid (keys %$list) {
2954
2955 my $d = $res->{$vmid};
2956 my $pid = $d->{pid};
2957 next if !$pid;
2958
694fcad4
DM
2959 my $pstat = PVE::ProcFSTools::read_proc_pid_stat($pid);
2960 next if !$pstat; # not running
19672434 2961
694fcad4 2962 my $used = $pstat->{utime} + $pstat->{stime};
1e3baf05 2963
694fcad4 2964 $d->{uptime} = int(($uptime - $pstat->{starttime})/$cpuinfo->{user_hz});
1e3baf05 2965
694fcad4 2966 if ($pstat->{vsize}) {
6b64503e 2967 $d->{mem} = int(($pstat->{rss}/$pstat->{vsize})*$d->{maxmem});
1e3baf05
DM
2968 }
2969
2970 my $old = $last_proc_pid_stat->{$pid};
2971 if (!$old) {
19672434
DM
2972 $last_proc_pid_stat->{$pid} = {
2973 time => $ctime,
1e3baf05
DM
2974 used => $used,
2975 cpu => 0,
1e3baf05
DM
2976 };
2977 next;
2978 }
2979
7f0b5beb 2980 my $dtime = ($ctime - $old->{time}) * $cpucount * $cpuinfo->{user_hz};
1e3baf05
DM
2981
2982 if ($dtime > 1000) {
2983 my $dutime = $used - $old->{used};
2984
ae4915a2 2985 $d->{cpu} = (($dutime/$dtime)* $cpucount) / $d->{cpus};
1e3baf05 2986 $last_proc_pid_stat->{$pid} = {
19672434 2987 time => $ctime,
1e3baf05
DM
2988 used => $used,
2989 cpu => $d->{cpu},
1e3baf05
DM
2990 };
2991 } else {
2992 $d->{cpu} = $old->{cpu};
1e3baf05
DM
2993 }
2994 }
2995
f5eb281a 2996 return $res if !$full;
03a33f30
DM
2997
2998 my $qmpclient = PVE::QMPClient->new();
2999
64e7fcf2
DM
3000 my $ballooncb = sub {
3001 my ($vmid, $resp) = @_;
3002
3003 my $info = $resp->{'return'};
38babf81
DM
3004 return if !$info->{max_mem};
3005
64e7fcf2
DM
3006 my $d = $res->{$vmid};
3007
38babf81
DM
3008 # use memory assigned to VM
3009 $d->{maxmem} = $info->{max_mem};
3010 $d->{balloon} = $info->{actual};
3011
3012 if (defined($info->{total_mem}) && defined($info->{free_mem})) {
3013 $d->{mem} = $info->{total_mem} - $info->{free_mem};
3014 $d->{freemem} = $info->{free_mem};
64e7fcf2
DM
3015 }
3016
604ea644 3017 $d->{ballooninfo} = $info;
64e7fcf2
DM
3018 };
3019
03a33f30
DM
3020 my $blockstatscb = sub {
3021 my ($vmid, $resp) = @_;
3022 my $data = $resp->{'return'} || [];
3023 my $totalrdbytes = 0;
3024 my $totalwrbytes = 0;
604ea644 3025
03a33f30
DM
3026 for my $blockstat (@$data) {
3027 $totalrdbytes = $totalrdbytes + $blockstat->{stats}->{rd_bytes};
3028 $totalwrbytes = $totalwrbytes + $blockstat->{stats}->{wr_bytes};
604ea644
AD
3029
3030 $blockstat->{device} =~ s/drive-//;
3031 $res->{$vmid}->{blockstat}->{$blockstat->{device}} = $blockstat->{stats};
03a33f30
DM
3032 }
3033 $res->{$vmid}->{diskread} = $totalrdbytes;
3034 $res->{$vmid}->{diskwrite} = $totalwrbytes;
3035 };
3036
949112c3
FE
3037 my $machinecb = sub {
3038 my ($vmid, $resp) = @_;
3039 my $data = $resp->{'return'} || [];
3040
3041 $res->{$vmid}->{'running-machine'} =
3042 PVE::QemuServer::Machine::current_from_query_machines($data);
3043 };
3044
3045 my $versioncb = sub {
3046 my ($vmid, $resp) = @_;
3047 my $data = $resp->{'return'} // {};
3048 my $version = 'unknown';
3049
3050 if (my $v = $data->{qemu}) {
3051 $version = $v->{major} . "." . $v->{minor} . "." . $v->{micro};
3052 }
3053
3054 $res->{$vmid}->{'running-qemu'} = $version;
3055 };
3056
03a33f30
DM
3057 my $statuscb = sub {
3058 my ($vmid, $resp) = @_;
64e7fcf2 3059
03a33f30 3060 $qmpclient->queue_cmd($vmid, $blockstatscb, 'query-blockstats');
949112c3
FE
3061 $qmpclient->queue_cmd($vmid, $machinecb, 'query-machines');
3062 $qmpclient->queue_cmd($vmid, $versioncb, 'query-version');
64e7fcf2
DM
3063 # this fails if ballon driver is not loaded, so this must be
3064 # the last commnand (following command are aborted if this fails).
38babf81 3065 $qmpclient->queue_cmd($vmid, $ballooncb, 'query-balloon');
03a33f30
DM
3066
3067 my $status = 'unknown';
3068 if (!defined($status = $resp->{'return'}->{status})) {
3069 warn "unable to get VM status\n";
3070 return;
3071 }
3072
3073 $res->{$vmid}->{qmpstatus} = $resp->{'return'}->{status};
3074 };
3075
3076 foreach my $vmid (keys %$list) {
3077 next if $opt_vmid && ($vmid ne $opt_vmid);
3078 next if !$res->{$vmid}->{pid}; # not running
3079 $qmpclient->queue_cmd($vmid, $statuscb, 'query-status');
3080 }
3081
b017fbda 3082 $qmpclient->queue_execute(undef, 2);
03a33f30 3083
6891fd70
SR
3084 foreach my $vmid (keys %$list) {
3085 next if $opt_vmid && ($vmid ne $opt_vmid);
e5b18771
FG
3086 next if !$res->{$vmid}->{pid}; #not running
3087
6891fd70
SR
3088 # we can't use the $qmpclient since it might have already aborted on
3089 # 'query-balloon', but this might also fail for older versions...
3090 my $qemu_support = eval { mon_cmd($vmid, "query-proxmox-support") };
3091 $res->{$vmid}->{'proxmox-support'} = $qemu_support // {};
3092 }
3093
03a33f30
DM
3094 foreach my $vmid (keys %$list) {
3095 next if $opt_vmid && ($vmid ne $opt_vmid);
3096 $res->{$vmid}->{qmpstatus} = $res->{$vmid}->{status} if !$res->{$vmid}->{qmpstatus};
3097 }
3098
1e3baf05
DM
3099 return $res;
3100}
3101
8107b378
DC
3102sub conf_has_serial {
3103 my ($conf) = @_;
3104
3105 for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) {
3106 if ($conf->{"serial$i"}) {
3107 return 1;
3108 }
3109 }
3110
3111 return 0;
3112}
3113
d5535a00
TL
3114sub conf_has_audio {
3115 my ($conf, $id) = @_;
3116
3117 $id //= 0;
3118 my $audio = $conf->{"audio$id"};
d1c1af4b 3119 return if !defined($audio);
d5535a00 3120
4df98f2f 3121 my $audioproperties = parse_property_string($audio_fmt, $audio);
d5535a00
TL
3122 my $audiodriver = $audioproperties->{driver} // 'spice';
3123
3124 return {
3125 dev => $audioproperties->{device},
b0f96836 3126 dev_id => "audiodev$id",
d5535a00
TL
3127 backend => $audiodriver,
3128 backend_id => "$audiodriver-backend${id}",
3129 };
3130}
3131
b01de199 3132sub audio_devs {
1cc5ed1b 3133 my ($audio, $audiopciaddr, $machine_version) = @_;
b01de199
TL
3134
3135 my $devs = [];
3136
3137 my $id = $audio->{dev_id};
1cc5ed1b
AL
3138 my $audiodev = "";
3139 if (min_version($machine_version, 4, 2)) {
3140 $audiodev = ",audiodev=$audio->{backend_id}";
3141 }
b01de199
TL
3142
3143 if ($audio->{dev} eq 'AC97') {
1cc5ed1b 3144 push @$devs, '-device', "AC97,id=${id}${audiopciaddr}$audiodev";
b01de199
TL
3145 } elsif ($audio->{dev} =~ /intel\-hda$/) {
3146 push @$devs, '-device', "$audio->{dev},id=${id}${audiopciaddr}";
1cc5ed1b
AL
3147 push @$devs, '-device', "hda-micro,id=${id}-codec0,bus=${id}.0,cad=0$audiodev";
3148 push @$devs, '-device', "hda-duplex,id=${id}-codec1,bus=${id}.0,cad=1$audiodev";
b01de199
TL
3149 } else {
3150 die "unkown audio device '$audio->{dev}', implement me!";
3151 }
3152
3153 push @$devs, '-audiodev', "$audio->{backend},id=$audio->{backend_id}";
3154
3155 return $devs;
3156}
3157
f9dde219
SR
3158sub get_tpm_paths {
3159 my ($vmid) = @_;
3160 return {
3161 socket => "/var/run/qemu-server/$vmid.swtpm",
3162 pid => "/var/run/qemu-server/$vmid.swtpm.pid",
3163 };
3164}
3165
3166sub add_tpm_device {
3167 my ($vmid, $devices, $conf) = @_;
3168
3169 return if !$conf->{tpmstate0};
3170
3171 my $paths = get_tpm_paths($vmid);
3172
3173 push @$devices, "-chardev", "socket,id=tpmchar,path=$paths->{socket}";
3174 push @$devices, "-tpmdev", "emulator,id=tpmdev,chardev=tpmchar";
3175 push @$devices, "-device", "tpm-tis,tpmdev=tpmdev";
3176}
3177
3178sub start_swtpm {
3179 my ($storecfg, $vmid, $tpmdrive, $migration) = @_;
3180
3181 return if !$tpmdrive;
3182
3183 my $state;
3184 my $tpm = parse_drive("tpmstate0", $tpmdrive);
3185 my ($storeid, $volname) = PVE::Storage::parse_volume_id($tpm->{file}, 1);
3186 if ($storeid) {
3187 $state = PVE::Storage::map_volume($storecfg, $tpm->{file});
3188 } else {
3189 $state = $tpm->{file};
3190 }
3191
3192 my $paths = get_tpm_paths($vmid);
3193
3194 # during migration, we will get state from remote
3195 #
3196 if (!$migration) {
3197 # run swtpm_setup to create a new TPM state if it doesn't exist yet
3198 my $setup_cmd = [
3199 "swtpm_setup",
3200 "--tpmstate",
3201 "file://$state",
3202 "--createek",
3203 "--create-ek-cert",
3204 "--create-platform-cert",
3205 "--lock-nvram",
3206 "--config",
3207 "/etc/swtpm_setup.conf", # do not use XDG configs
3208 "--runas",
3209 "0", # force creation as root, error if not possible
3210 "--not-overwrite", # ignore existing state, do not modify
3211 ];
3212
3213 push @$setup_cmd, "--tpm2" if $tpm->{version} eq 'v2.0';
3214 # TPM 2.0 supports ECC crypto, use if possible
3215 push @$setup_cmd, "--ecc" if $tpm->{version} eq 'v2.0';
3216
3217 run_command($setup_cmd, outfunc => sub {
3218 print "swtpm_setup: $1\n";
3219 });
3220 }
3221
72a5a176
FE
3222 # Used to distinguish different invocations in the log.
3223 my $log_prefix = "[id=" . int(time()) . "] ";
3224
f9dde219
SR
3225 my $emulator_cmd = [
3226 "swtpm",
3227 "socket",
3228 "--tpmstate",
3229 "backend-uri=file://$state,mode=0600",
3230 "--ctrl",
3231 "type=unixio,path=$paths->{socket},mode=0600",
3232 "--pid",
3233 "file=$paths->{pid}",
3234 "--terminate", # terminate on QEMU disconnect
3235 "--daemon",
b2e9c4d3 3236 "--log",
72a5a176 3237 "file=/run/qemu-server/$vmid-swtpm.log,level=1,prefix=$log_prefix",
f9dde219
SR
3238 ];
3239 push @$emulator_cmd, "--tpm2" if $tpm->{version} eq 'v2.0';
3240 run_command($emulator_cmd, outfunc => sub { print $1; });
3241
6bbcd71f 3242 my $tries = 100; # swtpm may take a bit to start before daemonizing, wait up to 5s for pid
f85951dc 3243 while (! -e $paths->{pid}) {
90c41bac 3244 die "failed to start swtpm: pid file '$paths->{pid}' wasn't created.\n" if --$tries == 0;
6bbcd71f 3245 usleep(50_000);
f85951dc
SR
3246 }
3247
f9dde219
SR
3248 # return untainted PID of swtpm daemon so it can be killed on error
3249 file_read_firstline($paths->{pid}) =~ m/(\d+)/;
3250 return $1;
3251}
3252
86b8228b
DM
3253sub vga_conf_has_spice {
3254 my ($vga) = @_;
3255
55655ebc
DC
3256 my $vgaconf = parse_vga($vga);
3257 my $vgatype = $vgaconf->{type};
3258 return 0 if !$vgatype || $vgatype !~ m/^qxl([234])?$/;
590e698c
DM
3259
3260 return $1 || 1;
86b8228b
DM
3261}
3262
d731ecbe
WB
3263sub is_native($) {
3264 my ($arch) = @_;
3265 return get_host_arch() eq $arch;
3266}
3267
045749f2
TL
3268sub get_vm_arch {
3269 my ($conf) = @_;
3270 return $conf->{arch} // get_host_arch();
3271}
3272
d731ecbe
WB
3273my $default_machines = {
3274 x86_64 => 'pc',
3275 aarch64 => 'virt',
3276};
3277
0761e619
TL
3278sub get_installed_machine_version {
3279 my ($kvmversion) = @_;
3280 $kvmversion = kvm_user_version() if !defined($kvmversion);
3281 $kvmversion =~ m/^(\d+\.\d+)/;
3282 return $1;
3283}
3284
3285sub windows_get_pinned_machine_version {
3286 my ($machine, $base_version, $kvmversion) = @_;
3287
3288 my $pin_version = $base_version;
3289 if (!defined($base_version) ||
3290 !PVE::QemuServer::Machine::can_run_pve_machine_version($base_version, $kvmversion)
3291 ) {
3292 $pin_version = get_installed_machine_version($kvmversion);
3293 }
3294 if (!$machine || $machine eq 'pc') {
3295 $machine = "pc-i440fx-$pin_version";
3296 } elsif ($machine eq 'q35') {
3297 $machine = "pc-q35-$pin_version";
3298 } elsif ($machine eq 'virt') {
3299 $machine = "virt-$pin_version";
3300 } else {
3301 warn "unknown machine type '$machine', not touching that!\n";
3302 }
3303
3304 return $machine;
3305}
3306
045749f2 3307sub get_vm_machine {
ac0077cc 3308 my ($conf, $forcemachine, $arch, $add_pve_version, $kvmversion) = @_;
045749f2
TL
3309
3310 my $machine = $forcemachine || $conf->{machine};
d731ecbe 3311
9471e48b 3312 if (!$machine || $machine =~ m/^(?:pc|q35|virt)$/) {
4dd1e83c
TL
3313 $kvmversion //= kvm_user_version();
3314 # we must pin Windows VMs without a specific version to 5.1, as 5.2 fixed a bug in ACPI
3315 # layout which confuses windows quite a bit and may result in various regressions..
3316 # see: https://lists.gnu.org/archive/html/qemu-devel/2021-02/msg08484.html
3317 if (windows_version($conf->{ostype})) {
0761e619 3318 $machine = windows_get_pinned_machine_version($machine, '5.1', $kvmversion);
4dd1e83c 3319 }
045749f2
TL
3320 $arch //= 'x86_64';
3321 $machine ||= $default_machines->{$arch};
ac0077cc 3322 if ($add_pve_version) {
ac0077cc
SR
3323 my $pvever = PVE::QemuServer::Machine::get_pve_version($kvmversion);
3324 $machine .= "+pve$pvever";
3325 }
3326 }
3327
d4be7f31
SR
3328 if ($add_pve_version && $machine !~ m/\+pve\d+?(?:\.pxe)?$/) {
3329 my $is_pxe = $machine =~ m/^(.*?)\.pxe$/;
3330 $machine = $1 if $is_pxe;
3331
ac0077cc
SR
3332 # for version-pinned machines that do not include a pve-version (e.g.
3333 # pc-q35-4.1), we assume 0 to keep them stable in case we bump
3334 $machine .= '+pve0';
d4be7f31
SR
3335
3336 $machine .= '.pxe' if $is_pxe;
045749f2
TL
3337 }
3338
3339 return $machine;
d731ecbe
WB
3340}
3341
90b20b15
DC
3342sub get_ovmf_files($$$) {
3343 my ($arch, $efidisk, $smm) = @_;
96ed3574 3344
b5099b4f 3345 my $types = $OVMF->{$arch}
96ed3574
WB
3346 or die "no OVMF images known for architecture '$arch'\n";
3347
b5099b4f 3348 my $type = 'default';
c351659d
TL
3349 if ($arch eq 'x86_64') {
3350 if (defined($efidisk->{efitype}) && $efidisk->{efitype} eq '4m') {
3351 $type = $smm ? "4m" : "4m-no-smm";
3352 $type .= '-ms' if $efidisk->{'pre-enrolled-keys'};
3353 } else {
3354 # TODO: log_warn about use of legacy images for x86_64 with Promxox VE 9
3355 }
b5099b4f
SR
3356 }
3357
f78c9b6b
NU
3358 my ($ovmf_code, $ovmf_vars) = $types->{$type}->@*;
3359 die "EFI base image '$ovmf_code' not found\n" if ! -f $ovmf_code;
3360 die "EFI vars image '$ovmf_vars' not found\n" if ! -f $ovmf_vars;
3361
3362 return ($ovmf_code, $ovmf_vars);
96ed3574
WB
3363}
3364
6908fd9b
WB
3365my $Arch2Qemu = {
3366 aarch64 => '/usr/bin/qemu-system-aarch64',
3367 x86_64 => '/usr/bin/qemu-system-x86_64',
3368};
3369sub get_command_for_arch($) {
3370 my ($arch) = @_;
3371 return '/usr/bin/kvm' if is_native($arch);
3372
3373 my $cmd = $Arch2Qemu->{$arch}
3374 or die "don't know how to emulate architecture '$arch'\n";
3375 return $cmd;
3376}
3377
05a4c550
SR
3378# To use query_supported_cpu_flags and query_understood_cpu_flags to get flags
3379# to use in a QEMU command line (-cpu element), first array_intersect the result
3380# of query_supported_ with query_understood_. This is necessary because:
3381#
3382# a) query_understood_ returns flags the host cannot use and
3383# b) query_supported_ (rather the QMP call) doesn't actually return CPU
3384# flags, but CPU settings - with most of them being flags. Those settings
3385# (and some flags, curiously) cannot be specified as a "-cpu" argument.
3386#
3387# query_supported_ needs to start up to 2 temporary VMs and is therefore rather
3388# expensive. If you need the value returned from this, you can get it much
3389# cheaper from pmxcfs using PVE::Cluster::get_node_kv('cpuflags-$accel') with
3390# $accel being 'kvm' or 'tcg'.
3391#
3392# pvestatd calls this function on startup and whenever the QEMU/KVM version
3393# changes, automatically populating pmxcfs.
3394#
3395# Returns: { kvm => [ flagX, flagY, ... ], tcg => [ flag1, flag2, ... ] }
3396# since kvm and tcg machines support different flags
3397#
3398sub query_supported_cpu_flags {
52cffab6 3399 my ($arch) = @_;
05a4c550 3400
52cffab6
SR
3401 $arch //= get_host_arch();
3402 my $default_machine = $default_machines->{$arch};
3403
3404 my $flags = {};
05a4c550
SR
3405
3406 # FIXME: Once this is merged, the code below should work for ARM as well:
3407 # https://lists.nongnu.org/archive/html/qemu-devel/2019-06/msg04947.html
3408 die "QEMU/KVM cannot detect CPU flags on ARM (aarch64)\n" if
3409 $arch eq "aarch64";
3410
3411 my $kvm_supported = defined(kvm_version());
3412 my $qemu_cmd = get_command_for_arch($arch);
3413 my $fakevmid = -1;
3414 my $pidfile = PVE::QemuServer::Helpers::pidfile_name($fakevmid);
3415
3416 # Start a temporary (frozen) VM with vmid -1 to allow sending a QMP command
3417 my $query_supported_run_qemu = sub {
3418 my ($kvm) = @_;
3419
3420 my $flags = {};
3421 my $cmd = [
3422 $qemu_cmd,
3423 '-machine', $default_machine,
3424 '-display', 'none',
378ad769 3425 '-chardev', "socket,id=qmp,path=/var/run/qemu-server/$fakevmid.qmp,server=on,wait=off",
05a4c550
SR
3426 '-mon', 'chardev=qmp,mode=control',
3427 '-pidfile', $pidfile,
3428 '-S', '-daemonize'
3429 ];
3430
3431 if (!$kvm) {
3432 push @$cmd, '-accel', 'tcg';
3433 }
3434
3435 my $rc = run_command($cmd, noerr => 1, quiet => 0);
3436 die "QEMU flag querying VM exited with code " . $rc if $rc;
3437
3438 eval {
3439 my $cmd_result = mon_cmd(
3440 $fakevmid,
3441 'query-cpu-model-expansion',
3442 type => 'full',
3443 model => { name => 'host' }
3444 );
3445
3446 my $props = $cmd_result->{model}->{props};
3447 foreach my $prop (keys %$props) {
3448 next if $props->{$prop} ne '1';
3449 # QEMU returns some flags multiple times, with '_', '.' or '-'
3450 # (e.g. lahf_lm and lahf-lm; sse4.2, sse4-2 and sse4_2; ...).
3451 # We only keep those with underscores, to match /proc/cpuinfo
3452 $prop =~ s/\.|-/_/g;
3453 $flags->{$prop} = 1;
3454 }
3455 };
3456 my $err = $@;
3457
6bbcd71f 3458 # force stop with 10 sec timeout and 'nocheck', always stop, even if QMP failed
05a4c550
SR
3459 vm_stop(undef, $fakevmid, 1, 1, 10, 0, 1);
3460
3461 die $err if $err;
3462
3463 return [ sort keys %$flags ];
3464 };
3465
3466 # We need to query QEMU twice, since KVM and TCG have different supported flags
3467 PVE::QemuConfig->lock_config($fakevmid, sub {
3468 $flags->{tcg} = eval { $query_supported_run_qemu->(0) };
3469 warn "warning: failed querying supported tcg flags: $@\n" if $@;
3470
3471 if ($kvm_supported) {
3472 $flags->{kvm} = eval { $query_supported_run_qemu->(1) };
3473 warn "warning: failed querying supported kvm flags: $@\n" if $@;
3474 }
3475 });
3476
3477 return $flags;
3478}
3479
3480# Understood CPU flags are written to a file at 'pve-qemu' compile time
3481my $understood_cpu_flag_dir = "/usr/share/kvm";
3482sub query_understood_cpu_flags {
3483 my $arch = get_host_arch();
3484 my $filepath = "$understood_cpu_flag_dir/recognized-CPUID-flags-$arch";
3485
3486 die "Cannot query understood QEMU CPU flags for architecture: $arch (file not found)\n"
3487 if ! -e $filepath;
3488
3489 my $raw = file_get_contents($filepath);
3490 $raw =~ s/^\s+|\s+$//g;
3491 my @flags = split(/\s+/, $raw);
3492
3493 return \@flags;
3494}
3495
e5a6919c
FE
3496# Since commit 277d33454f77ec1d1e0bc04e37621e4dd2424b67 in pve-qemu, smm is not off by default
3497# anymore. But smm=off seems to be required when using SeaBIOS and serial display.
3498my sub should_disable_smm {
e4263214
FE
3499 my ($conf, $vga, $machine) = @_;
3500
3501 return if $machine =~ m/^virt/; # there is no smm flag that could be disabled
e5a6919c
FE
3502
3503 return (!defined($conf->{bios}) || $conf->{bios} eq 'seabios') &&
bec87424 3504 $vga->{type} && $vga->{type} =~ m/^(serial\d+|none)$/;
e5a6919c
FE
3505}
3506
b7d80c79
FE
3507my sub print_ovmf_drive_commandlines {
3508 my ($conf, $storecfg, $vmid, $arch, $q35, $version_guard) = @_;
3509
3d07669c 3510 my $d = $conf->{efidisk0} ? parse_drive('efidisk0', $conf->{efidisk0}) : undef;
b7d80c79
FE
3511
3512 my ($ovmf_code, $ovmf_vars) = get_ovmf_files($arch, $d, $q35);
b7d80c79 3513
3d07669c 3514 my $var_drive_str = "if=pflash,unit=1,id=drive-efidisk0";
b7d80c79
FE
3515 if ($d) {
3516 my ($storeid, $volname) = PVE::Storage::parse_volume_id($d->{file}, 1);
3d07669c 3517 my ($path, $format) = $d->@{'file', 'format'};
b7d80c79
FE
3518 if ($storeid) {
3519 $path = PVE::Storage::path($storecfg, $d->{file});
3520 if (!defined($format)) {
3521 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
3522 $format = qemu_img_format($scfg, $volname);
3523 }
3d07669c
TL
3524 } elsif (!defined($format)) {
3525 die "efidisk format must be specified\n";
3526 }
3527 # SPI flash does lots of read-modify-write OPs, without writeback this gets really slow #3329
3528 if ($path =~ m/^rbd:/) {
3529 $var_drive_str .= ',cache=writeback';
3530 $path .= ':rbd_cache_policy=writeback'; # avoid write-around, we *need* to cache writes too
b7d80c79 3531 }
3d07669c 3532 $var_drive_str .= ",format=$format,file=$path";
b7d80c79 3533
3d07669c
TL
3534 $var_drive_str .= ",size=" . (-s $ovmf_vars) if $format eq 'raw' && $version_guard->(4, 1, 2);
3535 $var_drive_str .= ',readonly=on' if drive_is_read_only($conf, $d);
b7d80c79
FE
3536 } else {
3537 log_warn("no efidisk configured! Using temporary efivars disk.");
3d07669c 3538 my $path = "/tmp/$vmid-ovmf.fd";
b7d80c79 3539 PVE::Tools::file_copy($ovmf_vars, $path, -s $ovmf_vars);
3d07669c
TL
3540 $var_drive_str .= ",format=raw,file=$path";
3541 $var_drive_str .= ",size=" . (-s $ovmf_vars) if $version_guard->(4, 1, 2);
b7d80c79
FE
3542 }
3543
3d07669c 3544 return ("if=pflash,unit=0,format=raw,readonly=on,file=$ovmf_code", $var_drive_str);
b7d80c79
FE
3545}
3546
1e3baf05 3547sub config_to_command {
5921764c
SR
3548 my ($storecfg, $vmid, $conf, $defaults, $forcemachine, $forcecpu,
3549 $pbs_backing) = @_;
1e3baf05 3550
3326ae19 3551 my ($globalFlags, $machineFlags, $rtcFlags) = ([], [], []);
5bdcf937 3552 my $devices = [];
5bdcf937 3553 my $bridges = {};
b42d3cf9 3554 my $ostype = $conf->{ostype};
4317f69f 3555 my $winversion = windows_version($ostype);
d731ecbe 3556 my $kvm = $conf->{kvm};
38277afc 3557 my $nodename = nodename();
d731ecbe 3558
045749f2 3559 my $arch = get_vm_arch($conf);
1476b99f
DC
3560 my $kvm_binary = get_command_for_arch($arch);
3561 my $kvmver = kvm_user_version($kvm_binary);
045749f2 3562
a04dd5c4
SR
3563 if (!$kvmver || $kvmver !~ m/^(\d+)\.(\d+)/ || $1 < 3) {
3564 $kvmver //= "undefined";
3565 die "Detected old QEMU binary ('$kvmver', at least 3.0 is required)\n";
3566 }
3567
9471e48b
TL
3568 my $add_pve_version = min_version($kvmver, 4, 1);
3569
3570 my $machine_type = get_vm_machine($conf, $forcemachine, $arch, $add_pve_version);
4df98f2f 3571 my $machine_version = extract_version($machine_type, $kvmver);
d731ecbe 3572 $kvm //= 1 if is_native($arch);
4317f69f 3573
a77a53ae 3574 $machine_version =~ m/(\d+)\.(\d+)/;
ac0077cc 3575 my ($machine_major, $machine_minor) = ($1, $2);
ac0077cc 3576
b516c848
SR
3577 if ($kvmver =~ m/^\d+\.\d+\.(\d+)/ && $1 >= 90) {
3578 warn "warning: Installed QEMU version ($kvmver) is a release candidate, ignoring version checks\n";
3579 } elsif (!min_version($kvmver, $machine_major, $machine_minor)) {
4df98f2f
TL
3580 die "Installed QEMU version '$kvmver' is too old to run machine type '$machine_type',"
3581 ." please upgrade node '$nodename'\n"
b516c848 3582 } elsif (!PVE::QemuServer::Machine::can_run_pve_machine_version($machine_version, $kvmver)) {
ac0077cc 3583 my $max_pve_version = PVE::QemuServer::Machine::get_pve_version($machine_version);
4df98f2f
TL
3584 die "Installed qemu-server (max feature level for $machine_major.$machine_minor is"
3585 ." pve$max_pve_version) is too old to run machine type '$machine_type', please upgrade"
3586 ." node '$nodename'\n";
ac0077cc
SR
3587 }
3588
3589 # if a specific +pve version is required for a feature, use $version_guard
3590 # instead of min_version to allow machines to be run with the minimum
3591 # required version
3592 my $required_pve_version = 0;
3593 my $version_guard = sub {
3594 my ($major, $minor, $pve) = @_;
3595 return 0 if !min_version($machine_version, $major, $minor, $pve);
47f35977
SR
3596 my $max_pve = PVE::QemuServer::Machine::get_pve_version("$major.$minor");
3597 return 1 if min_version($machine_version, $major, $minor, $max_pve+1);
ac0077cc
SR
3598 $required_pve_version = $pve if $pve && $pve > $required_pve_version;
3599 return 1;
3600 };
a77a53ae 3601
4df98f2f
TL
3602 if ($kvm && !defined kvm_version()) {
3603 die "KVM virtualisation configured, but not available. Either disable in VM configuration"
3604 ." or enable in BIOS.\n";
d731ecbe 3605 }
bfcd9b7e 3606
3392d6ca 3607 my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf);
4d3f29ed 3608 my $hotplug_features = parse_hotplug_features(defined($conf->{hotplug}) ? $conf->{hotplug} : '1');
249c4a6c
AD
3609 my $use_old_bios_files = undef;
3610 ($use_old_bios_files, $machine_type) = qemu_use_old_bios_files($machine_type);
db656e5f 3611
74fe3d9a 3612 my $cmd = [];
83870398 3613 if ($conf->{affinity}) {
74fe3d9a 3614 push @$cmd, '/usr/bin/taskset', '--cpu-list', '--all-tasks', $conf->{affinity};
83870398
DB
3615 }
3616
1476b99f 3617 push @$cmd, $kvm_binary;
1e3baf05
DM
3618
3619 push @$cmd, '-id', $vmid;
3620
e4d4cda1
HR
3621 my $vmname = $conf->{name} || "vm$vmid";
3622
6884a7d7 3623 push @$cmd, '-name', "$vmname,debug-threads=on";
e4d4cda1 3624
27b25d03
SR
3625 push @$cmd, '-no-shutdown';
3626
1e3baf05
DM
3627 my $use_virtio = 0;
3628
d036e418 3629 my $qmpsocket = PVE::QemuServer::Helpers::qmp_socket($vmid);
378ad769 3630 push @$cmd, '-chardev', "socket,id=qmp,path=$qmpsocket,server=on,wait=off";
c971c4f2
AD
3631 push @$cmd, '-mon', "chardev=qmp,mode=control";
3632
2ea5fb7e 3633 if (min_version($machine_version, 2, 12)) {
b4496b9e 3634 push @$cmd, '-chardev', "socket,id=qmp-event,path=/var/run/qmeventd.sock,reconnect=5";
71bd73b5
DC
3635 push @$cmd, '-mon', "chardev=qmp-event,mode=control";
3636 }
1e3baf05 3637
d036e418 3638 push @$cmd, '-pidfile' , PVE::QemuServer::Helpers::pidfile_name($vmid);
19672434 3639
1e3baf05
DM
3640 push @$cmd, '-daemonize';
3641
2796e7d5 3642 if ($conf->{smbios1}) {
1f30ac3a
CE
3643 my $smbios_conf = parse_smbios1($conf->{smbios1});
3644 if ($smbios_conf->{base64}) {
3645 # Do not pass base64 flag to qemu
3646 delete $smbios_conf->{base64};
3647 my $smbios_string = "";
3648 foreach my $key (keys %$smbios_conf) {
3649 my $value;
3650 if ($key eq "uuid") {
3651 $value = $smbios_conf->{uuid}
3652 } else {
3653 $value = decode_base64($smbios_conf->{$key});
3654 }
3655 # qemu accepts any binary data, only commas need escaping by double comma
3656 $value =~ s/,/,,/g;
3657 $smbios_string .= "," . $key . "=" . $value if $value;
3658 }
3659 push @$cmd, '-smbios', "type=1" . $smbios_string;
3660 } else {
3661 push @$cmd, '-smbios', "type=1,$conf->{smbios1}";
3662 }
2796e7d5
DM
3663 }
3664
3edb45e7 3665 if ($conf->{bios} && $conf->{bios} eq 'ovmf') {
b7d80c79
FE
3666 my ($code_drive_str, $var_drive_str) =
3667 print_ovmf_drive_commandlines($conf, $storecfg, $vmid, $arch, $q35, $version_guard);
3668 push $cmd->@*, '-drive', $code_drive_str;
3669 push $cmd->@*, '-drive', $var_drive_str;
a783c78e
AD
3670 }
3671
483ceeab 3672 if ($q35) { # tell QEMU to load q35 config early
7583d156 3673 # we use different pcie-port hardware for qemu >= 4.0 for passthrough
2ea5fb7e 3674 if (min_version($machine_version, 4, 0)) {
7583d156
DC
3675 push @$devices, '-readconfig', '/usr/share/qemu-server/pve-q35-4.0.cfg';
3676 } else {
3677 push @$devices, '-readconfig', '/usr/share/qemu-server/pve-q35.cfg';
3678 }
3679 }
da8b4189 3680
cc181036
TL
3681 if (defined(my $fixups = qemu_created_version_fixups($conf, $forcemachine, $kvmver))) {
3682 push @$cmd, $fixups->@*;
3683 }
3684
844d8fa6
DC
3685 if ($conf->{vmgenid}) {
3686 push @$devices, '-device', 'vmgenid,guid='.$conf->{vmgenid};
3687 }
3688
d40e5e18 3689 # add usb controllers
4df98f2f 3690 my @usbcontrollers = PVE::QemuServer::USB::get_usb_controllers(
0cf8d56c 3691 $conf, $bridges, $arch, $machine_type, $machine_version);
d40e5e18 3692 push @$devices, @usbcontrollers if @usbcontrollers;
55655ebc 3693 my $vga = parse_vga($conf->{vga});
2fa3151e 3694
55655ebc
DC
3695 my $qxlnum = vga_conf_has_spice($conf->{vga});
3696 $vga->{type} = 'qxl' if $qxlnum;
2fa3151e 3697
55655ebc 3698 if (!$vga->{type}) {
869ad4a7
WB
3699 if ($arch eq 'aarch64') {
3700 $vga->{type} = 'virtio';
2ea5fb7e 3701 } elsif (min_version($machine_version, 2, 9)) {
55655ebc 3702 $vga->{type} = (!$winversion || $winversion >= 6) ? 'std' : 'cirrus';
a2a5cd64 3703 } else {
55655ebc 3704 $vga->{type} = ($winversion >= 6) ? 'std' : 'cirrus';
a2a5cd64 3705 }
5acbfe9e
DM
3706 }
3707
1e3baf05 3708 # enable absolute mouse coordinates (needed by vnc)
fa3b3ce0
TL
3709 my $tablet = $conf->{tablet};
3710 if (!defined($tablet)) {
5acbfe9e 3711 $tablet = $defaults->{tablet};
590e698c 3712 $tablet = 0 if $qxlnum; # disable for spice because it is not needed
55655ebc 3713 $tablet = 0 if $vga->{type} =~ m/^serial\d+$/; # disable if we use serial terminal (no vga card)
5acbfe9e
DM
3714 }
3715
d559309f
WB
3716 if ($tablet) {
3717 push @$devices, '-device', print_tabletdevice_full($conf, $arch) if $tablet;
3718 my $kbd = print_keyboarddevice_full($conf, $arch);
3719 push @$devices, '-device', $kbd if defined($kbd);
3720 }
b467f79a 3721
e5d611c3 3722 my $bootorder = device_bootorder($conf);
2141a802 3723
74c17b7a 3724 # host pci device passthrough
9b71c34d
DC
3725 my ($kvm_off, $gpu_passthrough, $legacy_igd, $pci_devices) = PVE::QemuServer::PCI::print_hostpci_devices(
3726 $vmid, $conf, $devices, $vga, $winversion, $bridges, $arch, $machine_type, $bootorder);
1e3baf05
DM
3727
3728 # usb devices
ae36393d 3729 my $usb_dev_features = {};
2ea5fb7e 3730 $usb_dev_features->{spice_usb3} = 1 if min_version($machine_version, 4, 0);
ae36393d 3731
4df98f2f 3732 my @usbdevices = PVE::QemuServer::USB::get_usb_devices(
0cf8d56c 3733 $conf, $usb_dev_features, $bootorder, $machine_version);
d40e5e18 3734 push @$devices, @usbdevices if @usbdevices;
2141a802 3735
1e3baf05 3736 # serial devices
bae179aa 3737 for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) {
fa3b3ce0
TL
3738 my $path = $conf->{"serial$i"} or next;
3739 if ($path eq 'socket') {
3740 my $socket = "/var/run/qemu-server/${vmid}.serial$i";
3741 push @$devices, '-chardev', "socket,id=serial$i,path=$socket,server=on,wait=off";
7bd9abd2 3742 # On aarch64, serial0 is the UART device. QEMU only allows
fa3b3ce0
TL
3743 # connecting UART devices via the '-serial' command line, as
3744 # the device has a fixed slot on the hardware...
3745 if ($arch eq 'aarch64' && $i == 0) {
3746 push @$devices, '-serial', "chardev:serial$i";
9f9d2fb2 3747 } else {
9f9d2fb2
DM
3748 push @$devices, '-device', "isa-serial,chardev=serial$i";
3749 }
fa3b3ce0
TL
3750 } else {
3751 die "no such serial device\n" if ! -c $path;
e35eb876 3752 push @$devices, '-chardev', "serial,id=serial$i,path=$path";
fa3b3ce0 3753 push @$devices, '-device', "isa-serial,chardev=serial$i";
34978be3 3754 }
1e3baf05
DM
3755 }
3756
3757 # parallel devices
1989a89c 3758 for (my $i = 0; $i < $MAX_PARALLEL_PORTS; $i++) {
34978be3 3759 if (my $path = $conf->{"parallel$i"}) {
19672434 3760 die "no such parallel device\n" if ! -c $path;
e35eb876 3761 my $devtype = $path =~ m!^/dev/usb/lp! ? 'serial' : 'parallel';
4c5dbaf6 3762 push @$devices, '-chardev', "$devtype,id=parallel$i,path=$path";
5bdcf937 3763 push @$devices, '-device', "isa-parallel,chardev=parallel$i";
34978be3 3764 }
1e3baf05
DM
3765 }
3766
b01de199 3767 if (min_version($machine_version, 4, 0) && (my $audio = conf_has_audio($conf))) {
2e7b5925 3768 my $audiopciaddr = print_pci_addr("audio0", $bridges, $arch, $machine_type);
1cc5ed1b 3769 my $audio_devs = audio_devs($audio, $audiopciaddr, $machine_version);
b01de199 3770 push @$devices, @$audio_devs;
2e7b5925 3771 }
19672434 3772
a55d0f71
FS
3773 # Add a TPM only if the VM is not a template,
3774 # to support backing up template VMs even if the TPM disk is write-protected.
3775 add_tpm_device($vmid, $devices, $conf) if (!PVE::QemuConfig->is_template($conf));
f9dde219 3776
1e3baf05
DM
3777 my $sockets = 1;
3778 $sockets = $conf->{smp} if $conf->{smp}; # old style - no longer iused
3779 $sockets = $conf->{sockets} if $conf->{sockets};
3780
3781 my $cores = $conf->{cores} || 1;
3bd18e48 3782
de9d1e55 3783 my $maxcpus = $sockets * $cores;
76267728 3784
de9d1e55 3785 my $vcpus = $conf->{vcpus} ? $conf->{vcpus} : $maxcpus;
76267728 3786
de9d1e55
AD
3787 my $allowed_vcpus = $cpuinfo->{cpus};
3788
483ceeab 3789 die "MAX $allowed_vcpus vcpus allowed per VM on this node\n" if ($allowed_vcpus < $maxcpus);
1e3baf05 3790
483ceeab 3791 if ($hotplug_features->{cpu} && min_version($machine_version, 2, 7)) {
69c81430
AD
3792 push @$cmd, '-smp', "1,sockets=$sockets,cores=$cores,maxcpus=$maxcpus";
3793 for (my $i = 2; $i <= $vcpus; $i++) {
3794 my $cpustr = print_cpu_device($conf,$i);
3795 push @$cmd, '-device', $cpustr;
3796 }
3797
3798 } else {
3799
3800 push @$cmd, '-smp', "$vcpus,sockets=$sockets,cores=$cores,maxcpus=$maxcpus";
3801 }
1e3baf05
DM
3802 push @$cmd, '-nodefaults';
3803
dbea4415 3804 push @$cmd, '-boot', "menu=on,strict=on,reboot-timeout=1000,splash=/usr/share/qemu-server/bootsplash.jpg";
1e3baf05 3805
0f704640 3806 push $machineFlags->@*, 'acpi=off' if defined($conf->{acpi}) && $conf->{acpi} == 0;
1e3baf05 3807
6b64503e 3808 push @$cmd, '-no-reboot' if defined($conf->{reboot}) && $conf->{reboot} == 0;
1e3baf05 3809
84902837 3810 if ($vga->{type} && $vga->{type} !~ m/^serial\d+$/ && $vga->{type} ne 'none'){
4df98f2f
TL
3811 push @$devices, '-device', print_vga_device(
3812 $conf, $vga, $arch, $machine_version, $machine_type, undef, $qxlnum, $bridges);
6f070e39
TL
3813
3814 push @$cmd, '-display', 'egl-headless,gl=core' if $vga->{type} eq 'virtio-gl'; # VIRGL
3815
d036e418 3816 my $socket = PVE::QemuServer::Helpers::vnc_socket($vmid);
378ad769 3817 push @$cmd, '-vnc', "unix:$socket,password=on";
b7be4ba9 3818 } else {
55655ebc 3819 push @$cmd, '-vga', 'none' if $vga->{type} eq 'none';
b7be4ba9
AD
3820 push @$cmd, '-nographic';
3821 }
3822
1e3baf05 3823 # time drift fix
6b64503e 3824 my $tdf = defined($conf->{tdf}) ? $conf->{tdf} : $defaults->{tdf};
8c559505 3825 my $useLocaltime = $conf->{localtime};
1e3baf05 3826
4317f69f
AD
3827 if ($winversion >= 5) { # windows
3828 $useLocaltime = 1 if !defined($conf->{localtime});
7a131888 3829
4317f69f
AD
3830 # use time drift fix when acpi is enabled
3831 if (!(defined($conf->{acpi}) && $conf->{acpi} == 0)) {
3832 $tdf = 1 if !defined($conf->{tdf});
462e8d19 3833 }
4317f69f 3834 }
462e8d19 3835
4317f69f
AD
3836 if ($winversion >= 6) {
3837 push @$globalFlags, 'kvm-pit.lost_tick_policy=discard';
17bacc21 3838 push @$machineFlags, 'hpet=off';
1e3baf05
DM
3839 }
3840
8c559505
DM
3841 push @$rtcFlags, 'driftfix=slew' if $tdf;
3842
2f6f002c 3843 if ($conf->{startdate} && $conf->{startdate} ne 'now') {
8c559505
DM
3844 push @$rtcFlags, "base=$conf->{startdate}";
3845 } elsif ($useLocaltime) {
3846 push @$rtcFlags, 'base=localtime';
3847 }
1e3baf05 3848
58c64ad5
SR
3849 if ($forcecpu) {
3850 push @$cmd, '-cpu', $forcecpu;
3851 } else {
2f6f002c 3852 push @$cmd, get_cpu_options($conf, $arch, $kvm, $kvm_off, $machine_version, $winversion, $gpu_passthrough);
58c64ad5 3853 }
519ed28c 3854
dafb728c 3855 PVE::QemuServer::Memory::config(
7f8c8087 3856 $conf, $vmid, $sockets, $cores, $hotplug_features->{memory}, $cmd);
370b05e7 3857
1e3baf05
DM
3858 push @$cmd, '-S' if $conf->{freeze};
3859
b20df606 3860 push @$cmd, '-k', $conf->{keyboard} if defined($conf->{keyboard});
1e3baf05 3861
48657158
MD
3862 my $guest_agent = parse_guest_agent($conf);
3863
3864 if ($guest_agent->{enabled}) {
d036e418 3865 my $qgasocket = PVE::QemuServer::Helpers::qmp_socket($vmid, 1);
378ad769 3866 push @$devices, '-chardev', "socket,path=$qgasocket,server=on,wait=off,id=qga0";
48657158 3867
60f03a11 3868 if (!$guest_agent->{type} || $guest_agent->{type} eq 'virtio') {
48657158
MD
3869 my $pciaddr = print_pci_addr("qga0", $bridges, $arch, $machine_type);
3870 push @$devices, '-device', "virtio-serial,id=qga0$pciaddr";
3871 push @$devices, '-device', 'virtserialport,chardev=qga0,name=org.qemu.guest_agent.0';
3872 } elsif ($guest_agent->{type} eq 'isa') {
3873 push @$devices, '-device', "isa-serial,chardev=qga0";
3874 }
ab6a046f
AD
3875 }
3876
e5d611c3
TL
3877 my $rng = $conf->{rng0} ? parse_rng($conf->{rng0}) : undef;
3878 if ($rng && $version_guard->(4, 1, 2)) {
05853188
SR
3879 check_rng_source($rng->{source});
3880
2cf61f33
SR
3881 my $max_bytes = $rng->{max_bytes} // $rng_fmt->{max_bytes}->{default};
3882 my $period = $rng->{period} // $rng_fmt->{period}->{default};
2cf61f33
SR
3883 my $limiter_str = "";
3884 if ($max_bytes) {
3885 $limiter_str = ",max-bytes=$max_bytes,period=$period";
3886 }
3887
2cf61f33 3888 my $rng_addr = print_pci_addr("rng0", $bridges, $arch, $machine_type);
2cf61f33
SR
3889 push @$devices, '-object', "rng-random,filename=$rng->{source},id=rng0";
3890 push @$devices, '-device', "virtio-rng-pci,rng=rng0$limiter_str$rng_addr";
3891 }
3892
1d794448 3893 my $spice_port;
2fa3151e 3894
f8ea1b30 3895 if ($qxlnum || $vga->{type} =~ /^virtio/) {
590e698c 3896 if ($qxlnum > 1) {
ac087616 3897 if ($winversion){
2f6f002c 3898 for (my $i = 1; $i < $qxlnum; $i++){
4df98f2f
TL
3899 push @$devices, '-device', print_vga_device(
3900 $conf, $vga, $arch, $machine_version, $machine_type, $i, $qxlnum, $bridges);
590e698c
DM
3901 }
3902 } else {
3903 # assume other OS works like Linux
55655ebc
DC
3904 my ($ram, $vram) = ("134217728", "67108864");
3905 if ($vga->{memory}) {
3906 $ram = PVE::Tools::convert_size($qxlnum*4*$vga->{memory}, 'mb' => 'b');
3907 $vram = PVE::Tools::convert_size($qxlnum*2*$vga->{memory}, 'mb' => 'b');
3908 }
3909 push @$cmd, '-global', "qxl-vga.ram_size=$ram";
3910 push @$cmd, '-global', "qxl-vga.vram_size=$vram";
2fa3151e
AD
3911 }
3912 }
3913
d559309f 3914 my $pciaddr = print_pci_addr("spice", $bridges, $arch, $machine_type);
95a4b4a9 3915
af0eba7e 3916 my $pfamily = PVE::Tools::get_host_address_family($nodename);
91152441
WB
3917 my @nodeaddrs = PVE::Tools::getaddrinfo_all('localhost', family => $pfamily);
3918 die "failed to get an ip address of type $pfamily for 'localhost'\n" if !@nodeaddrs;
4d316a63
AL
3919
3920 push @$devices, '-device', "virtio-serial,id=spice$pciaddr";
3921 push @$devices, '-chardev', "spicevmc,id=vdagent,name=vdagent";
3922 push @$devices, '-device', "virtserialport,chardev=vdagent,name=com.redhat.spice.0";
3923
91152441
WB
3924 my $localhost = PVE::Network::addr_to_ip($nodeaddrs[0]->{addr});
3925 $spice_port = PVE::Tools::next_spice_port($pfamily, $localhost);
943340a6 3926
4df98f2f
TL
3927 my $spice_enhancement_str = $conf->{spice_enhancements} // '';
3928 my $spice_enhancement = parse_property_string($spice_enhancements_fmt, $spice_enhancement_str);
caab114a
TL
3929 if ($spice_enhancement->{foldersharing}) {
3930 push @$devices, '-chardev', "spiceport,id=foldershare,name=org.spice-space.webdav.0";
3931 push @$devices, '-device', "virtserialport,chardev=foldershare,name=org.spice-space.webdav.0";
3932 }
c4df18db 3933
caab114a 3934 my $spice_opts = "tls-port=${spice_port},addr=$localhost,tls-ciphers=HIGH,seamless-migration=on";
4df98f2f
TL
3935 $spice_opts .= ",streaming-video=$spice_enhancement->{videostreaming}"
3936 if $spice_enhancement->{videostreaming};
3937
caab114a 3938 push @$devices, '-spice', "$spice_opts";
1011b570
DM
3939 }
3940
8d9ae0d2
DM
3941 # enable balloon by default, unless explicitly disabled
3942 if (!defined($conf->{balloon}) || $conf->{balloon}) {
3326ae19 3943 my $pciaddr = print_pci_addr("balloon0", $bridges, $arch, $machine_type);
c70e4ec3
AD
3944 my $ballooncmd = "virtio-balloon-pci,id=balloon0$pciaddr";
3945 $ballooncmd .= ",free-page-reporting=on" if min_version($machine_version, 6, 2);
3946 push @$devices, '-device', $ballooncmd;
8d9ae0d2 3947 }
1e3baf05 3948
0ea9541d
DM
3949 if ($conf->{watchdog}) {
3950 my $wdopts = parse_watchdog($conf->{watchdog});
3326ae19 3951 my $pciaddr = print_pci_addr("watchdog", $bridges, $arch, $machine_type);
0a40e8ea 3952 my $watchdog = $wdopts->{model} || 'i6300esb';
5bdcf937
AD
3953 push @$devices, '-device', "$watchdog$pciaddr";
3954 push @$devices, '-watchdog-action', $wdopts->{action} if $wdopts->{action};
0ea9541d
DM
3955 }
3956
1e3baf05 3957 my $vollist = [];
941e0c42 3958 my $scsicontroller = {};
26ee04b6 3959 my $ahcicontroller = {};
cdd20088 3960 my $scsihw = defined($conf->{scsihw}) ? $conf->{scsihw} : $defaults->{scsihw};
1e3baf05 3961
5881b913
DM
3962 # Add iscsi initiator name if available
3963 if (my $initiator = get_initiator_name()) {
3964 push @$devices, '-iscsi', "initiator-name=$initiator";
3965 }
3966
912792e2 3967 PVE::QemuConfig->foreach_volume($conf, sub {
1e3baf05
DM
3968 my ($ds, $drive) = @_;
3969
ff1a2432 3970 if (PVE::Storage::parse_volume_id($drive->{file}, 1)) {
3f11f0d7 3971 check_volume_storage_type($storecfg, $drive->{file});
1e3baf05 3972 push @$vollist, $drive->{file};
ff1a2432 3973 }
afdb31d5 3974
4dcce9ee
TL
3975 # ignore efidisk here, already added in bios/fw handling code above
3976 return if $drive->{interface} eq 'efidisk';
f9dde219
SR
3977 # similar for TPM
3978 return if $drive->{interface} eq 'tpmstate';
4dcce9ee 3979
1e3baf05 3980 $use_virtio = 1 if $ds =~ m/^virtio/;
3b408e82 3981
2141a802 3982 $drive->{bootindex} = $bootorder->{$ds} if $bootorder->{$ds};
3b408e82 3983
2f6f002c 3984 if ($drive->{interface} eq 'virtio'){
51f492cd
AD
3985 push @$cmd, '-object', "iothread,id=iothread-$ds" if $drive->{iothread};
3986 }
3987
2f6f002c 3988 if ($drive->{interface} eq 'scsi') {
cdd20088 3989
ee034f5c 3990 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $drive);
6731a4cf 3991
b8fb1c03
SR
3992 die "scsi$drive->{index}: machine version 4.1~pve2 or higher is required to use more than 14 SCSI disks\n"
3993 if $drive->{index} > 13 && !&$version_guard(4, 1, 2);
3994
3326ae19 3995 my $pciaddr = print_pci_addr("$controller_prefix$controller", $bridges, $arch, $machine_type);
a1b7d579 3996 my $scsihw_type = $scsihw =~ m/^virtio-scsi-single/ ? "virtio-scsi-pci" : $scsihw;
fc8b40fd
AD
3997
3998 my $iothread = '';
3999 if($conf->{scsihw} && $conf->{scsihw} eq "virtio-scsi-single" && $drive->{iothread}){
4000 $iothread .= ",iothread=iothread-$controller_prefix$controller";
4001 push @$cmd, '-object', "iothread,id=iothread-$controller_prefix$controller";
e7a5104d 4002 } elsif ($drive->{iothread}) {
d80ad18c
MH
4003 log_warn(
4004 "iothread is only valid with virtio disk or virtio-scsi-single controller, ignoring\n"
4005 );
fc8b40fd
AD
4006 }
4007
6e11f143
AD
4008 my $queues = '';
4009 if($conf->{scsihw} && $conf->{scsihw} eq "virtio-scsi-single" && $drive->{queues}){
4010 $queues = ",num_queues=$drive->{queues}";
370b05e7 4011 }
6e11f143 4012
4df98f2f
TL
4013 push @$devices, '-device', "$scsihw_type,id=$controller_prefix$controller$pciaddr$iothread$queues"
4014 if !$scsicontroller->{$controller};
cdd20088 4015 $scsicontroller->{$controller}=1;
2f6f002c 4016 }
3b408e82 4017
26ee04b6 4018 if ($drive->{interface} eq 'sata') {
2f6f002c 4019 my $controller = int($drive->{index} / $PVE::QemuServer::Drive::MAX_SATA_DISKS);
3326ae19 4020 my $pciaddr = print_pci_addr("ahci$controller", $bridges, $arch, $machine_type);
4df98f2f
TL
4021 push @$devices, '-device', "ahci,id=ahci$controller,multifunction=on$pciaddr"
4022 if !$ahcicontroller->{$controller};
2f6f002c 4023 $ahcicontroller->{$controller}=1;
26ee04b6 4024 }
46f58b5f 4025
5921764c
SR
4026 my $pbs_conf = $pbs_backing->{$ds};
4027 my $pbs_name = undef;
4028 if ($pbs_conf) {
4029 $pbs_name = "drive-$ds-pbs";
4030 push @$devices, '-blockdev', print_pbs_blockdev($pbs_conf, $pbs_name);
4031 }
4032
6d5673c3
SR
4033 my $drive_cmd = print_drive_commandline_full(
4034 $storecfg, $vmid, $drive, $pbs_name, min_version($kvmver, 6, 0));
3dc33a72
FG
4035
4036 # extra protection for templates, but SATA and IDE don't support it..
75748d44 4037 $drive_cmd .= ',readonly=on' if drive_is_read_only($conf, $drive);
4ef13a7f 4038
15b21acc 4039 push @$devices, '-drive',$drive_cmd;
4df98f2f
TL
4040 push @$devices, '-device', print_drivedevice_full(
4041 $storecfg, $conf, $vmid, $drive, $bridges, $arch, $machine_type);
1e3baf05
DM
4042 });
4043
cc4d6182 4044 for (my $i = 0; $i < $MAX_NETS; $i++) {
2141a802
SR
4045 my $netname = "net$i";
4046
4047 next if !$conf->{$netname};
4048 my $d = parse_net($conf->{$netname});
d0a86b24 4049 next if !$d;
4ddd2ca2 4050 # save the MAC addr here (could be auto-gen. in some odd setups) for FDB registering later?
1e3baf05 4051
d0a86b24 4052 $use_virtio = 1 if $d->{model} eq 'virtio';
1e3baf05 4053
2141a802 4054 $d->{bootindex} = $bootorder->{$netname} if $bootorder->{$netname};
1e3baf05 4055
2141a802 4056 my $netdevfull = print_netdev_full($vmid, $conf, $arch, $d, $netname);
d0a86b24 4057 push @$devices, '-netdev', $netdevfull;
5bdcf937 4058
d0a86b24 4059 my $netdevicefull = print_netdevice_full(
0c03a390 4060 $vmid, $conf, $d, $netname, $bridges, $use_old_bios_files, $arch, $machine_type, $machine_version);
4df98f2f 4061
d0a86b24 4062 push @$devices, '-device', $netdevicefull;
5bdcf937 4063 }
1e3baf05 4064
6dbcb073 4065 if ($conf->{ivshmem}) {
4df98f2f 4066 my $ivshmem = parse_property_string($ivshmem_fmt, $conf->{ivshmem});
e3c27a6a 4067
6dbcb073
DC
4068 my $bus;
4069 if ($q35) {
4070 $bus = print_pcie_addr("ivshmem");
4071 } else {
4072 $bus = print_pci_addr("ivshmem", $bridges, $arch, $machine_type);
4073 }
e3c27a6a
TL
4074
4075 my $ivshmem_name = $ivshmem->{name} // $vmid;
4076 my $path = '/dev/shm/pve-shm-' . $ivshmem_name;
4077
6dbcb073 4078 push @$devices, '-device', "ivshmem-plain,memdev=ivshmem$bus,";
4df98f2f
TL
4079 push @$devices, '-object', "memory-backend-file,id=ivshmem,share=on,mem-path=$path"
4080 .",size=$ivshmem->{size}M";
6dbcb073
DC
4081 }
4082
2513b862
DC
4083 # pci.4 is nested in pci.1
4084 $bridges->{1} = 1 if $bridges->{4};
4085
3326ae19
TL
4086 if (!$q35) { # add pci bridges
4087 if (min_version($machine_version, 2, 3)) {
fc79e813
AD
4088 $bridges->{1} = 1;
4089 $bridges->{2} = 1;
4090 }
6731a4cf 4091 $bridges->{3} = 1 if $scsihw =~ m/^virtio-scsi-single/;
2513b862
DC
4092 }
4093
4094 for my $k (sort {$b cmp $a} keys %$bridges) {
4095 next if $q35 && $k < 4; # q35.cfg already includes bridges up to 3
13d68979
SR
4096
4097 my $k_name = $k;
4098 if ($k == 2 && $legacy_igd) {
4099 $k_name = "$k-igd";
4100 }
3326ae19 4101 my $pciaddr = print_pci_addr("pci.$k_name", undef, $arch, $machine_type);
2513b862 4102 my $devstr = "pci-bridge,id=pci.$k,chassis_nr=$k$pciaddr";
3326ae19
TL
4103
4104 if ($q35) { # add after -readconfig pve-q35.cfg
2513b862
DC
4105 splice @$devices, 2, 0, '-device', $devstr;
4106 } else {
4107 unshift @$devices, '-device', $devstr if $k > 0;
f8e83f05 4108 }
19672434
DM
4109 }
4110
ac0077cc
SR
4111 if (!$kvm) {
4112 push @$machineFlags, 'accel=tcg';
4113 }
4114
e4263214 4115 push @$machineFlags, 'smm=off' if should_disable_smm($conf, $vga, $machine_type);
e5a6919c 4116
ac0077cc
SR
4117 my $machine_type_min = $machine_type;
4118 if ($add_pve_version) {
4119 $machine_type_min =~ s/\+pve\d+$//;
4120 $machine_type_min .= "+pve$required_pve_version";
4121 }
4122 push @$machineFlags, "type=${machine_type_min}";
4123
5bdcf937 4124 push @$cmd, @$devices;
2f6f002c
TL
4125 push @$cmd, '-rtc', join(',', @$rtcFlags) if scalar(@$rtcFlags);
4126 push @$cmd, '-machine', join(',', @$machineFlags) if scalar(@$machineFlags);
4127 push @$cmd, '-global', join(',', @$globalFlags) if scalar(@$globalFlags);
8c559505 4128
7ceade4c
DC
4129 if (my $vmstate = $conf->{vmstate}) {
4130 my $statepath = PVE::Storage::path($storecfg, $vmstate);
24d1f93a 4131 push @$vollist, $vmstate;
7ceade4c 4132 push @$cmd, '-loadstate', $statepath;
b85666cf 4133 print "activating and using '$vmstate' as vmstate\n";
7ceade4c
DC
4134 }
4135
85fcf79e
FG
4136 if (PVE::QemuConfig->is_template($conf)) {
4137 # needed to workaround base volumes being read-only
4138 push @$cmd, '-snapshot';
4139 }
4140
76350670
DC
4141 # add custom args
4142 if ($conf->{args}) {
4143 my $aa = PVE::Tools::split_args($conf->{args});
4144 push @$cmd, @$aa;
4145 }
4146
9b71c34d 4147 return wantarray ? ($cmd, $vollist, $spice_port, $pci_devices) : $cmd;
1e3baf05 4148}
19672434 4149
05853188
SR
4150sub check_rng_source {
4151 my ($source) = @_;
4152
4153 # mostly relevant for /dev/hwrng, but doesn't hurt to check others too
4154 die "cannot create VirtIO RNG device: source file '$source' doesn't exist\n"
4155 if ! -e $source;
4156
4157 my $rng_current = '/sys/devices/virtual/misc/hw_random/rng_current';
4158 if ($source eq '/dev/hwrng' && file_read_firstline($rng_current) eq 'none') {
4df98f2f
TL
4159 # Needs to abort, otherwise QEMU crashes on first rng access. Note that rng_current cannot
4160 # be changed to 'none' manually, so once the VM is past this point, it's no longer an issue.
4161 die "Cannot start VM with passed-through RNG device: '/dev/hwrng' exists, but"
4162 ." '$rng_current' is set to 'none'. Ensure that a compatible hardware-RNG is attached"
4163 ." to the host.\n";
05853188
SR
4164 }
4165}
4166
943340a6 4167sub spice_port {
1011b570 4168 my ($vmid) = @_;
943340a6 4169
0a13e08e 4170 my $res = mon_cmd($vmid, 'query-spice');
943340a6
DM
4171
4172 return $res->{'tls-port'} || $res->{'port'} || die "no spice port\n";
1011b570
DM
4173}
4174
86fdcfb2
DA
4175sub vm_devices_list {
4176 my ($vmid) = @_;
4177
0a13e08e 4178 my $res = mon_cmd($vmid, 'query-pci');
f721624b 4179 my $devices_to_check = [];
ceea9078
DM
4180 my $devices = {};
4181 foreach my $pcibus (@$res) {
f721624b
DC
4182 push @$devices_to_check, @{$pcibus->{devices}},
4183 }
4184
4185 while (@$devices_to_check) {
4186 my $to_check = [];
4187 for my $d (@$devices_to_check) {
4188 $devices->{$d->{'qdev_id'}} = 1 if $d->{'qdev_id'};
b3a3e929 4189 next if !$d->{'pci_bridge'} || !$d->{'pci_bridge'}->{devices};
f721624b
DC
4190
4191 $devices->{$d->{'qdev_id'}} += scalar(@{$d->{'pci_bridge'}->{devices}});
4192 push @$to_check, @{$d->{'pci_bridge'}->{devices}};
f78cc802 4193 }
f721624b 4194 $devices_to_check = $to_check;
f78cc802
AD
4195 }
4196
0a13e08e 4197 my $resblock = mon_cmd($vmid, 'query-block');
f78cc802
AD
4198 foreach my $block (@$resblock) {
4199 if($block->{device} =~ m/^drive-(\S+)/){
4200 $devices->{$1} = 1;
1dc4f496
DM
4201 }
4202 }
86fdcfb2 4203
0a13e08e 4204 my $resmice = mon_cmd($vmid, 'query-mice');
3d7389fe
DM
4205 foreach my $mice (@$resmice) {
4206 if ($mice->{name} eq 'QEMU HID Tablet') {
4207 $devices->{tablet} = 1;
4208 last;
4209 }
4210 }
4211
deb091c5
DC
4212 # for usb devices there is no query-usb
4213 # but we can iterate over the entries in
4214 # qom-list path=/machine/peripheral
0a13e08e 4215 my $resperipheral = mon_cmd($vmid, 'qom-list', path => '/machine/peripheral');
deb091c5 4216 foreach my $per (@$resperipheral) {
c60cad61 4217 if ($per->{name} =~ m/^usb(?:redirdev)?\d+$/) {
deb091c5
DC
4218 $devices->{$per->{name}} = 1;
4219 }
4220 }
4221
1dc4f496 4222 return $devices;
86fdcfb2
DA
4223}
4224
ec21aa11 4225sub vm_deviceplug {
d559309f 4226 my ($storecfg, $conf, $vmid, $deviceid, $device, $arch, $machine_type) = @_;
ae57f6b3 4227
3392d6ca 4228 my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf);
db656e5f 4229
95d6343b
DA
4230 my $devices_list = vm_devices_list($vmid);
4231 return 1 if defined($devices_list->{$deviceid});
4232
4df98f2f
TL
4233 # add PCI bridge if we need it for the device
4234 qemu_add_pci_bridge($storecfg, $conf, $vmid, $deviceid, $arch, $machine_type);
fee46675 4235
3d7389fe 4236 if ($deviceid eq 'tablet') {
d559309f 4237 qemu_deviceadd($vmid, print_tabletdevice_full($conf, $arch));
d559309f 4238 } elsif ($deviceid eq 'keyboard') {
d559309f 4239 qemu_deviceadd($vmid, print_keyboarddevice_full($conf, $arch));
c60cad61
DC
4240 } elsif ($deviceid =~ m/^usbredirdev(\d+)$/) {
4241 my $id = $1;
4242 qemu_spice_usbredir_chardev_add($vmid, "usbredirchardev$id");
4243 qemu_deviceadd($vmid, PVE::QemuServer::USB::print_spice_usbdevice($id, "xhci", $id + 1));
4eb68604 4244 } elsif ($deviceid =~ m/^usb(\d+)$/) {
c60cad61 4245 qemu_deviceadd($vmid, PVE::QemuServer::USB::print_usbdevice_full($conf, $deviceid, $device, {}, $1 + 1));
fee46675 4246 } elsif ($deviceid =~ m/^(virtio)(\d+)$/) {
22de899a
AD
4247 qemu_iothread_add($vmid, $deviceid, $device);
4248
3326ae19
TL
4249 qemu_driveadd($storecfg, $vmid, $device);
4250 my $devicefull = print_drivedevice_full($storecfg, $conf, $vmid, $device, undef, $arch, $machine_type);
fee46675 4251
3326ae19 4252 qemu_deviceadd($vmid, $devicefull);
fee46675
DM
4253 eval { qemu_deviceaddverify($vmid, $deviceid); };
4254 if (my $err = $@) {
63c2da2f
DM
4255 eval { qemu_drivedel($vmid, $deviceid); };
4256 warn $@ if $@;
fee46675 4257 die $err;
5e5dcb73 4258 }
2733141c 4259 } elsif ($deviceid =~ m/^(virtioscsi|scsihw)(\d+)$/) {
3326ae19
TL
4260 my $scsihw = defined($conf->{scsihw}) ? $conf->{scsihw} : "lsi";
4261 my $pciaddr = print_pci_addr($deviceid, undef, $arch, $machine_type);
a1b7d579 4262 my $scsihw_type = $scsihw eq 'virtio-scsi-single' ? "virtio-scsi-pci" : $scsihw;
2733141c 4263
3326ae19 4264 my $devicefull = "$scsihw_type,id=$deviceid$pciaddr";
fee46675 4265
fc8b40fd
AD
4266 if($deviceid =~ m/^virtioscsi(\d+)$/ && $device->{iothread}) {
4267 qemu_iothread_add($vmid, $deviceid, $device);
4268 $devicefull .= ",iothread=iothread-$deviceid";
4269 }
4270
6e11f143
AD
4271 if($deviceid =~ m/^virtioscsi(\d+)$/ && $device->{queues}) {
4272 $devicefull .= ",num_queues=$device->{queues}";
4273 }
4274
3326ae19
TL
4275 qemu_deviceadd($vmid, $devicefull);
4276 qemu_deviceaddverify($vmid, $deviceid);
fee46675 4277 } elsif ($deviceid =~ m/^(scsi)(\d+)$/) {
d559309f 4278 qemu_findorcreatescsihw($storecfg,$conf, $vmid, $device, $arch, $machine_type);
fee46675 4279 qemu_driveadd($storecfg, $vmid, $device);
a1b7d579 4280
acfc6ef8 4281 my $devicefull = print_drivedevice_full($storecfg, $conf, $vmid, $device, undef, $arch, $machine_type);
fee46675
DM
4282 eval { qemu_deviceadd($vmid, $devicefull); };
4283 if (my $err = $@) {
63c2da2f
DM
4284 eval { qemu_drivedel($vmid, $deviceid); };
4285 warn $@ if $@;
fee46675 4286 die $err;
a4f091a0 4287 }
fee46675 4288 } elsif ($deviceid =~ m/^(net)(\d+)$/) {
d1c1af4b 4289 return if !qemu_netdevadd($vmid, $conf, $arch, $device, $deviceid);
8718099c 4290
3392d6ca 4291 my $machine_type = PVE::QemuServer::Machine::qemu_machine_pxe($vmid, $conf);
0c03a390 4292 my $machine_version = PVE::QemuServer::Machine::extract_version($machine_type);
95d3be58
DC
4293 my $use_old_bios_files = undef;
4294 ($use_old_bios_files, $machine_type) = qemu_use_old_bios_files($machine_type);
8718099c 4295
4df98f2f 4296 my $netdevicefull = print_netdevice_full(
0c03a390 4297 $vmid, $conf, $device, $deviceid, undef, $use_old_bios_files, $arch, $machine_type, $machine_version);
95d3be58 4298 qemu_deviceadd($vmid, $netdevicefull);
79046fd1
DC
4299 eval {
4300 qemu_deviceaddverify($vmid, $deviceid);
4301 qemu_set_link_status($vmid, $deviceid, !$device->{link_down});
4302 };
fee46675
DM
4303 if (my $err = $@) {
4304 eval { qemu_netdevdel($vmid, $deviceid); };
4305 warn $@ if $@;
4306 die $err;
95d3be58 4307 }
fee46675 4308 } elsif (!$q35 && $deviceid =~ m/^(pci\.)(\d+)$/) {
40f28a9f 4309 my $bridgeid = $2;
d559309f 4310 my $pciaddr = print_pci_addr($deviceid, undef, $arch, $machine_type);
40f28a9f 4311 my $devicefull = "pci-bridge,id=pci.$bridgeid,chassis_nr=$bridgeid$pciaddr";
a1b7d579 4312
40f28a9f 4313 qemu_deviceadd($vmid, $devicefull);
fee46675 4314 qemu_deviceaddverify($vmid, $deviceid);
fee46675 4315 } else {
a1b7d579 4316 die "can't hotplug device '$deviceid'\n";
40f28a9f
AD
4317 }
4318
5e5dcb73 4319 return 1;
a4dea331
DA
4320}
4321
3eec5767 4322# fixme: this should raise exceptions on error!
ec21aa11 4323sub vm_deviceunplug {
f19d1c47 4324 my ($vmid, $conf, $deviceid) = @_;
873c2d69 4325
95d6343b
DA
4326 my $devices_list = vm_devices_list($vmid);
4327 return 1 if !defined($devices_list->{$deviceid});
4328
2141a802
SR
4329 my $bootdisks = PVE::QemuServer::Drive::get_bootdisks($conf);
4330 die "can't unplug bootdisk '$deviceid'\n" if grep {$_ eq $deviceid} @$bootdisks;
63c2da2f 4331
c60cad61 4332 if ($deviceid eq 'tablet' || $deviceid eq 'keyboard' || $deviceid eq 'xhci') {
3d7389fe 4333 qemu_devicedel($vmid, $deviceid);
c60cad61
DC
4334 } elsif ($deviceid =~ m/^usbredirdev\d+$/) {
4335 qemu_devicedel($vmid, $deviceid);
4336 qemu_devicedelverify($vmid, $deviceid);
4eb68604 4337 } elsif ($deviceid =~ m/^usb\d+$/) {
c60cad61
DC
4338 qemu_devicedel($vmid, $deviceid);
4339 qemu_devicedelverify($vmid, $deviceid);
63c2da2f 4340 } elsif ($deviceid =~ m/^(virtio)(\d+)$/) {
9a66c311 4341 my $device = parse_drive($deviceid, $conf->{$deviceid});
f19d1c47 4342
a8d0fec3
TL
4343 qemu_devicedel($vmid, $deviceid);
4344 qemu_devicedelverify($vmid, $deviceid);
4345 qemu_drivedel($vmid, $deviceid);
9a66c311 4346 qemu_iothread_del($vmid, $deviceid, $device);
2733141c 4347 } elsif ($deviceid =~ m/^(virtioscsi|scsihw)(\d+)$/) {
63c2da2f 4348 qemu_devicedel($vmid, $deviceid);
8ce30dde 4349 qemu_devicedelverify($vmid, $deviceid);
63c2da2f 4350 } elsif ($deviceid =~ m/^(scsi)(\d+)$/) {
9a66c311 4351 my $device = parse_drive($deviceid, $conf->{$deviceid});
cfc817c7 4352
a8d0fec3 4353 qemu_devicedel($vmid, $deviceid);
52b361af 4354 qemu_devicedelverify($vmid, $deviceid);
a8d0fec3 4355 qemu_drivedel($vmid, $deviceid);
a1b7d579 4356 qemu_deletescsihw($conf, $vmid, $deviceid);
8ce30dde 4357
9a66c311
FG
4358 qemu_iothread_del($vmid, "virtioscsi$device->{index}", $device)
4359 if $conf->{scsihw} && ($conf->{scsihw} eq 'virtio-scsi-single');
63c2da2f 4360 } elsif ($deviceid =~ m/^(net)(\d+)$/) {
a8d0fec3
TL
4361 qemu_devicedel($vmid, $deviceid);
4362 qemu_devicedelverify($vmid, $deviceid);
4363 qemu_netdevdel($vmid, $deviceid);
63c2da2f
DM
4364 } else {
4365 die "can't unplug device '$deviceid'\n";
2630d2a9
DA
4366 }
4367
5e5dcb73
DA
4368 return 1;
4369}
4370
c60cad61
DC
4371sub qemu_spice_usbredir_chardev_add {
4372 my ($vmid, $id) = @_;
4373
4374 mon_cmd($vmid, "chardev-add" , (
4375 id => $id,
4376 backend => {
4377 type => 'spicevmc',
4378 data => {
4379 type => "usbredir",
4380 },
4381 },
4382 ));
4383}
4384
22de899a 4385sub qemu_iothread_add {
a8d0fec3 4386 my ($vmid, $deviceid, $device) = @_;
22de899a
AD
4387
4388 if ($device->{iothread}) {
4389 my $iothreads = vm_iothreads_list($vmid);
4390 qemu_objectadd($vmid, "iothread-$deviceid", "iothread") if !$iothreads->{"iothread-$deviceid"};
4391 }
4392}
4393
4394sub qemu_iothread_del {
a8d0fec3 4395 my ($vmid, $deviceid, $device) = @_;
22de899a 4396
22de899a
AD
4397 if ($device->{iothread}) {
4398 my $iothreads = vm_iothreads_list($vmid);
4399 qemu_objectdel($vmid, "iothread-$deviceid") if $iothreads->{"iothread-$deviceid"};
4400 }
4401}
4402
5e5dcb73 4403sub qemu_driveadd {
fee46675 4404 my ($storecfg, $vmid, $device) = @_;
5e5dcb73 4405
6d5673c3
SR
4406 my $kvmver = get_running_qemu_version($vmid);
4407 my $io_uring = min_version($kvmver, 6, 0);
4408 my $drive = print_drive_commandline_full($storecfg, $vmid, $device, undef, $io_uring);
7a69fc3c 4409 $drive =~ s/\\/\\\\/g;
0a13e08e 4410 my $ret = PVE::QemuServer::Monitor::hmp_cmd($vmid, "drive_add auto \"$drive\"");
fee46675 4411
5e5dcb73 4412 # If the command succeeds qemu prints: "OK"
fee46675
DM
4413 return 1 if $ret =~ m/OK/s;
4414
4415 die "adding drive failed: $ret\n";
5e5dcb73 4416}
afdb31d5 4417
5e5dcb73 4418sub qemu_drivedel {
a8d0fec3 4419 my ($vmid, $deviceid) = @_;
873c2d69 4420
0a13e08e 4421 my $ret = PVE::QemuServer::Monitor::hmp_cmd($vmid, "drive_del drive-$deviceid");
5e5dcb73 4422 $ret =~ s/^\s+//;
a1b7d579 4423
63c2da2f 4424 return 1 if $ret eq "";
a1b7d579 4425
63c2da2f 4426 # NB: device not found errors mean the drive was auto-deleted and we ignore the error
a1b7d579
DM
4427 return 1 if $ret =~ m/Device \'.*?\' not found/s;
4428
63c2da2f 4429 die "deleting drive $deviceid failed : $ret\n";
5e5dcb73 4430}
f19d1c47 4431
5e5dcb73 4432sub qemu_deviceaddverify {
fee46675 4433 my ($vmid, $deviceid) = @_;
873c2d69 4434
5e5dcb73
DA
4435 for (my $i = 0; $i <= 5; $i++) {
4436 my $devices_list = vm_devices_list($vmid);
4437 return 1 if defined($devices_list->{$deviceid});
4438 sleep 1;
afdb31d5 4439 }
fee46675
DM
4440
4441 die "error on hotplug device '$deviceid'\n";
5e5dcb73 4442}
afdb31d5 4443
5e5dcb73
DA
4444
4445sub qemu_devicedelverify {
63c2da2f
DM
4446 my ($vmid, $deviceid) = @_;
4447
a1b7d579 4448 # need to verify that the device is correctly removed as device_del
63c2da2f 4449 # is async and empty return is not reliable
5e5dcb73 4450
5e5dcb73
DA
4451 for (my $i = 0; $i <= 5; $i++) {
4452 my $devices_list = vm_devices_list($vmid);
4453 return 1 if !defined($devices_list->{$deviceid});
4454 sleep 1;
afdb31d5 4455 }
63c2da2f
DM
4456
4457 die "error on hot-unplugging device '$deviceid'\n";
873c2d69
DA
4458}
4459
cdd20088 4460sub qemu_findorcreatescsihw {
d559309f 4461 my ($storecfg, $conf, $vmid, $device, $arch, $machine_type) = @_;
cfc817c7 4462
ee034f5c 4463 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $device);
2733141c
AD
4464
4465 my $scsihwid="$controller_prefix$controller";
cfc817c7
DA
4466 my $devices_list = vm_devices_list($vmid);
4467
a8d0fec3 4468 if (!defined($devices_list->{$scsihwid})) {
d559309f 4469 vm_deviceplug($storecfg, $conf, $vmid, $scsihwid, $device, $arch, $machine_type);
cfc817c7 4470 }
fee46675 4471
cfc817c7
DA
4472 return 1;
4473}
4474
8ce30dde
AD
4475sub qemu_deletescsihw {
4476 my ($conf, $vmid, $opt) = @_;
4477
4478 my $device = parse_drive($opt, $conf->{$opt});
4479
a1511b3c 4480 if ($conf->{scsihw} && ($conf->{scsihw} eq 'virtio-scsi-single')) {
2733141c
AD
4481 vm_deviceunplug($vmid, $conf, "virtioscsi$device->{index}");
4482 return 1;
4483 }
4484
ee034f5c 4485 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $device);
8ce30dde
AD
4486
4487 my $devices_list = vm_devices_list($vmid);
4488 foreach my $opt (keys %{$devices_list}) {
e0fd2b2f
FE
4489 if (is_valid_drivename($opt)) {
4490 my $drive = parse_drive($opt, $conf->{$opt});
a8d0fec3 4491 if ($drive->{interface} eq 'scsi' && $drive->{index} < (($maxdev-1)*($controller+1))) {
8ce30dde
AD
4492 return 1;
4493 }
4494 }
4495 }
4496
4497 my $scsihwid="scsihw$controller";
4498
4499 vm_deviceunplug($vmid, $conf, $scsihwid);
4500
4501 return 1;
4502}
4503
281fedb3 4504sub qemu_add_pci_bridge {
d559309f 4505 my ($storecfg, $conf, $vmid, $device, $arch, $machine_type) = @_;
40f28a9f
AD
4506
4507 my $bridges = {};
281fedb3
DM
4508
4509 my $bridgeid;
4510
d559309f 4511 print_pci_addr($device, $bridges, $arch, $machine_type);
40f28a9f
AD
4512
4513 while (my ($k, $v) = each %$bridges) {
4514 $bridgeid = $k;
4515 }
fee46675 4516 return 1 if !defined($bridgeid) || $bridgeid < 1;
281fedb3 4517
40f28a9f
AD
4518 my $bridge = "pci.$bridgeid";
4519 my $devices_list = vm_devices_list($vmid);
4520
281fedb3 4521 if (!defined($devices_list->{$bridge})) {
d559309f 4522 vm_deviceplug($storecfg, $conf, $vmid, $bridge, $arch, $machine_type);
40f28a9f 4523 }
281fedb3 4524
40f28a9f
AD
4525 return 1;
4526}
4527
25088687
DM
4528sub qemu_set_link_status {
4529 my ($vmid, $device, $up) = @_;
4530
0a13e08e 4531 mon_cmd($vmid, "set_link", name => $device,
25088687
DM
4532 up => $up ? JSON::true : JSON::false);
4533}
4534
2630d2a9 4535sub qemu_netdevadd {
d559309f 4536 my ($vmid, $conf, $arch, $device, $deviceid) = @_;
2630d2a9 4537
d559309f 4538 my $netdev = print_netdev_full($vmid, $conf, $arch, $device, $deviceid, 1);
73aa03b8 4539 my %options = split(/[=,]/, $netdev);
2630d2a9 4540
bf5aef9b
DC
4541 if (defined(my $vhost = $options{vhost})) {
4542 $options{vhost} = JSON::boolean(PVE::JSONSchema::parse_boolean($vhost));
4543 }
4544
4545 if (defined(my $queues = $options{queues})) {
4546 $options{queues} = $queues + 0;
4547 }
4548
0a13e08e 4549 mon_cmd($vmid, "netdev_add", %options);
73aa03b8 4550 return 1;
2630d2a9
DA
4551}
4552
4553sub qemu_netdevdel {
4554 my ($vmid, $deviceid) = @_;
4555
0a13e08e 4556 mon_cmd($vmid, "netdev_del", id => $deviceid);
2630d2a9
DA
4557}
4558
16521d63 4559sub qemu_usb_hotplug {
d559309f 4560 my ($storecfg, $conf, $vmid, $deviceid, $device, $arch, $machine_type) = @_;
16521d63
DC
4561
4562 return if !$device;
4563
4564 # remove the old one first
4565 vm_deviceunplug($vmid, $conf, $deviceid);
4566
4567 # check if xhci controller is necessary and available
c60cad61 4568 my $devicelist = vm_devices_list($vmid);
16521d63 4569
c60cad61
DC
4570 if (!$devicelist->{xhci}) {
4571 my $pciaddr = print_pci_addr("xhci", undef, $arch, $machine_type);
4572 qemu_deviceadd($vmid, PVE::QemuServer::USB::print_qemu_xhci_controller($pciaddr));
16521d63 4573 }
c60cad61 4574
16521d63 4575 # add the new one
0cf8d56c 4576 vm_deviceplug($storecfg, $conf, $vmid, $deviceid, $device, $arch, $machine_type);
16521d63
DC
4577}
4578
838776ab 4579sub qemu_cpu_hotplug {
8edc9c08 4580 my ($vmid, $conf, $vcpus) = @_;
838776ab 4581
3392d6ca 4582 my $machine_type = PVE::QemuServer::Machine::get_current_qemu_machine($vmid);
1e881b75 4583
8edc9c08
AD
4584 my $sockets = 1;
4585 $sockets = $conf->{smp} if $conf->{smp}; # old style - no longer iused
4586 $sockets = $conf->{sockets} if $conf->{sockets};
4587 my $cores = $conf->{cores} || 1;
4588 my $maxcpus = $sockets * $cores;
838776ab 4589
8edc9c08 4590 $vcpus = $maxcpus if !$vcpus;
3a11fadb 4591
8edc9c08
AD
4592 die "you can't add more vcpus than maxcpus\n"
4593 if $vcpus > $maxcpus;
3a11fadb 4594
8edc9c08 4595 my $currentvcpus = $conf->{vcpus} || $maxcpus;
1e881b75 4596
eba3e64d 4597 if ($vcpus < $currentvcpus) {
1e881b75 4598
2ea5fb7e 4599 if (PVE::QemuServer::Machine::machine_version($machine_type, 2, 7)) {
1e881b75
AD
4600
4601 for (my $i = $currentvcpus; $i > $vcpus; $i--) {
4602 qemu_devicedel($vmid, "cpu$i");
4603 my $retry = 0;
4604 my $currentrunningvcpus = undef;
4605 while (1) {
65af8c31 4606 $currentrunningvcpus = mon_cmd($vmid, "query-cpus-fast");
1e881b75 4607 last if scalar(@{$currentrunningvcpus}) == $i-1;
961af8a3 4608 raise_param_exc({ vcpus => "error unplugging cpu$i" }) if $retry > 5;
1e881b75
AD
4609 $retry++;
4610 sleep 1;
4611 }
4612 #update conf after each succesfull cpu unplug
4613 $conf->{vcpus} = scalar(@{$currentrunningvcpus});
4614 PVE::QemuConfig->write_config($vmid, $conf);
4615 }
4616 } else {
961af8a3 4617 die "cpu hot-unplugging requires qemu version 2.7 or higher\n";
1e881b75
AD
4618 }
4619
4620 return;
4621 }
838776ab 4622
65af8c31 4623 my $currentrunningvcpus = mon_cmd($vmid, "query-cpus-fast");
961af8a3 4624 die "vcpus in running vm does not match its configuration\n"
8edc9c08 4625 if scalar(@{$currentrunningvcpus}) != $currentvcpus;
838776ab 4626
2ea5fb7e 4627 if (PVE::QemuServer::Machine::machine_version($machine_type, 2, 7)) {
eba3e64d
AD
4628
4629 for (my $i = $currentvcpus+1; $i <= $vcpus; $i++) {
4630 my $cpustr = print_cpu_device($conf, $i);
4631 qemu_deviceadd($vmid, $cpustr);
4632
4633 my $retry = 0;
4634 my $currentrunningvcpus = undef;
4635 while (1) {
65af8c31 4636 $currentrunningvcpus = mon_cmd($vmid, "query-cpus-fast");
eba3e64d 4637 last if scalar(@{$currentrunningvcpus}) == $i;
961af8a3 4638 raise_param_exc({ vcpus => "error hotplugging cpu$i" }) if $retry > 10;
eba3e64d
AD
4639 sleep 1;
4640 $retry++;
4641 }
4642 #update conf after each succesfull cpu hotplug
4643 $conf->{vcpus} = scalar(@{$currentrunningvcpus});
4644 PVE::QemuConfig->write_config($vmid, $conf);
4645 }
4646 } else {
4647
4648 for (my $i = $currentvcpus; $i < $vcpus; $i++) {
0a13e08e 4649 mon_cmd($vmid, "cpu-add", id => int($i));
eba3e64d 4650 }
838776ab
AD
4651 }
4652}
4653
affd2f88 4654sub qemu_block_set_io_throttle {
277ca170
WB
4655 my ($vmid, $deviceid,
4656 $bps, $bps_rd, $bps_wr, $iops, $iops_rd, $iops_wr,
9196a8ec
WB
4657 $bps_max, $bps_rd_max, $bps_wr_max, $iops_max, $iops_rd_max, $iops_wr_max,
4658 $bps_max_length, $bps_rd_max_length, $bps_wr_max_length,
4659 $iops_max_length, $iops_rd_max_length, $iops_wr_max_length) = @_;
affd2f88 4660
f3f323a3
AD
4661 return if !check_running($vmid) ;
4662
0a13e08e 4663 mon_cmd($vmid, "block_set_io_throttle", device => $deviceid,
277ca170
WB
4664 bps => int($bps),
4665 bps_rd => int($bps_rd),
4666 bps_wr => int($bps_wr),
4667 iops => int($iops),
4668 iops_rd => int($iops_rd),
4669 iops_wr => int($iops_wr),
4670 bps_max => int($bps_max),
4671 bps_rd_max => int($bps_rd_max),
4672 bps_wr_max => int($bps_wr_max),
4673 iops_max => int($iops_max),
4674 iops_rd_max => int($iops_rd_max),
9196a8ec
WB
4675 iops_wr_max => int($iops_wr_max),
4676 bps_max_length => int($bps_max_length),
4677 bps_rd_max_length => int($bps_rd_max_length),
4678 bps_wr_max_length => int($bps_wr_max_length),
4679 iops_max_length => int($iops_max_length),
4680 iops_rd_max_length => int($iops_rd_max_length),
4681 iops_wr_max_length => int($iops_wr_max_length),
277ca170 4682 );
f3f323a3 4683
affd2f88
AD
4684}
4685
c1175c92
AD
4686sub qemu_block_resize {
4687 my ($vmid, $deviceid, $storecfg, $volid, $size) = @_;
4688
ed221350 4689 my $running = check_running($vmid);
c1175c92 4690
2e4357c5 4691 PVE::Storage::volume_resize($storecfg, $volid, $size, $running);
c1175c92
AD
4692
4693 return if !$running;
4694
375db731
FE
4695 my $padding = (1024 - $size % 1024) % 1024;
4696 $size = $size + $padding;
4697
190c8461
SR
4698 mon_cmd(
4699 $vmid,
4700 "block_resize",
4701 device => $deviceid,
4702 size => int($size),
4703 timeout => 60,
4704 );
c1175c92
AD
4705}
4706
1ab0057c
AD
4707sub qemu_volume_snapshot {
4708 my ($vmid, $deviceid, $storecfg, $volid, $snap) = @_;
4709
ed221350 4710 my $running = check_running($vmid);
1ab0057c 4711
9d83932d 4712 if ($running && do_snapshots_with_qemu($storecfg, $volid, $deviceid)) {
0a13e08e 4713 mon_cmd($vmid, 'blockdev-snapshot-internal-sync', device => $deviceid, name => $snap);
e5eaa028
WL
4714 } else {
4715 PVE::Storage::volume_snapshot($storecfg, $volid, $snap);
4716 }
1ab0057c
AD
4717}
4718
fc46aff9
AD
4719sub qemu_volume_snapshot_delete {
4720 my ($vmid, $deviceid, $storecfg, $volid, $snap) = @_;
4721
ed221350 4722 my $running = check_running($vmid);
fc46aff9 4723
a2f1554b
AD
4724 if($running) {
4725
4726 $running = undef;
4727 my $conf = PVE::QemuConfig->load_config($vmid);
912792e2 4728 PVE::QemuConfig->foreach_volume($conf, sub {
a2f1554b
AD
4729 my ($ds, $drive) = @_;
4730 $running = 1 if $drive->{file} eq $volid;
4731 });
4732 }
4733
9d83932d 4734 if ($running && do_snapshots_with_qemu($storecfg, $volid, $deviceid)) {
0a13e08e 4735 mon_cmd($vmid, 'blockdev-snapshot-delete-internal-sync', device => $deviceid, name => $snap);
1ef7592f
AD
4736 } else {
4737 PVE::Storage::volume_snapshot_delete($storecfg, $volid, $snap, $running);
4738 }
fc46aff9
AD
4739}
4740
264e519f 4741sub set_migration_caps {
27a5be53 4742 my ($vmid, $savevm) = @_;
a89fded1 4743
acc10e51
SR
4744 my $qemu_support = eval { mon_cmd($vmid, "query-proxmox-support") };
4745
27a5be53
SR
4746 my $bitmap_prop = $savevm ? 'pbs-dirty-bitmap-savevm' : 'pbs-dirty-bitmap-migration';
4747 my $dirty_bitmaps = $qemu_support->{$bitmap_prop} ? 1 : 0;
4748
8b8345f3 4749 my $cap_ref = [];
a89fded1
AD
4750
4751 my $enabled_cap = {
8b8345f3 4752 "auto-converge" => 1,
0b0a47e8 4753 "xbzrle" => 1,
8b8345f3
DM
4754 "x-rdma-pin-all" => 0,
4755 "zero-blocks" => 0,
acc10e51 4756 "compress" => 0,
27a5be53 4757 "dirty-bitmaps" => $dirty_bitmaps,
a89fded1
AD
4758 };
4759
0a13e08e 4760 my $supported_capabilities = mon_cmd($vmid, "query-migrate-capabilities");
a89fded1 4761
8b8345f3 4762 for my $supported_capability (@$supported_capabilities) {
b463a3ce
SP
4763 push @$cap_ref, {
4764 capability => $supported_capability->{capability},
22430fa2
DM
4765 state => $enabled_cap->{$supported_capability->{capability}} ? JSON::true : JSON::false,
4766 };
a89fded1
AD
4767 }
4768
0a13e08e 4769 mon_cmd($vmid, "migrate-set-capabilities", capabilities => $cap_ref);
8b8345f3 4770}
a89fded1 4771
912792e2 4772sub foreach_volid {
0b7a0b78 4773 my ($conf, $func, @param) = @_;
912792e2
FE
4774
4775 my $volhash = {};
4776
4777 my $test_volid = sub {
6328c554 4778 my ($key, $drive, $snapname, $pending) = @_;
912792e2 4779
ae180b8f 4780 my $volid = $drive->{file};
912792e2
FE
4781 return if !$volid;
4782
4783 $volhash->{$volid}->{cdrom} //= 1;
ae180b8f 4784 $volhash->{$volid}->{cdrom} = 0 if !drive_is_cdrom($drive);
912792e2 4785
ae180b8f 4786 my $replicate = $drive->{replicate} // 1;
912792e2
FE
4787 $volhash->{$volid}->{replicate} //= 0;
4788 $volhash->{$volid}->{replicate} = 1 if $replicate;
4789
4790 $volhash->{$volid}->{shared} //= 0;
ae180b8f 4791 $volhash->{$volid}->{shared} = 1 if $drive->{shared};
912792e2 4792
6e9c4929
AL
4793 $volhash->{$volid}->{is_unused} //= 0;
4794 $volhash->{$volid}->{is_unused} = 1 if $key =~ /^unused\d+$/;
4795
4796 $volhash->{$volid}->{is_attached} //= 0;
4797 $volhash->{$volid}->{is_attached} = 1
219719aa 4798 if !$volhash->{$volid}->{is_unused} && !defined($snapname) && !$pending;
912792e2
FE
4799
4800 $volhash->{$volid}->{referenced_in_snapshot}->{$snapname} = 1
4801 if defined($snapname);
ae180b8f 4802
219719aa 4803 $volhash->{$volid}->{referenced_in_pending} = 1 if $pending;
6328c554 4804
ae180b8f
FE
4805 my $size = $drive->{size};
4806 $volhash->{$volid}->{size} //= $size if $size;
4807
4808 $volhash->{$volid}->{is_vmstate} //= 0;
4809 $volhash->{$volid}->{is_vmstate} = 1 if $key eq 'vmstate';
4810
f9dde219
SR
4811 $volhash->{$volid}->{is_tpmstate} //= 0;
4812 $volhash->{$volid}->{is_tpmstate} = 1 if $key eq 'tpmstate0';
4813
a6be63ac 4814 $volhash->{$volid}->{drivename} = $key if is_valid_drivename($key);
912792e2
FE
4815 };
4816
ae180b8f
FE
4817 my $include_opts = {
4818 extra_keys => ['vmstate'],
4819 include_unused => 1,
4820 };
4821
0b953b8e 4822 PVE::QemuConfig->foreach_volume_full($conf, $include_opts, $test_volid);
6328c554 4823
0b7a0b78
AL
4824 PVE::QemuConfig->foreach_volume_full($conf->{pending}, $include_opts, $test_volid, undef, 1)
4825 if defined($conf->{pending}) && $conf->{pending}->%*;
6328c554 4826
912792e2
FE
4827 foreach my $snapname (keys %{$conf->{snapshots}}) {
4828 my $snap = $conf->{snapshots}->{$snapname};
0b953b8e 4829 PVE::QemuConfig->foreach_volume_full($snap, $include_opts, $test_volid, $snapname);
912792e2
FE
4830 }
4831
4832 foreach my $volid (keys %$volhash) {
4833 &$func($volid, $volhash->{$volid}, @param);
4834 }
4835}
4836
81d95ae1 4837my $fast_plug_option = {
f68910a0
FE
4838 'description' => 1,
4839 'hookscript' => 1,
7498eb64 4840 'lock' => 1,
d62bdac5
FE
4841 'migrate_downtime' => 1,
4842 'migrate_speed' => 1,
81d95ae1 4843 'name' => 1,
a1b7d579 4844 'onboot' => 1,
f68910a0 4845 'protection' => 1,
81d95ae1
DM
4846 'shares' => 1,
4847 'startup' => 1,
b8e7068a 4848 'tags' => 1,
f68910a0 4849 'vmstatestorage' => 1,
81d95ae1
DM
4850};
4851
71d9006b
AD
4852for my $opt (keys %$confdesc_cloudinit) {
4853 $fast_plug_option->{$opt} = 1;
4854};
4855
3a11fadb
DM
4856# hotplug changes in [PENDING]
4857# $selection hash can be used to only apply specified options, for
4858# example: { cores => 1 } (only apply changed 'cores')
4859# $errors ref is used to return error messages
c427973b 4860sub vmconfig_hotplug_pending {
3a11fadb 4861 my ($vmid, $conf, $storecfg, $selection, $errors) = @_;
c427973b 4862
8e90138a 4863 my $defaults = load_defaults();
045749f2
TL
4864 my $arch = get_vm_arch($conf);
4865 my $machine_type = get_vm_machine($conf, undef, $arch);
c427973b
DM
4866
4867 # commit values which do not have any impact on running VM first
3a11fadb
DM
4868 # Note: those option cannot raise errors, we we do not care about
4869 # $selection and always apply them.
4870
4871 my $add_error = sub {
4872 my ($opt, $msg) = @_;
4873 $errors->{$opt} = "hotplug problem - $msg";
4874 };
c427973b 4875
f16cf6c3
WB
4876 my $cloudinit_pending_properties = PVE::QemuServer::cloudinit_pending_properties();
4877
4878 my $cloudinit_record_changed = sub {
4879 my ($conf, $opt, $old, $new) = @_;
4880 return if !$cloudinit_pending_properties->{$opt};
4881
4882 my $ci = ($conf->{cloudinit} //= {});
4883
4884 my $recorded = $ci->{$opt};
a5409851
WB
4885 my %added = map { $_ => 1 } PVE::Tools::split_list(delete($ci->{added}) // '');
4886
4887 if (defined($new)) {
4888 if (defined($old)) {
4889 # an existing value is being modified
4890 if (defined($recorded)) {
4891 # the value was already not in sync
4892 if ($new eq $recorded) {
4893 # a value is being reverted to the cloud-init state:
4894 delete $ci->{$opt};
4895 delete $added{$opt};
4896 } else {
4897 # the value was changed multiple times, do nothing
4898 }
4899 } elsif ($added{$opt}) {
4900 # the value had been marked as added and is being changed, do nothing
4901 } else {
4902 # the value is new, record it:
4903 $ci->{$opt} = $old;
4904 }
f16cf6c3 4905 } else {
a5409851
WB
4906 # a new value is being added
4907 if (defined($recorded)) {
4908 # it was already not in sync
4909 if ($new eq $recorded) {
4910 # a value is being reverted to the cloud-init state:
4911 delete $ci->{$opt};
4912 delete $added{$opt};
4913 } else {
4914 # the value had temporarily been removed, do nothing
4915 }
4916 } elsif ($added{$opt}) {
4917 # the value had been marked as added already, do nothing
4918 } else {
4919 # the value is new, add it
4920 $added{$opt} = 1;
4921 }
f16cf6c3 4922 }
a5409851
WB
4923 } elsif (!defined($old)) {
4924 # a non-existent value is being removed? ignore...
f16cf6c3 4925 } else {
a5409851
WB
4926 # a value is being deleted
4927 if (defined($recorded)) {
4928 # a value was already recorded, just keep it
4929 } elsif ($added{$opt}) {
4930 # the value was marked as added, remove it
4931 delete $added{$opt};
f16cf6c3 4932 } else {
a5409851
WB
4933 # a previously unrecorded value is being removed, record the old value:
4934 $ci->{$opt} = $old;
f16cf6c3
WB
4935 }
4936 }
a5409851
WB
4937
4938 my $added = join(',', sort keys %added);
4939 $ci->{added} = $added if length($added);
f16cf6c3
WB
4940 };
4941
c427973b
DM
4942 my $changes = 0;
4943 foreach my $opt (keys %{$conf->{pending}}) { # add/change
81d95ae1 4944 if ($fast_plug_option->{$opt}) {
f16cf6c3
WB
4945 my $new = delete $conf->{pending}->{$opt};
4946 $cloudinit_record_changed->($conf, $opt, $conf->{$opt}, $new);
4947 $conf->{$opt} = $new;
c427973b
DM
4948 $changes = 1;
4949 }
4950 }
4951
4952 if ($changes) {
ffda963f 4953 PVE::QemuConfig->write_config($vmid, $conf);
c427973b
DM
4954 }
4955
c60cad61
DC
4956 my $ostype = $conf->{ostype};
4957 my $version = extract_version($machine_type, get_running_qemu_version($vmid));
b3c2bdd1 4958 my $hotplug_features = parse_hotplug_features(defined($conf->{hotplug}) ? $conf->{hotplug} : '1');
c60cad61
DC
4959 my $usb_hotplug = $hotplug_features->{usb}
4960 && min_version($version, 7, 1)
4961 && defined($ostype) && ($ostype eq 'l26' || windows_version($ostype) > 7);
c427973b 4962
5b65b00d 4963 my $cgroup = PVE::QemuServer::CGroup->new($vmid);
98bc3aeb 4964 my $pending_delete_hash = PVE::QemuConfig->parse_pending_delete($conf->{pending}->{delete});
f16cf6c3 4965
d321c4a9 4966 foreach my $opt (sort keys %$pending_delete_hash) {
3a11fadb 4967 next if $selection && !$selection->{$opt};
d321c4a9 4968 my $force = $pending_delete_hash->{$opt}->{force};
3a11fadb 4969 eval {
51a6f637 4970 if ($opt eq 'hotplug') {
d797bb62 4971 die "skip\n" if ($conf->{hotplug} =~ /(cpu|memory)/);
51a6f637 4972 } elsif ($opt eq 'tablet') {
b3c2bdd1 4973 die "skip\n" if !$hotplug_features->{usb};
3a11fadb 4974 if ($defaults->{tablet}) {
d559309f
WB
4975 vm_deviceplug($storecfg, $conf, $vmid, 'tablet', $arch, $machine_type);
4976 vm_deviceplug($storecfg, $conf, $vmid, 'keyboard', $arch, $machine_type)
4977 if $arch eq 'aarch64';
3a11fadb 4978 } else {
d559309f
WB
4979 vm_deviceunplug($vmid, $conf, 'tablet');
4980 vm_deviceunplug($vmid, $conf, 'keyboard') if $arch eq 'aarch64';
3a11fadb 4981 }
c60cad61
DC
4982 } elsif ($opt =~ m/^usb(\d+)$/) {
4983 my $index = $1;
4984 die "skip\n" if !$usb_hotplug;
4985 vm_deviceunplug($vmid, $conf, "usbredirdev$index"); # if it's a spice port
4986 vm_deviceunplug($vmid, $conf, $opt);
8edc9c08 4987 } elsif ($opt eq 'vcpus') {
b3c2bdd1 4988 die "skip\n" if !$hotplug_features->{cpu};
8edc9c08 4989 qemu_cpu_hotplug($vmid, $conf, undef);
9c2f7069 4990 } elsif ($opt eq 'balloon') {
81d95ae1 4991 # enable balloon device is not hotpluggable
75b51053
DC
4992 die "skip\n" if defined($conf->{balloon}) && $conf->{balloon} == 0;
4993 # here we reset the ballooning value to memory
7f8c8087 4994 my $balloon = get_current_memory($conf->{memory});
0a13e08e 4995 mon_cmd($vmid, "balloon", value => $balloon*1024*1024);
81d95ae1
DM
4996 } elsif ($fast_plug_option->{$opt}) {
4997 # do nothing
3eec5767 4998 } elsif ($opt =~ m/^net(\d+)$/) {
b3c2bdd1 4999 die "skip\n" if !$hotplug_features->{network};
3eec5767 5000 vm_deviceunplug($vmid, $conf, $opt);
74479ee9 5001 } elsif (is_valid_drivename($opt)) {
b3c2bdd1 5002 die "skip\n" if !$hotplug_features->{disk} || $opt =~ m/(ide|sata)(\d+)/;
19120f99 5003 vm_deviceunplug($vmid, $conf, $opt);
3dc38fbb 5004 vmconfig_delete_or_detach_drive($vmid, $storecfg, $conf, $opt, $force);
4d3f29ed
AD
5005 } elsif ($opt =~ m/^memory$/) {
5006 die "skip\n" if !$hotplug_features->{memory};
7f8c8087 5007 PVE::QemuServer::Memory::qemu_memory_hotplug($vmid, $conf);
c8effec3 5008 } elsif ($opt eq 'cpuunits') {
0d318453 5009 $cgroup->change_cpu_shares(undef);
58be00f1 5010 } elsif ($opt eq 'cpulimit') {
25de70ae 5011 $cgroup->change_cpu_quota(undef, undef); # reset, cgroup module can better decide values
3d7389fe 5012 } else {
e56beeda 5013 die "skip\n";
3d7389fe 5014 }
3a11fadb
DM
5015 };
5016 if (my $err = $@) {
e56beeda
DM
5017 &$add_error($opt, $err) if $err ne "skip\n";
5018 } else {
f16cf6c3
WB
5019 my $old = delete $conf->{$opt};
5020 $cloudinit_record_changed->($conf, $opt, $old, undef);
98bc3aeb 5021 PVE::QemuConfig->remove_from_pending_delete($conf, $opt);
3d7389fe 5022 }
3d7389fe
DM
5023 }
5024
4b785da1 5025 my $cloudinit_opt;
3d7389fe 5026 foreach my $opt (keys %{$conf->{pending}}) {
3a11fadb 5027 next if $selection && !$selection->{$opt};
3d7389fe 5028 my $value = $conf->{pending}->{$opt};
3a11fadb 5029 eval {
51a6f637
AD
5030 if ($opt eq 'hotplug') {
5031 die "skip\n" if ($value =~ /memory/) || ($value !~ /memory/ && $conf->{hotplug} =~ /memory/);
d797bb62 5032 die "skip\n" if ($value =~ /cpu/) || ($value !~ /cpu/ && $conf->{hotplug} =~ /cpu/);
51a6f637 5033 } elsif ($opt eq 'tablet') {
b3c2bdd1 5034 die "skip\n" if !$hotplug_features->{usb};
3a11fadb 5035 if ($value == 1) {
d559309f
WB
5036 vm_deviceplug($storecfg, $conf, $vmid, 'tablet', $arch, $machine_type);
5037 vm_deviceplug($storecfg, $conf, $vmid, 'keyboard', $arch, $machine_type)
5038 if $arch eq 'aarch64';
3a11fadb 5039 } elsif ($value == 0) {
d559309f
WB
5040 vm_deviceunplug($vmid, $conf, 'tablet');
5041 vm_deviceunplug($vmid, $conf, 'keyboard') if $arch eq 'aarch64';
3a11fadb 5042 }
c60cad61
DC
5043 } elsif ($opt =~ m/^usb(\d+)$/) {
5044 my $index = $1;
5045 die "skip\n" if !$usb_hotplug;
0cf8d56c 5046 my $d = eval { parse_property_string('pve-qm-usb', $value) };
c60cad61 5047 my $id = $opt;
0cf8d56c 5048 if ($d->{host} =~ m/^spice$/i) {
c60cad61
DC
5049 $id = "usbredirdev$index";
5050 }
5051 qemu_usb_hotplug($storecfg, $conf, $vmid, $id, $d, $arch, $machine_type);
8edc9c08 5052 } elsif ($opt eq 'vcpus') {
b3c2bdd1 5053 die "skip\n" if !$hotplug_features->{cpu};
3a11fadb
DM
5054 qemu_cpu_hotplug($vmid, $conf, $value);
5055 } elsif ($opt eq 'balloon') {
81d95ae1 5056 # enable/disable balloning device is not hotpluggable
8fe689e7 5057 my $old_balloon_enabled = !!(!defined($conf->{balloon}) || $conf->{balloon});
a1b7d579 5058 my $new_balloon_enabled = !!(!defined($conf->{pending}->{balloon}) || $conf->{pending}->{balloon});
81d95ae1
DM
5059 die "skip\n" if $old_balloon_enabled != $new_balloon_enabled;
5060
3a11fadb 5061 # allow manual ballooning if shares is set to zero
4cc1efa6 5062 if ((defined($conf->{shares}) && ($conf->{shares} == 0))) {
7f8c8087
AD
5063 my $memory = get_current_memory($conf->{memory});
5064 my $balloon = $conf->{pending}->{balloon} || $memory;
0a13e08e 5065 mon_cmd($vmid, "balloon", value => $balloon*1024*1024);
9c2f7069 5066 }
a1b7d579 5067 } elsif ($opt =~ m/^net(\d+)$/) {
3eec5767 5068 # some changes can be done without hotplug
a1b7d579 5069 vmconfig_update_net($storecfg, $conf, $hotplug_features->{network},
d559309f 5070 $vmid, $opt, $value, $arch, $machine_type);
74479ee9 5071 } elsif (is_valid_drivename($opt)) {
f9dde219 5072 die "skip\n" if $opt eq 'efidisk0' || $opt eq 'tpmstate0';
a05cff86 5073 # some changes can be done without hotplug
9ed7a77c
WB
5074 my $drive = parse_drive($opt, $value);
5075 if (drive_is_cloudinit($drive)) {
4b785da1
WB
5076 $cloudinit_opt = [$opt, $drive];
5077 # apply all the other changes first, then generate the cloudinit disk
5078 die "skip\n";
9ed7a77c 5079 }
b3c2bdd1 5080 vmconfig_update_disk($storecfg, $conf, $hotplug_features->{disk},
9e7bce2c 5081 $vmid, $opt, $value, $arch, $machine_type);
4d3f29ed
AD
5082 } elsif ($opt =~ m/^memory$/) { #dimms
5083 die "skip\n" if !$hotplug_features->{memory};
7f8c8087 5084 $value = PVE::QemuServer::Memory::qemu_memory_hotplug($vmid, $conf, $value);
c8effec3 5085 } elsif ($opt eq 'cpuunits') {
6b7ef5e5 5086 my $new_cpuunits = PVE::CGroup::clamp_cpu_shares($conf->{pending}->{$opt}); #clamp
0d318453 5087 $cgroup->change_cpu_shares($new_cpuunits);
58be00f1 5088 } elsif ($opt eq 'cpulimit') {
c6f773b8 5089 my $cpulimit = $conf->{pending}->{$opt} == 0 ? -1 : int($conf->{pending}->{$opt} * 100000);
5b65b00d 5090 $cgroup->change_cpu_quota($cpulimit, 100000);
74ea2c65
AD
5091 } elsif ($opt eq 'agent') {
5092 vmconfig_update_agent($conf, $opt, $value);
3a11fadb 5093 } else {
e56beeda 5094 die "skip\n"; # skip non-hot-pluggable options
3d7389fe 5095 }
3a11fadb 5096 };
4b785da1
WB
5097 if (my $err = $@) {
5098 &$add_error($opt, $err) if $err ne "skip\n";
5099 } else {
5100 $cloudinit_record_changed->($conf, $opt, $conf->{$opt}, $value);
5101 $conf->{$opt} = $value;
5102 delete $conf->{pending}->{$opt};
5103 }
5104 }
5105
5106 if (defined($cloudinit_opt)) {
5107 my ($opt, $drive) = @$cloudinit_opt;
5108 my $value = $conf->{pending}->{$opt};
5109 eval {
9660e606
WB
5110 my $temp = {%$conf, $opt => $value};
5111 PVE::QemuServer::Cloudinit::apply_cloudinit_config($temp, $vmid);
4b785da1
WB
5112 vmconfig_update_disk($storecfg, $conf, $hotplug_features->{disk},
5113 $vmid, $opt, $value, $arch, $machine_type);
5114 };
3a11fadb 5115 if (my $err = $@) {
e56beeda
DM
5116 &$add_error($opt, $err) if $err ne "skip\n";
5117 } else {
3a11fadb
DM
5118 $conf->{$opt} = $value;
5119 delete $conf->{pending}->{$opt};
3d7389fe 5120 }
3d7389fe 5121 }
c60cad61
DC
5122
5123 # unplug xhci controller if no usb device is left
5124 if ($usb_hotplug) {
5125 my $has_usb = 0;
0cf8d56c 5126 for (my $i = 0; $i < $PVE::QemuServer::USB::MAX_USB_DEVICES; $i++) {
c60cad61
DC
5127 next if !defined($conf->{"usb$i"});
5128 $has_usb = 1;
5129 last;
5130 }
5131 if (!$has_usb) {
5132 vm_deviceunplug($vmid, $conf, 'xhci');
5133 }
5134 }
5135
4df15a03 5136 PVE::QemuConfig->write_config($vmid, $conf);
94ec5e7c 5137
4b785da1
WB
5138 if ($hotplug_features->{cloudinit} && PVE::QemuServer::Cloudinit::has_changes($conf)) {
5139 PVE::QemuServer::vmconfig_update_cloudinit_drive($storecfg, $conf, $vmid);
94ec5e7c 5140 }
c427973b 5141}
055d554d 5142
3dc38fbb
WB
5143sub try_deallocate_drive {
5144 my ($storecfg, $vmid, $conf, $key, $drive, $rpcenv, $authuser, $force) = @_;
5145
5146 if (($force || $key =~ /^unused/) && !drive_is_cdrom($drive, 1)) {
5147 my $volid = $drive->{file};
5148 if (vm_is_volid_owner($storecfg, $vmid, $volid)) {
5149 my $sid = PVE::Storage::parse_volume_id($volid);
5150 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
cee01bcb
WB
5151
5152 # check if the disk is really unused
cee01bcb 5153 die "unable to delete '$volid' - volume is still in use (snapshot?)\n"
e0fd2b2f 5154 if PVE::QemuServer::Drive::is_volume_in_use($storecfg, $conf, $key, $volid);
cee01bcb 5155 PVE::Storage::vdisk_free($storecfg, $volid);
3dc38fbb 5156 return 1;
40b977f3
WL
5157 } else {
5158 # If vm is not owner of this disk remove from config
5159 return 1;
3dc38fbb
WB
5160 }
5161 }
5162
d1c1af4b 5163 return;
3dc38fbb
WB
5164}
5165
5166sub vmconfig_delete_or_detach_drive {
5167 my ($vmid, $storecfg, $conf, $opt, $force) = @_;
5168
5169 my $drive = parse_drive($opt, $conf->{$opt});
5170
5171 my $rpcenv = PVE::RPCEnvironment::get();
5172 my $authuser = $rpcenv->get_user();
5173
5174 if ($force) {
5175 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
5176 try_deallocate_drive($storecfg, $vmid, $conf, $opt, $drive, $rpcenv, $authuser, $force);
5177 } else {
5178 vmconfig_register_unused_drive($storecfg, $vmid, $conf, $drive);
5179 }
5180}
5181
98bc3aeb
OB
5182
5183
055d554d 5184sub vmconfig_apply_pending {
e97bbbb6 5185 my ($vmid, $conf, $storecfg, $errors, $skip_cloud_init) = @_;
eb5e482d 5186
a644de29
OB
5187 return if !scalar(keys %{$conf->{pending}});
5188
eb5e482d
OB
5189 my $add_apply_error = sub {
5190 my ($opt, $msg) = @_;
5191 my $err_msg = "unable to apply pending change $opt : $msg";
5192 $errors->{$opt} = $err_msg;
5193 warn $err_msg;
5194 };
c427973b
DM
5195
5196 # cold plug
055d554d 5197
98bc3aeb 5198 my $pending_delete_hash = PVE::QemuConfig->parse_pending_delete($conf->{pending}->{delete});
d321c4a9 5199 foreach my $opt (sort keys %$pending_delete_hash) {
fb4d1ba2 5200 my $force = $pending_delete_hash->{$opt}->{force};
eb5e482d 5201 eval {
3d48b95a
OB
5202 if ($opt =~ m/^unused/) {
5203 die "internal error";
5204 } elsif (defined($conf->{$opt}) && is_valid_drivename($opt)) {
eb5e482d 5205 vmconfig_delete_or_detach_drive($vmid, $storecfg, $conf, $opt, $force);
eb5e482d
OB
5206 }
5207 };
5208 if (my $err = $@) {
5209 $add_apply_error->($opt, $err);
055d554d 5210 } else {
98bc3aeb 5211 PVE::QemuConfig->remove_from_pending_delete($conf, $opt);
055d554d 5212 delete $conf->{$opt};
055d554d
DM
5213 }
5214 }
5215
3d48b95a 5216 PVE::QemuConfig->cleanup_pending($conf);
055d554d 5217
7a24c98a 5218 my $generate_cloudinit = $skip_cloud_init ? 0 : undef;
c930f99e 5219
055d554d 5220 foreach my $opt (keys %{$conf->{pending}}) { # add/change
3d48b95a 5221 next if $opt eq 'delete'; # just to be sure
eb5e482d 5222 eval {
3d48b95a 5223 if (defined($conf->{$opt}) && is_valid_drivename($opt)) {
eb5e482d 5224 vmconfig_register_unused_drive($storecfg, $vmid, $conf, parse_drive($opt, $conf->{$opt}))
eb5e482d
OB
5225 }
5226 };
5227 if (my $err = $@) {
5228 $add_apply_error->($opt, $err);
055d554d 5229 } else {
c930f99e
AD
5230
5231 if (is_valid_drivename($opt)) {
5232 my $drive = parse_drive($opt, $conf->{pending}->{$opt});
7a24c98a 5233 $generate_cloudinit //= 1 if drive_is_cloudinit($drive);
c930f99e
AD
5234 }
5235
eb5e482d 5236 $conf->{$opt} = delete $conf->{pending}->{$opt};
055d554d 5237 }
055d554d 5238 }
3d48b95a
OB
5239
5240 # write all changes at once to avoid unnecessary i/o
5241 PVE::QemuConfig->write_config($vmid, $conf);
7a24c98a 5242 if ($generate_cloudinit) {
4b785da1
WB
5243 if (PVE::QemuServer::Cloudinit::apply_cloudinit_config($conf, $vmid)) {
5244 # After successful generation and if there were changes to be applied, update the
5245 # config to drop the {cloudinit} entry.
5246 PVE::QemuConfig->write_config($vmid, $conf);
5247 }
5248 }
055d554d
DM
5249}
5250
3eec5767 5251sub vmconfig_update_net {
d559309f 5252 my ($storecfg, $conf, $hotplug, $vmid, $opt, $value, $arch, $machine_type) = @_;
3eec5767
DM
5253
5254 my $newnet = parse_net($value);
5255
5256 if ($conf->{$opt}) {
5257 my $oldnet = parse_net($conf->{$opt});
5258
0f1af9e7
OB
5259 if (safe_string_ne($oldnet->{model}, $newnet->{model}) ||
5260 safe_string_ne($oldnet->{macaddr}, $newnet->{macaddr}) ||
5261 safe_num_ne($oldnet->{queues}, $newnet->{queues}) ||
62fdcfd4 5262 safe_num_ne($oldnet->{mtu}, $newnet->{mtu}) ||
3eec5767
DM
5263 !($newnet->{bridge} && $oldnet->{bridge})) { # bridge/nat mode change
5264
5265 # for non online change, we try to hot-unplug
7196b757 5266 die "skip\n" if !$hotplug;
3eec5767
DM
5267 vm_deviceunplug($vmid, $conf, $opt);
5268 } else {
5269
5270 die "internal error" if $opt !~ m/net(\d+)/;
5271 my $iface = "tap${vmid}i$1";
a1b7d579 5272
0f1af9e7
OB
5273 if (safe_string_ne($oldnet->{bridge}, $newnet->{bridge}) ||
5274 safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
5275 safe_string_ne($oldnet->{trunks}, $newnet->{trunks}) ||
5276 safe_num_ne($oldnet->{firewall}, $newnet->{firewall})) {
3eec5767 5277 PVE::Network::tap_unplug($iface);
28e129cc
AD
5278
5279 if ($have_sdn) {
5280 PVE::Network::SDN::Zones::tap_plug($iface, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
5281 } else {
5282 PVE::Network::tap_plug($iface, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
5283 }
0f1af9e7 5284 } elsif (safe_num_ne($oldnet->{rate}, $newnet->{rate})) {
4f4fbeb0
WB
5285 # Rate can be applied on its own but any change above needs to
5286 # include the rate in tap_plug since OVS resets everything.
5287 PVE::Network::tap_rate_limit($iface, $newnet->{rate});
3eec5767 5288 }
38c590d9 5289
0f1af9e7 5290 if (safe_string_ne($oldnet->{link_down}, $newnet->{link_down})) {
25088687
DM
5291 qemu_set_link_status($vmid, $opt, !$newnet->{link_down});
5292 }
5293
38c590d9 5294 return 1;
3eec5767
DM
5295 }
5296 }
a1b7d579 5297
7196b757 5298 if ($hotplug) {
d559309f 5299 vm_deviceplug($storecfg, $conf, $vmid, $opt, $newnet, $arch, $machine_type);
38c590d9
DM
5300 } else {
5301 die "skip\n";
5302 }
3eec5767
DM
5303}
5304
74ea2c65
AD
5305sub vmconfig_update_agent {
5306 my ($conf, $opt, $value) = @_;
5307
5308 die "skip\n" if !$conf->{$opt};
5309
5310 my $hotplug_options = { fstrim_cloned_disks => 1 };
5311
5312 my $old_agent = parse_guest_agent($conf);
5313 my $agent = parse_guest_agent({$opt => $value});
5314
33f8b887 5315 for my $option (keys %$agent) { # added/changed options
74ea2c65
AD
5316 next if defined($hotplug_options->{$option});
5317 die "skip\n" if safe_string_ne($agent->{$option}, $old_agent->{$option});
5318 }
5319
33f8b887 5320 for my $option (keys %$old_agent) { # removed options
74ea2c65
AD
5321 next if defined($hotplug_options->{$option});
5322 die "skip\n" if safe_string_ne($old_agent->{$option}, $agent->{$option});
5323 }
33f8b887
TL
5324
5325 return; # either no actual change (e.g., format string reordered) or just hotpluggable changes
74ea2c65
AD
5326}
5327
a05cff86 5328sub vmconfig_update_disk {
9e7bce2c 5329 my ($storecfg, $conf, $hotplug, $vmid, $opt, $value, $arch, $machine_type) = @_;
a05cff86
DM
5330
5331 my $drive = parse_drive($opt, $value);
5332
4df98f2f
TL
5333 if ($conf->{$opt} && (my $old_drive = parse_drive($opt, $conf->{$opt}))) {
5334 my $media = $drive->{media} || 'disk';
5335 my $oldmedia = $old_drive->{media} || 'disk';
5336 die "unable to change media type\n" if $media ne $oldmedia;
a05cff86 5337
4df98f2f 5338 if (!drive_is_cdrom($old_drive)) {
a05cff86 5339
4df98f2f 5340 if ($drive->{file} ne $old_drive->{file}) {
a05cff86 5341
4df98f2f 5342 die "skip\n" if !$hotplug;
a05cff86 5343
4df98f2f
TL
5344 # unplug and register as unused
5345 vm_deviceunplug($vmid, $conf, $opt);
5346 vmconfig_register_unused_drive($storecfg, $vmid, $conf, $old_drive)
a1b7d579 5347
4df98f2f
TL
5348 } else {
5349 # update existing disk
5350
5351 # skip non hotpluggable value
ea7c3b39
FE
5352 if (safe_string_ne($drive->{aio}, $old_drive->{aio}) ||
5353 safe_string_ne($drive->{discard}, $old_drive->{discard}) ||
4df98f2f
TL
5354 safe_string_ne($drive->{iothread}, $old_drive->{iothread}) ||
5355 safe_string_ne($drive->{queues}, $old_drive->{queues}) ||
5356 safe_string_ne($drive->{cache}, $old_drive->{cache}) ||
e0e036e1
LN
5357 safe_string_ne($drive->{ssd}, $old_drive->{ssd}) ||
5358 safe_string_ne($drive->{ro}, $old_drive->{ro})) {
4df98f2f
TL
5359 die "skip\n";
5360 }
a05cff86 5361
4df98f2f
TL
5362 # apply throttle
5363 if (safe_num_ne($drive->{mbps}, $old_drive->{mbps}) ||
5364 safe_num_ne($drive->{mbps_rd}, $old_drive->{mbps_rd}) ||
5365 safe_num_ne($drive->{mbps_wr}, $old_drive->{mbps_wr}) ||
5366 safe_num_ne($drive->{iops}, $old_drive->{iops}) ||
5367 safe_num_ne($drive->{iops_rd}, $old_drive->{iops_rd}) ||
5368 safe_num_ne($drive->{iops_wr}, $old_drive->{iops_wr}) ||
5369 safe_num_ne($drive->{mbps_max}, $old_drive->{mbps_max}) ||
5370 safe_num_ne($drive->{mbps_rd_max}, $old_drive->{mbps_rd_max}) ||
5371 safe_num_ne($drive->{mbps_wr_max}, $old_drive->{mbps_wr_max}) ||
5372 safe_num_ne($drive->{iops_max}, $old_drive->{iops_max}) ||
5373 safe_num_ne($drive->{iops_rd_max}, $old_drive->{iops_rd_max}) ||
5374 safe_num_ne($drive->{iops_wr_max}, $old_drive->{iops_wr_max}) ||
5375 safe_num_ne($drive->{bps_max_length}, $old_drive->{bps_max_length}) ||
5376 safe_num_ne($drive->{bps_rd_max_length}, $old_drive->{bps_rd_max_length}) ||
5377 safe_num_ne($drive->{bps_wr_max_length}, $old_drive->{bps_wr_max_length}) ||
5378 safe_num_ne($drive->{iops_max_length}, $old_drive->{iops_max_length}) ||
5379 safe_num_ne($drive->{iops_rd_max_length}, $old_drive->{iops_rd_max_length}) ||
5380 safe_num_ne($drive->{iops_wr_max_length}, $old_drive->{iops_wr_max_length})) {
5381
5382 qemu_block_set_io_throttle(
5383 $vmid,"drive-$opt",
5384 ($drive->{mbps} || 0)*1024*1024,
5385 ($drive->{mbps_rd} || 0)*1024*1024,
5386 ($drive->{mbps_wr} || 0)*1024*1024,
5387 $drive->{iops} || 0,
5388 $drive->{iops_rd} || 0,
5389 $drive->{iops_wr} || 0,
5390 ($drive->{mbps_max} || 0)*1024*1024,
5391 ($drive->{mbps_rd_max} || 0)*1024*1024,
5392 ($drive->{mbps_wr_max} || 0)*1024*1024,
5393 $drive->{iops_max} || 0,
5394 $drive->{iops_rd_max} || 0,
5395 $drive->{iops_wr_max} || 0,
5396 $drive->{bps_max_length} || 1,
5397 $drive->{bps_rd_max_length} || 1,
5398 $drive->{bps_wr_max_length} || 1,
5399 $drive->{iops_max_length} || 1,
5400 $drive->{iops_rd_max_length} || 1,
5401 $drive->{iops_wr_max_length} || 1,
5402 );
a05cff86 5403
4df98f2f 5404 }
a1b7d579 5405
4df98f2f
TL
5406 return 1;
5407 }
4de1bb25 5408
4df98f2f 5409 } else { # cdrom
a1b7d579 5410
4df98f2f
TL
5411 if ($drive->{file} eq 'none') {
5412 mon_cmd($vmid, "eject", force => JSON::true, id => "$opt");
5413 if (drive_is_cloudinit($old_drive)) {
5414 vmconfig_register_unused_drive($storecfg, $vmid, $conf, $old_drive);
5415 }
5416 } else {
5417 my $path = get_iso_path($storecfg, $vmid, $drive->{file});
ce9fce79 5418
4df98f2f
TL
5419 # force eject if locked
5420 mon_cmd($vmid, "eject", force => JSON::true, id => "$opt");
ce9fce79 5421
4df98f2f
TL
5422 if ($path) {
5423 mon_cmd($vmid, "blockdev-change-medium",
5424 id => "$opt", filename => "$path");
4de1bb25 5425 }
a05cff86 5426 }
4df98f2f
TL
5427
5428 return 1;
a05cff86
DM
5429 }
5430 }
5431
a1b7d579 5432 die "skip\n" if !$hotplug || $opt =~ m/(ide|sata)(\d+)/;
4de1bb25 5433 # hotplug new disks
f7b4356f 5434 PVE::Storage::activate_volumes($storecfg, [$drive->{file}]) if $drive->{file} !~ m|^/dev/.+|;
d559309f 5435 vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive, $arch, $machine_type);
a05cff86
DM
5436}
5437
9687287b
AD
5438sub vmconfig_update_cloudinit_drive {
5439 my ($storecfg, $conf, $vmid) = @_;
5440
5441 my $cloudinit_ds = undef;
5442 my $cloudinit_drive = undef;
5443
5444 PVE::QemuConfig->foreach_volume($conf, sub {
5445 my ($ds, $drive) = @_;
5446 if (PVE::QemuServer::drive_is_cloudinit($drive)) {
5447 $cloudinit_ds = $ds;
5448 $cloudinit_drive = $drive;
5449 }
5450 });
5451
5452 return if !$cloudinit_drive;
5453
4b785da1
WB
5454 if (PVE::QemuServer::Cloudinit::apply_cloudinit_config($conf, $vmid)) {
5455 PVE::QemuConfig->write_config($vmid, $conf);
5456 }
5457
9687287b
AD
5458 my $running = PVE::QemuServer::check_running($vmid);
5459
5460 if ($running) {
5461 my $path = PVE::Storage::path($storecfg, $cloudinit_drive->{file});
5462 if ($path) {
5463 mon_cmd($vmid, "eject", force => JSON::true, id => "$cloudinit_ds");
5464 mon_cmd($vmid, "blockdev-change-medium", id => "$cloudinit_ds", filename => "$path");
5465 }
5466 }
5467}
5468
13cfe3b7 5469# called in locked context by incoming migration
ba5396b5
FG
5470sub vm_migrate_get_nbd_disks {
5471 my ($storecfg, $conf, $replicated_volumes) = @_;
13cfe3b7
FG
5472
5473 my $local_volumes = {};
912792e2 5474 PVE::QemuConfig->foreach_volume($conf, sub {
13cfe3b7
FG
5475 my ($ds, $drive) = @_;
5476
5477 return if drive_is_cdrom($drive);
41c8671e 5478 return if $ds eq 'tpmstate0';
13cfe3b7
FG
5479
5480 my $volid = $drive->{file};
5481
5482 return if !$volid;
5483
5484 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
5485
5486 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
5487 return if $scfg->{shared};
ba5396b5 5488
0d4e8cbd
FE
5489 my $format = qemu_img_format($scfg, $volname);
5490
ba5396b5
FG
5491 # replicated disks re-use existing state via bitmap
5492 my $use_existing = $replicated_volumes->{$volid} ? 1 : 0;
0d4e8cbd 5493 $local_volumes->{$ds} = [$volid, $storeid, $drive, $use_existing, $format];
13cfe3b7 5494 });
ba5396b5
FG
5495 return $local_volumes;
5496}
5497
5498# called in locked context by incoming migration
5499sub vm_migrate_alloc_nbd_disks {
5500 my ($storecfg, $vmid, $source_volumes, $storagemap) = @_;
13cfe3b7 5501
13cfe3b7 5502 my $nbd = {};
ba5396b5 5503 foreach my $opt (sort keys %$source_volumes) {
0d4e8cbd 5504 my ($volid, $storeid, $drive, $use_existing, $format) = @{$source_volumes->{$opt}};
ba5396b5
FG
5505
5506 if ($use_existing) {
5507 $nbd->{$opt}->{drivestr} = print_drive($drive);
5508 $nbd->{$opt}->{volid} = $volid;
5509 $nbd->{$opt}->{replicated} = 1;
13cfe3b7
FG
5510 next;
5511 }
13cfe3b7 5512
0d4e8cbd
FE
5513 $storeid = PVE::JSONSchema::map_id($storagemap, $storeid);
5514
5668463b
FG
5515 # order of precedence, filtered by whether storage supports it:
5516 # 1. explicit requested format
0d4e8cbd
FE
5517 # 2. default format of storage
5518 my ($defFormat, $validFormats) = PVE::Storage::storage_default_format($storecfg, $storeid);
5519 $format = $defFormat if !$format || !grep { $format eq $_ } $validFormats->@*;
13cfe3b7 5520
4df98f2f
TL
5521 my $size = $drive->{size} / 1024;
5522 my $newvolid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, $format, undef, $size);
13cfe3b7
FG
5523 my $newdrive = $drive;
5524 $newdrive->{format} = $format;
5525 $newdrive->{file} = $newvolid;
5526 my $drivestr = print_drive($newdrive);
ba5396b5
FG
5527 $nbd->{$opt}->{drivestr} = $drivestr;
5528 $nbd->{$opt}->{volid} = $newvolid;
13cfe3b7
FG
5529 }
5530
5531 return $nbd;
5532}
5533
5534# see vm_start_nolock for parameters, additionally:
5535# migrate_opts:
bf8fc5a3 5536# storagemap = parsed storage map for allocating NBD disks
3898a563
FG
5537sub vm_start {
5538 my ($storecfg, $vmid, $params, $migrate_opts) = @_;
5539
84da8217 5540 return PVE::QemuConfig->lock_config($vmid, sub {
3898a563
FG
5541 my $conf = PVE::QemuConfig->load_config($vmid, $migrate_opts->{migratedfrom});
5542
4ef13a7f
FG
5543 die "you can't start a vm if it's a template\n"
5544 if !$params->{skiptemplate} && PVE::QemuConfig->is_template($conf);
3898a563 5545
d544e0e0 5546 my $has_suspended_lock = PVE::QemuConfig->has_lock($conf, 'suspended');
8e0c97bb
SR
5547 my $has_backup_lock = PVE::QemuConfig->has_lock($conf, 'backup');
5548
5549 my $running = check_running($vmid, undef, $migrate_opts->{migratedfrom});
5550
5551 if ($has_backup_lock && $running) {
5552 # a backup is currently running, attempt to start the guest in the
5553 # existing QEMU instance
5554 return vm_resume($vmid);
5555 }
3898a563
FG
5556
5557 PVE::QemuConfig->check_lock($conf)
d544e0e0
FE
5558 if !($params->{skiplock} || $has_suspended_lock);
5559
5560 $params->{resume} = $has_suspended_lock || defined($conf->{vmstate});
3898a563 5561
8e0c97bb 5562 die "VM $vmid already running\n" if $running;
3898a563 5563
ba5396b5
FG
5564 if (my $storagemap = $migrate_opts->{storagemap}) {
5565 my $replicated = $migrate_opts->{replicated_volumes};
5566 my $disks = vm_migrate_get_nbd_disks($storecfg, $conf, $replicated);
5567 $migrate_opts->{nbd} = vm_migrate_alloc_nbd_disks($storecfg, $vmid, $disks, $storagemap);
5568
5569 foreach my $opt (keys %{$migrate_opts->{nbd}}) {
5570 $conf->{$opt} = $migrate_opts->{nbd}->{$opt}->{drivestr};
5571 }
5572 }
13cfe3b7 5573
84da8217 5574 return vm_start_nolock($storecfg, $vmid, $conf, $params, $migrate_opts);
3898a563
FG
5575 });
5576}
5577
5578
0c498cca
FG
5579# params:
5580# statefile => 'tcp', 'unix' for migration or path/volid for RAM state
5581# skiplock => 0/1, skip checking for config lock
4ef13a7f 5582# skiptemplate => 0/1, skip checking whether VM is template
7bd9abd2 5583# forcemachine => to force QEMU machine (rollback/migration)
58c64ad5 5584# forcecpu => a QEMU '-cpu' argument string to override get_cpu_options
0c498cca
FG
5585# timeout => in seconds
5586# paused => start VM in paused state (backup)
3898a563 5587# resume => resume from hibernation
5921764c
SR
5588# pbs-backing => {
5589# sata0 => {
5590# repository
5591# snapshot
5592# keyfile
5593# archive
5594# },
5595# virtio2 => ...
5596# }
0c498cca 5597# migrate_opts:
ba5396b5 5598# nbd => volumes for NBD exports (vm_migrate_alloc_nbd_disks)
0c498cca
FG
5599# migratedfrom => source node
5600# spice_ticket => used for spice migration, passed via tunnel/stdin
5601# network => CIDR of migration network
5602# type => secure/insecure - tunnel over encrypted connection or plain-text
0c498cca 5603# nbd_proto_version => int, 0 for TCP, 1 for UNIX
fd95d780 5604# replicated_volumes => which volids should be re-used with bitmaps for nbd migration
13d121d7
FE
5605# offline_volumes => new volids of offline migrated disks like tpmstate and cloudinit, not yet
5606# contained in config
3898a563
FG
5607sub vm_start_nolock {
5608 my ($storecfg, $vmid, $conf, $params, $migrate_opts) = @_;
1e3baf05 5609
3898a563
FG
5610 my $statefile = $params->{statefile};
5611 my $resume = $params->{resume};
3dcb98d5 5612
3898a563
FG
5613 my $migratedfrom = $migrate_opts->{migratedfrom};
5614 my $migration_type = $migrate_opts->{type};
7ceade4c 5615
84da8217
FG
5616 my $res = {};
5617
3898a563
FG
5618 # clean up leftover reboot request files
5619 eval { clear_reboot_request($vmid); };
5620 warn $@ if $@;
1e3baf05 5621
3898a563
FG
5622 if (!$statefile && scalar(keys %{$conf->{pending}})) {
5623 vmconfig_apply_pending($vmid, $conf, $storecfg);
5624 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
5625 }
64457ed4 5626
3de134ef
WB
5627 # don't regenerate the ISO if the VM is started as part of a live migration
5628 # this way we can reuse the old ISO with the correct config
4b785da1
WB
5629 if (!$migratedfrom) {
5630 if (PVE::QemuServer::Cloudinit::apply_cloudinit_config($conf, $vmid)) {
5631 # FIXME: apply_cloudinit_config updates $conf in this case, and it would only drop
5632 # $conf->{cloudinit}, so we could just not do this?
5633 # But we do it above, so for now let's be consistent.
5634 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
5635 }
5636 }
3de134ef 5637
13d121d7
FE
5638 # override offline migrated volumes, conf is out of date still
5639 if (my $offline_volumes = $migrate_opts->{offline_volumes}) {
5640 for my $key (sort keys $offline_volumes->%*) {
5641 my $parsed = parse_drive($key, $conf->{$key});
5642 $parsed->{file} = $offline_volumes->{$key};
5643 $conf->{$key} = print_drive($parsed);
5644 }
fd95d780
FG
5645 }
5646
3898a563 5647 my $defaults = load_defaults();
0c9a7596 5648
3898a563 5649 # set environment variable useful inside network script
eef93bc5
FG
5650 # for remote migration the config is available on the target node!
5651 if (!$migrate_opts->{remote_node}) {
5652 $ENV{PVE_MIGRATED_FROM} = $migratedfrom;
5653 }
6c47d546 5654
3898a563 5655 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-start', 1);
9e784b11 5656
3898a563 5657 my $forcemachine = $params->{forcemachine};
ea1c2110 5658 my $forcecpu = $params->{forcecpu};
3898a563 5659 if ($resume) {
ea1c2110 5660 # enforce machine and CPU type on suspended vm to ensure HW compatibility
3898a563 5661 $forcemachine = $conf->{runningmachine};
ea1c2110 5662 $forcecpu = $conf->{runningcpu};
3898a563
FG
5663 print "Resuming suspended VM\n";
5664 }
7ceade4c 5665
9b71c34d 5666 my ($cmd, $vollist, $spice_port, $pci_devices) = config_to_command($storecfg, $vmid,
5921764c 5667 $conf, $defaults, $forcemachine, $forcecpu, $params->{'pbs-backing'});
6c47d546 5668
3898a563
FG
5669 my $migration_ip;
5670 my $get_migration_ip = sub {
5671 my ($nodename) = @_;
b24e1ac2 5672
3898a563 5673 return $migration_ip if defined($migration_ip);
b24e1ac2 5674
3898a563 5675 my $cidr = $migrate_opts->{network};
0c498cca 5676
3898a563
FG
5677 if (!defined($cidr)) {
5678 my $dc_conf = PVE::Cluster::cfs_read_file('datacenter.cfg');
5679 $cidr = $dc_conf->{migration}->{network};
5680 }
b24e1ac2 5681
3898a563
FG
5682 if (defined($cidr)) {
5683 my $ips = PVE::Network::get_local_ip_from_cidr($cidr);
b24e1ac2 5684
3898a563
FG
5685 die "could not get IP: no address configured on local " .
5686 "node for network '$cidr'\n" if scalar(@$ips) == 0;
b24e1ac2 5687
3898a563
FG
5688 die "could not get IP: multiple addresses configured on local " .
5689 "node for network '$cidr'\n" if scalar(@$ips) > 1;
b24e1ac2 5690
3898a563
FG
5691 $migration_ip = @$ips[0];
5692 }
b24e1ac2 5693
3898a563
FG
5694 $migration_ip = PVE::Cluster::remote_node_ip($nodename, 1)
5695 if !defined($migration_ip);
b24e1ac2 5696
3898a563
FG
5697 return $migration_ip;
5698 };
b24e1ac2 5699
3898a563
FG
5700 if ($statefile) {
5701 if ($statefile eq 'tcp') {
05b2a4ae
FG
5702 my $migrate = $res->{migrate} = { proto => 'tcp' };
5703 $migrate->{addr} = "localhost";
3898a563
FG
5704 my $datacenterconf = PVE::Cluster::cfs_read_file('datacenter.cfg');
5705 my $nodename = nodename();
2de2d6f7 5706
3898a563
FG
5707 if (!defined($migration_type)) {
5708 if (defined($datacenterconf->{migration}->{type})) {
5709 $migration_type = $datacenterconf->{migration}->{type};
5710 } else {
5711 $migration_type = 'secure';
b7a5a225 5712 }
3898a563 5713 }
b7a5a225 5714
3898a563 5715 if ($migration_type eq 'insecure') {
05b2a4ae
FG
5716 $migrate->{addr} = $get_migration_ip->($nodename);
5717 $migrate->{addr} = "[$migrate->{addr}]" if Net::IP::ip_is_ipv6($migrate->{addr});
3898a563 5718 }
2de2d6f7 5719
3898a563 5720 my $pfamily = PVE::Tools::get_host_address_family($nodename);
05b2a4ae
FG
5721 $migrate->{port} = PVE::Tools::next_migrate_port($pfamily);
5722 $migrate->{uri} = "tcp:$migrate->{addr}:$migrate->{port}";
5723 push @$cmd, '-incoming', $migrate->{uri};
3898a563 5724 push @$cmd, '-S';
1c9d54bf 5725
3898a563
FG
5726 } elsif ($statefile eq 'unix') {
5727 # should be default for secure migrations as a ssh TCP forward
5728 # tunnel is not deterministic reliable ready and fails regurarly
5729 # to set up in time, so use UNIX socket forwards
05b2a4ae
FG
5730 my $migrate = $res->{migrate} = { proto => 'unix' };
5731 $migrate->{addr} = "/run/qemu-server/$vmid.migrate";
5732 unlink $migrate->{addr};
54323eed 5733
05b2a4ae
FG
5734 $migrate->{uri} = "unix:$migrate->{addr}";
5735 push @$cmd, '-incoming', $migrate->{uri};
3898a563 5736 push @$cmd, '-S';
1c9d54bf 5737
3898a563
FG
5738 } elsif (-e $statefile) {
5739 push @$cmd, '-loadstate', $statefile;
5740 } else {
5741 my $statepath = PVE::Storage::path($storecfg, $statefile);
5742 push @$vollist, $statefile;
5743 push @$cmd, '-loadstate', $statepath;
5744 }
5745 } elsif ($params->{paused}) {
5746 push @$cmd, '-S';
5747 }
5748
7f8c8087
AD
5749 my $memory = get_current_memory($conf->{memory});
5750 my $start_timeout = $params->{timeout} // config_aware_timeout($conf, $memory, $resume);
1fb1822e 5751
9b71c34d
DC
5752 my $pci_reserve_list = [];
5753 for my $device (values $pci_devices->%*) {
5754 next if $device->{mdev}; # we don't reserve for mdev devices
5755 push $pci_reserve_list->@*, map { $_->{id} } $device->{ids}->@*;
1fb1822e
DC
5756 }
5757
1fb1822e 5758 # reserve all PCI IDs before actually doing anything with them
9b71c34d 5759 PVE::QemuServer::PCI::reserve_pci_usage($pci_reserve_list, $vmid, $start_timeout);
1fb1822e
DC
5760
5761 eval {
bbf96e0f 5762 my $uuid;
1fb1822e
DC
5763 for my $id (sort keys %$pci_devices) {
5764 my $d = $pci_devices->{$id};
9b71c34d
DC
5765 my ($index) = ($id =~ m/^hostpci(\d+)$/);
5766
5767 my $chosen_mdev;
5768 for my $dev ($d->{ids}->@*) {
5769 my $info = eval { PVE::QemuServer::PCI::prepare_pci_device($vmid, $dev->{id}, $index, $d->{mdev}) };
5770 if ($d->{mdev}) {
5771 warn $@ if $@;
5772 $chosen_mdev = $info;
5773 last if $chosen_mdev; # if successful, we're done
5774 } else {
5775 die $@ if $@;
5776 }
5777 }
5778
5779 next if !$d->{mdev};
5780 die "could not create mediated device\n" if !defined($chosen_mdev);
5781
5782 # nvidia grid needs the uuid of the mdev as qemu parameter
5783 if (!defined($uuid) && $chosen_mdev->{vendor} =~ m/^(0x)?10de$/) {
5784 if (defined($conf->{smbios1})) {
5785 my $smbios_conf = parse_smbios1($conf->{smbios1});
5786 $uuid = $smbios_conf->{uuid} if defined($smbios_conf->{uuid});
bbf96e0f 5787 }
9b71c34d 5788 $uuid = PVE::QemuServer::PCI::generate_mdev_uuid($vmid, $index) if !defined($uuid);
1fb1822e
DC
5789 }
5790 }
bbf96e0f 5791 push @$cmd, '-uuid', $uuid if defined($uuid);
1fb1822e
DC
5792 };
5793 if (my $err = $@) {
1b189121 5794 eval { cleanup_pci_devices($vmid, $conf) };
1fb1822e
DC
5795 warn $@ if $@;
5796 die $err;
3898a563 5797 }
1e3baf05 5798
3898a563 5799 PVE::Storage::activate_volumes($storecfg, $vollist);
1e3baf05 5800
728404c0
TL
5801
5802 my %silence_std_outs = (outfunc => sub {}, errfunc => sub {});
3d79cf55 5803 eval { run_command(['/bin/systemctl', 'reset-failed', "$vmid.scope"], %silence_std_outs) };
728404c0 5804 eval { run_command(['/bin/systemctl', 'stop', "$vmid.scope"], %silence_std_outs) };
3898a563
FG
5805 # Issues with the above 'stop' not being fully completed are extremely rare, a very low
5806 # timeout should be more than enough here...
39abafc8 5807 PVE::Systemd::wait_for_unit_removed("$vmid.scope", 20);
3898a563 5808
6b7ef5e5 5809 my $cpuunits = PVE::CGroup::clamp_cpu_shares($conf->{cpuunits});
3898a563 5810
3898a563
FG
5811 my %run_params = (
5812 timeout => $statefile ? undef : $start_timeout,
5813 umask => 0077,
5814 noerr => 1,
5815 );
1e3baf05 5816
3898a563
FG
5817 # when migrating, prefix QEMU output so other side can pick up any
5818 # errors that might occur and show the user
5819 if ($migratedfrom) {
5820 $run_params{quiet} = 1;
5821 $run_params{logfunc} = sub { print "QEMU: $_[0]\n" };
5822 }
8bf30c2a 5823
212220a4 5824 my %systemd_properties = (
3898a563 5825 Slice => 'qemu.slice',
354e61aa
SR
5826 KillMode => 'process',
5827 SendSIGKILL => 0,
5828 TimeoutStopUSec => ULONG_MAX, # infinity
3898a563 5829 );
7023f3ea 5830
6cbd3eb8 5831 if (PVE::CGroup::cgroup_mode() == 2) {
212220a4 5832 $systemd_properties{CPUWeight} = $cpuunits;
6cbd3eb8 5833 } else {
212220a4 5834 $systemd_properties{CPUShares} = $cpuunits;
6cbd3eb8
AD
5835 }
5836
3898a563 5837 if (my $cpulimit = $conf->{cpulimit}) {
212220a4 5838 $systemd_properties{CPUQuota} = int($cpulimit * 100);
3898a563 5839 }
212220a4 5840 $systemd_properties{timeout} = 10 if $statefile; # setting up the scope shoul be quick
7023f3ea 5841
3898a563
FG
5842 my $run_qemu = sub {
5843 PVE::Tools::run_fork sub {
212220a4 5844 PVE::Systemd::enter_systemd_scope($vmid, "Proxmox VE VM $vmid", %systemd_properties);
6e0216d8 5845
f9dde219 5846 my $tpmpid;
a55d0f71 5847 if ((my $tpm = $conf->{tpmstate0}) && !PVE::QemuConfig->is_template($conf)) {
f9dde219
SR
5848 # start the TPM emulator so QEMU can connect on start
5849 $tpmpid = start_swtpm($storecfg, $vmid, $tpm, $migratedfrom);
5850 }
5851
3898a563 5852 my $exitcode = run_command($cmd, %run_params);
f9dde219 5853 if ($exitcode) {
23bee97d
FE
5854 if ($tpmpid) {
5855 warn "stopping swtpm instance (pid $tpmpid) due to QEMU startup error\n";
5856 kill 'TERM', $tpmpid;
5857 }
f9dde219
SR
5858 die "QEMU exited with code $exitcode\n";
5859 }
503308ed 5860 };
3898a563 5861 };
503308ed 5862
3898a563 5863 if ($conf->{hugepages}) {
7023f3ea 5864
3898a563 5865 my $code = sub {
dafb728c
AD
5866 my $hotplug_features =
5867 parse_hotplug_features(defined($conf->{hotplug}) ? $conf->{hotplug} : '1');
5868 my $hugepages_topology =
5869 PVE::QemuServer::Memory::hugepages_topology($conf, $hotplug_features->{memory});
5870
3898a563 5871 my $hugepages_host_topology = PVE::QemuServer::Memory::hugepages_host_topology();
7023f3ea 5872
3898a563
FG
5873 PVE::QemuServer::Memory::hugepages_mount();
5874 PVE::QemuServer::Memory::hugepages_allocate($hugepages_topology, $hugepages_host_topology);
7023f3ea 5875
503308ed 5876 eval { $run_qemu->() };
3898a563 5877 if (my $err = $@) {
f36e9894
SR
5878 PVE::QemuServer::Memory::hugepages_reset($hugepages_host_topology)
5879 if !$conf->{keephugepages};
3898a563
FG
5880 die $err;
5881 }
77cde36b 5882
f36e9894
SR
5883 PVE::QemuServer::Memory::hugepages_pre_deallocate($hugepages_topology)
5884 if !$conf->{keephugepages};
3898a563
FG
5885 };
5886 eval { PVE::QemuServer::Memory::hugepages_update_locked($code); };
1e3baf05 5887
3898a563
FG
5888 } else {
5889 eval { $run_qemu->() };
5890 }
afdb31d5 5891
3898a563
FG
5892 if (my $err = $@) {
5893 # deactivate volumes if start fails
5894 eval { PVE::Storage::deactivate_volumes($storecfg, $vollist); };
1b189121
DC
5895 warn $@ if $@;
5896 eval { cleanup_pci_devices($vmid, $conf) };
5897 warn $@ if $@;
1fb1822e 5898
3898a563
FG
5899 die "start failed: $err";
5900 }
62de2cbd 5901
1fb1822e
DC
5902 # re-reserve all PCI IDs now that we can know the actual VM PID
5903 my $pid = PVE::QemuServer::Helpers::vm_running_locally($vmid);
9b71c34d 5904 eval { PVE::QemuServer::PCI::reserve_pci_usage($pci_reserve_list, $vmid, undef, $pid) };
1fb1822e
DC
5905 warn $@ if $@;
5906
05b2a4ae
FG
5907 if (defined($res->{migrate})) {
5908 print "migration listens on $res->{migrate}->{uri}\n";
5909 } elsif ($statefile) {
3898a563
FG
5910 eval { mon_cmd($vmid, "cont"); };
5911 warn $@ if $@;
5912 }
2189246c 5913
3898a563 5914 #start nbd server for storage migration
13cfe3b7 5915 if (my $nbd = $migrate_opts->{nbd}) {
3898a563 5916 my $nbd_protocol_version = $migrate_opts->{nbd_proto_version} // 0;
2189246c 5917
3898a563
FG
5918 my $migrate_storage_uri;
5919 # nbd_protocol_version > 0 for unix socket support
eef93bc5 5920 if ($nbd_protocol_version > 0 && ($migration_type eq 'secure' || $migration_type eq 'websocket')) {
3898a563
FG
5921 my $socket_path = "/run/qemu-server/$vmid\_nbd.migrate";
5922 mon_cmd($vmid, "nbd-server-start", addr => { type => 'unix', data => { path => $socket_path } } );
5923 $migrate_storage_uri = "nbd:unix:$socket_path";
05b2a4ae 5924 $res->{migrate}->{unix_sockets} = [$socket_path];
3898a563
FG
5925 } else {
5926 my $nodename = nodename();
5927 my $localip = $get_migration_ip->($nodename);
5928 my $pfamily = PVE::Tools::get_host_address_family($nodename);
5929 my $storage_migrate_port = PVE::Tools::next_migrate_port($pfamily);
5930
4df98f2f
TL
5931 mon_cmd($vmid, "nbd-server-start", addr => {
5932 type => 'inet',
5933 data => {
5934 host => "${localip}",
5935 port => "${storage_migrate_port}",
5936 },
5937 });
3898a563
FG
5938 $localip = "[$localip]" if Net::IP::ip_is_ipv6($localip);
5939 $migrate_storage_uri = "nbd:${localip}:${storage_migrate_port}";
2189246c
AD
5940 }
5941
83f04be3
FE
5942 my $block_info = mon_cmd($vmid, "query-block");
5943 $block_info = { map { $_->{device} => $_ } $block_info->@* };
5944
13cfe3b7 5945 foreach my $opt (sort keys %$nbd) {
ba5396b5
FG
5946 my $drivestr = $nbd->{$opt}->{drivestr};
5947 my $volid = $nbd->{$opt}->{volid};
83f04be3
FE
5948
5949 my $block_node = $block_info->{"drive-$opt"}->{inserted}->{'node-name'};
5950
5951 mon_cmd(
5952 $vmid,
5953 "block-export-add",
5954 id => "drive-$opt",
5955 'node-name' => $block_node,
5956 writable => JSON::true,
5957 type => "nbd",
5958 name => "drive-$opt", # NBD export name
5959 );
5960
84da8217
FG
5961 my $nbd_uri = "$migrate_storage_uri:exportname=drive-$opt";
5962 print "storage migration listens on $nbd_uri volume:$drivestr\n";
ba5396b5
FG
5963 print "re-using replicated volume: $opt - $volid\n"
5964 if $nbd->{$opt}->{replicated};
84da8217
FG
5965
5966 $res->{drives}->{$opt} = $nbd->{$opt};
5967 $res->{drives}->{$opt}->{nbd_uri} = $nbd_uri;
3898a563
FG
5968 }
5969 }
a89fded1 5970
3898a563
FG
5971 if ($migratedfrom) {
5972 eval {
5973 set_migration_caps($vmid);
5974 };
5975 warn $@ if $@;
5976
5977 if ($spice_port) {
5978 print "spice listens on port $spice_port\n";
84da8217 5979 $res->{spice_port} = $spice_port;
3898a563 5980 if ($migrate_opts->{spice_ticket}) {
4df98f2f
TL
5981 mon_cmd($vmid, "set_password", protocol => 'spice', password =>
5982 $migrate_opts->{spice_ticket});
3898a563 5983 mon_cmd($vmid, "expire_password", protocol => 'spice', time => "+30");
95a4b4a9 5984 }
3898a563 5985 }
95a4b4a9 5986
3898a563
FG
5987 } else {
5988 mon_cmd($vmid, "balloon", value => $conf->{balloon}*1024*1024)
5989 if !$statefile && $conf->{balloon};
25088687 5990
3898a563
FG
5991 foreach my $opt (keys %$conf) {
5992 next if $opt !~ m/^net\d+$/;
5993 my $nicconf = parse_net($conf->{$opt});
5994 qemu_set_link_status($vmid, $opt, 0) if $nicconf->{link_down};
e18b0b99 5995 }
21947fea 5996 add_nets_bridge_fdb($conf, $vmid);
3898a563 5997 }
a1b7d579 5998
4044ae1f 5999 if (!defined($conf->{balloon}) || $conf->{balloon}) {
cb64a643
FE
6000 eval {
6001 mon_cmd(
6002 $vmid,
6003 'qom-set',
6004 path => "machine/peripheral/balloon0",
6005 property => "guest-stats-polling-interval",
6006 value => 2
6007 );
6008 };
6009 log_warn("could not set polling interval for ballooning - $@") if $@;
4044ae1f 6010 }
eb065317 6011
3898a563
FG
6012 if ($resume) {
6013 print "Resumed VM, removing state\n";
6014 if (my $vmstate = $conf->{vmstate}) {
6015 PVE::Storage::deactivate_volumes($storecfg, [$vmstate]);
6016 PVE::Storage::vdisk_free($storecfg, $vmstate);
7ceade4c 6017 }
ea1c2110 6018 delete $conf->@{qw(lock vmstate runningmachine runningcpu)};
3898a563
FG
6019 PVE::QemuConfig->write_config($vmid, $conf);
6020 }
7ceade4c 6021
3898a563 6022 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-start');
84da8217 6023
dec371d9
FE
6024 my ($current_machine, $is_deprecated) =
6025 PVE::QemuServer::Machine::get_current_qemu_machine($vmid);
6026 if ($is_deprecated) {
6027 log_warn(
6028 "current machine version '$current_machine' is deprecated - see the documentation and ".
6029 "change to a newer one",
6030 );
6031 }
6032
84da8217 6033 return $res;
1e3baf05
DM
6034}
6035
1e3baf05 6036sub vm_commandline {
b14477e7 6037 my ($storecfg, $vmid, $snapname) = @_;
1e3baf05 6038
ffda963f 6039 my $conf = PVE::QemuConfig->load_config($vmid);
1e3baf05 6040
e8a26810 6041 my ($forcemachine, $forcecpu);
b14477e7
RV
6042 if ($snapname) {
6043 my $snapshot = $conf->{snapshots}->{$snapname};
87d92707
TL
6044 die "snapshot '$snapname' does not exist\n" if !defined($snapshot);
6045
ea1c2110
SR
6046 # check for machine or CPU overrides in snapshot
6047 $forcemachine = $snapshot->{runningmachine};
6048 $forcecpu = $snapshot->{runningcpu};
092868c4 6049
87d92707 6050 $snapshot->{digest} = $conf->{digest}; # keep file digest for API
b14477e7 6051
b14477e7
RV
6052 $conf = $snapshot;
6053 }
6054
1e3baf05
DM
6055 my $defaults = load_defaults();
6056
e8a26810 6057 my $cmd = config_to_command($storecfg, $vmid, $conf, $defaults, $forcemachine, $forcecpu);
1e3baf05 6058
5930c1ff 6059 return PVE::Tools::cmd2string($cmd);
1e3baf05
DM
6060}
6061
6062sub vm_reset {
6063 my ($vmid, $skiplock) = @_;
6064
ffda963f 6065 PVE::QemuConfig->lock_config($vmid, sub {
1e3baf05 6066
ffda963f 6067 my $conf = PVE::QemuConfig->load_config($vmid);
1e3baf05 6068
ffda963f 6069 PVE::QemuConfig->check_lock($conf) if !$skiplock;
1e3baf05 6070
0a13e08e 6071 mon_cmd($vmid, "system_reset");
ff1a2432
DM
6072 });
6073}
6074
6075sub get_vm_volumes {
6076 my ($conf) = @_;
1e3baf05 6077
ff1a2432 6078 my $vollist = [];
0b7a0b78 6079 foreach_volid($conf, sub {
392f8b5d 6080 my ($volid, $attr) = @_;
ff1a2432 6081
d5769dc2 6082 return if $volid =~ m|^/|;
ff1a2432 6083
d5769dc2
DM
6084 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
6085 return if !$sid;
ff1a2432
DM
6086
6087 push @$vollist, $volid;
1e3baf05 6088 });
ff1a2432
DM
6089
6090 return $vollist;
6091}
6092
1b189121
DC
6093sub cleanup_pci_devices {
6094 my ($vmid, $conf) = @_;
6095
6096 foreach my $key (keys %$conf) {
6097 next if $key !~ m/^hostpci(\d+)$/;
6098 my $hostpciindex = $1;
6099 my $uuid = PVE::SysFSTools::generate_mdev_uuid($vmid, $hostpciindex);
6100 my $d = parse_hostpci($conf->{$key});
faf72d6c
TL
6101 if ($d->{mdev}) {
6102 # NOTE: avoid PVE::SysFSTools::pci_cleanup_mdev_device as it requires PCI ID and we
6103 # don't want to break ABI just for this two liner
6104 my $dev_sysfs_dir = "/sys/bus/mdev/devices/$uuid";
49c51a60
DC
6105
6106 # some nvidia vgpu driver versions want to clean the mdevs up themselves, and error
6107 # out when we do it first. so wait for 10 seconds and then try it
9b71c34d 6108 if ($d->{ids}->[0]->[0]->{vendor} =~ m/^(0x)?10de$/) {
49c51a60
DC
6109 sleep 10;
6110 }
6111
faf72d6c
TL
6112 PVE::SysFSTools::file_write("$dev_sysfs_dir/remove", "1") if -e $dev_sysfs_dir;
6113 }
1b189121
DC
6114 }
6115 PVE::QemuServer::PCI::remove_pci_reservation($vmid);
6116}
6117
ff1a2432 6118sub vm_stop_cleanup {
70b04821 6119 my ($storecfg, $vmid, $conf, $keepActive, $apply_pending_changes) = @_;
ff1a2432 6120
745fed70 6121 eval {
ff1a2432 6122
254575e9
DM
6123 if (!$keepActive) {
6124 my $vollist = get_vm_volumes($conf);
6125 PVE::Storage::deactivate_volumes($storecfg, $vollist);
f9dde219
SR
6126
6127 if (my $tpmdrive = $conf->{tpmstate0}) {
6128 my $tpm = parse_drive("tpmstate0", $tpmdrive);
6129 my ($storeid, $volname) = PVE::Storage::parse_volume_id($tpm->{file}, 1);
6130 if ($storeid) {
6131 PVE::Storage::unmap_volume($storecfg, $tpm->{file});
6132 }
6133 }
254575e9 6134 }
a1b7d579 6135
ab6a046f 6136 foreach my $ext (qw(mon qmp pid vnc qga)) {
961bfcb2
DM
6137 unlink "/var/run/qemu-server/${vmid}.$ext";
6138 }
a1b7d579 6139
6dbcb073 6140 if ($conf->{ivshmem}) {
4df98f2f 6141 my $ivshmem = parse_property_string($ivshmem_fmt, $conf->{ivshmem});
4c5a6a24
TL
6142 # just delete it for now, VMs which have this already open do not
6143 # are affected, but new VMs will get a separated one. If this
6144 # becomes an issue we either add some sort of ref-counting or just
6145 # add a "don't delete on stop" flag to the ivshmem format.
6dbcb073
DC
6146 unlink '/dev/shm/pve-shm-' . ($ivshmem->{name} // $vmid);
6147 }
6148
1b189121 6149 cleanup_pci_devices($vmid, $conf);
6ab45bd7 6150
70b04821 6151 vmconfig_apply_pending($vmid, $conf, $storecfg) if $apply_pending_changes;
745fed70
DM
6152 };
6153 warn $@ if $@; # avoid errors - just warn
1e3baf05
DM
6154}
6155
575d19da
DC
6156# call only in locked context
6157sub _do_vm_stop {
6158 my ($storecfg, $vmid, $skiplock, $nocheck, $timeout, $shutdown, $force, $keepActive) = @_;
9269013a 6159
575d19da
DC
6160 my $pid = check_running($vmid, $nocheck);
6161 return if !$pid;
1e3baf05 6162
575d19da
DC
6163 my $conf;
6164 if (!$nocheck) {
6165 $conf = PVE::QemuConfig->load_config($vmid);
6166 PVE::QemuConfig->check_lock($conf) if !$skiplock;
6167 if (!defined($timeout) && $shutdown && $conf->{startup}) {
6168 my $opts = PVE::JSONSchema::pve_parse_startup_order($conf->{startup});
6169 $timeout = $opts->{down} if $opts->{down};
e6c3b671 6170 }
575d19da
DC
6171 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-stop');
6172 }
19672434 6173
575d19da
DC
6174 eval {
6175 if ($shutdown) {
a2af1bbe 6176 if (defined($conf) && get_qga_key($conf, 'enabled')) {
0a13e08e 6177 mon_cmd($vmid, "guest-shutdown", timeout => $timeout);
9269013a 6178 } else {
0a13e08e 6179 mon_cmd($vmid, "system_powerdown");
1e3baf05
DM
6180 }
6181 } else {
0a13e08e 6182 mon_cmd($vmid, "quit");
1e3baf05 6183 }
575d19da
DC
6184 };
6185 my $err = $@;
1e3baf05 6186
575d19da
DC
6187 if (!$err) {
6188 $timeout = 60 if !defined($timeout);
1e3baf05
DM
6189
6190 my $count = 0;
e6c3b671 6191 while (($count < $timeout) && check_running($vmid, $nocheck)) {
1e3baf05
DM
6192 $count++;
6193 sleep 1;
6194 }
6195
6196 if ($count >= $timeout) {
575d19da
DC
6197 if ($force) {
6198 warn "VM still running - terminating now with SIGTERM\n";
6199 kill 15, $pid;
6200 } else {
6201 die "VM quit/powerdown failed - got timeout\n";
6202 }
6203 } else {
6204 vm_stop_cleanup($storecfg, $vmid, $conf, $keepActive, 1) if $conf;
6205 return;
1e3baf05 6206 }
575d19da 6207 } else {
d60cbb97
TL
6208 if (!check_running($vmid, $nocheck)) {
6209 warn "Unexpected: VM shutdown command failed, but VM not running anymore..\n";
6210 return;
6211 }
6212 if ($force) {
575d19da
DC
6213 warn "VM quit/powerdown failed - terminating now with SIGTERM\n";
6214 kill 15, $pid;
6215 } else {
6216 die "VM quit/powerdown failed\n";
6217 }
6218 }
6219
6220 # wait again
6221 $timeout = 10;
6222
6223 my $count = 0;
6224 while (($count < $timeout) && check_running($vmid, $nocheck)) {
6225 $count++;
6226 sleep 1;
6227 }
6228
6229 if ($count >= $timeout) {
6230 warn "VM still running - terminating now with SIGKILL\n";
6231 kill 9, $pid;
6232 sleep 1;
6233 }
1e3baf05 6234
575d19da
DC
6235 vm_stop_cleanup($storecfg, $vmid, $conf, $keepActive, 1) if $conf;
6236}
6237
6238# Note: use $nocheck to skip tests if VM configuration file exists.
6239# We need that when migration VMs to other nodes (files already moved)
6240# Note: we set $keepActive in vzdump stop mode - volumes need to stay active
6241sub vm_stop {
6242 my ($storecfg, $vmid, $skiplock, $nocheck, $timeout, $shutdown, $force, $keepActive, $migratedfrom) = @_;
6243
6244 $force = 1 if !defined($force) && !$shutdown;
6245
6246 if ($migratedfrom){
6247 my $pid = check_running($vmid, $nocheck, $migratedfrom);
6248 kill 15, $pid if $pid;
6249 my $conf = PVE::QemuConfig->load_config($vmid, $migratedfrom);
6250 vm_stop_cleanup($storecfg, $vmid, $conf, $keepActive, 0);
6251 return;
6252 }
6253
6254 PVE::QemuConfig->lock_config($vmid, sub {
6255 _do_vm_stop($storecfg, $vmid, $skiplock, $nocheck, $timeout, $shutdown, $force, $keepActive);
ff1a2432 6256 });
1e3baf05
DM
6257}
6258
165411f0
DC
6259sub vm_reboot {
6260 my ($vmid, $timeout) = @_;
6261
6262 PVE::QemuConfig->lock_config($vmid, sub {
66026117 6263 eval {
165411f0 6264
66026117
OB
6265 # only reboot if running, as qmeventd starts it again on a stop event
6266 return if !check_running($vmid);
165411f0 6267
66026117 6268 create_reboot_request($vmid);
165411f0 6269
66026117
OB
6270 my $storecfg = PVE::Storage::config();
6271 _do_vm_stop($storecfg, $vmid, undef, undef, $timeout, 1);
165411f0 6272
66026117
OB
6273 };
6274 if (my $err = $@) {
3c1c3fe6 6275 # avoid that the next normal shutdown will be confused for a reboot
66026117
OB
6276 clear_reboot_request($vmid);
6277 die $err;
6278 }
165411f0
DC
6279 });
6280}
6281
75c24bba 6282# note: if using the statestorage parameter, the caller has to check privileges
1e3baf05 6283sub vm_suspend {
48b4cdc2 6284 my ($vmid, $skiplock, $includestate, $statestorage) = @_;
159719e5
DC
6285
6286 my $conf;
6287 my $path;
6288 my $storecfg;
6289 my $vmstate;
1e3baf05 6290
ffda963f 6291 PVE::QemuConfig->lock_config($vmid, sub {
1e3baf05 6292
159719e5 6293 $conf = PVE::QemuConfig->load_config($vmid);
1e3baf05 6294
159719e5 6295 my $is_backing_up = PVE::QemuConfig->has_lock($conf, 'backup');
e79706d4 6296 PVE::QemuConfig->check_lock($conf)
159719e5
DC
6297 if !($skiplock || $is_backing_up);
6298
6299 die "cannot suspend to disk during backup\n"
6300 if $is_backing_up && $includestate;
bcb7c9cf 6301
159719e5
DC
6302 if ($includestate) {
6303 $conf->{lock} = 'suspending';
6304 my $date = strftime("%Y-%m-%d", localtime(time()));
6305 $storecfg = PVE::Storage::config();
75c24bba
DC
6306 if (!$statestorage) {
6307 $statestorage = find_vmstate_storage($conf, $storecfg);
6308 # check permissions for the storage
6309 my $rpcenv = PVE::RPCEnvironment::get();
6310 if ($rpcenv->{type} ne 'cli') {
6311 my $authuser = $rpcenv->get_user();
6312 $rpcenv->check($authuser, "/storage/$statestorage", ['Datastore.AllocateSpace']);
6313 }
6314 }
6315
6316
4df98f2f
TL
6317 $vmstate = PVE::QemuConfig->__snapshot_save_vmstate(
6318 $vmid, $conf, "suspend-$date", $storecfg, $statestorage, 1);
159719e5
DC
6319 $path = PVE::Storage::path($storecfg, $vmstate);
6320 PVE::QemuConfig->write_config($vmid, $conf);
6321 } else {
0a13e08e 6322 mon_cmd($vmid, "stop");
159719e5 6323 }
1e3baf05 6324 });
159719e5
DC
6325
6326 if ($includestate) {
6327 # save vm state
6328 PVE::Storage::activate_volumes($storecfg, [$vmstate]);
6329
6330 eval {
27a5be53 6331 set_migration_caps($vmid, 1);
0a13e08e 6332 mon_cmd($vmid, "savevm-start", statefile => $path);
159719e5 6333 for(;;) {
0a13e08e 6334 my $state = mon_cmd($vmid, "query-savevm");
159719e5
DC
6335 if (!$state->{status}) {
6336 die "savevm not active\n";
6337 } elsif ($state->{status} eq 'active') {
6338 sleep(1);
6339 next;
6340 } elsif ($state->{status} eq 'completed') {
b0a9a385 6341 print "State saved, quitting\n";
159719e5
DC
6342 last;
6343 } elsif ($state->{status} eq 'failed' && $state->{error}) {
6344 die "query-savevm failed with error '$state->{error}'\n"
6345 } else {
6346 die "query-savevm returned status '$state->{status}'\n";
6347 }
6348 }
6349 };
6350 my $err = $@;
6351
6352 PVE::QemuConfig->lock_config($vmid, sub {
6353 $conf = PVE::QemuConfig->load_config($vmid);
6354 if ($err) {
6355 # cleanup, but leave suspending lock, to indicate something went wrong
6356 eval {
0a13e08e 6357 mon_cmd($vmid, "savevm-end");
159719e5
DC
6358 PVE::Storage::deactivate_volumes($storecfg, [$vmstate]);
6359 PVE::Storage::vdisk_free($storecfg, $vmstate);
ea1c2110 6360 delete $conf->@{qw(vmstate runningmachine runningcpu)};
159719e5
DC
6361 PVE::QemuConfig->write_config($vmid, $conf);
6362 };
6363 warn $@ if $@;
6364 die $err;
6365 }
6366
6367 die "lock changed unexpectedly\n"
6368 if !PVE::QemuConfig->has_lock($conf, 'suspending');
6369
0a13e08e 6370 mon_cmd($vmid, "quit");
159719e5
DC
6371 $conf->{lock} = 'suspended';
6372 PVE::QemuConfig->write_config($vmid, $conf);
6373 });
6374 }
1e3baf05
DM
6375}
6376
a20dc58a
FG
6377# $nocheck is set when called as part of a migration - in this context the
6378# location of the config file (source or target node) is not deterministic,
6379# since migration cannot wait for pmxcfs to process the rename
1e3baf05 6380sub vm_resume {
289e0b85 6381 my ($vmid, $skiplock, $nocheck) = @_;
1e3baf05 6382
ffda963f 6383 PVE::QemuConfig->lock_config($vmid, sub {
0a13e08e 6384 my $res = mon_cmd($vmid, 'query-status');
c2786bed 6385 my $resume_cmd = 'cont';
8e0c97bb 6386 my $reset = 0;
270bfff2
FG
6387 my $conf;
6388 if ($nocheck) {
ad9e347c
FG
6389 $conf = eval { PVE::QemuConfig->load_config($vmid) }; # try on target node
6390 if ($@) {
6391 my $vmlist = PVE::Cluster::get_vmlist();
6392 if (exists($vmlist->{ids}->{$vmid})) {
6393 my $node = $vmlist->{ids}->{$vmid}->{node};
6394 $conf = eval { PVE::QemuConfig->load_config($vmid, $node) }; # try on source node
6395 }
6396 if (!$conf) {
6397 PVE::Cluster::cfs_update(); # vmlist was wrong, invalidate cache
6398 $conf = PVE::QemuConfig->load_config($vmid); # last try on target node again
6399 }
270bfff2 6400 }
270bfff2
FG
6401 } else {
6402 $conf = PVE::QemuConfig->load_config($vmid);
6403 }
c2786bed 6404
8e0c97bb
SR
6405 if ($res->{status}) {
6406 return if $res->{status} eq 'running'; # job done, go home
6407 $resume_cmd = 'system_wakeup' if $res->{status} eq 'suspended';
6408 $reset = 1 if $res->{status} eq 'shutdown';
c2786bed
DC
6409 }
6410
289e0b85 6411 if (!$nocheck) {
e79706d4
FG
6412 PVE::QemuConfig->check_lock($conf)
6413 if !($skiplock || PVE::QemuConfig->has_lock($conf, 'backup'));
289e0b85 6414 }
3e24733b 6415
8e0c97bb
SR
6416 if ($reset) {
6417 # required if a VM shuts down during a backup and we get a resume
6418 # request before the backup finishes for example
6419 mon_cmd($vmid, "system_reset");
6420 }
21947fea
AD
6421
6422 add_nets_bridge_fdb($conf, $vmid) if $resume_cmd eq 'cont';
6423
0a13e08e 6424 mon_cmd($vmid, $resume_cmd);
1e3baf05
DM
6425 });
6426}
6427
5fdbe4f0
DM
6428sub vm_sendkey {
6429 my ($vmid, $skiplock, $key) = @_;
1e3baf05 6430
ffda963f 6431 PVE::QemuConfig->lock_config($vmid, sub {
1e3baf05 6432
ffda963f 6433 my $conf = PVE::QemuConfig->load_config($vmid);
f5eb281a 6434
7b7c6d1b 6435 # there is no qmp command, so we use the human monitor command
0a13e08e 6436 my $res = PVE::QemuServer::Monitor::hmp_cmd($vmid, "sendkey $key");
d30820d6 6437 die $res if $res ne '';
1e3baf05
DM
6438 });
6439}
6440
d6deb7f6
TL
6441sub check_bridge_access {
6442 my ($rpcenv, $authuser, $conf) = @_;
6443
6444 return 1 if $authuser eq 'root@pam';
6445
6446 for my $opt (sort keys $conf->%*) {
6447 next if $opt !~ m/^net\d+$/;
6448 my $net = parse_net($conf->{$opt});
6449 my ($bridge, $tag, $trunks) = $net->@{'bridge', 'tag', 'trunks'};
6450 PVE::GuestHelpers::check_vnet_access($rpcenv, $authuser, $bridge, $tag, $trunks);
6451 }
6452 return 1;
6453};
6454
e3971865
DC
6455sub check_mapping_access {
6456 my ($rpcenv, $user, $conf) = @_;
6457
6458 for my $opt (keys $conf->%*) {
6459 if ($opt =~ m/^usb\d+$/) {
6460 my $device = PVE::JSONSchema::parse_property_string('pve-qm-usb', $conf->{$opt});
6461 if (my $host = $device->{host}) {
6462 die "only root can set '$opt' config for real devices\n"
6463 if $host !~ m/^spice$/i && $user ne 'root@pam';
6464 } elsif ($device->{mapping}) {
6465 $rpcenv->check_full($user, "/mapping/usb/$device->{mapping}", ['Mapping.Use']);
6466 } else {
6467 die "either 'host' or 'mapping' must be set.\n";
6468 }
9b71c34d
DC
6469 } elsif ($opt =~ m/^hostpci\d+$/) {
6470 my $device = PVE::JSONSchema::parse_property_string('pve-qm-hostpci', $conf->{$opt});
6471 if ($device->{host}) {
6472 die "only root can set '$opt' config for non-mapped devices\n" if $user ne 'root@pam';
6473 } elsif ($device->{mapping}) {
6474 $rpcenv->check_full($user, "/mapping/pci/$device->{mapping}", ['Mapping.Use']);
6475 } else {
6476 die "either 'host' or 'mapping' must be set.\n";
6477 }
e3971865
DC
6478 }
6479 }
6480};
6481
e3971865
DC
6482sub check_restore_permissions {
6483 my ($rpcenv, $user, $conf) = @_;
621edb2b 6484
e3971865
DC
6485 check_bridge_access($rpcenv, $user, $conf);
6486 check_mapping_access($rpcenv, $user, $conf);
6487}
3e16d5fc
DM
6488# vzdump restore implementaion
6489
ed221350 6490sub tar_archive_read_firstfile {
3e16d5fc 6491 my $archive = shift;
afdb31d5 6492
3e16d5fc
DM
6493 die "ERROR: file '$archive' does not exist\n" if ! -f $archive;
6494
6495 # try to detect archive type first
387ba257 6496 my $pid = open (my $fh, '-|', 'tar', 'tf', $archive) ||
3e16d5fc 6497 die "unable to open file '$archive'\n";
387ba257 6498 my $firstfile = <$fh>;
3e16d5fc 6499 kill 15, $pid;
387ba257 6500 close $fh;
3e16d5fc
DM
6501
6502 die "ERROR: archive contaions no data\n" if !$firstfile;
6503 chomp $firstfile;
6504
6505 return $firstfile;
6506}
6507
ed221350
DM
6508sub tar_restore_cleanup {
6509 my ($storecfg, $statfile) = @_;
3e16d5fc
DM
6510
6511 print STDERR "starting cleanup\n";
6512
6513 if (my $fd = IO::File->new($statfile, "r")) {
6514 while (defined(my $line = <$fd>)) {
6515 if ($line =~ m/vzdump:([^\s:]*):(\S+)$/) {
6516 my $volid = $2;
6517 eval {
6518 if ($volid =~ m|^/|) {
6519 unlink $volid || die 'unlink failed\n';
6520 } else {
ed221350 6521 PVE::Storage::vdisk_free($storecfg, $volid);
3e16d5fc 6522 }
afdb31d5 6523 print STDERR "temporary volume '$volid' sucessfuly removed\n";
3e16d5fc
DM
6524 };
6525 print STDERR "unable to cleanup '$volid' - $@" if $@;
6526 } else {
6527 print STDERR "unable to parse line in statfile - $line";
afdb31d5 6528 }
3e16d5fc
DM
6529 }
6530 $fd->close();
6531 }
6532}
6533
d1e92cf6 6534sub restore_file_archive {
a0d1b1a2 6535 my ($archive, $vmid, $user, $opts) = @_;
3e16d5fc 6536
a2ec5a67
FG
6537 return restore_vma_archive($archive, $vmid, $user, $opts)
6538 if $archive eq '-';
6539
c6d51783
AA
6540 my $info = PVE::Storage::archive_info($archive);
6541 my $format = $opts->{format} // $info->{format};
6542 my $comp = $info->{compression};
91bd6c90
DM
6543
6544 # try to detect archive format
6545 if ($format eq 'tar') {
6546 return restore_tar_archive($archive, $vmid, $user, $opts);
6547 } else {
6548 return restore_vma_archive($archive, $vmid, $user, $opts, $comp);
6549 }
6550}
6551
d1e92cf6
DM
6552# hepler to remove disks that will not be used after restore
6553my $restore_cleanup_oldconf = sub {
6554 my ($storecfg, $vmid, $oldconf, $virtdev_hash) = @_;
6555
01a4377f
FE
6556 my $kept_disks = {};
6557
912792e2 6558 PVE::QemuConfig->foreach_volume($oldconf, sub {
d1e92cf6
DM
6559 my ($ds, $drive) = @_;
6560
6561 return if drive_is_cdrom($drive, 1);
6562
6563 my $volid = $drive->{file};
6564 return if !$volid || $volid =~ m|^/|;
6565
6566 my ($path, $owner) = PVE::Storage::path($storecfg, $volid);
6567 return if !$path || !$owner || ($owner != $vmid);
6568
6569 # Note: only delete disk we want to restore
6570 # other volumes will become unused
6571 if ($virtdev_hash->{$ds}) {
6572 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
6573 if (my $err = $@) {
6574 warn $err;
6575 }
01a4377f
FE
6576 } else {
6577 $kept_disks->{$volid} = 1;
d1e92cf6
DM
6578 }
6579 });
6580
01a4377f
FE
6581 # after the restore we have no snapshots anymore
6582 for my $snapname (keys $oldconf->{snapshots}->%*) {
d1e92cf6
DM
6583 my $snap = $oldconf->{snapshots}->{$snapname};
6584 if ($snap->{vmstate}) {
6585 eval { PVE::Storage::vdisk_free($storecfg, $snap->{vmstate}); };
6586 if (my $err = $@) {
6587 warn $err;
6588 }
6589 }
01a4377f
FE
6590
6591 for my $volid (keys $kept_disks->%*) {
6592 eval { PVE::Storage::volume_snapshot_delete($storecfg, $volid, $snapname); };
6593 warn $@ if $@;
6594 }
d1e92cf6
DM
6595 }
6596};
6597
9f3d73bc
DM
6598# Helper to parse vzdump backup device hints
6599#
6600# $rpcenv: Environment, used to ckeck storage permissions
6601# $user: User ID, to check storage permissions
6602# $storecfg: Storage configuration
6603# $fh: the file handle for reading the configuration
6604# $devinfo: should contain device sizes for all backu-up'ed devices
6605# $options: backup options (pool, default storage)
6606#
6607# Return: $virtdev_hash, updates $devinfo (add devname, virtdev, format, storeid)
6608my $parse_backup_hints = sub {
6609 my ($rpcenv, $user, $storecfg, $fh, $devinfo, $options) = @_;
d1e92cf6 6610
36d4bdcb
TL
6611 my $check_storage = sub { # assert if an image can be allocate
6612 my ($storeid, $scfg) = @_;
6613 die "Content type 'images' is not available on storage '$storeid'\n"
6614 if !$scfg->{content}->{images};
6615 $rpcenv->check($user, "/storage/$storeid", ['Datastore.AllocateSpace'])
6616 if $user ne 'root@pam';
6617 };
d1e92cf6 6618
36d4bdcb 6619 my $virtdev_hash = {};
9f3d73bc
DM
6620 while (defined(my $line = <$fh>)) {
6621 if ($line =~ m/^\#qmdump\#map:(\S+):(\S+):(\S*):(\S*):$/) {
6622 my ($virtdev, $devname, $storeid, $format) = ($1, $2, $3, $4);
6623 die "archive does not contain data for drive '$virtdev'\n"
6624 if !$devinfo->{$devname};
6625
6626 if (defined($options->{storage})) {
6627 $storeid = $options->{storage} || 'local';
6628 } elsif (!$storeid) {
6629 $storeid = 'local';
d1e92cf6 6630 }
9f3d73bc
DM
6631 $format = 'raw' if !$format;
6632 $devinfo->{$devname}->{devname} = $devname;
6633 $devinfo->{$devname}->{virtdev} = $virtdev;
6634 $devinfo->{$devname}->{format} = $format;
6635 $devinfo->{$devname}->{storeid} = $storeid;
6636
62af60cd 6637 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
36d4bdcb 6638 $check_storage->($storeid, $scfg); # permission and content type check
d1e92cf6 6639
9f3d73bc
DM
6640 $virtdev_hash->{$virtdev} = $devinfo->{$devname};
6641 } elsif ($line =~ m/^((?:ide|sata|scsi)\d+):\s*(.*)\s*$/) {
6642 my $virtdev = $1;
6643 my $drive = parse_drive($virtdev, $2);
36d4bdcb 6644
9f3d73bc
DM
6645 if (drive_is_cloudinit($drive)) {
6646 my ($storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file});
5364990d
TL
6647 $storeid = $options->{storage} if defined ($options->{storage});
6648 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
9f3d73bc 6649 my $format = qemu_img_format($scfg, $volname); # has 'raw' fallback
d1e92cf6 6650
36d4bdcb 6651 $check_storage->($storeid, $scfg); # permission and content type check
9f8ba326 6652
9f3d73bc
DM
6653 $virtdev_hash->{$virtdev} = {
6654 format => $format,
5364990d 6655 storeid => $storeid,
9f3d73bc
DM
6656 size => PVE::QemuServer::Cloudinit::CLOUDINIT_DISK_SIZE,
6657 is_cloudinit => 1,
6658 };
d1e92cf6 6659 }
9f3d73bc
DM
6660 }
6661 }
d1e92cf6 6662
9f3d73bc
DM
6663 return $virtdev_hash;
6664};
d1e92cf6 6665
9f3d73bc
DM
6666# Helper to allocate and activate all volumes required for a restore
6667#
6668# $storecfg: Storage configuration
6669# $virtdev_hash: as returned by parse_backup_hints()
6670#
6671# Returns: { $virtdev => $volid }
6672my $restore_allocate_devices = sub {
6673 my ($storecfg, $virtdev_hash, $vmid) = @_;
d1e92cf6 6674
9f3d73bc
DM
6675 my $map = {};
6676 foreach my $virtdev (sort keys %$virtdev_hash) {
6677 my $d = $virtdev_hash->{$virtdev};
6678 my $alloc_size = int(($d->{size} + 1024 - 1)/1024);
6679 my $storeid = $d->{storeid};
6680 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
d1e92cf6 6681
9f3d73bc
DM
6682 # test if requested format is supported
6683 my ($defFormat, $validFormats) = PVE::Storage::storage_default_format($storecfg, $storeid);
6684 my $supported = grep { $_ eq $d->{format} } @$validFormats;
6685 $d->{format} = $defFormat if !$supported;
d1e92cf6 6686
9f3d73bc
DM
6687 my $name;
6688 if ($d->{is_cloudinit}) {
6689 $name = "vm-$vmid-cloudinit";
c997e24a
ML
6690 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
6691 if ($scfg->{path}) {
6692 $name .= ".$d->{format}";
6693 }
d1e92cf6
DM
6694 }
6695
4df98f2f
TL
6696 my $volid = PVE::Storage::vdisk_alloc(
6697 $storecfg, $storeid, $vmid, $d->{format}, $name, $alloc_size);
d1e92cf6 6698
9f3d73bc
DM
6699 print STDERR "new volume ID is '$volid'\n";
6700 $d->{volid} = $volid;
d1e92cf6 6701
9f3d73bc 6702 PVE::Storage::activate_volumes($storecfg, [$volid]);
d1e92cf6 6703
9f3d73bc 6704 $map->{$virtdev} = $volid;
d1e92cf6
DM
6705 }
6706
9f3d73bc
DM
6707 return $map;
6708};
d1e92cf6 6709
c62d7cf5 6710sub restore_update_config_line {
eabac302 6711 my ($cookie, $map, $line, $unique) = @_;
91bd6c90 6712
98a4b3fb
FE
6713 return '' if $line =~ m/^\#qmdump\#/;
6714 return '' if $line =~ m/^\#vzdump\#/;
6715 return '' if $line =~ m/^lock:/;
6716 return '' if $line =~ m/^unused\d+:/;
6717 return '' if $line =~ m/^parent:/;
6718
6719 my $res = '';
91bd6c90 6720
b5b99790 6721 my $dc = PVE::Cluster::cfs_read_file('datacenter.cfg');
91bd6c90
DM
6722 if (($line =~ m/^(vlan(\d+)):\s*(\S+)\s*$/)) {
6723 # try to convert old 1.X settings
6724 my ($id, $ind, $ethcfg) = ($1, $2, $3);
6725 foreach my $devconfig (PVE::Tools::split_list($ethcfg)) {
6726 my ($model, $macaddr) = split(/\=/, $devconfig);
b5b99790 6727 $macaddr = PVE::Tools::random_ether_addr($dc->{mac_prefix}) if !$macaddr || $unique;
91bd6c90
DM
6728 my $net = {
6729 model => $model,
6730 bridge => "vmbr$ind",
6731 macaddr => $macaddr,
6732 };
6733 my $netstr = print_net($net);
6734
98a4b3fb 6735 $res .= "net$cookie->{netcount}: $netstr\n";
91bd6c90
DM
6736 $cookie->{netcount}++;
6737 }
6738 } elsif (($line =~ m/^(net\d+):\s*(\S+)\s*$/) && $unique) {
6739 my ($id, $netstr) = ($1, $2);
6740 my $net = parse_net($netstr);
b5b99790 6741 $net->{macaddr} = PVE::Tools::random_ether_addr($dc->{mac_prefix}) if $net->{macaddr};
91bd6c90 6742 $netstr = print_net($net);
98a4b3fb 6743 $res .= "$id: $netstr\n";
f9dde219 6744 } elsif ($line =~ m/^((ide|scsi|virtio|sata|efidisk|tpmstate)\d+):\s*(\S+)\s*$/) {
91bd6c90 6745 my $virtdev = $1;
907ea891 6746 my $value = $3;
d9faf790
WB
6747 my $di = parse_drive($virtdev, $value);
6748 if (defined($di->{backup}) && !$di->{backup}) {
98a4b3fb 6749 $res .= "#$line";
c0f7406e 6750 } elsif ($map->{$virtdev}) {
8fd57431 6751 delete $di->{format}; # format can change on restore
91bd6c90 6752 $di->{file} = $map->{$virtdev};
71c58bb7 6753 $value = print_drive($di);
98a4b3fb 6754 $res .= "$virtdev: $value\n";
91bd6c90 6755 } else {
98a4b3fb 6756 $res .= $line;
91bd6c90 6757 }
1a0c2f03 6758 } elsif (($line =~ m/^vmgenid: (.*)/)) {
babecffe 6759 my $vmgenid = $1;
6ee499ff 6760 if ($vmgenid ne '0') {
1a0c2f03 6761 # always generate a new vmgenid if there was a valid one setup
6ee499ff
DC
6762 $vmgenid = generate_uuid();
6763 }
98a4b3fb 6764 $res .= "vmgenid: $vmgenid\n";
19a5dd55
WL
6765 } elsif (($line =~ m/^(smbios1: )(.*)/) && $unique) {
6766 my ($uuid, $uuid_str);
6767 UUID::generate($uuid);
6768 UUID::unparse($uuid, $uuid_str);
6769 my $smbios1 = parse_smbios1($2);
6770 $smbios1->{uuid} = $uuid_str;
98a4b3fb 6771 $res .= $1.print_smbios1($smbios1)."\n";
91bd6c90 6772 } else {
98a4b3fb 6773 $res .= $line;
91bd6c90 6774 }
98a4b3fb
FE
6775
6776 return $res;
c62d7cf5 6777}
9f3d73bc
DM
6778
6779my $restore_deactivate_volumes = sub {
e8b07b29 6780 my ($storecfg, $virtdev_hash) = @_;
9f3d73bc
DM
6781
6782 my $vollist = [];
e8b07b29
FE
6783 for my $dev (values $virtdev_hash->%*) {
6784 push $vollist->@*, $dev->{volid} if $dev->{volid};
9f3d73bc
DM
6785 }
6786
ff86112c
FE
6787 eval { PVE::Storage::deactivate_volumes($storecfg, $vollist); };
6788 print STDERR $@ if $@;
9f3d73bc
DM
6789};
6790
6791my $restore_destroy_volumes = sub {
e8b07b29 6792 my ($storecfg, $virtdev_hash) = @_;
9f3d73bc 6793
e8b07b29
FE
6794 for my $dev (values $virtdev_hash->%*) {
6795 my $volid = $dev->{volid} or next;
9f3d73bc 6796 eval {
e60afe82 6797 PVE::Storage::vdisk_free($storecfg, $volid);
9f3d73bc
DM
6798 print STDERR "temporary volume '$volid' sucessfuly removed\n";
6799 };
6800 print STDERR "unable to cleanup '$volid' - $@" if $@;
6801 }
6802};
91bd6c90 6803
621edb2b 6804sub restore_merge_config {
202a2a0b
FE
6805 my ($filename, $backup_conf_raw, $override_conf) = @_;
6806
6807 my $backup_conf = parse_vm_config($filename, $backup_conf_raw);
6808 for my $key (keys $override_conf->%*) {
6809 $backup_conf->{$key} = $override_conf->{$key};
6810 }
6811
6812 return $backup_conf;
621edb2b 6813}
202a2a0b 6814
91bd6c90 6815sub scan_volids {
9a8ba127 6816 my ($cfg, $vmid) = @_;
91bd6c90 6817
9a8ba127 6818 my $info = PVE::Storage::vdisk_list($cfg, undef, $vmid, undef, 'images');
91bd6c90
DM
6819
6820 my $volid_hash = {};
6821 foreach my $storeid (keys %$info) {
6822 foreach my $item (@{$info->{$storeid}}) {
6823 next if !($item->{volid} && $item->{size});
5996a936 6824 $item->{path} = PVE::Storage::path($cfg, $item->{volid});
91bd6c90
DM
6825 $volid_hash->{$item->{volid}} = $item;
6826 }
6827 }
6828
6829 return $volid_hash;
6830}
6831
68b108ee 6832sub update_disk_config {
91bd6c90 6833 my ($vmid, $conf, $volid_hash) = @_;
be190583 6834
91bd6c90 6835 my $changes;
9b29cbd0 6836 my $prefix = "VM $vmid";
91bd6c90 6837
c449137a
DC
6838 # used and unused disks
6839 my $referenced = {};
91bd6c90 6840
5996a936
DM
6841 # Note: it is allowed to define multiple storages with same path (alias), so
6842 # we need to check both 'volid' and real 'path' (two different volid can point
6843 # to the same path).
6844
c449137a 6845 my $referencedpath = {};
be190583 6846
91bd6c90 6847 # update size info
0c4fef3f 6848 PVE::QemuConfig->foreach_volume($conf, sub {
ca04977c 6849 my ($opt, $drive) = @_;
91bd6c90 6850
ca04977c
FE
6851 my $volid = $drive->{file};
6852 return if !$volid;
4df98f2f 6853 my $volume = $volid_hash->{$volid};
91bd6c90 6854
ca04977c
FE
6855 # mark volid as "in-use" for next step
6856 $referenced->{$volid} = 1;
4df98f2f 6857 if ($volume && (my $path = $volume->{path})) {
ca04977c 6858 $referencedpath->{$path} = 1;
91bd6c90 6859 }
ca04977c
FE
6860
6861 return if drive_is_cdrom($drive);
4df98f2f 6862 return if !$volume;
ca04977c 6863
4df98f2f 6864 my ($updated, $msg) = PVE::QemuServer::Drive::update_disksize($drive, $volume->{size});
ca04977c
FE
6865 if (defined($updated)) {
6866 $changes = 1;
6867 $conf->{$opt} = print_drive($updated);
9b29cbd0 6868 print "$prefix ($opt): $msg\n";
ca04977c
FE
6869 }
6870 });
91bd6c90 6871
5996a936 6872 # remove 'unusedX' entry if volume is used
ca04977c
FE
6873 PVE::QemuConfig->foreach_unused_volume($conf, sub {
6874 my ($opt, $drive) = @_;
6875
6876 my $volid = $drive->{file};
6877 return if !$volid;
6878
f7d1505b
TL
6879 my $path;
6880 $path = $volid_hash->{$volid}->{path} if $volid_hash->{$volid};
c449137a 6881 if ($referenced->{$volid} || ($path && $referencedpath->{$path})) {
68b108ee 6882 print "$prefix remove entry '$opt', its volume '$volid' is in use\n";
5996a936
DM
6883 $changes = 1;
6884 delete $conf->{$opt};
6885 }
c449137a
DC
6886
6887 $referenced->{$volid} = 1;
6888 $referencedpath->{$path} = 1 if $path;
ca04977c 6889 });
5996a936 6890
91bd6c90
DM
6891 foreach my $volid (sort keys %$volid_hash) {
6892 next if $volid =~ m/vm-$vmid-state-/;
c449137a 6893 next if $referenced->{$volid};
5996a936
DM
6894 my $path = $volid_hash->{$volid}->{path};
6895 next if !$path; # just to be sure
c449137a 6896 next if $referencedpath->{$path};
91bd6c90 6897 $changes = 1;
53b81297 6898 my $key = PVE::QemuConfig->add_unused_volume($conf, $volid);
68b108ee 6899 print "$prefix add unreferenced volume '$volid' as '$key' to config\n";
c449137a 6900 $referencedpath->{$path} = 1; # avoid to add more than once (aliases)
91bd6c90
DM
6901 }
6902
6903 return $changes;
6904}
6905
6906sub rescan {
9224dcee 6907 my ($vmid, $nolock, $dryrun) = @_;
91bd6c90 6908
20519efc 6909 my $cfg = PVE::Storage::config();
91bd6c90 6910
53b81297 6911 print "rescan volumes...\n";
9a8ba127 6912 my $volid_hash = scan_volids($cfg, $vmid);
91bd6c90
DM
6913
6914 my $updatefn = sub {
6915 my ($vmid) = @_;
6916
ffda963f 6917 my $conf = PVE::QemuConfig->load_config($vmid);
be190583 6918
ffda963f 6919 PVE::QemuConfig->check_lock($conf);
91bd6c90 6920
03da3f0d
DM
6921 my $vm_volids = {};
6922 foreach my $volid (keys %$volid_hash) {
6923 my $info = $volid_hash->{$volid};
6924 $vm_volids->{$volid} = $info if $info->{vmid} && $info->{vmid} == $vmid;
6925 }
6926
68b108ee 6927 my $changes = update_disk_config($vmid, $conf, $vm_volids);
91bd6c90 6928
9224dcee 6929 PVE::QemuConfig->write_config($vmid, $conf) if $changes && !$dryrun;
91bd6c90
DM
6930 };
6931
6932 if (defined($vmid)) {
6933 if ($nolock) {
6934 &$updatefn($vmid);
6935 } else {
ffda963f 6936 PVE::QemuConfig->lock_config($vmid, $updatefn, $vmid);
91bd6c90
DM
6937 }
6938 } else {
6939 my $vmlist = config_list();
6940 foreach my $vmid (keys %$vmlist) {
6941 if ($nolock) {
6942 &$updatefn($vmid);
6943 } else {
ffda963f 6944 PVE::QemuConfig->lock_config($vmid, $updatefn, $vmid);
be190583 6945 }
91bd6c90
DM
6946 }
6947 }
6948}
6949
9f3d73bc
DM
6950sub restore_proxmox_backup_archive {
6951 my ($archive, $vmid, $user, $options) = @_;
6952
6953 my $storecfg = PVE::Storage::config();
6954
6955 my ($storeid, $volname) = PVE::Storage::parse_volume_id($archive);
6956 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
6957
9f3d73bc 6958 my $fingerprint = $scfg->{fingerprint};
503e96f8 6959 my $keyfile = PVE::Storage::PBSPlugin::pbs_encryption_key_file_name($storecfg, $storeid);
9f3d73bc 6960
fbec3f89 6961 my $repo = PVE::PBSClient::get_repository($scfg);
2dda626d 6962 my $namespace = $scfg->{namespace};
dea4b04c 6963
26731a3c 6964 # This is only used for `pbs-restore` and the QEMU PBS driver (live-restore)
9f3d73bc
DM
6965 my $password = PVE::Storage::PBSPlugin::pbs_get_password($scfg, $storeid);
6966 local $ENV{PBS_PASSWORD} = $password;
6967 local $ENV{PBS_FINGERPRINT} = $fingerprint if defined($fingerprint);
6968
6969 my ($vtype, $pbs_backup_name, undef, undef, undef, undef, $format) =
6970 PVE::Storage::parse_volname($storecfg, $archive);
6971
6972 die "got unexpected vtype '$vtype'\n" if $vtype ne 'backup';
6973
6974 die "got unexpected backup format '$format'\n" if $format ne 'pbs-vm';
6975
6976 my $tmpdir = "/var/tmp/vzdumptmp$$";
6977 rmtree $tmpdir;
6978 mkpath $tmpdir;
6979
6980 my $conffile = PVE::QemuConfig->config_file($vmid);
9f3d73bc
DM
6981 # disable interrupts (always do cleanups)
6982 local $SIG{INT} =
6983 local $SIG{TERM} =
6984 local $SIG{QUIT} =
6985 local $SIG{HUP} = sub { print STDERR "got interrupt - ignored\n"; };
6986
6987 # Note: $oldconf is undef if VM does not exists
6988 my $cfs_path = PVE::QemuConfig->cfs_config_path($vmid);
6989 my $oldconf = PVE::Cluster::cfs_read_file($cfs_path);
98a4b3fb 6990 my $new_conf_raw = '';
9f3d73bc
DM
6991
6992 my $rpcenv = PVE::RPCEnvironment::get();
e8b07b29
FE
6993 my $devinfo = {}; # info about drives included in backup
6994 my $virtdev_hash = {}; # info about allocated drives
9f3d73bc
DM
6995
6996 eval {
6997 # enable interrupts
6998 local $SIG{INT} =
6999 local $SIG{TERM} =
7000 local $SIG{QUIT} =
7001 local $SIG{HUP} =
7002 local $SIG{PIPE} = sub { die "interrupted by signal\n"; };
7003
7004 my $cfgfn = "$tmpdir/qemu-server.conf";
7005 my $firewall_config_fn = "$tmpdir/fw.conf";
7006 my $index_fn = "$tmpdir/index.json";
7007
7008 my $cmd = "restore";
7009
7010 my $param = [$pbs_backup_name, "index.json", $index_fn];
7011 PVE::Storage::PBSPlugin::run_raw_client_cmd($scfg, $storeid, $cmd, $param);
7012 my $index = PVE::Tools::file_get_contents($index_fn);
7013 $index = decode_json($index);
7014
9f3d73bc
DM
7015 foreach my $info (@{$index->{files}}) {
7016 if ($info->{filename} =~ m/^(drive-\S+).img.fidx$/) {
7017 my $devname = $1;
7018 if ($info->{size} =~ m/^(\d+)$/) { # untaint size
7019 $devinfo->{$devname}->{size} = $1;
7020 } else {
7021 die "unable to parse file size in 'index.json' - got '$info->{size}'\n";
7022 }
7023 }
7024 }
7025
4df98f2f
TL
7026 my $is_qemu_server_backup = scalar(
7027 grep { $_->{filename} eq 'qemu-server.conf.blob' } @{$index->{files}}
7028 );
9f3d73bc
DM
7029 if (!$is_qemu_server_backup) {
7030 die "backup does not look like a qemu-server backup (missing 'qemu-server.conf' file)\n";
7031 }
7032 my $has_firewall_config = scalar(grep { $_->{filename} eq 'fw.conf.blob' } @{$index->{files}});
7033
7034 $param = [$pbs_backup_name, "qemu-server.conf", $cfgfn];
7035 PVE::Storage::PBSPlugin::run_raw_client_cmd($scfg, $storeid, $cmd, $param);
7036
7037 if ($has_firewall_config) {
7038 $param = [$pbs_backup_name, "fw.conf", $firewall_config_fn];
7039 PVE::Storage::PBSPlugin::run_raw_client_cmd($scfg, $storeid, $cmd, $param);
7040
7041 my $pve_firewall_dir = '/etc/pve/firewall';
7042 mkdir $pve_firewall_dir; # make sure the dir exists
7043 PVE::Tools::file_copy($firewall_config_fn, "${pve_firewall_dir}/$vmid.fw");
7044 }
7045
7046 my $fh = IO::File->new($cfgfn, "r") ||
a1cbe55c 7047 die "unable to read qemu-server.conf - $!\n";
9f3d73bc 7048
e8b07b29 7049 $virtdev_hash = $parse_backup_hints->($rpcenv, $user, $storecfg, $fh, $devinfo, $options);
9f3d73bc
DM
7050
7051 # fixme: rate limit?
7052
7053 # create empty/temp config
7054 PVE::Tools::file_set_contents($conffile, "memory: 128\nlock: create");
7055
7056 $restore_cleanup_oldconf->($storecfg, $vmid, $oldconf, $virtdev_hash) if $oldconf;
7057
7058 # allocate volumes
7059 my $map = $restore_allocate_devices->($storecfg, $virtdev_hash, $vmid);
7060
6f94e162
SR
7061 foreach my $virtdev (sort keys %$virtdev_hash) {
7062 my $d = $virtdev_hash->{$virtdev};
7063 next if $d->{is_cloudinit}; # no need to restore cloudinit
9f3d73bc 7064
55c7f9cf 7065 # this fails if storage is unavailable
6f94e162 7066 my $volid = $d->{volid};
6f94e162 7067 my $path = PVE::Storage::path($storecfg, $volid);
9f3d73bc 7068
f9dde219
SR
7069 # for live-restore we only want to preload the efidisk and TPM state
7070 next if $options->{live} && $virtdev ne 'efidisk0' && $virtdev ne 'tpmstate0';
55c7f9cf 7071
21a9ec2a
WB
7072 my @ns_arg;
7073 if (defined(my $ns = $scfg->{namespace})) {
7074 @ns_arg = ('--ns', $ns);
7075 }
7076
6f94e162
SR
7077 my $pbs_restore_cmd = [
7078 '/usr/bin/pbs-restore',
7079 '--repository', $repo,
21a9ec2a 7080 @ns_arg,
6f94e162
SR
7081 $pbs_backup_name,
7082 "$d->{devname}.img.fidx",
7083 $path,
7084 '--verbose',
7085 ];
55fb78aa 7086
6f94e162
SR
7087 push @$pbs_restore_cmd, '--format', $d->{format} if $d->{format};
7088 push @$pbs_restore_cmd, '--keyfile', $keyfile if -e $keyfile;
9f3d73bc 7089
6f94e162
SR
7090 if (PVE::Storage::volume_has_feature($storecfg, 'sparseinit', $volid)) {
7091 push @$pbs_restore_cmd, '--skip-zero';
26731a3c 7092 }
6f94e162
SR
7093
7094 my $dbg_cmdstring = PVE::Tools::cmd2string($pbs_restore_cmd);
7095 print "restore proxmox backup image: $dbg_cmdstring\n";
7096 run_command($pbs_restore_cmd);
9f3d73bc
DM
7097 }
7098
7099 $fh->seek(0, 0) || die "seek failed - $!\n";
7100
9f3d73bc
DM
7101 my $cookie = { netcount => 0 };
7102 while (defined(my $line = <$fh>)) {
c62d7cf5 7103 $new_conf_raw .= restore_update_config_line(
98a4b3fb 7104 $cookie,
98a4b3fb
FE
7105 $map,
7106 $line,
7107 $options->{unique},
7108 );
9f3d73bc
DM
7109 }
7110
7111 $fh->close();
9f3d73bc
DM
7112 };
7113 my $err = $@;
7114
26731a3c 7115 if ($err || !$options->{live}) {
e8b07b29 7116 $restore_deactivate_volumes->($storecfg, $virtdev_hash);
26731a3c 7117 }
9f3d73bc
DM
7118
7119 rmtree $tmpdir;
7120
7121 if ($err) {
e8b07b29 7122 $restore_destroy_volumes->($storecfg, $virtdev_hash);
9f3d73bc
DM
7123 die $err;
7124 }
7125
f7551170
SR
7126 if ($options->{live}) {
7127 # keep lock during live-restore
7128 $new_conf_raw .= "\nlock: create";
7129 }
7130
621edb2b 7131 my $new_conf = restore_merge_config($conffile, $new_conf_raw, $options->{override_conf});
e3971865 7132 check_restore_permissions($rpcenv, $user, $new_conf);
202a2a0b 7133 PVE::QemuConfig->write_config($vmid, $new_conf);
9f3d73bc
DM
7134
7135 eval { rescan($vmid, 1); };
7136 warn $@ if $@;
26731a3c
SR
7137
7138 PVE::AccessControl::add_vm_to_pool($vmid, $options->{pool}) if $options->{pool};
7139
7140 if ($options->{live}) {
fefd65a1
SR
7141 # enable interrupts
7142 local $SIG{INT} =
7143 local $SIG{TERM} =
7144 local $SIG{QUIT} =
7145 local $SIG{HUP} =
7146 local $SIG{PIPE} = sub { die "got signal ($!) - abort\n"; };
26731a3c 7147
fefd65a1
SR
7148 my $conf = PVE::QemuConfig->load_config($vmid);
7149 die "cannot do live-restore for template\n" if PVE::QemuConfig->is_template($conf);
26731a3c 7150
f9dde219
SR
7151 # these special drives are already restored before start
7152 delete $devinfo->{'drive-efidisk0'};
7153 delete $devinfo->{'drive-tpmstate0-backup'};
2dda626d
DC
7154
7155 my $pbs_opts = {
7156 repo => $repo,
7157 keyfile => $keyfile,
7158 snapshot => $pbs_backup_name,
7159 namespace => $namespace,
7160 };
7161 pbs_live_restore($vmid, $conf, $storecfg, $devinfo, $pbs_opts);
f7551170
SR
7162
7163 PVE::QemuConfig->remove_lock($vmid, "create");
26731a3c
SR
7164 }
7165}
7166
7167sub pbs_live_restore {
2dda626d 7168 my ($vmid, $conf, $storecfg, $restored_disks, $opts) = @_;
26731a3c 7169
88cabb62 7170 print "starting VM for live-restore\n";
2dda626d 7171 print "repository: '$opts->{repo}', snapshot: '$opts->{snapshot}'\n";
26731a3c
SR
7172
7173 my $pbs_backing = {};
8986e36e 7174 for my $ds (keys %$restored_disks) {
26731a3c 7175 $ds =~ m/^drive-(.*)$/;
88cabb62
SR
7176 my $confname = $1;
7177 $pbs_backing->{$confname} = {
2dda626d
DC
7178 repository => $opts->{repo},
7179 snapshot => $opts->{snapshot},
26731a3c
SR
7180 archive => "$ds.img.fidx",
7181 };
2dda626d
DC
7182 $pbs_backing->{$confname}->{keyfile} = $opts->{keyfile} if -e $opts->{keyfile};
7183 $pbs_backing->{$confname}->{namespace} = $opts->{namespace} if defined($opts->{namespace});
88cabb62
SR
7184
7185 my $drive = parse_drive($confname, $conf->{$confname});
7186 print "restoring '$ds' to '$drive->{file}'\n";
26731a3c
SR
7187 }
7188
fd70c843 7189 my $drives_streamed = 0;
26731a3c
SR
7190 eval {
7191 # make sure HA doesn't interrupt our restore by stopping the VM
7192 if (PVE::HA::Config::vm_is_ha_managed($vmid)) {
fd70c843 7193 run_command(['ha-manager', 'set', "vm:$vmid", '--state', 'started']);
26731a3c
SR
7194 }
7195
fd70c843
TL
7196 # start VM with backing chain pointing to PBS backup, environment vars for PBS driver
7197 # in QEMU (PBS_PASSWORD and PBS_FINGERPRINT) are already set by our caller
bfb12678 7198 vm_start_nolock($storecfg, $vmid, $conf, {paused => 1, 'pbs-backing' => $pbs_backing}, {});
26731a3c 7199
26697640
SR
7200 my $qmeventd_fd = register_qmeventd_handle($vmid);
7201
26731a3c
SR
7202 # begin streaming, i.e. data copy from PBS to target disk for every vol,
7203 # this will effectively collapse the backing image chain consisting of
7204 # [target <- alloc-track -> PBS snapshot] to just [target] (alloc-track
7205 # removes itself once all backing images vanish with 'auto-remove=on')
7206 my $jobs = {};
8986e36e 7207 for my $ds (sort keys %$restored_disks) {
26731a3c
SR
7208 my $job_id = "restore-$ds";
7209 mon_cmd($vmid, 'block-stream',
7210 'job-id' => $job_id,
7211 device => "$ds",
7212 );
7213 $jobs->{$job_id} = {};
7214 }
7215
7216 mon_cmd($vmid, 'cont');
7217 qemu_drive_mirror_monitor($vmid, undef, $jobs, 'auto', 0, 'stream');
7218
a09b39f1
TL
7219 print "restore-drive jobs finished successfully, removing all tracking block devices"
7220 ." to disconnect from Proxmox Backup Server\n";
7221
8986e36e 7222 for my $ds (sort keys %$restored_disks) {
26731a3c
SR
7223 mon_cmd($vmid, 'blockdev-del', 'node-name' => "$ds-pbs");
7224 }
26697640
SR
7225
7226 close($qmeventd_fd);
26731a3c
SR
7227 };
7228
7229 my $err = $@;
7230
7231 if ($err) {
8b8893c3 7232 warn "An error occurred during live-restore: $err\n";
26731a3c
SR
7233 _do_vm_stop($storecfg, $vmid, 1, 1, 10, 0, 1);
7234 die "live-restore failed\n";
7235 }
9f3d73bc
DM
7236}
7237
91bd6c90
DM
7238sub restore_vma_archive {
7239 my ($archive, $vmid, $user, $opts, $comp) = @_;
7240
91bd6c90
DM
7241 my $readfrom = $archive;
7242
7c536e11
WB
7243 my $cfg = PVE::Storage::config();
7244 my $commands = [];
7245 my $bwlimit = $opts->{bwlimit};
7246
7247 my $dbg_cmdstring = '';
7248 my $add_pipe = sub {
7249 my ($cmd) = @_;
7250 push @$commands, $cmd;
7251 $dbg_cmdstring .= ' | ' if length($dbg_cmdstring);
7252 $dbg_cmdstring .= PVE::Tools::cmd2string($cmd);
91bd6c90 7253 $readfrom = '-';
7c536e11
WB
7254 };
7255
7256 my $input = undef;
7257 if ($archive eq '-') {
7258 $input = '<&STDIN';
7259 } else {
7260 # If we use a backup from a PVE defined storage we also consider that
7261 # storage's rate limit:
7262 my (undef, $volid) = PVE::Storage::path_to_volume_id($cfg, $archive);
7263 if (defined($volid)) {
7264 my ($sid, undef) = PVE::Storage::parse_volume_id($volid);
7265 my $readlimit = PVE::Storage::get_bandwidth_limit('restore', [$sid], $bwlimit);
7266 if ($readlimit) {
7267 print STDERR "applying read rate limit: $readlimit\n";
9444c6e4 7268 my $cstream = ['cstream', '-t', $readlimit*1024, '--', $readfrom];
7c536e11
WB
7269 $add_pipe->($cstream);
7270 }
7271 }
7272 }
7273
7274 if ($comp) {
c6d51783
AA
7275 my $info = PVE::Storage::decompressor_info('vma', $comp);
7276 my $cmd = $info->{decompressor};
7277 push @$cmd, $readfrom;
7c536e11 7278 $add_pipe->($cmd);
91bd6c90
DM
7279 }
7280
7281 my $tmpdir = "/var/tmp/vzdumptmp$$";
7282 rmtree $tmpdir;
7283
7284 # disable interrupts (always do cleanups)
5b97ef24
TL
7285 local $SIG{INT} =
7286 local $SIG{TERM} =
7287 local $SIG{QUIT} =
7288 local $SIG{HUP} = sub { warn "got interrupt - ignored\n"; };
91bd6c90
DM
7289
7290 my $mapfifo = "/var/tmp/vzdumptmp$$.fifo";
7291 POSIX::mkfifo($mapfifo, 0600);
7292 my $fifofh;
808a65b5 7293 my $openfifo = sub { open($fifofh, '>', $mapfifo) or die $! };
91bd6c90 7294
7c536e11 7295 $add_pipe->(['vma', 'extract', '-v', '-r', $mapfifo, $readfrom, $tmpdir]);
91bd6c90 7296
e8b07b29
FE
7297 my $devinfo = {}; # info about drives included in backup
7298 my $virtdev_hash = {}; # info about allocated drives
91bd6c90
DM
7299
7300 my $rpcenv = PVE::RPCEnvironment::get();
7301
ffda963f 7302 my $conffile = PVE::QemuConfig->config_file($vmid);
91bd6c90 7303
ae200950 7304 # Note: $oldconf is undef if VM does not exist
ffda963f
FG
7305 my $cfs_path = PVE::QemuConfig->cfs_config_path($vmid);
7306 my $oldconf = PVE::Cluster::cfs_read_file($cfs_path);
98a4b3fb 7307 my $new_conf_raw = '';
ed221350 7308
7c536e11
WB
7309 my %storage_limits;
7310
91bd6c90 7311 my $print_devmap = sub {
91bd6c90
DM
7312 my $cfgfn = "$tmpdir/qemu-server.conf";
7313
7314 # we can read the config - that is already extracted
7315 my $fh = IO::File->new($cfgfn, "r") ||
a1cbe55c 7316 die "unable to read qemu-server.conf - $!\n";
91bd6c90 7317
6738ab9c 7318 my $fwcfgfn = "$tmpdir/qemu-server.fw";
3457d090
WL
7319 if (-f $fwcfgfn) {
7320 my $pve_firewall_dir = '/etc/pve/firewall';
7321 mkdir $pve_firewall_dir; # make sure the dir exists
7322 PVE::Tools::file_copy($fwcfgfn, "${pve_firewall_dir}/$vmid.fw");
7323 }
6738ab9c 7324
e8b07b29 7325 $virtdev_hash = $parse_backup_hints->($rpcenv, $user, $cfg, $fh, $devinfo, $opts);
91bd6c90 7326
c8964278
FE
7327 foreach my $info (values %{$virtdev_hash}) {
7328 my $storeid = $info->{storeid};
7329 next if defined($storage_limits{$storeid});
7330
7331 my $limit = PVE::Storage::get_bandwidth_limit('restore', [$storeid], $bwlimit) // 0;
7332 print STDERR "rate limit for storage $storeid: $limit KiB/s\n" if $limit;
7333 $storage_limits{$storeid} = $limit * 1024;
7c536e11
WB
7334 }
7335
91bd6c90 7336 foreach my $devname (keys %$devinfo) {
be190583
DM
7337 die "found no device mapping information for device '$devname'\n"
7338 if !$devinfo->{$devname}->{virtdev};
91bd6c90
DM
7339 }
7340
ed221350 7341 # create empty/temp config
be190583 7342 if ($oldconf) {
ed221350 7343 PVE::Tools::file_set_contents($conffile, "memory: 128\n");
d1e92cf6 7344 $restore_cleanup_oldconf->($cfg, $vmid, $oldconf, $virtdev_hash);
ed221350
DM
7345 }
7346
9f3d73bc
DM
7347 # allocate volumes
7348 my $map = $restore_allocate_devices->($cfg, $virtdev_hash, $vmid);
7349
7350 # print restore information to $fifofh
91bd6c90
DM
7351 foreach my $virtdev (sort keys %$virtdev_hash) {
7352 my $d = $virtdev_hash->{$virtdev};
9f3d73bc
DM
7353 next if $d->{is_cloudinit}; # no need to restore cloudinit
7354
7c536e11 7355 my $storeid = $d->{storeid};
9f3d73bc 7356 my $volid = $d->{volid};
7c536e11
WB
7357
7358 my $map_opts = '';
7359 if (my $limit = $storage_limits{$storeid}) {
7360 $map_opts .= "throttling.bps=$limit:throttling.group=$storeid:";
7361 }
8fd57431 7362
91bd6c90 7363 my $write_zeros = 1;
88240a83 7364 if (PVE::Storage::volume_has_feature($cfg, 'sparseinit', $volid)) {
91bd6c90
DM
7365 $write_zeros = 0;
7366 }
7367
9f3d73bc 7368 my $path = PVE::Storage::path($cfg, $volid);
87056e18 7369
9f3d73bc 7370 print $fifofh "${map_opts}format=$d->{format}:${write_zeros}:$d->{devname}=$path\n";
91bd6c90 7371
9f3d73bc 7372 print "map '$d->{devname}' to '$path' (write zeros = ${write_zeros})\n";
91bd6c90
DM
7373 }
7374
7375 $fh->seek(0, 0) || die "seek failed - $!\n";
7376
91bd6c90
DM
7377 my $cookie = { netcount => 0 };
7378 while (defined(my $line = <$fh>)) {
c62d7cf5 7379 $new_conf_raw .= restore_update_config_line(
98a4b3fb 7380 $cookie,
98a4b3fb
FE
7381 $map,
7382 $line,
7383 $opts->{unique},
7384 );
91bd6c90
DM
7385 }
7386
7387 $fh->close();
91bd6c90
DM
7388 };
7389
61b172d8
FE
7390 my $oldtimeout;
7391
91bd6c90
DM
7392 eval {
7393 # enable interrupts
6cb0144a
EK
7394 local $SIG{INT} =
7395 local $SIG{TERM} =
7396 local $SIG{QUIT} =
7397 local $SIG{HUP} =
7398 local $SIG{PIPE} = sub { die "interrupted by signal\n"; };
91bd6c90
DM
7399 local $SIG{ALRM} = sub { die "got timeout\n"; };
7400
61b172d8 7401 $oldtimeout = alarm(5); # for reading the VMA header - might hang with a corrupted one
91bd6c90
DM
7402
7403 my $parser = sub {
7404 my $line = shift;
7405
7406 print "$line\n";
7407
7408 if ($line =~ m/^DEV:\sdev_id=(\d+)\ssize:\s(\d+)\sdevname:\s(\S+)$/) {
7409 my ($dev_id, $size, $devname) = ($1, $2, $3);
7410 $devinfo->{$devname} = { size => $size, dev_id => $dev_id };
7411 } elsif ($line =~ m/^CTIME: /) {
46f58b5f 7412 # we correctly received the vma config, so we can disable
853757cc
FE
7413 # the timeout now for disk allocation
7414 alarm($oldtimeout || 0);
7415 $oldtimeout = undef;
91bd6c90
DM
7416 &$print_devmap();
7417 print $fifofh "done\n";
91bd6c90 7418 close($fifofh);
808a65b5 7419 $fifofh = undef;
91bd6c90
DM
7420 }
7421 };
be190583 7422
7c536e11
WB
7423 print "restore vma archive: $dbg_cmdstring\n";
7424 run_command($commands, input => $input, outfunc => $parser, afterfork => $openfifo);
91bd6c90
DM
7425 };
7426 my $err = $@;
7427
7428 alarm($oldtimeout) if $oldtimeout;
7429
e8b07b29 7430 $restore_deactivate_volumes->($cfg, $virtdev_hash);
5f96f4df 7431
808a65b5 7432 close($fifofh) if $fifofh;
91bd6c90 7433 unlink $mapfifo;
9f3d73bc 7434 rmtree $tmpdir;
91bd6c90
DM
7435
7436 if ($err) {
e8b07b29 7437 $restore_destroy_volumes->($cfg, $virtdev_hash);
91bd6c90
DM
7438 die $err;
7439 }
7440
621edb2b 7441 my $new_conf = restore_merge_config($conffile, $new_conf_raw, $opts->{override_conf});
e3971865 7442 check_restore_permissions($rpcenv, $user, $new_conf);
202a2a0b 7443 PVE::QemuConfig->write_config($vmid, $new_conf);
ed221350 7444
91bd6c90
DM
7445 eval { rescan($vmid, 1); };
7446 warn $@ if $@;
26731a3c
SR
7447
7448 PVE::AccessControl::add_vm_to_pool($vmid, $opts->{pool}) if $opts->{pool};
91bd6c90
DM
7449}
7450
7451sub restore_tar_archive {
7452 my ($archive, $vmid, $user, $opts) = @_;
7453
202a2a0b
FE
7454 if (scalar(keys $opts->{override_conf}->%*) > 0) {
7455 my $keystring = join(' ', keys $opts->{override_conf}->%*);
7456 die "cannot pass along options ($keystring) when restoring from tar archive\n";
7457 }
7458
9c502e26 7459 if ($archive ne '-') {
ed221350 7460 my $firstfile = tar_archive_read_firstfile($archive);
32e54050 7461 die "ERROR: file '$archive' does not look like a QemuServer vzdump backup\n"
9c502e26
DM
7462 if $firstfile ne 'qemu-server.conf';
7463 }
3e16d5fc 7464
20519efc 7465 my $storecfg = PVE::Storage::config();
ebb55558 7466
4b026937
TL
7467 # avoid zombie disks when restoring over an existing VM -> cleanup first
7468 # pass keep_empty_config=1 to keep the config (thus VMID) reserved for us
7469 # skiplock=1 because qmrestore has set the 'create' lock itself already
ffda963f 7470 my $vmcfgfn = PVE::QemuConfig->config_file($vmid);
b04ea584 7471 destroy_vm($storecfg, $vmid, 1, { lock => 'restore' }) if -f $vmcfgfn;
ed221350 7472
3e16d5fc
DM
7473 my $tocmd = "/usr/lib/qemu-server/qmextract";
7474
2415a446 7475 $tocmd .= " --storage " . PVE::Tools::shellquote($opts->{storage}) if $opts->{storage};
a0d1b1a2 7476 $tocmd .= " --pool " . PVE::Tools::shellquote($opts->{pool}) if $opts->{pool};
3e16d5fc
DM
7477 $tocmd .= ' --prealloc' if $opts->{prealloc};
7478 $tocmd .= ' --info' if $opts->{info};
7479
a0d1b1a2 7480 # tar option "xf" does not autodetect compression when read from STDIN,
9c502e26 7481 # so we pipe to zcat
2415a446
DM
7482 my $cmd = "zcat -f|tar xf " . PVE::Tools::shellquote($archive) . " " .
7483 PVE::Tools::shellquote("--to-command=$tocmd");
3e16d5fc
DM
7484
7485 my $tmpdir = "/var/tmp/vzdumptmp$$";
7486 mkpath $tmpdir;
7487
7488 local $ENV{VZDUMP_TMPDIR} = $tmpdir;
7489 local $ENV{VZDUMP_VMID} = $vmid;
a0d1b1a2 7490 local $ENV{VZDUMP_USER} = $user;
3e16d5fc 7491
ffda963f 7492 my $conffile = PVE::QemuConfig->config_file($vmid);
98a4b3fb 7493 my $new_conf_raw = '';
3e16d5fc
DM
7494
7495 # disable interrupts (always do cleanups)
6cb0144a
EK
7496 local $SIG{INT} =
7497 local $SIG{TERM} =
7498 local $SIG{QUIT} =
7499 local $SIG{HUP} = sub { print STDERR "got interrupt - ignored\n"; };
3e16d5fc 7500
afdb31d5 7501 eval {
3e16d5fc 7502 # enable interrupts
6cb0144a
EK
7503 local $SIG{INT} =
7504 local $SIG{TERM} =
7505 local $SIG{QUIT} =
7506 local $SIG{HUP} =
7507 local $SIG{PIPE} = sub { die "interrupted by signal\n"; };
3e16d5fc 7508
9c502e26
DM
7509 if ($archive eq '-') {
7510 print "extracting archive from STDIN\n";
7511 run_command($cmd, input => "<&STDIN");
7512 } else {
7513 print "extracting archive '$archive'\n";
7514 run_command($cmd);
7515 }
3e16d5fc
DM
7516
7517 return if $opts->{info};
7518
7519 # read new mapping
7520 my $map = {};
7521 my $statfile = "$tmpdir/qmrestore.stat";
7522 if (my $fd = IO::File->new($statfile, "r")) {
7523 while (defined (my $line = <$fd>)) {
7524 if ($line =~ m/vzdump:([^\s:]*):(\S+)$/) {
7525 $map->{$1} = $2 if $1;
7526 } else {
7527 print STDERR "unable to parse line in statfile - $line\n";
7528 }
7529 }
7530 $fd->close();
7531 }
7532
7533 my $confsrc = "$tmpdir/qemu-server.conf";
7534
f7d1505b 7535 my $srcfd = IO::File->new($confsrc, "r") || die "unable to open file '$confsrc'\n";
3e16d5fc 7536
91bd6c90 7537 my $cookie = { netcount => 0 };
3e16d5fc 7538 while (defined (my $line = <$srcfd>)) {
c62d7cf5 7539 $new_conf_raw .= restore_update_config_line(
98a4b3fb 7540 $cookie,
98a4b3fb
FE
7541 $map,
7542 $line,
7543 $opts->{unique},
7544 );
3e16d5fc
DM
7545 }
7546
7547 $srcfd->close();
3e16d5fc 7548 };
7dc7f315 7549 if (my $err = $@) {
ed221350 7550 tar_restore_cleanup($storecfg, "$tmpdir/qmrestore.stat") if !$opts->{info};
3e16d5fc 7551 die $err;
afdb31d5 7552 }
3e16d5fc
DM
7553
7554 rmtree $tmpdir;
7555
98a4b3fb 7556 PVE::Tools::file_set_contents($conffile, $new_conf_raw);
91bd6c90 7557
ed221350
DM
7558 PVE::Cluster::cfs_update(); # make sure we read new file
7559
91bd6c90
DM
7560 eval { rescan($vmid, 1); };
7561 warn $@ if $@;
3e16d5fc
DM
7562};
7563
65a5ce88 7564sub foreach_storage_used_by_vm {
18bfb361
DM
7565 my ($conf, $func) = @_;
7566
7567 my $sidhash = {};
7568
912792e2 7569 PVE::QemuConfig->foreach_volume($conf, sub {
8ddbcf8b
FG
7570 my ($ds, $drive) = @_;
7571 return if drive_is_cdrom($drive);
18bfb361
DM
7572
7573 my $volid = $drive->{file};
7574
7575 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
be190583 7576 $sidhash->{$sid} = $sid if $sid;
8ddbcf8b 7577 });
18bfb361
DM
7578
7579 foreach my $sid (sort keys %$sidhash) {
7580 &$func($sid);
7581 }
7582}
7583
6c9f59c1
TL
7584my $qemu_snap_storage = {
7585 rbd => 1,
7586};
e5eaa028 7587sub do_snapshots_with_qemu {
9d83932d
SR
7588 my ($storecfg, $volid, $deviceid) = @_;
7589
7590 return if $deviceid =~ m/tpmstate0/;
e5eaa028
WL
7591
7592 my $storage_name = PVE::Storage::parse_volume_id($volid);
8aa2ed7c 7593 my $scfg = $storecfg->{ids}->{$storage_name};
f7d1505b 7594 die "could not find storage '$storage_name'\n" if !defined($scfg);
e5eaa028 7595
8aa2ed7c 7596 if ($qemu_snap_storage->{$scfg->{type}} && !$scfg->{krbd}){
e5eaa028
WL
7597 return 1;
7598 }
7599
7600 if ($volid =~ m/\.(qcow2|qed)$/){
7601 return 1;
7602 }
7603
d1c1af4b 7604 return;
e5eaa028
WL
7605}
7606
4dcc780c 7607sub qga_check_running {
a4938c72 7608 my ($vmid, $nowarn) = @_;
4dcc780c 7609
0a13e08e 7610 eval { mon_cmd($vmid, "guest-ping", timeout => 3); };
4dcc780c 7611 if ($@) {
7bd9abd2 7612 warn "QEMU Guest Agent is not running - $@" if !$nowarn;
4dcc780c
WL
7613 return 0;
7614 }
7615 return 1;
7616}
7617
04a69bb4
AD
7618sub template_create {
7619 my ($vmid, $conf, $disk) = @_;
7620
04a69bb4 7621 my $storecfg = PVE::Storage::config();
04a69bb4 7622
912792e2 7623 PVE::QemuConfig->foreach_volume($conf, sub {
9cd07842
DM
7624 my ($ds, $drive) = @_;
7625
7626 return if drive_is_cdrom($drive);
7627 return if $disk && $ds ne $disk;
7628
7629 my $volid = $drive->{file};
bbd56097 7630 return if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid);
9cd07842 7631
04a69bb4
AD
7632 my $voliddst = PVE::Storage::vdisk_create_base($storecfg, $volid);
7633 $drive->{file} = $voliddst;
71c58bb7 7634 $conf->{$ds} = print_drive($drive);
ffda963f 7635 PVE::QemuConfig->write_config($vmid, $conf);
04a69bb4 7636 });
04a69bb4
AD
7637}
7638
92bdc3f0
DC
7639sub convert_iscsi_path {
7640 my ($path) = @_;
7641
7642 if ($path =~ m|^iscsi://([^/]+)/([^/]+)/(.+)$|) {
7643 my $portal = $1;
7644 my $target = $2;
7645 my $lun = $3;
7646
7647 my $initiator_name = get_initiator_name();
7648
7649 return "file.driver=iscsi,file.transport=tcp,file.initiator-name=$initiator_name,".
7650 "file.portal=$portal,file.target=$target,file.lun=$lun,driver=raw";
7651 }
7652
7653 die "cannot convert iscsi path '$path', unkown format\n";
7654}
7655
5133de42 7656sub qemu_img_convert {
56d16f16 7657 my ($src_volid, $dst_volid, $size, $snapname, $is_zero_initialized, $bwlimit) = @_;
5133de42
AD
7658
7659 my $storecfg = PVE::Storage::config();
7660 my ($src_storeid, $src_volname) = PVE::Storage::parse_volume_id($src_volid, 1);
7661 my ($dst_storeid, $dst_volname) = PVE::Storage::parse_volume_id($dst_volid, 1);
7662
af1f1ec0 7663 die "destination '$dst_volid' is not a valid volid form qemu-img convert\n" if !$dst_storeid;
6bb91c17 7664
af1f1ec0
DC
7665 my $cachemode;
7666 my $src_path;
7667 my $src_is_iscsi = 0;
bdd1feef 7668 my $src_format;
6bb91c17 7669
af1f1ec0
DC
7670 if ($src_storeid) {
7671 PVE::Storage::activate_volumes($storecfg, [$src_volid], $snapname);
5133de42 7672 my $src_scfg = PVE::Storage::storage_config($storecfg, $src_storeid);
af1f1ec0
DC
7673 $src_format = qemu_img_format($src_scfg, $src_volname);
7674 $src_path = PVE::Storage::path($storecfg, $src_volid, $snapname);
7675 $src_is_iscsi = ($src_path =~ m|^iscsi://|);
7676 $cachemode = 'none' if $src_scfg->{type} eq 'zfspool';
a23d57d5 7677 } elsif (-f $src_volid || -b $src_volid) {
af1f1ec0 7678 $src_path = $src_volid;
e0fd2b2f 7679 if ($src_path =~ m/\.($PVE::QemuServer::Drive::QEMU_FORMAT_RE)$/) {
af1f1ec0
DC
7680 $src_format = $1;
7681 }
7682 }
5133de42 7683
af1f1ec0 7684 die "source '$src_volid' is not a valid volid nor path for qemu-img convert\n" if !$src_path;
5133de42 7685
af1f1ec0
DC
7686 my $dst_scfg = PVE::Storage::storage_config($storecfg, $dst_storeid);
7687 my $dst_format = qemu_img_format($dst_scfg, $dst_volname);
7688 my $dst_path = PVE::Storage::path($storecfg, $dst_volid);
7689 my $dst_is_iscsi = ($dst_path =~ m|^iscsi://|);
5133de42 7690
af1f1ec0
DC
7691 my $cmd = [];
7692 push @$cmd, '/usr/bin/qemu-img', 'convert', '-p', '-n';
bdd1feef
TL
7693 push @$cmd, '-l', "snapshot.name=$snapname"
7694 if $snapname && $src_format && $src_format eq "qcow2";
af1f1ec0
DC
7695 push @$cmd, '-t', 'none' if $dst_scfg->{type} eq 'zfspool';
7696 push @$cmd, '-T', $cachemode if defined($cachemode);
56d16f16 7697 push @$cmd, '-r', "${bwlimit}K" if defined($bwlimit);
af1f1ec0
DC
7698
7699 if ($src_is_iscsi) {
7700 push @$cmd, '--image-opts';
7701 $src_path = convert_iscsi_path($src_path);
bdd1feef 7702 } elsif ($src_format) {
af1f1ec0
DC
7703 push @$cmd, '-f', $src_format;
7704 }
92bdc3f0 7705
af1f1ec0
DC
7706 if ($dst_is_iscsi) {
7707 push @$cmd, '--target-image-opts';
7708 $dst_path = convert_iscsi_path($dst_path);
7709 } else {
7710 push @$cmd, '-O', $dst_format;
7711 }
92bdc3f0 7712
af1f1ec0 7713 push @$cmd, $src_path;
92bdc3f0 7714
af1f1ec0
DC
7715 if (!$dst_is_iscsi && $is_zero_initialized) {
7716 push @$cmd, "zeroinit:$dst_path";
7717 } else {
7718 push @$cmd, $dst_path;
7719 }
92bdc3f0 7720
af1f1ec0
DC
7721 my $parser = sub {
7722 my $line = shift;
7723 if($line =~ m/\((\S+)\/100\%\)/){
7724 my $percent = $1;
7725 my $transferred = int($size * $percent / 100);
b5e9d97b
TL
7726 my $total_h = render_bytes($size, 1);
7727 my $transferred_h = render_bytes($transferred, 1);
92bdc3f0 7728
6629f976 7729 print "transferred $transferred_h of $total_h ($percent%)\n";
988e2714 7730 }
5133de42 7731
af1f1ec0 7732 };
5133de42 7733
af1f1ec0
DC
7734 eval { run_command($cmd, timeout => undef, outfunc => $parser); };
7735 my $err = $@;
7736 die "copy failed: $err" if $err;
5133de42
AD
7737}
7738
7739sub qemu_img_format {
7740 my ($scfg, $volname) = @_;
7741
e0fd2b2f 7742 if ($scfg->{path} && $volname =~ m/\.($PVE::QemuServer::Drive::QEMU_FORMAT_RE)$/) {
5133de42 7743 return $1;
be190583 7744 } else {
5133de42 7745 return "raw";
5133de42
AD
7746 }
7747}
7748
cfad42af 7749sub qemu_drive_mirror {
bc6c8231 7750 my ($vmid, $drive, $dst_volid, $vmiddst, $is_zero_initialized, $jobs, $completion, $qga, $bwlimit, $src_bitmap) = @_;
cfad42af 7751
5a345967
AD
7752 $jobs = {} if !$jobs;
7753
7754 my $qemu_target;
7755 my $format;
35e4ab04 7756 $jobs->{"drive-$drive"} = {};
152fe752 7757
1e5143de 7758 if ($dst_volid =~ /^nbd:/) {
87955688 7759 $qemu_target = $dst_volid;
5a345967 7760 $format = "nbd";
5a345967 7761 } else {
5a345967
AD
7762 my $storecfg = PVE::Storage::config();
7763 my ($dst_storeid, $dst_volname) = PVE::Storage::parse_volume_id($dst_volid);
7764
7765 my $dst_scfg = PVE::Storage::storage_config($storecfg, $dst_storeid);
cfad42af 7766
5a345967 7767 $format = qemu_img_format($dst_scfg, $dst_volname);
21ccdb50 7768
5a345967 7769 my $dst_path = PVE::Storage::path($storecfg, $dst_volid);
21ccdb50 7770
5a345967
AD
7771 $qemu_target = $is_zero_initialized ? "zeroinit:$dst_path" : $dst_path;
7772 }
988e2714
WB
7773
7774 my $opts = { timeout => 10, device => "drive-$drive", mode => "existing", sync => "full", target => $qemu_target };
88383920
DM
7775 $opts->{format} = $format if $format;
7776
bc6c8231
FG
7777 if (defined($src_bitmap)) {
7778 $opts->{sync} = 'incremental';
7779 $opts->{bitmap} = $src_bitmap;
7780 print "drive mirror re-using dirty bitmap '$src_bitmap'\n";
7781 }
7782
9fa05d31 7783 if (defined($bwlimit)) {
f6409f61
TL
7784 $opts->{speed} = $bwlimit * 1024;
7785 print "drive mirror is starting for drive-$drive with bandwidth limit: ${bwlimit} KB/s\n";
9fa05d31
SI
7786 } else {
7787 print "drive mirror is starting for drive-$drive\n";
7788 }
21ccdb50 7789
6dde5ea2 7790 # if a job already runs for this device we get an error, catch it for cleanup
0a13e08e 7791 eval { mon_cmd($vmid, "drive-mirror", %$opts); };
5a345967
AD
7792 if (my $err = $@) {
7793 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $jobs) };
6dde5ea2
TL
7794 warn "$@\n" if $@;
7795 die "mirroring error: $err\n";
5a345967
AD
7796 }
7797
e02fb126 7798 qemu_drive_mirror_monitor ($vmid, $vmiddst, $jobs, $completion, $qga);
5a345967
AD
7799}
7800
db1f8b39
FG
7801# $completion can be either
7802# 'complete': wait until all jobs are ready, block-job-complete them (default)
7803# 'cancel': wait until all jobs are ready, block-job-cancel them
7804# 'skip': wait until all jobs are ready, return with block jobs in ready state
9e671722 7805# 'auto': wait until all jobs disappear, only use for jobs which complete automatically
5a345967 7806sub qemu_drive_mirror_monitor {
9e671722 7807 my ($vmid, $vmiddst, $jobs, $completion, $qga, $op) = @_;
e02fb126 7808
db1f8b39 7809 $completion //= 'complete';
9e671722 7810 $op //= "mirror";
2e953867 7811
08ac653f 7812 eval {
5a345967
AD
7813 my $err_complete = 0;
7814
3b56383b 7815 my $starttime = time ();
08ac653f 7816 while (1) {
9e671722 7817 die "block job ('$op') timed out\n" if $err_complete > 300;
5a345967 7818
0a13e08e 7819 my $stats = mon_cmd($vmid, "query-block-jobs");
3b56383b 7820 my $ctime = time();
08ac653f 7821
9e671722 7822 my $running_jobs = {};
0ea24bf0 7823 for my $stat (@$stats) {
9e671722
SR
7824 next if $stat->{type} ne $op;
7825 $running_jobs->{$stat->{device}} = $stat;
5a345967 7826 }
08ac653f 7827
5a345967 7828 my $readycounter = 0;
67fb9de6 7829
0ea24bf0 7830 for my $job_id (sort keys %$jobs) {
1057fc74 7831 my $job = $running_jobs->{$job_id};
5a345967 7832
1057fc74 7833 my $vanished = !defined($job);
0ea24bf0 7834 my $complete = defined($jobs->{$job_id}->{complete}) && $vanished;
9e671722 7835 if($complete || ($vanished && $completion eq 'auto')) {
3b56383b 7836 print "$job_id: $op-job finished\n";
0ea24bf0 7837 delete $jobs->{$job_id};
5a345967
AD
7838 next;
7839 }
7840
1057fc74 7841 die "$job_id: '$op' has been cancelled\n" if !defined($job);
f34ebd52 7842
1057fc74
TL
7843 my $busy = $job->{busy};
7844 my $ready = $job->{ready};
7845 if (my $total = $job->{len}) {
7846 my $transferred = $job->{offset} || 0;
5a345967
AD
7847 my $remaining = $total - $transferred;
7848 my $percent = sprintf "%.2f", ($transferred * 100 / $total);
08ac653f 7849
3b56383b
TL
7850 my $duration = $ctime - $starttime;
7851 my $total_h = render_bytes($total, 1);
7852 my $transferred_h = render_bytes($transferred, 1);
7853
7854 my $status = sprintf(
7855 "transferred $transferred_h of $total_h ($percent%%) in %s",
7856 render_duration($duration),
7857 );
7858
7859 if ($ready) {
7860 if ($busy) {
7861 $status .= ", still busy"; # shouldn't even happen? but mirror is weird
7862 } else {
7863 $status .= ", ready";
7864 }
7865 }
67daf692
TL
7866 print "$job_id: $status\n" if !$jobs->{$job_id}->{ready};
7867 $jobs->{$job_id}->{ready} = $ready;
5a345967 7868 }
f34ebd52 7869
1057fc74 7870 $readycounter++ if $job->{ready};
5a345967 7871 }
b467f79a 7872
5a345967
AD
7873 last if scalar(keys %$jobs) == 0;
7874
7875 if ($readycounter == scalar(keys %$jobs)) {
9e671722
SR
7876 print "all '$op' jobs are ready\n";
7877
7878 # do the complete later (or has already been done)
7879 last if $completion eq 'skip' || $completion eq 'auto';
5a345967
AD
7880
7881 if ($vmiddst && $vmiddst != $vmid) {
1a988fd2
DC
7882 my $agent_running = $qga && qga_check_running($vmid);
7883 if ($agent_running) {
5619e74a 7884 print "freeze filesystem\n";
0a13e08e 7885 eval { mon_cmd($vmid, "guest-fsfreeze-freeze"); };
d6cdfae4 7886 warn $@ if $@;
5619e74a
AD
7887 } else {
7888 print "suspend vm\n";
7889 eval { PVE::QemuServer::vm_suspend($vmid, 1); };
d6cdfae4 7890 warn $@ if $@;
5619e74a
AD
7891 }
7892
5a345967
AD
7893 # if we clone a disk for a new target vm, we don't switch the disk
7894 PVE::QemuServer::qemu_blockjobs_cancel($vmid, $jobs);
5619e74a 7895
1a988fd2 7896 if ($agent_running) {
5619e74a 7897 print "unfreeze filesystem\n";
0a13e08e 7898 eval { mon_cmd($vmid, "guest-fsfreeze-thaw"); };
d6cdfae4 7899 warn $@ if $@;
5619e74a
AD
7900 } else {
7901 print "resume vm\n";
d6cdfae4
FE
7902 eval { PVE::QemuServer::vm_resume($vmid, 1, 1); };
7903 warn $@ if $@;
5619e74a
AD
7904 }
7905
2e953867 7906 last;
5a345967
AD
7907 } else {
7908
0ea24bf0 7909 for my $job_id (sort keys %$jobs) {
5a345967 7910 # try to switch the disk if source and destination are on the same guest
0ea24bf0 7911 print "$job_id: Completing block job_id...\n";
5a345967 7912
e02fb126 7913 my $op;
db1f8b39 7914 if ($completion eq 'complete') {
e02fb126 7915 $op = 'block-job-complete';
db1f8b39 7916 } elsif ($completion eq 'cancel') {
e02fb126
ML
7917 $op = 'block-job-cancel';
7918 } else {
7919 die "invalid completion value: $completion\n";
7920 }
0ea24bf0 7921 eval { mon_cmd($vmid, $op, device => $job_id) };
5a345967 7922 if ($@ =~ m/cannot be completed/) {
3b56383b 7923 print "$job_id: block job cannot be completed, trying again.\n";
5a345967
AD
7924 $err_complete++;
7925 }else {
0ea24bf0
TL
7926 print "$job_id: Completed successfully.\n";
7927 $jobs->{$job_id}->{complete} = 1;
5a345967
AD
7928 }
7929 }
2e953867 7930 }
08ac653f 7931 }
08ac653f 7932 sleep 1;
cfad42af 7933 }
08ac653f 7934 };
88383920 7935 my $err = $@;
08ac653f 7936
88383920 7937 if ($err) {
5a345967 7938 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $jobs) };
3b56383b 7939 die "block job ($op) error: $err";
88383920 7940 }
5a345967
AD
7941}
7942
7943sub qemu_blockjobs_cancel {
7944 my ($vmid, $jobs) = @_;
7945
7946 foreach my $job (keys %$jobs) {
bd2d5fe6 7947 print "$job: Cancelling block job\n";
0a13e08e 7948 eval { mon_cmd($vmid, "block-job-cancel", device => $job); };
5a345967
AD
7949 $jobs->{$job}->{cancel} = 1;
7950 }
7951
7952 while (1) {
0a13e08e 7953 my $stats = mon_cmd($vmid, "query-block-jobs");
5a345967
AD
7954
7955 my $running_jobs = {};
7956 foreach my $stat (@$stats) {
7957 $running_jobs->{$stat->{device}} = $stat;
7958 }
7959
7960 foreach my $job (keys %$jobs) {
7961
bd2d5fe6
WB
7962 if (defined($jobs->{$job}->{cancel}) && !defined($running_jobs->{$job})) {
7963 print "$job: Done.\n";
5a345967
AD
7964 delete $jobs->{$job};
7965 }
7966 }
7967
7968 last if scalar(keys %$jobs) == 0;
7969
7970 sleep 1;
cfad42af
AD
7971 }
7972}
7973
8fbae1dc
FE
7974# Check for bug #4525: drive-mirror will open the target drive with the same aio setting as the
7975# source, but some storages have problems with io_uring, sometimes even leading to crashes.
7976my sub clone_disk_check_io_uring {
7977 my ($src_drive, $storecfg, $src_storeid, $dst_storeid, $use_drive_mirror) = @_;
7978
7979 return if !$use_drive_mirror;
7980
7981 # Don't complain when not changing storage.
7982 # Assume if it works for the source, it'll work for the target too.
7983 return if $src_storeid eq $dst_storeid;
7984
7985 my $src_scfg = PVE::Storage::storage_config($storecfg, $src_storeid);
7986 my $dst_scfg = PVE::Storage::storage_config($storecfg, $dst_storeid);
7987
7988 my $cache_direct = drive_uses_cache_direct($src_drive);
7989
7990 my $src_uses_io_uring;
7991 if ($src_drive->{aio}) {
7992 $src_uses_io_uring = $src_drive->{aio} eq 'io_uring';
7993 } else {
7994 $src_uses_io_uring = storage_allows_io_uring_default($src_scfg, $cache_direct);
7995 }
7996
7997 die "target storage is known to cause issues with aio=io_uring (used by current drive)\n"
7998 if $src_uses_io_uring && !storage_allows_io_uring_default($dst_scfg, $cache_direct);
7999}
8000
152fe752 8001sub clone_disk {
1196086f
FE
8002 my ($storecfg, $source, $dest, $full, $newvollist, $jobs, $completion, $qga, $bwlimit) = @_;
8003
8004 my ($vmid, $running) = $source->@{qw(vmid running)};
25166060 8005 my ($src_drivename, $drive, $snapname) = $source->@{qw(drivename drive snapname)};
1196086f 8006
25166060 8007 my ($newvmid, $dst_drivename, $efisize) = $dest->@{qw(vmid drivename efisize)};
1196086f 8008 my ($storage, $format) = $dest->@{qw(storage format)};
152fe752 8009
5f957592
FE
8010 my $use_drive_mirror = $full && $running && $src_drivename && !$snapname;
8011
25166060
FE
8012 if ($src_drivename && $dst_drivename && $src_drivename ne $dst_drivename) {
8013 die "cloning from/to EFI disk requires EFI disk\n"
8014 if $src_drivename eq 'efidisk0' || $dst_drivename eq 'efidisk0';
8015 die "cloning from/to TPM state requires TPM state\n"
8016 if $src_drivename eq 'tpmstate0' || $dst_drivename eq 'tpmstate0';
5f957592
FE
8017
8018 # This would lead to two device nodes in QEMU pointing to the same backing image!
8019 die "cannot change drive name when cloning disk from/to the same VM\n"
8020 if $use_drive_mirror && $vmid == $newvmid;
25166060
FE
8021 }
8022
1d1f8f9a
FE
8023 die "cannot move TPM state while VM is running\n"
8024 if $use_drive_mirror && $src_drivename eq 'tpmstate0';
8025
152fe752
DM
8026 my $newvolid;
8027
25166060
FE
8028 print "create " . ($full ? 'full' : 'linked') . " clone of drive ";
8029 print "$src_drivename " if $src_drivename;
8030 print "($drive->{file})\n";
8031
152fe752 8032 if (!$full) {
258e646c 8033 $newvolid = PVE::Storage::vdisk_clone($storecfg, $drive->{file}, $newvmid, $snapname);
152fe752
DM
8034 push @$newvollist, $newvolid;
8035 } else {
8fbae1dc
FE
8036 my ($src_storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file});
8037 my $storeid = $storage || $src_storeid;
152fe752 8038
44549149 8039 my $dst_format = resolve_dst_disk_format($storecfg, $storeid, $volname, $format);
152fe752 8040
931432bd 8041 my $name = undef;
d0abc774 8042 my $size = undef;
7fe8b44c
TL
8043 if (drive_is_cloudinit($drive)) {
8044 $name = "vm-$newvmid-cloudinit";
c997e24a
ML
8045 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
8046 if ($scfg->{path}) {
8047 $name .= ".$dst_format";
8048 }
7fe8b44c
TL
8049 $snapname = undef;
8050 $size = PVE::QemuServer::Cloudinit::CLOUDINIT_DISK_SIZE;
25166060 8051 } elsif ($dst_drivename eq 'efidisk0') {
7344af7b 8052 $size = $efisize or die "internal error - need to specify EFI disk size\n";
25166060 8053 } elsif ($dst_drivename eq 'tpmstate0') {
5f5aba25 8054 $dst_format = 'raw';
f9dde219 8055 $size = PVE::QemuServer::Drive::TPMSTATE_DISK_SIZE;
d0abc774 8056 } else {
8fbae1dc
FE
8057 clone_disk_check_io_uring($drive, $storecfg, $src_storeid, $storeid, $use_drive_mirror);
8058
efa3aa24 8059 $size = PVE::Storage::volume_size_info($storecfg, $drive->{file}, 10);
7fe8b44c 8060 }
b5688f69
FE
8061 $newvolid = PVE::Storage::vdisk_alloc(
8062 $storecfg, $storeid, $newvmid, $dst_format, $name, ($size/1024)
8063 );
152fe752
DM
8064 push @$newvollist, $newvolid;
8065
3999f370 8066 PVE::Storage::activate_volumes($storecfg, [$newvolid]);
1dbd6d30 8067
7fe8b44c 8068 if (drive_is_cloudinit($drive)) {
1b485263
ML
8069 # when cloning multiple disks (e.g. during clone_vm) it might be the last disk
8070 # if this is the case, we have to complete any block-jobs still there from
8071 # previous drive-mirrors
8072 if (($completion eq 'complete') && (scalar(keys %$jobs) > 0)) {
8073 qemu_drive_mirror_monitor($vmid, $newvmid, $jobs, $completion, $qga);
8074 }
7fe8b44c
TL
8075 goto no_data_clone;
8076 }
8077
988e2714 8078 my $sparseinit = PVE::Storage::volume_has_feature($storecfg, 'sparseinit', $newvolid);
5f957592 8079 if ($use_drive_mirror) {
5f957592
FE
8080 qemu_drive_mirror($vmid, $src_drivename, $newvolid, $newvmid, $sparseinit, $jobs,
8081 $completion, $qga, $bwlimit);
8082 } else {
25166060 8083 if ($dst_drivename eq 'efidisk0') {
818ce80e
DC
8084 # the relevant data on the efidisk may be smaller than the source
8085 # e.g. on RBD/ZFS, so we use dd to copy only the amount
8086 # that is given by the OVMF_VARS.fd
62375438 8087 my $src_path = PVE::Storage::path($storecfg, $drive->{file}, $snapname);
818ce80e 8088 my $dst_path = PVE::Storage::path($storecfg, $newvolid);
fdfdc80e 8089
62375438
FE
8090 my $src_format = (PVE::Storage::parse_volname($storecfg, $drive->{file}))[6];
8091
fdfdc80e
FE
8092 # better for Ceph if block size is not too small, see bug #3324
8093 my $bs = 1024*1024;
8094
62375438 8095 my $cmd = ['qemu-img', 'dd', '-n', '-O', $dst_format];
a9c45bd4
FE
8096
8097 if ($src_format eq 'qcow2' && $snapname) {
8098 die "cannot clone qcow2 EFI disk snapshot - requires QEMU >= 6.2\n"
8099 if !min_version(kvm_user_version(), 6, 2);
8100 push $cmd->@*, '-l', $snapname;
8101 }
62375438
FE
8102 push $cmd->@*, "bs=$bs", "osize=$size", "if=$src_path", "of=$dst_path";
8103 run_command($cmd);
818ce80e 8104 } else {
56d16f16 8105 qemu_img_convert($drive->{file}, $newvolid, $size, $snapname, $sparseinit, $bwlimit);
818ce80e 8106 }
be190583 8107 }
152fe752
DM
8108 }
8109
7fe8b44c 8110no_data_clone:
efa3aa24 8111 my $size = eval { PVE::Storage::volume_size_info($storecfg, $newvolid, 10) };
152fe752 8112
3b53c471
FE
8113 my $disk = dclone($drive);
8114 delete $disk->{format};
152fe752 8115 $disk->{file} = $newvolid;
3bae384f 8116 $disk->{size} = $size if defined($size);
152fe752
DM
8117
8118 return $disk;
8119}
8120
98cfd8b6
AD
8121sub get_running_qemu_version {
8122 my ($vmid) = @_;
0a13e08e 8123 my $res = mon_cmd($vmid, "query-version");
98cfd8b6
AD
8124 return "$res->{qemu}->{major}.$res->{qemu}->{minor}";
8125}
8126
249c4a6c
AD
8127sub qemu_use_old_bios_files {
8128 my ($machine_type) = @_;
8129
8130 return if !$machine_type;
8131
8132 my $use_old_bios_files = undef;
8133
8134 if ($machine_type =~ m/^(\S+)\.pxe$/) {
8135 $machine_type = $1;
8136 $use_old_bios_files = 1;
8137 } else {
4df98f2f 8138 my $version = extract_version($machine_type, kvm_user_version());
249c4a6c
AD
8139 # Note: kvm version < 2.4 use non-efi pxe files, and have problems when we
8140 # load new efi bios files on migration. So this hack is required to allow
8141 # live migration from qemu-2.2 to qemu-2.4, which is sometimes used when
8142 # updrading from proxmox-ve-3.X to proxmox-ve 4.0
2ea5fb7e 8143 $use_old_bios_files = !min_version($version, 2, 4);
249c4a6c
AD
8144 }
8145
8146 return ($use_old_bios_files, $machine_type);
8147}
8148
818ce80e 8149sub get_efivars_size {
ff84f0e3
FE
8150 my ($conf, $efidisk) = @_;
8151
818ce80e 8152 my $arch = get_vm_arch($conf);
ff84f0e3 8153 $efidisk //= $conf->{efidisk0} ? parse_drive('efidisk0', $conf->{efidisk0}) : undef;
90b20b15
DC
8154 my $smm = PVE::QemuServer::Machine::machine_type_is_q35($conf);
8155 my (undef, $ovmf_vars) = get_ovmf_files($arch, $efidisk, $smm);
818ce80e
DC
8156 return -s $ovmf_vars;
8157}
8158
8159sub update_efidisk_size {
8160 my ($conf) = @_;
8161
8162 return if !defined($conf->{efidisk0});
8163
8164 my $disk = PVE::QemuServer::parse_drive('efidisk0', $conf->{efidisk0});
8165 $disk->{size} = get_efivars_size($conf);
8166 $conf->{efidisk0} = print_drive($disk);
8167
8168 return;
8169}
8170
f9dde219
SR
8171sub update_tpmstate_size {
8172 my ($conf) = @_;
8173
8174 my $disk = PVE::QemuServer::parse_drive('tpmstate0', $conf->{tpmstate0});
8175 $disk->{size} = PVE::QemuServer::Drive::TPMSTATE_DISK_SIZE;
8176 $conf->{tpmstate0} = print_drive($disk);
8177}
8178
90b20b15
DC
8179sub create_efidisk($$$$$$$) {
8180 my ($storecfg, $storeid, $vmid, $fmt, $arch, $efidisk, $smm) = @_;
3e1f1122 8181
90b20b15 8182 my (undef, $ovmf_vars) = get_ovmf_files($arch, $efidisk, $smm);
3e1f1122 8183
af1f1ec0
DC
8184 my $vars_size_b = -s $ovmf_vars;
8185 my $vars_size = PVE::Tools::convert_size($vars_size_b, 'b' => 'kb');
3e1f1122
TL
8186 my $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, $fmt, undef, $vars_size);
8187 PVE::Storage::activate_volumes($storecfg, [$volid]);
8188
af1f1ec0 8189 qemu_img_convert($ovmf_vars, $volid, $vars_size_b, undef, 0);
efa3aa24 8190 my $size = PVE::Storage::volume_size_info($storecfg, $volid, 3);
3e1f1122 8191
340dbcf7 8192 return ($volid, $size/1024);
3e1f1122
TL
8193}
8194
22de899a
AD
8195sub vm_iothreads_list {
8196 my ($vmid) = @_;
8197
0a13e08e 8198 my $res = mon_cmd($vmid, 'query-iothreads');
22de899a
AD
8199
8200 my $iothreads = {};
8201 foreach my $iothread (@$res) {
8202 $iothreads->{ $iothread->{id} } = $iothread->{"thread-id"};
8203 }
8204
8205 return $iothreads;
8206}
8207
ee034f5c
AD
8208sub scsihw_infos {
8209 my ($conf, $drive) = @_;
8210
8211 my $maxdev = 0;
8212
7fe1b688 8213 if (!$conf->{scsihw} || ($conf->{scsihw} =~ m/^lsi/)) {
ee034f5c 8214 $maxdev = 7;
a1511b3c 8215 } elsif ($conf->{scsihw} && ($conf->{scsihw} eq 'virtio-scsi-single')) {
ee034f5c
AD
8216 $maxdev = 1;
8217 } else {
8218 $maxdev = 256;
8219 }
8220
8221 my $controller = int($drive->{index} / $maxdev);
4df98f2f
TL
8222 my $controller_prefix = ($conf->{scsihw} && $conf->{scsihw} eq 'virtio-scsi-single')
8223 ? "virtioscsi"
8224 : "scsihw";
ee034f5c
AD
8225
8226 return ($maxdev, $controller, $controller_prefix);
8227}
a1511b3c 8228
44549149
EK
8229sub resolve_dst_disk_format {
8230 my ($storecfg, $storeid, $src_volname, $format) = @_;
8231 my ($defFormat, $validFormats) = PVE::Storage::storage_default_format($storecfg, $storeid);
8232
8233 if (!$format) {
8234 # if no target format is specified, use the source disk format as hint
8235 if ($src_volname) {
8236 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
8237 $format = qemu_img_format($scfg, $src_volname);
8238 } else {
8239 return $defFormat;
8240 }
8241 }
8242
8243 # test if requested format is supported - else use default
8244 my $supported = grep { $_ eq $format } @$validFormats;
8245 $format = $defFormat if !$supported;
8246 return $format;
8247}
8248
66cebc46
DC
8249# NOTE: if this logic changes, please update docs & possibly gui logic
8250sub find_vmstate_storage {
8251 my ($conf, $storecfg) = @_;
8252
8253 # first, return storage from conf if set
8254 return $conf->{vmstatestorage} if $conf->{vmstatestorage};
8255
8256 my ($target, $shared, $local);
8257
8258 foreach_storage_used_by_vm($conf, sub {
8259 my ($sid) = @_;
8260 my $scfg = PVE::Storage::storage_config($storecfg, $sid);
8261 my $dst = $scfg->{shared} ? \$shared : \$local;
8262 $$dst = $sid if !$$dst || $scfg->{path}; # prefer file based storage
8263 });
8264
8265 # second, use shared storage where VM has at least one disk
8266 # third, use local storage where VM has at least one disk
8267 # fall back to local storage
8268 $target = $shared // $local // 'local';
8269
8270 return $target;
8271}
8272
6ee499ff 8273sub generate_uuid {
ae2fcb3b
EK
8274 my ($uuid, $uuid_str);
8275 UUID::generate($uuid);
8276 UUID::unparse($uuid, $uuid_str);
6ee499ff
DC
8277 return $uuid_str;
8278}
8279
8280sub generate_smbios1_uuid {
8281 return "uuid=".generate_uuid();
ae2fcb3b
EK
8282}
8283
9c152e87
TL
8284sub nbd_stop {
8285 my ($vmid) = @_;
8286
6cb2338f 8287 mon_cmd($vmid, 'nbd-server-stop', timeout => 25);
9c152e87
TL
8288}
8289
dae98db9
DC
8290sub create_reboot_request {
8291 my ($vmid) = @_;
8292 open(my $fh, '>', "/run/qemu-server/$vmid.reboot")
8293 or die "failed to create reboot trigger file: $!\n";
8294 close($fh);
8295}
8296
8297sub clear_reboot_request {
8298 my ($vmid) = @_;
8299 my $path = "/run/qemu-server/$vmid.reboot";
8300 my $res = 0;
8301
8302 $res = unlink($path);
8303 die "could not remove reboot request for $vmid: $!"
8304 if !$res && $! != POSIX::ENOENT;
8305
8306 return $res;
8307}
8308
5cfa9f5f
SR
8309sub bootorder_from_legacy {
8310 my ($conf, $bootcfg) = @_;
8311
8312 my $boot = $bootcfg->{legacy} || $boot_fmt->{legacy}->{default};
8313 my $bootindex_hash = {};
8314 my $i = 1;
8315 foreach my $o (split(//, $boot)) {
8316 $bootindex_hash->{$o} = $i*100;
8317 $i++;
8318 }
8319
8320 my $bootorder = {};
8321
8322 PVE::QemuConfig->foreach_volume($conf, sub {
8323 my ($ds, $drive) = @_;
8324
8325 if (drive_is_cdrom ($drive, 1)) {
8326 if ($bootindex_hash->{d}) {
8327 $bootorder->{$ds} = $bootindex_hash->{d};
8328 $bootindex_hash->{d} += 1;
8329 }
8330 } elsif ($bootindex_hash->{c}) {
8331 $bootorder->{$ds} = $bootindex_hash->{c}
8332 if $conf->{bootdisk} && $conf->{bootdisk} eq $ds;
8333 $bootindex_hash->{c} += 1;
8334 }
8335 });
8336
8337 if ($bootindex_hash->{n}) {
8338 for (my $i = 0; $i < $MAX_NETS; $i++) {
8339 my $netname = "net$i";
8340 next if !$conf->{$netname};
8341 $bootorder->{$netname} = $bootindex_hash->{n};
8342 $bootindex_hash->{n} += 1;
8343 }
8344 }
8345
8346 return $bootorder;
8347}
8348
8349# Generate default device list for 'boot: order=' property. Matches legacy
8350# default boot order, but with explicit device names. This is important, since
8351# the fallback for when neither 'order' nor the old format is specified relies
8352# on 'bootorder_from_legacy' above, and it would be confusing if this diverges.
8353sub get_default_bootdevices {
8354 my ($conf) = @_;
8355
8356 my @ret = ();
8357
8358 # harddisk
8359 my $first = PVE::QemuServer::Drive::resolve_first_disk($conf, 0);
8360 push @ret, $first if $first;
8361
8362 # cdrom
8363 $first = PVE::QemuServer::Drive::resolve_first_disk($conf, 1);
8364 push @ret, $first if $first;
8365
8366 # network
8367 for (my $i = 0; $i < $MAX_NETS; $i++) {
8368 my $netname = "net$i";
8369 next if !$conf->{$netname};
8370 push @ret, $netname;
8371 last;
8372 }
8373
8374 return \@ret;
8375}
8376
e5d611c3
TL
8377sub device_bootorder {
8378 my ($conf) = @_;
8379
8380 return bootorder_from_legacy($conf) if !defined($conf->{boot});
8381
8382 my $boot = parse_property_string($boot_fmt, $conf->{boot});
8383
8384 my $bootorder = {};
8385 if (!defined($boot) || $boot->{legacy}) {
8386 $bootorder = bootorder_from_legacy($conf, $boot);
8387 } elsif ($boot->{order}) {
8388 my $i = 100; # start at 100 to allow user to insert devices before us with -args
8389 for my $dev (PVE::Tools::split_list($boot->{order})) {
8390 $bootorder->{$dev} = $i++;
8391 }
8392 }
8393
8394 return $bootorder;
8395}
8396
65911545
SR
8397sub register_qmeventd_handle {
8398 my ($vmid) = @_;
8399
8400 my $fh;
8401 my $peer = "/var/run/qmeventd.sock";
8402 my $count = 0;
8403
8404 for (;;) {
8405 $count++;
8406 $fh = IO::Socket::UNIX->new(Peer => $peer, Blocking => 0, Timeout => 1);
8407 last if $fh;
8408 if ($! != EINTR && $! != EAGAIN) {
8409 die "unable to connect to qmeventd socket (vmid: $vmid) - $!\n";
8410 }
8411 if ($count > 4) {
8412 die "unable to connect to qmeventd socket (vmid: $vmid) - timeout "
8413 . "after $count retries\n";
8414 }
8415 usleep(25000);
8416 }
8417
8418 # send handshake to mark VM as backing up
8419 print $fh to_json({vzdump => {vmid => "$vmid"}});
8420
8421 # return handle to be closed later when inhibit is no longer required
8422 return $fh;
8423}
8424
65e866e5
DM
8425# bash completion helper
8426
8427sub complete_backup_archives {
8428 my ($cmdname, $pname, $cvalue) = @_;
8429
8430 my $cfg = PVE::Storage::config();
8431
8432 my $storeid;
8433
8434 if ($cvalue =~ m/^([^:]+):/) {
8435 $storeid = $1;
8436 }
8437
8438 my $data = PVE::Storage::template_list($cfg, $storeid, 'backup');
8439
8440 my $res = [];
8441 foreach my $id (keys %$data) {
8442 foreach my $item (@{$data->{$id}}) {
f43a4f12 8443 next if $item->{format} !~ m/^vma\.(${\PVE::Storage::Plugin::COMPRESSOR_RE})$/;
65e866e5
DM
8444 push @$res, $item->{volid} if defined($item->{volid});
8445 }
8446 }
8447
8448 return $res;
8449}
8450
8451my $complete_vmid_full = sub {
8452 my ($running) = @_;
8453
8454 my $idlist = vmstatus();
8455
8456 my $res = [];
8457
8458 foreach my $id (keys %$idlist) {
8459 my $d = $idlist->{$id};
8460 if (defined($running)) {
8461 next if $d->{template};
8462 next if $running && $d->{status} ne 'running';
8463 next if !$running && $d->{status} eq 'running';
8464 }
8465 push @$res, $id;
8466
8467 }
8468 return $res;
8469};
8470
8471sub complete_vmid {
8472 return &$complete_vmid_full();
8473}
8474
8475sub complete_vmid_stopped {
8476 return &$complete_vmid_full(0);
8477}
8478
8479sub complete_vmid_running {
8480 return &$complete_vmid_full(1);
8481}
8482
335af808
DM
8483sub complete_storage {
8484
8485 my $cfg = PVE::Storage::config();
8486 my $ids = $cfg->{ids};
8487
8488 my $res = [];
8489 foreach my $sid (keys %$ids) {
8490 next if !PVE::Storage::storage_check_enabled($cfg, $sid, undef, 1);
c4c844ef 8491 next if !$ids->{$sid}->{content}->{images};
335af808
DM
8492 push @$res, $sid;
8493 }
8494
8495 return $res;
8496}
8497
255e9c54
AL
8498sub complete_migration_storage {
8499 my ($cmd, $param, $current_value, $all_args) = @_;
8500
8501 my $targetnode = @$all_args[1];
8502
8503 my $cfg = PVE::Storage::config();
8504 my $ids = $cfg->{ids};
8505
8506 my $res = [];
8507 foreach my $sid (keys %$ids) {
8508 next if !PVE::Storage::storage_check_enabled($cfg, $sid, $targetnode, 1);
8509 next if !$ids->{$sid}->{content}->{images};
8510 push @$res, $sid;
8511 }
8512
8513 return $res;
8514}
8515
b08c37c3 8516sub vm_is_paused {
6f0627d4 8517 my ($vmid, $include_suspended) = @_;
b08c37c3
DC
8518 my $qmpstatus = eval {
8519 PVE::QemuConfig::assert_config_exists_on_node($vmid);
8520 mon_cmd($vmid, "query-status");
8521 };
8522 warn "$@\n" if $@;
7ba974a6
FS
8523 return $qmpstatus && (
8524 $qmpstatus->{status} eq "paused" ||
6f0627d4
FS
8525 $qmpstatus->{status} eq "prelaunch" ||
8526 ($include_suspended && $qmpstatus->{status} eq "suspended")
7ba974a6 8527 );
b08c37c3
DC
8528}
8529
3f11f0d7
LS
8530sub check_volume_storage_type {
8531 my ($storecfg, $vol) = @_;
8532
8533 my ($storeid, $volname) = PVE::Storage::parse_volume_id($vol);
8534 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
8535 my ($vtype) = PVE::Storage::parse_volname($storecfg, $vol);
8536
8537 die "storage '$storeid' does not support content-type '$vtype'\n"
8538 if !$scfg->{content}->{$vtype};
8539
8540 return 1;
8541}
8542
21947fea
AD
8543sub add_nets_bridge_fdb {
8544 my ($conf, $vmid) = @_;
8545
1b5ba4dd
TL
8546 for my $opt (keys %$conf) {
8547 next if $opt !~ m/^net(\d+)$/;
8548 my $iface = "tap${vmid}i$1";
4ddd2ca2
TL
8549 # NOTE: expect setups with learning off to *not* use auto-random-generation of MAC on start
8550 my $net = parse_net($conf->{$opt}, 1) or next;
8551
8552 my $mac = $net->{macaddr};
8553 if (!$mac) {
8554 log_warn("MAC learning disabled, but vNIC '$iface' has no static MAC to add to forwarding DB!")
8555 if !file_read_firstline("/sys/class/net/$iface/brport/learning");
8556 next;
8557 }
21947fea 8558
f81c9843 8559 my $bridge = $net->{bridge};
bb547dcb
CE
8560 if (!$bridge) {
8561 log_warn("Interface '$iface' not attached to any bridge.");
8562 next;
8563 }
1b5ba4dd 8564 if ($have_sdn) {
5bb8815a 8565 PVE::Network::SDN::Zones::add_bridge_fdb($iface, $mac, $bridge);
fe62da4f 8566 } elsif (-d "/sys/class/net/$bridge/bridge") { # avoid fdb management with OVS for now
5bb8815a 8567 PVE::Network::add_bridge_fdb($iface, $mac);
21947fea
AD
8568 }
8569 }
8570}
1b5ba4dd 8571
73ed6496
AD
8572sub del_nets_bridge_fdb {
8573 my ($conf, $vmid) = @_;
8574
8575 for my $opt (keys %$conf) {
8576 next if $opt !~ m/^net(\d+)$/;
8577 my $iface = "tap${vmid}i$1";
8578
8579 my $net = parse_net($conf->{$opt}) or next;
8580 my $mac = $net->{macaddr} or next;
8581
f81c9843 8582 my $bridge = $net->{bridge};
73ed6496 8583 if ($have_sdn) {
5bb8815a 8584 PVE::Network::SDN::Zones::del_bridge_fdb($iface, $mac, $bridge);
fe62da4f 8585 } elsif (-d "/sys/class/net/$bridge/bridge") { # avoid fdb management with OVS for now
5bb8815a 8586 PVE::Network::del_bridge_fdb($iface, $mac);
73ed6496
AD
8587 }
8588 }
8589}
8590
1e3baf05 85911;