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