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