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