]> git.proxmox.com Git - qemu-server.git/blame - PVE/QemuServer.pm
nbd-stop: increase timeout to 25s
[qemu-server.git] / PVE / QemuServer.pm
CommitLineData
baa4f62d 1package PVE::QemuServer;
1e3baf05
DM
2
3use strict;
990fc5e2 4use warnings;
3ff84d6f 5
5da072fb
TL
6use Cwd 'abs_path';
7use Digest::SHA;
8use Fcntl ':flock';
9use Fcntl;
1e3baf05 10use File::Basename;
5da072fb 11use File::Copy qw(copy);
1e3baf05
DM
12use File::Path;
13use File::stat;
14use Getopt::Long;
5da072fb
TL
15use IO::Dir;
16use IO::File;
17use IO::Handle;
18use IO::Select;
19use IO::Socket::UNIX;
1e3baf05 20use IPC::Open3;
c971c4f2 21use JSON;
c3d15108 22use List::Util qw(first);
1f30ac3a 23use MIME::Base64;
5da072fb
TL
24use POSIX;
25use Storable qw(dclone);
f85951dc 26use Time::HiRes qw(gettimeofday usleep);
5da072fb 27use URI::Escape;
425441e6 28use UUID;
5da072fb 29
82841214 30use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file);
5b65b00d 31use PVE::CGroup;
83870398 32use PVE::CpuSet;
48cf040f 33use PVE::DataCenterConfig;
5da072fb 34use PVE::Exception qw(raise raise_param_exc);
3b56383b 35use PVE::Format qw(render_duration render_bytes);
81d6e4e1 36use PVE::GuestHelpers qw(safe_string_ne safe_num_ne safe_boolean_ne);
a52eb3c4
DC
37use PVE::Mapping::PCI;
38use PVE::Mapping::USB;
1e3baf05 39use PVE::INotify;
4df98f2f 40use PVE::JSONSchema qw(get_standard_option parse_property_string);
1e3baf05 41use PVE::ProcFSTools;
fbec3f89 42use PVE::PBSClient;
34e82fa2 43use PVE::RESTEnvironment qw(log_warn);
91bd6c90 44use PVE::RPCEnvironment;
5da072fb 45use PVE::Storage;
b71351a7 46use PVE::SysFSTools;
d04d6af1 47use PVE::Systemd;
82841214 48use PVE::Tools qw(run_command file_read_firstline file_get_contents dir_glob_foreach get_host_arch $IPV6RE);
5da072fb
TL
49
50use PVE::QMPClient;
51use PVE::QemuConfig;
0e32bf5b 52use PVE::QemuServer::Helpers qw(config_aware_timeout min_version windows_version);
5da072fb 53use PVE::QemuServer::Cloudinit;
5b65b00d 54use PVE::QemuServer::CGroup;
d786a274 55use PVE::QemuServer::CPUConfig qw(print_cpu_device get_cpu_options);
75748d44 56use PVE::QemuServer::Drive qw(is_valid_drivename drive_is_cloudinit drive_is_cdrom drive_is_read_only parse_drive print_drive);
2ea5fb7e 57use PVE::QemuServer::Machine;
7f8c8087 58use PVE::QemuServer::Memory qw(get_current_memory);
0a13e08e 59use PVE::QemuServer::Monitor qw(mon_cmd);
74c17b7a 60use PVE::QemuServer::PCI qw(print_pci_addr print_pcie_addr print_pcie_root_port parse_hostpci);
87b0f305 61use PVE::QemuServer::QMPHelpers qw(qemu_deviceadd qemu_devicedel qemu_objectadd qemu_objectdel);
0cf8d56c 62use PVE::QemuServer::USB;
1e3baf05 63
28e129cc
AD
64my $have_sdn;
65eval {
66 require PVE::Network::SDN::Zones;
67 $have_sdn = 1;
68};
69
102cf9d8 70my $EDK2_FW_BASE = '/usr/share/pve-edk2-firmware/';
96ed3574 71my $OVMF = {
b5099b4f 72 x86_64 => {
90b20b15
DC
73 '4m-no-smm' => [
74 "$EDK2_FW_BASE/OVMF_CODE_4M.fd",
75 "$EDK2_FW_BASE/OVMF_VARS_4M.fd",
76 ],
77 '4m-no-smm-ms' => [
78 "$EDK2_FW_BASE/OVMF_CODE_4M.fd",
79 "$EDK2_FW_BASE/OVMF_VARS_4M.ms.fd",
80 ],
b5099b4f
SR
81 '4m' => [
82 "$EDK2_FW_BASE/OVMF_CODE_4M.secboot.fd",
83 "$EDK2_FW_BASE/OVMF_VARS_4M.fd",
84 ],
85 '4m-ms' => [
86 "$EDK2_FW_BASE/OVMF_CODE_4M.secboot.fd",
87 "$EDK2_FW_BASE/OVMF_VARS_4M.ms.fd",
88 ],
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,
7f8c8087
AD
353 type => 'string',
354 description => "Memory properties.",
355 format => $PVE::QemuServer::Memory::memory_fmt
1e3baf05 356 },
13a48620 357 balloon => {
483ceeab
TL
358 optional => 1,
359 type => 'integer',
252e2624 360 description => "Amount of target RAM for the VM in MiB. Using zero disables the ballon driver.",
8b1accf7
DM
361 minimum => 0,
362 },
363 shares => {
483ceeab
TL
364 optional => 1,
365 type => 'integer',
366 description => "Amount of memory shares for auto-ballooning. The larger the number is, the"
8d88a594
TL
367 ." more memory this VM gets. Number is relative to weights of all other running VMs."
368 ." Using zero disables auto-ballooning. Auto-ballooning is done by pvestatd.",
8b1accf7
DM
369 minimum => 0,
370 maximum => 50000,
371 default => 1000,
13a48620 372 },
1e3baf05
DM
373 keyboard => {
374 optional => 1,
375 type => 'string',
233fb336
DW
376 description => "Keyboard layout for VNC server. This option is generally not required and"
377 ." is often better handled from within the guest OS.",
e95fe75f 378 enum => PVE::Tools::kvmkeymaplist(),
aea47dd6 379 default => undef,
1e3baf05
DM
380 },
381 name => {
382 optional => 1,
7fabe17d 383 type => 'string', format => 'dns-name',
1e3baf05
DM
384 description => "Set a name for the VM. Only used on the configuration web interface.",
385 },
cdd20088
AD
386 scsihw => {
387 optional => 1,
388 type => 'string',
52261945 389 description => "SCSI controller model",
6731a4cf 390 enum => [qw(lsi lsi53c810 virtio-scsi-pci virtio-scsi-single megasas pvscsi)],
cdd20088
AD
391 default => 'lsi',
392 },
1e3baf05
DM
393 description => {
394 optional => 1,
395 type => 'string',
a200af10
TL
396 description => "Description for the VM. Shown in the web-interface VM's summary."
397 ." This is saved as comment inside the configuration file.",
398 maxLength => 1024 * 8,
1e3baf05
DM
399 },
400 ostype => {
401 optional => 1,
402 type => 'string',
483ceeab 403 enum => [qw(other wxp w2k w2k3 w2k8 wvista win7 win8 win10 win11 l24 l26 solaris)],
52261945
DM
404 description => "Specify guest operating system.",
405 verbose_description => <<EODESC,
406Specify guest operating system. This is used to enable special
407optimization/features for specific operating systems:
408
409[horizontal]
410other;; unspecified OS
411wxp;; Microsoft Windows XP
412w2k;; Microsoft Windows 2000
413w2k3;; Microsoft Windows 2003
414w2k8;; Microsoft Windows 2008
415wvista;; Microsoft Windows Vista
416win7;; Microsoft Windows 7
44c2a647 417win8;; Microsoft Windows 8/2012/2012r2
1f5828f2 418win10;; Microsoft Windows 10/2016/2019
179b9f1b 419win11;; Microsoft Windows 11/2022
52261945 420l24;; Linux 2.4 Kernel
ea0bc514 421l26;; Linux 2.6 - 6.X Kernel
52261945 422solaris;; Solaris/OpenSolaris/OpenIndiania kernel
1e3baf05
DM
423EODESC
424 },
425 boot => {
426 optional => 1,
2141a802 427 type => 'string', format => 'pve-qm-boot',
483ceeab
TL
428 description => "Specify guest boot order. Use the 'order=' sub-property as usage with no"
429 ." key or 'legacy=' is deprecated.",
1e3baf05
DM
430 },
431 bootdisk => {
432 optional => 1,
433 type => 'string', format => 'pve-qm-bootdisk',
2141a802 434 description => "Enable booting from specified disk. Deprecated: Use 'boot: order=foo;bar' instead.",
03e480fc 435 pattern => '(ide|sata|scsi|virtio)\d+',
1e3baf05
DM
436 },
437 smp => {
438 optional => 1,
439 type => 'integer',
440 description => "The number of CPUs. Please use option -sockets instead.",
441 minimum => 1,
442 default => 1,
443 },
444 sockets => {
445 optional => 1,
446 type => 'integer',
447 description => "The number of CPU sockets.",
448 minimum => 1,
449 default => 1,
450 },
451 cores => {
452 optional => 1,
453 type => 'integer',
454 description => "The number of cores per socket.",
455 minimum => 1,
456 default => 1,
457 },
8a010eae
AD
458 numa => {
459 optional => 1,
460 type => 'boolean',
1917695c 461 description => "Enable/disable NUMA.",
8a010eae
AD
462 default => 0,
463 },
7023f3ea
AD
464 hugepages => {
465 optional => 1,
466 type => 'string',
467 description => "Enable/disable hugepages memory.",
468 enum => [qw(any 2 1024)],
469 },
f36e9894
SR
470 keephugepages => {
471 optional => 1,
472 type => 'boolean',
473 default => 0,
4df98f2f
TL
474 description => "Use together with hugepages. If enabled, hugepages will not not be deleted"
475 ." after VM shutdown and can be used for subsequent starts.",
f36e9894 476 },
de9d1e55 477 vcpus => {
3bd18e48
AD
478 optional => 1,
479 type => 'integer',
de9d1e55 480 description => "Number of hotplugged vcpus.",
3bd18e48 481 minimum => 1,
de9d1e55 482 default => 0,
3bd18e48 483 },
1e3baf05
DM
484 acpi => {
485 optional => 1,
486 type => 'boolean',
487 description => "Enable/disable ACPI.",
488 default => 1,
489 },
bc84dcca 490 agent => {
ab6a046f 491 optional => 1,
7bd9abd2 492 description => "Enable/disable communication with the QEMU Guest Agent and its properties.",
9d66b397
SI
493 type => 'string',
494 format => $agent_fmt,
ab6a046f 495 },
1e3baf05
DM
496 kvm => {
497 optional => 1,
498 type => 'boolean',
499 description => "Enable/disable KVM hardware virtualization.",
500 default => 1,
501 },
502 tdf => {
503 optional => 1,
504 type => 'boolean',
8c559505
DM
505 description => "Enable/disable time drift fix.",
506 default => 0,
1e3baf05 507 },
19672434 508 localtime => {
1e3baf05
DM
509 optional => 1,
510 type => 'boolean',
8d88a594
TL
511 description => "Set the real time clock (RTC) to local time. This is enabled by default if"
512 ." the `ostype` indicates a Microsoft Windows OS.",
1e3baf05
DM
513 },
514 freeze => {
515 optional => 1,
516 type => 'boolean',
517 description => "Freeze CPU at startup (use 'c' monitor command to start execution).",
518 },
519 vga => {
520 optional => 1,
55655ebc
DC
521 type => 'string', format => $vga_fmt,
522 description => "Configure the VGA hardware.",
4df98f2f
TL
523 verbose_description => "Configure the VGA Hardware. If you want to use high resolution"
524 ." modes (>= 1280x1024x16) you may need to increase the vga memory option. Since QEMU"
525 ." 2.9 the default VGA display type is 'std' for all OS types besides some Windows"
526 ." versions (XP and older) which use 'cirrus'. The 'qxl' option enables the SPICE"
527 ." display server. For win* OS you can select how many independent displays you want,"
528 ." Linux guests can add displays them self.\nYou can also run without any graphic card,"
529 ." using a serial device as terminal.",
1e3baf05 530 },
0ea9541d
DM
531 watchdog => {
532 optional => 1,
533 type => 'string', format => 'pve-qm-watchdog',
52261945 534 description => "Create a virtual hardware watchdog device.",
4df98f2f
TL
535 verbose_description => "Create a virtual hardware watchdog device. Once enabled (by a guest"
536 ." action), the watchdog must be periodically polled by an agent inside the guest or"
537 ." else the watchdog will reset the guest (or execute the respective action specified)",
0ea9541d 538 },
1e3baf05
DM
539 startdate => {
540 optional => 1,
19672434 541 type => 'string',
1e3baf05 542 typetext => "(now | YYYY-MM-DD | YYYY-MM-DDTHH:MM:SS)",
4df98f2f
TL
543 description => "Set the initial date of the real time clock. Valid format for date are:"
544 ."'now' or '2006-06-17T16:01:21' or '2006-06-17'.",
1e3baf05
DM
545 pattern => '(now|\d{4}-\d{1,2}-\d{1,2}(T\d{1,2}:\d{1,2}:\d{1,2})?)',
546 default => 'now',
547 },
43574f73 548 startup => get_standard_option('pve-startup-order'),
68eda3ab
AD
549 template => {
550 optional => 1,
551 type => 'boolean',
552 description => "Enable/disable Template.",
553 default => 0,
554 },
1e3baf05
DM
555 args => {
556 optional => 1,
557 type => 'string',
52261945
DM
558 description => "Arbitrary arguments passed to kvm.",
559 verbose_description => <<EODESCR,
c7a8aad6 560Arbitrary arguments passed to kvm, for example:
1e3baf05 561
bda7ccb1 562args: -no-reboot -smbios 'type=0,vendor=FOO'
c7a8aad6
FG
563
564NOTE: this option is for experts only.
1e3baf05
DM
565EODESCR
566 },
567 tablet => {
568 optional => 1,
569 type => 'boolean',
570 default => 1,
52261945 571 description => "Enable/disable the USB tablet device.",
4df98f2f
TL
572 verbose_description => "Enable/disable the USB tablet device. This device is usually needed"
573 ." to allow absolute mouse positioning with VNC. Else the mouse runs out of sync with"
574 ." normal VNC clients. If you're running lots of console-only guests on one host, you"
575 ." may consider disabling this to save some context switches. This is turned off by"
576 ." default if you use spice (`qm set <vmid> --vga qxl`).",
1e3baf05
DM
577 },
578 migrate_speed => {
579 optional => 1,
580 type => 'integer',
581 description => "Set maximum speed (in MB/s) for migrations. Value 0 is no limit.",
582 minimum => 0,
583 default => 0,
584 },
585 migrate_downtime => {
586 optional => 1,
04432191 587 type => 'number',
1e3baf05
DM
588 description => "Set maximum tolerated downtime (in seconds) for migrations.",
589 minimum => 0,
04432191 590 default => 0.1,
1e3baf05
DM
591 },
592 cdrom => {
593 optional => 1,
b799312f 594 type => 'string', format => 'pve-qm-ide',
8485b9ba 595 typetext => '<volume>',
1e3baf05
DM
596 description => "This is an alias for option -ide2",
597 },
598 cpu => {
599 optional => 1,
600 description => "Emulated CPU type.",
601 type => 'string',
5d008ad3 602 format => 'pve-vm-cpu-conf',
1e3baf05 603 },
b7ba6b79
DM
604 parent => get_standard_option('pve-snapshot-name', {
605 optional => 1,
606 description => "Parent snapshot name. This is used internally, and should not be modified.",
607 }),
982c7f12
DM
608 snaptime => {
609 optional => 1,
610 description => "Timestamp for snapshots.",
611 type => 'integer',
612 minimum => 0,
613 },
18bfb361
DM
614 vmstate => {
615 optional => 1,
616 type => 'string', format => 'pve-volume-id',
4df98f2f
TL
617 description => "Reference to a volume which stores the VM state. This is used internally"
618 ." for snapshots.",
18bfb361 619 },
253624c7
FG
620 vmstatestorage => get_standard_option('pve-storage-id', {
621 description => "Default storage for VM state volumes/files.",
622 optional => 1,
623 }),
c6737ef1 624 runningmachine => get_standard_option('pve-qemu-machine', {
4df98f2f
TL
625 description => "Specifies the QEMU machine type of the running vm. This is used internally"
626 ." for snapshots.",
c6737ef1 627 }),
ea1c2110 628 runningcpu => {
4df98f2f
TL
629 description => "Specifies the QEMU '-cpu' parameter of the running vm. This is used"
630 ." internally for snapshots.",
ea1c2110
SR
631 optional => 1,
632 type => 'string',
633 pattern => $PVE::QemuServer::CPUConfig::qemu_cmdline_cpu_re,
634 format_description => 'QEMU -cpu parameter'
635 },
c6737ef1 636 machine => get_standard_option('pve-qemu-machine'),
d731ecbe
WB
637 arch => {
638 description => "Virtual processor architecture. Defaults to the host.",
639 optional => 1,
640 type => 'string',
641 enum => [qw(x86_64 aarch64)],
642 },
2796e7d5
DM
643 smbios1 => {
644 description => "Specify SMBIOS type 1 fields.",
645 type => 'string', format => 'pve-qm-smbios1',
5d004b00 646 maxLength => 512,
2796e7d5
DM
647 optional => 1,
648 },
cb0e4540
AG
649 protection => {
650 optional => 1,
651 type => 'boolean',
4df98f2f
TL
652 description => "Sets the protection flag of the VM. This will disable the remove VM and"
653 ." remove disk operations.",
cb0e4540
AG
654 default => 0,
655 },
3edb45e7 656 bios => {
a783c78e 657 optional => 1,
3edb45e7
DM
658 type => 'string',
659 enum => [ qw(seabios ovmf) ],
660 description => "Select BIOS implementation.",
661 default => 'seabios',
a783c78e 662 },
6ee499ff
DC
663 vmgenid => {
664 type => 'string',
665 pattern => '(?:[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}|[01])',
666 format_description => 'UUID',
4df98f2f
TL
667 description => "Set VM Generation ID. Use '1' to autogenerate on create or update, pass '0'"
668 ." to disable explicitly.",
669 verbose_description => "The VM generation ID (vmgenid) device exposes a 128-bit integer"
670 ." value identifier to the guest OS. This allows to notify the guest operating system"
671 ." when the virtual machine is executed with a different configuration (e.g. snapshot"
672 ." execution or creation from a template). The guest operating system notices the"
673 ." change, and is then able to react as appropriate by marking its copies of"
674 ." distributed databases as dirty, re-initializing its random number generator, etc.\n"
675 ."Note that auto-creation only works when done through API/CLI create or update methods"
676 .", but not when manually editing the config file.",
f7ed64e7 677 default => "1 (autogenerated)",
6ee499ff
DC
678 optional => 1,
679 },
9e784b11
DC
680 hookscript => {
681 type => 'string',
682 format => 'pve-volume-id',
683 optional => 1,
684 description => "Script that will be executed during various steps in the vms lifetime.",
685 },
6dbcb073
DC
686 ivshmem => {
687 type => 'string',
688 format => $ivshmem_fmt,
4df98f2f
TL
689 description => "Inter-VM shared memory. Useful for direct communication between VMs, or to"
690 ." the host.",
6dbcb073 691 optional => 1,
2e7b5925
AL
692 },
693 audio0 => {
694 type => 'string',
1448547f 695 format => $audio_fmt,
194b65f1 696 description => "Configure a audio device, useful in combination with QXL/Spice.",
2e7b5925
AL
697 optional => 1
698 },
c4df18db
AL
699 spice_enhancements => {
700 type => 'string',
701 format => $spice_enhancements_fmt,
702 description => "Configure additional enhancements for SPICE.",
703 optional => 1
704 },
b8e7068a
DC
705 tags => {
706 type => 'string', format => 'pve-tag-list',
707 description => 'Tags of the VM. This is only meta information.',
708 optional => 1,
709 },
2cf61f33
SR
710 rng0 => {
711 type => 'string',
712 format => $rng_fmt,
713 description => "Configure a VirtIO-based Random Number Generator.",
714 optional => 1,
715 },
26b443c8
TL
716 meta => {
717 type => 'string',
718 format => $meta_info_fmt,
719 description => "Some (read-only) meta-information about this guest.",
720 optional => 1,
721 },
83870398
DB
722 affinity => {
723 type => 'string', format => 'pve-cpuset',
326704e7 724 description => "List of host cores used to execute guest processes, for example: 0,5,8-11",
83870398
DB
725 optional => 1,
726 },
9ed7a77c
WB
727};
728
cb702ebe
DL
729my $cicustom_fmt = {
730 meta => {
731 type => 'string',
732 optional => 1,
4df98f2f
TL
733 description => 'Specify a custom file containing all meta data passed to the VM via"
734 ." cloud-init. This is provider specific meaning configdrive2 and nocloud differ.',
cb702ebe
DL
735 format => 'pve-volume-id',
736 format_description => 'volume',
737 },
738 network => {
739 type => 'string',
740 optional => 1,
eba285f5 741 description => 'To pass a custom file containing all network data to the VM via cloud-init.',
cb702ebe
DL
742 format => 'pve-volume-id',
743 format_description => 'volume',
744 },
745 user => {
746 type => 'string',
747 optional => 1,
eba285f5 748 description => 'To pass a custom file containing all user data to the VM via cloud-init.',
cb702ebe
DL
749 format => 'pve-volume-id',
750 format_description => 'volume',
751 },
101beafe 752 vendor => {
eba285f5
TL
753 type => 'string',
754 optional => 1,
755 description => 'To pass a custom file containing all vendor data to the VM via cloud-init.',
756 format => 'pve-volume-id',
757 format_description => 'volume',
101beafe 758 },
cb702ebe
DL
759};
760PVE::JSONSchema::register_format('pve-qm-cicustom', $cicustom_fmt);
761
92c02f6c 762# any new option might need to be added to $cloudinitoptions in PVE::API2::Qemu
9ed7a77c 763my $confdesc_cloudinit = {
41cd94a0
WB
764 citype => {
765 optional => 1,
766 type => 'string',
4df98f2f
TL
767 description => 'Specifies the cloud-init configuration format. The default depends on the'
768 .' configured operating system type (`ostype`. We use the `nocloud` format for Linux,'
769 .' and `configdrive2` for windows.',
545eec65 770 enum => ['configdrive2', 'nocloud', 'opennebula'],
41cd94a0 771 },
7b42f951
WB
772 ciuser => {
773 optional => 1,
774 type => 'string',
4df98f2f
TL
775 description => "cloud-init: User name to change ssh keys and password for instead of the"
776 ." image's configured default user.",
7b42f951
WB
777 },
778 cipassword => {
779 optional => 1,
780 type => 'string',
4df98f2f
TL
781 description => 'cloud-init: Password to assign the user. Using this is generally not'
782 .' recommended. Use ssh keys instead. Also note that older cloud-init versions do not'
783 .' support hashed passwords.',
7b42f951 784 },
efa3355d
LN
785 ciupgrade => {
786 optional => 1,
787 type => 'boolean',
178c355d 788 description => 'cloud-init: do an automatic package upgrade after the first boot.',
ec11b92a 789 default => 1,
efa3355d 790 },
cb702ebe
DL
791 cicustom => {
792 optional => 1,
793 type => 'string',
4df98f2f
TL
794 description => 'cloud-init: Specify custom files to replace the automatically generated'
795 .' ones at start.',
cb702ebe
DL
796 format => 'pve-qm-cicustom',
797 },
0c9a7596
AD
798 searchdomain => {
799 optional => 1,
800 type => 'string',
bd49ecb4 801 description => 'cloud-init: Sets DNS search domains for a container. Create will'
4df98f2f 802 .' automatically use the setting from the host if neither searchdomain nor nameserver'
bd49ecb4 803 .' are set.',
0c9a7596
AD
804 },
805 nameserver => {
806 optional => 1,
807 type => 'string', format => 'address-list',
bd49ecb4 808 description => 'cloud-init: Sets DNS server IP address for a container. Create will'
4df98f2f 809 .' automatically use the setting from the host if neither searchdomain nor nameserver'
bd49ecb4 810 .' are set.',
0c9a7596
AD
811 },
812 sshkeys => {
813 optional => 1,
814 type => 'string',
815 format => 'urlencoded',
1d1c4e1c 816 description => "cloud-init: Setup public SSH keys (one key per line, OpenSSH format).",
0c9a7596 817 },
1e3baf05
DM
818};
819
820# what about other qemu settings ?
821#cpu => 'string',
822#machine => 'string',
823#fda => 'file',
824#fdb => 'file',
825#mtdblock => 'file',
826#sd => 'file',
827#pflash => 'file',
828#snapshot => 'bool',
829#bootp => 'file',
830##tftp => 'dir',
831##smb => 'dir',
832#kernel => 'file',
833#append => 'string',
834#initrd => 'file',
835##soundhw => 'string',
836
837while (my ($k, $v) = each %$confdesc) {
838 PVE::JSONSchema::register_standard_option("pve-qm-$k", $v);
839}
840
5bdcf937 841my $MAX_NETS = 32;
bae179aa 842my $MAX_SERIAL_PORTS = 4;
1989a89c 843my $MAX_PARALLEL_PORTS = 3;
2ed5d572 844
0e32bf5b
FE
845for (my $i = 0; $i < $PVE::QemuServer::Memory::MAX_NUMA; $i++) {
846 $confdesc->{"numa$i"} = $PVE::QemuServer::Memory::numadesc;
2ed5d572 847}
1e3baf05 848
f7bc17ca
TL
849my $nic_model_list = [
850 'e1000',
851 'e1000-82540em',
852 'e1000-82544gc',
853 'e1000-82545em',
e83dd50a 854 'e1000e',
f7bc17ca
TL
855 'i82551',
856 'i82557b',
857 'i82559er',
858 'ne2k_isa',
859 'ne2k_pci',
860 'pcnet',
861 'rtl8139',
862 'virtio',
863 'vmxnet3',
864];
6b64503e 865my $nic_model_list_txt = join(' ', sort @$nic_model_list);
1e3baf05 866
52261945
DM
867my $net_fmt_bridge_descr = <<__EOD__;
868Bridge to attach the network device to. The Proxmox VE standard bridge
869is called 'vmbr0'.
870
871If you do not specify a bridge, we create a kvm user (NATed) network
872device, which provides DHCP and DNS services. The following addresses
873are used:
874
875 10.0.2.2 Gateway
876 10.0.2.3 DNS Server
877 10.0.2.4 SMB Server
878
879The DHCP server assign addresses to the guest starting from 10.0.2.15.
880__EOD__
881
cd9c34d1 882my $net_fmt = {
399d96db 883 macaddr => get_standard_option('mac-addr', {
4df98f2f
TL
884 description => "MAC address. That address must be unique withing your network. This is"
885 ." automatically generated if not specified.",
399d96db 886 }),
7f694a71
DM
887 model => {
888 type => 'string',
4df98f2f
TL
889 description => "Network Card Model. The 'virtio' model provides the best performance with"
890 ." very low CPU overhead. If your guest does not support this driver, it is usually"
891 ." best to use 'e1000'.",
7f694a71
DM
892 enum => $nic_model_list,
893 default_key => 1,
894 },
895 (map { $_ => { keyAlias => 'model', alias => 'macaddr' }} @$nic_model_list),
dbdcc5cd 896 bridge => get_standard_option('pve-bridge-id', {
52261945 897 description => $net_fmt_bridge_descr,
cd9c34d1 898 optional => 1,
dbdcc5cd 899 }),
cd9c34d1
WB
900 queues => {
901 type => 'integer',
66222265 902 minimum => 0, maximum => 64,
cd9c34d1 903 description => 'Number of packet queues to be used on the device.',
cd9c34d1
WB
904 optional => 1,
905 },
906 rate => {
907 type => 'number',
908 minimum => 0,
52261945 909 description => "Rate limit in mbps (megabytes per second) as floating point number.",
cd9c34d1
WB
910 optional => 1,
911 },
912 tag => {
913 type => 'integer',
9f41a659 914 minimum => 1, maximum => 4094,
cd9c34d1 915 description => 'VLAN tag to apply to packets on this interface.',
cd9c34d1
WB
916 optional => 1,
917 },
918 trunks => {
919 type => 'string',
920 pattern => qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/,
921 description => 'VLAN trunks to pass through this interface.',
7f694a71 922 format_description => 'vlanid[;vlanid...]',
cd9c34d1
WB
923 optional => 1,
924 },
925 firewall => {
926 type => 'boolean',
927 description => 'Whether this interface should be protected by the firewall.',
cd9c34d1
WB
928 optional => 1,
929 },
930 link_down => {
931 type => 'boolean',
52261945 932 description => 'Whether this interface should be disconnected (like pulling the plug).',
cd9c34d1
WB
933 optional => 1,
934 },
61a14cde
AD
935 mtu => {
936 type => 'integer',
937 minimum => 1, maximum => 65520,
0530177b 938 description => "Force MTU, for VirtIO only. Set to '1' to use the bridge MTU",
61a14cde
AD
939 optional => 1,
940 },
cd9c34d1 941};
52261945 942
1e3baf05
DM
943my $netdesc = {
944 optional => 1,
7f694a71 945 type => 'string', format => $net_fmt,
52261945 946 description => "Specify network devices.",
1e3baf05 947};
52261945 948
1e3baf05
DM
949PVE::JSONSchema::register_standard_option("pve-qm-net", $netdesc);
950
0c9a7596
AD
951my $ipconfig_fmt = {
952 ip => {
953 type => 'string',
954 format => 'pve-ipv4-config',
955 format_description => 'IPv4Format/CIDR',
956 description => 'IPv4 address in CIDR format.',
957 optional => 1,
958 default => 'dhcp',
959 },
960 gw => {
961 type => 'string',
962 format => 'ipv4',
963 format_description => 'GatewayIPv4',
964 description => 'Default gateway for IPv4 traffic.',
965 optional => 1,
966 requires => 'ip',
967 },
968 ip6 => {
969 type => 'string',
970 format => 'pve-ipv6-config',
971 format_description => 'IPv6Format/CIDR',
972 description => 'IPv6 address in CIDR format.',
973 optional => 1,
974 default => 'dhcp',
975 },
976 gw6 => {
977 type => 'string',
978 format => 'ipv6',
979 format_description => 'GatewayIPv6',
980 description => 'Default gateway for IPv6 traffic.',
981 optional => 1,
982 requires => 'ip6',
983 },
984};
985PVE::JSONSchema::register_format('pve-qm-ipconfig', $ipconfig_fmt);
986my $ipconfigdesc = {
987 optional => 1,
988 type => 'string', format => 'pve-qm-ipconfig',
989 description => <<'EODESCR',
990cloud-init: Specify IP addresses and gateways for the corresponding interface.
991
992IP addresses use CIDR notation, gateways are optional but need an IP of the same type specified.
993
4df98f2f
TL
994The special string 'dhcp' can be used for IP addresses to use DHCP, in which case no explicit
995gateway should be provided.
988be8d0
ML
996For IPv6 the special string 'auto' can be used to use stateless autoconfiguration. This requires
997cloud-init 19.4 or newer.
0c9a7596 998
4df98f2f
TL
999If cloud-init is enabled and neither an IPv4 nor an IPv6 address is specified, it defaults to using
1000dhcp on IPv4.
0c9a7596
AD
1001EODESCR
1002};
1003PVE::JSONSchema::register_standard_option("pve-qm-ipconfig", $netdesc);
1004
1e3baf05
DM
1005for (my $i = 0; $i < $MAX_NETS; $i++) {
1006 $confdesc->{"net$i"} = $netdesc;
9ed7a77c
WB
1007 $confdesc_cloudinit->{"ipconfig$i"} = $ipconfigdesc;
1008}
1009
1010foreach my $key (keys %$confdesc_cloudinit) {
1011 $confdesc->{$key} = $confdesc_cloudinit->{$key};
1e3baf05
DM
1012}
1013
83870398
DB
1014PVE::JSONSchema::register_format('pve-cpuset', \&pve_verify_cpuset);
1015sub pve_verify_cpuset {
1016 my ($set_text, $noerr) = @_;
1017
1018 my ($count, $members) = eval { PVE::CpuSet::parse_cpuset($set_text) };
1019
1020 if ($@) {
1021 return if $noerr;
1022 die "unable to parse cpuset option\n";
1023 }
1024
1025 return PVE::CpuSet->new($members)->short_string();
1026}
1027
ffa42b86
DC
1028PVE::JSONSchema::register_format('pve-volume-id-or-qm-path', \&verify_volume_id_or_qm_path);
1029sub verify_volume_id_or_qm_path {
822c8a07
WB
1030 my ($volid, $noerr) = @_;
1031
6e55f579
FE
1032 return $volid if $volid eq 'none' || $volid eq 'cdrom';
1033
1034 return verify_volume_id_or_absolute_path($volid, $noerr);
1035}
1036
1037PVE::JSONSchema::register_format('pve-volume-id-or-absolute-path', \&verify_volume_id_or_absolute_path);
1038sub verify_volume_id_or_absolute_path {
1039 my ($volid, $noerr) = @_;
1040
1041 return $volid if $volid =~ m|^/|;
ffa42b86 1042
822c8a07
WB
1043 $volid = eval { PVE::JSONSchema::check_format('pve-volume-id', $volid, '') };
1044 if ($@) {
d1c1af4b 1045 return if $noerr;
822c8a07
WB
1046 die $@;
1047 }
1048 return $volid;
1049}
1050
bae179aa
DA
1051my $serialdesc = {
1052 optional => 1,
ca0cef26 1053 type => 'string',
1b0b51ed 1054 pattern => '(/dev/.+|socket)',
52261945
DM
1055 description => "Create a serial device inside the VM (n is 0 to 3)",
1056 verbose_description => <<EODESCR,
52261945
DM
1057Create a serial device inside the VM (n is 0 to 3), and pass through a
1058host serial device (i.e. /dev/ttyS0), or create a unix socket on the
1059host side (use 'qm terminal' to open a terminal connection).
bae179aa 1060
4df98f2f
TL
1061NOTE: If you pass through a host serial device, it is no longer possible to migrate such machines -
1062use with special care.
bae179aa 1063
52261945 1064CAUTION: Experimental! User reported problems with this option.
bae179aa
DA
1065EODESCR
1066};
bae179aa 1067
1989a89c
DA
1068my $paralleldesc= {
1069 optional => 1,
ca0cef26 1070 type => 'string',
9ecc8431 1071 pattern => '/dev/parport\d+|/dev/usb/lp\d+',
52261945
DM
1072 description => "Map host parallel devices (n is 0 to 2).",
1073 verbose_description => <<EODESCR,
19672434 1074Map host parallel devices (n is 0 to 2).
1989a89c 1075
4df98f2f
TL
1076NOTE: This option allows direct access to host hardware. So it is no longer possible to migrate such
1077machines - use with special care.
1989a89c 1078
52261945 1079CAUTION: Experimental! User reported problems with this option.
1989a89c
DA
1080EODESCR
1081};
1989a89c
DA
1082
1083for (my $i = 0; $i < $MAX_PARALLEL_PORTS; $i++) {
1084 $confdesc->{"parallel$i"} = $paralleldesc;
1085}
1086
bae179aa
DA
1087for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) {
1088 $confdesc->{"serial$i"} = $serialdesc;
1089}
1090
74c17b7a
SR
1091for (my $i = 0; $i < $PVE::QemuServer::PCI::MAX_HOSTPCI_DEVICES; $i++) {
1092 $confdesc->{"hostpci$i"} = $PVE::QemuServer::PCI::hostpcidesc;
040b06b7 1093}
1e3baf05 1094
e0fd2b2f
FE
1095for my $key (keys %{$PVE::QemuServer::Drive::drivedesc_hash}) {
1096 $confdesc->{$key} = $PVE::QemuServer::Drive::drivedesc_hash->{$key};
cdb0931f
DA
1097}
1098
0cf8d56c
DC
1099for (my $i = 0; $i < $PVE::QemuServer::USB::MAX_USB_DEVICES; $i++) {
1100 $confdesc->{"usb$i"} = $PVE::QemuServer::USB::usbdesc;
1e3baf05
DM
1101}
1102
5cfa9f5f
SR
1103my $boot_fmt = {
1104 legacy => {
1105 optional => 1,
1106 default_key => 1,
1107 type => 'string',
1108 description => "Boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)."
1109 . " Deprecated, use 'order=' instead.",
1110 pattern => '[acdn]{1,4}',
1111 format_description => "[acdn]{1,4}",
1112
1113 # note: this is also the fallback if boot: is not given at all
1114 default => 'cdn',
1115 },
1116 order => {
1117 optional => 1,
1118 type => 'string',
1119 format => 'pve-qm-bootdev-list',
1120 format_description => "device[;device...]",
1121 description => <<EODESC,
1122The guest will attempt to boot from devices in the order they appear here.
1123
1124Disks, optical drives and passed-through storage USB devices will be directly
1125booted from, NICs will load PXE, and PCIe devices will either behave like disks
1126(e.g. NVMe) or load an option ROM (e.g. RAID controller, hardware NIC).
1127
1128Note that only devices in this list will be marked as bootable and thus loaded
1129by the guest firmware (BIOS/UEFI). If you require multiple disks for booting
1130(e.g. software-raid), you need to specify all of them here.
1131
1132Overrides the deprecated 'legacy=[acdn]*' value when given.
1133EODESC
1134 },
1135};
1136PVE::JSONSchema::register_format('pve-qm-boot', $boot_fmt);
1137
1138PVE::JSONSchema::register_format('pve-qm-bootdev', \&verify_bootdev);
1139sub verify_bootdev {
1140 my ($dev, $noerr) = @_;
1141
f9dde219
SR
1142 my $special = $dev =~ m/^efidisk/ || $dev =~ m/^tpmstate/;
1143 return $dev if PVE::QemuServer::Drive::is_valid_drivename($dev) && !$special;
5cfa9f5f
SR
1144
1145 my $check = sub {
1146 my ($base) = @_;
1147 return 0 if $dev !~ m/^$base\d+$/;
1148 return 0 if !$confdesc->{$dev};
1149 return 1;
1150 };
1151
1152 return $dev if $check->("net");
1153 return $dev if $check->("usb");
1154 return $dev if $check->("hostpci");
1155
d1c1af4b 1156 return if $noerr;
5cfa9f5f
SR
1157 die "invalid boot device '$dev'\n";
1158}
1159
1160sub print_bootorder {
1161 my ($devs) = @_;
4c27b18c 1162 return "" if !@$devs;
5cfa9f5f
SR
1163 my $data = { order => join(';', @$devs) };
1164 return PVE::JSONSchema::print_property_string($data, $boot_fmt);
1165}
1166
1e3baf05
DM
1167my $kvm_api_version = 0;
1168
1169sub kvm_version {
1e3baf05
DM
1170 return $kvm_api_version if $kvm_api_version;
1171
808a65b5 1172 open my $fh, '<', '/dev/kvm' or return;
1e3baf05 1173
646f2df4
WB
1174 # 0xae00 => KVM_GET_API_VERSION
1175 $kvm_api_version = ioctl($fh, 0xae00, 0);
808a65b5 1176 close($fh);
1e3baf05 1177
646f2df4 1178 return $kvm_api_version;
1e3baf05
DM
1179}
1180
1476b99f
DC
1181my $kvm_user_version = {};
1182my $kvm_mtime = {};
1e3baf05
DM
1183
1184sub kvm_user_version {
1476b99f 1185 my ($binary) = @_;
1e3baf05 1186
1476b99f
DC
1187 $binary //= get_command_for_arch(get_host_arch()); # get the native arch by default
1188 my $st = stat($binary);
1e3baf05 1189
1476b99f
DC
1190 my $cachedmtime = $kvm_mtime->{$binary} // -1;
1191 return $kvm_user_version->{$binary} if $kvm_user_version->{$binary} &&
1192 $cachedmtime == $st->mtime;
1193
1194 $kvm_user_version->{$binary} = 'unknown';
1195 $kvm_mtime->{$binary} = $st->mtime;
1e3baf05 1196
09b11429
TL
1197 my $code = sub {
1198 my $line = shift;
1199 if ($line =~ m/^QEMU( PC)? emulator version (\d+\.\d+(\.\d+)?)(\.\d+)?[,\s]/) {
1476b99f 1200 $kvm_user_version->{$binary} = $2;
09b11429
TL
1201 }
1202 };
19672434 1203
1476b99f 1204 eval { run_command([$binary, '--version'], outfunc => $code); };
09b11429 1205 warn $@ if $@;
1e3baf05 1206
1476b99f 1207 return $kvm_user_version->{$binary};
1e3baf05
DM
1208
1209}
4df98f2f
TL
1210my sub extract_version {
1211 my ($machine_type, $version) = @_;
1212 $version = kvm_user_version() if !defined($version);
8eb73377 1213 return PVE::QemuServer::Machine::extract_version($machine_type, $version)
4df98f2f 1214}
1e3baf05 1215
db70021b
TL
1216sub kernel_has_vhost_net {
1217 return -c '/dev/vhost-net';
1218}
1e3baf05 1219
1e3baf05
DM
1220sub option_exists {
1221 my $key = shift;
1222 return defined($confdesc->{$key});
19672434 1223}
1e3baf05 1224
1e3baf05 1225my $cdrom_path;
1e3baf05
DM
1226sub get_cdrom_path {
1227
259470ee 1228 return $cdrom_path if defined($cdrom_path);
1e3baf05 1229
c3d15108
TL
1230 $cdrom_path = first { -l $_ } map { "/dev/cdrom$_" } ('', '1', '2');
1231
1232 if (!defined($cdrom_path)) {
490b7308
SS
1233 log_warn("no physical CD-ROM available, ignoring");
1234 $cdrom_path = '';
1235 }
259470ee
SS
1236
1237 return $cdrom_path;
1e3baf05
DM
1238}
1239
1240sub get_iso_path {
1241 my ($storecfg, $vmid, $cdrom) = @_;
1242
1243 if ($cdrom eq 'cdrom') {
1244 return get_cdrom_path();
1245 } elsif ($cdrom eq 'none') {
1246 return '';
1247 } elsif ($cdrom =~ m|^/|) {
1248 return $cdrom;
1249 } else {
6b64503e 1250 return PVE::Storage::path($storecfg, $cdrom);
1e3baf05
DM
1251 }
1252}
1253
1254# try to convert old style file names to volume IDs
1255sub filename_to_volume_id {
1256 my ($vmid, $file, $media) = @_;
1257
0c9a7596 1258 if (!($file eq 'none' || $file eq 'cdrom' ||
1e3baf05 1259 $file =~ m|^/dev/.+| || $file =~ m/^([^:]+):(.+)$/)) {
19672434 1260
d1c1af4b 1261 return if $file =~ m|/|;
19672434 1262
1e3baf05
DM
1263 if ($media && $media eq 'cdrom') {
1264 $file = "local:iso/$file";
1265 } else {
1266 $file = "local:$vmid/$file";
1267 }
1268 }
1269
1270 return $file;
1271}
1272
1273sub verify_media_type {
1274 my ($opt, $vtype, $media) = @_;
1275
1276 return if !$media;
1277
1278 my $etype;
1279 if ($media eq 'disk') {
a125592c 1280 $etype = 'images';
1e3baf05
DM
1281 } elsif ($media eq 'cdrom') {
1282 $etype = 'iso';
1283 } else {
1284 die "internal error";
1285 }
1286
1287 return if ($vtype eq $etype);
19672434 1288
1e3baf05
DM
1289 raise_param_exc({ $opt => "unexpected media type ($vtype != $etype)" });
1290}
1291
1292sub cleanup_drive_path {
1293 my ($opt, $storecfg, $drive) = @_;
1294
1295 # try to convert filesystem paths to volume IDs
1296
1297 if (($drive->{file} !~ m/^(cdrom|none)$/) &&
1298 ($drive->{file} !~ m|^/dev/.+|) &&
1299 ($drive->{file} !~ m/^([^:]+):(.+)$/) &&
19672434 1300 ($drive->{file} !~ m/^\d+$/)) {
1e3baf05 1301 my ($vtype, $volid) = PVE::Storage::path_to_volume_id($storecfg, $drive->{file});
4df98f2f
TL
1302 raise_param_exc({ $opt => "unable to associate path '$drive->{file}' to any storage"})
1303 if !$vtype;
1e3baf05
DM
1304 $drive->{media} = 'cdrom' if !$drive->{media} && $vtype eq 'iso';
1305 verify_media_type($opt, $vtype, $drive->{media});
1306 $drive->{file} = $volid;
1307 }
1308
1309 $drive->{media} = 'cdrom' if !$drive->{media} && $drive->{file} =~ m/^(cdrom|none)$/;
1310}
1311
b3c2bdd1
DM
1312sub parse_hotplug_features {
1313 my ($data) = @_;
1314
1315 my $res = {};
1316
1317 return $res if $data eq '0';
a1b7d579 1318
b3c2bdd1
DM
1319 $data = $confdesc->{hotplug}->{default} if $data eq '1';
1320
45827685 1321 foreach my $feature (PVE::Tools::split_list($data)) {
94ec5e7c 1322 if ($feature =~ m/^(network|disk|cpu|memory|usb|cloudinit)$/) {
b3c2bdd1
DM
1323 $res->{$1} = 1;
1324 } else {
596a0a20 1325 die "invalid hotplug feature '$feature'\n";
b3c2bdd1
DM
1326 }
1327 }
1328 return $res;
1329}
1330
1331PVE::JSONSchema::register_format('pve-hotplug-features', \&pve_verify_hotplug_features);
1332sub pve_verify_hotplug_features {
1333 my ($value, $noerr) = @_;
1334
1335 return $value if parse_hotplug_features($value);
1336
d1c1af4b 1337 return if $noerr;
b3c2bdd1
DM
1338
1339 die "unable to parse hotplug option\n";
1340}
1341
28ef82d3
DM
1342sub scsi_inquiry {
1343 my($fh, $noerr) = @_;
1344
1345 my $SG_IO = 0x2285;
1346 my $SG_GET_VERSION_NUM = 0x2282;
1347
1348 my $versionbuf = "\x00" x 8;
1349 my $ret = ioctl($fh, $SG_GET_VERSION_NUM, $versionbuf);
1350 if (!$ret) {
1351 die "scsi ioctl SG_GET_VERSION_NUM failoed - $!\n" if !$noerr;
d1c1af4b 1352 return;
28ef82d3 1353 }
97d62eb7 1354 my $version = unpack("I", $versionbuf);
28ef82d3
DM
1355 if ($version < 30000) {
1356 die "scsi generic interface too old\n" if !$noerr;
d1c1af4b 1357 return;
28ef82d3 1358 }
97d62eb7 1359
28ef82d3
DM
1360 my $buf = "\x00" x 36;
1361 my $sensebuf = "\x00" x 8;
f334aa3e 1362 my $cmd = pack("C x3 C x1", 0x12, 36);
97d62eb7 1363
28ef82d3
DM
1364 # see /usr/include/scsi/sg.h
1365 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";
1366
f606d5bd
TL
1367 my $packet = pack(
1368 $sg_io_hdr_t, ord('S'), -3, length($cmd), length($sensebuf), 0, length($buf), $buf, $cmd, $sensebuf, 6000
1369 );
28ef82d3
DM
1370
1371 $ret = ioctl($fh, $SG_IO, $packet);
1372 if (!$ret) {
1373 die "scsi ioctl SG_IO failed - $!\n" if !$noerr;
d1c1af4b 1374 return;
28ef82d3 1375 }
97d62eb7 1376
28ef82d3
DM
1377 my @res = unpack($sg_io_hdr_t, $packet);
1378 if ($res[17] || $res[18]) {
1379 die "scsi ioctl SG_IO status error - $!\n" if !$noerr;
d1c1af4b 1380 return;
28ef82d3
DM
1381 }
1382
1383 my $res = {};
f606d5bd 1384 $res->@{qw(type removable vendor product revision)} = unpack("C C x6 A8 A16 A4", $buf);
28ef82d3 1385
f606d5bd
TL
1386 $res->{removable} = $res->{removable} & 128 ? 1 : 0;
1387 $res->{type} &= 0x1F;
09984754 1388
28ef82d3
DM
1389 return $res;
1390}
1391
1392sub path_is_scsi {
1393 my ($path) = @_;
1394
d1c1af4b 1395 my $fh = IO::File->new("+<$path") || return;
28ef82d3
DM
1396 my $res = scsi_inquiry($fh, 1);
1397 close($fh);
1398
1399 return $res;
1400}
1401
db656e5f 1402sub print_tabletdevice_full {
d559309f 1403 my ($conf, $arch) = @_;
b467f79a 1404
3392d6ca 1405 my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf);
db656e5f
DM
1406
1407 # we use uhci for old VMs because tablet driver was buggy in older qemu
d559309f 1408 my $usbbus;
2b938c7d 1409 if ($q35 || $arch eq 'aarch64') {
d559309f
WB
1410 $usbbus = 'ehci';
1411 } else {
1412 $usbbus = 'uhci';
1413 }
b467f79a 1414
db656e5f
DM
1415 return "usb-tablet,id=tablet,bus=$usbbus.0,port=1";
1416}
1417
d559309f 1418sub print_keyboarddevice_full {
6971c38e 1419 my ($conf, $arch) = @_;
d559309f 1420
d1c1af4b 1421 return if $arch ne 'aarch64';
d559309f
WB
1422
1423 return "usb-kbd,id=keyboard,bus=ehci.0,port=2";
1424}
1425
a183df68
TL
1426my sub get_drive_id {
1427 my ($drive) = @_;
1428 return "$drive->{interface}$drive->{index}";
1429}
1430
ca916ecc 1431sub print_drivedevice_full {
d559309f 1432 my ($storecfg, $conf, $vmid, $drive, $bridges, $arch, $machine_type) = @_;
ca916ecc
DA
1433
1434 my $device = '';
1435 my $maxdev = 0;
19672434 1436
a183df68 1437 my $drive_id = get_drive_id($drive);
ca916ecc 1438 if ($drive->{interface} eq 'virtio') {
4df98f2f
TL
1439 my $pciaddr = print_pci_addr("$drive_id", $bridges, $arch, $machine_type);
1440 $device = "virtio-blk-pci,drive=drive-$drive_id,id=${drive_id}${pciaddr}";
1441 $device .= ",iothread=iothread-$drive_id" if $drive->{iothread};
2ed36a41 1442 } elsif ($drive->{interface} eq 'scsi') {
6731a4cf 1443
ee034f5c 1444 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $drive);
2ed36a41
DM
1445 my $unit = $drive->{index} % $maxdev;
1446 my $devicetype = 'hd';
69bcf246
WB
1447 my $path = '';
1448 if (drive_is_cdrom($drive)) {
1449 $devicetype = 'cd';
29b19529 1450 } else {
69bcf246
WB
1451 if ($drive->{file} =~ m|^/|) {
1452 $path = $drive->{file};
1453 if (my $info = path_is_scsi($path)) {
8e3c33ab 1454 if ($info->{type} == 0 && $drive->{scsiblock}) {
69bcf246
WB
1455 $devicetype = 'block';
1456 } elsif ($info->{type} == 1) { # tape
1457 $devicetype = 'generic';
1458 }
1459 }
1460 } else {
1461 $path = PVE::Storage::path($storecfg, $drive->{file});
1462 }
1463
a034e3d6 1464 # for compatibility only, we prefer scsi-hd (#2408, #2355, #2380)
4df98f2f 1465 my $version = extract_version($machine_type, kvm_user_version());
a034e3d6 1466 if ($path =~ m/^iscsi\:\/\// &&
2ea5fb7e 1467 !min_version($version, 4, 1)) {
69bcf246
WB
1468 $devicetype = 'generic';
1469 }
1470 }
1471
ef88eaaa 1472 if (!$conf->{scsihw} || $conf->{scsihw} =~ m/^lsi/ || $conf->{scsihw} eq 'pvscsi') {
4df98f2f 1473 $device = "scsi-$devicetype,bus=$controller_prefix$controller.0,scsi-id=$unit";
69bcf246 1474 } else {
4df98f2f
TL
1475 $device = "scsi-$devicetype,bus=$controller_prefix$controller.0,channel=0,scsi-id=0"
1476 .",lun=$drive->{index}";
69bcf246 1477 }
4df98f2f 1478 $device .= ",drive=drive-$drive_id,id=$drive_id";
cdd20088 1479
6c875f9f
NC
1480 if ($drive->{ssd} && ($devicetype eq 'block' || $devicetype eq 'hd')) {
1481 $device .= ",rotation_rate=1";
1482 }
e741c516 1483 $device .= ",wwn=$drive->{wwn}" if $drive->{wwn};
6c875f9f
NC
1484
1485 } elsif ($drive->{interface} eq 'ide' || $drive->{interface} eq 'sata') {
e0fd2b2f 1486 my $maxdev = ($drive->{interface} eq 'sata') ? $PVE::QemuServer::Drive::MAX_SATA_DISKS : 2;
2ed36a41
DM
1487 my $controller = int($drive->{index} / $maxdev);
1488 my $unit = $drive->{index} % $maxdev;
b155086b
FE
1489
1490 # machine type q35 only supports unit=0 for IDE rather than 2 units. This wasn't handled
1491 # correctly before, so e.g. index=2 was mapped to controller=1,unit=0 rather than
1492 # controller=2,unit=0. Note that odd indices never worked, as they would be mapped to
1493 # unit=1, so to keep backwards compat for migration, it suffices to keep even ones as they
1494 # were before. Move odd ones up by 2 where they don't clash.
1495 if (PVE::QemuServer::Machine::machine_type_is_q35($conf) && $drive->{interface} eq 'ide') {
1496 $controller += 2 * ($unit % 2);
1497 $unit = 0;
1498 }
1499
2ed36a41
DM
1500 my $devicetype = ($drive->{media} && $drive->{media} eq 'cdrom') ? "cd" : "hd";
1501
6c875f9f
NC
1502 $device = "ide-$devicetype";
1503 if ($drive->{interface} eq 'ide') {
1504 $device .= ",bus=ide.$controller,unit=$unit";
1505 } else {
1506 $device .= ",bus=ahci$controller.$unit";
1507 }
4df98f2f 1508 $device .= ",drive=drive-$drive_id,id=$drive_id";
6c875f9f
NC
1509
1510 if ($devicetype eq 'hd') {
1511 if (my $model = $drive->{model}) {
1512 $model = URI::Escape::uri_unescape($model);
1513 $device .= ",model=$model";
1514 }
1515 if ($drive->{ssd}) {
1516 $device .= ",rotation_rate=1";
1517 }
0f2812c2 1518 }
e741c516 1519 $device .= ",wwn=$drive->{wwn}" if $drive->{wwn};
2ed36a41
DM
1520 } elsif ($drive->{interface} eq 'usb') {
1521 die "implement me";
1522 # -device ide-drive,bus=ide.1,unit=0,drive=drive-ide0-1-0,id=ide0-1-0
1523 } else {
1524 die "unsupported interface type";
ca916ecc
DA
1525 }
1526
3b408e82
DM
1527 $device .= ",bootindex=$drive->{bootindex}" if $drive->{bootindex};
1528
a70e7e6c
TL
1529 if (my $serial = $drive->{serial}) {
1530 $serial = URI::Escape::uri_unescape($serial);
1531 $device .= ",serial=$serial";
1532 }
1533
1534
ca916ecc
DA
1535 return $device;
1536}
1537
15b21acc 1538sub get_initiator_name {
46f58b5f 1539 my $initiator;
15b21acc 1540
d1c1af4b 1541 my $fh = IO::File->new('/etc/iscsi/initiatorname.iscsi') || return;
46f58b5f
DM
1542 while (defined(my $line = <$fh>)) {
1543 next if $line !~ m/^\s*InitiatorName\s*=\s*([\.\-:\w]+)/;
15b21acc
MR
1544 $initiator = $1;
1545 last;
1546 }
46f58b5f
DM
1547 $fh->close();
1548
15b21acc
MR
1549 return $initiator;
1550}
1551
eec9f9fe
FE
1552my sub storage_allows_io_uring_default {
1553 my ($scfg, $cache_direct) = @_;
1554
1555 # io_uring with cache mode writeback or writethrough on krbd will hang...
1556 return if $scfg && $scfg->{type} eq 'rbd' && $scfg->{krbd} && !$cache_direct;
1557
1558 # io_uring with cache mode writeback or writethrough on LVM will hang, without cache only
1559 # sometimes, just plain disable...
1560 return if $scfg && $scfg->{type} eq 'lvm';
1561
1562 # io_uring causes problems when used with CIFS since kernel 5.15
1563 # Some discussion: https://www.spinics.net/lists/linux-cifs/msg26734.html
1564 return if $scfg && $scfg->{type} eq 'cifs';
1565
1566 return 1;
1567}
1568
b7071d6c
FE
1569my sub drive_uses_cache_direct {
1570 my ($drive, $scfg) = @_;
1571
1572 my $cache_direct = 0;
1573
1574 if (my $cache = $drive->{cache}) {
1575 $cache_direct = $cache =~ /^(?:off|none|directsync)$/;
1576 } elsif (!drive_is_cdrom($drive) && !($scfg && $scfg->{type} eq 'btrfs' && !$scfg->{nocow})) {
1577 $cache_direct = 1;
1578 }
1579
1580 return $cache_direct;
1581}
1582
776c5f50 1583sub print_drive_commandline_full {
6d5673c3 1584 my ($storecfg, $vmid, $drive, $pbs_name, $io_uring) = @_;
1e3baf05 1585
d81f0f09
DM
1586 my $path;
1587 my $volid = $drive->{file};
5921764c 1588 my $format = $drive->{format};
a183df68 1589 my $drive_id = get_drive_id($drive);
370b05e7 1590
0fe779a6
WB
1591 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1592 my $scfg = $storeid ? PVE::Storage::storage_config($storecfg, $storeid) : undef;
1593
d81f0f09
DM
1594 if (drive_is_cdrom($drive)) {
1595 $path = get_iso_path($storecfg, $vmid, $volid);
a183df68 1596 die "$drive_id: cannot back cdrom drive with PBS snapshot\n" if $pbs_name;
d81f0f09 1597 } else {
d81f0f09
DM
1598 if ($storeid) {
1599 $path = PVE::Storage::path($storecfg, $volid);
5921764c 1600 $format //= qemu_img_format($scfg, $volname);
d81f0f09
DM
1601 } else {
1602 $path = $volid;
5921764c 1603 $format //= "raw";
d81f0f09
DM
1604 }
1605 }
1606
5921764c
SR
1607 my $is_rbd = $path =~ m/^rbd:/;
1608
1e3baf05 1609 my $opts = '';
5921764c 1610 my @qemu_drive_options = qw(heads secs cyls trans media cache rerror werror aio discard);
1e3baf05 1611 foreach my $o (@qemu_drive_options) {
5fc74861 1612 $opts .= ",$o=$drive->{$o}" if defined($drive->{$o});
19672434 1613 }
8a267708
DC
1614
1615 # snapshot only accepts on|off
1616 if (defined($drive->{snapshot})) {
1617 my $v = $drive->{snapshot} ? 'on' : 'off';
1618 $opts .= ",snapshot=$v";
1619 }
1620
1f91f7b4
TL
1621 if (defined($drive->{ro})) { # ro maps to QEMUs `readonly`, which accepts `on` or `off` only
1622 $opts .= ",readonly=" . ($drive->{ro} ? 'on' : 'off');
12e1d472
DC
1623 }
1624
fb8e95a2
WB
1625 foreach my $type (['', '-total'], [_rd => '-read'], [_wr => '-write']) {
1626 my ($dir, $qmpname) = @$type;
1627 if (my $v = $drive->{"mbps$dir"}) {
1628 $opts .= ",throttling.bps$qmpname=".int($v*1024*1024);
1629 }
1630 if (my $v = $drive->{"mbps${dir}_max"}) {
1631 $opts .= ",throttling.bps$qmpname-max=".int($v*1024*1024);
1632 }
1633 if (my $v = $drive->{"bps${dir}_max_length"}) {
1634 $opts .= ",throttling.bps$qmpname-max-length=$v";
1635 }
1636 if (my $v = $drive->{"iops${dir}"}) {
1637 $opts .= ",throttling.iops$qmpname=$v";
1638 }
1639 if (my $v = $drive->{"iops${dir}_max"}) {
8aca1654 1640 $opts .= ",throttling.iops$qmpname-max=$v";
fb8e95a2
WB
1641 }
1642 if (my $v = $drive->{"iops${dir}_max_length"}) {
8aca1654 1643 $opts .= ",throttling.iops$qmpname-max-length=$v";
fb8e95a2
WB
1644 }
1645 }
1646
5921764c
SR
1647 if ($pbs_name) {
1648 $format = "rbd" if $is_rbd;
a183df68
TL
1649 die "$drive_id: Proxmox Backup Server backed drive cannot auto-detect the format\n"
1650 if !$format;
5921764c
SR
1651 $opts .= ",format=alloc-track,file.driver=$format";
1652 } elsif ($format) {
1653 $opts .= ",format=$format";
1654 }
d81f0f09 1655
b7071d6c 1656 my $cache_direct = drive_uses_cache_direct($drive, $scfg);
b2ee900e 1657
b7071d6c 1658 $opts .= ",cache=none" if !$drive->{cache} && $cache_direct;
b2ee900e 1659
b2ee900e 1660 if (!$drive->{aio}) {
eec9f9fe 1661 if ($io_uring && storage_allows_io_uring_default($scfg, $cache_direct)) {
6d5673c3
SR
1662 # io_uring supports all cache modes
1663 $opts .= ",aio=io_uring";
b2ee900e 1664 } else {
6d5673c3
SR
1665 # aio native works only with O_DIRECT
1666 if($cache_direct) {
1667 $opts .= ",aio=native";
1668 } else {
1669 $opts .= ",aio=threads";
1670 }
b2ee900e
WB
1671 }
1672 }
11490cf2 1673
6e47c3b4
WB
1674 if (!drive_is_cdrom($drive)) {
1675 my $detectzeroes;
7d4e30f3 1676 if (defined($drive->{detect_zeroes}) && !$drive->{detect_zeroes}) {
6e47c3b4
WB
1677 $detectzeroes = 'off';
1678 } elsif ($drive->{discard}) {
1679 $detectzeroes = $drive->{discard} eq 'on' ? 'unmap' : 'on';
1680 } else {
1681 # This used to be our default with discard not being specified:
1682 $detectzeroes = 'on';
1683 }
5921764c
SR
1684
1685 # note: 'detect-zeroes' works per blockdev and we want it to persist
1686 # after the alloc-track is removed, so put it on 'file' directly
1687 my $dz_param = $pbs_name ? "file.detect-zeroes" : "detect-zeroes";
1688 $opts .= ",$dz_param=$detectzeroes" if $detectzeroes;
6e47c3b4 1689 }
f1e05305 1690
5921764c
SR
1691 if ($pbs_name) {
1692 $opts .= ",backing=$pbs_name";
1693 $opts .= ",auto-remove=on";
1694 }
1695
1696 # my $file_param = $pbs_name ? "file.file.filename" : "file";
1697 my $file_param = "file";
1698 if ($pbs_name) {
1699 # non-rbd drivers require the underlying file to be a seperate block
1700 # node, so add a second .file indirection
1701 $file_param .= ".file" if !$is_rbd;
1702 $file_param .= ".filename";
1703 }
1704 my $pathinfo = $path ? "$file_param=$path," : '';
1e3baf05 1705
3ebfcc86 1706 return "${pathinfo}if=none,id=drive-$drive->{interface}$drive->{index}$opts";
1e3baf05
DM
1707}
1708
5921764c
SR
1709sub print_pbs_blockdev {
1710 my ($pbs_conf, $pbs_name) = @_;
1711 my $blockdev = "driver=pbs,node-name=$pbs_name,read-only=on";
1712 $blockdev .= ",repository=$pbs_conf->{repository}";
2dda626d 1713 $blockdev .= ",namespace=$pbs_conf->{namespace}" if $pbs_conf->{namespace};
5921764c
SR
1714 $blockdev .= ",snapshot=$pbs_conf->{snapshot}";
1715 $blockdev .= ",archive=$pbs_conf->{archive}";
1716 $blockdev .= ",keyfile=$pbs_conf->{keyfile}" if $pbs_conf->{keyfile};
1717 return $blockdev;
1718}
1719
cc4d6182 1720sub print_netdevice_full {
0c03a390 1721 my ($vmid, $conf, $net, $netid, $bridges, $use_old_bios_files, $arch, $machine_type, $machine_version) = @_;
cc4d6182 1722
cc4d6182
DA
1723 my $device = $net->{model};
1724 if ($net->{model} eq 'virtio') {
1725 $device = 'virtio-net-pci';
1726 };
1727
d559309f 1728 my $pciaddr = print_pci_addr("$netid", $bridges, $arch, $machine_type);
5e2068d2 1729 my $tmpstr = "$device,mac=$net->{macaddr},netdev=$netid$pciaddr,id=$netid";
a9410357 1730 if ($net->{queues} && $net->{queues} > 1 && $net->{model} eq 'virtio'){
4df98f2f
TL
1731 # Consider we have N queues, the number of vectors needed is 2 * N + 2, i.e., one per in
1732 # and out of each queue plus one config interrupt and control vector queue
a9410357
AD
1733 my $vectors = $net->{queues} * 2 + 2;
1734 $tmpstr .= ",vectors=$vectors,mq=on";
0c03a390
AD
1735 if (min_version($machine_version, 7, 1)) {
1736 $tmpstr .= ",packed=on";
1737 }
a9410357 1738 }
620d6b32
AD
1739
1740 if (min_version($machine_version, 7, 1) && $net->{model} eq 'virtio'){
089aed81 1741 $tmpstr .= ",rx_queue_size=1024,tx_queue_size=256";
620d6b32
AD
1742 }
1743
cc4d6182 1744 $tmpstr .= ",bootindex=$net->{bootindex}" if $net->{bootindex} ;
ba9e1000 1745
0530177b
TL
1746 if (my $mtu = $net->{mtu}) {
1747 if ($net->{model} eq 'virtio' && $net->{bridge}) {
1748 my $bridge_mtu = PVE::Network::read_bridge_mtu($net->{bridge});
1749 if ($mtu == 1) {
1750 $mtu = $bridge_mtu;
1751 } elsif ($mtu < 576) {
1752 die "netdev $netid: MTU '$mtu' is smaller than the IP minimum MTU '576'\n";
1753 } elsif ($mtu > $bridge_mtu) {
1754 die "netdev $netid: MTU '$mtu' is bigger than the bridge MTU '$bridge_mtu'\n";
1755 }
1756 $tmpstr .= ",host_mtu=$mtu";
1757 } else {
1758 warn "WARN: netdev $netid: ignoring MTU '$mtu', not using VirtIO or no bridge configured.\n";
61a14cde 1759 }
61a14cde
AD
1760 }
1761
ba9e1000
DM
1762 if ($use_old_bios_files) {
1763 my $romfile;
1764 if ($device eq 'virtio-net-pci') {
1765 $romfile = 'pxe-virtio.rom';
1766 } elsif ($device eq 'e1000') {
1767 $romfile = 'pxe-e1000.rom';
e83dd50a
TL
1768 } elsif ($device eq 'e1000e') {
1769 $romfile = 'pxe-e1000e.rom';
ba9e1000
DM
1770 } elsif ($device eq 'ne2k') {
1771 $romfile = 'pxe-ne2k_pci.rom';
1772 } elsif ($device eq 'pcnet') {
1773 $romfile = 'pxe-pcnet.rom';
1774 } elsif ($device eq 'rtl8139') {
1775 $romfile = 'pxe-rtl8139.rom';
1776 }
1777 $tmpstr .= ",romfile=$romfile" if $romfile;
1778 }
1779
cc4d6182
DA
1780 return $tmpstr;
1781}
1782
1783sub print_netdev_full {
d559309f 1784 my ($vmid, $conf, $arch, $net, $netid, $hotplug) = @_;
cc4d6182
DA
1785
1786 my $i = '';
1787 if ($netid =~ m/^net(\d+)$/) {
1788 $i = int($1);
1789 }
1790
1791 die "got strange net id '$i'\n" if $i >= ${MAX_NETS};
1792
1793 my $ifname = "tap${vmid}i$i";
1794
1795 # kvm uses TUNSETIFF ioctl, and that limits ifname length
1796 die "interface name '$ifname' is too long (max 15 character)\n"
1797 if length($ifname) >= 16;
1798
1799 my $vhostparam = '';
6f0cb675 1800 if (is_native($arch)) {
db70021b 1801 $vhostparam = ',vhost=on' if kernel_has_vhost_net() && $net->{model} eq 'virtio';
6f0cb675 1802 }
cc4d6182
DA
1803
1804 my $vmname = $conf->{name} || "vm$vmid";
1805
a9410357 1806 my $netdev = "";
208ba94e 1807 my $script = $hotplug ? "pve-bridge-hotplug" : "pve-bridge";
a9410357 1808
cc4d6182 1809 if ($net->{bridge}) {
4df98f2f
TL
1810 $netdev = "type=tap,id=$netid,ifname=${ifname},script=/var/lib/qemu-server/$script"
1811 .",downscript=/var/lib/qemu-server/pve-bridgedown$vhostparam";
cc4d6182 1812 } else {
a9410357 1813 $netdev = "type=user,id=$netid,hostname=$vmname";
cc4d6182 1814 }
a9410357
AD
1815
1816 $netdev .= ",queues=$net->{queues}" if ($net->{queues} && $net->{model} eq 'virtio');
1817
1818 return $netdev;
cc4d6182 1819}
1e3baf05 1820
55655ebc
DC
1821my $vga_map = {
1822 'cirrus' => 'cirrus-vga',
1823 'std' => 'VGA',
1824 'vmware' => 'vmware-svga',
1825 'virtio' => 'virtio-vga',
6f070e39 1826 'virtio-gl' => 'virtio-vga-gl',
55655ebc
DC
1827};
1828
1829sub print_vga_device {
2ea5fb7e 1830 my ($conf, $vga, $arch, $machine_version, $machine, $id, $qxlnum, $bridges) = @_;
55655ebc
DC
1831
1832 my $type = $vga_map->{$vga->{type}};
86c9fafe 1833 if ($arch eq 'aarch64' && defined($type) && $type eq 'virtio-vga') {
d559309f
WB
1834 $type = 'virtio-gpu';
1835 }
55655ebc 1836 my $vgamem_mb = $vga->{memory};
6021c7a5
AL
1837
1838 my $max_outputs = '';
55655ebc
DC
1839 if ($qxlnum) {
1840 $type = $id ? 'qxl' : 'qxl-vga';
6021c7a5 1841
c5a4c92c 1842 if (!$conf->{ostype} || $conf->{ostype} =~ m/^(?:l\d\d)|(?:other)$/) {
6021c7a5 1843 # set max outputs so linux can have up to 4 qxl displays with one device
2ea5fb7e 1844 if (min_version($machine_version, 4, 1)) {
9e8976ea
TL
1845 $max_outputs = ",max_outputs=4";
1846 }
6021c7a5 1847 }
55655ebc 1848 }
6021c7a5 1849
55655ebc
DC
1850 die "no devicetype for $vga->{type}\n" if !$type;
1851
1852 my $memory = "";
1853 if ($vgamem_mb) {
6f070e39 1854 if ($vga->{type} =~ /^virtio/) {
55655ebc
DC
1855 my $bytes = PVE::Tools::convert_size($vgamem_mb, "mb" => "b");
1856 $memory = ",max_hostmem=$bytes";
1857 } elsif ($qxlnum) {
1858 # from https://www.spice-space.org/multiple-monitors.html
1859 $memory = ",vgamem_mb=$vga->{memory}";
1860 my $ram = $vgamem_mb * 4;
1861 my $vram = $vgamem_mb * 2;
1862 $memory .= ",ram_size_mb=$ram,vram_size_mb=$vram";
1863 } else {
1864 $memory = ",vgamem_mb=$vga->{memory}";
1865 }
1866 } elsif ($qxlnum && $id) {
1867 $memory = ",ram_size=67108864,vram_size=33554432";
1868 }
1869
789fe8e8
AL
1870 my $edidoff = "";
1871 if ($type eq 'VGA' && windows_version($conf->{ostype})) {
b5d32c6b 1872 $edidoff=",edid=off" if (!defined($conf->{bios}) || $conf->{bios} ne 'ovmf');
789fe8e8
AL
1873 }
1874
3392d6ca 1875 my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf);
55655ebc
DC
1876 my $vgaid = "vga" . ($id // '');
1877 my $pciaddr;
1878 if ($q35 && $vgaid eq 'vga') {
daadd5a4 1879 # the first display uses pcie.0 bus on q35 machines
d559309f 1880 $pciaddr = print_pcie_addr($vgaid, $bridges, $arch, $machine);
55655ebc 1881 } else {
d559309f 1882 $pciaddr = print_pci_addr($vgaid, $bridges, $arch, $machine);
55655ebc
DC
1883 }
1884
9f979d9f 1885 if ($vga->{type} eq 'virtio-gl') {
8884a8bf
TL
1886 my $base = '/usr/lib/x86_64-linux-gnu/lib';
1887 die "missing libraries for '$vga->{type}' detected! Please install 'libgl1' and 'libegl1'\n"
1888 if !-e "${base}EGL.so.1" || !-e "${base}GL.so.1";
9f979d9f 1889
8884a8bf
TL
1890 die "no DRM render node detected (/dev/dri/renderD*), no GPU? - needed for '$vga->{type}' display\n"
1891 if !PVE::Tools::dir_glob_regex('/dev/dri/', "renderD.*");
9f979d9f
SI
1892 }
1893
789fe8e8 1894 return "$type,id=${vgaid}${memory}${max_outputs}${pciaddr}${edidoff}";
55655ebc
DC
1895}
1896
1e3baf05
DM
1897# netX: e1000=XX:XX:XX:XX:XX:XX,bridge=vmbr0,rate=<mbps>
1898sub parse_net {
4ddd2ca2 1899 my ($data, $disable_mac_autogen) = @_;
1e3baf05 1900
4df98f2f 1901 my $res = eval { parse_property_string($net_fmt, $data) };
cd9c34d1
WB
1902 if ($@) {
1903 warn $@;
d1c1af4b 1904 return;
1e3baf05 1905 }
4ddd2ca2 1906 if (!defined($res->{macaddr}) && !$disable_mac_autogen) {
b5b99790
WB
1907 my $dc = PVE::Cluster::cfs_read_file('datacenter.cfg');
1908 $res->{macaddr} = PVE::Tools::random_ether_addr($dc->{mac_prefix});
1909 }
0c9a7596
AD
1910 return $res;
1911}
1912
1913# ipconfigX ip=cidr,gw=ip,ip6=cidr,gw6=ip
1914sub parse_ipconfig {
1915 my ($data) = @_;
1916
4df98f2f 1917 my $res = eval { parse_property_string($ipconfig_fmt, $data) };
0c9a7596
AD
1918 if ($@) {
1919 warn $@;
d1c1af4b 1920 return;
0c9a7596
AD
1921 }
1922
1923 if ($res->{gw} && !$res->{ip}) {
1924 warn 'gateway specified without specifying an IP address';
d1c1af4b 1925 return;
0c9a7596
AD
1926 }
1927 if ($res->{gw6} && !$res->{ip6}) {
1928 warn 'IPv6 gateway specified without specifying an IPv6 address';
d1c1af4b 1929 return;
0c9a7596
AD
1930 }
1931 if ($res->{gw} && $res->{ip} eq 'dhcp') {
1932 warn 'gateway specified together with DHCP';
d1c1af4b 1933 return;
0c9a7596
AD
1934 }
1935 if ($res->{gw6} && $res->{ip6} !~ /^$IPV6RE/) {
1936 # gw6 + auto/dhcp
1937 warn "IPv6 gateway specified together with $res->{ip6} address";
d1c1af4b 1938 return;
0c9a7596
AD
1939 }
1940
1941 if (!$res->{ip} && !$res->{ip6}) {
1942 return { ip => 'dhcp', ip6 => 'dhcp' };
1943 }
1944
1e3baf05
DM
1945 return $res;
1946}
1947
1948sub print_net {
1949 my $net = shift;
1950
cd9c34d1 1951 return PVE::JSONSchema::print_property_string($net, $net_fmt);
1e3baf05
DM
1952}
1953
1954sub add_random_macs {
1955 my ($settings) = @_;
1956
1957 foreach my $opt (keys %$settings) {
1958 next if $opt !~ m/^net(\d+)$/;
1959 my $net = parse_net($settings->{$opt});
1960 next if !$net;
1961 $settings->{$opt} = print_net($net);
1962 }
1963}
1964
055d554d
DM
1965sub vm_is_volid_owner {
1966 my ($storecfg, $vmid, $volid) = @_;
1967
1968 if ($volid !~ m|^/|) {
1969 my ($path, $owner);
1970 eval { ($path, $owner) = PVE::Storage::path($storecfg, $volid); };
1971 if ($owner && ($owner == $vmid)) {
1972 return 1;
1973 }
1974 }
1975
d1c1af4b 1976 return;
055d554d
DM
1977}
1978
055d554d
DM
1979sub vmconfig_register_unused_drive {
1980 my ($storecfg, $vmid, $conf, $drive) = @_;
1981
2d9ddec5
WB
1982 if (drive_is_cloudinit($drive)) {
1983 eval { PVE::Storage::vdisk_free($storecfg, $drive->{file}) };
1984 warn $@ if $@;
95a5135d 1985 delete $conf->{cloudinit};
2d9ddec5 1986 } elsif (!drive_is_cdrom($drive)) {
055d554d
DM
1987 my $volid = $drive->{file};
1988 if (vm_is_volid_owner($storecfg, $vmid, $volid)) {
8793d495 1989 PVE::QemuConfig->add_unused_volume($conf, $volid, $vmid);
055d554d
DM
1990 }
1991 }
1992}
1993
1f30ac3a 1994# smbios: [manufacturer=str][,product=str][,version=str][,serial=str][,uuid=uuid][,sku=str][,family=str][,base64=bool]
ff6ffe20 1995my $smbios1_fmt = {
bd27e851
WB
1996 uuid => {
1997 type => 'string',
1998 pattern => '[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}',
1999 format_description => 'UUID',
52261945 2000 description => "Set SMBIOS1 UUID.",
bd27e851
WB
2001 optional => 1,
2002 },
2003 version => {
2004 type => 'string',
1f30ac3a
CE
2005 pattern => '[A-Za-z0-9+\/]+={0,2}',
2006 format_description => 'Base64 encoded string',
52261945 2007 description => "Set SMBIOS1 version.",
bd27e851
WB
2008 optional => 1,
2009 },
2010 serial => {
2011 type => 'string',
1f30ac3a
CE
2012 pattern => '[A-Za-z0-9+\/]+={0,2}',
2013 format_description => 'Base64 encoded string',
52261945 2014 description => "Set SMBIOS1 serial number.",
bd27e851
WB
2015 optional => 1,
2016 },
2017 manufacturer => {
2018 type => 'string',
1f30ac3a
CE
2019 pattern => '[A-Za-z0-9+\/]+={0,2}',
2020 format_description => 'Base64 encoded string',
52261945 2021 description => "Set SMBIOS1 manufacturer.",
bd27e851
WB
2022 optional => 1,
2023 },
2024 product => {
2025 type => 'string',
1f30ac3a
CE
2026 pattern => '[A-Za-z0-9+\/]+={0,2}',
2027 format_description => 'Base64 encoded string',
52261945 2028 description => "Set SMBIOS1 product ID.",
bd27e851
WB
2029 optional => 1,
2030 },
2031 sku => {
2032 type => 'string',
1f30ac3a
CE
2033 pattern => '[A-Za-z0-9+\/]+={0,2}',
2034 format_description => 'Base64 encoded string',
52261945 2035 description => "Set SMBIOS1 SKU string.",
bd27e851
WB
2036 optional => 1,
2037 },
2038 family => {
2039 type => 'string',
1f30ac3a
CE
2040 pattern => '[A-Za-z0-9+\/]+={0,2}',
2041 format_description => 'Base64 encoded string',
52261945 2042 description => "Set SMBIOS1 family string.",
bd27e851
WB
2043 optional => 1,
2044 },
1f30ac3a
CE
2045 base64 => {
2046 type => 'boolean',
2047 description => 'Flag to indicate that the SMBIOS values are base64 encoded',
2048 optional => 1,
2049 },
2796e7d5
DM
2050};
2051
2796e7d5
DM
2052sub parse_smbios1 {
2053 my ($data) = @_;
2054
4df98f2f 2055 my $res = eval { parse_property_string($smbios1_fmt, $data) };
bd27e851 2056 warn $@ if $@;
2796e7d5
DM
2057 return $res;
2058}
2059
cd11416f
DM
2060sub print_smbios1 {
2061 my ($smbios1) = @_;
ff6ffe20 2062 return PVE::JSONSchema::print_property_string($smbios1, $smbios1_fmt);
cd11416f
DM
2063}
2064
ff6ffe20 2065PVE::JSONSchema::register_format('pve-qm-smbios1', $smbios1_fmt);
2796e7d5 2066
0ea9541d
DM
2067sub parse_watchdog {
2068 my ($value) = @_;
2069
d1c1af4b 2070 return if !$value;
0ea9541d 2071
4df98f2f 2072 my $res = eval { parse_property_string($watchdog_fmt, $value) };
ec3582b5 2073 warn $@ if $@;
0ea9541d
DM
2074 return $res;
2075}
2076
9d66b397 2077sub parse_guest_agent {
a2af1bbe 2078 my ($conf) = @_;
9d66b397 2079
a2af1bbe 2080 return {} if !defined($conf->{agent});
9d66b397 2081
a2af1bbe 2082 my $res = eval { parse_property_string($agent_fmt, $conf->{agent}) };
9d66b397
SI
2083 warn $@ if $@;
2084
2085 # if the agent is disabled ignore the other potentially set properties
2086 return {} if !$res->{enabled};
2087 return $res;
2088}
2089
a2af1bbe
TL
2090sub get_qga_key {
2091 my ($conf, $key) = @_;
2092 return undef if !defined($conf->{agent});
2093
2094 my $agent = parse_guest_agent($conf);
2095 return $agent->{$key};
2096}
2097
55655ebc
DC
2098sub parse_vga {
2099 my ($value) = @_;
2100
2101 return {} if !$value;
4df98f2f 2102 my $res = eval { parse_property_string($vga_fmt, $value) };
55655ebc
DC
2103 warn $@ if $@;
2104 return $res;
2105}
2106
2cf61f33
SR
2107sub parse_rng {
2108 my ($value) = @_;
2109
d1c1af4b 2110 return if !$value;
2cf61f33 2111
4df98f2f 2112 my $res = eval { parse_property_string($rng_fmt, $value) };
2cf61f33
SR
2113 warn $@ if $@;
2114 return $res;
2115}
2116
26b443c8
TL
2117sub parse_meta_info {
2118 my ($value) = @_;
2119
2120 return if !$value;
2121
2122 my $res = eval { parse_property_string($meta_info_fmt, $value) };
2123 warn $@ if $@;
2124 return $res;
2125}
2126
2127sub new_meta_info_string {
2128 my () = @_; # for now do not allow to override any value
2129
2130 return PVE::JSONSchema::print_property_string(
2131 {
af2a1a1c 2132 'creation-qemu' => kvm_user_version(),
26b443c8
TL
2133 ctime => "". int(time()),
2134 },
2135 $meta_info_fmt
2136 );
2137}
2138
cc181036
TL
2139sub qemu_created_version_fixups {
2140 my ($conf, $forcemachine, $kvmver) = @_;
2141
2142 my $meta = parse_meta_info($conf->{meta}) // {};
2143 my $forced_vers = PVE::QemuServer::Machine::extract_version($forcemachine);
2144
2145 # check if we need to apply some handling for VMs that always use the latest machine version but
2146 # had a machine version transition happen that affected HW such that, e.g., an OS config change
2147 # would be required (we do not want to pin machine version for non-windows OS type)
2148 if (
2149 (!defined($conf->{machine}) || $conf->{machine} =~ m/^(?:pc|q35|virt)$/) # non-versioned machine
2150 && (!defined($meta->{'creation-qemu'}) || !min_version($meta->{'creation-qemu'}, 6, 1)) # created before 6.1
2151 && (!$forced_vers || min_version($forced_vers, 6, 1)) # handle snapshot-rollback/migrations
2152 && min_version($kvmver, 6, 1) # only need to apply the change since 6.1
2153 ) {
2154 my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf);
2155 if ($q35 && $conf->{ostype} && $conf->{ostype} eq 'l26') {
2156 # this changed to default-on in Q 6.1 for q35 machines, it will mess with PCI slot view
2157 # and thus with the predictable interface naming of systemd
2158 return ['-global', 'ICH9-LPC.acpi-pci-hotplug-with-bridge-support=off'];
2159 }
2160 }
2161 return;
2162}
2163
1e3baf05
DM
2164# add JSON properties for create and set function
2165sub json_config_properties {
c1accf9d 2166 my ($prop, $with_disk_alloc) = @_;
1e3baf05 2167
5a08fb9c
TL
2168 my $skip_json_config_opts = {
2169 parent => 1,
2170 snaptime => 1,
2171 vmstate => 1,
2172 runningmachine => 1,
2173 runningcpu => 1,
26b443c8 2174 meta => 1,
5a08fb9c
TL
2175 };
2176
1e3baf05 2177 foreach my $opt (keys %$confdesc) {
5a08fb9c 2178 next if $skip_json_config_opts->{$opt};
c1accf9d
FE
2179
2180 if ($with_disk_alloc && is_valid_drivename($opt)) {
2181 $prop->{$opt} = $PVE::QemuServer::Drive::drivedesc_hash_with_alloc->{$opt};
2182 } else {
2183 $prop->{$opt} = $confdesc->{$opt};
2184 }
1e3baf05
DM
2185 }
2186
2187 return $prop;
2188}
2189
39051ac0
FE
2190# Properties that we can read from an OVF file
2191sub json_ovf_properties {
2192 my $prop = {};
2193
2194 for my $device (PVE::QemuServer::Drive::valid_drive_names()) {
2195 $prop->{$device} = {
2196 type => 'string',
2197 format => 'pve-volume-id-or-absolute-path',
2198 description => "Disk image that gets imported to $device",
2199 optional => 1,
2200 };
2201 }
2202
2203 $prop->{cores} = {
2204 type => 'integer',
2205 description => "The number of CPU cores.",
2206 optional => 1,
2207 };
2208 $prop->{memory} = {
2209 type => 'integer',
2210 description => "Amount of RAM for the VM in MB.",
2211 optional => 1,
2212 };
2213 $prop->{name} = {
2214 type => 'string',
2215 description => "Name of the VM.",
2216 optional => 1,
2217 };
2218
2219 return $prop;
2220}
2221
d41121fd
DM
2222# return copy of $confdesc_cloudinit to generate documentation
2223sub cloudinit_config_properties {
2224
2225 return dclone($confdesc_cloudinit);
2226}
2227
f16cf6c3
WB
2228sub cloudinit_pending_properties {
2229 my $p = {
2230 map { $_ => 1 } keys $confdesc_cloudinit->%*,
2231 name => 1,
2232 };
2233 $p->{"net$_"} = 1 for 0..($MAX_NETS-1);
2234 return $p;
2235}
2236
1e3baf05
DM
2237sub check_type {
2238 my ($key, $value) = @_;
2239
2240 die "unknown setting '$key'\n" if !$confdesc->{$key};
2241
2242 my $type = $confdesc->{$key}->{type};
2243
6b64503e 2244 if (!defined($value)) {
1e3baf05
DM
2245 die "got undefined value\n";
2246 }
2247
2248 if ($value =~ m/[\n\r]/) {
2249 die "property contains a line feed\n";
2250 }
2251
2252 if ($type eq 'boolean') {
19672434
DM
2253 return 1 if ($value eq '1') || ($value =~ m/^(on|yes|true)$/i);
2254 return 0 if ($value eq '0') || ($value =~ m/^(off|no|false)$/i);
2255 die "type check ('boolean') failed - got '$value'\n";
1e3baf05
DM
2256 } elsif ($type eq 'integer') {
2257 return int($1) if $value =~ m/^(\d+)$/;
2258 die "type check ('integer') failed - got '$value'\n";
04432191
AD
2259 } elsif ($type eq 'number') {
2260 return $value if $value =~ m/^(\d+)(\.\d+)?$/;
2261 die "type check ('number') failed - got '$value'\n";
1e3baf05
DM
2262 } elsif ($type eq 'string') {
2263 if (my $fmt = $confdesc->{$key}->{format}) {
1e3baf05 2264 PVE::JSONSchema::check_format($fmt, $value);
19672434
DM
2265 return $value;
2266 }
1e3baf05 2267 $value =~ s/^\"(.*)\"$/$1/;
19672434 2268 return $value;
1e3baf05
DM
2269 } else {
2270 die "internal error"
2271 }
2272}
2273
1e3baf05 2274sub destroy_vm {
75854662 2275 my ($storecfg, $vmid, $skiplock, $replacement_conf, $purge_unreferenced) = @_;
1e3baf05 2276
ffda963f 2277 my $conf = PVE::QemuConfig->load_config($vmid);
1e3baf05 2278
30fdf99c
SH
2279 if (!$skiplock && !PVE::QemuConfig->has_lock($conf, 'suspended')) {
2280 PVE::QemuConfig->check_lock($conf);
2281 }
1e3baf05 2282
5e67a2d2
DC
2283 if ($conf->{template}) {
2284 # check if any base image is still used by a linked clone
3ab0f925 2285 PVE::QemuConfig->foreach_volume_full($conf, { include_unused => 1 }, sub {
5e67a2d2 2286 my ($ds, $drive) = @_;
5e67a2d2
DC
2287 return if drive_is_cdrom($drive);
2288
2289 my $volid = $drive->{file};
5e67a2d2
DC
2290 return if !$volid || $volid =~ m|^/|;
2291
2292 die "base volume '$volid' is still in use by linked cloned\n"
2293 if PVE::Storage::volume_is_base_and_used($storecfg, $volid);
2294
2295 });
2296 }
2297
3e07c6d5 2298 my $volids = {};
ba1a1984 2299 my $remove_owned_drive = sub {
1e3baf05 2300 my ($ds, $drive) = @_;
9c52f5ed 2301 return if drive_is_cdrom($drive, 1);
1e3baf05
DM
2302
2303 my $volid = $drive->{file};
ff1a2432 2304 return if !$volid || $volid =~ m|^/|;
3e07c6d5 2305 return if $volids->{$volid};
1e3baf05 2306
6b64503e 2307 my ($path, $owner) = PVE::Storage::path($storecfg, $volid);
ff1a2432 2308 return if !$path || !$owner || ($owner != $vmid);
1e3baf05 2309
3e07c6d5 2310 $volids->{$volid} = 1;
a2f50f01 2311 eval { PVE::Storage::vdisk_free($storecfg, $volid) };
31b52247 2312 warn "Could not remove disk '$volid', check manually: $@" if $@;
ba1a1984
FE
2313 };
2314
2315 # only remove disks owned by this VM (referenced in the config)
2316 my $include_opts = {
2317 include_unused => 1,
2318 extra_keys => ['vmstate'],
2319 };
2320 PVE::QemuConfig->foreach_volume_full($conf, $include_opts, $remove_owned_drive);
2321
2322 for my $snap (values %{$conf->{snapshots}}) {
2323 next if !defined($snap->{vmstate});
2324 my $drive = PVE::QemuConfig->parse_volume('vmstate', $snap->{vmstate}, 1);
2325 next if !defined($drive);
2326 $remove_owned_drive->('vmstate', $drive);
2327 }
19672434 2328
3e07c6d5
FG
2329 PVE::QemuConfig->foreach_volume_full($conf->{pending}, $include_opts, $remove_owned_drive);
2330
75854662 2331 if ($purge_unreferenced) { # also remove unreferenced disk
d0ff75d9 2332 my $vmdisks = PVE::Storage::vdisk_list($storecfg, undef, $vmid, undef, 'images');
75854662
TL
2333 PVE::Storage::foreach_volid($vmdisks, sub {
2334 my ($volid, $sid, $volname, $d) = @_;
2335 eval { PVE::Storage::vdisk_free($storecfg, $volid) };
2336 warn $@ if $@;
2337 });
2338 }
dfda979e 2339
b04ea584 2340 if (defined $replacement_conf) {
8baf8bc7 2341 PVE::QemuConfig->write_config($vmid, $replacement_conf);
dfda979e
DJ
2342 } else {
2343 PVE::QemuConfig->destroy_config($vmid);
2344 }
1e3baf05
DM
2345}
2346
1e3baf05 2347sub parse_vm_config {
ad5812d8 2348 my ($filename, $raw, $strict) = @_;
1e3baf05 2349
d1c1af4b 2350 return if !defined($raw);
1e3baf05 2351
554ac7e7 2352 my $res = {
fc1ddcdc 2353 digest => Digest::SHA::sha1_hex($raw),
0d18dcfc 2354 snapshots => {},
0d732d16 2355 pending => {},
95a5135d 2356 cloudinit => {},
554ac7e7 2357 };
1e3baf05 2358
ad5812d8
FG
2359 my $handle_error = sub {
2360 my ($msg) = @_;
2361
2362 if ($strict) {
2363 die $msg;
2364 } else {
2365 warn $msg;
2366 }
2367 };
2368
19672434 2369 $filename =~ m|/qemu-server/(\d+)\.conf$|
1e3baf05
DM
2370 || die "got strange filename '$filename'";
2371
2372 my $vmid = $1;
2373
0d18dcfc 2374 my $conf = $res;
b0ec896e 2375 my $descr;
cbfc9d75
TL
2376 my $finish_description = sub {
2377 if (defined($descr)) {
2378 $descr =~ s/\s+$//;
2379 $conf->{description} = $descr;
2380 }
2381 $descr = undef;
2382 };
e297c490 2383 my $section = '';
0581fe4f 2384
0d18dcfc
DM
2385 my @lines = split(/\n/, $raw);
2386 foreach my $line (@lines) {
1e3baf05 2387 next if $line =~ m/^\s*$/;
be190583 2388
eab09f4e 2389 if ($line =~ m/^\[PENDING\]\s*$/i) {
e297c490 2390 $section = 'pending';
cbfc9d75 2391 $finish_description->();
e297c490 2392 $conf = $res->{$section} = {};
eab09f4e 2393 next;
95a5135d
AD
2394 } elsif ($line =~ m/^\[special:cloudinit\]\s*$/i) {
2395 $section = 'cloudinit';
eb9923f9 2396 $finish_description->();
95a5135d
AD
2397 $conf = $res->{$section} = {};
2398 next;
eab09f4e 2399
0d732d16 2400 } elsif ($line =~ m/^\[([a-z][a-z0-9_\-]+)\]\s*$/i) {
e297c490 2401 $section = $1;
cbfc9d75 2402 $finish_description->();
e297c490 2403 $conf = $res->{snapshots}->{$section} = {};
0d18dcfc
DM
2404 next;
2405 }
1e3baf05 2406
d1e7b922 2407 if ($line =~ m/^\#(.*)$/) {
b0ec896e 2408 $descr = '' if !defined($descr);
0581fe4f
DM
2409 $descr .= PVE::Tools::decode_text($1) . "\n";
2410 next;
2411 }
2412
1e3baf05 2413 if ($line =~ m/^(description):\s*(.*\S)\s*$/) {
b0ec896e 2414 $descr = '' if !defined($descr);
0581fe4f 2415 $descr .= PVE::Tools::decode_text($2);
0d18dcfc
DM
2416 } elsif ($line =~ m/snapstate:\s*(prepare|delete)\s*$/) {
2417 $conf->{snapstate} = $1;
1e3baf05
DM
2418 } elsif ($line =~ m/^(args):\s*(.*\S)\s*$/) {
2419 my $key = $1;
2420 my $value = $2;
0d18dcfc 2421 $conf->{$key} = $value;
ef824322 2422 } elsif ($line =~ m/^delete:\s*(.*\S)\s*$/) {
e297c490 2423 my $value = $1;
ef824322
DM
2424 if ($section eq 'pending') {
2425 $conf->{delete} = $value; # we parse this later
2426 } else {
ad5812d8 2427 $handle_error->("vm $vmid - property 'delete' is only allowed in [PENDING]\n");
eab09f4e 2428 }
15cf7698 2429 } elsif ($line =~ m/^([a-z][a-z_]*\d*):\s*(.+?)\s*$/) {
1e3baf05
DM
2430 my $key = $1;
2431 my $value = $2;
c229961a
TL
2432 if ($section eq 'cloudinit') {
2433 # ignore validation only used for informative purpose
2434 $conf->{$key} = $value;
2435 next;
2436 }
1e3baf05
DM
2437 eval { $value = check_type($key, $value); };
2438 if ($@) {
ad5812d8 2439 $handle_error->("vm $vmid - unable to parse value of '$key' - $@");
1e3baf05 2440 } else {
b799312f 2441 $key = 'ide2' if $key eq 'cdrom';
1e3baf05 2442 my $fmt = $confdesc->{$key}->{format};
b799312f 2443 if ($fmt && $fmt =~ /^pve-qm-(?:ide|scsi|virtio|sata)$/) {
1e3baf05
DM
2444 my $v = parse_drive($key, $value);
2445 if (my $volid = filename_to_volume_id($vmid, $v->{file}, $v->{media})) {
2446 $v->{file} = $volid;
71c58bb7 2447 $value = print_drive($v);
1e3baf05 2448 } else {
ad5812d8 2449 $handle_error->("vm $vmid - unable to parse value of '$key'\n");
1e3baf05
DM
2450 next;
2451 }
2452 }
2453
b799312f 2454 $conf->{$key} = $value;
1e3baf05 2455 }
f8d2a1ce 2456 } else {
ad5812d8 2457 $handle_error->("vm $vmid - unable to parse config: $line\n");
1e3baf05
DM
2458 }
2459 }
2460
cbfc9d75 2461 $finish_description->();
0d18dcfc 2462 delete $res->{snapstate}; # just to be sure
1e3baf05
DM
2463
2464 return $res;
2465}
2466
1858638f
DM
2467sub write_vm_config {
2468 my ($filename, $conf) = @_;
1e3baf05 2469
0d18dcfc
DM
2470 delete $conf->{snapstate}; # just to be sure
2471
1858638f
DM
2472 if ($conf->{cdrom}) {
2473 die "option ide2 conflicts with cdrom\n" if $conf->{ide2};
2474 $conf->{ide2} = $conf->{cdrom};
2475 delete $conf->{cdrom};
2476 }
1e3baf05
DM
2477
2478 # we do not use 'smp' any longer
1858638f
DM
2479 if ($conf->{sockets}) {
2480 delete $conf->{smp};
2481 } elsif ($conf->{smp}) {
2482 $conf->{sockets} = $conf->{smp};
2483 delete $conf->{cores};
2484 delete $conf->{smp};
1e3baf05
DM
2485 }
2486
ee2f90b1 2487 my $used_volids = {};
0d18dcfc 2488
ee2f90b1 2489 my $cleanup_config = sub {
ef824322 2490 my ($cref, $pending, $snapname) = @_;
1858638f 2491
ee2f90b1
DM
2492 foreach my $key (keys %$cref) {
2493 next if $key eq 'digest' || $key eq 'description' || $key eq 'snapshots' ||
95a5135d 2494 $key eq 'snapstate' || $key eq 'pending' || $key eq 'cloudinit';
ee2f90b1 2495 my $value = $cref->{$key};
ef824322
DM
2496 if ($key eq 'delete') {
2497 die "propertry 'delete' is only allowed in [PENDING]\n"
2498 if !$pending;
2499 # fixme: check syntax?
2500 next;
2501 }
ee2f90b1
DM
2502 eval { $value = check_type($key, $value); };
2503 die "unable to parse value of '$key' - $@" if $@;
1858638f 2504
ee2f90b1
DM
2505 $cref->{$key} = $value;
2506
74479ee9 2507 if (!$snapname && is_valid_drivename($key)) {
ed221350 2508 my $drive = parse_drive($key, $value);
ee2f90b1
DM
2509 $used_volids->{$drive->{file}} = 1 if $drive && $drive->{file};
2510 }
1e3baf05 2511 }
ee2f90b1
DM
2512 };
2513
2514 &$cleanup_config($conf);
ef824322
DM
2515
2516 &$cleanup_config($conf->{pending}, 1);
2517
ee2f90b1 2518 foreach my $snapname (keys %{$conf->{snapshots}}) {
15c6e277 2519 die "internal error: snapshot name '$snapname' is forbidden" if lc($snapname) eq 'pending';
ef824322 2520 &$cleanup_config($conf->{snapshots}->{$snapname}, undef, $snapname);
1e3baf05
DM
2521 }
2522
1858638f
DM
2523 # remove 'unusedX' settings if we re-add a volume
2524 foreach my $key (keys %$conf) {
2525 my $value = $conf->{$key};
ee2f90b1 2526 if ($key =~ m/^unused/ && $used_volids->{$value}) {
1858638f 2527 delete $conf->{$key};
1e3baf05 2528 }
1858638f 2529 }
be190583 2530
0d18dcfc 2531 my $generate_raw_config = sub {
b0ec896e 2532 my ($conf, $pending) = @_;
0581fe4f 2533
0d18dcfc
DM
2534 my $raw = '';
2535
2536 # add description as comment to top of file
b0ec896e
DM
2537 if (defined(my $descr = $conf->{description})) {
2538 if ($descr) {
2539 foreach my $cl (split(/\n/, $descr)) {
2540 $raw .= '#' . PVE::Tools::encode_text($cl) . "\n";
2541 }
2542 } else {
2543 $raw .= "#\n" if $pending;
2544 }
0d18dcfc
DM
2545 }
2546
2547 foreach my $key (sort keys %$conf) {
95a5135d 2548 next if $key =~ /^(digest|description|pending|cloudinit|snapshots)$/;
0d18dcfc
DM
2549 $raw .= "$key: $conf->{$key}\n";
2550 }
2551 return $raw;
2552 };
0581fe4f 2553
0d18dcfc 2554 my $raw = &$generate_raw_config($conf);
ef824322
DM
2555
2556 if (scalar(keys %{$conf->{pending}})){
2557 $raw .= "\n[PENDING]\n";
b0ec896e 2558 $raw .= &$generate_raw_config($conf->{pending}, 1);
ef824322
DM
2559 }
2560
1e1d6f58 2561 if (scalar(keys %{$conf->{cloudinit}}) && PVE::QemuConfig->has_cloudinit($conf)){
95a5135d
AD
2562 $raw .= "\n[special:cloudinit]\n";
2563 $raw .= &$generate_raw_config($conf->{cloudinit});
2564 }
2565
0d18dcfc
DM
2566 foreach my $snapname (sort keys %{$conf->{snapshots}}) {
2567 $raw .= "\n[$snapname]\n";
2568 $raw .= &$generate_raw_config($conf->{snapshots}->{$snapname});
1858638f 2569 }
1e3baf05 2570
1858638f
DM
2571 return $raw;
2572}
1e3baf05 2573
19672434 2574sub load_defaults {
1e3baf05
DM
2575
2576 my $res = {};
2577
2578 # we use static defaults from our JSON schema configuration
2579 foreach my $key (keys %$confdesc) {
2580 if (defined(my $default = $confdesc->{$key}->{default})) {
2581 $res->{$key} = $default;
2582 }
2583 }
19672434 2584
1e3baf05
DM
2585 return $res;
2586}
2587
2588sub config_list {
2589 my $vmlist = PVE::Cluster::get_vmlist();
2590 my $res = {};
2591 return $res if !$vmlist || !$vmlist->{ids};
2592 my $ids = $vmlist->{ids};
38277afc 2593 my $nodename = nodename();
1e3baf05 2594
1e3baf05
DM
2595 foreach my $vmid (keys %$ids) {
2596 my $d = $ids->{$vmid};
2597 next if !$d->{node} || $d->{node} ne $nodename;
5ee957cc 2598 next if !$d->{type} || $d->{type} ne 'qemu';
1e3baf05
DM
2599 $res->{$vmid}->{exists} = 1;
2600 }
2601 return $res;
2602}
2603
64e13401
DM
2604# test if VM uses local resources (to prevent migration)
2605sub check_local_resources {
2606 my ($conf, $noerr) = @_;
2607
ca6abacf 2608 my @loc_res = ();
a52eb3c4
DC
2609 my $mapped_res = [];
2610
2611 my $nodelist = PVE::Cluster::get_nodelist();
2612 my $pci_map = PVE::Mapping::PCI::config();
2613 my $usb_map = PVE::Mapping::USB::config();
2614
2615 my $missing_mappings_by_node = { map { $_ => [] } @$nodelist };
2616
2617 my $add_missing_mapping = sub {
2618 my ($type, $key, $id) = @_;
2619 for my $node (@$nodelist) {
2620 my $entry;
2621 if ($type eq 'pci') {
2622 $entry = PVE::Mapping::PCI::get_node_mapping($pci_map, $id, $node);
2623 } elsif ($type eq 'usb') {
2624 $entry = PVE::Mapping::USB::get_node_mapping($usb_map, $id, $node);
2625 }
2626 if (!scalar($entry->@*)) {
2627 push @{$missing_mappings_by_node->{$node}}, $key;
2628 }
2629 }
2630 };
19672434 2631
ca6abacf
TM
2632 push @loc_res, "hostusb" if $conf->{hostusb}; # old syntax
2633 push @loc_res, "hostpci" if $conf->{hostpci}; # old syntax
64e13401 2634
ca6abacf 2635 push @loc_res, "ivshmem" if $conf->{ivshmem};
6dbcb073 2636
0d29ab3b 2637 foreach my $k (keys %$conf) {
a52eb3c4
DC
2638 if ($k =~ m/^usb/) {
2639 my $entry = parse_property_string('pve-qm-usb', $conf->{$k});
2640 next if $entry->{host} =~ m/^spice$/i;
2641 if ($entry->{mapping}) {
2642 $add_missing_mapping->('usb', $k, $entry->{mapping});
2643 push @$mapped_res, $k;
2644 }
2645 }
2646 if ($k =~ m/^hostpci/) {
2647 my $entry = parse_property_string('pve-qm-hostpci', $conf->{$k});
2648 if ($entry->{mapping}) {
2649 $add_missing_mapping->('pci', $k, $entry->{mapping});
2650 push @$mapped_res, $k;
2651 }
2652 }
d44712fc
EK
2653 # sockets are safe: they will recreated be on the target side post-migrate
2654 next if $k =~ m/^serial/ && ($conf->{$k} eq 'socket');
ca6abacf 2655 push @loc_res, $k if $k =~ m/^(usb|hostpci|serial|parallel)\d+$/;
64e13401
DM
2656 }
2657
ca6abacf 2658 die "VM uses local resources\n" if scalar @loc_res && !$noerr;
64e13401 2659
a52eb3c4 2660 return wantarray ? (\@loc_res, $mapped_res, $missing_mappings_by_node) : \@loc_res;
64e13401
DM
2661}
2662
719893a9 2663# check if used storages are available on all nodes (use by migrate)
47152e2e
DM
2664sub check_storage_availability {
2665 my ($storecfg, $conf, $node) = @_;
2666
912792e2 2667 PVE::QemuConfig->foreach_volume($conf, sub {
47152e2e
DM
2668 my ($ds, $drive) = @_;
2669
2670 my $volid = $drive->{file};
2671 return if !$volid;
2672
2673 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
2674 return if !$sid;
2675
2676 # check if storage is available on both nodes
0d2db084
FE
2677 my $scfg = PVE::Storage::storage_check_enabled($storecfg, $sid);
2678 PVE::Storage::storage_check_enabled($storecfg, $sid, $node);
24b84b47 2679
3148f0b0
TL
2680 my ($vtype) = PVE::Storage::parse_volname($storecfg, $volid);
2681
2682 die "$volid: content type '$vtype' is not available on storage '$sid'\n"
2683 if !$scfg->{content}->{$vtype};
47152e2e
DM
2684 });
2685}
2686
719893a9
DM
2687# list nodes where all VM images are available (used by has_feature API)
2688sub shared_nodes {
2689 my ($conf, $storecfg) = @_;
2690
2691 my $nodelist = PVE::Cluster::get_nodelist();
2692 my $nodehash = { map { $_ => 1 } @$nodelist };
38277afc 2693 my $nodename = nodename();
be190583 2694
912792e2 2695 PVE::QemuConfig->foreach_volume($conf, sub {
719893a9
DM
2696 my ($ds, $drive) = @_;
2697
2698 my $volid = $drive->{file};
2699 return if !$volid;
2700
2701 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
2702 if ($storeid) {
2703 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
2704 if ($scfg->{disable}) {
2705 $nodehash = {};
2706 } elsif (my $avail = $scfg->{nodes}) {
2707 foreach my $node (keys %$nodehash) {
2708 delete $nodehash->{$node} if !$avail->{$node};
2709 }
2710 } elsif (!$scfg->{shared}) {
2711 foreach my $node (keys %$nodehash) {
2712 delete $nodehash->{$node} if $node ne $nodename
2713 }
2714 }
2715 }
2716 });
2717
2718 return $nodehash
2719}
2720
f25852c2
TM
2721sub check_local_storage_availability {
2722 my ($conf, $storecfg) = @_;
2723
2724 my $nodelist = PVE::Cluster::get_nodelist();
2725 my $nodehash = { map { $_ => {} } @$nodelist };
2726
912792e2 2727 PVE::QemuConfig->foreach_volume($conf, sub {
f25852c2
TM
2728 my ($ds, $drive) = @_;
2729
2730 my $volid = $drive->{file};
2731 return if !$volid;
2732
2733 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
2734 if ($storeid) {
2735 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
2736
2737 if ($scfg->{disable}) {
2738 foreach my $node (keys %$nodehash) {
32075a2c 2739 $nodehash->{$node}->{unavailable_storages}->{$storeid} = 1;
f25852c2
TM
2740 }
2741 } elsif (my $avail = $scfg->{nodes}) {
2742 foreach my $node (keys %$nodehash) {
2743 if (!$avail->{$node}) {
32075a2c 2744 $nodehash->{$node}->{unavailable_storages}->{$storeid} = 1;
f25852c2
TM
2745 }
2746 }
2747 }
2748 }
2749 });
2750
32075a2c
TL
2751 foreach my $node (values %$nodehash) {
2752 if (my $unavail = $node->{unavailable_storages}) {
2753 $node->{unavailable_storages} = [ sort keys %$unavail ];
2754 }
2755 }
2756
f25852c2
TM
2757 return $nodehash
2758}
2759
babf613a 2760# Compat only, use assert_config_exists_on_node and vm_running_locally where possible
1e3baf05 2761sub check_running {
7e8dcf2c 2762 my ($vmid, $nocheck, $node) = @_;
1e3baf05 2763
a20dc58a
FG
2764 # $nocheck is set when called during a migration, in which case the config
2765 # file might still or already reside on the *other* node
2766 # - because rename has already happened, and current node is source
2767 # - because rename hasn't happened yet, and current node is target
2768 # - because rename has happened, current node is target, but hasn't yet
2769 # processed it yet
babf613a
SR
2770 PVE::QemuConfig::assert_config_exists_on_node($vmid, $node) if !$nocheck;
2771 return PVE::QemuServer::Helpers::vm_running_locally($vmid);
1e3baf05
DM
2772}
2773
2774sub vzlist {
19672434 2775
1e3baf05
DM
2776 my $vzlist = config_list();
2777
d036e418 2778 my $fd = IO::Dir->new($PVE::QemuServer::Helpers::var_run_tmpdir) || return $vzlist;
1e3baf05 2779
19672434 2780 while (defined(my $de = $fd->read)) {
1e3baf05
DM
2781 next if $de !~ m/^(\d+)\.pid$/;
2782 my $vmid = $1;
6b64503e
DM
2783 next if !defined($vzlist->{$vmid});
2784 if (my $pid = check_running($vmid)) {
1e3baf05
DM
2785 $vzlist->{$vmid}->{pid} = $pid;
2786 }
2787 }
2788
2789 return $vzlist;
2790}
2791
b1a70cab
DM
2792our $vmstatus_return_properties = {
2793 vmid => get_standard_option('pve-vmid'),
2794 status => {
7bd9abd2 2795 description => "QEMU process status.",
b1a70cab
DM
2796 type => 'string',
2797 enum => ['stopped', 'running'],
2798 },
2799 maxmem => {
2800 description => "Maximum memory in bytes.",
2801 type => 'integer',
2802 optional => 1,
2803 renderer => 'bytes',
2804 },
2805 maxdisk => {
2806 description => "Root disk size in bytes.",
2807 type => 'integer',
2808 optional => 1,
2809 renderer => 'bytes',
2810 },
2811 name => {
2812 description => "VM name.",
2813 type => 'string',
2814 optional => 1,
2815 },
2816 qmpstatus => {
58542139 2817 description => "VM run state from the 'query-status' QMP monitor command.",
b1a70cab
DM
2818 type => 'string',
2819 optional => 1,
2820 },
2821 pid => {
2822 description => "PID of running qemu process.",
2823 type => 'integer',
2824 optional => 1,
2825 },
2826 uptime => {
2827 description => "Uptime.",
2828 type => 'integer',
2829 optional => 1,
2830 renderer => 'duration',
2831 },
2832 cpus => {
2833 description => "Maximum usable CPUs.",
2834 type => 'number',
2835 optional => 1,
2836 },
e6ed61b4 2837 lock => {
11efdfa5 2838 description => "The current config lock, if any.",
e6ed61b4
DC
2839 type => 'string',
2840 optional => 1,
b8e7068a
DC
2841 },
2842 tags => {
2843 description => "The current configured tags, if any",
2844 type => 'string',
2845 optional => 1,
2846 },
949112c3
FE
2847 'running-machine' => {
2848 description => "The currently running machine type (if running).",
2849 type => 'string',
2850 optional => 1,
2851 },
2852 'running-qemu' => {
2853 description => "The currently running QEMU version (if running).",
2854 type => 'string',
2855 optional => 1,
2856 },
b1a70cab
DM
2857};
2858
1e3baf05
DM
2859my $last_proc_pid_stat;
2860
03a33f30
DM
2861# get VM status information
2862# This must be fast and should not block ($full == false)
2863# We only query KVM using QMP if $full == true (this can be slow)
1e3baf05 2864sub vmstatus {
03a33f30 2865 my ($opt_vmid, $full) = @_;
1e3baf05
DM
2866
2867 my $res = {};
2868
19672434 2869 my $storecfg = PVE::Storage::config();
1e3baf05
DM
2870
2871 my $list = vzlist();
3618ee99
EK
2872 my $defaults = load_defaults();
2873
694fcad4 2874 my ($uptime) = PVE::ProcFSTools::read_proc_uptime(1);
1e3baf05 2875
ae4915a2
DM
2876 my $cpucount = $cpuinfo->{cpus} || 1;
2877
1e3baf05
DM
2878 foreach my $vmid (keys %$list) {
2879 next if $opt_vmid && ($vmid ne $opt_vmid);
2880
9f78b695 2881 my $conf = PVE::QemuConfig->load_config($vmid);
1e3baf05 2882
ad2cad72 2883 my $d = { vmid => int($vmid) };
8a0addab 2884 $d->{pid} = int($list->{$vmid}->{pid}) if $list->{$vmid}->{pid};
1e3baf05
DM
2885
2886 # fixme: better status?
2887 $d->{status} = $list->{$vmid}->{pid} ? 'running' : 'stopped';
2888
776c5f50 2889 my $size = PVE::QemuServer::Drive::bootdisk_size($storecfg, $conf);
af990afe
DM
2890 if (defined($size)) {
2891 $d->{disk} = 0; # no info available
1e3baf05
DM
2892 $d->{maxdisk} = $size;
2893 } else {
2894 $d->{disk} = 0;
2895 $d->{maxdisk} = 0;
2896 }
2897
3618ee99
EK
2898 $d->{cpus} = ($conf->{sockets} || $defaults->{sockets})
2899 * ($conf->{cores} || $defaults->{cores});
ae4915a2 2900 $d->{cpus} = $cpucount if $d->{cpus} > $cpucount;
d7c8364b 2901 $d->{cpus} = $conf->{vcpus} if $conf->{vcpus};
ae4915a2 2902
1e3baf05 2903 $d->{name} = $conf->{name} || "VM $vmid";
7f8c8087 2904 $d->{maxmem} = get_current_memory($conf->{memory})*(1024*1024);
1e3baf05 2905
8b1accf7 2906 if ($conf->{balloon}) {
4bdb0514 2907 $d->{balloon_min} = $conf->{balloon}*(1024*1024);
3618ee99
EK
2908 $d->{shares} = defined($conf->{shares}) ? $conf->{shares}
2909 : $defaults->{shares};
8b1accf7
DM
2910 }
2911
1e3baf05
DM
2912 $d->{uptime} = 0;
2913 $d->{cpu} = 0;
1e3baf05
DM
2914 $d->{mem} = 0;
2915
2916 $d->{netout} = 0;
2917 $d->{netin} = 0;
2918
2919 $d->{diskread} = 0;
2920 $d->{diskwrite} = 0;
2921
75a2a423 2922 $d->{template} = 1 if PVE::QemuConfig->is_template($conf);
4d8c851b 2923
8107b378 2924 $d->{serial} = 1 if conf_has_serial($conf);
e6ed61b4 2925 $d->{lock} = $conf->{lock} if $conf->{lock};
b8e7068a 2926 $d->{tags} = $conf->{tags} if defined($conf->{tags});
8107b378 2927
1e3baf05
DM
2928 $res->{$vmid} = $d;
2929 }
2930
2931 my $netdev = PVE::ProcFSTools::read_proc_net_dev();
2932 foreach my $dev (keys %$netdev) {
2933 next if $dev !~ m/^tap([1-9]\d*)i/;
2934 my $vmid = $1;
2935 my $d = $res->{$vmid};
2936 next if !$d;
19672434 2937
1e3baf05
DM
2938 $d->{netout} += $netdev->{$dev}->{receive};
2939 $d->{netin} += $netdev->{$dev}->{transmit};
604ea644
AD
2940
2941 if ($full) {
ad2cad72
FE
2942 $d->{nics}->{$dev}->{netout} = int($netdev->{$dev}->{receive});
2943 $d->{nics}->{$dev}->{netin} = int($netdev->{$dev}->{transmit});
604ea644
AD
2944 }
2945
1e3baf05
DM
2946 }
2947
1e3baf05
DM
2948 my $ctime = gettimeofday;
2949
2950 foreach my $vmid (keys %$list) {
2951
2952 my $d = $res->{$vmid};
2953 my $pid = $d->{pid};
2954 next if !$pid;
2955
694fcad4
DM
2956 my $pstat = PVE::ProcFSTools::read_proc_pid_stat($pid);
2957 next if !$pstat; # not running
19672434 2958
694fcad4 2959 my $used = $pstat->{utime} + $pstat->{stime};
1e3baf05 2960
694fcad4 2961 $d->{uptime} = int(($uptime - $pstat->{starttime})/$cpuinfo->{user_hz});
1e3baf05 2962
694fcad4 2963 if ($pstat->{vsize}) {
6b64503e 2964 $d->{mem} = int(($pstat->{rss}/$pstat->{vsize})*$d->{maxmem});
1e3baf05
DM
2965 }
2966
2967 my $old = $last_proc_pid_stat->{$pid};
2968 if (!$old) {
19672434
DM
2969 $last_proc_pid_stat->{$pid} = {
2970 time => $ctime,
1e3baf05
DM
2971 used => $used,
2972 cpu => 0,
1e3baf05
DM
2973 };
2974 next;
2975 }
2976
7f0b5beb 2977 my $dtime = ($ctime - $old->{time}) * $cpucount * $cpuinfo->{user_hz};
1e3baf05
DM
2978
2979 if ($dtime > 1000) {
2980 my $dutime = $used - $old->{used};
2981
ae4915a2 2982 $d->{cpu} = (($dutime/$dtime)* $cpucount) / $d->{cpus};
1e3baf05 2983 $last_proc_pid_stat->{$pid} = {
19672434 2984 time => $ctime,
1e3baf05
DM
2985 used => $used,
2986 cpu => $d->{cpu},
1e3baf05
DM
2987 };
2988 } else {
2989 $d->{cpu} = $old->{cpu};
1e3baf05
DM
2990 }
2991 }
2992
f5eb281a 2993 return $res if !$full;
03a33f30
DM
2994
2995 my $qmpclient = PVE::QMPClient->new();
2996
64e7fcf2
DM
2997 my $ballooncb = sub {
2998 my ($vmid, $resp) = @_;
2999
3000 my $info = $resp->{'return'};
38babf81
DM
3001 return if !$info->{max_mem};
3002
64e7fcf2
DM
3003 my $d = $res->{$vmid};
3004
38babf81
DM
3005 # use memory assigned to VM
3006 $d->{maxmem} = $info->{max_mem};
3007 $d->{balloon} = $info->{actual};
3008
3009 if (defined($info->{total_mem}) && defined($info->{free_mem})) {
3010 $d->{mem} = $info->{total_mem} - $info->{free_mem};
3011 $d->{freemem} = $info->{free_mem};
64e7fcf2
DM
3012 }
3013
604ea644 3014 $d->{ballooninfo} = $info;
64e7fcf2
DM
3015 };
3016
03a33f30
DM
3017 my $blockstatscb = sub {
3018 my ($vmid, $resp) = @_;
3019 my $data = $resp->{'return'} || [];
3020 my $totalrdbytes = 0;
3021 my $totalwrbytes = 0;
604ea644 3022
03a33f30
DM
3023 for my $blockstat (@$data) {
3024 $totalrdbytes = $totalrdbytes + $blockstat->{stats}->{rd_bytes};
3025 $totalwrbytes = $totalwrbytes + $blockstat->{stats}->{wr_bytes};
604ea644
AD
3026
3027 $blockstat->{device} =~ s/drive-//;
3028 $res->{$vmid}->{blockstat}->{$blockstat->{device}} = $blockstat->{stats};
03a33f30
DM
3029 }
3030 $res->{$vmid}->{diskread} = $totalrdbytes;
3031 $res->{$vmid}->{diskwrite} = $totalwrbytes;
3032 };
3033
949112c3
FE
3034 my $machinecb = sub {
3035 my ($vmid, $resp) = @_;
3036 my $data = $resp->{'return'} || [];
3037
3038 $res->{$vmid}->{'running-machine'} =
3039 PVE::QemuServer::Machine::current_from_query_machines($data);
3040 };
3041
3042 my $versioncb = sub {
3043 my ($vmid, $resp) = @_;
3044 my $data = $resp->{'return'} // {};
3045 my $version = 'unknown';
3046
3047 if (my $v = $data->{qemu}) {
3048 $version = $v->{major} . "." . $v->{minor} . "." . $v->{micro};
3049 }
3050
3051 $res->{$vmid}->{'running-qemu'} = $version;
3052 };
3053
03a33f30
DM
3054 my $statuscb = sub {
3055 my ($vmid, $resp) = @_;
64e7fcf2 3056
03a33f30 3057 $qmpclient->queue_cmd($vmid, $blockstatscb, 'query-blockstats');
949112c3
FE
3058 $qmpclient->queue_cmd($vmid, $machinecb, 'query-machines');
3059 $qmpclient->queue_cmd($vmid, $versioncb, 'query-version');
64e7fcf2
DM
3060 # this fails if ballon driver is not loaded, so this must be
3061 # the last commnand (following command are aborted if this fails).
38babf81 3062 $qmpclient->queue_cmd($vmid, $ballooncb, 'query-balloon');
03a33f30
DM
3063
3064 my $status = 'unknown';
3065 if (!defined($status = $resp->{'return'}->{status})) {
3066 warn "unable to get VM status\n";
3067 return;
3068 }
3069
3070 $res->{$vmid}->{qmpstatus} = $resp->{'return'}->{status};
3071 };
3072
3073 foreach my $vmid (keys %$list) {
3074 next if $opt_vmid && ($vmid ne $opt_vmid);
3075 next if !$res->{$vmid}->{pid}; # not running
3076 $qmpclient->queue_cmd($vmid, $statuscb, 'query-status');
3077 }
3078
b017fbda 3079 $qmpclient->queue_execute(undef, 2);
03a33f30 3080
6891fd70
SR
3081 foreach my $vmid (keys %$list) {
3082 next if $opt_vmid && ($vmid ne $opt_vmid);
e5b18771
FG
3083 next if !$res->{$vmid}->{pid}; #not running
3084
6891fd70
SR
3085 # we can't use the $qmpclient since it might have already aborted on
3086 # 'query-balloon', but this might also fail for older versions...
3087 my $qemu_support = eval { mon_cmd($vmid, "query-proxmox-support") };
3088 $res->{$vmid}->{'proxmox-support'} = $qemu_support // {};
3089 }
3090
03a33f30
DM
3091 foreach my $vmid (keys %$list) {
3092 next if $opt_vmid && ($vmid ne $opt_vmid);
3093 $res->{$vmid}->{qmpstatus} = $res->{$vmid}->{status} if !$res->{$vmid}->{qmpstatus};
3094 }
3095
1e3baf05
DM
3096 return $res;
3097}
3098
8107b378
DC
3099sub conf_has_serial {
3100 my ($conf) = @_;
3101
3102 for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) {
3103 if ($conf->{"serial$i"}) {
3104 return 1;
3105 }
3106 }
3107
3108 return 0;
3109}
3110
d5535a00
TL
3111sub conf_has_audio {
3112 my ($conf, $id) = @_;
3113
3114 $id //= 0;
3115 my $audio = $conf->{"audio$id"};
d1c1af4b 3116 return if !defined($audio);
d5535a00 3117
4df98f2f 3118 my $audioproperties = parse_property_string($audio_fmt, $audio);
d5535a00
TL
3119 my $audiodriver = $audioproperties->{driver} // 'spice';
3120
3121 return {
3122 dev => $audioproperties->{device},
b0f96836 3123 dev_id => "audiodev$id",
d5535a00
TL
3124 backend => $audiodriver,
3125 backend_id => "$audiodriver-backend${id}",
3126 };
3127}
3128
b01de199 3129sub audio_devs {
1cc5ed1b 3130 my ($audio, $audiopciaddr, $machine_version) = @_;
b01de199
TL
3131
3132 my $devs = [];
3133
3134 my $id = $audio->{dev_id};
1cc5ed1b
AL
3135 my $audiodev = "";
3136 if (min_version($machine_version, 4, 2)) {
3137 $audiodev = ",audiodev=$audio->{backend_id}";
3138 }
b01de199
TL
3139
3140 if ($audio->{dev} eq 'AC97') {
1cc5ed1b 3141 push @$devs, '-device', "AC97,id=${id}${audiopciaddr}$audiodev";
b01de199
TL
3142 } elsif ($audio->{dev} =~ /intel\-hda$/) {
3143 push @$devs, '-device', "$audio->{dev},id=${id}${audiopciaddr}";
1cc5ed1b
AL
3144 push @$devs, '-device', "hda-micro,id=${id}-codec0,bus=${id}.0,cad=0$audiodev";
3145 push @$devs, '-device', "hda-duplex,id=${id}-codec1,bus=${id}.0,cad=1$audiodev";
b01de199
TL
3146 } else {
3147 die "unkown audio device '$audio->{dev}', implement me!";
3148 }
3149
3150 push @$devs, '-audiodev', "$audio->{backend},id=$audio->{backend_id}";
3151
3152 return $devs;
3153}
3154
f9dde219
SR
3155sub get_tpm_paths {
3156 my ($vmid) = @_;
3157 return {
3158 socket => "/var/run/qemu-server/$vmid.swtpm",
3159 pid => "/var/run/qemu-server/$vmid.swtpm.pid",
3160 };
3161}
3162
3163sub add_tpm_device {
3164 my ($vmid, $devices, $conf) = @_;
3165
3166 return if !$conf->{tpmstate0};
3167
3168 my $paths = get_tpm_paths($vmid);
3169
3170 push @$devices, "-chardev", "socket,id=tpmchar,path=$paths->{socket}";
3171 push @$devices, "-tpmdev", "emulator,id=tpmdev,chardev=tpmchar";
3172 push @$devices, "-device", "tpm-tis,tpmdev=tpmdev";
3173}
3174
3175sub start_swtpm {
3176 my ($storecfg, $vmid, $tpmdrive, $migration) = @_;
3177
3178 return if !$tpmdrive;
3179
3180 my $state;
3181 my $tpm = parse_drive("tpmstate0", $tpmdrive);
3182 my ($storeid, $volname) = PVE::Storage::parse_volume_id($tpm->{file}, 1);
3183 if ($storeid) {
3184 $state = PVE::Storage::map_volume($storecfg, $tpm->{file});
3185 } else {
3186 $state = $tpm->{file};
3187 }
3188
3189 my $paths = get_tpm_paths($vmid);
3190
3191 # during migration, we will get state from remote
3192 #
3193 if (!$migration) {
3194 # run swtpm_setup to create a new TPM state if it doesn't exist yet
3195 my $setup_cmd = [
3196 "swtpm_setup",
3197 "--tpmstate",
3198 "file://$state",
3199 "--createek",
3200 "--create-ek-cert",
3201 "--create-platform-cert",
3202 "--lock-nvram",
3203 "--config",
3204 "/etc/swtpm_setup.conf", # do not use XDG configs
3205 "--runas",
3206 "0", # force creation as root, error if not possible
3207 "--not-overwrite", # ignore existing state, do not modify
3208 ];
3209
3210 push @$setup_cmd, "--tpm2" if $tpm->{version} eq 'v2.0';
3211 # TPM 2.0 supports ECC crypto, use if possible
3212 push @$setup_cmd, "--ecc" if $tpm->{version} eq 'v2.0';
3213
3214 run_command($setup_cmd, outfunc => sub {
3215 print "swtpm_setup: $1\n";
3216 });
3217 }
3218
72a5a176
FE
3219 # Used to distinguish different invocations in the log.
3220 my $log_prefix = "[id=" . int(time()) . "] ";
3221
f9dde219
SR
3222 my $emulator_cmd = [
3223 "swtpm",
3224 "socket",
3225 "--tpmstate",
3226 "backend-uri=file://$state,mode=0600",
3227 "--ctrl",
3228 "type=unixio,path=$paths->{socket},mode=0600",
3229 "--pid",
3230 "file=$paths->{pid}",
3231 "--terminate", # terminate on QEMU disconnect
3232 "--daemon",
b2e9c4d3 3233 "--log",
72a5a176 3234 "file=/run/qemu-server/$vmid-swtpm.log,level=1,prefix=$log_prefix",
f9dde219
SR
3235 ];
3236 push @$emulator_cmd, "--tpm2" if $tpm->{version} eq 'v2.0';
3237 run_command($emulator_cmd, outfunc => sub { print $1; });
3238
6bbcd71f 3239 my $tries = 100; # swtpm may take a bit to start before daemonizing, wait up to 5s for pid
f85951dc 3240 while (! -e $paths->{pid}) {
90c41bac 3241 die "failed to start swtpm: pid file '$paths->{pid}' wasn't created.\n" if --$tries == 0;
6bbcd71f 3242 usleep(50_000);
f85951dc
SR
3243 }
3244
f9dde219
SR
3245 # return untainted PID of swtpm daemon so it can be killed on error
3246 file_read_firstline($paths->{pid}) =~ m/(\d+)/;
3247 return $1;
3248}
3249
86b8228b
DM
3250sub vga_conf_has_spice {
3251 my ($vga) = @_;
3252
55655ebc
DC
3253 my $vgaconf = parse_vga($vga);
3254 my $vgatype = $vgaconf->{type};
3255 return 0 if !$vgatype || $vgatype !~ m/^qxl([234])?$/;
590e698c
DM
3256
3257 return $1 || 1;
86b8228b
DM
3258}
3259
d731ecbe
WB
3260sub is_native($) {
3261 my ($arch) = @_;
3262 return get_host_arch() eq $arch;
3263}
3264
045749f2
TL
3265sub get_vm_arch {
3266 my ($conf) = @_;
3267 return $conf->{arch} // get_host_arch();
3268}
3269
d731ecbe
WB
3270my $default_machines = {
3271 x86_64 => 'pc',
3272 aarch64 => 'virt',
3273};
3274
0761e619
TL
3275sub get_installed_machine_version {
3276 my ($kvmversion) = @_;
3277 $kvmversion = kvm_user_version() if !defined($kvmversion);
3278 $kvmversion =~ m/^(\d+\.\d+)/;
3279 return $1;
3280}
3281
3282sub windows_get_pinned_machine_version {
3283 my ($machine, $base_version, $kvmversion) = @_;
3284
3285 my $pin_version = $base_version;
3286 if (!defined($base_version) ||
3287 !PVE::QemuServer::Machine::can_run_pve_machine_version($base_version, $kvmversion)
3288 ) {
3289 $pin_version = get_installed_machine_version($kvmversion);
3290 }
3291 if (!$machine || $machine eq 'pc') {
3292 $machine = "pc-i440fx-$pin_version";
3293 } elsif ($machine eq 'q35') {
3294 $machine = "pc-q35-$pin_version";
3295 } elsif ($machine eq 'virt') {
3296 $machine = "virt-$pin_version";
3297 } else {
3298 warn "unknown machine type '$machine', not touching that!\n";
3299 }
3300
3301 return $machine;
3302}
3303
045749f2 3304sub get_vm_machine {
ac0077cc 3305 my ($conf, $forcemachine, $arch, $add_pve_version, $kvmversion) = @_;
045749f2
TL
3306
3307 my $machine = $forcemachine || $conf->{machine};
d731ecbe 3308
9471e48b 3309 if (!$machine || $machine =~ m/^(?:pc|q35|virt)$/) {
4dd1e83c
TL
3310 $kvmversion //= kvm_user_version();
3311 # we must pin Windows VMs without a specific version to 5.1, as 5.2 fixed a bug in ACPI
3312 # layout which confuses windows quite a bit and may result in various regressions..
3313 # see: https://lists.gnu.org/archive/html/qemu-devel/2021-02/msg08484.html
3314 if (windows_version($conf->{ostype})) {
0761e619 3315 $machine = windows_get_pinned_machine_version($machine, '5.1', $kvmversion);
4dd1e83c 3316 }
045749f2
TL
3317 $arch //= 'x86_64';
3318 $machine ||= $default_machines->{$arch};
ac0077cc 3319 if ($add_pve_version) {
ac0077cc
SR
3320 my $pvever = PVE::QemuServer::Machine::get_pve_version($kvmversion);
3321 $machine .= "+pve$pvever";
3322 }
3323 }
3324
d4be7f31
SR
3325 if ($add_pve_version && $machine !~ m/\+pve\d+?(?:\.pxe)?$/) {
3326 my $is_pxe = $machine =~ m/^(.*?)\.pxe$/;
3327 $machine = $1 if $is_pxe;
3328
ac0077cc
SR
3329 # for version-pinned machines that do not include a pve-version (e.g.
3330 # pc-q35-4.1), we assume 0 to keep them stable in case we bump
3331 $machine .= '+pve0';
d4be7f31
SR
3332
3333 $machine .= '.pxe' if $is_pxe;
045749f2
TL
3334 }
3335
3336 return $machine;
d731ecbe
WB
3337}
3338
90b20b15
DC
3339sub get_ovmf_files($$$) {
3340 my ($arch, $efidisk, $smm) = @_;
96ed3574 3341
b5099b4f 3342 my $types = $OVMF->{$arch}
96ed3574
WB
3343 or die "no OVMF images known for architecture '$arch'\n";
3344
b5099b4f 3345 my $type = 'default';
1183c8f1 3346 if ($arch ne "aarch64" && defined($efidisk->{efitype}) && $efidisk->{efitype} eq '4m') {
90b20b15
DC
3347 $type = $smm ? "4m" : "4m-no-smm";
3348 $type .= '-ms' if $efidisk->{'pre-enrolled-keys'};
b5099b4f
SR
3349 }
3350
f78c9b6b
NU
3351 my ($ovmf_code, $ovmf_vars) = $types->{$type}->@*;
3352 die "EFI base image '$ovmf_code' not found\n" if ! -f $ovmf_code;
3353 die "EFI vars image '$ovmf_vars' not found\n" if ! -f $ovmf_vars;
3354
3355 return ($ovmf_code, $ovmf_vars);
96ed3574
WB
3356}
3357
6908fd9b
WB
3358my $Arch2Qemu = {
3359 aarch64 => '/usr/bin/qemu-system-aarch64',
3360 x86_64 => '/usr/bin/qemu-system-x86_64',
3361};
3362sub get_command_for_arch($) {
3363 my ($arch) = @_;
3364 return '/usr/bin/kvm' if is_native($arch);
3365
3366 my $cmd = $Arch2Qemu->{$arch}
3367 or die "don't know how to emulate architecture '$arch'\n";
3368 return $cmd;
3369}
3370
05a4c550
SR
3371# To use query_supported_cpu_flags and query_understood_cpu_flags to get flags
3372# to use in a QEMU command line (-cpu element), first array_intersect the result
3373# of query_supported_ with query_understood_. This is necessary because:
3374#
3375# a) query_understood_ returns flags the host cannot use and
3376# b) query_supported_ (rather the QMP call) doesn't actually return CPU
3377# flags, but CPU settings - with most of them being flags. Those settings
3378# (and some flags, curiously) cannot be specified as a "-cpu" argument.
3379#
3380# query_supported_ needs to start up to 2 temporary VMs and is therefore rather
3381# expensive. If you need the value returned from this, you can get it much
3382# cheaper from pmxcfs using PVE::Cluster::get_node_kv('cpuflags-$accel') with
3383# $accel being 'kvm' or 'tcg'.
3384#
3385# pvestatd calls this function on startup and whenever the QEMU/KVM version
3386# changes, automatically populating pmxcfs.
3387#
3388# Returns: { kvm => [ flagX, flagY, ... ], tcg => [ flag1, flag2, ... ] }
3389# since kvm and tcg machines support different flags
3390#
3391sub query_supported_cpu_flags {
52cffab6 3392 my ($arch) = @_;
05a4c550 3393
52cffab6
SR
3394 $arch //= get_host_arch();
3395 my $default_machine = $default_machines->{$arch};
3396
3397 my $flags = {};
05a4c550
SR
3398
3399 # FIXME: Once this is merged, the code below should work for ARM as well:
3400 # https://lists.nongnu.org/archive/html/qemu-devel/2019-06/msg04947.html
3401 die "QEMU/KVM cannot detect CPU flags on ARM (aarch64)\n" if
3402 $arch eq "aarch64";
3403
3404 my $kvm_supported = defined(kvm_version());
3405 my $qemu_cmd = get_command_for_arch($arch);
3406 my $fakevmid = -1;
3407 my $pidfile = PVE::QemuServer::Helpers::pidfile_name($fakevmid);
3408
3409 # Start a temporary (frozen) VM with vmid -1 to allow sending a QMP command
3410 my $query_supported_run_qemu = sub {
3411 my ($kvm) = @_;
3412
3413 my $flags = {};
3414 my $cmd = [
3415 $qemu_cmd,
3416 '-machine', $default_machine,
3417 '-display', 'none',
378ad769 3418 '-chardev', "socket,id=qmp,path=/var/run/qemu-server/$fakevmid.qmp,server=on,wait=off",
05a4c550
SR
3419 '-mon', 'chardev=qmp,mode=control',
3420 '-pidfile', $pidfile,
3421 '-S', '-daemonize'
3422 ];
3423
3424 if (!$kvm) {
3425 push @$cmd, '-accel', 'tcg';
3426 }
3427
3428 my $rc = run_command($cmd, noerr => 1, quiet => 0);
3429 die "QEMU flag querying VM exited with code " . $rc if $rc;
3430
3431 eval {
3432 my $cmd_result = mon_cmd(
3433 $fakevmid,
3434 'query-cpu-model-expansion',
3435 type => 'full',
3436 model => { name => 'host' }
3437 );
3438
3439 my $props = $cmd_result->{model}->{props};
3440 foreach my $prop (keys %$props) {
3441 next if $props->{$prop} ne '1';
3442 # QEMU returns some flags multiple times, with '_', '.' or '-'
3443 # (e.g. lahf_lm and lahf-lm; sse4.2, sse4-2 and sse4_2; ...).
3444 # We only keep those with underscores, to match /proc/cpuinfo
3445 $prop =~ s/\.|-/_/g;
3446 $flags->{$prop} = 1;
3447 }
3448 };
3449 my $err = $@;
3450
6bbcd71f 3451 # force stop with 10 sec timeout and 'nocheck', always stop, even if QMP failed
05a4c550
SR
3452 vm_stop(undef, $fakevmid, 1, 1, 10, 0, 1);
3453
3454 die $err if $err;
3455
3456 return [ sort keys %$flags ];
3457 };
3458
3459 # We need to query QEMU twice, since KVM and TCG have different supported flags
3460 PVE::QemuConfig->lock_config($fakevmid, sub {
3461 $flags->{tcg} = eval { $query_supported_run_qemu->(0) };
3462 warn "warning: failed querying supported tcg flags: $@\n" if $@;
3463
3464 if ($kvm_supported) {
3465 $flags->{kvm} = eval { $query_supported_run_qemu->(1) };
3466 warn "warning: failed querying supported kvm flags: $@\n" if $@;
3467 }
3468 });
3469
3470 return $flags;
3471}
3472
3473# Understood CPU flags are written to a file at 'pve-qemu' compile time
3474my $understood_cpu_flag_dir = "/usr/share/kvm";
3475sub query_understood_cpu_flags {
3476 my $arch = get_host_arch();
3477 my $filepath = "$understood_cpu_flag_dir/recognized-CPUID-flags-$arch";
3478
3479 die "Cannot query understood QEMU CPU flags for architecture: $arch (file not found)\n"
3480 if ! -e $filepath;
3481
3482 my $raw = file_get_contents($filepath);
3483 $raw =~ s/^\s+|\s+$//g;
3484 my @flags = split(/\s+/, $raw);
3485
3486 return \@flags;
3487}
3488
e5a6919c
FE
3489# Since commit 277d33454f77ec1d1e0bc04e37621e4dd2424b67 in pve-qemu, smm is not off by default
3490# anymore. But smm=off seems to be required when using SeaBIOS and serial display.
3491my sub should_disable_smm {
e4263214
FE
3492 my ($conf, $vga, $machine) = @_;
3493
3494 return if $machine =~ m/^virt/; # there is no smm flag that could be disabled
e5a6919c
FE
3495
3496 return (!defined($conf->{bios}) || $conf->{bios} eq 'seabios') &&
bec87424 3497 $vga->{type} && $vga->{type} =~ m/^(serial\d+|none)$/;
e5a6919c
FE
3498}
3499
b7d80c79
FE
3500my sub print_ovmf_drive_commandlines {
3501 my ($conf, $storecfg, $vmid, $arch, $q35, $version_guard) = @_;
3502
3d07669c 3503 my $d = $conf->{efidisk0} ? parse_drive('efidisk0', $conf->{efidisk0}) : undef;
b7d80c79
FE
3504
3505 my ($ovmf_code, $ovmf_vars) = get_ovmf_files($arch, $d, $q35);
b7d80c79 3506
3d07669c 3507 my $var_drive_str = "if=pflash,unit=1,id=drive-efidisk0";
b7d80c79
FE
3508 if ($d) {
3509 my ($storeid, $volname) = PVE::Storage::parse_volume_id($d->{file}, 1);
3d07669c 3510 my ($path, $format) = $d->@{'file', 'format'};
b7d80c79
FE
3511 if ($storeid) {
3512 $path = PVE::Storage::path($storecfg, $d->{file});
3513 if (!defined($format)) {
3514 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
3515 $format = qemu_img_format($scfg, $volname);
3516 }
3d07669c
TL
3517 } elsif (!defined($format)) {
3518 die "efidisk format must be specified\n";
3519 }
3520 # SPI flash does lots of read-modify-write OPs, without writeback this gets really slow #3329
3521 if ($path =~ m/^rbd:/) {
3522 $var_drive_str .= ',cache=writeback';
3523 $path .= ':rbd_cache_policy=writeback'; # avoid write-around, we *need* to cache writes too
b7d80c79 3524 }
3d07669c 3525 $var_drive_str .= ",format=$format,file=$path";
b7d80c79 3526
3d07669c
TL
3527 $var_drive_str .= ",size=" . (-s $ovmf_vars) if $format eq 'raw' && $version_guard->(4, 1, 2);
3528 $var_drive_str .= ',readonly=on' if drive_is_read_only($conf, $d);
b7d80c79
FE
3529 } else {
3530 log_warn("no efidisk configured! Using temporary efivars disk.");
3d07669c 3531 my $path = "/tmp/$vmid-ovmf.fd";
b7d80c79 3532 PVE::Tools::file_copy($ovmf_vars, $path, -s $ovmf_vars);
3d07669c
TL
3533 $var_drive_str .= ",format=raw,file=$path";
3534 $var_drive_str .= ",size=" . (-s $ovmf_vars) if $version_guard->(4, 1, 2);
b7d80c79
FE
3535 }
3536
3d07669c 3537 return ("if=pflash,unit=0,format=raw,readonly=on,file=$ovmf_code", $var_drive_str);
b7d80c79
FE
3538}
3539
1e3baf05 3540sub config_to_command {
5921764c
SR
3541 my ($storecfg, $vmid, $conf, $defaults, $forcemachine, $forcecpu,
3542 $pbs_backing) = @_;
1e3baf05 3543
3326ae19 3544 my ($globalFlags, $machineFlags, $rtcFlags) = ([], [], []);
5bdcf937 3545 my $devices = [];
5bdcf937 3546 my $bridges = {};
b42d3cf9 3547 my $ostype = $conf->{ostype};
4317f69f 3548 my $winversion = windows_version($ostype);
d731ecbe 3549 my $kvm = $conf->{kvm};
38277afc 3550 my $nodename = nodename();
d731ecbe 3551
045749f2 3552 my $arch = get_vm_arch($conf);
1476b99f
DC
3553 my $kvm_binary = get_command_for_arch($arch);
3554 my $kvmver = kvm_user_version($kvm_binary);
045749f2 3555
a04dd5c4
SR
3556 if (!$kvmver || $kvmver !~ m/^(\d+)\.(\d+)/ || $1 < 3) {
3557 $kvmver //= "undefined";
3558 die "Detected old QEMU binary ('$kvmver', at least 3.0 is required)\n";
3559 }
3560
9471e48b
TL
3561 my $add_pve_version = min_version($kvmver, 4, 1);
3562
3563 my $machine_type = get_vm_machine($conf, $forcemachine, $arch, $add_pve_version);
4df98f2f 3564 my $machine_version = extract_version($machine_type, $kvmver);
d731ecbe 3565 $kvm //= 1 if is_native($arch);
4317f69f 3566
a77a53ae 3567 $machine_version =~ m/(\d+)\.(\d+)/;
ac0077cc 3568 my ($machine_major, $machine_minor) = ($1, $2);
ac0077cc 3569
b516c848
SR
3570 if ($kvmver =~ m/^\d+\.\d+\.(\d+)/ && $1 >= 90) {
3571 warn "warning: Installed QEMU version ($kvmver) is a release candidate, ignoring version checks\n";
3572 } elsif (!min_version($kvmver, $machine_major, $machine_minor)) {
4df98f2f
TL
3573 die "Installed QEMU version '$kvmver' is too old to run machine type '$machine_type',"
3574 ." please upgrade node '$nodename'\n"
b516c848 3575 } elsif (!PVE::QemuServer::Machine::can_run_pve_machine_version($machine_version, $kvmver)) {
ac0077cc 3576 my $max_pve_version = PVE::QemuServer::Machine::get_pve_version($machine_version);
4df98f2f
TL
3577 die "Installed qemu-server (max feature level for $machine_major.$machine_minor is"
3578 ." pve$max_pve_version) is too old to run machine type '$machine_type', please upgrade"
3579 ." node '$nodename'\n";
ac0077cc
SR
3580 }
3581
3582 # if a specific +pve version is required for a feature, use $version_guard
3583 # instead of min_version to allow machines to be run with the minimum
3584 # required version
3585 my $required_pve_version = 0;
3586 my $version_guard = sub {
3587 my ($major, $minor, $pve) = @_;
3588 return 0 if !min_version($machine_version, $major, $minor, $pve);
47f35977
SR
3589 my $max_pve = PVE::QemuServer::Machine::get_pve_version("$major.$minor");
3590 return 1 if min_version($machine_version, $major, $minor, $max_pve+1);
ac0077cc
SR
3591 $required_pve_version = $pve if $pve && $pve > $required_pve_version;
3592 return 1;
3593 };
a77a53ae 3594
4df98f2f
TL
3595 if ($kvm && !defined kvm_version()) {
3596 die "KVM virtualisation configured, but not available. Either disable in VM configuration"
3597 ." or enable in BIOS.\n";
d731ecbe 3598 }
bfcd9b7e 3599
3392d6ca 3600 my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf);
4d3f29ed 3601 my $hotplug_features = parse_hotplug_features(defined($conf->{hotplug}) ? $conf->{hotplug} : '1');
249c4a6c
AD
3602 my $use_old_bios_files = undef;
3603 ($use_old_bios_files, $machine_type) = qemu_use_old_bios_files($machine_type);
db656e5f 3604
74fe3d9a 3605 my $cmd = [];
83870398 3606 if ($conf->{affinity}) {
74fe3d9a 3607 push @$cmd, '/usr/bin/taskset', '--cpu-list', '--all-tasks', $conf->{affinity};
83870398
DB
3608 }
3609
1476b99f 3610 push @$cmd, $kvm_binary;
1e3baf05
DM
3611
3612 push @$cmd, '-id', $vmid;
3613
e4d4cda1
HR
3614 my $vmname = $conf->{name} || "vm$vmid";
3615
6884a7d7 3616 push @$cmd, '-name', "$vmname,debug-threads=on";
e4d4cda1 3617
27b25d03
SR
3618 push @$cmd, '-no-shutdown';
3619
1e3baf05
DM
3620 my $use_virtio = 0;
3621
d036e418 3622 my $qmpsocket = PVE::QemuServer::Helpers::qmp_socket($vmid);
378ad769 3623 push @$cmd, '-chardev', "socket,id=qmp,path=$qmpsocket,server=on,wait=off";
c971c4f2
AD
3624 push @$cmd, '-mon', "chardev=qmp,mode=control";
3625
2ea5fb7e 3626 if (min_version($machine_version, 2, 12)) {
b4496b9e 3627 push @$cmd, '-chardev', "socket,id=qmp-event,path=/var/run/qmeventd.sock,reconnect=5";
71bd73b5
DC
3628 push @$cmd, '-mon', "chardev=qmp-event,mode=control";
3629 }
1e3baf05 3630
d036e418 3631 push @$cmd, '-pidfile' , PVE::QemuServer::Helpers::pidfile_name($vmid);
19672434 3632
1e3baf05
DM
3633 push @$cmd, '-daemonize';
3634
2796e7d5 3635 if ($conf->{smbios1}) {
1f30ac3a
CE
3636 my $smbios_conf = parse_smbios1($conf->{smbios1});
3637 if ($smbios_conf->{base64}) {
3638 # Do not pass base64 flag to qemu
3639 delete $smbios_conf->{base64};
3640 my $smbios_string = "";
3641 foreach my $key (keys %$smbios_conf) {
3642 my $value;
3643 if ($key eq "uuid") {
3644 $value = $smbios_conf->{uuid}
3645 } else {
3646 $value = decode_base64($smbios_conf->{$key});
3647 }
3648 # qemu accepts any binary data, only commas need escaping by double comma
3649 $value =~ s/,/,,/g;
3650 $smbios_string .= "," . $key . "=" . $value if $value;
3651 }
3652 push @$cmd, '-smbios', "type=1" . $smbios_string;
3653 } else {
3654 push @$cmd, '-smbios', "type=1,$conf->{smbios1}";
3655 }
2796e7d5
DM
3656 }
3657
3edb45e7 3658 if ($conf->{bios} && $conf->{bios} eq 'ovmf') {
b7d80c79
FE
3659 my ($code_drive_str, $var_drive_str) =
3660 print_ovmf_drive_commandlines($conf, $storecfg, $vmid, $arch, $q35, $version_guard);
3661 push $cmd->@*, '-drive', $code_drive_str;
3662 push $cmd->@*, '-drive', $var_drive_str;
a783c78e
AD
3663 }
3664
483ceeab 3665 if ($q35) { # tell QEMU to load q35 config early
7583d156 3666 # we use different pcie-port hardware for qemu >= 4.0 for passthrough
2ea5fb7e 3667 if (min_version($machine_version, 4, 0)) {
7583d156
DC
3668 push @$devices, '-readconfig', '/usr/share/qemu-server/pve-q35-4.0.cfg';
3669 } else {
3670 push @$devices, '-readconfig', '/usr/share/qemu-server/pve-q35.cfg';
3671 }
3672 }
da8b4189 3673
cc181036
TL
3674 if (defined(my $fixups = qemu_created_version_fixups($conf, $forcemachine, $kvmver))) {
3675 push @$cmd, $fixups->@*;
3676 }
3677
844d8fa6
DC
3678 if ($conf->{vmgenid}) {
3679 push @$devices, '-device', 'vmgenid,guid='.$conf->{vmgenid};
3680 }
3681
d40e5e18 3682 # add usb controllers
4df98f2f 3683 my @usbcontrollers = PVE::QemuServer::USB::get_usb_controllers(
0cf8d56c 3684 $conf, $bridges, $arch, $machine_type, $machine_version);
d40e5e18 3685 push @$devices, @usbcontrollers if @usbcontrollers;
55655ebc 3686 my $vga = parse_vga($conf->{vga});
2fa3151e 3687
55655ebc
DC
3688 my $qxlnum = vga_conf_has_spice($conf->{vga});
3689 $vga->{type} = 'qxl' if $qxlnum;
2fa3151e 3690
55655ebc 3691 if (!$vga->{type}) {
869ad4a7
WB
3692 if ($arch eq 'aarch64') {
3693 $vga->{type} = 'virtio';
2ea5fb7e 3694 } elsif (min_version($machine_version, 2, 9)) {
55655ebc 3695 $vga->{type} = (!$winversion || $winversion >= 6) ? 'std' : 'cirrus';
a2a5cd64 3696 } else {
55655ebc 3697 $vga->{type} = ($winversion >= 6) ? 'std' : 'cirrus';
a2a5cd64 3698 }
5acbfe9e
DM
3699 }
3700
1e3baf05 3701 # enable absolute mouse coordinates (needed by vnc)
fa3b3ce0
TL
3702 my $tablet = $conf->{tablet};
3703 if (!defined($tablet)) {
5acbfe9e 3704 $tablet = $defaults->{tablet};
590e698c 3705 $tablet = 0 if $qxlnum; # disable for spice because it is not needed
55655ebc 3706 $tablet = 0 if $vga->{type} =~ m/^serial\d+$/; # disable if we use serial terminal (no vga card)
5acbfe9e
DM
3707 }
3708
d559309f
WB
3709 if ($tablet) {
3710 push @$devices, '-device', print_tabletdevice_full($conf, $arch) if $tablet;
3711 my $kbd = print_keyboarddevice_full($conf, $arch);
3712 push @$devices, '-device', $kbd if defined($kbd);
3713 }
b467f79a 3714
e5d611c3 3715 my $bootorder = device_bootorder($conf);
2141a802 3716
74c17b7a 3717 # host pci device passthrough
9b71c34d
DC
3718 my ($kvm_off, $gpu_passthrough, $legacy_igd, $pci_devices) = PVE::QemuServer::PCI::print_hostpci_devices(
3719 $vmid, $conf, $devices, $vga, $winversion, $bridges, $arch, $machine_type, $bootorder);
1e3baf05
DM
3720
3721 # usb devices
ae36393d 3722 my $usb_dev_features = {};
2ea5fb7e 3723 $usb_dev_features->{spice_usb3} = 1 if min_version($machine_version, 4, 0);
ae36393d 3724
4df98f2f 3725 my @usbdevices = PVE::QemuServer::USB::get_usb_devices(
0cf8d56c 3726 $conf, $usb_dev_features, $bootorder, $machine_version);
d40e5e18 3727 push @$devices, @usbdevices if @usbdevices;
2141a802 3728
1e3baf05 3729 # serial devices
bae179aa 3730 for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) {
fa3b3ce0
TL
3731 my $path = $conf->{"serial$i"} or next;
3732 if ($path eq 'socket') {
3733 my $socket = "/var/run/qemu-server/${vmid}.serial$i";
3734 push @$devices, '-chardev', "socket,id=serial$i,path=$socket,server=on,wait=off";
7bd9abd2 3735 # On aarch64, serial0 is the UART device. QEMU only allows
fa3b3ce0
TL
3736 # connecting UART devices via the '-serial' command line, as
3737 # the device has a fixed slot on the hardware...
3738 if ($arch eq 'aarch64' && $i == 0) {
3739 push @$devices, '-serial', "chardev:serial$i";
9f9d2fb2 3740 } else {
9f9d2fb2
DM
3741 push @$devices, '-device', "isa-serial,chardev=serial$i";
3742 }
fa3b3ce0
TL
3743 } else {
3744 die "no such serial device\n" if ! -c $path;
e35eb876 3745 push @$devices, '-chardev', "serial,id=serial$i,path=$path";
fa3b3ce0 3746 push @$devices, '-device', "isa-serial,chardev=serial$i";
34978be3 3747 }
1e3baf05
DM
3748 }
3749
3750 # parallel devices
1989a89c 3751 for (my $i = 0; $i < $MAX_PARALLEL_PORTS; $i++) {
34978be3 3752 if (my $path = $conf->{"parallel$i"}) {
19672434 3753 die "no such parallel device\n" if ! -c $path;
e35eb876 3754 my $devtype = $path =~ m!^/dev/usb/lp! ? 'serial' : 'parallel';
4c5dbaf6 3755 push @$devices, '-chardev', "$devtype,id=parallel$i,path=$path";
5bdcf937 3756 push @$devices, '-device', "isa-parallel,chardev=parallel$i";
34978be3 3757 }
1e3baf05
DM
3758 }
3759
b01de199 3760 if (min_version($machine_version, 4, 0) && (my $audio = conf_has_audio($conf))) {
2e7b5925 3761 my $audiopciaddr = print_pci_addr("audio0", $bridges, $arch, $machine_type);
1cc5ed1b 3762 my $audio_devs = audio_devs($audio, $audiopciaddr, $machine_version);
b01de199 3763 push @$devices, @$audio_devs;
2e7b5925 3764 }
19672434 3765
a55d0f71
FS
3766 # Add a TPM only if the VM is not a template,
3767 # to support backing up template VMs even if the TPM disk is write-protected.
3768 add_tpm_device($vmid, $devices, $conf) if (!PVE::QemuConfig->is_template($conf));
f9dde219 3769
1e3baf05
DM
3770 my $sockets = 1;
3771 $sockets = $conf->{smp} if $conf->{smp}; # old style - no longer iused
3772 $sockets = $conf->{sockets} if $conf->{sockets};
3773
3774 my $cores = $conf->{cores} || 1;
3bd18e48 3775
de9d1e55 3776 my $maxcpus = $sockets * $cores;
76267728 3777
de9d1e55 3778 my $vcpus = $conf->{vcpus} ? $conf->{vcpus} : $maxcpus;
76267728 3779
de9d1e55
AD
3780 my $allowed_vcpus = $cpuinfo->{cpus};
3781
483ceeab 3782 die "MAX $allowed_vcpus vcpus allowed per VM on this node\n" if ($allowed_vcpus < $maxcpus);
1e3baf05 3783
483ceeab 3784 if ($hotplug_features->{cpu} && min_version($machine_version, 2, 7)) {
69c81430
AD
3785 push @$cmd, '-smp', "1,sockets=$sockets,cores=$cores,maxcpus=$maxcpus";
3786 for (my $i = 2; $i <= $vcpus; $i++) {
3787 my $cpustr = print_cpu_device($conf,$i);
3788 push @$cmd, '-device', $cpustr;
3789 }
3790
3791 } else {
3792
3793 push @$cmd, '-smp', "$vcpus,sockets=$sockets,cores=$cores,maxcpus=$maxcpus";
3794 }
1e3baf05
DM
3795 push @$cmd, '-nodefaults';
3796
dbea4415 3797 push @$cmd, '-boot', "menu=on,strict=on,reboot-timeout=1000,splash=/usr/share/qemu-server/bootsplash.jpg";
1e3baf05 3798
0f704640 3799 push $machineFlags->@*, 'acpi=off' if defined($conf->{acpi}) && $conf->{acpi} == 0;
1e3baf05 3800
6b64503e 3801 push @$cmd, '-no-reboot' if defined($conf->{reboot}) && $conf->{reboot} == 0;
1e3baf05 3802
84902837 3803 if ($vga->{type} && $vga->{type} !~ m/^serial\d+$/ && $vga->{type} ne 'none'){
4df98f2f
TL
3804 push @$devices, '-device', print_vga_device(
3805 $conf, $vga, $arch, $machine_version, $machine_type, undef, $qxlnum, $bridges);
6f070e39
TL
3806
3807 push @$cmd, '-display', 'egl-headless,gl=core' if $vga->{type} eq 'virtio-gl'; # VIRGL
3808
d036e418 3809 my $socket = PVE::QemuServer::Helpers::vnc_socket($vmid);
378ad769 3810 push @$cmd, '-vnc', "unix:$socket,password=on";
b7be4ba9 3811 } else {
55655ebc 3812 push @$cmd, '-vga', 'none' if $vga->{type} eq 'none';
b7be4ba9
AD
3813 push @$cmd, '-nographic';
3814 }
3815
1e3baf05 3816 # time drift fix
6b64503e 3817 my $tdf = defined($conf->{tdf}) ? $conf->{tdf} : $defaults->{tdf};
8c559505 3818 my $useLocaltime = $conf->{localtime};
1e3baf05 3819
4317f69f
AD
3820 if ($winversion >= 5) { # windows
3821 $useLocaltime = 1 if !defined($conf->{localtime});
7a131888 3822
4317f69f
AD
3823 # use time drift fix when acpi is enabled
3824 if (!(defined($conf->{acpi}) && $conf->{acpi} == 0)) {
3825 $tdf = 1 if !defined($conf->{tdf});
462e8d19 3826 }
4317f69f 3827 }
462e8d19 3828
4317f69f
AD
3829 if ($winversion >= 6) {
3830 push @$globalFlags, 'kvm-pit.lost_tick_policy=discard';
17bacc21 3831 push @$machineFlags, 'hpet=off';
1e3baf05
DM
3832 }
3833
8c559505
DM
3834 push @$rtcFlags, 'driftfix=slew' if $tdf;
3835
2f6f002c 3836 if ($conf->{startdate} && $conf->{startdate} ne 'now') {
8c559505
DM
3837 push @$rtcFlags, "base=$conf->{startdate}";
3838 } elsif ($useLocaltime) {
3839 push @$rtcFlags, 'base=localtime';
3840 }
1e3baf05 3841
58c64ad5
SR
3842 if ($forcecpu) {
3843 push @$cmd, '-cpu', $forcecpu;
3844 } else {
2f6f002c 3845 push @$cmd, get_cpu_options($conf, $arch, $kvm, $kvm_off, $machine_version, $winversion, $gpu_passthrough);
58c64ad5 3846 }
519ed28c 3847
dafb728c 3848 PVE::QemuServer::Memory::config(
7f8c8087 3849 $conf, $vmid, $sockets, $cores, $hotplug_features->{memory}, $cmd);
370b05e7 3850
1e3baf05
DM
3851 push @$cmd, '-S' if $conf->{freeze};
3852
b20df606 3853 push @$cmd, '-k', $conf->{keyboard} if defined($conf->{keyboard});
1e3baf05 3854
48657158
MD
3855 my $guest_agent = parse_guest_agent($conf);
3856
3857 if ($guest_agent->{enabled}) {
d036e418 3858 my $qgasocket = PVE::QemuServer::Helpers::qmp_socket($vmid, 1);
378ad769 3859 push @$devices, '-chardev', "socket,path=$qgasocket,server=on,wait=off,id=qga0";
48657158 3860
60f03a11 3861 if (!$guest_agent->{type} || $guest_agent->{type} eq 'virtio') {
48657158
MD
3862 my $pciaddr = print_pci_addr("qga0", $bridges, $arch, $machine_type);
3863 push @$devices, '-device', "virtio-serial,id=qga0$pciaddr";
3864 push @$devices, '-device', 'virtserialport,chardev=qga0,name=org.qemu.guest_agent.0';
3865 } elsif ($guest_agent->{type} eq 'isa') {
3866 push @$devices, '-device', "isa-serial,chardev=qga0";
3867 }
ab6a046f
AD
3868 }
3869
e5d611c3
TL
3870 my $rng = $conf->{rng0} ? parse_rng($conf->{rng0}) : undef;
3871 if ($rng && $version_guard->(4, 1, 2)) {
05853188
SR
3872 check_rng_source($rng->{source});
3873
2cf61f33
SR
3874 my $max_bytes = $rng->{max_bytes} // $rng_fmt->{max_bytes}->{default};
3875 my $period = $rng->{period} // $rng_fmt->{period}->{default};
2cf61f33
SR
3876 my $limiter_str = "";
3877 if ($max_bytes) {
3878 $limiter_str = ",max-bytes=$max_bytes,period=$period";
3879 }
3880
2cf61f33 3881 my $rng_addr = print_pci_addr("rng0", $bridges, $arch, $machine_type);
2cf61f33
SR
3882 push @$devices, '-object', "rng-random,filename=$rng->{source},id=rng0";
3883 push @$devices, '-device', "virtio-rng-pci,rng=rng0$limiter_str$rng_addr";
3884 }
3885
1d794448 3886 my $spice_port;
2fa3151e 3887
f8ea1b30 3888 if ($qxlnum || $vga->{type} =~ /^virtio/) {
590e698c 3889 if ($qxlnum > 1) {
ac087616 3890 if ($winversion){
2f6f002c 3891 for (my $i = 1; $i < $qxlnum; $i++){
4df98f2f
TL
3892 push @$devices, '-device', print_vga_device(
3893 $conf, $vga, $arch, $machine_version, $machine_type, $i, $qxlnum, $bridges);
590e698c
DM
3894 }
3895 } else {
3896 # assume other OS works like Linux
55655ebc
DC
3897 my ($ram, $vram) = ("134217728", "67108864");
3898 if ($vga->{memory}) {
3899 $ram = PVE::Tools::convert_size($qxlnum*4*$vga->{memory}, 'mb' => 'b');
3900 $vram = PVE::Tools::convert_size($qxlnum*2*$vga->{memory}, 'mb' => 'b');
3901 }
3902 push @$cmd, '-global', "qxl-vga.ram_size=$ram";
3903 push @$cmd, '-global', "qxl-vga.vram_size=$vram";
2fa3151e
AD
3904 }
3905 }
3906
d559309f 3907 my $pciaddr = print_pci_addr("spice", $bridges, $arch, $machine_type);
95a4b4a9 3908
af0eba7e 3909 my $pfamily = PVE::Tools::get_host_address_family($nodename);
91152441
WB
3910 my @nodeaddrs = PVE::Tools::getaddrinfo_all('localhost', family => $pfamily);
3911 die "failed to get an ip address of type $pfamily for 'localhost'\n" if !@nodeaddrs;
4d316a63
AL
3912
3913 push @$devices, '-device', "virtio-serial,id=spice$pciaddr";
3914 push @$devices, '-chardev', "spicevmc,id=vdagent,name=vdagent";
3915 push @$devices, '-device', "virtserialport,chardev=vdagent,name=com.redhat.spice.0";
3916
91152441
WB
3917 my $localhost = PVE::Network::addr_to_ip($nodeaddrs[0]->{addr});
3918 $spice_port = PVE::Tools::next_spice_port($pfamily, $localhost);
943340a6 3919
4df98f2f
TL
3920 my $spice_enhancement_str = $conf->{spice_enhancements} // '';
3921 my $spice_enhancement = parse_property_string($spice_enhancements_fmt, $spice_enhancement_str);
caab114a
TL
3922 if ($spice_enhancement->{foldersharing}) {
3923 push @$devices, '-chardev', "spiceport,id=foldershare,name=org.spice-space.webdav.0";
3924 push @$devices, '-device', "virtserialport,chardev=foldershare,name=org.spice-space.webdav.0";
3925 }
c4df18db 3926
caab114a 3927 my $spice_opts = "tls-port=${spice_port},addr=$localhost,tls-ciphers=HIGH,seamless-migration=on";
4df98f2f
TL
3928 $spice_opts .= ",streaming-video=$spice_enhancement->{videostreaming}"
3929 if $spice_enhancement->{videostreaming};
3930
caab114a 3931 push @$devices, '-spice', "$spice_opts";
1011b570
DM
3932 }
3933
8d9ae0d2
DM
3934 # enable balloon by default, unless explicitly disabled
3935 if (!defined($conf->{balloon}) || $conf->{balloon}) {
3326ae19 3936 my $pciaddr = print_pci_addr("balloon0", $bridges, $arch, $machine_type);
c70e4ec3
AD
3937 my $ballooncmd = "virtio-balloon-pci,id=balloon0$pciaddr";
3938 $ballooncmd .= ",free-page-reporting=on" if min_version($machine_version, 6, 2);
3939 push @$devices, '-device', $ballooncmd;
8d9ae0d2 3940 }
1e3baf05 3941
0ea9541d
DM
3942 if ($conf->{watchdog}) {
3943 my $wdopts = parse_watchdog($conf->{watchdog});
3326ae19 3944 my $pciaddr = print_pci_addr("watchdog", $bridges, $arch, $machine_type);
0a40e8ea 3945 my $watchdog = $wdopts->{model} || 'i6300esb';
5bdcf937
AD
3946 push @$devices, '-device', "$watchdog$pciaddr";
3947 push @$devices, '-watchdog-action', $wdopts->{action} if $wdopts->{action};
0ea9541d
DM
3948 }
3949
1e3baf05 3950 my $vollist = [];
941e0c42 3951 my $scsicontroller = {};
26ee04b6 3952 my $ahcicontroller = {};
cdd20088 3953 my $scsihw = defined($conf->{scsihw}) ? $conf->{scsihw} : $defaults->{scsihw};
1e3baf05 3954
5881b913
DM
3955 # Add iscsi initiator name if available
3956 if (my $initiator = get_initiator_name()) {
3957 push @$devices, '-iscsi', "initiator-name=$initiator";
3958 }
3959
912792e2 3960 PVE::QemuConfig->foreach_volume($conf, sub {
1e3baf05
DM
3961 my ($ds, $drive) = @_;
3962
ff1a2432 3963 if (PVE::Storage::parse_volume_id($drive->{file}, 1)) {
3f11f0d7 3964 check_volume_storage_type($storecfg, $drive->{file});
1e3baf05 3965 push @$vollist, $drive->{file};
ff1a2432 3966 }
afdb31d5 3967
4dcce9ee
TL
3968 # ignore efidisk here, already added in bios/fw handling code above
3969 return if $drive->{interface} eq 'efidisk';
f9dde219
SR
3970 # similar for TPM
3971 return if $drive->{interface} eq 'tpmstate';
4dcce9ee 3972
1e3baf05 3973 $use_virtio = 1 if $ds =~ m/^virtio/;
3b408e82 3974
2141a802 3975 $drive->{bootindex} = $bootorder->{$ds} if $bootorder->{$ds};
3b408e82 3976
2f6f002c 3977 if ($drive->{interface} eq 'virtio'){
51f492cd
AD
3978 push @$cmd, '-object', "iothread,id=iothread-$ds" if $drive->{iothread};
3979 }
3980
2f6f002c 3981 if ($drive->{interface} eq 'scsi') {
cdd20088 3982
ee034f5c 3983 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $drive);
6731a4cf 3984
b8fb1c03
SR
3985 die "scsi$drive->{index}: machine version 4.1~pve2 or higher is required to use more than 14 SCSI disks\n"
3986 if $drive->{index} > 13 && !&$version_guard(4, 1, 2);
3987
3326ae19 3988 my $pciaddr = print_pci_addr("$controller_prefix$controller", $bridges, $arch, $machine_type);
a1b7d579 3989 my $scsihw_type = $scsihw =~ m/^virtio-scsi-single/ ? "virtio-scsi-pci" : $scsihw;
fc8b40fd
AD
3990
3991 my $iothread = '';
3992 if($conf->{scsihw} && $conf->{scsihw} eq "virtio-scsi-single" && $drive->{iothread}){
3993 $iothread .= ",iothread=iothread-$controller_prefix$controller";
3994 push @$cmd, '-object', "iothread,id=iothread-$controller_prefix$controller";
e7a5104d 3995 } elsif ($drive->{iothread}) {
d80ad18c
MH
3996 log_warn(
3997 "iothread is only valid with virtio disk or virtio-scsi-single controller, ignoring\n"
3998 );
fc8b40fd
AD
3999 }
4000
6e11f143
AD
4001 my $queues = '';
4002 if($conf->{scsihw} && $conf->{scsihw} eq "virtio-scsi-single" && $drive->{queues}){
4003 $queues = ",num_queues=$drive->{queues}";
370b05e7 4004 }
6e11f143 4005
4df98f2f
TL
4006 push @$devices, '-device', "$scsihw_type,id=$controller_prefix$controller$pciaddr$iothread$queues"
4007 if !$scsicontroller->{$controller};
cdd20088 4008 $scsicontroller->{$controller}=1;
2f6f002c 4009 }
3b408e82 4010
26ee04b6 4011 if ($drive->{interface} eq 'sata') {
2f6f002c 4012 my $controller = int($drive->{index} / $PVE::QemuServer::Drive::MAX_SATA_DISKS);
3326ae19 4013 my $pciaddr = print_pci_addr("ahci$controller", $bridges, $arch, $machine_type);
4df98f2f
TL
4014 push @$devices, '-device', "ahci,id=ahci$controller,multifunction=on$pciaddr"
4015 if !$ahcicontroller->{$controller};
2f6f002c 4016 $ahcicontroller->{$controller}=1;
26ee04b6 4017 }
46f58b5f 4018
5921764c
SR
4019 my $pbs_conf = $pbs_backing->{$ds};
4020 my $pbs_name = undef;
4021 if ($pbs_conf) {
4022 $pbs_name = "drive-$ds-pbs";
4023 push @$devices, '-blockdev', print_pbs_blockdev($pbs_conf, $pbs_name);
4024 }
4025
6d5673c3
SR
4026 my $drive_cmd = print_drive_commandline_full(
4027 $storecfg, $vmid, $drive, $pbs_name, min_version($kvmver, 6, 0));
3dc33a72
FG
4028
4029 # extra protection for templates, but SATA and IDE don't support it..
75748d44 4030 $drive_cmd .= ',readonly=on' if drive_is_read_only($conf, $drive);
4ef13a7f 4031
15b21acc 4032 push @$devices, '-drive',$drive_cmd;
4df98f2f
TL
4033 push @$devices, '-device', print_drivedevice_full(
4034 $storecfg, $conf, $vmid, $drive, $bridges, $arch, $machine_type);
1e3baf05
DM
4035 });
4036
cc4d6182 4037 for (my $i = 0; $i < $MAX_NETS; $i++) {
2141a802
SR
4038 my $netname = "net$i";
4039
4040 next if !$conf->{$netname};
4041 my $d = parse_net($conf->{$netname});
d0a86b24 4042 next if !$d;
4ddd2ca2 4043 # save the MAC addr here (could be auto-gen. in some odd setups) for FDB registering later?
1e3baf05 4044
d0a86b24 4045 $use_virtio = 1 if $d->{model} eq 'virtio';
1e3baf05 4046
2141a802 4047 $d->{bootindex} = $bootorder->{$netname} if $bootorder->{$netname};
1e3baf05 4048
2141a802 4049 my $netdevfull = print_netdev_full($vmid, $conf, $arch, $d, $netname);
d0a86b24 4050 push @$devices, '-netdev', $netdevfull;
5bdcf937 4051
d0a86b24 4052 my $netdevicefull = print_netdevice_full(
0c03a390 4053 $vmid, $conf, $d, $netname, $bridges, $use_old_bios_files, $arch, $machine_type, $machine_version);
4df98f2f 4054
d0a86b24 4055 push @$devices, '-device', $netdevicefull;
5bdcf937 4056 }
1e3baf05 4057
6dbcb073 4058 if ($conf->{ivshmem}) {
4df98f2f 4059 my $ivshmem = parse_property_string($ivshmem_fmt, $conf->{ivshmem});
e3c27a6a 4060
6dbcb073
DC
4061 my $bus;
4062 if ($q35) {
4063 $bus = print_pcie_addr("ivshmem");
4064 } else {
4065 $bus = print_pci_addr("ivshmem", $bridges, $arch, $machine_type);
4066 }
e3c27a6a
TL
4067
4068 my $ivshmem_name = $ivshmem->{name} // $vmid;
4069 my $path = '/dev/shm/pve-shm-' . $ivshmem_name;
4070
6dbcb073 4071 push @$devices, '-device', "ivshmem-plain,memdev=ivshmem$bus,";
4df98f2f
TL
4072 push @$devices, '-object', "memory-backend-file,id=ivshmem,share=on,mem-path=$path"
4073 .",size=$ivshmem->{size}M";
6dbcb073
DC
4074 }
4075
2513b862
DC
4076 # pci.4 is nested in pci.1
4077 $bridges->{1} = 1 if $bridges->{4};
4078
3326ae19
TL
4079 if (!$q35) { # add pci bridges
4080 if (min_version($machine_version, 2, 3)) {
fc79e813
AD
4081 $bridges->{1} = 1;
4082 $bridges->{2} = 1;
4083 }
6731a4cf 4084 $bridges->{3} = 1 if $scsihw =~ m/^virtio-scsi-single/;
2513b862
DC
4085 }
4086
4087 for my $k (sort {$b cmp $a} keys %$bridges) {
4088 next if $q35 && $k < 4; # q35.cfg already includes bridges up to 3
13d68979
SR
4089
4090 my $k_name = $k;
4091 if ($k == 2 && $legacy_igd) {
4092 $k_name = "$k-igd";
4093 }
3326ae19 4094 my $pciaddr = print_pci_addr("pci.$k_name", undef, $arch, $machine_type);
2513b862 4095 my $devstr = "pci-bridge,id=pci.$k,chassis_nr=$k$pciaddr";
3326ae19
TL
4096
4097 if ($q35) { # add after -readconfig pve-q35.cfg
2513b862
DC
4098 splice @$devices, 2, 0, '-device', $devstr;
4099 } else {
4100 unshift @$devices, '-device', $devstr if $k > 0;
f8e83f05 4101 }
19672434
DM
4102 }
4103
ac0077cc
SR
4104 if (!$kvm) {
4105 push @$machineFlags, 'accel=tcg';
4106 }
4107
e4263214 4108 push @$machineFlags, 'smm=off' if should_disable_smm($conf, $vga, $machine_type);
e5a6919c 4109
ac0077cc
SR
4110 my $machine_type_min = $machine_type;
4111 if ($add_pve_version) {
4112 $machine_type_min =~ s/\+pve\d+$//;
4113 $machine_type_min .= "+pve$required_pve_version";
4114 }
4115 push @$machineFlags, "type=${machine_type_min}";
4116
5bdcf937 4117 push @$cmd, @$devices;
2f6f002c
TL
4118 push @$cmd, '-rtc', join(',', @$rtcFlags) if scalar(@$rtcFlags);
4119 push @$cmd, '-machine', join(',', @$machineFlags) if scalar(@$machineFlags);
4120 push @$cmd, '-global', join(',', @$globalFlags) if scalar(@$globalFlags);
8c559505 4121
7ceade4c
DC
4122 if (my $vmstate = $conf->{vmstate}) {
4123 my $statepath = PVE::Storage::path($storecfg, $vmstate);
24d1f93a 4124 push @$vollist, $vmstate;
7ceade4c 4125 push @$cmd, '-loadstate', $statepath;
b85666cf 4126 print "activating and using '$vmstate' as vmstate\n";
7ceade4c
DC
4127 }
4128
85fcf79e
FG
4129 if (PVE::QemuConfig->is_template($conf)) {
4130 # needed to workaround base volumes being read-only
4131 push @$cmd, '-snapshot';
4132 }
4133
76350670
DC
4134 # add custom args
4135 if ($conf->{args}) {
4136 my $aa = PVE::Tools::split_args($conf->{args});
4137 push @$cmd, @$aa;
4138 }
4139
9b71c34d 4140 return wantarray ? ($cmd, $vollist, $spice_port, $pci_devices) : $cmd;
1e3baf05 4141}
19672434 4142
05853188
SR
4143sub check_rng_source {
4144 my ($source) = @_;
4145
4146 # mostly relevant for /dev/hwrng, but doesn't hurt to check others too
4147 die "cannot create VirtIO RNG device: source file '$source' doesn't exist\n"
4148 if ! -e $source;
4149
4150 my $rng_current = '/sys/devices/virtual/misc/hw_random/rng_current';
4151 if ($source eq '/dev/hwrng' && file_read_firstline($rng_current) eq 'none') {
4df98f2f
TL
4152 # Needs to abort, otherwise QEMU crashes on first rng access. Note that rng_current cannot
4153 # be changed to 'none' manually, so once the VM is past this point, it's no longer an issue.
4154 die "Cannot start VM with passed-through RNG device: '/dev/hwrng' exists, but"
4155 ." '$rng_current' is set to 'none'. Ensure that a compatible hardware-RNG is attached"
4156 ." to the host.\n";
05853188
SR
4157 }
4158}
4159
943340a6 4160sub spice_port {
1011b570 4161 my ($vmid) = @_;
943340a6 4162
0a13e08e 4163 my $res = mon_cmd($vmid, 'query-spice');
943340a6
DM
4164
4165 return $res->{'tls-port'} || $res->{'port'} || die "no spice port\n";
1011b570
DM
4166}
4167
86fdcfb2
DA
4168sub vm_devices_list {
4169 my ($vmid) = @_;
4170
0a13e08e 4171 my $res = mon_cmd($vmid, 'query-pci');
f721624b 4172 my $devices_to_check = [];
ceea9078
DM
4173 my $devices = {};
4174 foreach my $pcibus (@$res) {
f721624b
DC
4175 push @$devices_to_check, @{$pcibus->{devices}},
4176 }
4177
4178 while (@$devices_to_check) {
4179 my $to_check = [];
4180 for my $d (@$devices_to_check) {
4181 $devices->{$d->{'qdev_id'}} = 1 if $d->{'qdev_id'};
b3a3e929 4182 next if !$d->{'pci_bridge'} || !$d->{'pci_bridge'}->{devices};
f721624b
DC
4183
4184 $devices->{$d->{'qdev_id'}} += scalar(@{$d->{'pci_bridge'}->{devices}});
4185 push @$to_check, @{$d->{'pci_bridge'}->{devices}};
f78cc802 4186 }
f721624b 4187 $devices_to_check = $to_check;
f78cc802
AD
4188 }
4189
0a13e08e 4190 my $resblock = mon_cmd($vmid, 'query-block');
f78cc802
AD
4191 foreach my $block (@$resblock) {
4192 if($block->{device} =~ m/^drive-(\S+)/){
4193 $devices->{$1} = 1;
1dc4f496
DM
4194 }
4195 }
86fdcfb2 4196
0a13e08e 4197 my $resmice = mon_cmd($vmid, 'query-mice');
3d7389fe
DM
4198 foreach my $mice (@$resmice) {
4199 if ($mice->{name} eq 'QEMU HID Tablet') {
4200 $devices->{tablet} = 1;
4201 last;
4202 }
4203 }
4204
deb091c5
DC
4205 # for usb devices there is no query-usb
4206 # but we can iterate over the entries in
4207 # qom-list path=/machine/peripheral
0a13e08e 4208 my $resperipheral = mon_cmd($vmid, 'qom-list', path => '/machine/peripheral');
deb091c5 4209 foreach my $per (@$resperipheral) {
c60cad61 4210 if ($per->{name} =~ m/^usb(?:redirdev)?\d+$/) {
deb091c5
DC
4211 $devices->{$per->{name}} = 1;
4212 }
4213 }
4214
1dc4f496 4215 return $devices;
86fdcfb2
DA
4216}
4217
ec21aa11 4218sub vm_deviceplug {
d559309f 4219 my ($storecfg, $conf, $vmid, $deviceid, $device, $arch, $machine_type) = @_;
ae57f6b3 4220
3392d6ca 4221 my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf);
db656e5f 4222
95d6343b
DA
4223 my $devices_list = vm_devices_list($vmid);
4224 return 1 if defined($devices_list->{$deviceid});
4225
4df98f2f
TL
4226 # add PCI bridge if we need it for the device
4227 qemu_add_pci_bridge($storecfg, $conf, $vmid, $deviceid, $arch, $machine_type);
fee46675 4228
3d7389fe 4229 if ($deviceid eq 'tablet') {
d559309f 4230 qemu_deviceadd($vmid, print_tabletdevice_full($conf, $arch));
d559309f 4231 } elsif ($deviceid eq 'keyboard') {
d559309f 4232 qemu_deviceadd($vmid, print_keyboarddevice_full($conf, $arch));
c60cad61
DC
4233 } elsif ($deviceid =~ m/^usbredirdev(\d+)$/) {
4234 my $id = $1;
4235 qemu_spice_usbredir_chardev_add($vmid, "usbredirchardev$id");
4236 qemu_deviceadd($vmid, PVE::QemuServer::USB::print_spice_usbdevice($id, "xhci", $id + 1));
4eb68604 4237 } elsif ($deviceid =~ m/^usb(\d+)$/) {
c60cad61 4238 qemu_deviceadd($vmid, PVE::QemuServer::USB::print_usbdevice_full($conf, $deviceid, $device, {}, $1 + 1));
fee46675 4239 } elsif ($deviceid =~ m/^(virtio)(\d+)$/) {
22de899a
AD
4240 qemu_iothread_add($vmid, $deviceid, $device);
4241
3326ae19
TL
4242 qemu_driveadd($storecfg, $vmid, $device);
4243 my $devicefull = print_drivedevice_full($storecfg, $conf, $vmid, $device, undef, $arch, $machine_type);
fee46675 4244
3326ae19 4245 qemu_deviceadd($vmid, $devicefull);
fee46675
DM
4246 eval { qemu_deviceaddverify($vmid, $deviceid); };
4247 if (my $err = $@) {
63c2da2f
DM
4248 eval { qemu_drivedel($vmid, $deviceid); };
4249 warn $@ if $@;
fee46675 4250 die $err;
5e5dcb73 4251 }
2733141c 4252 } elsif ($deviceid =~ m/^(virtioscsi|scsihw)(\d+)$/) {
3326ae19
TL
4253 my $scsihw = defined($conf->{scsihw}) ? $conf->{scsihw} : "lsi";
4254 my $pciaddr = print_pci_addr($deviceid, undef, $arch, $machine_type);
a1b7d579 4255 my $scsihw_type = $scsihw eq 'virtio-scsi-single' ? "virtio-scsi-pci" : $scsihw;
2733141c 4256
3326ae19 4257 my $devicefull = "$scsihw_type,id=$deviceid$pciaddr";
fee46675 4258
fc8b40fd
AD
4259 if($deviceid =~ m/^virtioscsi(\d+)$/ && $device->{iothread}) {
4260 qemu_iothread_add($vmid, $deviceid, $device);
4261 $devicefull .= ",iothread=iothread-$deviceid";
4262 }
4263
6e11f143
AD
4264 if($deviceid =~ m/^virtioscsi(\d+)$/ && $device->{queues}) {
4265 $devicefull .= ",num_queues=$device->{queues}";
4266 }
4267
3326ae19
TL
4268 qemu_deviceadd($vmid, $devicefull);
4269 qemu_deviceaddverify($vmid, $deviceid);
fee46675 4270 } elsif ($deviceid =~ m/^(scsi)(\d+)$/) {
d559309f 4271 qemu_findorcreatescsihw($storecfg,$conf, $vmid, $device, $arch, $machine_type);
fee46675 4272 qemu_driveadd($storecfg, $vmid, $device);
a1b7d579 4273
acfc6ef8 4274 my $devicefull = print_drivedevice_full($storecfg, $conf, $vmid, $device, undef, $arch, $machine_type);
fee46675
DM
4275 eval { qemu_deviceadd($vmid, $devicefull); };
4276 if (my $err = $@) {
63c2da2f
DM
4277 eval { qemu_drivedel($vmid, $deviceid); };
4278 warn $@ if $@;
fee46675 4279 die $err;
a4f091a0 4280 }
fee46675 4281 } elsif ($deviceid =~ m/^(net)(\d+)$/) {
d1c1af4b 4282 return if !qemu_netdevadd($vmid, $conf, $arch, $device, $deviceid);
8718099c 4283
3392d6ca 4284 my $machine_type = PVE::QemuServer::Machine::qemu_machine_pxe($vmid, $conf);
0c03a390 4285 my $machine_version = PVE::QemuServer::Machine::extract_version($machine_type);
95d3be58
DC
4286 my $use_old_bios_files = undef;
4287 ($use_old_bios_files, $machine_type) = qemu_use_old_bios_files($machine_type);
8718099c 4288
4df98f2f 4289 my $netdevicefull = print_netdevice_full(
0c03a390 4290 $vmid, $conf, $device, $deviceid, undef, $use_old_bios_files, $arch, $machine_type, $machine_version);
95d3be58 4291 qemu_deviceadd($vmid, $netdevicefull);
79046fd1
DC
4292 eval {
4293 qemu_deviceaddverify($vmid, $deviceid);
4294 qemu_set_link_status($vmid, $deviceid, !$device->{link_down});
4295 };
fee46675
DM
4296 if (my $err = $@) {
4297 eval { qemu_netdevdel($vmid, $deviceid); };
4298 warn $@ if $@;
4299 die $err;
95d3be58 4300 }
fee46675 4301 } elsif (!$q35 && $deviceid =~ m/^(pci\.)(\d+)$/) {
40f28a9f 4302 my $bridgeid = $2;
d559309f 4303 my $pciaddr = print_pci_addr($deviceid, undef, $arch, $machine_type);
40f28a9f 4304 my $devicefull = "pci-bridge,id=pci.$bridgeid,chassis_nr=$bridgeid$pciaddr";
a1b7d579 4305
40f28a9f 4306 qemu_deviceadd($vmid, $devicefull);
fee46675 4307 qemu_deviceaddverify($vmid, $deviceid);
fee46675 4308 } else {
a1b7d579 4309 die "can't hotplug device '$deviceid'\n";
40f28a9f
AD
4310 }
4311
5e5dcb73 4312 return 1;
a4dea331
DA
4313}
4314
3eec5767 4315# fixme: this should raise exceptions on error!
ec21aa11 4316sub vm_deviceunplug {
f19d1c47 4317 my ($vmid, $conf, $deviceid) = @_;
873c2d69 4318
95d6343b
DA
4319 my $devices_list = vm_devices_list($vmid);
4320 return 1 if !defined($devices_list->{$deviceid});
4321
2141a802
SR
4322 my $bootdisks = PVE::QemuServer::Drive::get_bootdisks($conf);
4323 die "can't unplug bootdisk '$deviceid'\n" if grep {$_ eq $deviceid} @$bootdisks;
63c2da2f 4324
c60cad61 4325 if ($deviceid eq 'tablet' || $deviceid eq 'keyboard' || $deviceid eq 'xhci') {
3d7389fe 4326 qemu_devicedel($vmid, $deviceid);
c60cad61
DC
4327 } elsif ($deviceid =~ m/^usbredirdev\d+$/) {
4328 qemu_devicedel($vmid, $deviceid);
4329 qemu_devicedelverify($vmid, $deviceid);
4eb68604 4330 } elsif ($deviceid =~ m/^usb\d+$/) {
c60cad61
DC
4331 qemu_devicedel($vmid, $deviceid);
4332 qemu_devicedelverify($vmid, $deviceid);
63c2da2f 4333 } elsif ($deviceid =~ m/^(virtio)(\d+)$/) {
9a66c311 4334 my $device = parse_drive($deviceid, $conf->{$deviceid});
f19d1c47 4335
a8d0fec3
TL
4336 qemu_devicedel($vmid, $deviceid);
4337 qemu_devicedelverify($vmid, $deviceid);
4338 qemu_drivedel($vmid, $deviceid);
9a66c311 4339 qemu_iothread_del($vmid, $deviceid, $device);
2733141c 4340 } elsif ($deviceid =~ m/^(virtioscsi|scsihw)(\d+)$/) {
63c2da2f 4341 qemu_devicedel($vmid, $deviceid);
8ce30dde 4342 qemu_devicedelverify($vmid, $deviceid);
63c2da2f 4343 } elsif ($deviceid =~ m/^(scsi)(\d+)$/) {
9a66c311 4344 my $device = parse_drive($deviceid, $conf->{$deviceid});
cfc817c7 4345
a8d0fec3 4346 qemu_devicedel($vmid, $deviceid);
52b361af 4347 qemu_devicedelverify($vmid, $deviceid);
a8d0fec3 4348 qemu_drivedel($vmid, $deviceid);
a1b7d579 4349 qemu_deletescsihw($conf, $vmid, $deviceid);
8ce30dde 4350
9a66c311
FG
4351 qemu_iothread_del($vmid, "virtioscsi$device->{index}", $device)
4352 if $conf->{scsihw} && ($conf->{scsihw} eq 'virtio-scsi-single');
63c2da2f 4353 } elsif ($deviceid =~ m/^(net)(\d+)$/) {
a8d0fec3
TL
4354 qemu_devicedel($vmid, $deviceid);
4355 qemu_devicedelverify($vmid, $deviceid);
4356 qemu_netdevdel($vmid, $deviceid);
63c2da2f
DM
4357 } else {
4358 die "can't unplug device '$deviceid'\n";
2630d2a9
DA
4359 }
4360
5e5dcb73
DA
4361 return 1;
4362}
4363
c60cad61
DC
4364sub qemu_spice_usbredir_chardev_add {
4365 my ($vmid, $id) = @_;
4366
4367 mon_cmd($vmid, "chardev-add" , (
4368 id => $id,
4369 backend => {
4370 type => 'spicevmc',
4371 data => {
4372 type => "usbredir",
4373 },
4374 },
4375 ));
4376}
4377
22de899a 4378sub qemu_iothread_add {
a8d0fec3 4379 my ($vmid, $deviceid, $device) = @_;
22de899a
AD
4380
4381 if ($device->{iothread}) {
4382 my $iothreads = vm_iothreads_list($vmid);
4383 qemu_objectadd($vmid, "iothread-$deviceid", "iothread") if !$iothreads->{"iothread-$deviceid"};
4384 }
4385}
4386
4387sub qemu_iothread_del {
a8d0fec3 4388 my ($vmid, $deviceid, $device) = @_;
22de899a 4389
22de899a
AD
4390 if ($device->{iothread}) {
4391 my $iothreads = vm_iothreads_list($vmid);
4392 qemu_objectdel($vmid, "iothread-$deviceid") if $iothreads->{"iothread-$deviceid"};
4393 }
4394}
4395
5e5dcb73 4396sub qemu_driveadd {
fee46675 4397 my ($storecfg, $vmid, $device) = @_;
5e5dcb73 4398
6d5673c3
SR
4399 my $kvmver = get_running_qemu_version($vmid);
4400 my $io_uring = min_version($kvmver, 6, 0);
4401 my $drive = print_drive_commandline_full($storecfg, $vmid, $device, undef, $io_uring);
7a69fc3c 4402 $drive =~ s/\\/\\\\/g;
0a13e08e 4403 my $ret = PVE::QemuServer::Monitor::hmp_cmd($vmid, "drive_add auto \"$drive\"");
fee46675 4404
5e5dcb73 4405 # If the command succeeds qemu prints: "OK"
fee46675
DM
4406 return 1 if $ret =~ m/OK/s;
4407
4408 die "adding drive failed: $ret\n";
5e5dcb73 4409}
afdb31d5 4410
5e5dcb73 4411sub qemu_drivedel {
a8d0fec3 4412 my ($vmid, $deviceid) = @_;
873c2d69 4413
0a13e08e 4414 my $ret = PVE::QemuServer::Monitor::hmp_cmd($vmid, "drive_del drive-$deviceid");
5e5dcb73 4415 $ret =~ s/^\s+//;
a1b7d579 4416
63c2da2f 4417 return 1 if $ret eq "";
a1b7d579 4418
63c2da2f 4419 # NB: device not found errors mean the drive was auto-deleted and we ignore the error
a1b7d579
DM
4420 return 1 if $ret =~ m/Device \'.*?\' not found/s;
4421
63c2da2f 4422 die "deleting drive $deviceid failed : $ret\n";
5e5dcb73 4423}
f19d1c47 4424
5e5dcb73 4425sub qemu_deviceaddverify {
fee46675 4426 my ($vmid, $deviceid) = @_;
873c2d69 4427
5e5dcb73
DA
4428 for (my $i = 0; $i <= 5; $i++) {
4429 my $devices_list = vm_devices_list($vmid);
4430 return 1 if defined($devices_list->{$deviceid});
4431 sleep 1;
afdb31d5 4432 }
fee46675
DM
4433
4434 die "error on hotplug device '$deviceid'\n";
5e5dcb73 4435}
afdb31d5 4436
5e5dcb73
DA
4437
4438sub qemu_devicedelverify {
63c2da2f
DM
4439 my ($vmid, $deviceid) = @_;
4440
a1b7d579 4441 # need to verify that the device is correctly removed as device_del
63c2da2f 4442 # is async and empty return is not reliable
5e5dcb73 4443
5e5dcb73
DA
4444 for (my $i = 0; $i <= 5; $i++) {
4445 my $devices_list = vm_devices_list($vmid);
4446 return 1 if !defined($devices_list->{$deviceid});
4447 sleep 1;
afdb31d5 4448 }
63c2da2f
DM
4449
4450 die "error on hot-unplugging device '$deviceid'\n";
873c2d69
DA
4451}
4452
cdd20088 4453sub qemu_findorcreatescsihw {
d559309f 4454 my ($storecfg, $conf, $vmid, $device, $arch, $machine_type) = @_;
cfc817c7 4455
ee034f5c 4456 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $device);
2733141c
AD
4457
4458 my $scsihwid="$controller_prefix$controller";
cfc817c7
DA
4459 my $devices_list = vm_devices_list($vmid);
4460
a8d0fec3 4461 if (!defined($devices_list->{$scsihwid})) {
d559309f 4462 vm_deviceplug($storecfg, $conf, $vmid, $scsihwid, $device, $arch, $machine_type);
cfc817c7 4463 }
fee46675 4464
cfc817c7
DA
4465 return 1;
4466}
4467
8ce30dde
AD
4468sub qemu_deletescsihw {
4469 my ($conf, $vmid, $opt) = @_;
4470
4471 my $device = parse_drive($opt, $conf->{$opt});
4472
a1511b3c 4473 if ($conf->{scsihw} && ($conf->{scsihw} eq 'virtio-scsi-single')) {
2733141c
AD
4474 vm_deviceunplug($vmid, $conf, "virtioscsi$device->{index}");
4475 return 1;
4476 }
4477
ee034f5c 4478 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $device);
8ce30dde
AD
4479
4480 my $devices_list = vm_devices_list($vmid);
4481 foreach my $opt (keys %{$devices_list}) {
e0fd2b2f
FE
4482 if (is_valid_drivename($opt)) {
4483 my $drive = parse_drive($opt, $conf->{$opt});
a8d0fec3 4484 if ($drive->{interface} eq 'scsi' && $drive->{index} < (($maxdev-1)*($controller+1))) {
8ce30dde
AD
4485 return 1;
4486 }
4487 }
4488 }
4489
4490 my $scsihwid="scsihw$controller";
4491
4492 vm_deviceunplug($vmid, $conf, $scsihwid);
4493
4494 return 1;
4495}
4496
281fedb3 4497sub qemu_add_pci_bridge {
d559309f 4498 my ($storecfg, $conf, $vmid, $device, $arch, $machine_type) = @_;
40f28a9f
AD
4499
4500 my $bridges = {};
281fedb3
DM
4501
4502 my $bridgeid;
4503
d559309f 4504 print_pci_addr($device, $bridges, $arch, $machine_type);
40f28a9f
AD
4505
4506 while (my ($k, $v) = each %$bridges) {
4507 $bridgeid = $k;
4508 }
fee46675 4509 return 1 if !defined($bridgeid) || $bridgeid < 1;
281fedb3 4510
40f28a9f
AD
4511 my $bridge = "pci.$bridgeid";
4512 my $devices_list = vm_devices_list($vmid);
4513
281fedb3 4514 if (!defined($devices_list->{$bridge})) {
d559309f 4515 vm_deviceplug($storecfg, $conf, $vmid, $bridge, $arch, $machine_type);
40f28a9f 4516 }
281fedb3 4517
40f28a9f
AD
4518 return 1;
4519}
4520
25088687
DM
4521sub qemu_set_link_status {
4522 my ($vmid, $device, $up) = @_;
4523
0a13e08e 4524 mon_cmd($vmid, "set_link", name => $device,
25088687
DM
4525 up => $up ? JSON::true : JSON::false);
4526}
4527
2630d2a9 4528sub qemu_netdevadd {
d559309f 4529 my ($vmid, $conf, $arch, $device, $deviceid) = @_;
2630d2a9 4530
d559309f 4531 my $netdev = print_netdev_full($vmid, $conf, $arch, $device, $deviceid, 1);
73aa03b8 4532 my %options = split(/[=,]/, $netdev);
2630d2a9 4533
bf5aef9b
DC
4534 if (defined(my $vhost = $options{vhost})) {
4535 $options{vhost} = JSON::boolean(PVE::JSONSchema::parse_boolean($vhost));
4536 }
4537
4538 if (defined(my $queues = $options{queues})) {
4539 $options{queues} = $queues + 0;
4540 }
4541
0a13e08e 4542 mon_cmd($vmid, "netdev_add", %options);
73aa03b8 4543 return 1;
2630d2a9
DA
4544}
4545
4546sub qemu_netdevdel {
4547 my ($vmid, $deviceid) = @_;
4548
0a13e08e 4549 mon_cmd($vmid, "netdev_del", id => $deviceid);
2630d2a9
DA
4550}
4551
16521d63 4552sub qemu_usb_hotplug {
d559309f 4553 my ($storecfg, $conf, $vmid, $deviceid, $device, $arch, $machine_type) = @_;
16521d63
DC
4554
4555 return if !$device;
4556
4557 # remove the old one first
4558 vm_deviceunplug($vmid, $conf, $deviceid);
4559
4560 # check if xhci controller is necessary and available
c60cad61 4561 my $devicelist = vm_devices_list($vmid);
16521d63 4562
c60cad61
DC
4563 if (!$devicelist->{xhci}) {
4564 my $pciaddr = print_pci_addr("xhci", undef, $arch, $machine_type);
4565 qemu_deviceadd($vmid, PVE::QemuServer::USB::print_qemu_xhci_controller($pciaddr));
16521d63 4566 }
c60cad61 4567
16521d63 4568 # add the new one
0cf8d56c 4569 vm_deviceplug($storecfg, $conf, $vmid, $deviceid, $device, $arch, $machine_type);
16521d63
DC
4570}
4571
838776ab 4572sub qemu_cpu_hotplug {
8edc9c08 4573 my ($vmid, $conf, $vcpus) = @_;
838776ab 4574
3392d6ca 4575 my $machine_type = PVE::QemuServer::Machine::get_current_qemu_machine($vmid);
1e881b75 4576
8edc9c08
AD
4577 my $sockets = 1;
4578 $sockets = $conf->{smp} if $conf->{smp}; # old style - no longer iused
4579 $sockets = $conf->{sockets} if $conf->{sockets};
4580 my $cores = $conf->{cores} || 1;
4581 my $maxcpus = $sockets * $cores;
838776ab 4582
8edc9c08 4583 $vcpus = $maxcpus if !$vcpus;
3a11fadb 4584
8edc9c08
AD
4585 die "you can't add more vcpus than maxcpus\n"
4586 if $vcpus > $maxcpus;
3a11fadb 4587
8edc9c08 4588 my $currentvcpus = $conf->{vcpus} || $maxcpus;
1e881b75 4589
eba3e64d 4590 if ($vcpus < $currentvcpus) {
1e881b75 4591
2ea5fb7e 4592 if (PVE::QemuServer::Machine::machine_version($machine_type, 2, 7)) {
1e881b75
AD
4593
4594 for (my $i = $currentvcpus; $i > $vcpus; $i--) {
4595 qemu_devicedel($vmid, "cpu$i");
4596 my $retry = 0;
4597 my $currentrunningvcpus = undef;
4598 while (1) {
65af8c31 4599 $currentrunningvcpus = mon_cmd($vmid, "query-cpus-fast");
1e881b75 4600 last if scalar(@{$currentrunningvcpus}) == $i-1;
961af8a3 4601 raise_param_exc({ vcpus => "error unplugging cpu$i" }) if $retry > 5;
1e881b75
AD
4602 $retry++;
4603 sleep 1;
4604 }
4605 #update conf after each succesfull cpu unplug
4606 $conf->{vcpus} = scalar(@{$currentrunningvcpus});
4607 PVE::QemuConfig->write_config($vmid, $conf);
4608 }
4609 } else {
961af8a3 4610 die "cpu hot-unplugging requires qemu version 2.7 or higher\n";
1e881b75
AD
4611 }
4612
4613 return;
4614 }
838776ab 4615
65af8c31 4616 my $currentrunningvcpus = mon_cmd($vmid, "query-cpus-fast");
961af8a3 4617 die "vcpus in running vm does not match its configuration\n"
8edc9c08 4618 if scalar(@{$currentrunningvcpus}) != $currentvcpus;
838776ab 4619
2ea5fb7e 4620 if (PVE::QemuServer::Machine::machine_version($machine_type, 2, 7)) {
eba3e64d
AD
4621
4622 for (my $i = $currentvcpus+1; $i <= $vcpus; $i++) {
4623 my $cpustr = print_cpu_device($conf, $i);
4624 qemu_deviceadd($vmid, $cpustr);
4625
4626 my $retry = 0;
4627 my $currentrunningvcpus = undef;
4628 while (1) {
65af8c31 4629 $currentrunningvcpus = mon_cmd($vmid, "query-cpus-fast");
eba3e64d 4630 last if scalar(@{$currentrunningvcpus}) == $i;
961af8a3 4631 raise_param_exc({ vcpus => "error hotplugging cpu$i" }) if $retry > 10;
eba3e64d
AD
4632 sleep 1;
4633 $retry++;
4634 }
4635 #update conf after each succesfull cpu hotplug
4636 $conf->{vcpus} = scalar(@{$currentrunningvcpus});
4637 PVE::QemuConfig->write_config($vmid, $conf);
4638 }
4639 } else {
4640
4641 for (my $i = $currentvcpus; $i < $vcpus; $i++) {
0a13e08e 4642 mon_cmd($vmid, "cpu-add", id => int($i));
eba3e64d 4643 }
838776ab
AD
4644 }
4645}
4646
affd2f88 4647sub qemu_block_set_io_throttle {
277ca170
WB
4648 my ($vmid, $deviceid,
4649 $bps, $bps_rd, $bps_wr, $iops, $iops_rd, $iops_wr,
9196a8ec
WB
4650 $bps_max, $bps_rd_max, $bps_wr_max, $iops_max, $iops_rd_max, $iops_wr_max,
4651 $bps_max_length, $bps_rd_max_length, $bps_wr_max_length,
4652 $iops_max_length, $iops_rd_max_length, $iops_wr_max_length) = @_;
affd2f88 4653
f3f323a3
AD
4654 return if !check_running($vmid) ;
4655
0a13e08e 4656 mon_cmd($vmid, "block_set_io_throttle", device => $deviceid,
277ca170
WB
4657 bps => int($bps),
4658 bps_rd => int($bps_rd),
4659 bps_wr => int($bps_wr),
4660 iops => int($iops),
4661 iops_rd => int($iops_rd),
4662 iops_wr => int($iops_wr),
4663 bps_max => int($bps_max),
4664 bps_rd_max => int($bps_rd_max),
4665 bps_wr_max => int($bps_wr_max),
4666 iops_max => int($iops_max),
4667 iops_rd_max => int($iops_rd_max),
9196a8ec
WB
4668 iops_wr_max => int($iops_wr_max),
4669 bps_max_length => int($bps_max_length),
4670 bps_rd_max_length => int($bps_rd_max_length),
4671 bps_wr_max_length => int($bps_wr_max_length),
4672 iops_max_length => int($iops_max_length),
4673 iops_rd_max_length => int($iops_rd_max_length),
4674 iops_wr_max_length => int($iops_wr_max_length),
277ca170 4675 );
f3f323a3 4676
affd2f88
AD
4677}
4678
c1175c92
AD
4679sub qemu_block_resize {
4680 my ($vmid, $deviceid, $storecfg, $volid, $size) = @_;
4681
ed221350 4682 my $running = check_running($vmid);
c1175c92 4683
2e4357c5 4684 PVE::Storage::volume_resize($storecfg, $volid, $size, $running);
c1175c92
AD
4685
4686 return if !$running;
4687
375db731
FE
4688 my $padding = (1024 - $size % 1024) % 1024;
4689 $size = $size + $padding;
4690
190c8461
SR
4691 mon_cmd(
4692 $vmid,
4693 "block_resize",
4694 device => $deviceid,
4695 size => int($size),
4696 timeout => 60,
4697 );
c1175c92
AD
4698}
4699
1ab0057c
AD
4700sub qemu_volume_snapshot {
4701 my ($vmid, $deviceid, $storecfg, $volid, $snap) = @_;
4702
ed221350 4703 my $running = check_running($vmid);
1ab0057c 4704
9d83932d 4705 if ($running && do_snapshots_with_qemu($storecfg, $volid, $deviceid)) {
0a13e08e 4706 mon_cmd($vmid, 'blockdev-snapshot-internal-sync', device => $deviceid, name => $snap);
e5eaa028
WL
4707 } else {
4708 PVE::Storage::volume_snapshot($storecfg, $volid, $snap);
4709 }
1ab0057c
AD
4710}
4711
fc46aff9
AD
4712sub qemu_volume_snapshot_delete {
4713 my ($vmid, $deviceid, $storecfg, $volid, $snap) = @_;
4714
ed221350 4715 my $running = check_running($vmid);
fc46aff9 4716
a2f1554b
AD
4717 if($running) {
4718
4719 $running = undef;
4720 my $conf = PVE::QemuConfig->load_config($vmid);
912792e2 4721 PVE::QemuConfig->foreach_volume($conf, sub {
a2f1554b
AD
4722 my ($ds, $drive) = @_;
4723 $running = 1 if $drive->{file} eq $volid;
4724 });
4725 }
4726
9d83932d 4727 if ($running && do_snapshots_with_qemu($storecfg, $volid, $deviceid)) {
0a13e08e 4728 mon_cmd($vmid, 'blockdev-snapshot-delete-internal-sync', device => $deviceid, name => $snap);
1ef7592f
AD
4729 } else {
4730 PVE::Storage::volume_snapshot_delete($storecfg, $volid, $snap, $running);
4731 }
fc46aff9
AD
4732}
4733
264e519f 4734sub set_migration_caps {
27a5be53 4735 my ($vmid, $savevm) = @_;
a89fded1 4736
acc10e51
SR
4737 my $qemu_support = eval { mon_cmd($vmid, "query-proxmox-support") };
4738
27a5be53
SR
4739 my $bitmap_prop = $savevm ? 'pbs-dirty-bitmap-savevm' : 'pbs-dirty-bitmap-migration';
4740 my $dirty_bitmaps = $qemu_support->{$bitmap_prop} ? 1 : 0;
4741
8b8345f3 4742 my $cap_ref = [];
a89fded1
AD
4743
4744 my $enabled_cap = {
8b8345f3 4745 "auto-converge" => 1,
0b0a47e8 4746 "xbzrle" => 1,
8b8345f3
DM
4747 "x-rdma-pin-all" => 0,
4748 "zero-blocks" => 0,
acc10e51 4749 "compress" => 0,
27a5be53 4750 "dirty-bitmaps" => $dirty_bitmaps,
a89fded1
AD
4751 };
4752
0a13e08e 4753 my $supported_capabilities = mon_cmd($vmid, "query-migrate-capabilities");
a89fded1 4754
8b8345f3 4755 for my $supported_capability (@$supported_capabilities) {
b463a3ce
SP
4756 push @$cap_ref, {
4757 capability => $supported_capability->{capability},
22430fa2
DM
4758 state => $enabled_cap->{$supported_capability->{capability}} ? JSON::true : JSON::false,
4759 };
a89fded1
AD
4760 }
4761
0a13e08e 4762 mon_cmd($vmid, "migrate-set-capabilities", capabilities => $cap_ref);
8b8345f3 4763}
a89fded1 4764
912792e2 4765sub foreach_volid {
0b7a0b78 4766 my ($conf, $func, @param) = @_;
912792e2
FE
4767
4768 my $volhash = {};
4769
4770 my $test_volid = sub {
6328c554 4771 my ($key, $drive, $snapname, $pending) = @_;
912792e2 4772
ae180b8f 4773 my $volid = $drive->{file};
912792e2
FE
4774 return if !$volid;
4775
4776 $volhash->{$volid}->{cdrom} //= 1;
ae180b8f 4777 $volhash->{$volid}->{cdrom} = 0 if !drive_is_cdrom($drive);
912792e2 4778
ae180b8f 4779 my $replicate = $drive->{replicate} // 1;
912792e2
FE
4780 $volhash->{$volid}->{replicate} //= 0;
4781 $volhash->{$volid}->{replicate} = 1 if $replicate;
4782
4783 $volhash->{$volid}->{shared} //= 0;
ae180b8f 4784 $volhash->{$volid}->{shared} = 1 if $drive->{shared};
912792e2 4785
6e9c4929
AL
4786 $volhash->{$volid}->{is_unused} //= 0;
4787 $volhash->{$volid}->{is_unused} = 1 if $key =~ /^unused\d+$/;
4788
4789 $volhash->{$volid}->{is_attached} //= 0;
4790 $volhash->{$volid}->{is_attached} = 1
219719aa 4791 if !$volhash->{$volid}->{is_unused} && !defined($snapname) && !$pending;
912792e2
FE
4792
4793 $volhash->{$volid}->{referenced_in_snapshot}->{$snapname} = 1
4794 if defined($snapname);
ae180b8f 4795
219719aa 4796 $volhash->{$volid}->{referenced_in_pending} = 1 if $pending;
6328c554 4797
ae180b8f
FE
4798 my $size = $drive->{size};
4799 $volhash->{$volid}->{size} //= $size if $size;
4800
4801 $volhash->{$volid}->{is_vmstate} //= 0;
4802 $volhash->{$volid}->{is_vmstate} = 1 if $key eq 'vmstate';
4803
f9dde219
SR
4804 $volhash->{$volid}->{is_tpmstate} //= 0;
4805 $volhash->{$volid}->{is_tpmstate} = 1 if $key eq 'tpmstate0';
4806
a6be63ac 4807 $volhash->{$volid}->{drivename} = $key if is_valid_drivename($key);
912792e2
FE
4808 };
4809
ae180b8f
FE
4810 my $include_opts = {
4811 extra_keys => ['vmstate'],
4812 include_unused => 1,
4813 };
4814
0b953b8e 4815 PVE::QemuConfig->foreach_volume_full($conf, $include_opts, $test_volid);
6328c554 4816
0b7a0b78
AL
4817 PVE::QemuConfig->foreach_volume_full($conf->{pending}, $include_opts, $test_volid, undef, 1)
4818 if defined($conf->{pending}) && $conf->{pending}->%*;
6328c554 4819
912792e2
FE
4820 foreach my $snapname (keys %{$conf->{snapshots}}) {
4821 my $snap = $conf->{snapshots}->{$snapname};
0b953b8e 4822 PVE::QemuConfig->foreach_volume_full($snap, $include_opts, $test_volid, $snapname);
912792e2
FE
4823 }
4824
4825 foreach my $volid (keys %$volhash) {
4826 &$func($volid, $volhash->{$volid}, @param);
4827 }
4828}
4829
81d95ae1 4830my $fast_plug_option = {
f68910a0
FE
4831 'description' => 1,
4832 'hookscript' => 1,
7498eb64 4833 'lock' => 1,
d62bdac5
FE
4834 'migrate_downtime' => 1,
4835 'migrate_speed' => 1,
81d95ae1 4836 'name' => 1,
a1b7d579 4837 'onboot' => 1,
f68910a0 4838 'protection' => 1,
81d95ae1
DM
4839 'shares' => 1,
4840 'startup' => 1,
b8e7068a 4841 'tags' => 1,
f68910a0 4842 'vmstatestorage' => 1,
81d95ae1
DM
4843};
4844
71d9006b
AD
4845for my $opt (keys %$confdesc_cloudinit) {
4846 $fast_plug_option->{$opt} = 1;
4847};
4848
3a11fadb
DM
4849# hotplug changes in [PENDING]
4850# $selection hash can be used to only apply specified options, for
4851# example: { cores => 1 } (only apply changed 'cores')
4852# $errors ref is used to return error messages
c427973b 4853sub vmconfig_hotplug_pending {
3a11fadb 4854 my ($vmid, $conf, $storecfg, $selection, $errors) = @_;
c427973b 4855
8e90138a 4856 my $defaults = load_defaults();
045749f2
TL
4857 my $arch = get_vm_arch($conf);
4858 my $machine_type = get_vm_machine($conf, undef, $arch);
c427973b
DM
4859
4860 # commit values which do not have any impact on running VM first
3a11fadb
DM
4861 # Note: those option cannot raise errors, we we do not care about
4862 # $selection and always apply them.
4863
4864 my $add_error = sub {
4865 my ($opt, $msg) = @_;
4866 $errors->{$opt} = "hotplug problem - $msg";
4867 };
c427973b 4868
f16cf6c3
WB
4869 my $cloudinit_pending_properties = PVE::QemuServer::cloudinit_pending_properties();
4870
4871 my $cloudinit_record_changed = sub {
4872 my ($conf, $opt, $old, $new) = @_;
4873 return if !$cloudinit_pending_properties->{$opt};
4874
4875 my $ci = ($conf->{cloudinit} //= {});
4876
4877 my $recorded = $ci->{$opt};
a5409851
WB
4878 my %added = map { $_ => 1 } PVE::Tools::split_list(delete($ci->{added}) // '');
4879
4880 if (defined($new)) {
4881 if (defined($old)) {
4882 # an existing value is being modified
4883 if (defined($recorded)) {
4884 # the value was already not in sync
4885 if ($new eq $recorded) {
4886 # a value is being reverted to the cloud-init state:
4887 delete $ci->{$opt};
4888 delete $added{$opt};
4889 } else {
4890 # the value was changed multiple times, do nothing
4891 }
4892 } elsif ($added{$opt}) {
4893 # the value had been marked as added and is being changed, do nothing
4894 } else {
4895 # the value is new, record it:
4896 $ci->{$opt} = $old;
4897 }
f16cf6c3 4898 } else {
a5409851
WB
4899 # a new value is being added
4900 if (defined($recorded)) {
4901 # it was already not in sync
4902 if ($new eq $recorded) {
4903 # a value is being reverted to the cloud-init state:
4904 delete $ci->{$opt};
4905 delete $added{$opt};
4906 } else {
4907 # the value had temporarily been removed, do nothing
4908 }
4909 } elsif ($added{$opt}) {
4910 # the value had been marked as added already, do nothing
4911 } else {
4912 # the value is new, add it
4913 $added{$opt} = 1;
4914 }
f16cf6c3 4915 }
a5409851
WB
4916 } elsif (!defined($old)) {
4917 # a non-existent value is being removed? ignore...
f16cf6c3 4918 } else {
a5409851
WB
4919 # a value is being deleted
4920 if (defined($recorded)) {
4921 # a value was already recorded, just keep it
4922 } elsif ($added{$opt}) {
4923 # the value was marked as added, remove it
4924 delete $added{$opt};
f16cf6c3 4925 } else {
a5409851
WB
4926 # a previously unrecorded value is being removed, record the old value:
4927 $ci->{$opt} = $old;
f16cf6c3
WB
4928 }
4929 }
a5409851
WB
4930
4931 my $added = join(',', sort keys %added);
4932 $ci->{added} = $added if length($added);
f16cf6c3
WB
4933 };
4934
c427973b
DM
4935 my $changes = 0;
4936 foreach my $opt (keys %{$conf->{pending}}) { # add/change
81d95ae1 4937 if ($fast_plug_option->{$opt}) {
f16cf6c3
WB
4938 my $new = delete $conf->{pending}->{$opt};
4939 $cloudinit_record_changed->($conf, $opt, $conf->{$opt}, $new);
4940 $conf->{$opt} = $new;
c427973b
DM
4941 $changes = 1;
4942 }
4943 }
4944
4945 if ($changes) {
ffda963f 4946 PVE::QemuConfig->write_config($vmid, $conf);
c427973b
DM
4947 }
4948
c60cad61
DC
4949 my $ostype = $conf->{ostype};
4950 my $version = extract_version($machine_type, get_running_qemu_version($vmid));
b3c2bdd1 4951 my $hotplug_features = parse_hotplug_features(defined($conf->{hotplug}) ? $conf->{hotplug} : '1');
c60cad61
DC
4952 my $usb_hotplug = $hotplug_features->{usb}
4953 && min_version($version, 7, 1)
4954 && defined($ostype) && ($ostype eq 'l26' || windows_version($ostype) > 7);
c427973b 4955
5b65b00d 4956 my $cgroup = PVE::QemuServer::CGroup->new($vmid);
98bc3aeb 4957 my $pending_delete_hash = PVE::QemuConfig->parse_pending_delete($conf->{pending}->{delete});
f16cf6c3 4958
d321c4a9 4959 foreach my $opt (sort keys %$pending_delete_hash) {
3a11fadb 4960 next if $selection && !$selection->{$opt};
d321c4a9 4961 my $force = $pending_delete_hash->{$opt}->{force};
3a11fadb 4962 eval {
51a6f637 4963 if ($opt eq 'hotplug') {
d797bb62 4964 die "skip\n" if ($conf->{hotplug} =~ /(cpu|memory)/);
51a6f637 4965 } elsif ($opt eq 'tablet') {
b3c2bdd1 4966 die "skip\n" if !$hotplug_features->{usb};
3a11fadb 4967 if ($defaults->{tablet}) {
d559309f
WB
4968 vm_deviceplug($storecfg, $conf, $vmid, 'tablet', $arch, $machine_type);
4969 vm_deviceplug($storecfg, $conf, $vmid, 'keyboard', $arch, $machine_type)
4970 if $arch eq 'aarch64';
3a11fadb 4971 } else {
d559309f
WB
4972 vm_deviceunplug($vmid, $conf, 'tablet');
4973 vm_deviceunplug($vmid, $conf, 'keyboard') if $arch eq 'aarch64';
3a11fadb 4974 }
c60cad61
DC
4975 } elsif ($opt =~ m/^usb(\d+)$/) {
4976 my $index = $1;
4977 die "skip\n" if !$usb_hotplug;
4978 vm_deviceunplug($vmid, $conf, "usbredirdev$index"); # if it's a spice port
4979 vm_deviceunplug($vmid, $conf, $opt);
8edc9c08 4980 } elsif ($opt eq 'vcpus') {
b3c2bdd1 4981 die "skip\n" if !$hotplug_features->{cpu};
8edc9c08 4982 qemu_cpu_hotplug($vmid, $conf, undef);
9c2f7069 4983 } elsif ($opt eq 'balloon') {
81d95ae1 4984 # enable balloon device is not hotpluggable
75b51053
DC
4985 die "skip\n" if defined($conf->{balloon}) && $conf->{balloon} == 0;
4986 # here we reset the ballooning value to memory
7f8c8087 4987 my $balloon = get_current_memory($conf->{memory});
0a13e08e 4988 mon_cmd($vmid, "balloon", value => $balloon*1024*1024);
81d95ae1
DM
4989 } elsif ($fast_plug_option->{$opt}) {
4990 # do nothing
3eec5767 4991 } elsif ($opt =~ m/^net(\d+)$/) {
b3c2bdd1 4992 die "skip\n" if !$hotplug_features->{network};
3eec5767 4993 vm_deviceunplug($vmid, $conf, $opt);
74479ee9 4994 } elsif (is_valid_drivename($opt)) {
b3c2bdd1 4995 die "skip\n" if !$hotplug_features->{disk} || $opt =~ m/(ide|sata)(\d+)/;
19120f99 4996 vm_deviceunplug($vmid, $conf, $opt);
3dc38fbb 4997 vmconfig_delete_or_detach_drive($vmid, $storecfg, $conf, $opt, $force);
4d3f29ed
AD
4998 } elsif ($opt =~ m/^memory$/) {
4999 die "skip\n" if !$hotplug_features->{memory};
7f8c8087 5000 PVE::QemuServer::Memory::qemu_memory_hotplug($vmid, $conf);
c8effec3 5001 } elsif ($opt eq 'cpuunits') {
0d318453 5002 $cgroup->change_cpu_shares(undef);
58be00f1 5003 } elsif ($opt eq 'cpulimit') {
25de70ae 5004 $cgroup->change_cpu_quota(undef, undef); # reset, cgroup module can better decide values
3d7389fe 5005 } else {
e56beeda 5006 die "skip\n";
3d7389fe 5007 }
3a11fadb
DM
5008 };
5009 if (my $err = $@) {
e56beeda
DM
5010 &$add_error($opt, $err) if $err ne "skip\n";
5011 } else {
f16cf6c3
WB
5012 my $old = delete $conf->{$opt};
5013 $cloudinit_record_changed->($conf, $opt, $old, undef);
98bc3aeb 5014 PVE::QemuConfig->remove_from_pending_delete($conf, $opt);
3d7389fe 5015 }
3d7389fe
DM
5016 }
5017
4b785da1 5018 my $cloudinit_opt;
3d7389fe 5019 foreach my $opt (keys %{$conf->{pending}}) {
3a11fadb 5020 next if $selection && !$selection->{$opt};
3d7389fe 5021 my $value = $conf->{pending}->{$opt};
3a11fadb 5022 eval {
51a6f637
AD
5023 if ($opt eq 'hotplug') {
5024 die "skip\n" if ($value =~ /memory/) || ($value !~ /memory/ && $conf->{hotplug} =~ /memory/);
d797bb62 5025 die "skip\n" if ($value =~ /cpu/) || ($value !~ /cpu/ && $conf->{hotplug} =~ /cpu/);
51a6f637 5026 } elsif ($opt eq 'tablet') {
b3c2bdd1 5027 die "skip\n" if !$hotplug_features->{usb};
3a11fadb 5028 if ($value == 1) {
d559309f
WB
5029 vm_deviceplug($storecfg, $conf, $vmid, 'tablet', $arch, $machine_type);
5030 vm_deviceplug($storecfg, $conf, $vmid, 'keyboard', $arch, $machine_type)
5031 if $arch eq 'aarch64';
3a11fadb 5032 } elsif ($value == 0) {
d559309f
WB
5033 vm_deviceunplug($vmid, $conf, 'tablet');
5034 vm_deviceunplug($vmid, $conf, 'keyboard') if $arch eq 'aarch64';
3a11fadb 5035 }
c60cad61
DC
5036 } elsif ($opt =~ m/^usb(\d+)$/) {
5037 my $index = $1;
5038 die "skip\n" if !$usb_hotplug;
0cf8d56c 5039 my $d = eval { parse_property_string('pve-qm-usb', $value) };
c60cad61 5040 my $id = $opt;
0cf8d56c 5041 if ($d->{host} =~ m/^spice$/i) {
c60cad61
DC
5042 $id = "usbredirdev$index";
5043 }
5044 qemu_usb_hotplug($storecfg, $conf, $vmid, $id, $d, $arch, $machine_type);
8edc9c08 5045 } elsif ($opt eq 'vcpus') {
b3c2bdd1 5046 die "skip\n" if !$hotplug_features->{cpu};
3a11fadb
DM
5047 qemu_cpu_hotplug($vmid, $conf, $value);
5048 } elsif ($opt eq 'balloon') {
81d95ae1 5049 # enable/disable balloning device is not hotpluggable
8fe689e7 5050 my $old_balloon_enabled = !!(!defined($conf->{balloon}) || $conf->{balloon});
a1b7d579 5051 my $new_balloon_enabled = !!(!defined($conf->{pending}->{balloon}) || $conf->{pending}->{balloon});
81d95ae1
DM
5052 die "skip\n" if $old_balloon_enabled != $new_balloon_enabled;
5053
3a11fadb 5054 # allow manual ballooning if shares is set to zero
4cc1efa6 5055 if ((defined($conf->{shares}) && ($conf->{shares} == 0))) {
7f8c8087
AD
5056 my $memory = get_current_memory($conf->{memory});
5057 my $balloon = $conf->{pending}->{balloon} || $memory;
0a13e08e 5058 mon_cmd($vmid, "balloon", value => $balloon*1024*1024);
9c2f7069 5059 }
a1b7d579 5060 } elsif ($opt =~ m/^net(\d+)$/) {
3eec5767 5061 # some changes can be done without hotplug
a1b7d579 5062 vmconfig_update_net($storecfg, $conf, $hotplug_features->{network},
d559309f 5063 $vmid, $opt, $value, $arch, $machine_type);
74479ee9 5064 } elsif (is_valid_drivename($opt)) {
f9dde219 5065 die "skip\n" if $opt eq 'efidisk0' || $opt eq 'tpmstate0';
a05cff86 5066 # some changes can be done without hotplug
9ed7a77c
WB
5067 my $drive = parse_drive($opt, $value);
5068 if (drive_is_cloudinit($drive)) {
4b785da1
WB
5069 $cloudinit_opt = [$opt, $drive];
5070 # apply all the other changes first, then generate the cloudinit disk
5071 die "skip\n";
9ed7a77c 5072 }
b3c2bdd1 5073 vmconfig_update_disk($storecfg, $conf, $hotplug_features->{disk},
9e7bce2c 5074 $vmid, $opt, $value, $arch, $machine_type);
4d3f29ed
AD
5075 } elsif ($opt =~ m/^memory$/) { #dimms
5076 die "skip\n" if !$hotplug_features->{memory};
7f8c8087 5077 $value = PVE::QemuServer::Memory::qemu_memory_hotplug($vmid, $conf, $value);
c8effec3 5078 } elsif ($opt eq 'cpuunits') {
6b7ef5e5 5079 my $new_cpuunits = PVE::CGroup::clamp_cpu_shares($conf->{pending}->{$opt}); #clamp
0d318453 5080 $cgroup->change_cpu_shares($new_cpuunits);
58be00f1 5081 } elsif ($opt eq 'cpulimit') {
c6f773b8 5082 my $cpulimit = $conf->{pending}->{$opt} == 0 ? -1 : int($conf->{pending}->{$opt} * 100000);
5b65b00d 5083 $cgroup->change_cpu_quota($cpulimit, 100000);
74ea2c65
AD
5084 } elsif ($opt eq 'agent') {
5085 vmconfig_update_agent($conf, $opt, $value);
3a11fadb 5086 } else {
e56beeda 5087 die "skip\n"; # skip non-hot-pluggable options
3d7389fe 5088 }
3a11fadb 5089 };
4b785da1
WB
5090 if (my $err = $@) {
5091 &$add_error($opt, $err) if $err ne "skip\n";
5092 } else {
5093 $cloudinit_record_changed->($conf, $opt, $conf->{$opt}, $value);
5094 $conf->{$opt} = $value;
5095 delete $conf->{pending}->{$opt};
5096 }
5097 }
5098
5099 if (defined($cloudinit_opt)) {
5100 my ($opt, $drive) = @$cloudinit_opt;
5101 my $value = $conf->{pending}->{$opt};
5102 eval {
9660e606
WB
5103 my $temp = {%$conf, $opt => $value};
5104 PVE::QemuServer::Cloudinit::apply_cloudinit_config($temp, $vmid);
4b785da1
WB
5105 vmconfig_update_disk($storecfg, $conf, $hotplug_features->{disk},
5106 $vmid, $opt, $value, $arch, $machine_type);
5107 };
3a11fadb 5108 if (my $err = $@) {
e56beeda
DM
5109 &$add_error($opt, $err) if $err ne "skip\n";
5110 } else {
3a11fadb
DM
5111 $conf->{$opt} = $value;
5112 delete $conf->{pending}->{$opt};
3d7389fe 5113 }
3d7389fe 5114 }
c60cad61
DC
5115
5116 # unplug xhci controller if no usb device is left
5117 if ($usb_hotplug) {
5118 my $has_usb = 0;
0cf8d56c 5119 for (my $i = 0; $i < $PVE::QemuServer::USB::MAX_USB_DEVICES; $i++) {
c60cad61
DC
5120 next if !defined($conf->{"usb$i"});
5121 $has_usb = 1;
5122 last;
5123 }
5124 if (!$has_usb) {
5125 vm_deviceunplug($vmid, $conf, 'xhci');
5126 }
5127 }
5128
4df15a03 5129 PVE::QemuConfig->write_config($vmid, $conf);
94ec5e7c 5130
4b785da1
WB
5131 if ($hotplug_features->{cloudinit} && PVE::QemuServer::Cloudinit::has_changes($conf)) {
5132 PVE::QemuServer::vmconfig_update_cloudinit_drive($storecfg, $conf, $vmid);
94ec5e7c 5133 }
c427973b 5134}
055d554d 5135
3dc38fbb
WB
5136sub try_deallocate_drive {
5137 my ($storecfg, $vmid, $conf, $key, $drive, $rpcenv, $authuser, $force) = @_;
5138
5139 if (($force || $key =~ /^unused/) && !drive_is_cdrom($drive, 1)) {
5140 my $volid = $drive->{file};
5141 if (vm_is_volid_owner($storecfg, $vmid, $volid)) {
5142 my $sid = PVE::Storage::parse_volume_id($volid);
5143 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
cee01bcb
WB
5144
5145 # check if the disk is really unused
cee01bcb 5146 die "unable to delete '$volid' - volume is still in use (snapshot?)\n"
e0fd2b2f 5147 if PVE::QemuServer::Drive::is_volume_in_use($storecfg, $conf, $key, $volid);
cee01bcb 5148 PVE::Storage::vdisk_free($storecfg, $volid);
3dc38fbb 5149 return 1;
40b977f3
WL
5150 } else {
5151 # If vm is not owner of this disk remove from config
5152 return 1;
3dc38fbb
WB
5153 }
5154 }
5155
d1c1af4b 5156 return;
3dc38fbb
WB
5157}
5158
5159sub vmconfig_delete_or_detach_drive {
5160 my ($vmid, $storecfg, $conf, $opt, $force) = @_;
5161
5162 my $drive = parse_drive($opt, $conf->{$opt});
5163
5164 my $rpcenv = PVE::RPCEnvironment::get();
5165 my $authuser = $rpcenv->get_user();
5166
5167 if ($force) {
5168 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
5169 try_deallocate_drive($storecfg, $vmid, $conf, $opt, $drive, $rpcenv, $authuser, $force);
5170 } else {
5171 vmconfig_register_unused_drive($storecfg, $vmid, $conf, $drive);
5172 }
5173}
5174
98bc3aeb
OB
5175
5176
055d554d 5177sub vmconfig_apply_pending {
e97bbbb6 5178 my ($vmid, $conf, $storecfg, $errors, $skip_cloud_init) = @_;
eb5e482d 5179
a644de29
OB
5180 return if !scalar(keys %{$conf->{pending}});
5181
eb5e482d
OB
5182 my $add_apply_error = sub {
5183 my ($opt, $msg) = @_;
5184 my $err_msg = "unable to apply pending change $opt : $msg";
5185 $errors->{$opt} = $err_msg;
5186 warn $err_msg;
5187 };
c427973b
DM
5188
5189 # cold plug
055d554d 5190
98bc3aeb 5191 my $pending_delete_hash = PVE::QemuConfig->parse_pending_delete($conf->{pending}->{delete});
d321c4a9 5192 foreach my $opt (sort keys %$pending_delete_hash) {
fb4d1ba2 5193 my $force = $pending_delete_hash->{$opt}->{force};
eb5e482d 5194 eval {
3d48b95a
OB
5195 if ($opt =~ m/^unused/) {
5196 die "internal error";
5197 } elsif (defined($conf->{$opt}) && is_valid_drivename($opt)) {
eb5e482d 5198 vmconfig_delete_or_detach_drive($vmid, $storecfg, $conf, $opt, $force);
eb5e482d
OB
5199 }
5200 };
5201 if (my $err = $@) {
5202 $add_apply_error->($opt, $err);
055d554d 5203 } else {
98bc3aeb 5204 PVE::QemuConfig->remove_from_pending_delete($conf, $opt);
055d554d 5205 delete $conf->{$opt};
055d554d
DM
5206 }
5207 }
5208
3d48b95a 5209 PVE::QemuConfig->cleanup_pending($conf);
055d554d 5210
7a24c98a 5211 my $generate_cloudinit = $skip_cloud_init ? 0 : undef;
c930f99e 5212
055d554d 5213 foreach my $opt (keys %{$conf->{pending}}) { # add/change
3d48b95a 5214 next if $opt eq 'delete'; # just to be sure
eb5e482d 5215 eval {
3d48b95a 5216 if (defined($conf->{$opt}) && is_valid_drivename($opt)) {
eb5e482d 5217 vmconfig_register_unused_drive($storecfg, $vmid, $conf, parse_drive($opt, $conf->{$opt}))
eb5e482d
OB
5218 }
5219 };
5220 if (my $err = $@) {
5221 $add_apply_error->($opt, $err);
055d554d 5222 } else {
c930f99e
AD
5223
5224 if (is_valid_drivename($opt)) {
5225 my $drive = parse_drive($opt, $conf->{pending}->{$opt});
7a24c98a 5226 $generate_cloudinit //= 1 if drive_is_cloudinit($drive);
c930f99e
AD
5227 }
5228
eb5e482d 5229 $conf->{$opt} = delete $conf->{pending}->{$opt};
055d554d 5230 }
055d554d 5231 }
3d48b95a
OB
5232
5233 # write all changes at once to avoid unnecessary i/o
5234 PVE::QemuConfig->write_config($vmid, $conf);
7a24c98a 5235 if ($generate_cloudinit) {
4b785da1
WB
5236 if (PVE::QemuServer::Cloudinit::apply_cloudinit_config($conf, $vmid)) {
5237 # After successful generation and if there were changes to be applied, update the
5238 # config to drop the {cloudinit} entry.
5239 PVE::QemuConfig->write_config($vmid, $conf);
5240 }
5241 }
055d554d
DM
5242}
5243
3eec5767 5244sub vmconfig_update_net {
d559309f 5245 my ($storecfg, $conf, $hotplug, $vmid, $opt, $value, $arch, $machine_type) = @_;
3eec5767
DM
5246
5247 my $newnet = parse_net($value);
5248
5249 if ($conf->{$opt}) {
5250 my $oldnet = parse_net($conf->{$opt});
5251
0f1af9e7
OB
5252 if (safe_string_ne($oldnet->{model}, $newnet->{model}) ||
5253 safe_string_ne($oldnet->{macaddr}, $newnet->{macaddr}) ||
5254 safe_num_ne($oldnet->{queues}, $newnet->{queues}) ||
62fdcfd4 5255 safe_num_ne($oldnet->{mtu}, $newnet->{mtu}) ||
3eec5767
DM
5256 !($newnet->{bridge} && $oldnet->{bridge})) { # bridge/nat mode change
5257
5258 # for non online change, we try to hot-unplug
7196b757 5259 die "skip\n" if !$hotplug;
3eec5767
DM
5260 vm_deviceunplug($vmid, $conf, $opt);
5261 } else {
5262
5263 die "internal error" if $opt !~ m/net(\d+)/;
5264 my $iface = "tap${vmid}i$1";
a1b7d579 5265
0f1af9e7
OB
5266 if (safe_string_ne($oldnet->{bridge}, $newnet->{bridge}) ||
5267 safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
5268 safe_string_ne($oldnet->{trunks}, $newnet->{trunks}) ||
5269 safe_num_ne($oldnet->{firewall}, $newnet->{firewall})) {
3eec5767 5270 PVE::Network::tap_unplug($iface);
28e129cc
AD
5271
5272 if ($have_sdn) {
5273 PVE::Network::SDN::Zones::tap_plug($iface, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
5274 } else {
5275 PVE::Network::tap_plug($iface, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
5276 }
0f1af9e7 5277 } elsif (safe_num_ne($oldnet->{rate}, $newnet->{rate})) {
4f4fbeb0
WB
5278 # Rate can be applied on its own but any change above needs to
5279 # include the rate in tap_plug since OVS resets everything.
5280 PVE::Network::tap_rate_limit($iface, $newnet->{rate});
3eec5767 5281 }
38c590d9 5282
0f1af9e7 5283 if (safe_string_ne($oldnet->{link_down}, $newnet->{link_down})) {
25088687
DM
5284 qemu_set_link_status($vmid, $opt, !$newnet->{link_down});
5285 }
5286
38c590d9 5287 return 1;
3eec5767
DM
5288 }
5289 }
a1b7d579 5290
7196b757 5291 if ($hotplug) {
d559309f 5292 vm_deviceplug($storecfg, $conf, $vmid, $opt, $newnet, $arch, $machine_type);
38c590d9
DM
5293 } else {
5294 die "skip\n";
5295 }
3eec5767
DM
5296}
5297
74ea2c65
AD
5298sub vmconfig_update_agent {
5299 my ($conf, $opt, $value) = @_;
5300
5301 die "skip\n" if !$conf->{$opt};
5302
5303 my $hotplug_options = { fstrim_cloned_disks => 1 };
5304
5305 my $old_agent = parse_guest_agent($conf);
5306 my $agent = parse_guest_agent({$opt => $value});
5307
33f8b887 5308 for my $option (keys %$agent) { # added/changed options
74ea2c65
AD
5309 next if defined($hotplug_options->{$option});
5310 die "skip\n" if safe_string_ne($agent->{$option}, $old_agent->{$option});
5311 }
5312
33f8b887 5313 for my $option (keys %$old_agent) { # removed options
74ea2c65
AD
5314 next if defined($hotplug_options->{$option});
5315 die "skip\n" if safe_string_ne($old_agent->{$option}, $agent->{$option});
5316 }
33f8b887
TL
5317
5318 return; # either no actual change (e.g., format string reordered) or just hotpluggable changes
74ea2c65
AD
5319}
5320
a05cff86 5321sub vmconfig_update_disk {
9e7bce2c 5322 my ($storecfg, $conf, $hotplug, $vmid, $opt, $value, $arch, $machine_type) = @_;
a05cff86
DM
5323
5324 my $drive = parse_drive($opt, $value);
5325
4df98f2f
TL
5326 if ($conf->{$opt} && (my $old_drive = parse_drive($opt, $conf->{$opt}))) {
5327 my $media = $drive->{media} || 'disk';
5328 my $oldmedia = $old_drive->{media} || 'disk';
5329 die "unable to change media type\n" if $media ne $oldmedia;
a05cff86 5330
4df98f2f 5331 if (!drive_is_cdrom($old_drive)) {
a05cff86 5332
4df98f2f 5333 if ($drive->{file} ne $old_drive->{file}) {
a05cff86 5334
4df98f2f 5335 die "skip\n" if !$hotplug;
a05cff86 5336
4df98f2f
TL
5337 # unplug and register as unused
5338 vm_deviceunplug($vmid, $conf, $opt);
5339 vmconfig_register_unused_drive($storecfg, $vmid, $conf, $old_drive)
a1b7d579 5340
4df98f2f
TL
5341 } else {
5342 # update existing disk
5343
5344 # skip non hotpluggable value
ea7c3b39
FE
5345 if (safe_string_ne($drive->{aio}, $old_drive->{aio}) ||
5346 safe_string_ne($drive->{discard}, $old_drive->{discard}) ||
4df98f2f
TL
5347 safe_string_ne($drive->{iothread}, $old_drive->{iothread}) ||
5348 safe_string_ne($drive->{queues}, $old_drive->{queues}) ||
5349 safe_string_ne($drive->{cache}, $old_drive->{cache}) ||
e0e036e1
LN
5350 safe_string_ne($drive->{ssd}, $old_drive->{ssd}) ||
5351 safe_string_ne($drive->{ro}, $old_drive->{ro})) {
4df98f2f
TL
5352 die "skip\n";
5353 }
a05cff86 5354
4df98f2f
TL
5355 # apply throttle
5356 if (safe_num_ne($drive->{mbps}, $old_drive->{mbps}) ||
5357 safe_num_ne($drive->{mbps_rd}, $old_drive->{mbps_rd}) ||
5358 safe_num_ne($drive->{mbps_wr}, $old_drive->{mbps_wr}) ||
5359 safe_num_ne($drive->{iops}, $old_drive->{iops}) ||
5360 safe_num_ne($drive->{iops_rd}, $old_drive->{iops_rd}) ||
5361 safe_num_ne($drive->{iops_wr}, $old_drive->{iops_wr}) ||
5362 safe_num_ne($drive->{mbps_max}, $old_drive->{mbps_max}) ||
5363 safe_num_ne($drive->{mbps_rd_max}, $old_drive->{mbps_rd_max}) ||
5364 safe_num_ne($drive->{mbps_wr_max}, $old_drive->{mbps_wr_max}) ||
5365 safe_num_ne($drive->{iops_max}, $old_drive->{iops_max}) ||
5366 safe_num_ne($drive->{iops_rd_max}, $old_drive->{iops_rd_max}) ||
5367 safe_num_ne($drive->{iops_wr_max}, $old_drive->{iops_wr_max}) ||
5368 safe_num_ne($drive->{bps_max_length}, $old_drive->{bps_max_length}) ||
5369 safe_num_ne($drive->{bps_rd_max_length}, $old_drive->{bps_rd_max_length}) ||
5370 safe_num_ne($drive->{bps_wr_max_length}, $old_drive->{bps_wr_max_length}) ||
5371 safe_num_ne($drive->{iops_max_length}, $old_drive->{iops_max_length}) ||
5372 safe_num_ne($drive->{iops_rd_max_length}, $old_drive->{iops_rd_max_length}) ||
5373 safe_num_ne($drive->{iops_wr_max_length}, $old_drive->{iops_wr_max_length})) {
5374
5375 qemu_block_set_io_throttle(
5376 $vmid,"drive-$opt",
5377 ($drive->{mbps} || 0)*1024*1024,
5378 ($drive->{mbps_rd} || 0)*1024*1024,
5379 ($drive->{mbps_wr} || 0)*1024*1024,
5380 $drive->{iops} || 0,
5381 $drive->{iops_rd} || 0,
5382 $drive->{iops_wr} || 0,
5383 ($drive->{mbps_max} || 0)*1024*1024,
5384 ($drive->{mbps_rd_max} || 0)*1024*1024,
5385 ($drive->{mbps_wr_max} || 0)*1024*1024,
5386 $drive->{iops_max} || 0,
5387 $drive->{iops_rd_max} || 0,
5388 $drive->{iops_wr_max} || 0,
5389 $drive->{bps_max_length} || 1,
5390 $drive->{bps_rd_max_length} || 1,
5391 $drive->{bps_wr_max_length} || 1,
5392 $drive->{iops_max_length} || 1,
5393 $drive->{iops_rd_max_length} || 1,
5394 $drive->{iops_wr_max_length} || 1,
5395 );
a05cff86 5396
4df98f2f 5397 }
a1b7d579 5398
4df98f2f
TL
5399 return 1;
5400 }
4de1bb25 5401
4df98f2f 5402 } else { # cdrom
a1b7d579 5403
4df98f2f
TL
5404 if ($drive->{file} eq 'none') {
5405 mon_cmd($vmid, "eject", force => JSON::true, id => "$opt");
5406 if (drive_is_cloudinit($old_drive)) {
5407 vmconfig_register_unused_drive($storecfg, $vmid, $conf, $old_drive);
5408 }
5409 } else {
5410 my $path = get_iso_path($storecfg, $vmid, $drive->{file});
ce9fce79 5411
4df98f2f
TL
5412 # force eject if locked
5413 mon_cmd($vmid, "eject", force => JSON::true, id => "$opt");
ce9fce79 5414
4df98f2f
TL
5415 if ($path) {
5416 mon_cmd($vmid, "blockdev-change-medium",
5417 id => "$opt", filename => "$path");
4de1bb25 5418 }
a05cff86 5419 }
4df98f2f
TL
5420
5421 return 1;
a05cff86
DM
5422 }
5423 }
5424
a1b7d579 5425 die "skip\n" if !$hotplug || $opt =~ m/(ide|sata)(\d+)/;
4de1bb25 5426 # hotplug new disks
f7b4356f 5427 PVE::Storage::activate_volumes($storecfg, [$drive->{file}]) if $drive->{file} !~ m|^/dev/.+|;
d559309f 5428 vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive, $arch, $machine_type);
a05cff86
DM
5429}
5430
9687287b
AD
5431sub vmconfig_update_cloudinit_drive {
5432 my ($storecfg, $conf, $vmid) = @_;
5433
5434 my $cloudinit_ds = undef;
5435 my $cloudinit_drive = undef;
5436
5437 PVE::QemuConfig->foreach_volume($conf, sub {
5438 my ($ds, $drive) = @_;
5439 if (PVE::QemuServer::drive_is_cloudinit($drive)) {
5440 $cloudinit_ds = $ds;
5441 $cloudinit_drive = $drive;
5442 }
5443 });
5444
5445 return if !$cloudinit_drive;
5446
4b785da1
WB
5447 if (PVE::QemuServer::Cloudinit::apply_cloudinit_config($conf, $vmid)) {
5448 PVE::QemuConfig->write_config($vmid, $conf);
5449 }
5450
9687287b
AD
5451 my $running = PVE::QemuServer::check_running($vmid);
5452
5453 if ($running) {
5454 my $path = PVE::Storage::path($storecfg, $cloudinit_drive->{file});
5455 if ($path) {
5456 mon_cmd($vmid, "eject", force => JSON::true, id => "$cloudinit_ds");
5457 mon_cmd($vmid, "blockdev-change-medium", id => "$cloudinit_ds", filename => "$path");
5458 }
5459 }
5460}
5461
13cfe3b7 5462# called in locked context by incoming migration
ba5396b5
FG
5463sub vm_migrate_get_nbd_disks {
5464 my ($storecfg, $conf, $replicated_volumes) = @_;
13cfe3b7
FG
5465
5466 my $local_volumes = {};
912792e2 5467 PVE::QemuConfig->foreach_volume($conf, sub {
13cfe3b7
FG
5468 my ($ds, $drive) = @_;
5469
5470 return if drive_is_cdrom($drive);
41c8671e 5471 return if $ds eq 'tpmstate0';
13cfe3b7
FG
5472
5473 my $volid = $drive->{file};
5474
5475 return if !$volid;
5476
5477 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
5478
5479 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
5480 return if $scfg->{shared};
ba5396b5 5481
0d4e8cbd
FE
5482 my $format = qemu_img_format($scfg, $volname);
5483
ba5396b5
FG
5484 # replicated disks re-use existing state via bitmap
5485 my $use_existing = $replicated_volumes->{$volid} ? 1 : 0;
0d4e8cbd 5486 $local_volumes->{$ds} = [$volid, $storeid, $drive, $use_existing, $format];
13cfe3b7 5487 });
ba5396b5
FG
5488 return $local_volumes;
5489}
5490
5491# called in locked context by incoming migration
5492sub vm_migrate_alloc_nbd_disks {
5493 my ($storecfg, $vmid, $source_volumes, $storagemap) = @_;
13cfe3b7 5494
13cfe3b7 5495 my $nbd = {};
ba5396b5 5496 foreach my $opt (sort keys %$source_volumes) {
0d4e8cbd 5497 my ($volid, $storeid, $drive, $use_existing, $format) = @{$source_volumes->{$opt}};
ba5396b5
FG
5498
5499 if ($use_existing) {
5500 $nbd->{$opt}->{drivestr} = print_drive($drive);
5501 $nbd->{$opt}->{volid} = $volid;
5502 $nbd->{$opt}->{replicated} = 1;
13cfe3b7
FG
5503 next;
5504 }
13cfe3b7 5505
0d4e8cbd
FE
5506 $storeid = PVE::JSONSchema::map_id($storagemap, $storeid);
5507
5668463b
FG
5508 # order of precedence, filtered by whether storage supports it:
5509 # 1. explicit requested format
0d4e8cbd
FE
5510 # 2. default format of storage
5511 my ($defFormat, $validFormats) = PVE::Storage::storage_default_format($storecfg, $storeid);
5512 $format = $defFormat if !$format || !grep { $format eq $_ } $validFormats->@*;
13cfe3b7 5513
4df98f2f
TL
5514 my $size = $drive->{size} / 1024;
5515 my $newvolid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, $format, undef, $size);
13cfe3b7
FG
5516 my $newdrive = $drive;
5517 $newdrive->{format} = $format;
5518 $newdrive->{file} = $newvolid;
5519 my $drivestr = print_drive($newdrive);
ba5396b5
FG
5520 $nbd->{$opt}->{drivestr} = $drivestr;
5521 $nbd->{$opt}->{volid} = $newvolid;
13cfe3b7
FG
5522 }
5523
5524 return $nbd;
5525}
5526
5527# see vm_start_nolock for parameters, additionally:
5528# migrate_opts:
bf8fc5a3 5529# storagemap = parsed storage map for allocating NBD disks
3898a563
FG
5530sub vm_start {
5531 my ($storecfg, $vmid, $params, $migrate_opts) = @_;
5532
84da8217 5533 return PVE::QemuConfig->lock_config($vmid, sub {
3898a563
FG
5534 my $conf = PVE::QemuConfig->load_config($vmid, $migrate_opts->{migratedfrom});
5535
4ef13a7f
FG
5536 die "you can't start a vm if it's a template\n"
5537 if !$params->{skiptemplate} && PVE::QemuConfig->is_template($conf);
3898a563 5538
d544e0e0 5539 my $has_suspended_lock = PVE::QemuConfig->has_lock($conf, 'suspended');
8e0c97bb
SR
5540 my $has_backup_lock = PVE::QemuConfig->has_lock($conf, 'backup');
5541
5542 my $running = check_running($vmid, undef, $migrate_opts->{migratedfrom});
5543
5544 if ($has_backup_lock && $running) {
5545 # a backup is currently running, attempt to start the guest in the
5546 # existing QEMU instance
5547 return vm_resume($vmid);
5548 }
3898a563
FG
5549
5550 PVE::QemuConfig->check_lock($conf)
d544e0e0
FE
5551 if !($params->{skiplock} || $has_suspended_lock);
5552
5553 $params->{resume} = $has_suspended_lock || defined($conf->{vmstate});
3898a563 5554
8e0c97bb 5555 die "VM $vmid already running\n" if $running;
3898a563 5556
ba5396b5
FG
5557 if (my $storagemap = $migrate_opts->{storagemap}) {
5558 my $replicated = $migrate_opts->{replicated_volumes};
5559 my $disks = vm_migrate_get_nbd_disks($storecfg, $conf, $replicated);
5560 $migrate_opts->{nbd} = vm_migrate_alloc_nbd_disks($storecfg, $vmid, $disks, $storagemap);
5561
5562 foreach my $opt (keys %{$migrate_opts->{nbd}}) {
5563 $conf->{$opt} = $migrate_opts->{nbd}->{$opt}->{drivestr};
5564 }
5565 }
13cfe3b7 5566
84da8217 5567 return vm_start_nolock($storecfg, $vmid, $conf, $params, $migrate_opts);
3898a563
FG
5568 });
5569}
5570
5571
0c498cca
FG
5572# params:
5573# statefile => 'tcp', 'unix' for migration or path/volid for RAM state
5574# skiplock => 0/1, skip checking for config lock
4ef13a7f 5575# skiptemplate => 0/1, skip checking whether VM is template
7bd9abd2 5576# forcemachine => to force QEMU machine (rollback/migration)
58c64ad5 5577# forcecpu => a QEMU '-cpu' argument string to override get_cpu_options
0c498cca
FG
5578# timeout => in seconds
5579# paused => start VM in paused state (backup)
3898a563 5580# resume => resume from hibernation
5921764c
SR
5581# pbs-backing => {
5582# sata0 => {
5583# repository
5584# snapshot
5585# keyfile
5586# archive
5587# },
5588# virtio2 => ...
5589# }
0c498cca 5590# migrate_opts:
ba5396b5 5591# nbd => volumes for NBD exports (vm_migrate_alloc_nbd_disks)
0c498cca
FG
5592# migratedfrom => source node
5593# spice_ticket => used for spice migration, passed via tunnel/stdin
5594# network => CIDR of migration network
5595# type => secure/insecure - tunnel over encrypted connection or plain-text
0c498cca 5596# nbd_proto_version => int, 0 for TCP, 1 for UNIX
fd95d780 5597# replicated_volumes => which volids should be re-used with bitmaps for nbd migration
13d121d7
FE
5598# offline_volumes => new volids of offline migrated disks like tpmstate and cloudinit, not yet
5599# contained in config
3898a563
FG
5600sub vm_start_nolock {
5601 my ($storecfg, $vmid, $conf, $params, $migrate_opts) = @_;
1e3baf05 5602
3898a563
FG
5603 my $statefile = $params->{statefile};
5604 my $resume = $params->{resume};
3dcb98d5 5605
3898a563
FG
5606 my $migratedfrom = $migrate_opts->{migratedfrom};
5607 my $migration_type = $migrate_opts->{type};
7ceade4c 5608
84da8217
FG
5609 my $res = {};
5610
3898a563
FG
5611 # clean up leftover reboot request files
5612 eval { clear_reboot_request($vmid); };
5613 warn $@ if $@;
1e3baf05 5614
3898a563
FG
5615 if (!$statefile && scalar(keys %{$conf->{pending}})) {
5616 vmconfig_apply_pending($vmid, $conf, $storecfg);
5617 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
5618 }
64457ed4 5619
3de134ef
WB
5620 # don't regenerate the ISO if the VM is started as part of a live migration
5621 # this way we can reuse the old ISO with the correct config
4b785da1
WB
5622 if (!$migratedfrom) {
5623 if (PVE::QemuServer::Cloudinit::apply_cloudinit_config($conf, $vmid)) {
5624 # FIXME: apply_cloudinit_config updates $conf in this case, and it would only drop
5625 # $conf->{cloudinit}, so we could just not do this?
5626 # But we do it above, so for now let's be consistent.
5627 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
5628 }
5629 }
3de134ef 5630
13d121d7
FE
5631 # override offline migrated volumes, conf is out of date still
5632 if (my $offline_volumes = $migrate_opts->{offline_volumes}) {
5633 for my $key (sort keys $offline_volumes->%*) {
5634 my $parsed = parse_drive($key, $conf->{$key});
5635 $parsed->{file} = $offline_volumes->{$key};
5636 $conf->{$key} = print_drive($parsed);
5637 }
fd95d780
FG
5638 }
5639
3898a563 5640 my $defaults = load_defaults();
0c9a7596 5641
3898a563 5642 # set environment variable useful inside network script
eef93bc5
FG
5643 # for remote migration the config is available on the target node!
5644 if (!$migrate_opts->{remote_node}) {
5645 $ENV{PVE_MIGRATED_FROM} = $migratedfrom;
5646 }
6c47d546 5647
3898a563 5648 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-start', 1);
9e784b11 5649
3898a563 5650 my $forcemachine = $params->{forcemachine};
ea1c2110 5651 my $forcecpu = $params->{forcecpu};
3898a563 5652 if ($resume) {
ea1c2110 5653 # enforce machine and CPU type on suspended vm to ensure HW compatibility
3898a563 5654 $forcemachine = $conf->{runningmachine};
ea1c2110 5655 $forcecpu = $conf->{runningcpu};
3898a563
FG
5656 print "Resuming suspended VM\n";
5657 }
7ceade4c 5658
9b71c34d 5659 my ($cmd, $vollist, $spice_port, $pci_devices) = config_to_command($storecfg, $vmid,
5921764c 5660 $conf, $defaults, $forcemachine, $forcecpu, $params->{'pbs-backing'});
6c47d546 5661
3898a563
FG
5662 my $migration_ip;
5663 my $get_migration_ip = sub {
5664 my ($nodename) = @_;
b24e1ac2 5665
3898a563 5666 return $migration_ip if defined($migration_ip);
b24e1ac2 5667
3898a563 5668 my $cidr = $migrate_opts->{network};
0c498cca 5669
3898a563
FG
5670 if (!defined($cidr)) {
5671 my $dc_conf = PVE::Cluster::cfs_read_file('datacenter.cfg');
5672 $cidr = $dc_conf->{migration}->{network};
5673 }
b24e1ac2 5674
3898a563
FG
5675 if (defined($cidr)) {
5676 my $ips = PVE::Network::get_local_ip_from_cidr($cidr);
b24e1ac2 5677
3898a563
FG
5678 die "could not get IP: no address configured on local " .
5679 "node for network '$cidr'\n" if scalar(@$ips) == 0;
b24e1ac2 5680
3898a563
FG
5681 die "could not get IP: multiple addresses configured on local " .
5682 "node for network '$cidr'\n" if scalar(@$ips) > 1;
b24e1ac2 5683
3898a563
FG
5684 $migration_ip = @$ips[0];
5685 }
b24e1ac2 5686
3898a563
FG
5687 $migration_ip = PVE::Cluster::remote_node_ip($nodename, 1)
5688 if !defined($migration_ip);
b24e1ac2 5689
3898a563
FG
5690 return $migration_ip;
5691 };
b24e1ac2 5692
3898a563
FG
5693 if ($statefile) {
5694 if ($statefile eq 'tcp') {
05b2a4ae
FG
5695 my $migrate = $res->{migrate} = { proto => 'tcp' };
5696 $migrate->{addr} = "localhost";
3898a563
FG
5697 my $datacenterconf = PVE::Cluster::cfs_read_file('datacenter.cfg');
5698 my $nodename = nodename();
2de2d6f7 5699
3898a563
FG
5700 if (!defined($migration_type)) {
5701 if (defined($datacenterconf->{migration}->{type})) {
5702 $migration_type = $datacenterconf->{migration}->{type};
5703 } else {
5704 $migration_type = 'secure';
b7a5a225 5705 }
3898a563 5706 }
b7a5a225 5707
3898a563 5708 if ($migration_type eq 'insecure') {
05b2a4ae
FG
5709 $migrate->{addr} = $get_migration_ip->($nodename);
5710 $migrate->{addr} = "[$migrate->{addr}]" if Net::IP::ip_is_ipv6($migrate->{addr});
3898a563 5711 }
2de2d6f7 5712
3898a563 5713 my $pfamily = PVE::Tools::get_host_address_family($nodename);
05b2a4ae
FG
5714 $migrate->{port} = PVE::Tools::next_migrate_port($pfamily);
5715 $migrate->{uri} = "tcp:$migrate->{addr}:$migrate->{port}";
5716 push @$cmd, '-incoming', $migrate->{uri};
3898a563 5717 push @$cmd, '-S';
1c9d54bf 5718
3898a563
FG
5719 } elsif ($statefile eq 'unix') {
5720 # should be default for secure migrations as a ssh TCP forward
5721 # tunnel is not deterministic reliable ready and fails regurarly
5722 # to set up in time, so use UNIX socket forwards
05b2a4ae
FG
5723 my $migrate = $res->{migrate} = { proto => 'unix' };
5724 $migrate->{addr} = "/run/qemu-server/$vmid.migrate";
5725 unlink $migrate->{addr};
54323eed 5726
05b2a4ae
FG
5727 $migrate->{uri} = "unix:$migrate->{addr}";
5728 push @$cmd, '-incoming', $migrate->{uri};
3898a563 5729 push @$cmd, '-S';
1c9d54bf 5730
3898a563
FG
5731 } elsif (-e $statefile) {
5732 push @$cmd, '-loadstate', $statefile;
5733 } else {
5734 my $statepath = PVE::Storage::path($storecfg, $statefile);
5735 push @$vollist, $statefile;
5736 push @$cmd, '-loadstate', $statepath;
5737 }
5738 } elsif ($params->{paused}) {
5739 push @$cmd, '-S';
5740 }
5741
7f8c8087
AD
5742 my $memory = get_current_memory($conf->{memory});
5743 my $start_timeout = $params->{timeout} // config_aware_timeout($conf, $memory, $resume);
1fb1822e 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
6cb2338f 8271 mon_cmd($vmid, 'nbd-server-stop', timeout => 25);
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 8500sub vm_is_paused {
6f0627d4 8501 my ($vmid, $include_suspended) = @_;
b08c37c3
DC
8502 my $qmpstatus = eval {
8503 PVE::QemuConfig::assert_config_exists_on_node($vmid);
8504 mon_cmd($vmid, "query-status");
8505 };
8506 warn "$@\n" if $@;
7ba974a6
FS
8507 return $qmpstatus && (
8508 $qmpstatus->{status} eq "paused" ||
6f0627d4
FS
8509 $qmpstatus->{status} eq "prelaunch" ||
8510 ($include_suspended && $qmpstatus->{status} eq "suspended")
7ba974a6 8511 );
b08c37c3
DC
8512}
8513
3f11f0d7
LS
8514sub check_volume_storage_type {
8515 my ($storecfg, $vol) = @_;
8516
8517 my ($storeid, $volname) = PVE::Storage::parse_volume_id($vol);
8518 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
8519 my ($vtype) = PVE::Storage::parse_volname($storecfg, $vol);
8520
8521 die "storage '$storeid' does not support content-type '$vtype'\n"
8522 if !$scfg->{content}->{$vtype};
8523
8524 return 1;
8525}
8526
21947fea
AD
8527sub add_nets_bridge_fdb {
8528 my ($conf, $vmid) = @_;
8529
1b5ba4dd
TL
8530 for my $opt (keys %$conf) {
8531 next if $opt !~ m/^net(\d+)$/;
8532 my $iface = "tap${vmid}i$1";
4ddd2ca2
TL
8533 # NOTE: expect setups with learning off to *not* use auto-random-generation of MAC on start
8534 my $net = parse_net($conf->{$opt}, 1) or next;
8535
8536 my $mac = $net->{macaddr};
8537 if (!$mac) {
8538 log_warn("MAC learning disabled, but vNIC '$iface' has no static MAC to add to forwarding DB!")
8539 if !file_read_firstline("/sys/class/net/$iface/brport/learning");
8540 next;
8541 }
21947fea 8542
f81c9843 8543 my $bridge = $net->{bridge};
bb547dcb
CE
8544 if (!$bridge) {
8545 log_warn("Interface '$iface' not attached to any bridge.");
8546 next;
8547 }
1b5ba4dd 8548 if ($have_sdn) {
5bb8815a 8549 PVE::Network::SDN::Zones::add_bridge_fdb($iface, $mac, $bridge);
fe62da4f 8550 } elsif (-d "/sys/class/net/$bridge/bridge") { # avoid fdb management with OVS for now
5bb8815a 8551 PVE::Network::add_bridge_fdb($iface, $mac);
21947fea
AD
8552 }
8553 }
8554}
1b5ba4dd 8555
73ed6496
AD
8556sub del_nets_bridge_fdb {
8557 my ($conf, $vmid) = @_;
8558
8559 for my $opt (keys %$conf) {
8560 next if $opt !~ m/^net(\d+)$/;
8561 my $iface = "tap${vmid}i$1";
8562
8563 my $net = parse_net($conf->{$opt}) or next;
8564 my $mac = $net->{macaddr} or next;
8565
f81c9843 8566 my $bridge = $net->{bridge};
73ed6496 8567 if ($have_sdn) {
5bb8815a 8568 PVE::Network::SDN::Zones::del_bridge_fdb($iface, $mac, $bridge);
fe62da4f 8569 } elsif (-d "/sys/class/net/$bridge/bridge") { # avoid fdb management with OVS for now
5bb8815a 8570 PVE::Network::del_bridge_fdb($iface, $mac);
73ed6496
AD
8571 }
8572 }
8573}
8574
1e3baf05 85751;