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