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