qemu: Tweak Intel IOMMU command line generation
[libvirt/ericb.git] / src / qemu / qemu_command.c
blob73f570c41962b0733b05ac9047eed3b0a4f47e9a
1 /*
2 * qemu_command.c: QEMU command generation
4 * Copyright (C) 2006-2016 Red Hat, Inc.
5 * Copyright (C) 2006 Daniel P. Berrange
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library. If not, see
19 * <http://www.gnu.org/licenses/>.
22 #include <config.h>
24 #include "qemu_command.h"
25 #include "qemu_hostdev.h"
26 #include "qemu_capabilities.h"
27 #include "qemu_interface.h"
28 #include "qemu_alias.h"
29 #include "qemu_security.h"
30 #include "qemu_block.h"
31 #include "cpu/cpu.h"
32 #include "dirname.h"
33 #include "viralloc.h"
34 #include "virlog.h"
35 #include "virarch.h"
36 #include "virerror.h"
37 #include "virfile.h"
38 #include "virnetdev.h"
39 #include "virnetdevbridge.h"
40 #include "virqemu.h"
41 #include "virstring.h"
42 #include "virtime.h"
43 #include "viruuid.h"
44 #include "domain_nwfilter.h"
45 #include "domain_addr.h"
46 #include "domain_audit.h"
47 #include "domain_conf.h"
48 #include "netdev_bandwidth_conf.h"
49 #include "snapshot_conf.h"
50 #include "storage_conf.h"
51 #include "secret_conf.h"
52 #include "virnetdevtap.h"
53 #include "virnetdevopenvswitch.h"
54 #include "device_conf.h"
55 #include "virstoragefile.h"
56 #include "virtpm.h"
57 #include "virscsi.h"
58 #include "virnuma.h"
59 #include "virgic.h"
60 #include "virmdev.h"
61 #include "virdomainsnapshotobjlist.h"
62 #if defined(__linux__)
63 # include <linux/capability.h>
64 #endif
65 #include "logging/log_manager.h"
67 #include <sys/stat.h>
68 #include <fcntl.h>
70 #define VIR_FROM_THIS VIR_FROM_QEMU
72 VIR_LOG_INIT("qemu.qemu_command");
74 VIR_ENUM_DECL(virDomainDiskQEMUBus);
75 VIR_ENUM_IMPL(virDomainDiskQEMUBus,
76 VIR_DOMAIN_DISK_BUS_LAST,
77 "ide",
78 "floppy",
79 "scsi",
80 "virtio",
81 "xen",
82 "usb",
83 "uml",
84 "sata",
85 "sd",
89 VIR_ENUM_DECL(qemuDiskCacheV2);
91 VIR_ENUM_IMPL(qemuDiskCacheV2,
92 VIR_DOMAIN_DISK_CACHE_LAST,
93 "default",
94 "none",
95 "writethrough",
96 "writeback",
97 "directsync",
98 "unsafe",
101 VIR_ENUM_IMPL(qemuVideo,
102 VIR_DOMAIN_VIDEO_TYPE_LAST,
103 "", /* default value, we shouldn't see this */
104 "std",
105 "cirrus",
106 "vmware",
107 "", /* don't support xen */
108 "", /* don't support vbox */
109 "qxl",
110 "", /* don't support parallels */
111 "", /* no need for virtio */
112 "" /* don't support gop */,
113 "" /* 'none' doesn't make sense here */,
116 VIR_ENUM_DECL(qemuDeviceVideo);
118 VIR_ENUM_IMPL(qemuDeviceVideo,
119 VIR_DOMAIN_VIDEO_TYPE_LAST,
120 "", /* default value, we shouldn't see this */
121 "VGA",
122 "cirrus-vga",
123 "vmware-svga",
124 "", /* don't support xen */
125 "", /* don't support vbox */
126 "qxl-vga",
127 "", /* don't support parallels */
128 "virtio-vga",
129 "" /* don't support gop */,
130 "" /* 'none' doesn't make sense here */,
133 VIR_ENUM_DECL(qemuDeviceVideoSecondary);
135 VIR_ENUM_IMPL(qemuDeviceVideoSecondary,
136 VIR_DOMAIN_VIDEO_TYPE_LAST,
137 "", /* default value, we shouldn't see this */
138 "", /* no secondary device for VGA */
139 "", /* no secondary device for cirrus-vga */
140 "", /* no secondary device for vmware-svga */
141 "", /* don't support xen */
142 "", /* don't support vbox */
143 "qxl",
144 "", /* don't support parallels */
145 "virtio-gpu",
146 "" /* don't support gop */,
147 "" /* 'none' doesn't make sense here */,
150 VIR_ENUM_DECL(qemuSoundCodec);
152 VIR_ENUM_IMPL(qemuSoundCodec,
153 VIR_DOMAIN_SOUND_CODEC_TYPE_LAST,
154 "hda-duplex",
155 "hda-micro",
156 "hda-output",
159 VIR_ENUM_DECL(qemuControllerModelUSB);
161 VIR_ENUM_IMPL(qemuControllerModelUSB,
162 VIR_DOMAIN_CONTROLLER_MODEL_USB_LAST,
163 "piix3-usb-uhci",
164 "piix4-usb-uhci",
165 "usb-ehci",
166 "ich9-usb-ehci1",
167 "ich9-usb-uhci1",
168 "ich9-usb-uhci2",
169 "ich9-usb-uhci3",
170 "vt82c686b-usb-uhci",
171 "pci-ohci",
172 "nec-usb-xhci",
173 "qusb1",
174 "qusb2",
175 "qemu-xhci",
176 "none",
179 VIR_ENUM_DECL(qemuDomainFSDriver);
180 VIR_ENUM_IMPL(qemuDomainFSDriver,
181 VIR_DOMAIN_FS_DRIVER_TYPE_LAST,
182 "local",
183 "local",
184 "handle",
185 NULL,
186 NULL,
187 NULL,
190 VIR_ENUM_DECL(qemuNumaPolicy);
191 VIR_ENUM_IMPL(qemuNumaPolicy,
192 VIR_DOMAIN_NUMATUNE_MEM_LAST,
193 "bind",
194 "preferred",
195 "interleave",
200 * qemuBuildMasterKeyCommandLine:
201 * @cmd: the command to modify
202 * @qemuCaps qemu capabilities object
203 * @domainLibDir: location to find the master key
205 * Formats the command line for a master key if available
207 * Returns 0 on success, -1 w/ error message on failure
209 static int
210 qemuBuildMasterKeyCommandLine(virCommandPtr cmd,
211 qemuDomainObjPrivatePtr priv)
213 int ret = -1;
214 char *alias = NULL;
215 char *path = NULL;
216 virBuffer buf = VIR_BUFFER_INITIALIZER;
218 /* If the -object secret does not exist, then just return. This just
219 * means the domain won't be able to use a secret master key and is
220 * not a failure.
222 if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_OBJECT_SECRET)) {
223 VIR_INFO("secret object is not supported by this QEMU binary");
224 return 0;
227 if (!(alias = qemuDomainGetMasterKeyAlias()))
228 return -1;
230 /* Get the path. NB, the mocked test will not have the created
231 * file so we cannot check for existence, which is no different
232 * than other command line options which do not check for the
233 * existence of socket files before using.
235 if (!(path = qemuDomainGetMasterKeyFilePath(priv->libDir)))
236 goto cleanup;
238 virCommandAddArg(cmd, "-object");
239 virBufferAsprintf(&buf, "secret,id=%s,format=raw,file=", alias);
240 virQEMUBuildBufferEscapeComma(&buf, path);
241 virCommandAddArgBuffer(cmd, &buf);
243 ret = 0;
245 cleanup:
246 virBufferFreeAndReset(&buf);
247 VIR_FREE(alias);
248 VIR_FREE(path);
249 return ret;
254 * qemuVirCommandGetFDSet:
255 * @cmd: the command to modify
256 * @fd: fd to reassign to the child
258 * Get the parameters for the QEMU -add-fd command line option
259 * for the given file descriptor. The file descriptor must previously
260 * have been 'transferred' in a virCommandPassFD() call.
261 * This function for example returns "set=10,fd=20".
263 static char *
264 qemuVirCommandGetFDSet(virCommandPtr cmd, int fd)
266 char *result = NULL;
267 int idx = virCommandPassFDGetFDIndex(cmd, fd);
269 if (idx >= 0) {
270 ignore_value(virAsprintf(&result, "set=%d,fd=%d", idx, fd));
271 } else {
272 virReportError(VIR_ERR_INTERNAL_ERROR,
273 _("file descriptor %d has not been transferred"), fd);
276 return result;
281 * qemuVirCommandGetDevSet:
282 * @cmd: the command to modify
283 * @fd: fd to reassign to the child
285 * Get the parameters for the QEMU path= parameter where a file
286 * descriptor is accessed via a file descriptor set, for example
287 * /dev/fdset/10. The file descriptor must previously have been
288 * 'transferred' in a virCommandPassFD() call.
290 static char *
291 qemuVirCommandGetDevSet(virCommandPtr cmd, int fd)
293 char *result = NULL;
294 int idx = virCommandPassFDGetFDIndex(cmd, fd);
296 if (idx >= 0) {
297 ignore_value(virAsprintf(&result, "/dev/fdset/%d", idx));
298 } else {
299 virReportError(VIR_ERR_INTERNAL_ERROR,
300 _("file descriptor %d has not been transferred"), fd);
302 return result;
306 static int
307 qemuBuildDeviceAddressStr(virBufferPtr buf,
308 const virDomainDef *domainDef,
309 virDomainDeviceInfoPtr info,
310 virQEMUCapsPtr qemuCaps)
312 int ret = -1;
313 char *devStr = NULL;
314 const char *contAlias = NULL;
315 bool contIsPHB = false;
316 int contTargetIndex = 0;
318 if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
319 size_t i;
321 if (!(devStr = virPCIDeviceAddressAsString(&info->addr.pci)))
322 goto cleanup;
323 for (i = 0; i < domainDef->ncontrollers; i++) {
324 virDomainControllerDefPtr cont = domainDef->controllers[i];
326 if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI &&
327 cont->idx == info->addr.pci.bus) {
328 contAlias = cont->info.alias;
329 contIsPHB = virDomainControllerIsPSeriesPHB(cont);
330 contTargetIndex = cont->opts.pciopts.targetIndex;
332 if (!contAlias) {
333 virReportError(VIR_ERR_INTERNAL_ERROR,
334 _("Device alias was not set for PCI "
335 "controller with index %u required "
336 "for device at address %s"),
337 info->addr.pci.bus, devStr);
338 goto cleanup;
341 if (virDomainDeviceAliasIsUserAlias(contAlias)) {
342 /* When domain has builtin pci-root controller we don't put it
343 * onto cmd line. Therefore we can't set its alias. In that
344 * case, use the default one. */
345 if (!qemuDomainIsPSeries(domainDef) &&
346 cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT) {
347 if (virQEMUCapsHasPCIMultiBus(qemuCaps, domainDef))
348 contAlias = "pci.0";
349 else
350 contAlias = "pci";
351 } else if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT) {
352 contAlias = "pcie.0";
355 break;
358 if (!contAlias) {
359 virReportError(VIR_ERR_INTERNAL_ERROR,
360 _("Could not find PCI "
361 "controller with index %u required "
362 "for device at address %s"),
363 info->addr.pci.bus, devStr);
364 goto cleanup;
367 if (contIsPHB && contTargetIndex > 0) {
368 /* The PCI bus created by a spapr-pci-host-bridge device with
369 * alias 'x' will be called 'x.0' rather than 'x'; however,
370 * this does not apply to the implicit PHB in a pSeries guest,
371 * which always has the hardcoded name 'pci.0' */
372 virBufferAsprintf(buf, ",bus=%s.0", contAlias);
373 } else {
374 /* For all other controllers, the bus name matches the alias
375 * of the corresponding controller */
376 virBufferAsprintf(buf, ",bus=%s", contAlias);
379 if (info->addr.pci.multi == VIR_TRISTATE_SWITCH_ON)
380 virBufferAddLit(buf, ",multifunction=on");
381 else if (info->addr.pci.multi == VIR_TRISTATE_SWITCH_OFF)
382 virBufferAddLit(buf, ",multifunction=off");
383 virBufferAsprintf(buf, ",addr=0x%x", info->addr.pci.slot);
384 if (info->addr.pci.function != 0)
385 virBufferAsprintf(buf, ".0x%x", info->addr.pci.function);
386 } else if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB) {
387 if (!(contAlias = virDomainControllerAliasFind(domainDef,
388 VIR_DOMAIN_CONTROLLER_TYPE_USB,
389 info->addr.usb.bus)))
390 goto cleanup;
391 virBufferAsprintf(buf, ",bus=%s.0", contAlias);
392 if (virDomainUSBAddressPortIsValid(info->addr.usb.port)) {
393 virBufferAddLit(buf, ",port=");
394 virDomainUSBAddressPortFormatBuf(buf, info->addr.usb.port);
396 } else if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO) {
397 if (info->addr.spaprvio.has_reg)
398 virBufferAsprintf(buf, ",reg=0x%llx", info->addr.spaprvio.reg);
399 } else if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW) {
400 if (info->addr.ccw.assigned)
401 virBufferAsprintf(buf, ",devno=%x.%x.%04x",
402 info->addr.ccw.cssid,
403 info->addr.ccw.ssid,
404 info->addr.ccw.devno);
405 } else if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_ISA) {
406 virBufferAsprintf(buf, ",iobase=0x%x,irq=0x%x",
407 info->addr.isa.iobase,
408 info->addr.isa.irq);
411 ret = 0;
412 cleanup:
413 VIR_FREE(devStr);
414 return ret;
419 * qemuBuildVirtioDevStr
420 * @buf: virBufferPtr to append the built string
421 * @baseName: qemu virtio device basename string. Ex: virtio-rng for <rng>
422 * @qemuCaps: virQEMUCapPtr
423 * @devtype: virDomainDeviceType of the device. Ex: VIR_DOMAIN_DEVICE_TYPE_RNG
424 * @devdata: *DefPtr of the device definition
426 * Build the qemu virtio -device name from the passed parameters. Currently
427 * this is mostly about attaching the correct string prefix to @baseName for
428 * the passed @type. So for @baseName "virtio-rng" and devdata->info.type
429 * VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI, generate "virtio-rng-pci"
431 * Returns: -1 on failure, 0 on success
433 static int
434 qemuBuildVirtioDevStr(virBufferPtr buf,
435 const char *baseName,
436 virQEMUCapsPtr qemuCaps,
437 virDomainDeviceType devtype,
438 void *devdata)
440 const char *implName = NULL;
441 virDomainDeviceDef device = { .type = devtype };
442 virDomainDeviceInfoPtr info;
443 bool has_tmodel, has_ntmodel;
445 virDomainDeviceSetData(&device, devdata);
446 info = virDomainDeviceGetInfo(&device);
448 switch ((virDomainDeviceAddressType) info->type) {
449 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI:
450 implName = "pci";
451 break;
453 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO:
454 implName = "device";
455 break;
457 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW:
458 implName = "ccw";
459 break;
461 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390:
462 implName = "s390";
463 break;
465 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE:
466 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL:
467 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID:
468 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB:
469 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO:
470 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_ISA:
471 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM:
472 virReportError(VIR_ERR_INTERNAL_ERROR,
473 _("Unexpected address type for '%s'"), baseName);
474 return -1;
476 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE:
477 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_LAST:
478 default:
479 virReportEnumRangeError(virDomainDeviceAddressType, info->type);
480 return -1;
483 virBufferAsprintf(buf, "%s-%s", baseName, implName);
485 switch (devtype) {
486 case VIR_DOMAIN_DEVICE_DISK:
487 has_tmodel = device.data.disk->model == VIR_DOMAIN_DISK_MODEL_VIRTIO_TRANSITIONAL;
488 has_ntmodel = device.data.disk->model == VIR_DOMAIN_DISK_MODEL_VIRTIO_NON_TRANSITIONAL;
489 break;
491 case VIR_DOMAIN_DEVICE_NET:
492 has_tmodel = device.data.net->model == VIR_DOMAIN_NET_MODEL_VIRTIO_TRANSITIONAL;
493 has_ntmodel = device.data.net->model == VIR_DOMAIN_NET_MODEL_VIRTIO_NON_TRANSITIONAL;
494 break;
496 case VIR_DOMAIN_DEVICE_HOSTDEV:
497 if (device.data.hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI_HOST)
498 return 0;
499 has_tmodel = device.data.hostdev->source.subsys.u.scsi_host.model == VIR_DOMAIN_HOSTDEV_SUBSYS_SCSI_VHOST_MODEL_TYPE_VIRTIO_TRANSITIONAL;
500 has_ntmodel = device.data.hostdev->source.subsys.u.scsi_host.model == VIR_DOMAIN_HOSTDEV_SUBSYS_SCSI_VHOST_MODEL_TYPE_VIRTIO_NON_TRANSITIONAL;
501 break;
503 case VIR_DOMAIN_DEVICE_RNG:
504 has_tmodel = device.data.rng->model == VIR_DOMAIN_RNG_MODEL_VIRTIO_TRANSITIONAL;
505 has_ntmodel = device.data.rng->model == VIR_DOMAIN_RNG_MODEL_VIRTIO_NON_TRANSITIONAL;
506 break;
508 case VIR_DOMAIN_DEVICE_FS:
509 has_tmodel = device.data.fs->model == VIR_DOMAIN_FS_MODEL_VIRTIO_TRANSITIONAL;
510 has_ntmodel = device.data.fs->model == VIR_DOMAIN_FS_MODEL_VIRTIO_NON_TRANSITIONAL;
511 break;
513 case VIR_DOMAIN_DEVICE_MEMBALLOON:
514 has_tmodel = device.data.memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO_TRANSITIONAL;
515 has_ntmodel = device.data.memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO_NON_TRANSITIONAL;
516 break;
518 case VIR_DOMAIN_DEVICE_VSOCK:
519 has_tmodel = device.data.vsock->model == VIR_DOMAIN_VSOCK_MODEL_VIRTIO_TRANSITIONAL;
520 has_ntmodel = device.data.vsock->model == VIR_DOMAIN_VSOCK_MODEL_VIRTIO_NON_TRANSITIONAL;
521 break;
523 case VIR_DOMAIN_DEVICE_INPUT:
524 if (device.data.input->type != VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH)
525 return 0;
526 has_tmodel = device.data.input->model == VIR_DOMAIN_INPUT_MODEL_VIRTIO_TRANSITIONAL;
527 has_ntmodel = device.data.input->model == VIR_DOMAIN_INPUT_MODEL_VIRTIO_NON_TRANSITIONAL;
528 break;
530 case VIR_DOMAIN_DEVICE_CONTROLLER:
531 if (device.data.controller->type == VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL) {
532 has_tmodel = device.data.controller->model == VIR_DOMAIN_CONTROLLER_MODEL_VIRTIO_SERIAL_VIRTIO_TRANSITIONAL;
533 has_ntmodel = device.data.controller->model == VIR_DOMAIN_CONTROLLER_MODEL_VIRTIO_SERIAL_VIRTIO_NON_TRANSITIONAL;
534 } else if (device.data.controller->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI) {
535 has_tmodel = device.data.controller->model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_TRANSITIONAL;
536 has_ntmodel = device.data.controller->model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_NON_TRANSITIONAL;
537 } else {
538 return 0;
540 break;
542 case VIR_DOMAIN_DEVICE_LEASE:
543 case VIR_DOMAIN_DEVICE_SOUND:
544 case VIR_DOMAIN_DEVICE_VIDEO:
545 case VIR_DOMAIN_DEVICE_WATCHDOG:
546 case VIR_DOMAIN_DEVICE_GRAPHICS:
547 case VIR_DOMAIN_DEVICE_HUB:
548 case VIR_DOMAIN_DEVICE_REDIRDEV:
549 case VIR_DOMAIN_DEVICE_NONE:
550 case VIR_DOMAIN_DEVICE_SMARTCARD:
551 case VIR_DOMAIN_DEVICE_CHR:
552 case VIR_DOMAIN_DEVICE_NVRAM:
553 case VIR_DOMAIN_DEVICE_SHMEM:
554 case VIR_DOMAIN_DEVICE_TPM:
555 case VIR_DOMAIN_DEVICE_PANIC:
556 case VIR_DOMAIN_DEVICE_MEMORY:
557 case VIR_DOMAIN_DEVICE_IOMMU:
558 case VIR_DOMAIN_DEVICE_LAST:
559 default:
560 return 0;
563 if (info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI &&
564 (has_tmodel || has_ntmodel)) {
565 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
566 _("virtio (non-)transitional models are not "
567 "supported for address type=%s"),
568 virDomainDeviceAddressTypeToString(info->type));
569 return -1;
572 if (has_tmodel) {
573 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_PCI_TRANSITIONAL)) {
574 virBufferAddLit(buf, "-transitional");
575 } else if (virQEMUCapsGet(qemuCaps,
576 QEMU_CAPS_VIRTIO_PCI_DISABLE_LEGACY)) {
577 virBufferAddLit(buf, ",disable-legacy=off,disable-modern=off");
579 /* No error if -transitional is not supported: our address
580 * allocation will force the device into plain PCI bus, which
581 * is functionally identical to standard 'virtio-XXX' behavior
583 } else if (has_ntmodel) {
584 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_PCI_TRANSITIONAL)) {
585 virBufferAddLit(buf, "-non-transitional");
586 } else if (virQEMUCapsGet(qemuCaps,
587 QEMU_CAPS_VIRTIO_PCI_DISABLE_LEGACY)) {
588 /* Even if the QEMU binary doesn't support the non-transitional
589 * device, we can still make it work by manually disabling legacy
590 * VirtIO and enabling modern VirtIO */
591 virBufferAddLit(buf, ",disable-legacy=on,disable-modern=off");
592 } else {
593 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
594 _("virtio non-transitional model not supported "
595 "for this qemu"));
596 return -1;
600 return 0;
603 static int
604 qemuBuildVirtioOptionsStr(virBufferPtr buf,
605 virDomainVirtioOptionsPtr virtio,
606 virQEMUCapsPtr qemuCaps)
608 if (!virtio)
609 return 0;
611 if (virtio->iommu != VIR_TRISTATE_SWITCH_ABSENT) {
612 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_PCI_IOMMU_PLATFORM)) {
613 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
614 _("the iommu setting is not supported "
615 "with this QEMU binary"));
616 return -1;
618 virBufferAsprintf(buf, ",iommu_platform=%s",
619 virTristateSwitchTypeToString(virtio->iommu));
621 if (virtio->ats != VIR_TRISTATE_SWITCH_ABSENT) {
622 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_PCI_ATS)) {
623 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
624 _("the ats setting is not supported with this "
625 "QEMU binary"));
626 return -1;
628 virBufferAsprintf(buf, ",ats=%s",
629 virTristateSwitchTypeToString(virtio->ats));
632 return 0;
635 static int
636 qemuBuildRomStr(virBufferPtr buf,
637 virDomainDeviceInfoPtr info)
639 if (info->romenabled || info->rombar || info->romfile) {
640 if (info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
641 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
642 "%s", _("ROM tuning is only supported for PCI devices"));
643 return -1;
646 /* Passing an empty romfile= tells QEMU to disable ROM entirely for
647 * this device, and makes other settings irrelevant */
648 if (info->romenabled == VIR_TRISTATE_BOOL_NO) {
649 virBufferAddLit(buf, ",romfile=");
650 return 0;
653 switch (info->rombar) {
654 case VIR_TRISTATE_SWITCH_OFF:
655 virBufferAddLit(buf, ",rombar=0");
656 break;
657 case VIR_TRISTATE_SWITCH_ON:
658 virBufferAddLit(buf, ",rombar=1");
659 break;
660 default:
661 break;
663 if (info->romfile) {
664 virBufferAddLit(buf, ",romfile=");
665 virQEMUBuildBufferEscapeComma(buf, info->romfile);
669 return 0;
672 static int
673 qemuBuildIoEventFdStr(virBufferPtr buf,
674 virTristateSwitch use,
675 virQEMUCapsPtr qemuCaps)
677 if (use && virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_IOEVENTFD))
678 virBufferAsprintf(buf, ",ioeventfd=%s",
679 virTristateSwitchTypeToString(use));
680 return 0;
683 #define QEMU_SERIAL_PARAM_ACCEPTED_CHARS \
684 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_ .+"
686 static int
687 qemuSafeSerialParamValue(const char *value)
689 if (strspn(value, QEMU_SERIAL_PARAM_ACCEPTED_CHARS) != strlen(value)) {
690 virReportError(VIR_ERR_INTERNAL_ERROR,
691 _("driver serial '%s' contains unsafe characters"),
692 value);
693 return -1;
696 return 0;
701 * qemuBuildSecretInfoProps:
702 * @secinfo: pointer to the secret info object
703 * @props: json properties to return
705 * Build the JSON properties for the secret info type.
707 * Returns 0 on success with the filled in JSON property; otherwise,
708 * returns -1 on failure error message set.
711 qemuBuildSecretInfoProps(qemuDomainSecretInfoPtr secinfo,
712 virJSONValuePtr *propsret)
714 int ret = -1;
715 char *keyid = NULL;
717 if (!(keyid = qemuDomainGetMasterKeyAlias()))
718 return -1;
720 ret = qemuMonitorCreateObjectProps(propsret,
721 "secret", secinfo->s.aes.alias,
722 "s:data", secinfo->s.aes.ciphertext,
723 "s:keyid", keyid,
724 "s:iv", secinfo->s.aes.iv,
725 "s:format", "base64", NULL);
727 VIR_FREE(keyid);
728 return ret;
733 * qemuBuildObjectSecretCommandLine:
734 * @cmd: the command to modify
735 * @secinfo: pointer to the secret info object
737 * If the secinfo is available and associated with an AES secret,
738 * then format the command line for the secret object. This object
739 * will be referenced by the device that needs/uses it, so it needs
740 * to be in place first.
742 * Returns 0 on success, -1 w/ error message on failure
744 static int
745 qemuBuildObjectSecretCommandLine(virCommandPtr cmd,
746 qemuDomainSecretInfoPtr secinfo)
748 virBuffer buf = VIR_BUFFER_INITIALIZER;
749 int ret = -1;
750 virJSONValuePtr props = NULL;
752 if (qemuBuildSecretInfoProps(secinfo, &props) < 0)
753 return -1;
755 if (virQEMUBuildObjectCommandlineFromJSON(&buf, props) < 0)
756 goto cleanup;
758 virCommandAddArg(cmd, "-object");
759 virCommandAddArgBuffer(cmd, &buf);
761 ret = 0;
763 cleanup:
764 virBufferFreeAndReset(&buf);
765 virJSONValueFree(props);
766 return ret;
770 /* qemuBuildDiskSecinfoCommandLine:
771 * @cmd: Pointer to the command string
772 * @secinfo: Pointer to a possible secinfo
774 * Add the secret object for the disks that will be using it to perform
775 * their authentication.
777 * Returns 0 on success, -1 w/ error on some sort of failure.
779 static int
780 qemuBuildDiskSecinfoCommandLine(virCommandPtr cmd,
781 qemuDomainSecretInfoPtr secinfo)
783 /* Not necessary for non AES secrets */
784 if (!secinfo || secinfo->type != VIR_DOMAIN_SECRET_INFO_TYPE_AES)
785 return 0;
787 return qemuBuildObjectSecretCommandLine(cmd, secinfo);
791 /* qemuBuildGeneralSecinfoURI:
792 * @uri: Pointer to the URI structure to add to
793 * @secinfo: Pointer to the secret info data (if present)
795 * If we have a secinfo, then build the command line options for
796 * the secret info for the "general" case (somewhat a misnomer since
797 * an iscsi disk is the only one with a secinfo).
799 * Returns 0 on success or if no secinfo,
800 * -1 and error message if fail to add secret information
802 static int
803 qemuBuildGeneralSecinfoURI(virURIPtr uri,
804 qemuDomainSecretInfoPtr secinfo)
806 if (!secinfo)
807 return 0;
809 switch ((qemuDomainSecretInfoType) secinfo->type) {
810 case VIR_DOMAIN_SECRET_INFO_TYPE_PLAIN:
811 if (secinfo->s.plain.secret) {
812 if (!virStringBufferIsPrintable(secinfo->s.plain.secret,
813 secinfo->s.plain.secretlen)) {
814 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
815 _("found non printable characters in secret"));
816 return -1;
818 if (virAsprintf(&uri->user, "%s:%s",
819 secinfo->s.plain.username,
820 secinfo->s.plain.secret) < 0)
821 return -1;
822 } else {
823 if (VIR_STRDUP(uri->user, secinfo->s.plain.username) < 0)
824 return -1;
826 break;
828 case VIR_DOMAIN_SECRET_INFO_TYPE_AES:
829 case VIR_DOMAIN_SECRET_INFO_TYPE_LAST:
830 return -1;
833 return 0;
837 /* qemuBuildRBDSecinfoURI:
838 * @uri: Pointer to the URI structure to add to
839 * @secinfo: Pointer to the secret info data (if present)
841 * If we have a secinfo, then build the command line options for
842 * the secret info for the RBD network storage. Assumption for this
843 * is both username and secret exist for plaintext
845 * Returns 0 on success or if no secinfo,
846 * -1 and error message if fail to add secret information
848 static int
849 qemuBuildRBDSecinfoURI(virBufferPtr buf,
850 qemuDomainSecretInfoPtr secinfo)
852 VIR_AUTODISPOSE_STR base64secret = NULL;
854 if (!secinfo) {
855 virBufferAddLit(buf, ":auth_supported=none");
856 return 0;
859 switch ((qemuDomainSecretInfoType) secinfo->type) {
860 case VIR_DOMAIN_SECRET_INFO_TYPE_PLAIN:
861 if (!(base64secret = virStringEncodeBase64(secinfo->s.plain.secret,
862 secinfo->s.plain.secretlen)))
863 return -1;
864 virBufferEscape(buf, '\\', ":", ":id=%s", secinfo->s.plain.username);
865 virBufferEscape(buf, '\\', ":",
866 ":key=%s:auth_supported=cephx\\;none",
867 base64secret);
868 break;
870 case VIR_DOMAIN_SECRET_INFO_TYPE_AES:
871 virBufferEscape(buf, '\\', ":", ":id=%s:auth_supported=cephx\\;none",
872 secinfo->s.aes.username);
873 break;
875 case VIR_DOMAIN_SECRET_INFO_TYPE_LAST:
876 return -1;
879 return 0;
883 /* qemuBuildTLSx509BackendProps:
884 * @tlspath: path to the TLS credentials
885 * @listen: boolen listen for client or server setting
886 * @verifypeer: boolean to enable peer verification (form of authorization)
887 * @alias: alias for the TLS credentials object
888 * @secalias: if one exists, the alias of the security object for passwordid
889 * @qemuCaps: capabilities
890 * @propsret: json properties to return
892 * Create a backend string for the tls-creds-x509 object.
894 * Returns 0 on success, -1 on failure with error set.
897 qemuBuildTLSx509BackendProps(const char *tlspath,
898 bool isListen,
899 bool verifypeer,
900 const char *alias,
901 const char *secalias,
902 virQEMUCapsPtr qemuCaps,
903 virJSONValuePtr *propsret)
905 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_TLS_CREDS_X509)) {
906 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
907 _("tls-creds-x509 not supported in this QEMU binary"));
908 return -1;
911 if (qemuMonitorCreateObjectProps(propsret, "tls-creds-x509", alias,
912 "s:dir", tlspath,
913 "s:endpoint", (isListen ? "server": "client"),
914 "b:verify-peer", (isListen ? verifypeer : true),
915 "S:passwordid", secalias,
916 NULL) < 0)
917 return -1;
919 return 0;
923 /* qemuBuildTLSx509CommandLine:
924 * @cmd: Pointer to command
925 * @tlspath: path to the TLS credentials
926 * @listen: boolen listen for client or server setting
927 * @verifypeer: boolean to enable peer verification (form of authorization)
928 * @certEncSecretAlias: alias of a 'secret' object for decrypting TLS private key
929 * (optional)
930 * @alias: TLS object alias
931 * @qemuCaps: capabilities
933 * Create the command line for a TLS object
935 * Returns 0 on success, -1 on failure with error set.
937 static int
938 qemuBuildTLSx509CommandLine(virCommandPtr cmd,
939 const char *tlspath,
940 bool isListen,
941 bool verifypeer,
942 const char *certEncSecretAlias,
943 const char *alias,
944 virQEMUCapsPtr qemuCaps)
946 virBuffer buf = VIR_BUFFER_INITIALIZER;
947 int ret = -1;
948 virJSONValuePtr props = NULL;
950 if (qemuBuildTLSx509BackendProps(tlspath, isListen, verifypeer, alias,
951 certEncSecretAlias, qemuCaps, &props) < 0)
952 goto cleanup;
954 if (virQEMUBuildObjectCommandlineFromJSON(&buf, props) < 0)
955 goto cleanup;
957 virCommandAddArg(cmd, "-object");
958 virCommandAddArgBuffer(cmd, &buf);
960 ret = 0;
962 cleanup:
963 virBufferFreeAndReset(&buf);
964 virJSONValueFree(props);
965 return ret;
969 static char *
970 qemuBuildNetworkDriveURI(virStorageSourcePtr src,
971 qemuDomainSecretInfoPtr secinfo)
973 virURIPtr uri = NULL;
974 char *ret = NULL;
976 if (!(uri = qemuBlockStorageSourceGetURI(src)))
977 goto cleanup;
979 if (src->hosts->socket &&
980 virAsprintf(&uri->query, "socket=%s", src->hosts->socket) < 0)
981 goto cleanup;
983 if (qemuBuildGeneralSecinfoURI(uri, secinfo) < 0)
984 goto cleanup;
986 ret = virURIFormat(uri);
988 cleanup:
989 virURIFree(uri);
990 return ret;
994 static char *
995 qemuBuildNetworkDriveStr(virStorageSourcePtr src,
996 qemuDomainSecretInfoPtr secinfo)
998 char *ret = NULL;
999 virBuffer buf = VIR_BUFFER_INITIALIZER;
1000 size_t i;
1002 switch ((virStorageNetProtocol) src->protocol) {
1003 case VIR_STORAGE_NET_PROTOCOL_NBD:
1004 if (src->nhosts != 1) {
1005 virReportError(VIR_ERR_INTERNAL_ERROR,
1006 _("protocol '%s' accepts only one host"),
1007 virStorageNetProtocolTypeToString(src->protocol));
1008 goto cleanup;
1011 if (!((src->hosts->name && strchr(src->hosts->name, ':')) ||
1012 (src->hosts->transport == VIR_STORAGE_NET_HOST_TRANS_TCP &&
1013 !src->hosts->name) ||
1014 (src->hosts->transport == VIR_STORAGE_NET_HOST_TRANS_UNIX &&
1015 src->hosts->socket &&
1016 src->hosts->socket[0] != '/'))) {
1018 virBufferAddLit(&buf, "nbd:");
1020 switch (src->hosts->transport) {
1021 case VIR_STORAGE_NET_HOST_TRANS_TCP:
1022 virBufferAsprintf(&buf, "%s:%u",
1023 src->hosts->name, src->hosts->port);
1024 break;
1026 case VIR_STORAGE_NET_HOST_TRANS_UNIX:
1027 if (!src->hosts->socket) {
1028 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1029 _("socket attribute required for "
1030 "unix transport"));
1031 goto cleanup;
1034 virBufferAsprintf(&buf, "unix:%s", src->hosts->socket);
1035 break;
1037 default:
1038 virReportError(VIR_ERR_INTERNAL_ERROR,
1039 _("nbd does not support transport '%s'"),
1040 virStorageNetHostTransportTypeToString(src->hosts->transport));
1041 goto cleanup;
1044 if (src->path)
1045 virBufferAsprintf(&buf, ":exportname=%s", src->path);
1047 if (virBufferCheckError(&buf) < 0)
1048 goto cleanup;
1050 ret = virBufferContentAndReset(&buf);
1051 goto cleanup;
1053 /* NBD code uses URI formatting scheme as others in some cases */
1054 ret = qemuBuildNetworkDriveURI(src, secinfo);
1055 break;
1057 case VIR_STORAGE_NET_PROTOCOL_HTTP:
1058 case VIR_STORAGE_NET_PROTOCOL_HTTPS:
1059 case VIR_STORAGE_NET_PROTOCOL_FTP:
1060 case VIR_STORAGE_NET_PROTOCOL_FTPS:
1061 case VIR_STORAGE_NET_PROTOCOL_TFTP:
1062 case VIR_STORAGE_NET_PROTOCOL_ISCSI:
1063 case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
1064 ret = qemuBuildNetworkDriveURI(src, secinfo);
1065 break;
1067 case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
1068 if (!src->path) {
1069 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1070 _("missing disk source for 'sheepdog' protocol"));
1071 goto cleanup;
1074 if (src->nhosts == 0) {
1075 if (virAsprintf(&ret, "sheepdog:%s", src->path) < 0)
1076 goto cleanup;
1077 } else if (src->nhosts == 1) {
1078 if (virAsprintf(&ret, "sheepdog:%s:%u:%s",
1079 src->hosts->name, src->hosts->port,
1080 src->path) < 0)
1081 goto cleanup;
1082 } else {
1083 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1084 _("protocol 'sheepdog' accepts up to one host"));
1085 goto cleanup;
1088 break;
1090 case VIR_STORAGE_NET_PROTOCOL_RBD:
1091 if (strchr(src->path, ':')) {
1092 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1093 _("':' not allowed in RBD source volume name '%s'"),
1094 src->path);
1095 goto cleanup;
1098 virBufferStrcat(&buf, "rbd:", src->volume, "/", src->path, NULL);
1100 if (src->snapshot)
1101 virBufferEscape(&buf, '\\', ":", "@%s", src->snapshot);
1103 if (qemuBuildRBDSecinfoURI(&buf, secinfo) < 0)
1104 goto cleanup;
1106 if (src->nhosts > 0) {
1107 virBufferAddLit(&buf, ":mon_host=");
1108 for (i = 0; i < src->nhosts; i++) {
1109 if (i)
1110 virBufferAddLit(&buf, "\\;");
1112 /* assume host containing : is ipv6 */
1113 if (strchr(src->hosts[i].name, ':'))
1114 virBufferEscape(&buf, '\\', ":", "[%s]",
1115 src->hosts[i].name);
1116 else
1117 virBufferAsprintf(&buf, "%s", src->hosts[i].name);
1119 if (src->hosts[i].port)
1120 virBufferAsprintf(&buf, "\\:%u", src->hosts[i].port);
1124 if (src->configFile)
1125 virBufferEscape(&buf, '\\', ":", ":conf=%s", src->configFile);
1127 if (virBufferCheckError(&buf) < 0)
1128 goto cleanup;
1130 ret = virBufferContentAndReset(&buf);
1131 break;
1133 case VIR_STORAGE_NET_PROTOCOL_VXHS:
1134 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1135 _("VxHS protocol does not support URI syntax"));
1136 goto cleanup;
1138 case VIR_STORAGE_NET_PROTOCOL_SSH:
1139 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1140 _("'ssh' protocol is not yet supported"));
1141 goto cleanup;
1143 case VIR_STORAGE_NET_PROTOCOL_LAST:
1144 case VIR_STORAGE_NET_PROTOCOL_NONE:
1145 virReportError(VIR_ERR_INTERNAL_ERROR,
1146 _("Unexpected network protocol '%s'"),
1147 virStorageNetProtocolTypeToString(src->protocol));
1148 goto cleanup;
1151 cleanup:
1152 virBufferFreeAndReset(&buf);
1154 return ret;
1159 qemuGetDriveSourceString(virStorageSourcePtr src,
1160 qemuDomainSecretInfoPtr secinfo,
1161 char **source)
1163 int actualType = virStorageSourceGetActualType(src);
1164 int ret = -1;
1166 *source = NULL;
1168 /* return 1 for empty sources */
1169 if (virStorageSourceIsEmpty(src))
1170 return 1;
1172 switch ((virStorageType)actualType) {
1173 case VIR_STORAGE_TYPE_BLOCK:
1174 case VIR_STORAGE_TYPE_FILE:
1175 case VIR_STORAGE_TYPE_DIR:
1176 if (VIR_STRDUP(*source, src->path) < 0)
1177 goto cleanup;
1179 break;
1181 case VIR_STORAGE_TYPE_NETWORK:
1182 if (!(*source = qemuBuildNetworkDriveStr(src, secinfo)))
1183 goto cleanup;
1184 break;
1186 case VIR_STORAGE_TYPE_VOLUME:
1187 case VIR_STORAGE_TYPE_NONE:
1188 case VIR_STORAGE_TYPE_LAST:
1189 break;
1192 ret = 0;
1194 cleanup:
1195 return ret;
1199 static bool
1200 qemuDiskConfigBlkdeviotuneHasBasic(virDomainDiskDefPtr disk)
1202 return disk->blkdeviotune.total_bytes_sec ||
1203 disk->blkdeviotune.read_bytes_sec ||
1204 disk->blkdeviotune.write_bytes_sec ||
1205 disk->blkdeviotune.total_iops_sec ||
1206 disk->blkdeviotune.read_iops_sec ||
1207 disk->blkdeviotune.write_iops_sec;
1211 static bool
1212 qemuDiskConfigBlkdeviotuneHasMax(virDomainDiskDefPtr disk)
1214 return disk->blkdeviotune.total_bytes_sec_max ||
1215 disk->blkdeviotune.read_bytes_sec_max ||
1216 disk->blkdeviotune.write_bytes_sec_max ||
1217 disk->blkdeviotune.total_iops_sec_max ||
1218 disk->blkdeviotune.read_iops_sec_max ||
1219 disk->blkdeviotune.write_iops_sec_max ||
1220 disk->blkdeviotune.size_iops_sec;
1224 static bool
1225 qemuDiskConfigBlkdeviotuneHasMaxLength(virDomainDiskDefPtr disk)
1227 return disk->blkdeviotune.total_bytes_sec_max_length ||
1228 disk->blkdeviotune.read_bytes_sec_max_length ||
1229 disk->blkdeviotune.write_bytes_sec_max_length ||
1230 disk->blkdeviotune.total_iops_sec_max_length ||
1231 disk->blkdeviotune.read_iops_sec_max_length ||
1232 disk->blkdeviotune.write_iops_sec_max_length;
1236 bool
1237 qemuDiskConfigBlkdeviotuneEnabled(virDomainDiskDefPtr disk)
1239 return !!disk->blkdeviotune.group_name ||
1240 qemuDiskConfigBlkdeviotuneHasBasic(disk) ||
1241 qemuDiskConfigBlkdeviotuneHasMax(disk) ||
1242 qemuDiskConfigBlkdeviotuneHasMaxLength(disk);
1247 * qemuCheckDiskConfigBlkdeviotune:
1248 * @disk: disk configuration
1249 * @qemuCaps: qemu capabilities, NULL if checking cold-configuration
1251 * Checks whether block io tuning settings make sense. Returns -1 on error and
1252 * reports a proper libvirt error.
1254 static int
1255 qemuCheckDiskConfigBlkdeviotune(virDomainDiskDefPtr disk,
1256 virQEMUCapsPtr qemuCaps)
1258 /* group_name by itself is ignored by qemu */
1259 if (disk->blkdeviotune.group_name &&
1260 !qemuDiskConfigBlkdeviotuneHasBasic(disk) &&
1261 !qemuDiskConfigBlkdeviotuneHasMax(disk) &&
1262 !qemuDiskConfigBlkdeviotuneHasMaxLength(disk)) {
1263 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1264 _("group_name can be configured only together with "
1265 "settings"));
1266 return -1;
1269 if (disk->blkdeviotune.total_bytes_sec > QEMU_BLOCK_IOTUNE_MAX ||
1270 disk->blkdeviotune.read_bytes_sec > QEMU_BLOCK_IOTUNE_MAX ||
1271 disk->blkdeviotune.write_bytes_sec > QEMU_BLOCK_IOTUNE_MAX ||
1272 disk->blkdeviotune.total_iops_sec > QEMU_BLOCK_IOTUNE_MAX ||
1273 disk->blkdeviotune.read_iops_sec > QEMU_BLOCK_IOTUNE_MAX ||
1274 disk->blkdeviotune.write_iops_sec > QEMU_BLOCK_IOTUNE_MAX ||
1275 disk->blkdeviotune.total_bytes_sec_max > QEMU_BLOCK_IOTUNE_MAX ||
1276 disk->blkdeviotune.read_bytes_sec_max > QEMU_BLOCK_IOTUNE_MAX ||
1277 disk->blkdeviotune.write_bytes_sec_max > QEMU_BLOCK_IOTUNE_MAX ||
1278 disk->blkdeviotune.total_iops_sec_max > QEMU_BLOCK_IOTUNE_MAX ||
1279 disk->blkdeviotune.read_iops_sec_max > QEMU_BLOCK_IOTUNE_MAX ||
1280 disk->blkdeviotune.write_iops_sec_max > QEMU_BLOCK_IOTUNE_MAX ||
1281 disk->blkdeviotune.size_iops_sec > QEMU_BLOCK_IOTUNE_MAX) {
1282 virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED,
1283 _("block I/O throttle limit must "
1284 "be no more than %llu using QEMU"), QEMU_BLOCK_IOTUNE_MAX);
1285 return -1;
1288 if (qemuCaps) {
1289 /* block I/O throttling 1.7 */
1290 if (qemuDiskConfigBlkdeviotuneHasMax(disk) &&
1291 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_IOTUNE_MAX)) {
1292 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1293 _("there are some block I/O throttling parameters "
1294 "that are not supported with this QEMU binary"));
1295 return -1;
1298 /* block I/O group 2.4 */
1299 if (disk->blkdeviotune.group_name &&
1300 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_IOTUNE_GROUP)) {
1301 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1302 _("the block I/O throttling group parameter is "
1303 "not supported with this QEMU binary"));
1304 return -1;
1307 /* block I/O throttling length 2.6 */
1308 if (qemuDiskConfigBlkdeviotuneHasMaxLength(disk) &&
1309 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_IOTUNE_MAX_LENGTH)) {
1310 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1311 _("there are some block I/O throttling length parameters "
1312 "that are not supported with this QEMU binary"));
1313 return -1;
1317 return 0;
1322 * qemuCheckDiskConfig:
1323 * @disk: disk definition
1324 * @qemuCaps: qemu capabilities, may be NULL for cold-plug check
1326 * Perform disk definition config validity checks. Returns -1 on error with
1327 * error reported.
1330 qemuCheckDiskConfig(virDomainDiskDefPtr disk,
1331 virQEMUCapsPtr qemuCaps)
1333 if (qemuCheckDiskConfigBlkdeviotune(disk, qemuCaps) < 0)
1334 return -1;
1336 if (virDiskNameToIndex(disk->dst) < 0) {
1337 virReportError(VIR_ERR_INTERNAL_ERROR,
1338 _("unsupported disk type '%s'"), disk->dst);
1339 return -1;
1342 if (disk->wwn) {
1343 if ((disk->bus != VIR_DOMAIN_DISK_BUS_IDE) &&
1344 (disk->bus != VIR_DOMAIN_DISK_BUS_SCSI)) {
1345 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1346 _("Only ide and scsi disk support wwn"));
1347 return -1;
1351 if ((disk->vendor || disk->product) &&
1352 disk->bus != VIR_DOMAIN_DISK_BUS_SCSI) {
1353 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1354 _("Only scsi disk supports vendor and product"));
1355 return -1;
1358 if (disk->device == VIR_DOMAIN_DISK_DEVICE_LUN) {
1359 /* make sure that both the bus supports type='lun' (SG_IO). */
1360 if (disk->bus != VIR_DOMAIN_DISK_BUS_VIRTIO &&
1361 disk->bus != VIR_DOMAIN_DISK_BUS_SCSI) {
1362 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1363 _("disk device='lun' is not supported for bus='%s'"),
1364 virDomainDiskQEMUBusTypeToString(disk->bus));
1365 return -1;
1368 if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI &&
1369 disk->src->format != VIR_STORAGE_FILE_RAW) {
1370 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1371 _("disk device 'lun' using target 'scsi' must use "
1372 "'raw' format"));
1373 return -1;
1376 if (qemuDomainDefValidateDiskLunSource(disk->src) < 0)
1377 return -1;
1379 if (disk->wwn) {
1380 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1381 _("Setting wwn is not supported for lun device"));
1382 return -1;
1384 if (disk->vendor || disk->product) {
1385 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1386 _("Setting vendor or product is not supported "
1387 "for lun device"));
1388 return -1;
1392 switch (disk->bus) {
1393 case VIR_DOMAIN_DISK_BUS_SCSI:
1394 if (disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE) {
1395 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1396 _("unexpected address type for scsi disk"));
1397 return -1;
1400 /* Setting bus= attr for SCSI drives, causes a controller
1401 * to be created. Yes this is slightly odd. It is not possible
1402 * to have > 1 bus on a SCSI controller (yet). */
1403 if (disk->info.addr.drive.bus != 0) {
1404 virReportError(VIR_ERR_INTERNAL_ERROR,
1405 "%s", _("SCSI controller only supports 1 bus"));
1406 return -1;
1408 break;
1410 case VIR_DOMAIN_DISK_BUS_IDE:
1411 if (disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE) {
1412 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1413 _("unexpected address type for ide disk"));
1414 return -1;
1416 /* We can only have 1 IDE controller (currently) */
1417 if (disk->info.addr.drive.controller != 0) {
1418 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1419 _("Only 1 IDE controller is supported"));
1420 return -1;
1422 break;
1424 case VIR_DOMAIN_DISK_BUS_FDC:
1425 if (disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE) {
1426 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1427 _("unexpected address type for fdc disk"));
1428 return -1;
1430 /* We can only have 1 FDC controller (currently) */
1431 if (disk->info.addr.drive.controller != 0) {
1432 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1433 _("Only 1 fdc controller is supported"));
1434 return -1;
1436 /* We can only have 1 FDC bus (currently) */
1437 if (disk->info.addr.drive.bus != 0) {
1438 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1439 _("Only 1 fdc bus is supported"));
1440 return -1;
1442 if (disk->info.addr.drive.target != 0) {
1443 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1444 _("target must be 0 for controller fdc"));
1445 return -1;
1447 break;
1449 case VIR_DOMAIN_DISK_BUS_VIRTIO:
1450 case VIR_DOMAIN_DISK_BUS_XEN:
1451 case VIR_DOMAIN_DISK_BUS_SD:
1452 break;
1455 if (disk->src->readonly &&
1456 disk->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
1457 if (disk->bus == VIR_DOMAIN_DISK_BUS_IDE) {
1458 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1459 _("readonly ide disks are not supported"));
1460 return -1;
1463 if (disk->bus == VIR_DOMAIN_DISK_BUS_SATA) {
1464 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1465 _("readonly sata disks are not supported"));
1466 return -1;
1470 if (disk->transient) {
1471 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1472 _("transient disks not supported yet"));
1473 return -1;
1476 if (disk->iomode == VIR_DOMAIN_DISK_IO_NATIVE &&
1477 disk->cachemode != VIR_DOMAIN_DISK_CACHE_DIRECTSYNC &&
1478 disk->cachemode != VIR_DOMAIN_DISK_CACHE_DISABLE) {
1479 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1480 _("native I/O needs either no disk cache "
1481 "or directsync cache mode, QEMU will fallback "
1482 "to aio=threads"));
1483 return -1;
1486 if (qemuCaps) {
1487 if (disk->serial &&
1488 disk->bus == VIR_DOMAIN_DISK_BUS_SCSI &&
1489 disk->device == VIR_DOMAIN_DISK_DEVICE_LUN) {
1490 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1491 _("scsi-block 'lun' devices do not support the "
1492 "serial property"));
1493 return -1;
1496 if (disk->discard &&
1497 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_DISCARD)) {
1498 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1499 _("discard is not supported by this QEMU binary"));
1500 return -1;
1503 if (disk->detect_zeroes &&
1504 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_DETECT_ZEROES)) {
1505 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1506 _("detect_zeroes is not supported by this QEMU binary"));
1507 return -1;
1511 if (disk->serial &&
1512 qemuSafeSerialParamValue(disk->serial) < 0)
1513 return -1;
1515 return 0;
1519 /* QEMU 1.2 and later have a binary flag -enable-fips that must be
1520 * used for VNC auth to obey FIPS settings; but the flag only
1521 * exists on Linux, and with no way to probe for it via QMP. Our
1522 * solution: if FIPS mode is required, then unconditionally use
1523 * the flag, regardless of qemu version, for the following matrix:
1525 * old QEMU new QEMU
1526 * FIPS enabled doesn't start VNC auth disabled
1527 * FIPS disabled/missing VNC auth enabled VNC auth enabled
1529 bool
1530 qemuCheckFips(void)
1532 bool ret = false;
1534 if (virFileExists("/proc/sys/crypto/fips_enabled")) {
1535 char *buf = NULL;
1537 if (virFileReadAll("/proc/sys/crypto/fips_enabled", 10, &buf) < 0)
1538 return ret;
1539 if (STREQ(buf, "1\n"))
1540 ret = true;
1541 VIR_FREE(buf);
1544 return ret;
1549 * qemuDiskBusNeedsDriveArg:
1550 * @bus: disk bus
1552 * Unfortunately it is not possible to use -device for SD devices.
1553 * Fortunately, those don't need static PCI addresses, so we can use -drive
1554 * without -device.
1556 bool
1557 qemuDiskBusNeedsDriveArg(int bus)
1559 return bus == VIR_DOMAIN_DISK_BUS_SD;
1564 * qemuDiskSourceNeedsProps:
1565 * @src: disk source
1567 * Returns true, if the disk source needs to be generated from the JSON
1568 * representation. Otherwise, the disk source should be represented using
1569 * the legacy representation.
1571 static bool
1572 qemuDiskSourceNeedsProps(virStorageSourcePtr src,
1573 virQEMUCapsPtr qemuCaps)
1575 int actualType = virStorageSourceGetActualType(src);
1577 if (actualType == VIR_STORAGE_TYPE_NETWORK &&
1578 src->protocol == VIR_STORAGE_NET_PROTOCOL_GLUSTER &&
1579 src->nhosts > 1)
1580 return true;
1582 if (actualType == VIR_STORAGE_TYPE_NETWORK &&
1583 src->protocol == VIR_STORAGE_NET_PROTOCOL_VXHS)
1584 return true;
1586 if (actualType == VIR_STORAGE_TYPE_NETWORK &&
1587 src->protocol == VIR_STORAGE_NET_PROTOCOL_ISCSI &&
1588 virQEMUCapsGet(qemuCaps, QEMU_CAPS_ISCSI_PASSWORD_SECRET))
1589 return true;
1591 if (actualType == VIR_STORAGE_TYPE_NETWORK &&
1592 src->protocol == VIR_STORAGE_NET_PROTOCOL_NBD &&
1593 src->haveTLS == VIR_TRISTATE_BOOL_YES)
1594 return true;
1596 return false;
1601 * qemuDiskSourceGetProps:
1602 * @src: disk source struct
1604 * Returns the disk source struct wrapped so that it can be used as disk source
1605 * directly by converting it from json.
1607 static virJSONValuePtr
1608 qemuDiskSourceGetProps(virStorageSourcePtr src)
1610 virJSONValuePtr props;
1611 virJSONValuePtr ret;
1613 if (!(props = qemuBlockStorageSourceGetBackendProps(src, true)))
1614 return NULL;
1616 if (virJSONValueObjectCreate(&ret, "a:file", &props, NULL) < 0) {
1617 virJSONValueFree(props);
1618 return NULL;
1621 return ret;
1625 static int
1626 qemuBuildDriveSourcePR(virBufferPtr buf,
1627 virDomainDiskDefPtr disk)
1629 char *alias = NULL;
1630 const char *defaultAlias = NULL;
1632 if (!disk->src->pr)
1633 return 0;
1635 if (virStoragePRDefIsManaged(disk->src->pr))
1636 defaultAlias = qemuDomainGetManagedPRAlias();
1637 else if (!(alias = qemuDomainGetUnmanagedPRAlias(disk->info.alias)))
1638 return -1;
1641 virBufferAsprintf(buf, ",file.pr-manager=%s", alias ? alias : defaultAlias);
1642 VIR_FREE(alias);
1643 return 0;
1647 static int
1648 qemuBuildDriveSourceStr(virDomainDiskDefPtr disk,
1649 virQEMUCapsPtr qemuCaps,
1650 virBufferPtr buf)
1652 int actualType = virStorageSourceGetActualType(disk->src);
1653 qemuDomainStorageSourcePrivatePtr srcpriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(disk->src);
1654 qemuDomainSecretInfoPtr secinfo = NULL;
1655 qemuDomainSecretInfoPtr encinfo = NULL;
1656 virJSONValuePtr srcprops = NULL;
1657 char *source = NULL;
1658 bool rawluks = false;
1659 int ret = -1;
1661 if (srcpriv) {
1662 secinfo = srcpriv->secinfo;
1663 encinfo = srcpriv->encinfo;
1666 if (qemuDiskSourceNeedsProps(disk->src, qemuCaps) &&
1667 !(srcprops = qemuDiskSourceGetProps(disk->src)))
1668 goto cleanup;
1670 if (!srcprops &&
1671 qemuGetDriveSourceString(disk->src, secinfo, &source) < 0)
1672 goto cleanup;
1674 /* nothing to format if the drive is empty */
1675 if (!(source || srcprops) ||
1676 ((disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY ||
1677 disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM) &&
1678 disk->tray_status == VIR_DOMAIN_DISK_TRAY_OPEN)) {
1679 ret = 0;
1680 goto cleanup;
1683 if (actualType == VIR_STORAGE_TYPE_BLOCK &&
1684 disk->tray_status == VIR_DOMAIN_DISK_TRAY_OPEN) {
1685 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1686 disk->src->type == VIR_STORAGE_TYPE_VOLUME ?
1687 _("tray status 'open' is invalid for block type volume") :
1688 _("tray status 'open' is invalid for block type disk"));
1689 goto cleanup;
1692 if (source) {
1693 virBufferAddLit(buf, "file=");
1695 /* for now the DIR based storage is handled by the magic FAT format */
1696 if (actualType == VIR_STORAGE_TYPE_DIR) {
1697 virBufferAddLit(buf, "fat:");
1699 if (disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY)
1700 virBufferAddLit(buf, "floppy:");
1703 virQEMUBuildBufferEscapeComma(buf, source);
1705 if (secinfo && secinfo->type == VIR_DOMAIN_SECRET_INFO_TYPE_AES)
1706 virBufferAsprintf(buf, ",file.password-secret=%s", secinfo->s.aes.alias);
1708 if (disk->src->debug)
1709 virBufferAsprintf(buf, ",file.debug=%d", disk->src->debugLevel);
1711 if (qemuBuildDriveSourcePR(buf, disk) < 0)
1712 goto cleanup;
1713 } else {
1714 if (!(source = virQEMUBuildDriveCommandlineFromJSON(srcprops)))
1715 goto cleanup;
1717 virBufferAdd(buf, source, -1);
1719 virBufferAddLit(buf, ",");
1721 if (encinfo) {
1722 if (disk->src->format == VIR_STORAGE_FILE_RAW) {
1723 virBufferAsprintf(buf, "key-secret=%s,", encinfo->s.aes.alias);
1724 rawluks = true;
1725 } else if (disk->src->format == VIR_STORAGE_FILE_QCOW2 &&
1726 disk->src->encryption->format == VIR_STORAGE_ENCRYPTION_FORMAT_LUKS) {
1727 virBufferAddLit(buf, "encrypt.format=luks,");
1728 virBufferAsprintf(buf, "encrypt.key-secret=%s,", encinfo->s.aes.alias);
1732 if (disk->src->format > 0 &&
1733 disk->src->type != VIR_STORAGE_TYPE_DIR) {
1734 const char *qemuformat = virStorageFileFormatTypeToString(disk->src->format);
1735 if (rawluks)
1736 qemuformat = "luks";
1737 virBufferAsprintf(buf, "format=%s,", qemuformat);
1740 ret = 0;
1742 cleanup:
1743 VIR_FREE(source);
1744 virJSONValueFree(srcprops);
1745 return ret;
1749 static void
1750 qemuBuildDiskThrottling(virDomainDiskDefPtr disk,
1751 virBufferPtr buf)
1753 #define IOTUNE_ADD(_field, _label) \
1754 if (disk->blkdeviotune._field) { \
1755 virBufferAsprintf(buf, ",throttling." _label "=%llu", \
1756 disk->blkdeviotune._field); \
1759 IOTUNE_ADD(total_bytes_sec, "bps-total");
1760 IOTUNE_ADD(read_bytes_sec, "bps-read");
1761 IOTUNE_ADD(write_bytes_sec, "bps-write");
1762 IOTUNE_ADD(total_iops_sec, "iops-total");
1763 IOTUNE_ADD(read_iops_sec, "iops-read");
1764 IOTUNE_ADD(write_iops_sec, "iops-write");
1766 IOTUNE_ADD(total_bytes_sec_max, "bps-total-max");
1767 IOTUNE_ADD(read_bytes_sec_max, "bps-read-max");
1768 IOTUNE_ADD(write_bytes_sec_max, "bps-write-max");
1769 IOTUNE_ADD(total_iops_sec_max, "iops-total-max");
1770 IOTUNE_ADD(read_iops_sec_max, "iops-read-max");
1771 IOTUNE_ADD(write_iops_sec_max, "iops-write-max");
1773 IOTUNE_ADD(size_iops_sec, "iops-size");
1774 if (disk->blkdeviotune.group_name) {
1775 virBufferAddLit(buf, ",throttling.group=");
1776 virQEMUBuildBufferEscapeComma(buf, disk->blkdeviotune.group_name);
1779 IOTUNE_ADD(total_bytes_sec_max_length, "bps-total-max-length");
1780 IOTUNE_ADD(read_bytes_sec_max_length, "bps-read-max-length");
1781 IOTUNE_ADD(write_bytes_sec_max_length, "bps-write-max-length");
1782 IOTUNE_ADD(total_iops_sec_max_length, "iops-total-max-length");
1783 IOTUNE_ADD(read_iops_sec_max_length, "iops-read-max-length");
1784 IOTUNE_ADD(write_iops_sec_max_length, "iops-write-max-length");
1785 #undef IOTUNE_ADD
1789 static void
1790 qemuBuildDiskFrontendAttributeErrorPolicy(virDomainDiskDefPtr disk,
1791 virBufferPtr buf)
1793 const char *wpolicy = NULL;
1794 const char *rpolicy = NULL;
1796 if (disk->error_policy)
1797 wpolicy = virDomainDiskErrorPolicyTypeToString(disk->error_policy);
1799 if (disk->rerror_policy)
1800 rpolicy = virDomainDiskErrorPolicyTypeToString(disk->rerror_policy);
1802 if (disk->error_policy == VIR_DOMAIN_DISK_ERROR_POLICY_ENOSPACE) {
1803 /* in the case of enospace, the option is spelled
1804 * differently in qemu, and it's only valid for werror,
1805 * not for rerror, so leave rerror NULL.
1807 wpolicy = "enospc";
1808 } else if (!rpolicy) {
1809 /* for other policies, rpolicy can match wpolicy */
1810 rpolicy = wpolicy;
1813 if (wpolicy)
1814 virBufferAsprintf(buf, ",werror=%s", wpolicy);
1815 if (rpolicy)
1816 virBufferAsprintf(buf, ",rerror=%s", rpolicy);
1820 static void
1821 qemuBuildDiskFrontendAttributes(virDomainDiskDefPtr disk,
1822 virBufferPtr buf)
1824 /* generate geometry command string */
1825 if (disk->geometry.cylinders > 0 &&
1826 disk->geometry.heads > 0 &&
1827 disk->geometry.sectors > 0) {
1828 virBufferAsprintf(buf, ",cyls=%u,heads=%u,secs=%u",
1829 disk->geometry.cylinders,
1830 disk->geometry.heads,
1831 disk->geometry.sectors);
1833 if (disk->geometry.trans != VIR_DOMAIN_DISK_TRANS_DEFAULT)
1834 virBufferAsprintf(buf, ",bios-chs-trans=%s",
1835 virDomainDiskGeometryTransTypeToString(disk->geometry.trans));
1838 if (disk->serial) {
1839 virBufferAddLit(buf, ",serial=");
1840 virBufferEscape(buf, '\\', " ", "%s", disk->serial);
1845 static char *
1846 qemuBuildDriveStr(virDomainDiskDefPtr disk,
1847 virQEMUCapsPtr qemuCaps)
1849 virBuffer opt = VIR_BUFFER_INITIALIZER;
1850 int detect_zeroes = virDomainDiskGetDetectZeroesMode(disk->discard,
1851 disk->detect_zeroes);
1853 if (qemuBuildDriveSourceStr(disk, qemuCaps, &opt) < 0)
1854 goto error;
1856 if (!qemuDiskBusNeedsDriveArg(disk->bus)) {
1857 char *drivealias = qemuAliasDiskDriveFromDisk(disk);
1858 if (!drivealias)
1859 goto error;
1861 virBufferAddLit(&opt, "if=none");
1862 virBufferAsprintf(&opt, ",id=%s", drivealias);
1863 VIR_FREE(drivealias);
1864 } else {
1865 int idx = virDiskNameToIndex(disk->dst);
1867 if (idx < 0) {
1868 virReportError(VIR_ERR_INTERNAL_ERROR,
1869 _("unsupported disk type '%s'"), disk->dst);
1870 goto error;
1873 /* if we are using -device this will be checked elsewhere */
1874 if (qemuCheckDiskConfig(disk, qemuCaps) < 0)
1875 goto error;
1877 virBufferAsprintf(&opt, "if=%s",
1878 virDomainDiskQEMUBusTypeToString(disk->bus));
1879 virBufferAsprintf(&opt, ",index=%d", idx);
1882 /* werror/rerror are really frontend attributes, but older
1883 * qemu requires them on -drive instead of -device */
1884 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_USB_STORAGE_WERROR))
1885 qemuBuildDiskFrontendAttributeErrorPolicy(disk, &opt);
1887 if (disk->src->readonly)
1888 virBufferAddLit(&opt, ",readonly=on");
1890 /* qemu rejects some parameters for an empty -drive, so we need to skip
1891 * them in that case:
1892 * cache: modifies properties of the format driver which is not present
1893 * copy_on_read: really only works for floppies
1894 * discard: modifies properties of format driver
1895 * detect_zeroes: works but really depends on discard so it's useless
1896 * iomode: setting it to 'native' requires a specific cache mode
1898 if (!virStorageSourceIsEmpty(disk->src)) {
1899 if (disk->cachemode) {
1900 virBufferAsprintf(&opt, ",cache=%s",
1901 qemuDiskCacheV2TypeToString(disk->cachemode));
1904 if (disk->copy_on_read) {
1905 virBufferAsprintf(&opt, ",copy-on-read=%s",
1906 virTristateSwitchTypeToString(disk->copy_on_read));
1909 if (disk->discard) {
1910 virBufferAsprintf(&opt, ",discard=%s",
1911 virDomainDiskDiscardTypeToString(disk->discard));
1914 if (detect_zeroes) {
1915 virBufferAsprintf(&opt, ",detect-zeroes=%s",
1916 virDomainDiskDetectZeroesTypeToString(detect_zeroes));
1919 if (disk->iomode) {
1920 virBufferAsprintf(&opt, ",aio=%s",
1921 virDomainDiskIoTypeToString(disk->iomode));
1925 qemuBuildDiskThrottling(disk, &opt);
1927 if (virBufferCheckError(&opt) < 0)
1928 goto error;
1930 return virBufferContentAndReset(&opt);
1932 error:
1933 virBufferFreeAndReset(&opt);
1934 return NULL;
1938 static bool
1939 qemuCheckIOThreads(const virDomainDef *def,
1940 virDomainDiskDefPtr disk)
1942 /* Right "type" of disk" */
1943 switch ((virDomainDiskBus)disk->bus) {
1944 case VIR_DOMAIN_DISK_BUS_VIRTIO:
1945 if (disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI &&
1946 disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW) {
1947 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1948 _("IOThreads only available for virtio pci and "
1949 "virtio ccw disk"));
1950 return false;
1952 break;
1954 case VIR_DOMAIN_DISK_BUS_IDE:
1955 case VIR_DOMAIN_DISK_BUS_FDC:
1956 case VIR_DOMAIN_DISK_BUS_SCSI:
1957 case VIR_DOMAIN_DISK_BUS_XEN:
1958 case VIR_DOMAIN_DISK_BUS_USB:
1959 case VIR_DOMAIN_DISK_BUS_UML:
1960 case VIR_DOMAIN_DISK_BUS_SATA:
1961 case VIR_DOMAIN_DISK_BUS_SD:
1962 case VIR_DOMAIN_DISK_BUS_LAST:
1963 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1964 _("IOThreads not available for bus %s target %s"),
1965 virDomainDiskBusTypeToString(disk->bus), disk->dst);
1966 return false;
1969 /* Can we find the disk iothread in the iothreadid list? */
1970 if (!virDomainIOThreadIDFind(def, disk->iothread)) {
1971 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1972 _("Disk iothread '%u' not defined in iothreadid"),
1973 disk->iothread);
1974 return false;
1977 return true;
1981 static int
1982 qemuBuildDriveDevCacheStr(virDomainDiskDefPtr disk,
1983 virBufferPtr buf,
1984 virQEMUCapsPtr qemuCaps)
1986 bool wb;
1988 if (disk->cachemode == VIR_DOMAIN_DISK_CACHE_DEFAULT)
1989 return 0;
1991 /* VIR_DOMAIN_DISK_DEVICE_LUN translates into 'scsi-block'
1992 * where any caching setting makes no sense. */
1993 if (disk->device == VIR_DOMAIN_DISK_DEVICE_LUN)
1994 return 0;
1996 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DISK_WRITE_CACHE))
1997 return 0;
1999 if (qemuDomainDiskCachemodeFlags(disk->cachemode, &wb, NULL, NULL) < 0)
2000 return -1;
2002 virBufferStrcat(buf, ",write-cache=",
2003 virTristateSwitchTypeToString(virTristateSwitchFromBool(wb)),
2004 NULL);
2006 return 0;
2010 char *
2011 qemuBuildDiskDeviceStr(const virDomainDef *def,
2012 virDomainDiskDefPtr disk,
2013 unsigned int bootindex,
2014 virQEMUCapsPtr qemuCaps)
2016 virBuffer opt = VIR_BUFFER_INITIALIZER;
2017 const char *bus = virDomainDiskQEMUBusTypeToString(disk->bus);
2018 const char *contAlias;
2019 char *backendAlias = NULL;
2020 VIR_AUTOFREE(char *) scsiVPDDeviceId = NULL;
2021 int controllerModel;
2023 if (qemuCheckDiskConfig(disk, qemuCaps) < 0)
2024 goto error;
2026 if (!qemuDomainCheckCCWS390AddressSupport(def, &disk->info, qemuCaps, disk->dst))
2027 goto error;
2029 if (disk->iothread && !qemuCheckIOThreads(def, disk))
2030 goto error;
2032 switch ((virDomainDiskBus) disk->bus) {
2033 case VIR_DOMAIN_DISK_BUS_IDE:
2034 if (disk->info.addr.drive.target != 0) {
2035 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2036 _("target must be 0 for ide controller"));
2037 goto error;
2040 if (disk->wwn &&
2041 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_IDE_DRIVE_WWN)) {
2042 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2043 _("Setting wwn for ide disk is not supported "
2044 "by this QEMU"));
2045 goto error;
2048 if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM)
2049 virBufferAddLit(&opt, "ide-cd");
2050 else
2051 virBufferAddLit(&opt, "ide-hd");
2053 /* When domain has builtin IDE controller we don't put it onto cmd
2054 * line. Therefore we can't set its alias. In that case, use the
2055 * default one. */
2056 if (qemuDomainHasBuiltinIDE(def)) {
2057 contAlias = "ide";
2058 } else {
2059 if (!(contAlias = virDomainControllerAliasFind(def,
2060 VIR_DOMAIN_CONTROLLER_TYPE_IDE,
2061 disk->info.addr.drive.controller)))
2062 goto error;
2064 virBufferAsprintf(&opt, ",bus=%s.%d,unit=%d",
2065 contAlias,
2066 disk->info.addr.drive.bus,
2067 disk->info.addr.drive.unit);
2068 break;
2070 case VIR_DOMAIN_DISK_BUS_SCSI:
2071 if (disk->device == VIR_DOMAIN_DISK_DEVICE_LUN) {
2072 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_BLOCK)) {
2073 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2074 _("This QEMU doesn't support scsi-block for "
2075 "lun passthrough"));
2076 goto error;
2080 if (disk->wwn &&
2081 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_DISK_WWN)) {
2082 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2083 _("Setting wwn for scsi disk is not supported "
2084 "by this QEMU"));
2085 goto error;
2088 /* Properties wwn, vendor and product were introduced in the
2089 * same QEMU release (1.2.0).
2091 if ((disk->vendor || disk->product) &&
2092 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_DISK_WWN)) {
2093 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2094 _("Setting vendor or product for scsi disk is not "
2095 "supported by this QEMU"));
2096 goto error;
2099 controllerModel = qemuDomainFindSCSIControllerModel(def, &disk->info);
2100 if (controllerModel < 0)
2101 goto error;
2103 if (disk->device == VIR_DOMAIN_DISK_DEVICE_LUN) {
2104 virBufferAddLit(&opt, "scsi-block");
2105 } else {
2106 if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM)
2107 virBufferAddLit(&opt, "scsi-cd");
2108 else
2109 virBufferAddLit(&opt, "scsi-hd");
2111 /* qemu historically used the name of -drive as one of the device
2112 * ids in the Vital Product Data Device Identification page if
2113 * disk serial was not set and the disk serial otherwise.
2114 * To avoid a guest-visible regression we need to provide it
2115 * ourselves especially for cases when -blockdev will be used */
2116 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_DISK_DEVICE_ID)) {
2117 if (disk->serial) {
2118 if (VIR_STRDUP(scsiVPDDeviceId, disk->serial) < 0)
2119 goto error;
2120 } else {
2121 if (!(scsiVPDDeviceId = qemuAliasDiskDriveFromDisk(disk)))
2122 goto error;
2127 if (!(contAlias = virDomainControllerAliasFind(def, VIR_DOMAIN_CONTROLLER_TYPE_SCSI,
2128 disk->info.addr.drive.controller)))
2129 goto error;
2131 if (controllerModel == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC) {
2132 if (disk->info.addr.drive.target != 0) {
2133 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2134 _("target must be 0 for controller "
2135 "model 'lsilogic'"));
2136 goto error;
2139 virBufferAsprintf(&opt, ",bus=%s.%d,scsi-id=%d",
2140 contAlias,
2141 disk->info.addr.drive.bus,
2142 disk->info.addr.drive.unit);
2143 } else {
2144 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_DISK_CHANNEL)) {
2145 if (disk->info.addr.drive.target > 7) {
2146 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2147 _("This QEMU doesn't support target "
2148 "greater than 7"));
2149 goto error;
2152 if (disk->info.addr.drive.bus != 0 &&
2153 disk->info.addr.drive.unit != 0) {
2154 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2155 _("This QEMU only supports both bus and "
2156 "unit equal to 0"));
2157 goto error;
2161 virBufferAsprintf(&opt, ",bus=%s.0,channel=%d,scsi-id=%d,lun=%d",
2162 contAlias,
2163 disk->info.addr.drive.bus,
2164 disk->info.addr.drive.target,
2165 disk->info.addr.drive.unit);
2168 if (scsiVPDDeviceId)
2169 virBufferStrcat(&opt, ",device_id=", scsiVPDDeviceId, NULL);
2171 break;
2173 case VIR_DOMAIN_DISK_BUS_SATA:
2174 if (disk->info.addr.drive.bus != 0) {
2175 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2176 _("bus must be 0 for ide controller"));
2177 goto error;
2179 if (disk->info.addr.drive.target != 0) {
2180 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2181 _("target must be 0 for ide controller"));
2182 goto error;
2185 if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM)
2186 virBufferAddLit(&opt, "ide-cd");
2187 else
2188 virBufferAddLit(&opt, "ide-hd");
2190 /* When domain has builtin SATA controller we don't put it onto cmd
2191 * line. Therefore we can't set its alias. In that case, use the
2192 * default one. */
2193 if (qemuDomainIsQ35(def) &&
2194 disk->info.addr.drive.controller == 0) {
2195 contAlias = "ide";
2196 } else {
2197 if (!(contAlias = virDomainControllerAliasFind(def,
2198 VIR_DOMAIN_CONTROLLER_TYPE_SATA,
2199 disk->info.addr.drive.controller)))
2200 goto error;
2202 virBufferAsprintf(&opt, ",bus=%s.%d",
2203 contAlias,
2204 disk->info.addr.drive.unit);
2205 break;
2207 case VIR_DOMAIN_DISK_BUS_VIRTIO:
2208 if (qemuBuildVirtioDevStr(&opt, "virtio-blk", qemuCaps,
2209 VIR_DOMAIN_DEVICE_DISK, disk) < 0) {
2210 goto error;
2213 if (disk->iothread)
2214 virBufferAsprintf(&opt, ",iothread=iothread%u", disk->iothread);
2216 qemuBuildIoEventFdStr(&opt, disk->ioeventfd, qemuCaps);
2217 if (disk->event_idx &&
2218 virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_BLK_EVENT_IDX)) {
2219 virBufferAsprintf(&opt, ",event_idx=%s",
2220 virTristateSwitchTypeToString(disk->event_idx));
2222 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_BLK_SCSI)) {
2223 /* if sg_io is true but the scsi option isn't supported,
2224 * that means it's just always on in this version of qemu.
2226 virBufferAsprintf(&opt, ",scsi=%s",
2227 (disk->device == VIR_DOMAIN_DISK_DEVICE_LUN)
2228 ? "on" : "off");
2231 if (disk->queues) {
2232 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_BLK_NUM_QUEUES)) {
2233 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2234 _("num-queues property isn't supported by this "
2235 "QEMU binary"));
2236 goto error;
2239 virBufferAsprintf(&opt, ",num-queues=%u", disk->queues);
2242 if (qemuBuildVirtioOptionsStr(&opt, disk->virtio, qemuCaps) < 0)
2243 goto error;
2245 if (qemuBuildDeviceAddressStr(&opt, def, &disk->info, qemuCaps) < 0)
2246 goto error;
2247 break;
2249 case VIR_DOMAIN_DISK_BUS_USB:
2250 if (disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
2251 disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB) {
2252 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2253 _("unexpected address type for usb disk"));
2254 goto error;
2256 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_USB_STORAGE)) {
2257 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2258 _("This QEMU doesn't support '-device "
2259 "usb-storage'"));
2260 goto error;
2263 virBufferAddLit(&opt, "usb-storage");
2265 if (qemuBuildDeviceAddressStr(&opt, def, &disk->info, qemuCaps) < 0)
2266 goto error;
2267 break;
2269 case VIR_DOMAIN_DISK_BUS_FDC:
2270 virBufferAsprintf(&opt, "floppy,unit=%d", disk->info.addr.drive.unit);
2271 break;
2273 case VIR_DOMAIN_DISK_BUS_XEN:
2274 case VIR_DOMAIN_DISK_BUS_UML:
2275 case VIR_DOMAIN_DISK_BUS_SD:
2276 case VIR_DOMAIN_DISK_BUS_LAST:
2277 default:
2278 virReportError(VIR_ERR_INTERNAL_ERROR,
2279 _("unsupported disk bus '%s' with device setup"), bus);
2280 goto error;
2283 if (disk->src->shared &&
2284 virQEMUCapsGet(qemuCaps, QEMU_CAPS_DISK_SHARE_RW))
2285 virBufferAddLit(&opt, ",share-rw=on");
2287 if (qemuDomainDiskGetBackendAlias(disk, qemuCaps, &backendAlias) < 0)
2288 goto error;
2290 if (backendAlias)
2291 virBufferAsprintf(&opt, ",drive=%s", backendAlias);
2292 VIR_FREE(backendAlias);
2294 virBufferAsprintf(&opt, ",id=%s", disk->info.alias);
2295 if (bootindex)
2296 virBufferAsprintf(&opt, ",bootindex=%u", bootindex);
2297 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_BLOCKIO)) {
2298 if (disk->blockio.logical_block_size > 0)
2299 virBufferAsprintf(&opt, ",logical_block_size=%u",
2300 disk->blockio.logical_block_size);
2301 if (disk->blockio.physical_block_size > 0)
2302 virBufferAsprintf(&opt, ",physical_block_size=%u",
2303 disk->blockio.physical_block_size);
2306 if (disk->wwn) {
2307 if (STRPREFIX(disk->wwn, "0x"))
2308 virBufferAsprintf(&opt, ",wwn=%s", disk->wwn);
2309 else
2310 virBufferAsprintf(&opt, ",wwn=0x%s", disk->wwn);
2313 if (disk->vendor) {
2314 virBufferAddLit(&opt, ",vendor=");
2315 virQEMUBuildBufferEscapeComma(&opt, disk->vendor);
2318 if (disk->product) {
2319 virBufferAddLit(&opt, ",product=");
2320 virQEMUBuildBufferEscapeComma(&opt, disk->product);
2323 if (disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
2324 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_USB_STORAGE_REMOVABLE)) {
2325 if (disk->removable == VIR_TRISTATE_SWITCH_ON)
2326 virBufferAddLit(&opt, ",removable=on");
2327 else
2328 virBufferAddLit(&opt, ",removable=off");
2329 } else {
2330 if (disk->removable != VIR_TRISTATE_SWITCH_ABSENT) {
2331 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2332 _("This QEMU doesn't support setting the "
2333 "removable flag of USB storage devices"));
2334 goto error;
2339 if (qemuBuildDriveDevCacheStr(disk, &opt, qemuCaps) < 0)
2340 goto error;
2342 qemuBuildDiskFrontendAttributes(disk, &opt);
2344 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_USB_STORAGE_WERROR))
2345 qemuBuildDiskFrontendAttributeErrorPolicy(disk, &opt);
2347 if (virBufferCheckError(&opt) < 0)
2348 goto error;
2350 return virBufferContentAndReset(&opt);
2352 error:
2353 VIR_FREE(backendAlias);
2354 virBufferFreeAndReset(&opt);
2355 return NULL;
2358 char *
2359 qemuBuildZPCIDevStr(virDomainDeviceInfoPtr dev)
2361 virBuffer buf = VIR_BUFFER_INITIALIZER;
2363 virBufferAsprintf(&buf,
2364 "zpci,uid=%u,fid=%u,target=%s,id=zpci%u",
2365 dev->addr.pci.zpci.uid,
2366 dev->addr.pci.zpci.fid,
2367 dev->alias,
2368 dev->addr.pci.zpci.uid);
2370 if (virBufferCheckError(&buf) < 0) {
2371 virBufferFreeAndReset(&buf);
2372 return NULL;
2375 return virBufferContentAndReset(&buf);
2378 static int
2379 qemuCommandAddZPCIDevice(virCommandPtr cmd,
2380 virDomainDeviceInfoPtr dev)
2382 char *devstr = NULL;
2384 virCommandAddArg(cmd, "-device");
2386 if (!(devstr = qemuBuildZPCIDevStr(dev)))
2387 return -1;
2389 virCommandAddArg(cmd, devstr);
2391 VIR_FREE(devstr);
2392 return 0;
2395 static int
2396 qemuCommandAddExtDevice(virCommandPtr cmd,
2397 virDomainDeviceInfoPtr dev)
2399 if (dev->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI ||
2400 dev->addr.pci.extFlags == VIR_PCI_ADDRESS_EXTENSION_NONE) {
2401 return 0;
2404 if (dev->addr.pci.extFlags & VIR_PCI_ADDRESS_EXTENSION_ZPCI)
2405 return qemuCommandAddZPCIDevice(cmd, dev);
2407 return 0;
2410 static int
2411 qemuBuildFloppyCommandLineControllerOptions(virCommandPtr cmd,
2412 const virDomainDef *def,
2413 virQEMUCapsPtr qemuCaps,
2414 unsigned int bootFloppy)
2416 virBuffer fdc_opts = VIR_BUFFER_INITIALIZER;
2417 bool explicitfdc = qemuDomainNeedsFDC(def);
2418 bool hasfloppy = false;
2419 unsigned int bootindex;
2420 char driveLetter;
2421 char *backendAlias = NULL;
2422 char *backendStr = NULL;
2423 char *bootindexStr = NULL;
2424 size_t i;
2425 int ret = -1;
2427 virBufferAddLit(&fdc_opts, "isa-fdc,");
2429 for (i = 0; i < def->ndisks; i++) {
2430 virDomainDiskDefPtr disk = def->disks[i];
2432 if (disk->bus != VIR_DOMAIN_DISK_BUS_FDC)
2433 continue;
2435 hasfloppy = true;
2437 if (disk->info.bootIndex) {
2438 bootindex = disk->info.bootIndex;
2439 } else {
2440 bootindex = bootFloppy;
2441 bootFloppy = 0;
2444 if (disk->info.addr.drive.unit)
2445 driveLetter = 'B';
2446 else
2447 driveLetter = 'A';
2449 if (bootindex &&
2450 virAsprintf(&bootindexStr, "bootindex%c=%u", driveLetter, bootindex) < 0)
2451 goto cleanup;
2453 /* with -blockdev we setup the floppy device and it's backend with -device */
2454 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_BLOCKDEV)) {
2455 if (qemuDomainDiskGetBackendAlias(disk, qemuCaps, &backendAlias) < 0)
2456 goto cleanup;
2458 if (backendAlias &&
2459 virAsprintf(&backendStr, "drive%c=%s", driveLetter, backendAlias) < 0)
2460 goto cleanup;
2463 if (!explicitfdc) {
2464 if (backendStr) {
2465 virCommandAddArg(cmd, "-global");
2466 virCommandAddArgFormat(cmd, "isa-fdc.%s", backendStr);
2469 if (bootindexStr) {
2470 virCommandAddArg(cmd, "-global");
2471 virCommandAddArgFormat(cmd, "isa-fdc.%s", bootindexStr);
2473 } else {
2474 virBufferStrcat(&fdc_opts, backendStr, ",", NULL);
2475 virBufferStrcat(&fdc_opts, bootindexStr, ",", NULL);
2478 VIR_FREE(backendAlias);
2479 VIR_FREE(backendStr);
2480 VIR_FREE(bootindexStr);
2483 if (explicitfdc && hasfloppy) {
2484 /* Newer Q35 machine types require an explicit FDC controller */
2485 virBufferTrim(&fdc_opts, ",", -1);
2486 virCommandAddArg(cmd, "-device");
2487 virCommandAddArgBuffer(cmd, &fdc_opts);
2490 ret = 0;
2492 cleanup:
2493 VIR_FREE(backendAlias);
2494 VIR_FREE(backendStr);
2495 VIR_FREE(bootindexStr);
2496 virBufferFreeAndReset(&fdc_opts);
2497 return ret;
2501 static int
2502 qemuBuildObjectCommandline(virCommandPtr cmd,
2503 virJSONValuePtr objProps)
2505 virBuffer buf = VIR_BUFFER_INITIALIZER;
2507 if (!objProps)
2508 return 0;
2510 if (virQEMUBuildObjectCommandlineFromJSON(&buf, objProps) < 0) {
2511 virBufferFreeAndReset(&buf);
2512 return -1;
2515 virCommandAddArg(cmd, "-object");
2516 virCommandAddArgBuffer(cmd, &buf);
2518 return 0;
2522 static int
2523 qemuBuildBlockStorageSourceAttachDataCommandline(virCommandPtr cmd,
2524 qemuBlockStorageSourceAttachDataPtr data)
2526 char *tmp;
2528 if (qemuBuildObjectCommandline(cmd, data->prmgrProps) < 0 ||
2529 qemuBuildObjectCommandline(cmd, data->authsecretProps) < 0 ||
2530 qemuBuildObjectCommandline(cmd, data->encryptsecretProps) < 0 ||
2531 qemuBuildObjectCommandline(cmd, data->tlsProps) < 0)
2532 return -1;
2534 if (data->driveCmd)
2535 virCommandAddArgList(cmd, "-drive", data->driveCmd, NULL);
2537 if (data->storageProps) {
2538 if (!(tmp = virJSONValueToString(data->storageProps, false)))
2539 return -1;
2541 virCommandAddArgList(cmd, "-blockdev", tmp, NULL);
2542 VIR_FREE(tmp);
2545 if (data->formatProps) {
2546 if (!(tmp = virJSONValueToString(data->formatProps, false)))
2547 return -1;
2549 virCommandAddArgList(cmd, "-blockdev", tmp, NULL);
2550 VIR_FREE(tmp);
2553 return 0;
2557 static int
2558 qemuBuildDiskSourceCommandLine(virCommandPtr cmd,
2559 virDomainDiskDefPtr disk,
2560 virQEMUCapsPtr qemuCaps)
2562 qemuBlockStorageSourceAttachDataPtr *data = NULL;
2563 size_t ndata = 0;
2564 VIR_AUTOPTR(qemuBlockStorageSourceAttachData) tmp = NULL;
2565 virJSONValuePtr copyOnReadProps = NULL;
2566 virStorageSourcePtr n;
2567 char *str = NULL;
2568 size_t i;
2569 int ret = -1;
2571 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_BLOCKDEV)) {
2572 if (virStorageSourceIsEmpty(disk->src)) {
2573 ret = 0;
2574 goto cleanup;
2577 for (n = disk->src; virStorageSourceIsBacking(n); n = n->backingStore) {
2578 if (!(tmp = qemuBlockStorageSourceAttachPrepareBlockdev(n)))
2579 goto cleanup;
2581 if (qemuBuildStorageSourceAttachPrepareCommon(n, tmp, qemuCaps) < 0)
2582 goto cleanup;
2584 if (VIR_APPEND_ELEMENT(data, ndata, tmp) < 0)
2585 goto cleanup;
2588 if (disk->copy_on_read == VIR_TRISTATE_SWITCH_ON &&
2589 !(copyOnReadProps = qemuBlockStorageGetCopyOnReadProps(disk)))
2590 goto cleanup;
2591 } else {
2592 if (!(tmp = qemuBuildStorageSourceAttachPrepareDrive(disk, qemuCaps)))
2593 goto cleanup;
2595 if (qemuBuildStorageSourceAttachPrepareCommon(disk->src, tmp,
2596 qemuCaps) < 0)
2597 goto cleanup;
2599 if (VIR_APPEND_ELEMENT(data, ndata, tmp) < 0)
2600 goto cleanup;
2603 for (i = ndata; i > 0; i--) {
2604 if (qemuBuildBlockStorageSourceAttachDataCommandline(cmd,
2605 data[i - 1]) < 0)
2606 goto cleanup;
2609 if (copyOnReadProps) {
2610 if (!(str = virJSONValueToString(copyOnReadProps, false)))
2611 goto cleanup;
2613 virCommandAddArgList(cmd, "-blockdev", str, NULL);
2614 VIR_FREE(str);
2617 ret = 0;
2619 cleanup:
2620 for (i = 0; i < ndata; i++)
2621 qemuBlockStorageSourceAttachDataFree(data[i]);
2622 VIR_FREE(data);
2623 virJSONValueFree(copyOnReadProps);
2624 VIR_FREE(str);
2625 return ret;
2629 static int
2630 qemuBuildDiskCommandLine(virCommandPtr cmd,
2631 const virDomainDef *def,
2632 virDomainDiskDefPtr disk,
2633 virQEMUCapsPtr qemuCaps,
2634 unsigned int bootindex)
2636 char *optstr;
2638 if (qemuBuildDiskSourceCommandLine(cmd, disk, qemuCaps) < 0)
2639 return -1;
2641 if (!qemuDiskBusNeedsDriveArg(disk->bus)) {
2642 if (disk->bus != VIR_DOMAIN_DISK_BUS_FDC ||
2643 virQEMUCapsGet(qemuCaps, QEMU_CAPS_BLOCKDEV)) {
2644 if (qemuCommandAddExtDevice(cmd, &disk->info) < 0)
2645 return -1;
2647 virCommandAddArg(cmd, "-device");
2649 if (!(optstr = qemuBuildDiskDeviceStr(def, disk, bootindex,
2650 qemuCaps)))
2651 return -1;
2652 virCommandAddArg(cmd, optstr);
2653 VIR_FREE(optstr);
2657 return 0;
2661 static int
2662 qemuBuildDisksCommandLine(virCommandPtr cmd,
2663 const virDomainDef *def,
2664 virQEMUCapsPtr qemuCaps)
2666 size_t i;
2667 unsigned int bootCD = 0;
2668 unsigned int bootFloppy = 0;
2669 unsigned int bootDisk = 0;
2670 bool blockdev = virQEMUCapsGet(qemuCaps, QEMU_CAPS_BLOCKDEV);
2672 for (i = 0; i < def->os.nBootDevs; i++) {
2673 switch (def->os.bootDevs[i]) {
2674 case VIR_DOMAIN_BOOT_CDROM:
2675 bootCD = i + 1;
2676 break;
2677 case VIR_DOMAIN_BOOT_FLOPPY:
2678 bootFloppy = i + 1;
2679 break;
2680 case VIR_DOMAIN_BOOT_DISK:
2681 bootDisk = i + 1;
2682 break;
2686 /* If we want to express the floppy drives via -device, the controller needs
2687 * to be instantiated prior to that */
2688 if (blockdev &&
2689 qemuBuildFloppyCommandLineControllerOptions(cmd, def, qemuCaps, bootFloppy) < 0)
2690 return -1;
2692 for (i = 0; i < def->ndisks; i++) {
2693 virDomainDiskDefPtr disk = def->disks[i];
2694 unsigned int bootindex = 0;
2696 if (disk->info.bootIndex) {
2697 bootindex = disk->info.bootIndex;
2698 } else {
2699 switch (disk->device) {
2700 case VIR_DOMAIN_DISK_DEVICE_CDROM:
2701 bootindex = bootCD;
2702 bootCD = 0;
2703 break;
2704 case VIR_DOMAIN_DISK_DEVICE_DISK:
2705 case VIR_DOMAIN_DISK_DEVICE_LUN:
2706 bootindex = bootDisk;
2707 bootDisk = 0;
2708 break;
2712 /* The floppy device itself does not support the bootindex property
2713 * so we need to set it up for the controller */
2714 if (disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY)
2715 bootindex = 0;
2717 if (qemuBuildDiskCommandLine(cmd, def, disk, qemuCaps, bootindex) < 0)
2718 return -1;
2721 if (!blockdev &&
2722 qemuBuildFloppyCommandLineControllerOptions(cmd, def, qemuCaps, bootFloppy) < 0)
2723 return -1;
2725 return 0;
2729 static char *
2730 qemuBuildFSStr(virDomainFSDefPtr fs)
2732 virBuffer opt = VIR_BUFFER_INITIALIZER;
2733 const char *driver = qemuDomainFSDriverTypeToString(fs->fsdriver);
2734 const char *wrpolicy = virDomainFSWrpolicyTypeToString(fs->wrpolicy);
2736 if (fs->type != VIR_DOMAIN_FS_TYPE_MOUNT) {
2737 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2738 _("only supports mount filesystem type"));
2739 goto error;
2742 if (!driver) {
2743 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2744 _("Filesystem driver type not supported"));
2745 goto error;
2747 virBufferAdd(&opt, driver, -1);
2749 if (fs->fsdriver == VIR_DOMAIN_FS_DRIVER_TYPE_PATH ||
2750 fs->fsdriver == VIR_DOMAIN_FS_DRIVER_TYPE_DEFAULT) {
2751 if (fs->accessmode == VIR_DOMAIN_FS_ACCESSMODE_MAPPED) {
2752 virBufferAddLit(&opt, ",security_model=mapped");
2753 } else if (fs->accessmode == VIR_DOMAIN_FS_ACCESSMODE_PASSTHROUGH) {
2754 virBufferAddLit(&opt, ",security_model=passthrough");
2755 } else if (fs->accessmode == VIR_DOMAIN_FS_ACCESSMODE_SQUASH) {
2756 virBufferAddLit(&opt, ",security_model=none");
2758 } else {
2759 /* For other fs drivers, default(passthru) should always
2760 * be supported */
2761 if (fs->accessmode != VIR_DOMAIN_FS_ACCESSMODE_PASSTHROUGH) {
2762 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2763 _("only supports passthrough accessmode"));
2764 goto error;
2768 if (fs->wrpolicy)
2769 virBufferAsprintf(&opt, ",writeout=%s", wrpolicy);
2771 virBufferAsprintf(&opt, ",id=%s%s", QEMU_FSDEV_HOST_PREFIX, fs->info.alias);
2772 virBufferAddLit(&opt, ",path=");
2773 virQEMUBuildBufferEscapeComma(&opt, fs->src->path);
2775 if (fs->readonly)
2776 virBufferAddLit(&opt, ",readonly");
2778 if (virBufferCheckError(&opt) < 0)
2779 goto error;
2781 return virBufferContentAndReset(&opt);
2783 error:
2784 virBufferFreeAndReset(&opt);
2785 return NULL;
2789 static char *
2790 qemuBuildFSDevStr(const virDomainDef *def,
2791 virDomainFSDefPtr fs,
2792 virQEMUCapsPtr qemuCaps)
2794 virBuffer opt = VIR_BUFFER_INITIALIZER;
2796 if (fs->type != VIR_DOMAIN_FS_TYPE_MOUNT) {
2797 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2798 _("can only passthrough directories"));
2799 goto error;
2802 if (qemuBuildVirtioDevStr(&opt, "virtio-9p", qemuCaps,
2803 VIR_DOMAIN_DEVICE_FS, fs) < 0) {
2804 goto error;
2807 virBufferAsprintf(&opt, ",id=%s", fs->info.alias);
2808 virBufferAsprintf(&opt, ",fsdev=%s%s",
2809 QEMU_FSDEV_HOST_PREFIX, fs->info.alias);
2810 virBufferAddLit(&opt, ",mount_tag=");
2811 virQEMUBuildBufferEscapeComma(&opt, fs->dst);
2813 if (qemuBuildVirtioOptionsStr(&opt, fs->virtio, qemuCaps) < 0)
2814 goto error;
2816 if (qemuBuildDeviceAddressStr(&opt, def, &fs->info, qemuCaps) < 0)
2817 goto error;
2819 if (virBufferCheckError(&opt) < 0)
2820 goto error;
2822 return virBufferContentAndReset(&opt);
2824 error:
2825 virBufferFreeAndReset(&opt);
2826 return NULL;
2830 static int
2831 qemuBuildFSDevCommandLine(virCommandPtr cmd,
2832 const virDomainDef *def,
2833 virQEMUCapsPtr qemuCaps)
2835 size_t i;
2837 for (i = 0; i < def->nfss; i++) {
2838 char *optstr;
2839 virDomainFSDefPtr fs = def->fss[i];
2841 virCommandAddArg(cmd, "-fsdev");
2842 if (!(optstr = qemuBuildFSStr(fs)))
2843 return -1;
2844 virCommandAddArg(cmd, optstr);
2845 VIR_FREE(optstr);
2847 if (qemuCommandAddExtDevice(cmd, &fs->info) < 0)
2848 return -1;
2850 virCommandAddArg(cmd, "-device");
2851 if (!(optstr = qemuBuildFSDevStr(def, fs, qemuCaps)))
2852 return -1;
2853 virCommandAddArg(cmd, optstr);
2854 VIR_FREE(optstr);
2857 return 0;
2861 static int
2862 qemuControllerModelUSBToCaps(int model)
2864 switch (model) {
2865 case VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX3_UHCI:
2866 return QEMU_CAPS_PIIX3_USB_UHCI;
2867 case VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX4_UHCI:
2868 return QEMU_CAPS_PIIX4_USB_UHCI;
2869 case VIR_DOMAIN_CONTROLLER_MODEL_USB_EHCI:
2870 return QEMU_CAPS_USB_EHCI;
2871 case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_EHCI1:
2872 case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI1:
2873 case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI2:
2874 case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI3:
2875 return QEMU_CAPS_ICH9_USB_EHCI1;
2876 case VIR_DOMAIN_CONTROLLER_MODEL_USB_VT82C686B_UHCI:
2877 return QEMU_CAPS_VT82C686B_USB_UHCI;
2878 case VIR_DOMAIN_CONTROLLER_MODEL_USB_PCI_OHCI:
2879 return QEMU_CAPS_PCI_OHCI;
2880 case VIR_DOMAIN_CONTROLLER_MODEL_USB_NEC_XHCI:
2881 return QEMU_CAPS_NEC_USB_XHCI;
2882 case VIR_DOMAIN_CONTROLLER_MODEL_USB_QEMU_XHCI:
2883 return QEMU_CAPS_DEVICE_QEMU_XHCI;
2884 default:
2885 return -1;
2890 static const char *
2891 qemuBuildUSBControllerFindMasterAlias(const virDomainDef *domainDef,
2892 const virDomainControllerDef *def)
2894 size_t i;
2896 for (i = 0; i < domainDef->ncontrollers; i++) {
2897 const virDomainControllerDef *tmp = domainDef->controllers[i];
2899 if (tmp->type != VIR_DOMAIN_CONTROLLER_TYPE_USB)
2900 continue;
2902 if (tmp->idx != def->idx)
2903 continue;
2905 if (tmp->info.mastertype == VIR_DOMAIN_CONTROLLER_MASTER_USB)
2906 continue;
2908 return tmp->info.alias;
2911 return NULL;
2915 static int
2916 qemuBuildUSBControllerDevStr(const virDomainDef *domainDef,
2917 virDomainControllerDefPtr def,
2918 virQEMUCapsPtr qemuCaps,
2919 virBuffer *buf)
2921 const char *smodel;
2922 int model, flags;
2924 model = def->model;
2926 if (model == VIR_DOMAIN_CONTROLLER_MODEL_USB_DEFAULT) {
2927 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2928 "%s", _("no model provided for USB controller"));
2929 return -1;
2932 smodel = qemuControllerModelUSBTypeToString(model);
2933 flags = qemuControllerModelUSBToCaps(model);
2935 if (flags == -1 || !virQEMUCapsGet(qemuCaps, flags)) {
2936 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2937 _("%s not supported in this QEMU binary"), smodel);
2938 return -1;
2941 virBufferAsprintf(buf, "%s", smodel);
2943 if (def->opts.usbopts.ports != -1) {
2944 if ((model != VIR_DOMAIN_CONTROLLER_MODEL_USB_NEC_XHCI ||
2945 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_NEC_USB_XHCI_PORTS)) &&
2946 model != VIR_DOMAIN_CONTROLLER_MODEL_USB_QEMU_XHCI) {
2947 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2948 _("usb controller type %s doesn't support 'ports' "
2949 "with this QEMU binary"), smodel);
2950 return -1;
2953 virBufferAsprintf(buf, ",p2=%d,p3=%d",
2954 def->opts.usbopts.ports, def->opts.usbopts.ports);
2957 if (def->info.mastertype == VIR_DOMAIN_CONTROLLER_MASTER_USB) {
2958 const char *masterbus;
2960 if (!(masterbus = qemuBuildUSBControllerFindMasterAlias(domainDef, def))) {
2961 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2962 _("masterbus not found"));
2963 return -1;
2965 virBufferAsprintf(buf, ",masterbus=%s.0,firstport=%d",
2966 masterbus, def->info.master.usb.startport);
2967 } else {
2968 virBufferAsprintf(buf, ",id=%s", def->info.alias);
2971 return 0;
2976 * qemuBuildControllerDevStr:
2977 * @domainDef: domain definition
2978 * @def: controller definition
2979 * @qemuCaps: QEMU binary capabilities
2980 * @devstr: device string
2981 * @nusbcontroller: number of USB controllers
2983 * Turn @def into a description of the controller that QEMU will understand,
2984 * to be used either on the command line or through the monitor.
2986 * The description will be returned in @devstr and can be NULL, eg. when
2987 * passing in one of the built-in controllers. The returned string must be
2988 * freed by the caller.
2990 * The number pointed to by @nusbcontroller will be increased by one every
2991 * time the description for a USB controller has been generated successfully.
2993 * Returns: 0 on success, <0 on failure
2996 qemuBuildControllerDevStr(const virDomainDef *domainDef,
2997 virDomainControllerDefPtr def,
2998 virQEMUCapsPtr qemuCaps,
2999 char **devstr)
3001 virBuffer buf = VIR_BUFFER_INITIALIZER;
3003 *devstr = NULL;
3005 switch ((virDomainControllerType)def->type) {
3006 case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
3007 switch ((virDomainControllerModelSCSI) def->model) {
3008 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI:
3009 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_TRANSITIONAL:
3010 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_NON_TRANSITIONAL:
3011 if (qemuBuildVirtioDevStr(&buf, "virtio-scsi", qemuCaps,
3012 VIR_DOMAIN_DEVICE_CONTROLLER, def) < 0) {
3013 goto error;
3016 if (def->iothread) {
3017 virBufferAsprintf(&buf, ",iothread=iothread%u",
3018 def->iothread);
3021 if (qemuBuildVirtioOptionsStr(&buf, def->virtio, qemuCaps) < 0)
3022 goto error;
3023 break;
3024 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC:
3025 virBufferAddLit(&buf, "lsi");
3026 break;
3027 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_IBMVSCSI:
3028 virBufferAddLit(&buf, "spapr-vscsi");
3029 break;
3030 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068:
3031 virBufferAddLit(&buf, "mptsas1068");
3032 break;
3033 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1078:
3034 virBufferAddLit(&buf, "megasas");
3035 break;
3036 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_AUTO:
3037 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_BUSLOGIC:
3038 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VMPVSCSI:
3039 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
3040 _("Unsupported controller model: %s"),
3041 virDomainControllerModelSCSITypeToString(def->model));
3042 goto error;
3043 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_DEFAULT:
3044 case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LAST:
3045 virReportError(VIR_ERR_INTERNAL_ERROR,
3046 _("Unexpected SCSI controller model %d"),
3047 def->model);
3048 goto error;
3050 virBufferAsprintf(&buf, ",id=%s", def->info.alias);
3051 break;
3053 case VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL:
3054 if (qemuBuildVirtioDevStr(&buf, "virtio-serial", qemuCaps,
3055 VIR_DOMAIN_DEVICE_CONTROLLER, def) < 0) {
3056 goto error;
3059 virBufferAsprintf(&buf, ",id=%s", def->info.alias);
3060 if (def->opts.vioserial.ports != -1) {
3061 virBufferAsprintf(&buf, ",max_ports=%d",
3062 def->opts.vioserial.ports);
3064 if (def->opts.vioserial.vectors != -1) {
3065 virBufferAsprintf(&buf, ",vectors=%d",
3066 def->opts.vioserial.vectors);
3068 if (qemuBuildVirtioOptionsStr(&buf, def->virtio, qemuCaps) < 0)
3069 goto error;
3070 break;
3072 case VIR_DOMAIN_CONTROLLER_TYPE_CCID:
3073 virBufferAsprintf(&buf, "usb-ccid,id=%s", def->info.alias);
3074 break;
3076 case VIR_DOMAIN_CONTROLLER_TYPE_SATA:
3077 virBufferAsprintf(&buf, "ahci,id=%s", def->info.alias);
3078 break;
3080 case VIR_DOMAIN_CONTROLLER_TYPE_USB:
3081 if (qemuBuildUSBControllerDevStr(domainDef, def, qemuCaps, &buf) == -1)
3082 goto error;
3084 break;
3086 case VIR_DOMAIN_CONTROLLER_TYPE_PCI: {
3087 const virDomainPCIControllerOpts *pciopts = &def->opts.pciopts;
3088 const char *modelName = virDomainControllerPCIModelNameTypeToString(pciopts->modelName);
3090 /* Skip the implicit PHB for pSeries guests */
3091 if (def->model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT &&
3092 pciopts->modelName == VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_SPAPR_PCI_HOST_BRIDGE &&
3093 pciopts->targetIndex == 0) {
3094 goto done;
3097 if (!modelName) {
3098 virReportError(VIR_ERR_INTERNAL_ERROR,
3099 _("Unknown virDomainControllerPCIModelName value: %d"),
3100 pciopts->modelName);
3101 return -1;
3104 switch ((virDomainControllerModelPCI) def->model) {
3105 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
3106 virBufferAsprintf(&buf, "%s,chassis_nr=%d,id=%s",
3107 modelName, pciopts->chassisNr,
3108 def->info.alias);
3109 break;
3110 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS:
3111 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS:
3112 virBufferAsprintf(&buf, "%s,bus_nr=%d,id=%s",
3113 modelName, pciopts->busNr,
3114 def->info.alias);
3115 if (pciopts->numaNode != -1) {
3116 virBufferAsprintf(&buf, ",numa_node=%d",
3117 pciopts->numaNode);
3119 break;
3120 case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
3121 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_UPSTREAM_PORT:
3122 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_TO_PCI_BRIDGE:
3123 virBufferAsprintf(&buf, "%s,id=%s", modelName, def->info.alias);
3124 break;
3125 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT_PORT:
3126 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_DOWNSTREAM_PORT:
3127 virBufferAsprintf(&buf, "%s,port=0x%x,chassis=%d,id=%s",
3128 modelName, pciopts->port,
3129 pciopts->chassis, def->info.alias);
3130 break;
3131 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
3132 virBufferAsprintf(&buf, "%s,index=%d,id=%s",
3133 modelName, pciopts->targetIndex,
3134 def->info.alias);
3136 if (pciopts->numaNode != -1)
3137 virBufferAsprintf(&buf, ",numa_node=%d", pciopts->numaNode);
3138 break;
3139 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
3140 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3141 _("Unsupported PCI Express root controller"));
3142 goto error;
3143 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_DEFAULT:
3144 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST:
3145 virReportError(VIR_ERR_INTERNAL_ERROR,
3146 _("Unexpected PCI controller model %d"),
3147 def->model);
3148 goto error;
3150 break;
3153 case VIR_DOMAIN_CONTROLLER_TYPE_IDE:
3154 case VIR_DOMAIN_CONTROLLER_TYPE_FDC:
3155 case VIR_DOMAIN_CONTROLLER_TYPE_XENBUS:
3156 case VIR_DOMAIN_CONTROLLER_TYPE_LAST:
3157 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
3158 _("Unsupported controller type: %s"),
3159 virDomainControllerTypeToString(def->type));
3160 goto error;
3163 if (def->queues)
3164 virBufferAsprintf(&buf, ",num_queues=%u", def->queues);
3166 if (def->cmd_per_lun)
3167 virBufferAsprintf(&buf, ",cmd_per_lun=%u", def->cmd_per_lun);
3169 if (def->max_sectors)
3170 virBufferAsprintf(&buf, ",max_sectors=%u", def->max_sectors);
3172 qemuBuildIoEventFdStr(&buf, def->ioeventfd, qemuCaps);
3174 if (qemuBuildDeviceAddressStr(&buf, domainDef, &def->info, qemuCaps) < 0)
3175 goto error;
3177 done:
3178 if (virBufferCheckError(&buf) < 0)
3179 goto error;
3181 *devstr = virBufferContentAndReset(&buf);
3182 return 0;
3184 error:
3185 virBufferFreeAndReset(&buf);
3186 return -1;
3190 static bool
3191 qemuBuildDomainForbidLegacyUSBController(const virDomainDef *def)
3193 if (qemuDomainIsQ35(def) ||
3194 qemuDomainIsARMVirt(def) ||
3195 qemuDomainIsRISCVVirt(def))
3196 return true;
3198 return false;
3202 static int
3203 qemuBuildLegacyUSBControllerCommandLine(virCommandPtr cmd,
3204 const virDomainDef *def)
3206 size_t i;
3207 size_t nlegacy = 0;
3208 size_t nusb = 0;
3210 for (i = 0; i < def->ncontrollers; i++) {
3211 virDomainControllerDefPtr cont = def->controllers[i];
3213 if (cont->type != VIR_DOMAIN_CONTROLLER_TYPE_USB)
3214 continue;
3216 /* If we have mode='none', there are no other USB controllers */
3217 if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE)
3218 return 0;
3220 if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_DEFAULT)
3221 nlegacy++;
3222 else
3223 nusb++;
3226 if (nlegacy > 1) {
3227 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3228 _("Multiple legacy USB controllers are "
3229 "not supported"));
3230 return -1;
3233 if (nusb == 0 &&
3234 !qemuBuildDomainForbidLegacyUSBController(def) &&
3235 !ARCH_IS_S390(def->os.arch)) {
3236 /* We haven't added any USB controller yet, but we haven't been asked
3237 * not to add one either. Add a legacy USB controller, unless we're
3238 * creating a kind of guest we want to keep legacy-free */
3239 virCommandAddArg(cmd, "-usb");
3242 return 0;
3247 * qemuBuildSkipController:
3248 * @controller: Controller to check
3249 * @def: Domain definition
3251 * Returns true if this controller can be skipped for command line
3252 * generation or device validation.
3254 static bool
3255 qemuBuildSkipController(const virDomainControllerDef *controller,
3256 const virDomainDef *def)
3258 /* skip pcie-root */
3259 if (controller->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI &&
3260 controller->model == VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT)
3261 return true;
3263 /* Skip pci-root, except for pSeries guests (which actually
3264 * support more than one PCI Host Bridge per guest) */
3265 if (!qemuDomainIsPSeries(def) &&
3266 controller->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI &&
3267 controller->model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT)
3268 return true;
3270 /* first SATA controller on Q35 machines is implicit */
3271 if (controller->type == VIR_DOMAIN_CONTROLLER_TYPE_SATA &&
3272 controller->idx == 0 && qemuDomainIsQ35(def))
3273 return true;
3275 /* first IDE controller is implicit on various machines */
3276 if (controller->type == VIR_DOMAIN_CONTROLLER_TYPE_IDE &&
3277 controller->idx == 0 && qemuDomainHasBuiltinIDE(def))
3278 return true;
3280 return false;
3284 static int
3285 qemuBuildControllersByTypeCommandLine(virCommandPtr cmd,
3286 const virDomainDef *def,
3287 virQEMUCapsPtr qemuCaps,
3288 virDomainControllerType type)
3290 char *devstr = NULL;
3291 int ret = -1;
3292 size_t i;
3294 for (i = 0; i < def->ncontrollers; i++) {
3295 virDomainControllerDefPtr cont = def->controllers[i];
3297 if (cont->type != type)
3298 continue;
3300 if (qemuBuildSkipController(cont, def))
3301 continue;
3303 /* skip USB controllers with type none.*/
3304 if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
3305 cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE) {
3306 continue;
3309 if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
3310 cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_DEFAULT &&
3311 !qemuBuildDomainForbidLegacyUSBController(def)) {
3313 /* An appropriate default USB controller model should already
3314 * have been selected in qemuDomainDeviceDefPostParse(); if
3315 * we still have no model by now, we have to fall back to the
3316 * legacy USB controller.
3318 * Note that we *don't* want to end up with the legacy USB
3319 * controller for q35 and virt machines, so we go ahead and
3320 * fail in qemuBuildControllerDevStr(); on the other hand,
3321 * for s390 machines we want to ignore any USB controller
3322 * (see 548ba43028 for the full story), so we skip
3323 * qemuBuildControllerDevStr() but we don't ultimately end
3324 * up adding the legacy USB controller */
3325 continue;
3328 VIR_FREE(devstr);
3329 if (qemuBuildControllerDevStr(def, cont, qemuCaps, &devstr) < 0)
3330 goto cleanup;
3332 if (devstr) {
3333 if (qemuCommandAddExtDevice(cmd, &cont->info) < 0)
3334 goto cleanup;
3336 virCommandAddArg(cmd, "-device");
3337 virCommandAddArg(cmd, devstr);
3341 ret = 0;
3342 cleanup:
3343 VIR_FREE(devstr);
3344 return ret;
3348 static int
3349 qemuBuildControllersCommandLine(virCommandPtr cmd,
3350 const virDomainDef *def,
3351 virQEMUCapsPtr qemuCaps)
3353 size_t i;
3354 int contOrder[] = {
3356 * List of controller types that we add commandline args for,
3357 * *in the order we want to add them*.
3359 * The floppy controller is implicit on PIIX4 and older Q35
3360 * machines. For newer Q35 machines it is added out of the
3361 * controllers loop, after the floppy drives.
3363 * We don't add PCI/PCIe root controller either, because it's
3364 * implicit, but we do add PCI bridges and other PCI
3365 * controllers, so we leave that in to check each
3366 * one. Likewise, we don't do anything for the primary IDE
3367 * controller on an i440fx machine or primary SATA on q35, but
3368 * we do add those beyond these two exceptions.
3370 * CCID controllers are formatted separately after USB hubs,
3371 * because they go on the USB bus.
3373 VIR_DOMAIN_CONTROLLER_TYPE_PCI,
3374 VIR_DOMAIN_CONTROLLER_TYPE_USB,
3375 VIR_DOMAIN_CONTROLLER_TYPE_SCSI,
3376 VIR_DOMAIN_CONTROLLER_TYPE_IDE,
3377 VIR_DOMAIN_CONTROLLER_TYPE_SATA,
3378 VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL,
3380 int ret = -1;
3382 for (i = 0; i < ARRAY_CARDINALITY(contOrder); i++) {
3383 if (qemuBuildControllersByTypeCommandLine(cmd, def, qemuCaps, contOrder[i]) < 0)
3384 goto cleanup;
3387 if (qemuBuildLegacyUSBControllerCommandLine(cmd, def) < 0)
3388 goto cleanup;
3390 ret = 0;
3392 cleanup:
3393 return ret;
3397 static int
3398 qemuBuildMemoryBackendPropsShare(virJSONValuePtr props,
3399 virDomainMemoryAccess memAccess)
3401 switch (memAccess) {
3402 case VIR_DOMAIN_MEMORY_ACCESS_SHARED:
3403 return virJSONValueObjectAdd(props, "b:share", true, NULL);
3405 case VIR_DOMAIN_MEMORY_ACCESS_PRIVATE:
3406 return virJSONValueObjectAdd(props, "b:share", false, NULL);
3408 case VIR_DOMAIN_MEMORY_ACCESS_DEFAULT:
3409 case VIR_DOMAIN_MEMORY_ACCESS_LAST:
3410 break;
3413 return 0;
3417 static int
3418 qemuBuildMemoryGetDefaultPagesize(virQEMUDriverConfigPtr cfg,
3419 unsigned long long *pagesize)
3421 virHugeTLBFSPtr p;
3423 if (!cfg->nhugetlbfs) {
3424 virReportError(VIR_ERR_INTERNAL_ERROR,
3425 "%s", _("hugetlbfs filesystem is not mounted "
3426 "or disabled by administrator config"));
3427 return -1;
3430 if (!(p = virFileGetDefaultHugepage(cfg->hugetlbfs, cfg->nhugetlbfs)))
3431 p = &cfg->hugetlbfs[0];
3433 *pagesize = p->size;
3434 return 0;
3439 * qemuBuildMemoryBackendProps:
3440 * @backendProps: [out] constructed object
3441 * @alias: alias of the device
3442 * @cfg: qemu driver config object
3443 * @priv: pointer to domain private object
3444 * @def: domain definition object
3445 * @mem: memory definition object
3446 * @force: forcibly use one of the backends
3448 * Creates a configuration object that represents memory backend of given guest
3449 * NUMA node (domain @def and @mem). Use @priv->autoNodeset to fine tune the
3450 * placement of the memory on the host NUMA nodes.
3452 * By default, if no memory-backend-* object is necessary to fulfil the guest
3453 * configuration value of 1 is returned. This behaviour can be suppressed by
3454 * setting @force to true in which case 0 would be returned.
3456 * Then, if one of the three memory-backend-* should be used, the @priv->qemuCaps
3457 * is consulted to check if qemu does support it.
3459 * Returns: 0 on success,
3460 * 1 on success and if there's no need to use memory-backend-*
3461 * -1 on error.
3464 qemuBuildMemoryBackendProps(virJSONValuePtr *backendProps,
3465 const char *alias,
3466 virQEMUDriverConfigPtr cfg,
3467 qemuDomainObjPrivatePtr priv,
3468 virDomainDefPtr def,
3469 virDomainMemoryDefPtr mem,
3470 bool force)
3472 const char *backendType = "memory-backend-file";
3473 virDomainNumatuneMemMode mode;
3474 const long system_page_size = virGetSystemPageSizeKB();
3475 virDomainMemoryAccess memAccess = mem->access;
3476 size_t i;
3477 char *memPath = NULL;
3478 bool prealloc = false;
3479 virBitmapPtr nodemask = NULL;
3480 int ret = -1;
3481 virJSONValuePtr props = NULL;
3482 bool nodeSpecified = virDomainNumatuneNodeSpecified(def->numa, mem->targetNode);
3483 unsigned long long pagesize = mem->pagesize;
3484 bool needHugepage = !!pagesize;
3485 bool useHugepage = !!pagesize;
3486 int discard = mem->discard;
3488 /* The difference between @needHugepage and @useHugepage is that the latter
3489 * is true whenever huge page is defined for the current memory cell.
3490 * Either directly, or transitively via global domain huge pages. The
3491 * former is true whenever "memory-backend-file" must be used to satisfy
3492 * @useHugepage. */
3494 *backendProps = NULL;
3496 if (mem->targetNode >= 0) {
3497 /* memory devices could provide a invalid guest node */
3498 if (mem->targetNode >= virDomainNumaGetNodeCount(def->numa)) {
3499 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
3500 _("can't add memory backend for guest node '%d' as "
3501 "the guest has only '%zu' NUMA nodes configured"),
3502 mem->targetNode, virDomainNumaGetNodeCount(def->numa));
3503 return -1;
3506 if (memAccess == VIR_DOMAIN_MEMORY_ACCESS_DEFAULT)
3507 memAccess = virDomainNumaGetNodeMemoryAccessMode(def->numa, mem->targetNode);
3509 if (discard == VIR_TRISTATE_BOOL_ABSENT)
3510 discard = virDomainNumaGetNodeDiscard(def->numa, mem->targetNode);
3513 if (memAccess == VIR_DOMAIN_MEMORY_ACCESS_DEFAULT)
3514 memAccess = def->mem.access;
3516 if (discard == VIR_TRISTATE_BOOL_ABSENT)
3517 discard = def->mem.discard;
3519 if (virDomainNumatuneGetMode(def->numa, mem->targetNode, &mode) < 0 &&
3520 virDomainNumatuneGetMode(def->numa, -1, &mode) < 0)
3521 mode = VIR_DOMAIN_NUMATUNE_MEM_STRICT;
3523 if (pagesize == 0) {
3524 virDomainHugePagePtr master_hugepage = NULL;
3525 virDomainHugePagePtr hugepage = NULL;
3526 bool thisHugepage = false;
3528 /* Find the huge page size we want to use */
3529 for (i = 0; i < def->mem.nhugepages; i++) {
3530 hugepage = &def->mem.hugepages[i];
3532 if (!hugepage->nodemask) {
3533 master_hugepage = hugepage;
3534 continue;
3537 /* just find the master hugepage in case we don't use NUMA */
3538 if (mem->targetNode < 0)
3539 continue;
3541 if (virBitmapGetBit(hugepage->nodemask, mem->targetNode,
3542 &thisHugepage) < 0) {
3543 /* Ignore this error. It's not an error after all. Well,
3544 * the nodemask for this <page/> can contain lower NUMA
3545 * nodes than we are querying in here. */
3546 continue;
3549 if (thisHugepage) {
3550 /* Hooray, we've found the page size */
3551 needHugepage = true;
3552 break;
3556 if (i == def->mem.nhugepages) {
3557 /* We have not found specific huge page to be used with this
3558 * NUMA node. Use the generic setting then (<page/> without any
3559 * @nodemask) if possible. */
3560 hugepage = master_hugepage;
3563 if (hugepage) {
3564 pagesize = hugepage->size;
3565 useHugepage = true;
3569 if (pagesize == system_page_size) {
3570 /* However, if user specified to use "huge" page
3571 * of regular system page size, it's as if they
3572 * hasn't specified any huge pages at all. */
3573 pagesize = 0;
3574 needHugepage = false;
3575 useHugepage = false;
3576 } else if (pagesize == 0) {
3577 if (qemuBuildMemoryGetDefaultPagesize(cfg, &pagesize) < 0)
3578 goto cleanup;
3581 if (!(props = virJSONValueNewObject()))
3582 return -1;
3584 if (def->mem.source == VIR_DOMAIN_MEMORY_SOURCE_MEMFD) {
3585 backendType = "memory-backend-memfd";
3587 if (useHugepage &&
3588 (virJSONValueObjectAdd(props, "b:hugetlb", useHugepage, NULL) < 0 ||
3589 virJSONValueObjectAdd(props, "U:hugetlbsize", pagesize << 10, NULL) < 0)) {
3590 goto cleanup;
3593 if (qemuBuildMemoryBackendPropsShare(props, memAccess) < 0)
3594 goto cleanup;
3596 } else if (useHugepage || mem->nvdimmPath || memAccess ||
3597 def->mem.source == VIR_DOMAIN_MEMORY_SOURCE_FILE) {
3599 if (mem->nvdimmPath) {
3600 if (VIR_STRDUP(memPath, mem->nvdimmPath) < 0)
3601 goto cleanup;
3602 if (!priv->memPrealloc)
3603 prealloc = true;
3604 } else if (useHugepage) {
3605 if (qemuGetDomainHupageMemPath(def, cfg, pagesize, &memPath) < 0)
3606 goto cleanup;
3607 if (!priv->memPrealloc)
3608 prealloc = true;
3609 } else {
3610 /* We can have both pagesize and mem source. If that's the case,
3611 * prefer hugepages as those are more specific. */
3612 if (qemuGetMemoryBackingPath(def, cfg, mem->info.alias, &memPath) < 0)
3613 goto cleanup;
3616 if (virJSONValueObjectAdd(props,
3617 "B:prealloc", prealloc,
3618 "s:mem-path", memPath,
3619 NULL) < 0)
3620 goto cleanup;
3622 if (!mem->nvdimmPath &&
3623 discard == VIR_TRISTATE_BOOL_YES) {
3624 if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_OBJECT_MEMORY_FILE_DISCARD)) {
3625 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3626 _("this QEMU doesn't support memory discard"));
3627 goto cleanup;
3630 if (virJSONValueObjectAdd(props,
3631 "B:discard-data", true,
3632 NULL) < 0)
3633 goto cleanup;
3636 if (qemuBuildMemoryBackendPropsShare(props, memAccess) < 0)
3637 goto cleanup;
3638 } else {
3639 backendType = "memory-backend-ram";
3642 if (virJSONValueObjectAdd(props, "U:size", mem->size * 1024, NULL) < 0)
3643 goto cleanup;
3645 if (mem->alignsize) {
3646 if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_OBJECT_MEMORY_FILE_ALIGN)) {
3647 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3648 _("nvdimm align property is not available "
3649 "with this QEMU binary"));
3650 goto cleanup;
3652 if (virJSONValueObjectAdd(props, "U:align", mem->alignsize * 1024, NULL) < 0)
3653 goto cleanup;
3656 if (mem->nvdimmPmem) {
3657 if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_OBJECT_MEMORY_FILE_PMEM)) {
3658 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3659 _("nvdimm pmem property is not available "
3660 "with this QEMU binary"));
3661 goto cleanup;
3663 if (virJSONValueObjectAdd(props, "s:pmem", "on", NULL) < 0)
3664 goto cleanup;
3667 if (mem->sourceNodes) {
3668 nodemask = mem->sourceNodes;
3669 } else {
3670 if (virDomainNumatuneMaybeGetNodeset(def->numa, priv->autoNodeset,
3671 &nodemask, mem->targetNode) < 0)
3672 goto cleanup;
3675 if (nodemask) {
3676 if (!virNumaNodesetIsAvailable(nodemask))
3677 goto cleanup;
3678 if (virJSONValueObjectAdd(props,
3679 "m:host-nodes", nodemask,
3680 "S:policy", qemuNumaPolicyTypeToString(mode),
3681 NULL) < 0)
3682 goto cleanup;
3685 /* If none of the following is requested... */
3686 if (!needHugepage && !mem->sourceNodes && !nodeSpecified &&
3687 !mem->nvdimmPath &&
3688 memAccess == VIR_DOMAIN_MEMORY_ACCESS_DEFAULT &&
3689 def->mem.source != VIR_DOMAIN_MEMORY_SOURCE_FILE &&
3690 def->mem.source != VIR_DOMAIN_MEMORY_SOURCE_MEMFD &&
3691 !force) {
3692 /* report back that using the new backend is not necessary
3693 * to achieve the desired configuration */
3694 ret = 1;
3695 } else {
3696 /* otherwise check the required capability */
3697 if (STREQ(backendType, "memory-backend-file") &&
3698 !virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_OBJECT_MEMORY_FILE)) {
3699 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3700 _("this qemu doesn't support the "
3701 "memory-backend-file object"));
3702 goto cleanup;
3703 } else if (STREQ(backendType, "memory-backend-ram") &&
3704 !virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_OBJECT_MEMORY_RAM)) {
3705 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3706 _("this qemu doesn't support the "
3707 "memory-backend-ram object"));
3708 goto cleanup;
3709 } else if (STREQ(backendType, "memory-backend-memory") &&
3710 !virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_OBJECT_MEMORY_MEMFD)) {
3711 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3712 _("this qemu doesn't support the "
3713 "memory-backend-memfd object"));
3714 goto cleanup;
3717 ret = 0;
3720 if (!(*backendProps = qemuMonitorCreateObjectPropsWrap(backendType, alias,
3721 &props)))
3722 ret = -1;
3724 cleanup:
3725 virJSONValueFree(props);
3726 VIR_FREE(memPath);
3727 return ret;
3731 static int
3732 qemuBuildMemoryCellBackendStr(virDomainDefPtr def,
3733 virQEMUDriverConfigPtr cfg,
3734 size_t cell,
3735 qemuDomainObjPrivatePtr priv,
3736 virBufferPtr buf)
3738 virJSONValuePtr props = NULL;
3739 char *alias = NULL;
3740 int ret = -1;
3741 int rc;
3742 virDomainMemoryDef mem = { 0 };
3743 unsigned long long memsize = virDomainNumaGetNodeMemorySize(def->numa,
3744 cell);
3746 if (virAsprintf(&alias, "ram-node%zu", cell) < 0)
3747 goto cleanup;
3749 mem.size = memsize;
3750 mem.targetNode = cell;
3751 mem.info.alias = alias;
3753 if ((rc = qemuBuildMemoryBackendProps(&props, alias, cfg,
3754 priv, def, &mem, false)) < 0)
3755 goto cleanup;
3757 if (virQEMUBuildObjectCommandlineFromJSON(buf, props) < 0)
3758 goto cleanup;
3760 ret = rc;
3762 cleanup:
3763 VIR_FREE(alias);
3764 virJSONValueFree(props);
3766 return ret;
3770 static int
3771 qemuBuildMemoryDimmBackendStr(virBufferPtr buf,
3772 virDomainMemoryDefPtr mem,
3773 virDomainDefPtr def,
3774 virQEMUDriverConfigPtr cfg,
3775 qemuDomainObjPrivatePtr priv)
3777 virJSONValuePtr props = NULL;
3778 char *alias = NULL;
3779 int ret = -1;
3781 if (!mem->info.alias) {
3782 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3783 _("memory device alias is not assigned"));
3784 return -1;
3787 if (virAsprintf(&alias, "mem%s", mem->info.alias) < 0)
3788 goto cleanup;
3790 if (qemuBuildMemoryBackendProps(&props, alias, cfg,
3791 priv, def, mem, true) < 0)
3792 goto cleanup;
3794 if (virQEMUBuildObjectCommandlineFromJSON(buf, props) < 0)
3795 goto cleanup;
3797 ret = 0;
3799 cleanup:
3800 VIR_FREE(alias);
3801 virJSONValueFree(props);
3803 return ret;
3807 char *
3808 qemuBuildMemoryDeviceStr(virDomainMemoryDefPtr mem,
3809 qemuDomainObjPrivatePtr priv)
3811 virBuffer buf = VIR_BUFFER_INITIALIZER;
3812 const char *device;
3814 if (!mem->info.alias) {
3815 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3816 _("missing alias for memory device"));
3817 return NULL;
3820 switch ((virDomainMemoryModel) mem->model) {
3821 case VIR_DOMAIN_MEMORY_MODEL_NVDIMM:
3822 case VIR_DOMAIN_MEMORY_MODEL_DIMM:
3824 if (mem->model == VIR_DOMAIN_MEMORY_MODEL_DIMM)
3825 device = "pc-dimm";
3826 else
3827 device = "nvdimm";
3829 virBufferAsprintf(&buf, "%s,", device);
3831 if (mem->targetNode >= 0)
3832 virBufferAsprintf(&buf, "node=%d,", mem->targetNode);
3834 if (mem->labelsize)
3835 virBufferAsprintf(&buf, "label-size=%llu,", mem->labelsize * 1024);
3837 if (mem->readonly) {
3838 if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE_NVDIMM_UNARMED)) {
3839 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3840 _("nvdimm readonly property is not available "
3841 "with this QEMU binary"));
3842 return NULL;
3844 virBufferAddLit(&buf, "unarmed=on,");
3847 virBufferAsprintf(&buf, "memdev=mem%s,id=%s",
3848 mem->info.alias, mem->info.alias);
3850 if (mem->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM) {
3851 virBufferAsprintf(&buf, ",slot=%d", mem->info.addr.dimm.slot);
3852 if (mem->info.addr.dimm.base)
3853 virBufferAsprintf(&buf, ",addr=%llu", mem->info.addr.dimm.base);
3856 break;
3858 case VIR_DOMAIN_MEMORY_MODEL_NONE:
3859 case VIR_DOMAIN_MEMORY_MODEL_LAST:
3860 break;
3864 if (virBufferCheckError(&buf) < 0)
3865 return NULL;
3867 return virBufferContentAndReset(&buf);
3871 static char *
3872 qemuBuildLegacyNicStr(virDomainNetDefPtr net)
3874 char *str;
3875 char macaddr[VIR_MAC_STRING_BUFLEN];
3876 const char *netmodel = virDomainNetGetModelString(net);
3878 ignore_value(virAsprintf(&str,
3879 "nic,macaddr=%s,netdev=host%s%s%s%s%s",
3880 virMacAddrFormat(&net->mac, macaddr),
3881 net->info.alias,
3882 netmodel ? ",model=" : "",
3883 NULLSTR_EMPTY(netmodel),
3884 (net->info.alias ? ",id=" : ""),
3885 NULLSTR_EMPTY(net->info.alias)));
3886 return str;
3890 char *
3891 qemuBuildNicDevStr(virDomainDefPtr def,
3892 virDomainNetDefPtr net,
3893 unsigned int bootindex,
3894 size_t vhostfdSize,
3895 virQEMUCapsPtr qemuCaps)
3897 virBuffer buf = VIR_BUFFER_INITIALIZER;
3898 bool usingVirtio = false;
3899 char macaddr[VIR_MAC_STRING_BUFLEN];
3901 if (virDomainNetIsVirtioModel(net)) {
3902 if (qemuBuildVirtioDevStr(&buf, "virtio-net", qemuCaps,
3903 VIR_DOMAIN_DEVICE_NET, net) < 0) {
3904 goto error;
3907 usingVirtio = true;
3908 } else {
3909 virBufferAddStr(&buf, virDomainNetGetModelString(net));
3912 if (usingVirtio && net->driver.virtio.txmode) {
3913 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_TX_ALG)) {
3914 virBufferAddLit(&buf, ",tx=");
3915 switch (net->driver.virtio.txmode) {
3916 case VIR_DOMAIN_NET_VIRTIO_TX_MODE_IOTHREAD:
3917 virBufferAddLit(&buf, "bh");
3918 break;
3920 case VIR_DOMAIN_NET_VIRTIO_TX_MODE_TIMER:
3921 virBufferAddLit(&buf, "timer");
3922 break;
3924 case VIR_DOMAIN_NET_VIRTIO_TX_MODE_DEFAULT:
3925 break;
3927 case VIR_DOMAIN_NET_VIRTIO_TX_MODE_LAST:
3928 default:
3929 /* this should never happen, if it does, we need
3930 * to add another case to this switch.
3932 virReportEnumRangeError(virDomainNetVirtioTxModeType,
3933 net->driver.virtio.txmode);
3934 goto error;
3936 } else {
3937 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3938 _("virtio-net-pci 'tx' option not supported in this QEMU binary"));
3939 goto error;
3942 if (usingVirtio) {
3943 qemuBuildIoEventFdStr(&buf, net->driver.virtio.ioeventfd, qemuCaps);
3944 if (net->driver.virtio.event_idx &&
3945 virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_NET_EVENT_IDX)) {
3946 virBufferAsprintf(&buf, ",event_idx=%s",
3947 virTristateSwitchTypeToString(net->driver.virtio.event_idx));
3949 if (net->driver.virtio.host.csum) {
3950 virBufferAsprintf(&buf, ",csum=%s",
3951 virTristateSwitchTypeToString(net->driver.virtio.host.csum));
3953 if (net->driver.virtio.host.gso) {
3954 virBufferAsprintf(&buf, ",gso=%s",
3955 virTristateSwitchTypeToString(net->driver.virtio.host.gso));
3957 if (net->driver.virtio.host.tso4) {
3958 virBufferAsprintf(&buf, ",host_tso4=%s",
3959 virTristateSwitchTypeToString(net->driver.virtio.host.tso4));
3961 if (net->driver.virtio.host.tso6) {
3962 virBufferAsprintf(&buf, ",host_tso6=%s",
3963 virTristateSwitchTypeToString(net->driver.virtio.host.tso6));
3965 if (net->driver.virtio.host.ecn) {
3966 virBufferAsprintf(&buf, ",host_ecn=%s",
3967 virTristateSwitchTypeToString(net->driver.virtio.host.ecn));
3969 if (net->driver.virtio.host.ufo) {
3970 virBufferAsprintf(&buf, ",host_ufo=%s",
3971 virTristateSwitchTypeToString(net->driver.virtio.host.ufo));
3973 if (net->driver.virtio.host.mrg_rxbuf) {
3974 virBufferAsprintf(&buf, ",mrg_rxbuf=%s",
3975 virTristateSwitchTypeToString(net->driver.virtio.host.mrg_rxbuf));
3977 if (net->driver.virtio.guest.csum) {
3978 virBufferAsprintf(&buf, ",guest_csum=%s",
3979 virTristateSwitchTypeToString(net->driver.virtio.guest.csum));
3981 if (net->driver.virtio.guest.tso4) {
3982 virBufferAsprintf(&buf, ",guest_tso4=%s",
3983 virTristateSwitchTypeToString(net->driver.virtio.guest.tso4));
3985 if (net->driver.virtio.guest.tso6) {
3986 virBufferAsprintf(&buf, ",guest_tso6=%s",
3987 virTristateSwitchTypeToString(net->driver.virtio.guest.tso6));
3989 if (net->driver.virtio.guest.ecn) {
3990 virBufferAsprintf(&buf, ",guest_ecn=%s",
3991 virTristateSwitchTypeToString(net->driver.virtio.guest.ecn));
3993 if (net->driver.virtio.guest.ufo) {
3994 virBufferAsprintf(&buf, ",guest_ufo=%s",
3995 virTristateSwitchTypeToString(net->driver.virtio.guest.ufo));
3998 if (usingVirtio && vhostfdSize > 1) {
3999 if (net->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW) {
4000 /* ccw provides a one to one relation of fds to queues and
4001 * does not support the vectors option
4003 virBufferAddLit(&buf, ",mq=on");
4004 } else {
4005 /* As advised at https://www.linux-kvm.org/page/Multiqueue
4006 * we should add vectors=2*N+2 where N is the vhostfdSize
4008 virBufferAsprintf(&buf, ",mq=on,vectors=%zu", 2 * vhostfdSize + 2);
4011 if (usingVirtio && net->driver.virtio.rx_queue_size) {
4012 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_NET_RX_QUEUE_SIZE)) {
4013 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4014 _("virtio rx_queue_size option is not supported with this QEMU binary"));
4015 goto error;
4017 virBufferAsprintf(&buf, ",rx_queue_size=%u", net->driver.virtio.rx_queue_size);
4019 if (usingVirtio && net->driver.virtio.tx_queue_size) {
4020 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_NET_TX_QUEUE_SIZE)) {
4021 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4022 _("virtio tx_queue_size option is not supported with this QEMU binary"));
4023 goto error;
4025 virBufferAsprintf(&buf, ",tx_queue_size=%u", net->driver.virtio.tx_queue_size);
4028 if (usingVirtio && net->mtu) {
4029 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_NET_HOST_MTU)) {
4030 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4031 _("setting MTU is not supported with this QEMU binary"));
4032 goto error;
4034 virBufferAsprintf(&buf, ",host_mtu=%u", net->mtu);
4037 virBufferAsprintf(&buf, ",netdev=host%s", net->info.alias);
4038 virBufferAsprintf(&buf, ",id=%s", net->info.alias);
4039 virBufferAsprintf(&buf, ",mac=%s",
4040 virMacAddrFormat(&net->mac, macaddr));
4042 if (qemuBuildDeviceAddressStr(&buf, def, &net->info, qemuCaps) < 0)
4043 goto error;
4044 if (qemuBuildRomStr(&buf, &net->info) < 0)
4045 goto error;
4046 if (bootindex)
4047 virBufferAsprintf(&buf, ",bootindex=%u", bootindex);
4048 if (usingVirtio &&
4049 qemuBuildVirtioOptionsStr(&buf, net->virtio, qemuCaps) < 0)
4050 goto error;
4052 if (virBufferCheckError(&buf) < 0)
4053 goto error;
4055 return virBufferContentAndReset(&buf);
4057 error:
4058 virBufferFreeAndReset(&buf);
4059 return NULL;
4063 char *
4064 qemuBuildHostNetStr(virDomainNetDefPtr net,
4065 virQEMUDriverPtr driver,
4066 char **tapfd,
4067 size_t tapfdSize,
4068 char **vhostfd,
4069 size_t vhostfdSize)
4071 bool is_tap = false;
4072 virBuffer buf = VIR_BUFFER_INITIALIZER;
4073 virDomainNetType netType = virDomainNetGetActualType(net);
4074 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
4075 size_t i;
4076 char *addr = NULL;
4077 char *ret = NULL;
4079 if (net->script && netType != VIR_DOMAIN_NET_TYPE_ETHERNET) {
4080 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4081 _("scripts are not supported on interfaces of type %s"),
4082 virDomainNetTypeToString(netType));
4083 goto cleanup;
4086 switch (netType) {
4088 * If type='bridge', and we're running as privileged user
4089 * or -netdev bridge is not supported then it will fall
4090 * through, -net tap,fd
4092 case VIR_DOMAIN_NET_TYPE_BRIDGE:
4093 case VIR_DOMAIN_NET_TYPE_NETWORK:
4094 case VIR_DOMAIN_NET_TYPE_DIRECT:
4095 case VIR_DOMAIN_NET_TYPE_ETHERNET:
4096 virBufferAddLit(&buf, "tap,");
4097 /* for one tapfd 'fd=' shall be used,
4098 * for more than one 'fds=' is the right choice */
4099 if (tapfdSize == 1) {
4100 virBufferAsprintf(&buf, "fd=%s,", tapfd[0]);
4101 } else {
4102 virBufferAddLit(&buf, "fds=");
4103 for (i = 0; i < tapfdSize; i++) {
4104 if (i)
4105 virBufferAddChar(&buf, ':');
4106 virBufferAdd(&buf, tapfd[i], -1);
4108 virBufferAddChar(&buf, ',');
4110 is_tap = true;
4111 break;
4113 case VIR_DOMAIN_NET_TYPE_CLIENT:
4114 virBufferAsprintf(&buf, "socket,connect=%s:%d,",
4115 net->data.socket.address,
4116 net->data.socket.port);
4117 break;
4119 case VIR_DOMAIN_NET_TYPE_SERVER:
4120 virBufferAsprintf(&buf, "socket,listen=%s:%d,",
4121 NULLSTR_EMPTY(net->data.socket.address),
4122 net->data.socket.port);
4123 break;
4125 case VIR_DOMAIN_NET_TYPE_MCAST:
4126 virBufferAsprintf(&buf, "socket,mcast=%s:%d,",
4127 net->data.socket.address,
4128 net->data.socket.port);
4129 break;
4131 case VIR_DOMAIN_NET_TYPE_UDP:
4132 virBufferAsprintf(&buf, "socket,udp=%s:%d,localaddr=%s:%d,",
4133 net->data.socket.address,
4134 net->data.socket.port,
4135 net->data.socket.localaddr,
4136 net->data.socket.localport);
4137 break;
4139 case VIR_DOMAIN_NET_TYPE_USER:
4140 virBufferAddLit(&buf, "user,");
4141 for (i = 0; i < net->guestIP.nips; i++) {
4142 const virNetDevIPAddr *ip = net->guestIP.ips[i];
4143 const char *prefix = "";
4145 if (!(addr = virSocketAddrFormat(&ip->address)))
4146 goto cleanup;
4148 if (VIR_SOCKET_ADDR_IS_FAMILY(&ip->address, AF_INET))
4149 prefix = "net=";
4150 if (VIR_SOCKET_ADDR_IS_FAMILY(&ip->address, AF_INET6))
4151 prefix = "ipv6-net=";
4153 virBufferAsprintf(&buf, "%s%s", prefix, addr);
4154 if (ip->prefix)
4155 virBufferAsprintf(&buf, "/%u", ip->prefix);
4156 virBufferAddChar(&buf, ',');
4157 VIR_FREE(addr);
4159 break;
4161 case VIR_DOMAIN_NET_TYPE_INTERNAL:
4162 virBufferAddLit(&buf, "user,");
4163 break;
4165 case VIR_DOMAIN_NET_TYPE_VHOSTUSER:
4166 virBufferAsprintf(&buf, "vhost-user,chardev=char%s,",
4167 net->info.alias);
4168 if (net->driver.virtio.queues > 1)
4169 virBufferAsprintf(&buf, "queues=%u,",
4170 net->driver.virtio.queues);
4171 break;
4173 case VIR_DOMAIN_NET_TYPE_HOSTDEV:
4174 /* Should have been handled earlier via PCI/USB hotplug code. */
4175 case VIR_DOMAIN_NET_TYPE_LAST:
4176 break;
4179 virBufferAsprintf(&buf, "id=host%s,", net->info.alias);
4181 if (is_tap) {
4182 if (vhostfdSize) {
4183 virBufferAddLit(&buf, "vhost=on,");
4184 if (vhostfdSize == 1) {
4185 virBufferAsprintf(&buf, "vhostfd=%s,", vhostfd[0]);
4186 } else {
4187 virBufferAddLit(&buf, "vhostfds=");
4188 for (i = 0; i < vhostfdSize; i++) {
4189 if (i)
4190 virBufferAddChar(&buf, ':');
4191 virBufferAdd(&buf, vhostfd[i], -1);
4193 virBufferAddChar(&buf, ',');
4196 if (net->tune.sndbuf_specified)
4197 virBufferAsprintf(&buf, "sndbuf=%lu,", net->tune.sndbuf);
4201 virBufferTrim(&buf, ",", -1);
4202 if (virBufferCheckError(&buf) < 0)
4203 goto cleanup;
4205 ret = virBufferContentAndReset(&buf);
4206 cleanup:
4207 virBufferFreeAndReset(&buf);
4208 virObjectUnref(cfg);
4209 VIR_FREE(addr);
4210 return ret;
4214 char *
4215 qemuBuildWatchdogDevStr(const virDomainDef *def,
4216 virDomainWatchdogDefPtr dev,
4217 virQEMUCapsPtr qemuCaps)
4219 virBuffer buf = VIR_BUFFER_INITIALIZER;
4221 const char *model = virDomainWatchdogModelTypeToString(dev->model);
4222 if (!model) {
4223 virReportError(VIR_ERR_INTERNAL_ERROR,
4224 "%s", _("missing watchdog model"));
4225 goto error;
4228 virBufferAsprintf(&buf, "%s,id=%s", model, dev->info.alias);
4229 if (qemuBuildDeviceAddressStr(&buf, def, &dev->info, qemuCaps) < 0)
4230 goto error;
4232 if (virBufferCheckError(&buf) < 0)
4233 goto error;
4235 return virBufferContentAndReset(&buf);
4237 error:
4238 virBufferFreeAndReset(&buf);
4239 return NULL;
4243 static int
4244 qemuBuildWatchdogCommandLine(virCommandPtr cmd,
4245 const virDomainDef *def,
4246 virQEMUCapsPtr qemuCaps)
4248 virDomainWatchdogDefPtr watchdog = def->watchdog;
4249 char *optstr;
4250 const char *action;
4251 int actualAction;
4253 if (!def->watchdog)
4254 return 0;
4256 if (qemuCommandAddExtDevice(cmd, &def->watchdog->info) < 0)
4257 return -1;
4259 virCommandAddArg(cmd, "-device");
4261 optstr = qemuBuildWatchdogDevStr(def, watchdog, qemuCaps);
4262 if (!optstr)
4263 return -1;
4265 virCommandAddArg(cmd, optstr);
4266 VIR_FREE(optstr);
4268 /* qemu doesn't have a 'dump' action; we tell qemu to 'pause', then
4269 libvirt listens for the watchdog event, and we perform the dump
4270 ourselves. so convert 'dump' to 'pause' for the qemu cli */
4271 actualAction = watchdog->action;
4272 if (watchdog->action == VIR_DOMAIN_WATCHDOG_ACTION_DUMP)
4273 actualAction = VIR_DOMAIN_WATCHDOG_ACTION_PAUSE;
4275 action = virDomainWatchdogActionTypeToString(actualAction);
4276 if (!action) {
4277 virReportError(VIR_ERR_INTERNAL_ERROR,
4278 "%s", _("invalid watchdog action"));
4279 return -1;
4281 virCommandAddArgList(cmd, "-watchdog-action", action, NULL);
4283 return 0;
4287 static int
4288 qemuBuildMemballoonCommandLine(virCommandPtr cmd,
4289 const virDomainDef *def,
4290 virQEMUCapsPtr qemuCaps)
4292 virBuffer buf = VIR_BUFFER_INITIALIZER;
4294 if (!virDomainDefHasMemballoon(def))
4295 return 0;
4297 if (qemuBuildVirtioDevStr(&buf, "virtio-balloon", qemuCaps,
4298 VIR_DOMAIN_DEVICE_MEMBALLOON,
4299 def->memballoon) < 0) {
4300 goto error;
4303 virBufferAsprintf(&buf, ",id=%s", def->memballoon->info.alias);
4304 if (qemuBuildDeviceAddressStr(&buf, def, &def->memballoon->info, qemuCaps) < 0)
4305 goto error;
4307 if (def->memballoon->autodeflate != VIR_TRISTATE_SWITCH_ABSENT) {
4308 virBufferAsprintf(&buf, ",deflate-on-oom=%s",
4309 virTristateSwitchTypeToString(def->memballoon->autodeflate));
4312 if (qemuBuildVirtioOptionsStr(&buf, def->memballoon->virtio, qemuCaps) < 0)
4313 goto error;
4315 if (qemuCommandAddExtDevice(cmd, &def->memballoon->info) < 0)
4316 goto error;
4318 virCommandAddArg(cmd, "-device");
4319 virCommandAddArgBuffer(cmd, &buf);
4320 return 0;
4322 error:
4323 virBufferFreeAndReset(&buf);
4324 return -1;
4328 static char *
4329 qemuBuildNVRAMDevStr(virDomainNVRAMDefPtr dev)
4331 virBuffer buf = VIR_BUFFER_INITIALIZER;
4333 if (dev->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO &&
4334 dev->info.addr.spaprvio.has_reg) {
4335 virBufferAsprintf(&buf, "spapr-nvram.reg=0x%llx",
4336 dev->info.addr.spaprvio.reg);
4337 } else {
4338 virReportError(VIR_ERR_XML_ERROR, "%s",
4339 _("nvram address type must be spaprvio"));
4340 goto error;
4343 if (virBufferCheckError(&buf) < 0)
4344 goto error;
4346 return virBufferContentAndReset(&buf);
4348 error:
4349 virBufferFreeAndReset(&buf);
4350 return NULL;
4354 static int
4355 qemuBuildNVRAMCommandLine(virCommandPtr cmd,
4356 const virDomainDef *def,
4357 virQEMUCapsPtr qemuCaps)
4359 if (!def->nvram)
4360 return 0;
4362 if (qemuDomainIsPSeries(def)) {
4363 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_NVRAM)) {
4364 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4365 _("nvram device is not supported by "
4366 "this QEMU binary"));
4367 return -1;
4370 char *optstr;
4371 virCommandAddArg(cmd, "-global");
4372 optstr = qemuBuildNVRAMDevStr(def->nvram);
4373 if (!optstr)
4374 return -1;
4375 virCommandAddArg(cmd, optstr);
4376 VIR_FREE(optstr);
4377 } else {
4378 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4379 _("nvram device is only supported for PPC64"));
4380 return -1;
4383 return 0;
4387 static char *
4388 qemuBuildVirtioInputDevStr(const virDomainDef *def,
4389 virDomainInputDefPtr dev,
4390 virQEMUCapsPtr qemuCaps)
4392 virBuffer buf = VIR_BUFFER_INITIALIZER;
4394 switch ((virDomainInputType)dev->type) {
4395 case VIR_DOMAIN_INPUT_TYPE_MOUSE:
4396 if (qemuBuildVirtioDevStr(&buf, "virtio-mouse", qemuCaps,
4397 VIR_DOMAIN_DEVICE_INPUT, dev) < 0) {
4398 goto error;
4400 break;
4401 case VIR_DOMAIN_INPUT_TYPE_TABLET:
4402 if (qemuBuildVirtioDevStr(&buf, "virtio-tablet", qemuCaps,
4403 VIR_DOMAIN_DEVICE_INPUT, dev) < 0) {
4404 goto error;
4406 break;
4407 case VIR_DOMAIN_INPUT_TYPE_KBD:
4408 if (qemuBuildVirtioDevStr(&buf, "virtio-keyboard", qemuCaps,
4409 VIR_DOMAIN_DEVICE_INPUT, dev) < 0) {
4410 goto error;
4412 break;
4413 case VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH:
4414 if (qemuBuildVirtioDevStr(&buf, "virtio-input-host", qemuCaps,
4415 VIR_DOMAIN_DEVICE_INPUT, dev) < 0) {
4416 goto error;
4418 break;
4419 case VIR_DOMAIN_INPUT_TYPE_LAST:
4420 default:
4421 virReportEnumRangeError(virDomainInputType, dev->type);
4422 goto error;
4425 virBufferAsprintf(&buf, ",id=%s", dev->info.alias);
4427 if (dev->type == VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH) {
4428 virBufferAddLit(&buf, ",evdev=");
4429 virQEMUBuildBufferEscapeComma(&buf, dev->source.evdev);
4432 if (qemuBuildDeviceAddressStr(&buf, def, &dev->info, qemuCaps) < 0)
4433 goto error;
4435 if (qemuBuildVirtioOptionsStr(&buf, dev->virtio, qemuCaps) < 0)
4436 goto error;
4438 if (virBufferCheckError(&buf) < 0)
4439 goto error;
4441 return virBufferContentAndReset(&buf);
4443 error:
4444 virBufferFreeAndReset(&buf);
4445 return NULL;
4448 static char *
4449 qemuBuildUSBInputDevStr(const virDomainDef *def,
4450 virDomainInputDefPtr dev,
4451 virQEMUCapsPtr qemuCaps)
4453 virBuffer buf = VIR_BUFFER_INITIALIZER;
4455 switch (dev->type) {
4456 case VIR_DOMAIN_INPUT_TYPE_MOUSE:
4457 virBufferAsprintf(&buf, "usb-mouse,id=%s", dev->info.alias);
4458 break;
4459 case VIR_DOMAIN_INPUT_TYPE_TABLET:
4460 virBufferAsprintf(&buf, "usb-tablet,id=%s", dev->info.alias);
4461 break;
4462 case VIR_DOMAIN_INPUT_TYPE_KBD:
4463 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_USB_KBD)) {
4464 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4465 _("usb keyboard is not supported by this "
4466 "QEMU binary"));
4467 goto error;
4469 virBufferAsprintf(&buf, "usb-kbd,id=%s", dev->info.alias);
4470 break;
4473 if (qemuBuildDeviceAddressStr(&buf, def, &dev->info, qemuCaps) < 0)
4474 goto error;
4476 if (virBufferCheckError(&buf) < 0)
4477 goto error;
4479 return virBufferContentAndReset(&buf);
4481 error:
4482 virBufferFreeAndReset(&buf);
4483 return NULL;
4488 qemuBuildInputDevStr(char **devstr,
4489 const virDomainDef *def,
4490 virDomainInputDefPtr input,
4491 virQEMUCapsPtr qemuCaps)
4493 switch (input->bus) {
4494 case VIR_DOMAIN_INPUT_BUS_USB:
4495 if (!(*devstr = qemuBuildUSBInputDevStr(def, input, qemuCaps)))
4496 return -1;
4497 break;
4499 case VIR_DOMAIN_INPUT_BUS_VIRTIO:
4500 if (!(*devstr = qemuBuildVirtioInputDevStr(def, input, qemuCaps)))
4501 return -1;
4502 break;
4504 return 0;
4508 static int
4509 qemuBuildInputCommandLine(virCommandPtr cmd,
4510 const virDomainDef *def,
4511 virQEMUCapsPtr qemuCaps)
4513 size_t i;
4515 for (i = 0; i < def->ninputs; i++) {
4516 virDomainInputDefPtr input = def->inputs[i];
4517 char *devstr = NULL;
4519 if (qemuCommandAddExtDevice(cmd, &input->info) < 0)
4520 return -1;
4522 if (qemuBuildInputDevStr(&devstr, def, input, qemuCaps) < 0)
4523 return -1;
4525 if (devstr) {
4526 virCommandAddArg(cmd, "-device");
4527 virCommandAddArg(cmd, devstr);
4530 VIR_FREE(devstr);
4533 return 0;
4537 static char *
4538 qemuBuildSoundDevStr(const virDomainDef *def,
4539 virDomainSoundDefPtr sound,
4540 virQEMUCapsPtr qemuCaps)
4542 virBuffer buf = VIR_BUFFER_INITIALIZER;
4543 const char *model = NULL;
4545 /* Hack for devices with different names in QEMU and libvirt */
4546 switch ((virDomainSoundModel) sound->model) {
4547 case VIR_DOMAIN_SOUND_MODEL_ES1370:
4548 model = "ES1370";
4549 break;
4550 case VIR_DOMAIN_SOUND_MODEL_AC97:
4551 model = "AC97";
4552 break;
4553 case VIR_DOMAIN_SOUND_MODEL_ICH6:
4554 model = "intel-hda";
4555 break;
4556 case VIR_DOMAIN_SOUND_MODEL_USB:
4557 model = "usb-audio";
4558 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_USB_AUDIO)) {
4559 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4560 _("usb-audio controller is not supported "
4561 "by this QEMU binary"));
4562 goto error;
4564 break;
4565 case VIR_DOMAIN_SOUND_MODEL_ICH9:
4566 model = "ich9-intel-hda";
4567 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_ICH9_INTEL_HDA)) {
4568 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4569 _("The ich9-intel-hda audio controller "
4570 "is not supported in this QEMU binary"));
4571 goto error;
4573 break;
4574 case VIR_DOMAIN_SOUND_MODEL_SB16:
4575 model = "sb16";
4576 break;
4577 case VIR_DOMAIN_SOUND_MODEL_PCSPK: /* pc-speaker is handled separately */
4578 case VIR_DOMAIN_SOUND_MODEL_LAST:
4579 virReportError(VIR_ERR_INTERNAL_ERROR,
4580 _("sound card model '%s' is not supported by qemu"),
4581 virDomainSoundModelTypeToString(sound->model));
4582 goto error;
4585 virBufferAsprintf(&buf, "%s,id=%s", model, sound->info.alias);
4586 if (qemuBuildDeviceAddressStr(&buf, def, &sound->info, qemuCaps) < 0)
4587 goto error;
4589 if (virBufferCheckError(&buf) < 0)
4590 goto error;
4592 return virBufferContentAndReset(&buf);
4594 error:
4595 virBufferFreeAndReset(&buf);
4596 return NULL;
4600 static int
4601 qemuSoundCodecTypeToCaps(int type)
4603 switch (type) {
4604 case VIR_DOMAIN_SOUND_CODEC_TYPE_DUPLEX:
4605 return QEMU_CAPS_HDA_DUPLEX;
4606 case VIR_DOMAIN_SOUND_CODEC_TYPE_MICRO:
4607 return QEMU_CAPS_HDA_MICRO;
4608 case VIR_DOMAIN_SOUND_CODEC_TYPE_OUTPUT:
4609 return QEMU_CAPS_HDA_OUTPUT;
4610 default:
4611 return -1;
4616 static char *
4617 qemuBuildSoundCodecStr(virDomainSoundDefPtr sound,
4618 virDomainSoundCodecDefPtr codec,
4619 virQEMUCapsPtr qemuCaps)
4621 virBuffer buf = VIR_BUFFER_INITIALIZER;
4622 const char *stype;
4623 int type, flags;
4625 type = codec->type;
4626 stype = qemuSoundCodecTypeToString(type);
4627 flags = qemuSoundCodecTypeToCaps(type);
4629 if (flags == -1 || !virQEMUCapsGet(qemuCaps, flags)) {
4630 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4631 _("%s not supported in this QEMU binary"), stype);
4632 goto error;
4635 virBufferAsprintf(&buf, "%s,id=%s-codec%d,bus=%s.0,cad=%d",
4636 stype, sound->info.alias, codec->cad, sound->info.alias, codec->cad);
4638 return virBufferContentAndReset(&buf);
4640 error:
4641 virBufferFreeAndReset(&buf);
4642 return NULL;
4646 static int
4647 qemuBuildSoundCommandLine(virCommandPtr cmd,
4648 const virDomainDef *def,
4649 virQEMUCapsPtr qemuCaps)
4651 size_t i, j;
4653 for (i = 0; i < def->nsounds; i++) {
4654 virDomainSoundDefPtr sound = def->sounds[i];
4655 char *str = NULL;
4657 /* Sadly pcspk device doesn't use -device syntax. Fortunately
4658 * we don't need to set any PCI address on it, so we don't
4659 * mind too much */
4660 if (sound->model == VIR_DOMAIN_SOUND_MODEL_PCSPK) {
4661 virCommandAddArgList(cmd, "-soundhw", "pcspk", NULL);
4662 } else {
4663 if (qemuCommandAddExtDevice(cmd, &sound->info) < 0)
4664 return -1;
4666 virCommandAddArg(cmd, "-device");
4667 if (!(str = qemuBuildSoundDevStr(def, sound, qemuCaps)))
4668 return -1;
4670 virCommandAddArg(cmd, str);
4671 VIR_FREE(str);
4672 if (sound->model == VIR_DOMAIN_SOUND_MODEL_ICH6 ||
4673 sound->model == VIR_DOMAIN_SOUND_MODEL_ICH9) {
4674 char *codecstr = NULL;
4676 for (j = 0; j < sound->ncodecs; j++) {
4677 virCommandAddArg(cmd, "-device");
4678 if (!(codecstr =
4679 qemuBuildSoundCodecStr(sound, sound->codecs[j],
4680 qemuCaps))) {
4681 return -1;
4684 virCommandAddArg(cmd, codecstr);
4685 VIR_FREE(codecstr);
4687 if (j == 0) {
4688 virDomainSoundCodecDef codec = {
4689 VIR_DOMAIN_SOUND_CODEC_TYPE_DUPLEX,
4692 virCommandAddArg(cmd, "-device");
4693 if (!(codecstr =
4694 qemuBuildSoundCodecStr(sound, &codec,
4695 qemuCaps))) {
4696 return -1;
4699 virCommandAddArg(cmd, codecstr);
4700 VIR_FREE(codecstr);
4705 return 0;
4710 static char *
4711 qemuBuildDeviceVideoStr(const virDomainDef *def,
4712 virDomainVideoDefPtr video,
4713 virQEMUCapsPtr qemuCaps)
4715 virBuffer buf = VIR_BUFFER_INITIALIZER;
4716 const char *model;
4718 /* We try to chose the best model for primary video device by preferring
4719 * model with VGA compatibility mode. For some video devices on some
4720 * architectures there might not be such model so fallback to one
4721 * without VGA compatibility mode. */
4722 if (video->primary && qemuDomainSupportsVideoVga(video, qemuCaps))
4723 model = qemuDeviceVideoTypeToString(video->type);
4724 else
4725 model = qemuDeviceVideoSecondaryTypeToString(video->type);
4727 if (!model || STREQ(model, "")) {
4728 virReportError(VIR_ERR_INTERNAL_ERROR,
4729 _("invalid model for video type '%s'"),
4730 virDomainVideoTypeToString(video->type));
4731 goto error;
4734 if (STREQ(model, "virtio-gpu")) {
4735 if (qemuBuildVirtioDevStr(&buf, "virtio-gpu", qemuCaps,
4736 VIR_DOMAIN_DEVICE_VIDEO, video) < 0) {
4737 goto error;
4739 } else {
4740 virBufferAsprintf(&buf, "%s", model);
4743 virBufferAsprintf(&buf, ",id=%s", video->info.alias);
4745 if (video->accel && video->accel->accel3d == VIR_TRISTATE_SWITCH_ON) {
4746 virBufferAsprintf(&buf, ",virgl=%s",
4747 virTristateSwitchTypeToString(video->accel->accel3d));
4750 if (video->type == VIR_DOMAIN_VIDEO_TYPE_QXL) {
4751 if (video->ram) {
4752 /* QEMU accepts bytes for ram_size. */
4753 virBufferAsprintf(&buf, ",ram_size=%u", video->ram * 1024);
4756 if (video->vram) {
4757 /* QEMU accepts bytes for vram_size. */
4758 virBufferAsprintf(&buf, ",vram_size=%u", video->vram * 1024);
4761 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_QXL_VRAM64)) {
4762 /* QEMU accepts mebibytes for vram64_size_mb. */
4763 virBufferAsprintf(&buf, ",vram64_size_mb=%u", video->vram64 / 1024);
4766 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_QXL_VGAMEM)) {
4767 /* QEMU accepts mebibytes for vgamem_mb. */
4768 virBufferAsprintf(&buf, ",vgamem_mb=%u", video->vgamem / 1024);
4771 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_QXL_MAX_OUTPUTS)) {
4772 if (video->heads)
4773 virBufferAsprintf(&buf, ",max_outputs=%u", video->heads);
4775 } else if (video->type == VIR_DOMAIN_VIDEO_TYPE_VIRTIO) {
4776 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_GPU_MAX_OUTPUTS)) {
4777 if (video->heads)
4778 virBufferAsprintf(&buf, ",max_outputs=%u", video->heads);
4780 } else if (video->vram &&
4781 ((video->type == VIR_DOMAIN_VIDEO_TYPE_VGA &&
4782 virQEMUCapsGet(qemuCaps, QEMU_CAPS_VGA_VGAMEM)) ||
4783 (video->type == VIR_DOMAIN_VIDEO_TYPE_VMVGA &&
4784 virQEMUCapsGet(qemuCaps, QEMU_CAPS_VMWARE_SVGA_VGAMEM)))) {
4786 virBufferAsprintf(&buf, ",vgamem_mb=%u", video->vram / 1024);
4789 if (qemuBuildDeviceAddressStr(&buf, def, &video->info, qemuCaps) < 0)
4790 goto error;
4792 if (qemuBuildVirtioOptionsStr(&buf, video->virtio, qemuCaps) < 0)
4793 goto error;
4795 if (virBufferCheckError(&buf) < 0)
4796 goto error;
4798 return virBufferContentAndReset(&buf);
4800 error:
4801 virBufferFreeAndReset(&buf);
4802 return NULL;
4806 static int
4807 qemuBuildVgaVideoCommand(virCommandPtr cmd,
4808 virDomainVideoDefPtr video,
4809 virQEMUCapsPtr qemuCaps)
4811 const char *vgastr = qemuVideoTypeToString(video->type);
4812 if (!vgastr || STREQ(vgastr, "")) {
4813 virReportError(VIR_ERR_INTERNAL_ERROR,
4814 _("invalid model for video type '%s'"),
4815 virDomainVideoTypeToString(video->type));
4816 return -1;
4819 virCommandAddArgList(cmd, "-vga", vgastr, NULL);
4821 /* If we cannot use --device option to specify the video device
4822 * in QEMU we will fallback to the old --vga option. To get the
4823 * correct device name for the --vga option the 'qemuVideo' is
4824 * used, but to set some device attributes we need to use the
4825 * --global option and for that we need to specify the device
4826 * name the same as for --device option and for that we need to
4827 * use 'qemuDeviceVideo'.
4829 * See 'Graphics Devices' section in docs/qdev-device-use.txt in
4830 * QEMU repository.
4832 const char *dev = qemuDeviceVideoTypeToString(video->type);
4834 if (video->type == VIR_DOMAIN_VIDEO_TYPE_QXL &&
4835 (video->vram || video->ram)) {
4836 unsigned int ram = video->ram;
4837 unsigned int vram = video->vram;
4838 unsigned int vram64 = video->vram64;
4839 unsigned int vgamem = video->vgamem;
4840 unsigned int heads = video->heads;
4842 if (ram) {
4843 virCommandAddArg(cmd, "-global");
4844 virCommandAddArgFormat(cmd, "%s.ram_size=%u",
4845 dev, ram * 1024);
4847 if (vram) {
4848 virCommandAddArg(cmd, "-global");
4849 virCommandAddArgFormat(cmd, "%s.vram_size=%u",
4850 dev, vram * 1024);
4852 if (vram64 &&
4853 virQEMUCapsGet(qemuCaps, QEMU_CAPS_QXL_VRAM64)) {
4854 virCommandAddArg(cmd, "-global");
4855 virCommandAddArgFormat(cmd, "%s.vram64_size_mb=%u",
4856 dev, vram64 / 1024);
4858 if (vgamem &&
4859 virQEMUCapsGet(qemuCaps, QEMU_CAPS_QXL_VGAMEM)) {
4860 virCommandAddArg(cmd, "-global");
4861 virCommandAddArgFormat(cmd, "%s.vgamem_mb=%u",
4862 dev, vgamem / 1024);
4864 if (heads &&
4865 virQEMUCapsGet(qemuCaps, QEMU_CAPS_QXL_MAX_OUTPUTS)) {
4866 virCommandAddArg(cmd, "-global");
4867 virCommandAddArgFormat(cmd, "%s.max_outputs=%u",
4868 dev, heads);
4872 if (video->vram &&
4873 ((video->type == VIR_DOMAIN_VIDEO_TYPE_VGA &&
4874 virQEMUCapsGet(qemuCaps, QEMU_CAPS_VGA_VGAMEM)) ||
4875 (video->type == VIR_DOMAIN_VIDEO_TYPE_VMVGA &&
4876 virQEMUCapsGet(qemuCaps, QEMU_CAPS_VMWARE_SVGA_VGAMEM)))) {
4877 unsigned int vram = video->vram;
4879 virCommandAddArg(cmd, "-global");
4880 virCommandAddArgFormat(cmd, "%s.vgamem_mb=%u",
4881 dev, vram / 1024);
4884 return 0;
4888 static int
4889 qemuBuildVideoCommandLine(virCommandPtr cmd,
4890 const virDomainDef *def,
4891 virQEMUCapsPtr qemuCaps)
4893 size_t i;
4895 for (i = 0; i < def->nvideos; i++) {
4896 char *str = NULL;
4897 virDomainVideoDefPtr video = def->videos[i];
4899 if (video->type == VIR_DOMAIN_VIDEO_TYPE_NONE)
4900 continue;
4902 if (video->primary) {
4903 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIDEO_PRIMARY)) {
4905 if (qemuCommandAddExtDevice(cmd,
4906 &def->videos[i]->info) < 0)
4907 return -1;
4909 virCommandAddArg(cmd, "-device");
4911 if (!(str = qemuBuildDeviceVideoStr(def, video, qemuCaps)))
4912 return -1;
4914 virCommandAddArg(cmd, str);
4915 VIR_FREE(str);
4916 } else {
4917 if (qemuBuildVgaVideoCommand(cmd, video, qemuCaps) < 0)
4918 return -1;
4920 } else {
4921 if (qemuCommandAddExtDevice(cmd, &def->videos[i]->info) < 0)
4922 return -1;
4924 virCommandAddArg(cmd, "-device");
4926 if (!(str = qemuBuildDeviceVideoStr(def, video, qemuCaps)))
4927 return -1;
4929 virCommandAddArg(cmd, str);
4930 VIR_FREE(str);
4934 return 0;
4939 qemuOpenPCIConfig(virDomainHostdevDefPtr dev)
4941 virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
4942 char *path = NULL;
4943 int configfd = -1;
4945 if (virAsprintf(&path, "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/config",
4946 pcisrc->addr.domain, pcisrc->addr.bus,
4947 pcisrc->addr.slot, pcisrc->addr.function) < 0)
4948 return -1;
4950 configfd = open(path, O_RDWR, 0);
4952 if (configfd < 0)
4953 virReportSystemError(errno, _("Failed opening %s"), path);
4955 VIR_FREE(path);
4957 return configfd;
4960 char *
4961 qemuBuildPCIHostdevDevStr(const virDomainDef *def,
4962 virDomainHostdevDefPtr dev,
4963 unsigned int bootIndex, /* used iff dev->info->bootIndex == 0 */
4964 const char *configfd,
4965 virQEMUCapsPtr qemuCaps)
4967 virBuffer buf = VIR_BUFFER_INITIALIZER;
4968 virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
4969 int backend = pcisrc->backend;
4971 /* caller has to assign proper passthrough backend type */
4972 switch ((virDomainHostdevSubsysPCIBackendType)backend) {
4973 case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_KVM:
4974 virBufferAddLit(&buf, "pci-assign");
4975 if (configfd && *configfd)
4976 virBufferAsprintf(&buf, ",configfd=%s", configfd);
4977 break;
4979 case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO:
4980 virBufferAddLit(&buf, "vfio-pci");
4981 break;
4983 case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_DEFAULT:
4984 case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN:
4985 case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_TYPE_LAST:
4986 virReportError(VIR_ERR_INTERNAL_ERROR,
4987 _("invalid PCI passthrough type '%s'"),
4988 virDomainHostdevSubsysPCIBackendTypeToString(backend));
4989 goto error;
4992 virBufferAddLit(&buf, ",host=");
4993 if (pcisrc->addr.domain)
4994 virBufferAsprintf(&buf, "%.4x:", pcisrc->addr.domain);
4995 virBufferAsprintf(&buf, "%.2x:%.2x.%.1x",
4996 pcisrc->addr.bus, pcisrc->addr.slot,
4997 pcisrc->addr.function);
4998 virBufferAsprintf(&buf, ",id=%s", dev->info->alias);
4999 if (dev->info->bootIndex)
5000 bootIndex = dev->info->bootIndex;
5001 if (bootIndex)
5002 virBufferAsprintf(&buf, ",bootindex=%u", bootIndex);
5003 if (qemuBuildDeviceAddressStr(&buf, def, dev->info, qemuCaps) < 0)
5004 goto error;
5005 if (qemuBuildRomStr(&buf, dev->info) < 0)
5006 goto error;
5008 if (virBufferCheckError(&buf) < 0)
5009 goto error;
5011 return virBufferContentAndReset(&buf);
5013 error:
5014 virBufferFreeAndReset(&buf);
5015 return NULL;
5019 char *
5020 qemuBuildUSBHostdevDevStr(const virDomainDef *def,
5021 virDomainHostdevDefPtr dev,
5022 virQEMUCapsPtr qemuCaps)
5024 virBuffer buf = VIR_BUFFER_INITIALIZER;
5025 virDomainHostdevSubsysUSBPtr usbsrc = &dev->source.subsys.u.usb;
5027 if (!dev->missing && !usbsrc->bus && !usbsrc->device) {
5028 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
5029 _("USB host device is missing bus/device information"));
5030 return NULL;
5033 virBufferAddLit(&buf, "usb-host");
5034 if (!dev->missing) {
5035 virBufferAsprintf(&buf, ",hostbus=%d,hostaddr=%d",
5036 usbsrc->bus, usbsrc->device);
5038 virBufferAsprintf(&buf, ",id=%s", dev->info->alias);
5039 if (dev->info->bootIndex)
5040 virBufferAsprintf(&buf, ",bootindex=%u", dev->info->bootIndex);
5042 if (qemuBuildDeviceAddressStr(&buf, def, dev->info, qemuCaps) < 0)
5043 goto error;
5045 if (virBufferCheckError(&buf) < 0)
5046 goto error;
5048 return virBufferContentAndReset(&buf);
5050 error:
5051 virBufferFreeAndReset(&buf);
5052 return NULL;
5056 static char *
5057 qemuBuildHubDevStr(const virDomainDef *def,
5058 virDomainHubDefPtr dev,
5059 virQEMUCapsPtr qemuCaps)
5061 virBuffer buf = VIR_BUFFER_INITIALIZER;
5063 if (dev->type != VIR_DOMAIN_HUB_TYPE_USB) {
5064 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5065 _("hub type %s not supported"),
5066 virDomainHubTypeToString(dev->type));
5067 goto error;
5070 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_USB_HUB)) {
5071 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5072 _("usb-hub not supported by QEMU binary"));
5073 goto error;
5076 virBufferAddLit(&buf, "usb-hub");
5077 virBufferAsprintf(&buf, ",id=%s", dev->info.alias);
5078 if (qemuBuildDeviceAddressStr(&buf, def, &dev->info, qemuCaps) < 0)
5079 goto error;
5081 if (virBufferCheckError(&buf) < 0)
5082 goto error;
5084 return virBufferContentAndReset(&buf);
5086 error:
5087 virBufferFreeAndReset(&buf);
5088 return NULL;
5092 static int
5093 qemuBuildHubCommandLine(virCommandPtr cmd,
5094 const virDomainDef *def,
5095 virQEMUCapsPtr qemuCaps)
5097 size_t i;
5099 for (i = 0; i < def->nhubs; i++) {
5100 virDomainHubDefPtr hub = def->hubs[i];
5101 char *optstr;
5103 virCommandAddArg(cmd, "-device");
5104 if (!(optstr = qemuBuildHubDevStr(def, hub, qemuCaps)))
5105 return -1;
5106 virCommandAddArg(cmd, optstr);
5107 VIR_FREE(optstr);
5110 return 0;
5114 static char *
5115 qemuBuildSCSIHostHostdevDrvStr(virDomainHostdevDefPtr dev)
5117 virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
5118 virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
5120 return virSCSIDeviceGetSgName(NULL,
5121 scsihostsrc->adapter,
5122 scsihostsrc->bus,
5123 scsihostsrc->target,
5124 scsihostsrc->unit);
5127 static char *
5128 qemuBuildSCSIiSCSIHostdevDrvStr(virDomainHostdevDefPtr dev,
5129 virQEMUCapsPtr qemuCaps)
5131 char *ret = NULL;
5132 virBuffer buf = VIR_BUFFER_INITIALIZER;
5133 char *netsource = NULL;
5134 virJSONValuePtr srcprops = NULL;
5135 virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
5136 virDomainHostdevSubsysSCSIiSCSIPtr iscsisrc = &scsisrc->u.iscsi;
5137 qemuDomainStorageSourcePrivatePtr srcPriv =
5138 QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(iscsisrc->src);
5140 if (qemuDiskSourceNeedsProps(iscsisrc->src, qemuCaps)) {
5141 if (!(srcprops = qemuDiskSourceGetProps(iscsisrc->src)))
5142 goto cleanup;
5143 if (!(netsource = virQEMUBuildDriveCommandlineFromJSON(srcprops)))
5144 goto cleanup;
5145 virBufferAsprintf(&buf, "%s,if=none,format=raw", netsource);
5146 } else {
5147 /* Rather than pull what we think we want - use the network disk code */
5148 if (!(netsource = qemuBuildNetworkDriveStr(iscsisrc->src, srcPriv ?
5149 srcPriv->secinfo : NULL)))
5150 goto cleanup;
5151 virBufferAddLit(&buf, "file=");
5152 virQEMUBuildBufferEscapeComma(&buf, netsource);
5153 virBufferAddLit(&buf, ",if=none,format=raw");
5156 if (virBufferCheckError(&buf) < 0)
5157 goto cleanup;
5159 ret = virBufferContentAndReset(&buf);
5161 cleanup:
5162 VIR_FREE(netsource);
5163 virJSONValueFree(srcprops);
5164 virBufferFreeAndReset(&buf);
5165 return ret;
5168 char *
5169 qemuBuildSCSIVHostHostdevDevStr(const virDomainDef *def,
5170 virDomainHostdevDefPtr dev,
5171 virQEMUCapsPtr qemuCaps,
5172 char *vhostfdName)
5174 virBuffer buf = VIR_BUFFER_INITIALIZER;
5175 virDomainHostdevSubsysSCSIVHostPtr hostsrc = &dev->source.subsys.u.scsi_host;
5177 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VHOST_SCSI)) {
5178 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5179 _("This QEMU doesn't support vhost-scsi devices"));
5180 goto cleanup;
5183 if (qemuBuildVirtioDevStr(&buf, "vhost-scsi", qemuCaps,
5184 VIR_DOMAIN_DEVICE_HOSTDEV, dev) < 0) {
5185 goto cleanup;
5188 virBufferAsprintf(&buf, ",wwpn=%s,vhostfd=%s,id=%s",
5189 hostsrc->wwpn,
5190 vhostfdName,
5191 dev->info->alias);
5193 if (qemuBuildDeviceAddressStr(&buf, def, dev->info, qemuCaps) < 0)
5194 goto cleanup;
5196 if (virBufferCheckError(&buf) < 0)
5197 goto cleanup;
5199 return virBufferContentAndReset(&buf);
5201 cleanup:
5202 virBufferFreeAndReset(&buf);
5203 return NULL;
5206 char *
5207 qemuBuildSCSIHostdevDrvStr(virDomainHostdevDefPtr dev,
5208 virQEMUCapsPtr qemuCaps)
5210 virBuffer buf = VIR_BUFFER_INITIALIZER;
5211 char *source = NULL;
5212 char *drivealias = NULL;
5213 virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
5215 if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
5216 if (!(source = qemuBuildSCSIiSCSIHostdevDrvStr(dev, qemuCaps)))
5217 goto error;
5218 virBufferAdd(&buf, source, -1);
5219 } else {
5220 if (!(source = qemuBuildSCSIHostHostdevDrvStr(dev)))
5221 goto error;
5222 virBufferAsprintf(&buf, "file=/dev/%s,if=none,format=raw", source);
5224 VIR_FREE(source);
5226 if (!(drivealias = qemuAliasFromHostdev(dev)))
5227 goto error;
5228 virBufferAsprintf(&buf, ",id=%s", drivealias);
5229 VIR_FREE(drivealias);
5231 if (dev->readonly)
5232 virBufferAddLit(&buf, ",readonly=on");
5234 if (virBufferCheckError(&buf) < 0)
5235 goto error;
5237 return virBufferContentAndReset(&buf);
5238 error:
5239 virBufferFreeAndReset(&buf);
5240 return NULL;
5243 char *
5244 qemuBuildSCSIHostdevDevStr(const virDomainDef *def,
5245 virDomainHostdevDefPtr dev)
5247 virBuffer buf = VIR_BUFFER_INITIALIZER;
5248 int model = -1;
5249 char *driveAlias;
5250 const char *contAlias;
5252 model = qemuDomainFindSCSIControllerModel(def, dev->info);
5253 if (model < 0)
5254 goto error;
5256 if (model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC) {
5257 if (dev->info->addr.drive.target != 0) {
5258 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5259 _("target must be 0 for scsi host device "
5260 "if its controller model is 'lsilogic'"));
5261 goto error;
5264 if (dev->info->addr.drive.unit > 7) {
5265 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5266 _("unit must be not more than 7 for scsi host "
5267 "device if its controller model is 'lsilogic'"));
5268 goto error;
5272 virBufferAddLit(&buf, "scsi-generic");
5274 if (!(contAlias = virDomainControllerAliasFind(def, VIR_DOMAIN_CONTROLLER_TYPE_SCSI,
5275 dev->info->addr.drive.controller)))
5276 goto error;
5278 if (model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC) {
5279 virBufferAsprintf(&buf, ",bus=%s.%d,scsi-id=%d",
5280 contAlias,
5281 dev->info->addr.drive.bus,
5282 dev->info->addr.drive.unit);
5283 } else {
5284 virBufferAsprintf(&buf, ",bus=%s.0,channel=%d,scsi-id=%d,lun=%d",
5285 contAlias,
5286 dev->info->addr.drive.bus,
5287 dev->info->addr.drive.target,
5288 dev->info->addr.drive.unit);
5291 if (!(driveAlias = qemuAliasFromHostdev(dev)))
5292 goto error;
5293 virBufferAsprintf(&buf, ",drive=%s,id=%s", driveAlias, dev->info->alias);
5294 VIR_FREE(driveAlias);
5296 if (dev->info->bootIndex)
5297 virBufferAsprintf(&buf, ",bootindex=%u", dev->info->bootIndex);
5299 if (virBufferCheckError(&buf) < 0)
5300 goto error;
5302 return virBufferContentAndReset(&buf);
5303 error:
5304 virBufferFreeAndReset(&buf);
5305 return NULL;
5308 static int
5309 qemuBuildChrChardevFileStr(virLogManagerPtr logManager,
5310 virCommandPtr cmd,
5311 const virDomainDef *def,
5312 virBufferPtr buf,
5313 const char *filearg, const char *fileval,
5314 const char *appendarg, int appendval)
5316 if (logManager) {
5317 char *fdset, *fdpath;
5318 int flags = 0;
5319 int logfd;
5321 if (appendval == VIR_TRISTATE_SWITCH_ABSENT ||
5322 appendval == VIR_TRISTATE_SWITCH_OFF)
5323 flags |= VIR_LOG_MANAGER_PROTOCOL_DOMAIN_OPEN_LOG_FILE_TRUNCATE;
5325 if ((logfd = virLogManagerDomainOpenLogFile(logManager,
5326 "qemu",
5327 def->uuid,
5328 def->name,
5329 fileval,
5330 flags,
5331 NULL, NULL)) < 0)
5332 return -1;
5334 virCommandPassFD(cmd, logfd, VIR_COMMAND_PASS_FD_CLOSE_PARENT);
5335 if (!(fdset = qemuVirCommandGetFDSet(cmd, logfd)))
5336 return -1;
5338 virCommandAddArg(cmd, "-add-fd");
5339 virCommandAddArg(cmd, fdset);
5340 VIR_FREE(fdset);
5342 if (!(fdpath = qemuVirCommandGetDevSet(cmd, logfd)))
5343 return -1;
5345 virBufferAsprintf(buf, ",%s=%s,%s=on", filearg, fdpath, appendarg);
5346 VIR_FREE(fdpath);
5347 } else {
5348 virBufferAsprintf(buf, ",%s=", filearg);
5349 virQEMUBuildBufferEscapeComma(buf, fileval);
5350 if (appendval != VIR_TRISTATE_SWITCH_ABSENT) {
5351 virBufferAsprintf(buf, ",%s=%s", appendarg,
5352 virTristateSwitchTypeToString(appendval));
5356 return 0;
5360 static void
5361 qemuBuildChrChardevReconnectStr(virBufferPtr buf,
5362 const virDomainChrSourceReconnectDef *def)
5364 if (def->enabled == VIR_TRISTATE_BOOL_YES) {
5365 virBufferAsprintf(buf, ",reconnect=%u", def->timeout);
5366 } else if (def->enabled == VIR_TRISTATE_BOOL_NO) {
5367 virBufferAddLit(buf, ",reconnect=0");
5373 qemuOpenChrChardevUNIXSocket(const virDomainChrSourceDef *dev)
5375 struct sockaddr_un addr;
5376 socklen_t addrlen = sizeof(addr);
5377 int fd;
5379 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
5380 virReportSystemError(errno, "%s",
5381 _("Unable to create UNIX socket"));
5382 goto error;
5385 memset(&addr, 0, sizeof(addr));
5386 addr.sun_family = AF_UNIX;
5387 if (virStrcpyStatic(addr.sun_path, dev->data.nix.path) < 0) {
5388 virReportError(VIR_ERR_INTERNAL_ERROR,
5389 _("UNIX socket path '%s' too long"),
5390 dev->data.nix.path);
5391 goto error;
5394 if (unlink(dev->data.nix.path) < 0 && errno != ENOENT) {
5395 virReportSystemError(errno,
5396 _("Unable to unlink %s"),
5397 dev->data.nix.path);
5398 goto error;
5401 if (bind(fd, (struct sockaddr *)&addr, addrlen) < 0) {
5402 virReportSystemError(errno,
5403 _("Unable to bind to UNIX socket path '%s'"),
5404 dev->data.nix.path);
5405 goto error;
5408 if (listen(fd, 1) < 0) {
5409 virReportSystemError(errno,
5410 _("Unable to listen to UNIX socket path '%s'"),
5411 dev->data.nix.path);
5412 goto error;
5415 /* We run QEMU with umask 0002. Compensate for the umask
5416 * libvirtd might be running under to get the same permission
5417 * QEMU would have. */
5418 if (virFileUpdatePerm(dev->data.nix.path, 0002, 0664) < 0)
5419 goto error;
5421 return fd;
5423 error:
5424 VIR_FORCE_CLOSE(fd);
5425 return -1;
5429 enum {
5430 QEMU_BUILD_CHARDEV_TCP_NOWAIT = (1 << 0),
5431 QEMU_BUILD_CHARDEV_FILE_LOGD = (1 << 1),
5432 QEMU_BUILD_CHARDEV_UNIX_FD_PASS = (1 << 2),
5435 /* This function outputs a -chardev command line option which describes only the
5436 * host side of the character device */
5437 static char *
5438 qemuBuildChrChardevStr(virLogManagerPtr logManager,
5439 virSecurityManagerPtr secManager,
5440 virCommandPtr cmd,
5441 virQEMUDriverConfigPtr cfg,
5442 const virDomainDef *def,
5443 const virDomainChrSourceDef *dev,
5444 const char *alias,
5445 virQEMUCapsPtr qemuCaps,
5446 unsigned int flags)
5448 qemuDomainChrSourcePrivatePtr chrSourcePriv = QEMU_DOMAIN_CHR_SOURCE_PRIVATE(dev);
5449 virBuffer buf = VIR_BUFFER_INITIALIZER;
5450 bool telnet;
5451 char *charAlias = NULL;
5452 char *ret = NULL;
5454 if (!(charAlias = qemuAliasChardevFromDevAlias(alias)))
5455 goto cleanup;
5457 switch (dev->type) {
5458 case VIR_DOMAIN_CHR_TYPE_NULL:
5459 virBufferAsprintf(&buf, "null,id=%s", charAlias);
5460 break;
5462 case VIR_DOMAIN_CHR_TYPE_VC:
5463 virBufferAsprintf(&buf, "vc,id=%s", charAlias);
5464 break;
5466 case VIR_DOMAIN_CHR_TYPE_PTY:
5467 virBufferAsprintf(&buf, "pty,id=%s", charAlias);
5468 break;
5470 case VIR_DOMAIN_CHR_TYPE_DEV:
5471 virBufferAsprintf(&buf, "%s,id=%s,path=",
5472 STRPREFIX(alias, "parallel") ? "parport" : "tty",
5473 charAlias);
5474 virQEMUBuildBufferEscapeComma(&buf, dev->data.file.path);
5475 break;
5477 case VIR_DOMAIN_CHR_TYPE_FILE:
5478 virBufferAsprintf(&buf, "file,id=%s", charAlias);
5480 if (dev->data.file.append != VIR_TRISTATE_SWITCH_ABSENT &&
5481 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_CHARDEV_FILE_APPEND)) {
5482 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5483 _("append not supported in this QEMU binary"));
5484 goto cleanup;
5486 if (qemuBuildChrChardevFileStr(flags & QEMU_BUILD_CHARDEV_FILE_LOGD ?
5487 logManager : NULL,
5488 cmd, def, &buf,
5489 "path", dev->data.file.path,
5490 "append", dev->data.file.append) < 0)
5491 goto cleanup;
5492 break;
5494 case VIR_DOMAIN_CHR_TYPE_PIPE:
5495 virBufferAsprintf(&buf, "pipe,id=%s,path=", charAlias);
5496 virQEMUBuildBufferEscapeComma(&buf, dev->data.file.path);
5497 break;
5499 case VIR_DOMAIN_CHR_TYPE_STDIO:
5500 virBufferAsprintf(&buf, "stdio,id=%s", charAlias);
5501 break;
5503 case VIR_DOMAIN_CHR_TYPE_UDP: {
5504 const char *connectHost = dev->data.udp.connectHost;
5505 const char *bindHost = dev->data.udp.bindHost;
5506 const char *bindService = dev->data.udp.bindService;
5508 if (connectHost == NULL)
5509 connectHost = "";
5510 if (bindHost == NULL)
5511 bindHost = "";
5512 if (bindService == NULL)
5513 bindService = "0";
5515 virBufferAsprintf(&buf,
5516 "udp,id=%s,host=%s,port=%s,localaddr=%s,"
5517 "localport=%s",
5518 charAlias,
5519 connectHost,
5520 dev->data.udp.connectService,
5521 bindHost, bindService);
5522 break;
5524 case VIR_DOMAIN_CHR_TYPE_TCP:
5525 telnet = dev->data.tcp.protocol == VIR_DOMAIN_CHR_TCP_PROTOCOL_TELNET;
5526 virBufferAsprintf(&buf,
5527 "socket,id=%s,host=%s,port=%s%s",
5528 charAlias,
5529 dev->data.tcp.host,
5530 dev->data.tcp.service,
5531 telnet ? ",telnet" : "");
5533 if (dev->data.tcp.listen) {
5534 virBufferAddLit(&buf, ",server");
5535 if (flags & QEMU_BUILD_CHARDEV_TCP_NOWAIT)
5536 virBufferAddLit(&buf, ",nowait");
5539 qemuBuildChrChardevReconnectStr(&buf, &dev->data.tcp.reconnect);
5541 if (dev->data.tcp.haveTLS == VIR_TRISTATE_BOOL_YES) {
5542 char *objalias = NULL;
5543 const char *tlsCertEncSecAlias = NULL;
5545 /* Add the secret object first if necessary. The
5546 * secinfo is added only to a TCP serial device during
5547 * qemuDomainSecretChardevPrepare. Subsequently called
5548 * functions can just check the config fields */
5549 if (chrSourcePriv && chrSourcePriv->secinfo) {
5550 if (qemuBuildObjectSecretCommandLine(cmd,
5551 chrSourcePriv->secinfo) < 0)
5552 goto cleanup;
5554 tlsCertEncSecAlias = chrSourcePriv->secinfo->s.aes.alias;
5557 if (!(objalias = qemuAliasTLSObjFromSrcAlias(charAlias)))
5558 goto cleanup;
5560 if (qemuBuildTLSx509CommandLine(cmd, cfg->chardevTLSx509certdir,
5561 dev->data.tcp.listen,
5562 cfg->chardevTLSx509verify,
5563 tlsCertEncSecAlias,
5564 objalias, qemuCaps) < 0) {
5565 VIR_FREE(objalias);
5566 goto cleanup;
5569 virBufferAsprintf(&buf, ",tls-creds=%s", objalias);
5570 VIR_FREE(objalias);
5572 break;
5574 case VIR_DOMAIN_CHR_TYPE_UNIX:
5575 virBufferAsprintf(&buf, "socket,id=%s", charAlias);
5576 if (dev->data.nix.listen &&
5577 (flags & QEMU_BUILD_CHARDEV_UNIX_FD_PASS) &&
5578 virQEMUCapsGet(qemuCaps, QEMU_CAPS_CHARDEV_FD_PASS)) {
5579 if (qemuSecuritySetSocketLabel(secManager, (virDomainDefPtr)def) < 0)
5580 goto cleanup;
5581 int fd = qemuOpenChrChardevUNIXSocket(dev);
5582 if (qemuSecurityClearSocketLabel(secManager, (virDomainDefPtr)def) < 0) {
5583 VIR_FORCE_CLOSE(fd);
5584 goto cleanup;
5586 if (fd < 0)
5587 goto cleanup;
5589 virBufferAsprintf(&buf, ",fd=%d", fd);
5591 virCommandPassFD(cmd, fd, VIR_COMMAND_PASS_FD_CLOSE_PARENT);
5592 } else {
5593 virBufferAddLit(&buf, ",path=");
5594 virQEMUBuildBufferEscapeComma(&buf, dev->data.nix.path);
5596 if (dev->data.nix.listen) {
5597 virBufferAddLit(&buf, ",server");
5598 if (flags & QEMU_BUILD_CHARDEV_TCP_NOWAIT)
5599 virBufferAddLit(&buf, ",nowait");
5602 qemuBuildChrChardevReconnectStr(&buf, &dev->data.nix.reconnect);
5603 break;
5605 case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
5606 virBufferAsprintf(&buf, "spicevmc,id=%s,name=%s", charAlias,
5607 virDomainChrSpicevmcTypeToString(dev->data.spicevmc));
5608 break;
5610 case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
5611 virBufferAsprintf(&buf, "spiceport,id=%s,name=%s", charAlias,
5612 dev->data.spiceport.channel);
5613 break;
5615 default:
5616 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5617 _("unsupported chardev '%s'"),
5618 virDomainChrTypeToString(dev->type));
5619 goto cleanup;
5622 if (dev->logfile) {
5623 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_CHARDEV_LOGFILE)) {
5624 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5625 _("logfile not supported in this QEMU binary"));
5626 goto cleanup;
5628 if (qemuBuildChrChardevFileStr(logManager, cmd, def, &buf,
5629 "logfile", dev->logfile,
5630 "logappend", dev->logappend) < 0)
5631 goto cleanup;
5634 if (virBufferCheckError(&buf) < 0)
5635 goto cleanup;
5637 ret = virBufferContentAndReset(&buf);
5638 cleanup:
5639 VIR_FREE(charAlias);
5640 virBufferFreeAndReset(&buf);
5641 return ret;
5644 char *
5645 qemuBuildHostdevMediatedDevStr(const virDomainDef *def,
5646 virDomainHostdevDefPtr dev,
5647 virQEMUCapsPtr qemuCaps)
5649 virBuffer buf = VIR_BUFFER_INITIALIZER;
5650 virDomainHostdevSubsysMediatedDevPtr mdevsrc = &dev->source.subsys.u.mdev;
5651 char *ret = NULL;
5652 char *mdevPath = NULL;
5653 const char *dev_str = NULL;
5655 if (!(mdevPath = virMediatedDeviceGetSysfsPath(mdevsrc->uuidstr)))
5656 goto cleanup;
5658 dev_str = virMediatedDeviceModelTypeToString(mdevsrc->model);
5660 if (!dev_str)
5661 goto cleanup;
5663 virBufferAdd(&buf, dev_str, -1);
5664 virBufferAsprintf(&buf, ",id=%s,sysfsdev=%s", dev->info->alias, mdevPath);
5666 if (mdevsrc->display != VIR_TRISTATE_SWITCH_ABSENT)
5667 virBufferAsprintf(&buf, ",display=%s",
5668 virTristateSwitchTypeToString(mdevsrc->display));
5670 if (qemuBuildDeviceAddressStr(&buf, def, dev->info, qemuCaps) < 0)
5671 goto cleanup;
5673 if (virBufferCheckError(&buf) < 0)
5674 goto cleanup;
5676 ret = virBufferContentAndReset(&buf);
5678 cleanup:
5679 VIR_FREE(mdevPath);
5680 virBufferFreeAndReset(&buf);
5681 return ret;
5684 static int
5685 qemuBuildHostdevCommandLine(virCommandPtr cmd,
5686 const virDomainDef *def,
5687 virQEMUCapsPtr qemuCaps,
5688 unsigned int *bootHostdevNet)
5690 size_t i;
5692 for (i = 0; i < def->nhostdevs; i++) {
5693 virDomainHostdevDefPtr hostdev = def->hostdevs[i];
5694 virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
5695 char *devstr;
5697 if (hostdev->info->bootIndex) {
5698 if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
5699 (subsys->type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
5700 subsys->type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB &&
5701 subsys->type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI)) {
5702 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5703 _("booting from assigned devices is only "
5704 "supported for PCI, USB and SCSI devices"));
5705 return -1;
5709 /* USB */
5710 if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
5711 subsys->type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
5713 virCommandAddArg(cmd, "-device");
5714 if (!(devstr =
5715 qemuBuildUSBHostdevDevStr(def, hostdev, qemuCaps)))
5716 return -1;
5717 virCommandAddArg(cmd, devstr);
5718 VIR_FREE(devstr);
5721 /* PCI */
5722 if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
5723 subsys->type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI) {
5724 int backend = subsys->u.pci.backend;
5726 if (backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
5727 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VFIO_PCI)) {
5728 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5729 _("VFIO PCI device assignment is not "
5730 "supported by this version of qemu"));
5731 return -1;
5735 char *configfd_name = NULL;
5736 unsigned int bootIndex = hostdev->info->bootIndex;
5738 /* bootNet will be non-0 if boot order was set and no other
5739 * net devices were encountered
5741 if (hostdev->parentnet && bootIndex == 0) {
5742 bootIndex = *bootHostdevNet;
5743 *bootHostdevNet = 0;
5745 if (backend != VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
5746 int configfd = qemuOpenPCIConfig(hostdev);
5748 if (configfd >= 0) {
5749 if (virAsprintf(&configfd_name, "%d", configfd) < 0) {
5750 VIR_FORCE_CLOSE(configfd);
5751 return -1;
5754 virCommandPassFD(cmd, configfd,
5755 VIR_COMMAND_PASS_FD_CLOSE_PARENT);
5759 if (qemuCommandAddExtDevice(cmd, hostdev->info) < 0)
5760 return -1;
5762 virCommandAddArg(cmd, "-device");
5763 devstr = qemuBuildPCIHostdevDevStr(def, hostdev, bootIndex,
5764 configfd_name, qemuCaps);
5765 VIR_FREE(configfd_name);
5766 if (!devstr)
5767 return -1;
5768 virCommandAddArg(cmd, devstr);
5769 VIR_FREE(devstr);
5772 /* SCSI */
5773 if (virHostdevIsSCSIDevice(hostdev)) {
5774 virDomainHostdevSubsysSCSIPtr scsisrc =
5775 &hostdev->source.subsys.u.scsi;
5776 char *drvstr;
5778 if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
5779 virDomainHostdevSubsysSCSIiSCSIPtr iscsisrc =
5780 &scsisrc->u.iscsi;
5781 qemuDomainStorageSourcePrivatePtr srcPriv =
5782 QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(iscsisrc->src);
5784 if (qemuBuildDiskSecinfoCommandLine(cmd, srcPriv ?
5785 srcPriv->secinfo :
5786 NULL) < 0)
5787 return -1;
5790 virCommandAddArg(cmd, "-drive");
5791 if (!(drvstr = qemuBuildSCSIHostdevDrvStr(hostdev, qemuCaps)))
5792 return -1;
5793 virCommandAddArg(cmd, drvstr);
5794 VIR_FREE(drvstr);
5796 virCommandAddArg(cmd, "-device");
5797 if (!(devstr = qemuBuildSCSIHostdevDevStr(def, hostdev)))
5798 return -1;
5799 virCommandAddArg(cmd, devstr);
5800 VIR_FREE(devstr);
5803 /* SCSI_host */
5804 if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
5805 subsys->type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI_HOST) {
5806 if (hostdev->source.subsys.u.scsi_host.protocol ==
5807 VIR_DOMAIN_HOSTDEV_SUBSYS_SCSI_HOST_PROTOCOL_TYPE_VHOST) {
5808 char *vhostfdName = NULL;
5809 int vhostfd = -1;
5811 if (virSCSIVHostOpenVhostSCSI(&vhostfd) < 0)
5812 return -1;
5814 if (virAsprintf(&vhostfdName, "%d", vhostfd) < 0) {
5815 VIR_FORCE_CLOSE(vhostfd);
5816 return -1;
5819 virCommandPassFD(cmd, vhostfd,
5820 VIR_COMMAND_PASS_FD_CLOSE_PARENT);
5822 virCommandAddArg(cmd, "-device");
5823 if (!(devstr = qemuBuildSCSIVHostHostdevDevStr(def,
5824 hostdev,
5825 qemuCaps,
5826 vhostfdName))) {
5827 VIR_FREE(vhostfdName);
5828 return -1;
5830 virCommandAddArg(cmd, devstr);
5832 VIR_FREE(vhostfdName);
5833 VIR_FREE(devstr);
5837 /* MDEV */
5838 if (virHostdevIsMdevDevice(hostdev)) {
5839 virDomainHostdevSubsysMediatedDevPtr mdevsrc = &subsys->u.mdev;
5841 switch ((virMediatedDeviceModelType) mdevsrc->model) {
5842 case VIR_MDEV_MODEL_TYPE_VFIO_PCI:
5843 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VFIO_PCI)) {
5844 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5845 _("VFIO PCI device assignment is not "
5846 "supported by this version of QEMU"));
5847 return -1;
5850 break;
5851 case VIR_MDEV_MODEL_TYPE_VFIO_CCW:
5852 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VFIO_CCW)) {
5853 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5854 _("VFIO CCW device assignment is not "
5855 "supported by this version of QEMU"));
5856 return -1;
5858 break;
5859 case VIR_MDEV_MODEL_TYPE_VFIO_AP:
5860 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VFIO_AP)) {
5861 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5862 _("VFIO AP device assignment is not "
5863 "supported by this version of QEMU"));
5864 return -1;
5866 break;
5867 case VIR_MDEV_MODEL_TYPE_LAST:
5868 default:
5869 virReportEnumRangeError(virMediatedDeviceModelType,
5870 subsys->u.mdev.model);
5871 return -1;
5874 virCommandAddArg(cmd, "-device");
5875 if (!(devstr =
5876 qemuBuildHostdevMediatedDevStr(def, hostdev, qemuCaps)))
5877 return -1;
5878 virCommandAddArg(cmd, devstr);
5879 VIR_FREE(devstr);
5883 return 0;
5887 static int
5888 qemuBuildMonitorCommandLine(virLogManagerPtr logManager,
5889 virSecurityManagerPtr secManager,
5890 virCommandPtr cmd,
5891 virQEMUDriverConfigPtr cfg,
5892 virDomainDefPtr def,
5893 qemuDomainObjPrivatePtr priv)
5895 char *chrdev;
5896 unsigned int cdevflags = QEMU_BUILD_CHARDEV_TCP_NOWAIT |
5897 QEMU_BUILD_CHARDEV_UNIX_FD_PASS;
5898 if (priv->chardevStdioLogd)
5899 cdevflags |= QEMU_BUILD_CHARDEV_FILE_LOGD;
5901 if (!priv->monConfig)
5902 return 0;
5904 if (!(chrdev = qemuBuildChrChardevStr(logManager, secManager,
5905 cmd, cfg, def,
5906 priv->monConfig, "monitor",
5907 priv->qemuCaps, cdevflags)))
5908 return -1;
5909 virCommandAddArg(cmd, "-chardev");
5910 virCommandAddArg(cmd, chrdev);
5911 VIR_FREE(chrdev);
5913 virCommandAddArg(cmd, "-mon");
5914 virCommandAddArgFormat(cmd,
5915 "chardev=charmonitor,id=monitor,mode=%s",
5916 priv->monJSON ? "control" : "readline");
5918 return 0;
5922 static char *
5923 qemuBuildVirtioSerialPortDevStr(const virDomainDef *def,
5924 virDomainChrDefPtr dev)
5926 virBuffer buf = VIR_BUFFER_INITIALIZER;
5927 const char *contAlias;
5929 switch (dev->deviceType) {
5930 case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
5931 virBufferAddLit(&buf, "virtconsole");
5932 break;
5933 case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
5934 virBufferAddLit(&buf, "virtserialport");
5935 break;
5936 default:
5937 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5938 _("Cannot use virtio serial for parallel/serial devices"));
5939 return NULL;
5942 if (dev->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
5943 dev->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW &&
5944 dev->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390) {
5945 /* Check it's a virtio-serial address */
5946 if (dev->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL) {
5947 virReportError(VIR_ERR_INTERNAL_ERROR,
5948 "%s", _("virtio serial device has invalid address type"));
5949 goto error;
5952 contAlias = virDomainControllerAliasFind(def, VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL,
5953 dev->info.addr.vioserial.controller);
5954 if (!contAlias)
5955 goto error;
5957 virBufferAsprintf(&buf, ",bus=%s.%d,nr=%d", contAlias,
5958 dev->info.addr.vioserial.bus,
5959 dev->info.addr.vioserial.port);
5962 if (dev->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL &&
5963 dev->source->type == VIR_DOMAIN_CHR_TYPE_SPICEVMC &&
5964 dev->target.name &&
5965 STRNEQ(dev->target.name, "com.redhat.spice.0")) {
5966 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5967 _("Unsupported spicevmc target name '%s'"),
5968 dev->target.name);
5969 goto error;
5972 virBufferAsprintf(&buf, ",chardev=char%s,id=%s",
5973 dev->info.alias, dev->info.alias);
5974 if (dev->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL &&
5975 (dev->source->type == VIR_DOMAIN_CHR_TYPE_SPICEVMC ||
5976 dev->target.name)) {
5977 virBufferAsprintf(&buf, ",name=%s", dev->target.name
5978 ? dev->target.name : "com.redhat.spice.0");
5980 if (virBufferCheckError(&buf) < 0)
5981 goto error;
5983 return virBufferContentAndReset(&buf);
5985 error:
5986 virBufferFreeAndReset(&buf);
5987 return NULL;
5990 static char *
5991 qemuBuildSclpDevStr(virDomainChrDefPtr dev)
5993 virBuffer buf = VIR_BUFFER_INITIALIZER;
5994 if (dev->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE) {
5995 switch (dev->targetType) {
5996 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SCLP:
5997 virBufferAddLit(&buf, "sclpconsole");
5998 break;
5999 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SCLPLM:
6000 virBufferAddLit(&buf, "sclplmconsole");
6001 break;
6003 } else {
6004 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6005 _("Cannot use slcp with devices other than console"));
6006 goto error;
6008 virBufferAsprintf(&buf, ",chardev=char%s,id=%s",
6009 dev->info.alias, dev->info.alias);
6010 if (virBufferCheckError(&buf) < 0)
6011 goto error;
6013 return virBufferContentAndReset(&buf);
6015 error:
6016 virBufferFreeAndReset(&buf);
6017 return NULL;
6021 static int
6022 qemuBuildRNGBackendChrdevStr(virLogManagerPtr logManager,
6023 virSecurityManagerPtr secManager,
6024 virCommandPtr cmd,
6025 virQEMUDriverConfigPtr cfg,
6026 const virDomainDef *def,
6027 virDomainRNGDefPtr rng,
6028 virQEMUCapsPtr qemuCaps,
6029 char **chr,
6030 bool chardevStdioLogd)
6032 unsigned int cdevflags = QEMU_BUILD_CHARDEV_TCP_NOWAIT |
6033 QEMU_BUILD_CHARDEV_UNIX_FD_PASS;
6035 *chr = NULL;
6037 if (chardevStdioLogd)
6038 cdevflags |= QEMU_BUILD_CHARDEV_FILE_LOGD;
6040 switch ((virDomainRNGBackend) rng->backend) {
6041 case VIR_DOMAIN_RNG_BACKEND_RANDOM:
6042 case VIR_DOMAIN_RNG_BACKEND_LAST:
6043 /* no chardev backend is needed */
6044 return 0;
6046 case VIR_DOMAIN_RNG_BACKEND_EGD:
6047 if (!(*chr = qemuBuildChrChardevStr(logManager, secManager,
6048 cmd, cfg, def,
6049 rng->source.chardev,
6050 rng->info.alias, qemuCaps,
6051 cdevflags)))
6052 return -1;
6055 return 0;
6060 qemuBuildRNGBackendProps(virDomainRNGDefPtr rng,
6061 virQEMUCapsPtr qemuCaps,
6062 virJSONValuePtr *props)
6064 char *objAlias = NULL;
6065 char *charBackendAlias = NULL;
6066 int ret = -1;
6068 if (virAsprintf(&objAlias, "obj%s", rng->info.alias) < 0)
6069 goto cleanup;
6071 switch ((virDomainRNGBackend) rng->backend) {
6072 case VIR_DOMAIN_RNG_BACKEND_RANDOM:
6073 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_RNG_RANDOM)) {
6074 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6075 _("this qemu doesn't support the rng-random "
6076 "backend"));
6077 goto cleanup;
6080 if (qemuMonitorCreateObjectProps(props, "rng-random", objAlias,
6081 "s:filename", rng->source.file,
6082 NULL) < 0)
6083 goto cleanup;
6085 break;
6087 case VIR_DOMAIN_RNG_BACKEND_EGD:
6088 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_RNG_EGD)) {
6089 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6090 _("this qemu doesn't support the rng-egd "
6091 "backend"));
6092 goto cleanup;
6095 if (!(charBackendAlias = qemuAliasChardevFromDevAlias(rng->info.alias)))
6096 goto cleanup;
6098 if (qemuMonitorCreateObjectProps(props, "rng-egd", objAlias,
6099 "s:chardev", charBackendAlias,
6100 NULL) < 0)
6101 goto cleanup;
6103 break;
6105 case VIR_DOMAIN_RNG_BACKEND_LAST:
6106 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6107 _("unknown rng-random backend"));
6108 goto cleanup;
6111 ret = 0;
6113 cleanup:
6114 VIR_FREE(objAlias);
6115 VIR_FREE(charBackendAlias);
6116 return ret;
6120 char *
6121 qemuBuildRNGDevStr(const virDomainDef *def,
6122 virDomainRNGDefPtr dev,
6123 virQEMUCapsPtr qemuCaps)
6125 virBuffer buf = VIR_BUFFER_INITIALIZER;
6127 if (!qemuDomainCheckCCWS390AddressSupport(def, &dev->info, qemuCaps,
6128 dev->source.file))
6129 goto error;
6131 if (qemuBuildVirtioDevStr(&buf, "virtio-rng", qemuCaps,
6132 VIR_DOMAIN_DEVICE_RNG, dev) < 0) {
6133 goto error;
6136 virBufferAsprintf(&buf, ",rng=obj%s,id=%s",
6137 dev->info.alias, dev->info.alias);
6139 if (dev->rate > 0) {
6140 virBufferAsprintf(&buf, ",max-bytes=%u", dev->rate);
6141 if (dev->period)
6142 virBufferAsprintf(&buf, ",period=%u", dev->period);
6143 else
6144 virBufferAddLit(&buf, ",period=1000");
6147 if (qemuBuildVirtioOptionsStr(&buf, dev->virtio, qemuCaps) < 0)
6148 goto error;
6150 if (qemuBuildDeviceAddressStr(&buf, def, &dev->info, qemuCaps) < 0)
6151 goto error;
6152 if (virBufferCheckError(&buf) < 0)
6153 goto error;
6155 return virBufferContentAndReset(&buf);
6157 error:
6158 virBufferFreeAndReset(&buf);
6159 return NULL;
6163 static int
6164 qemuBuildRNGCommandLine(virLogManagerPtr logManager,
6165 virSecurityManagerPtr secManager,
6166 virCommandPtr cmd,
6167 virQEMUDriverConfigPtr cfg,
6168 const virDomainDef *def,
6169 virQEMUCapsPtr qemuCaps,
6170 bool chardevStdioLogd)
6172 size_t i;
6174 for (i = 0; i < def->nrngs; i++) {
6175 virJSONValuePtr props;
6176 virBuffer buf = VIR_BUFFER_INITIALIZER;
6177 virDomainRNGDefPtr rng = def->rngs[i];
6178 char *tmp;
6179 int rc;
6181 if (!rng->info.alias) {
6182 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
6183 _("RNG device is missing alias"));
6184 return -1;
6187 /* possibly add character device for backend */
6188 if (qemuBuildRNGBackendChrdevStr(logManager, secManager, cmd, cfg, def,
6189 rng, qemuCaps, &tmp,
6190 chardevStdioLogd) < 0)
6191 return -1;
6193 if (tmp) {
6194 virCommandAddArgList(cmd, "-chardev", tmp, NULL);
6195 VIR_FREE(tmp);
6198 if (qemuBuildRNGBackendProps(rng, qemuCaps, &props) < 0)
6199 return -1;
6201 rc = virQEMUBuildObjectCommandlineFromJSON(&buf, props);
6202 virJSONValueFree(props);
6204 if (rc < 0)
6205 return -1;
6207 virCommandAddArg(cmd, "-object");
6208 virCommandAddArgBuffer(cmd, &buf);
6210 /* add the device */
6211 if (qemuCommandAddExtDevice(cmd, &rng->info) < 0)
6212 return -1;
6214 if (!(tmp = qemuBuildRNGDevStr(def, rng, qemuCaps)))
6215 return -1;
6216 virCommandAddArgList(cmd, "-device", tmp, NULL);
6217 VIR_FREE(tmp);
6220 return 0;
6224 static char *
6225 qemuBuildSmbiosBiosStr(virSysinfoBIOSDefPtr def)
6227 virBuffer buf = VIR_BUFFER_INITIALIZER;
6229 if (!def)
6230 return NULL;
6232 virBufferAddLit(&buf, "type=0");
6234 /* 0:Vendor */
6235 if (def->vendor) {
6236 virBufferAddLit(&buf, ",vendor=");
6237 virQEMUBuildBufferEscapeComma(&buf, def->vendor);
6239 /* 0:BIOS Version */
6240 if (def->version) {
6241 virBufferAddLit(&buf, ",version=");
6242 virQEMUBuildBufferEscapeComma(&buf, def->version);
6244 /* 0:BIOS Release Date */
6245 if (def->date) {
6246 virBufferAddLit(&buf, ",date=");
6247 virQEMUBuildBufferEscapeComma(&buf, def->date);
6249 /* 0:System BIOS Major Release and 0:System BIOS Minor Release */
6250 if (def->release) {
6251 virBufferAddLit(&buf, ",release=");
6252 virQEMUBuildBufferEscapeComma(&buf, def->release);
6255 return virBufferContentAndReset(&buf);
6259 static char *
6260 qemuBuildSmbiosSystemStr(virSysinfoSystemDefPtr def,
6261 bool skip_uuid)
6263 virBuffer buf = VIR_BUFFER_INITIALIZER;
6265 if (!def ||
6266 (!def->manufacturer && !def->product && !def->version &&
6267 !def->serial && (!def->uuid || skip_uuid) &&
6268 def->sku && !def->family))
6269 return NULL;
6271 virBufferAddLit(&buf, "type=1");
6273 /* 1:Manufacturer */
6274 if (def->manufacturer) {
6275 virBufferAddLit(&buf, ",manufacturer=");
6276 virQEMUBuildBufferEscapeComma(&buf, def->manufacturer);
6278 /* 1:Product Name */
6279 if (def->product) {
6280 virBufferAddLit(&buf, ",product=");
6281 virQEMUBuildBufferEscapeComma(&buf, def->product);
6283 /* 1:Version */
6284 if (def->version) {
6285 virBufferAddLit(&buf, ",version=");
6286 virQEMUBuildBufferEscapeComma(&buf, def->version);
6288 /* 1:Serial Number */
6289 if (def->serial) {
6290 virBufferAddLit(&buf, ",serial=");
6291 virQEMUBuildBufferEscapeComma(&buf, def->serial);
6293 /* 1:UUID */
6294 if (def->uuid && !skip_uuid) {
6295 virBufferAddLit(&buf, ",uuid=");
6296 virQEMUBuildBufferEscapeComma(&buf, def->uuid);
6298 /* 1:SKU Number */
6299 if (def->sku) {
6300 virBufferAddLit(&buf, ",sku=");
6301 virQEMUBuildBufferEscapeComma(&buf, def->sku);
6303 /* 1:Family */
6304 if (def->family) {
6305 virBufferAddLit(&buf, ",family=");
6306 virQEMUBuildBufferEscapeComma(&buf, def->family);
6309 return virBufferContentAndReset(&buf);
6313 static char *
6314 qemuBuildSmbiosBaseBoardStr(virSysinfoBaseBoardDefPtr def)
6316 virBuffer buf = VIR_BUFFER_INITIALIZER;
6318 if (!def)
6319 return NULL;
6321 virBufferAddLit(&buf, "type=2");
6323 /* 2:Manufacturer */
6324 virBufferAddLit(&buf, ",manufacturer=");
6325 virQEMUBuildBufferEscapeComma(&buf, def->manufacturer);
6326 /* 2:Product Name */
6327 if (def->product) {
6328 virBufferAddLit(&buf, ",product=");
6329 virQEMUBuildBufferEscapeComma(&buf, def->product);
6331 /* 2:Version */
6332 if (def->version) {
6333 virBufferAddLit(&buf, ",version=");
6334 virQEMUBuildBufferEscapeComma(&buf, def->version);
6336 /* 2:Serial Number */
6337 if (def->serial) {
6338 virBufferAddLit(&buf, ",serial=");
6339 virQEMUBuildBufferEscapeComma(&buf, def->serial);
6341 /* 2:Asset Tag */
6342 if (def->asset) {
6343 virBufferAddLit(&buf, ",asset=");
6344 virQEMUBuildBufferEscapeComma(&buf, def->asset);
6346 /* 2:Location */
6347 if (def->location) {
6348 virBufferAddLit(&buf, ",location=");
6349 virQEMUBuildBufferEscapeComma(&buf, def->location);
6352 if (virBufferCheckError(&buf) < 0)
6353 goto error;
6355 return virBufferContentAndReset(&buf);
6357 error:
6358 virBufferFreeAndReset(&buf);
6359 return NULL;
6363 static char *
6364 qemuBuildSmbiosOEMStringsStr(virSysinfoOEMStringsDefPtr def)
6366 virBuffer buf = VIR_BUFFER_INITIALIZER;
6367 size_t i;
6369 if (!def)
6370 return NULL;
6372 virBufferAddLit(&buf, "type=11");
6374 for (i = 0; i < def->nvalues; i++) {
6375 virBufferAddLit(&buf, ",value=");
6376 virQEMUBuildBufferEscapeComma(&buf, def->values[i]);
6379 return virBufferContentAndReset(&buf);
6383 static char *
6384 qemuBuildSmbiosChassisStr(virSysinfoChassisDefPtr def)
6386 virBuffer buf = VIR_BUFFER_INITIALIZER;
6388 if (!def)
6389 return NULL;
6391 virBufferAddLit(&buf, "type=3");
6393 /* 3:Manufacturer */
6394 virBufferAddLit(&buf, ",manufacturer=");
6395 virQEMUBuildBufferEscapeComma(&buf, def->manufacturer);
6396 /* 3:Version */
6397 if (def->version) {
6398 virBufferAddLit(&buf, ",version=");
6399 virQEMUBuildBufferEscapeComma(&buf, def->version);
6401 /* 3:Serial Number */
6402 if (def->serial) {
6403 virBufferAddLit(&buf, ",serial=");
6404 virQEMUBuildBufferEscapeComma(&buf, def->serial);
6406 /* 3:Asset Tag */
6407 if (def->asset) {
6408 virBufferAddLit(&buf, ",asset=");
6409 virQEMUBuildBufferEscapeComma(&buf, def->asset);
6411 /* 3:Sku */
6412 if (def->sku) {
6413 virBufferAddLit(&buf, ",sku=");
6414 virQEMUBuildBufferEscapeComma(&buf, def->sku);
6417 if (virBufferCheckError(&buf) < 0)
6418 goto error;
6420 return virBufferContentAndReset(&buf);
6422 error:
6423 virBufferFreeAndReset(&buf);
6424 return NULL;
6428 static int
6429 qemuBuildSmbiosCommandLine(virCommandPtr cmd,
6430 virQEMUDriverPtr driver,
6431 const virDomainDef *def)
6433 size_t i;
6434 virSysinfoDefPtr source = NULL;
6435 bool skip_uuid = false;
6437 if (def->os.smbios_mode == VIR_DOMAIN_SMBIOS_NONE ||
6438 def->os.smbios_mode == VIR_DOMAIN_SMBIOS_EMULATE)
6439 return 0;
6441 /* should we really error out or just warn in those cases ? */
6442 if (def->os.smbios_mode == VIR_DOMAIN_SMBIOS_HOST) {
6443 if (driver->hostsysinfo == NULL) {
6444 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6445 _("Host SMBIOS information is not available"));
6446 return -1;
6448 source = driver->hostsysinfo;
6449 /* Host and guest uuid must differ, by definition of UUID. */
6450 skip_uuid = true;
6451 } else if (def->os.smbios_mode == VIR_DOMAIN_SMBIOS_SYSINFO) {
6452 if (def->sysinfo == NULL) {
6453 virReportError(VIR_ERR_XML_ERROR,
6454 _("Domain '%s' sysinfo are not available"),
6455 def->name);
6456 return -1;
6458 source = def->sysinfo;
6459 /* domain_conf guaranteed that system_uuid matches guest uuid. */
6461 if (source != NULL) {
6462 char *smbioscmd;
6464 smbioscmd = qemuBuildSmbiosBiosStr(source->bios);
6465 if (smbioscmd != NULL) {
6466 virCommandAddArgList(cmd, "-smbios", smbioscmd, NULL);
6467 VIR_FREE(smbioscmd);
6469 smbioscmd = qemuBuildSmbiosSystemStr(source->system, skip_uuid);
6470 if (smbioscmd != NULL) {
6471 virCommandAddArgList(cmd, "-smbios", smbioscmd, NULL);
6472 VIR_FREE(smbioscmd);
6475 if (source->nbaseBoard > 1) {
6476 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6477 _("qemu does not support more than "
6478 "one entry to Type 2 in SMBIOS table"));
6479 return -1;
6482 for (i = 0; i < source->nbaseBoard; i++) {
6483 if (!(smbioscmd =
6484 qemuBuildSmbiosBaseBoardStr(source->baseBoard + i)))
6485 return -1;
6487 virCommandAddArgList(cmd, "-smbios", smbioscmd, NULL);
6488 VIR_FREE(smbioscmd);
6491 smbioscmd = qemuBuildSmbiosChassisStr(source->chassis);
6492 if (smbioscmd != NULL) {
6493 virCommandAddArgList(cmd, "-smbios", smbioscmd, NULL);
6494 VIR_FREE(smbioscmd);
6497 if (source->oemStrings) {
6498 if (!(smbioscmd = qemuBuildSmbiosOEMStringsStr(source->oemStrings)))
6499 return -1;
6501 virCommandAddArgList(cmd, "-smbios", smbioscmd, NULL);
6502 VIR_FREE(smbioscmd);
6506 return 0;
6510 static int
6511 qemuBuildVMGenIDCommandLine(virCommandPtr cmd,
6512 const virDomainDef *def,
6513 virQEMUCapsPtr qemuCaps)
6515 virBuffer opts = VIR_BUFFER_INITIALIZER;
6516 char guid[VIR_UUID_STRING_BUFLEN];
6518 if (!def->genidRequested)
6519 return 0;
6521 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VMGENID)) {
6522 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6523 _("this QEMU does not support the 'genid' capability"));
6524 return -1;
6527 virUUIDFormat(def->genid, guid);
6528 virBufferAsprintf(&opts, "vmgenid,guid=%s,id=vmgenid0", guid);
6530 virCommandAddArg(cmd, "-device");
6531 virCommandAddArgBuffer(cmd, &opts);
6533 virBufferFreeAndReset(&opts);
6534 return 0;
6538 static int
6539 qemuBuildSgaCommandLine(virCommandPtr cmd,
6540 const virDomainDef *def,
6541 virQEMUCapsPtr qemuCaps)
6543 /* Serial graphics adapter */
6544 if (def->os.bios.useserial == VIR_TRISTATE_BOOL_YES) {
6545 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SGA)) {
6546 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
6547 _("qemu does not support SGA"));
6548 return -1;
6550 if (!def->nserials) {
6551 virReportError(VIR_ERR_XML_ERROR, "%s",
6552 _("need at least one serial port to use SGA"));
6553 return -1;
6555 virCommandAddArgList(cmd, "-device", "sga", NULL);
6558 return 0;
6562 static char *
6563 qemuBuildClockArgStr(virDomainClockDefPtr def)
6565 size_t i;
6566 virBuffer buf = VIR_BUFFER_INITIALIZER;
6568 switch (def->offset) {
6569 case VIR_DOMAIN_CLOCK_OFFSET_UTC:
6570 virBufferAddLit(&buf, "base=utc");
6571 break;
6573 case VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME:
6574 case VIR_DOMAIN_CLOCK_OFFSET_TIMEZONE:
6575 virBufferAddLit(&buf, "base=localtime");
6576 break;
6578 case VIR_DOMAIN_CLOCK_OFFSET_VARIABLE: {
6579 time_t now = time(NULL);
6580 struct tm nowbits;
6582 if (def->data.variable.basis == VIR_DOMAIN_CLOCK_BASIS_LOCALTIME) {
6583 long localOffset;
6585 /* in the case of basis='localtime', rather than trying to
6586 * keep that basis (and associated offset from UTC) in the
6587 * status and deal with adding in the difference each time
6588 * there is an RTC_CHANGE event, it is simpler and less
6589 * error prone to just convert the adjustment an offset
6590 * from UTC right now (and change the status to
6591 * "basis='utc' to reflect this). This eliminates
6592 * potential errors in both RTC_CHANGE events and in
6593 * migration (in the case that the status of DST, or the
6594 * timezone of the destination host, changed relative to
6595 * startup).
6597 if (virTimeLocalOffsetFromUTC(&localOffset) < 0)
6598 goto error;
6599 def->data.variable.adjustment += localOffset;
6600 def->data.variable.basis = VIR_DOMAIN_CLOCK_BASIS_UTC;
6603 now += def->data.variable.adjustment;
6604 gmtime_r(&now, &nowbits);
6606 /* when an RTC_CHANGE event is received from qemu, we need to
6607 * have the adjustment used at domain start time available to
6608 * compute the new offset from UTC. As this new value is
6609 * itself stored in def->data.variable.adjustment, we need to
6610 * save a copy of it now.
6612 def->data.variable.adjustment0 = def->data.variable.adjustment;
6614 virBufferAsprintf(&buf, "base=%d-%02d-%02dT%02d:%02d:%02d",
6615 nowbits.tm_year + 1900,
6616 nowbits.tm_mon + 1,
6617 nowbits.tm_mday,
6618 nowbits.tm_hour,
6619 nowbits.tm_min,
6620 nowbits.tm_sec);
6621 } break;
6623 default:
6624 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6625 _("unsupported clock offset '%s'"),
6626 virDomainClockOffsetTypeToString(def->offset));
6627 goto error;
6630 /* Look for an 'rtc' timer element, and add in appropriate
6631 * clock= and driftfix= */
6632 for (i = 0; i < def->ntimers; i++) {
6633 if (def->timers[i]->name == VIR_DOMAIN_TIMER_NAME_RTC) {
6634 switch (def->timers[i]->track) {
6635 case -1: /* unspecified - use hypervisor default */
6636 break;
6637 case VIR_DOMAIN_TIMER_TRACK_BOOT:
6638 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6639 _("unsupported rtc timer track '%s'"),
6640 virDomainTimerTrackTypeToString(def->timers[i]->track));
6641 goto error;
6642 case VIR_DOMAIN_TIMER_TRACK_GUEST:
6643 virBufferAddLit(&buf, ",clock=vm");
6644 break;
6645 case VIR_DOMAIN_TIMER_TRACK_WALL:
6646 virBufferAddLit(&buf, ",clock=host");
6647 break;
6650 switch (def->timers[i]->tickpolicy) {
6651 case -1:
6652 case VIR_DOMAIN_TIMER_TICKPOLICY_DELAY:
6653 /* This is the default - missed ticks delivered when
6654 next scheduled, at normal rate */
6655 break;
6656 case VIR_DOMAIN_TIMER_TICKPOLICY_CATCHUP:
6657 /* deliver ticks at a faster rate until caught up */
6658 virBufferAddLit(&buf, ",driftfix=slew");
6659 break;
6660 case VIR_DOMAIN_TIMER_TICKPOLICY_MERGE:
6661 case VIR_DOMAIN_TIMER_TICKPOLICY_DISCARD:
6662 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6663 _("unsupported rtc timer tickpolicy '%s'"),
6664 virDomainTimerTickpolicyTypeToString(def->timers[i]->tickpolicy));
6665 goto error;
6667 break; /* no need to check other timers - there is only one rtc */
6671 if (virBufferCheckError(&buf) < 0)
6672 goto error;
6674 return virBufferContentAndReset(&buf);
6676 error:
6677 virBufferFreeAndReset(&buf);
6678 return NULL;
6682 /* NOTE: Building of commands can change def->clock->data.* values, so
6683 * virDomainDef is not const here.
6685 static int
6686 qemuBuildClockCommandLine(virCommandPtr cmd,
6687 virDomainDefPtr def,
6688 virQEMUCapsPtr qemuCaps)
6690 size_t i;
6691 char *rtcopt;
6693 virCommandAddArg(cmd, "-rtc");
6694 if (!(rtcopt = qemuBuildClockArgStr(&def->clock)))
6695 return -1;
6696 virCommandAddArg(cmd, rtcopt);
6697 VIR_FREE(rtcopt);
6699 if (def->clock.offset == VIR_DOMAIN_CLOCK_OFFSET_TIMEZONE &&
6700 def->clock.data.timezone) {
6701 virCommandAddEnvPair(cmd, "TZ", def->clock.data.timezone);
6704 for (i = 0; i < def->clock.ntimers; i++) {
6705 switch ((virDomainTimerNameType)def->clock.timers[i]->name) {
6706 case VIR_DOMAIN_TIMER_NAME_PLATFORM:
6707 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6708 _("unsupported timer type (name) '%s'"),
6709 virDomainTimerNameTypeToString(def->clock.timers[i]->name));
6710 return -1;
6712 case VIR_DOMAIN_TIMER_NAME_TSC:
6713 case VIR_DOMAIN_TIMER_NAME_KVMCLOCK:
6714 case VIR_DOMAIN_TIMER_NAME_HYPERVCLOCK:
6715 /* Timers above are handled when building -cpu. */
6716 case VIR_DOMAIN_TIMER_NAME_LAST:
6717 break;
6719 case VIR_DOMAIN_TIMER_NAME_RTC:
6720 /* Already handled in qemuBuildClockArgStr */
6721 break;
6723 case VIR_DOMAIN_TIMER_NAME_PIT:
6724 switch (def->clock.timers[i]->tickpolicy) {
6725 case -1:
6726 case VIR_DOMAIN_TIMER_TICKPOLICY_DELAY:
6727 /* delay is the default if we don't have kernel
6728 (kvm-pit), otherwise, the default is catchup. */
6729 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_KVM_PIT_TICK_POLICY))
6730 virCommandAddArgList(cmd, "-global",
6731 "kvm-pit.lost_tick_policy=delay", NULL);
6732 break;
6733 case VIR_DOMAIN_TIMER_TICKPOLICY_CATCHUP:
6734 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_KVM_PIT_TICK_POLICY)) {
6735 /* do nothing - this is default for kvm-pit */
6736 } else {
6737 /* can't catchup if we don't have kvm-pit */
6738 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6739 _("unsupported pit tickpolicy '%s'"),
6740 virDomainTimerTickpolicyTypeToString(def->clock.timers[i]->tickpolicy));
6741 return -1;
6743 break;
6744 case VIR_DOMAIN_TIMER_TICKPOLICY_DISCARD:
6745 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_KVM_PIT_TICK_POLICY))
6746 virCommandAddArgList(cmd, "-global",
6747 "kvm-pit.lost_tick_policy=discard", NULL);
6748 break;
6749 case VIR_DOMAIN_TIMER_TICKPOLICY_MERGE:
6750 /* no way to support this mode for pit in qemu */
6751 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6752 _("unsupported pit tickpolicy '%s'"),
6753 virDomainTimerTickpolicyTypeToString(def->clock.timers[i]->tickpolicy));
6754 return -1;
6756 break;
6758 case VIR_DOMAIN_TIMER_NAME_HPET:
6759 /* the only meaningful attribute for hpet is "present". If
6760 * present is -1, that means it wasn't specified, and
6761 * should be left at the default for the
6762 * hypervisor. "default" when -no-hpet exists is "yes",
6763 * and when -no-hpet doesn't exist is "no". "confusing"?
6764 * "yes"! */
6766 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NO_HPET)) {
6767 if (def->clock.timers[i]->present == 0)
6768 virCommandAddArg(cmd, "-no-hpet");
6769 } else {
6770 /* no hpet timer available. The only possible action
6771 is to raise an error if present="yes" */
6772 if (def->clock.timers[i]->present == 1) {
6773 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6774 "%s", _("hpet timer is not supported"));
6775 return -1;
6778 break;
6782 return 0;
6786 static int
6787 qemuBuildPMCommandLine(virCommandPtr cmd,
6788 const virDomainDef *def,
6789 qemuDomainObjPrivatePtr priv)
6791 virQEMUCapsPtr qemuCaps = priv->qemuCaps;
6793 /* Only add -no-reboot option if each event destroys domain */
6794 if (priv->allowReboot == VIR_TRISTATE_BOOL_NO)
6795 virCommandAddArg(cmd, "-no-reboot");
6797 if (qemuDomainIsUsingNoShutdown(priv))
6798 virCommandAddArg(cmd, "-no-shutdown");
6800 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NO_ACPI)) {
6801 if (def->features[VIR_DOMAIN_FEATURE_ACPI] != VIR_TRISTATE_SWITCH_ON)
6802 virCommandAddArg(cmd, "-no-acpi");
6805 /* We fall back to PIIX4_PM even for q35, since it's what we did
6806 pre-q35-pm support. QEMU starts up fine (with a warning) if
6807 mixing PIIX PM and -M q35. Starting to reject things here
6808 could mean we refuse to start existing configs in the wild.*/
6809 if (def->pm.s3) {
6810 const char *pm_object = "PIIX4_PM";
6812 if (qemuDomainIsQ35(def) &&
6813 virQEMUCapsGet(qemuCaps, QEMU_CAPS_ICH9_DISABLE_S3)) {
6814 pm_object = "ICH9-LPC";
6815 } else if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_PIIX_DISABLE_S3)) {
6816 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6817 "%s", _("setting ACPI S3 not supported"));
6818 return -1;
6821 virCommandAddArg(cmd, "-global");
6822 virCommandAddArgFormat(cmd, "%s.disable_s3=%d",
6823 pm_object, def->pm.s3 == VIR_TRISTATE_BOOL_NO);
6826 if (def->pm.s4) {
6827 const char *pm_object = "PIIX4_PM";
6829 if (qemuDomainIsQ35(def) &&
6830 virQEMUCapsGet(qemuCaps, QEMU_CAPS_ICH9_DISABLE_S4)) {
6831 pm_object = "ICH9-LPC";
6832 } else if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_PIIX_DISABLE_S4)) {
6833 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6834 "%s", _("setting ACPI S4 not supported"));
6835 return -1;
6838 virCommandAddArg(cmd, "-global");
6839 virCommandAddArgFormat(cmd, "%s.disable_s4=%d",
6840 pm_object, def->pm.s4 == VIR_TRISTATE_BOOL_NO);
6843 return 0;
6847 static int
6848 qemuBuildBootCommandLine(virCommandPtr cmd,
6849 const virDomainDef *def,
6850 virQEMUCapsPtr qemuCaps)
6852 virBuffer boot_buf = VIR_BUFFER_INITIALIZER;
6853 char *boot_opts_str = NULL;
6855 if (def->os.bootmenu) {
6856 if (def->os.bootmenu == VIR_TRISTATE_BOOL_YES)
6857 virBufferAddLit(&boot_buf, "menu=on,");
6858 else
6859 virBufferAddLit(&boot_buf, "menu=off,");
6862 if (def->os.bios.rt_set) {
6863 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_REBOOT_TIMEOUT)) {
6864 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6865 _("reboot timeout is not supported "
6866 "by this QEMU binary"));
6867 goto error;
6870 virBufferAsprintf(&boot_buf,
6871 "reboot-timeout=%d,",
6872 def->os.bios.rt_delay);
6875 if (def->os.bm_timeout_set) {
6876 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SPLASH_TIMEOUT)) {
6877 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6878 _("splash timeout is not supported "
6879 "by this QEMU binary"));
6880 goto error;
6883 virBufferAsprintf(&boot_buf, "splash-time=%u,", def->os.bm_timeout);
6886 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_BOOT_STRICT))
6887 virBufferAddLit(&boot_buf, "strict=on,");
6889 virBufferTrim(&boot_buf, ",", -1);
6891 if (virBufferCheckError(&boot_buf) < 0)
6892 goto error;
6894 boot_opts_str = virBufferContentAndReset(&boot_buf);
6895 if (boot_opts_str) {
6896 virCommandAddArg(cmd, "-boot");
6897 virCommandAddArg(cmd, boot_opts_str);
6899 VIR_FREE(boot_opts_str);
6901 if (def->os.kernel)
6902 virCommandAddArgList(cmd, "-kernel", def->os.kernel, NULL);
6903 if (def->os.initrd)
6904 virCommandAddArgList(cmd, "-initrd", def->os.initrd, NULL);
6905 if (def->os.cmdline)
6906 virCommandAddArgList(cmd, "-append", def->os.cmdline, NULL);
6907 if (def->os.dtb)
6908 virCommandAddArgList(cmd, "-dtb", def->os.dtb, NULL);
6909 if (def->os.slic_table) {
6910 virBuffer buf = VIR_BUFFER_INITIALIZER;
6911 virCommandAddArg(cmd, "-acpitable");
6912 virBufferAddLit(&buf, "sig=SLIC,file=");
6913 virQEMUBuildBufferEscapeComma(&buf, def->os.slic_table);
6914 virCommandAddArgBuffer(cmd, &buf);
6917 return 0;
6919 error:
6920 VIR_FREE(boot_opts_str);
6921 virBufferFreeAndReset(&boot_buf);
6922 return -1;
6926 static int
6927 qemuBuildIOMMUCommandLine(virCommandPtr cmd,
6928 const virDomainDef *def,
6929 virQEMUCapsPtr qemuCaps)
6931 virBuffer opts = VIR_BUFFER_INITIALIZER;
6932 const virDomainIOMMUDef *iommu = def->iommu;
6933 int ret = -1;
6935 if (!iommu)
6936 return 0;
6938 /* qemuDomainDeviceDefValidate() already made sure we have one of
6939 * QEMU_CAPS_DEVICE_INTEL_IOMMU or QEMU_CAPS_MACHINE_IOMMU: here we
6940 * handle the former case, while the latter is taken care of in
6941 * qemuBuildMachineCommandLine() */
6942 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_INTEL_IOMMU))
6943 return 0;
6945 switch (iommu->model) {
6946 case VIR_DOMAIN_IOMMU_MODEL_INTEL:
6947 virBufferAddLit(&opts, "intel-iommu");
6948 if (iommu->intremap != VIR_TRISTATE_SWITCH_ABSENT) {
6949 virBufferAsprintf(&opts, ",intremap=%s",
6950 virTristateSwitchTypeToString(iommu->intremap));
6952 if (iommu->caching_mode != VIR_TRISTATE_SWITCH_ABSENT) {
6953 virBufferAsprintf(&opts, ",caching-mode=%s",
6954 virTristateSwitchTypeToString(iommu->caching_mode));
6956 if (iommu->eim != VIR_TRISTATE_SWITCH_ABSENT) {
6957 virBufferAsprintf(&opts, ",eim=%s",
6958 virTristateSwitchTypeToString(iommu->eim));
6960 if (iommu->iotlb != VIR_TRISTATE_SWITCH_ABSENT) {
6961 virBufferAsprintf(&opts, ",device-iotlb=%s",
6962 virTristateSwitchTypeToString(iommu->iotlb));
6964 case VIR_DOMAIN_IOMMU_MODEL_LAST:
6965 break;
6967 virCommandAddArg(cmd, "-device");
6968 virCommandAddArgBuffer(cmd, &opts);
6970 ret = 0;
6971 virBufferFreeAndReset(&opts);
6972 return ret;
6976 static int
6977 qemuBuildGlobalControllerCommandLine(virCommandPtr cmd,
6978 const virDomainDef *def,
6979 virQEMUCapsPtr qemuCaps)
6981 size_t i;
6983 for (i = 0; i < def->ncontrollers; i++) {
6984 virDomainControllerDefPtr cont = def->controllers[i];
6985 if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI &&
6986 cont->opts.pciopts.pcihole64) {
6987 const char *hoststr = NULL;
6988 bool cap = false;
6989 bool machine = false;
6991 switch (cont->model) {
6992 case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
6993 hoststr = "i440FX-pcihost";
6994 cap = virQEMUCapsGet(qemuCaps, QEMU_CAPS_I440FX_PCI_HOLE64_SIZE);
6995 machine = qemuDomainIsI440FX(def);
6996 break;
6998 case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
6999 hoststr = "q35-pcihost";
7000 cap = virQEMUCapsGet(qemuCaps, QEMU_CAPS_Q35_PCI_HOLE64_SIZE);
7001 machine = qemuDomainIsQ35(def);
7002 break;
7004 default:
7005 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
7006 _("64-bit PCI hole setting is only for root"
7007 " PCI controllers"));
7008 return -1;
7011 if (!machine) {
7012 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7013 _("Setting the 64-bit PCI hole size is not "
7014 "supported for machine '%s'"), def->os.machine);
7015 return -1;
7017 if (!cap) {
7018 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7019 _("64-bit PCI hole size setting is not supported "
7020 "with this QEMU binary"));
7021 return -1;
7024 virCommandAddArg(cmd, "-global");
7025 virCommandAddArgFormat(cmd, "%s.pci-hole64-size=%luK", hoststr,
7026 cont->opts.pciopts.pcihole64size);
7030 return 0;
7034 * qemuFeatureNoEffect:
7035 * @feature: CPU Feature
7037 * Returns true, if the feature is known to have (never had) an effect on QEMU.
7038 * Those features might be dropped in qemu without a longer deprecation cycle
7039 * and must therefore be known e.g. to no more define them on command line.
7041 static bool
7042 qemuFeatureNoEffect(virCPUFeatureDefPtr feature)
7044 if (!feature->name)
7045 return false;
7047 if (STREQ(feature->name, "osxsave"))
7048 return true;
7049 if (STREQ(feature->name, "ospke"))
7050 return true;
7052 return false;
7055 static int
7056 qemuBuildCpuModelArgStr(virQEMUDriverPtr driver,
7057 const virDomainDef *def,
7058 virBufferPtr buf,
7059 virQEMUCapsPtr qemuCaps)
7061 int ret = -1;
7062 size_t i;
7063 virCapsPtr caps = NULL;
7064 virCPUDefPtr cpu = def->cpu;
7066 if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
7067 goto cleanup;
7069 switch ((virCPUMode) cpu->mode) {
7070 case VIR_CPU_MODE_HOST_PASSTHROUGH:
7071 virBufferAddLit(buf, "host");
7073 if (def->os.arch == VIR_ARCH_ARMV7L &&
7074 caps->host.arch == VIR_ARCH_AARCH64) {
7075 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_CPU_AARCH64_OFF)) {
7076 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7077 _("QEMU binary does not support CPU "
7078 "host-passthrough for armv7l on "
7079 "aarch64 host"));
7080 goto cleanup;
7082 virBufferAddLit(buf, ",aarch64=off");
7084 break;
7086 case VIR_CPU_MODE_HOST_MODEL:
7087 if (ARCH_IS_PPC64(def->os.arch)) {
7088 virBufferAddLit(buf, "host");
7089 if (cpu->model &&
7090 !(qemuDomainIsPSeries(def) &&
7091 virQEMUCapsGet(qemuCaps, QEMU_CAPS_MACHINE_PSERIES_MAX_CPU_COMPAT))) {
7092 virBufferAsprintf(buf, ",compat=%s", cpu->model);
7094 } else {
7095 virReportError(VIR_ERR_INTERNAL_ERROR,
7096 _("unexpected host-model CPU for %s architecture"),
7097 virArchToString(def->os.arch));
7098 goto cleanup;
7100 break;
7102 case VIR_CPU_MODE_CUSTOM:
7103 virBufferAdd(buf, cpu->model, -1);
7104 break;
7106 case VIR_CPU_MODE_LAST:
7107 break;
7110 if (ARCH_IS_S390(def->os.arch) && cpu->features &&
7111 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_QUERY_CPU_MODEL_EXPANSION)) {
7112 virReportError(VIR_ERR_INTERNAL_ERROR,
7113 _("CPU features not supported by hypervisor for %s "
7114 "architecture"), virArchToString(def->os.arch));
7115 goto cleanup;
7118 if (cpu->vendor_id)
7119 virBufferAsprintf(buf, ",vendor=%s", cpu->vendor_id);
7121 for (i = 0; i < cpu->nfeatures; i++) {
7122 if (qemuFeatureNoEffect(&(cpu->features[i])))
7123 continue;
7124 switch ((virCPUFeaturePolicy) cpu->features[i].policy) {
7125 case VIR_CPU_FEATURE_FORCE:
7126 case VIR_CPU_FEATURE_REQUIRE:
7127 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_QUERY_CPU_MODEL_EXPANSION))
7128 virBufferAsprintf(buf, ",%s=on", cpu->features[i].name);
7129 else
7130 virBufferAsprintf(buf, ",+%s", cpu->features[i].name);
7131 break;
7133 case VIR_CPU_FEATURE_DISABLE:
7134 case VIR_CPU_FEATURE_FORBID:
7135 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_QUERY_CPU_MODEL_EXPANSION))
7136 virBufferAsprintf(buf, ",%s=off", cpu->features[i].name);
7137 else
7138 virBufferAsprintf(buf, ",-%s", cpu->features[i].name);
7139 break;
7141 case VIR_CPU_FEATURE_OPTIONAL:
7142 case VIR_CPU_FEATURE_LAST:
7143 break;
7147 ret = 0;
7148 cleanup:
7149 virObjectUnref(caps);
7150 return ret;
7153 static int
7154 qemuBuildCpuCommandLine(virCommandPtr cmd,
7155 virQEMUDriverPtr driver,
7156 const virDomainDef *def,
7157 virQEMUCapsPtr qemuCaps)
7159 virArch hostarch = virArchFromHost();
7160 char *cpu = NULL, *cpu_flags = NULL;
7161 int ret = -1;
7162 virBuffer cpu_buf = VIR_BUFFER_INITIALIZER;
7163 virBuffer buf = VIR_BUFFER_INITIALIZER;
7164 size_t i;
7166 if (def->cpu &&
7167 (def->cpu->mode != VIR_CPU_MODE_CUSTOM || def->cpu->model)) {
7168 if (qemuBuildCpuModelArgStr(driver, def, &cpu_buf, qemuCaps) < 0)
7169 goto cleanup;
7170 } else {
7172 * Need to force a 32-bit guest CPU type if
7174 * 1. guest OS is i686
7175 * 2. host OS is x86_64
7176 * 3. emulator is qemu-kvm or kvm
7178 * Or
7180 * 1. guest OS is i686
7181 * 2. emulator is qemu-system-x86_64
7183 if (def->os.arch == VIR_ARCH_I686 &&
7184 ((hostarch == VIR_ARCH_X86_64 &&
7185 strstr(def->emulator, "kvm")) ||
7186 strstr(def->emulator, "x86_64"))) {
7187 virBufferAddLit(&cpu_buf, "qemu32");
7191 /* Handle paravirtual timers */
7192 for (i = 0; i < def->clock.ntimers; i++) {
7193 virDomainTimerDefPtr timer = def->clock.timers[i];
7195 if (timer->name == VIR_DOMAIN_TIMER_NAME_KVMCLOCK &&
7196 timer->present != -1) {
7197 virBufferAsprintf(&buf, ",%ckvmclock",
7198 timer->present ? '+' : '-');
7199 } else if (timer->name == VIR_DOMAIN_TIMER_NAME_HYPERVCLOCK &&
7200 timer->present == 1) {
7201 virBufferAddLit(&buf, ",hv_time");
7202 } else if (timer->name == VIR_DOMAIN_TIMER_NAME_TSC &&
7203 timer->frequency > 0) {
7204 virBufferAsprintf(&buf, ",tsc-frequency=%lu", timer->frequency);
7208 if (def->apic_eoi) {
7209 char sign;
7210 if (def->apic_eoi == VIR_TRISTATE_SWITCH_ON)
7211 sign = '+';
7212 else
7213 sign = '-';
7215 virBufferAsprintf(&buf, ",%ckvm_pv_eoi", sign);
7218 if (def->features[VIR_DOMAIN_FEATURE_PVSPINLOCK]) {
7219 char sign;
7220 if (def->features[VIR_DOMAIN_FEATURE_PVSPINLOCK] ==
7221 VIR_TRISTATE_SWITCH_ON)
7222 sign = '+';
7223 else
7224 sign = '-';
7226 virBufferAsprintf(&buf, ",%ckvm_pv_unhalt", sign);
7229 if (def->features[VIR_DOMAIN_FEATURE_HYPERV] == VIR_TRISTATE_SWITCH_ON) {
7230 for (i = 0; i < VIR_DOMAIN_HYPERV_LAST; i++) {
7231 switch ((virDomainHyperv) i) {
7232 case VIR_DOMAIN_HYPERV_RELAXED:
7233 case VIR_DOMAIN_HYPERV_VAPIC:
7234 case VIR_DOMAIN_HYPERV_VPINDEX:
7235 case VIR_DOMAIN_HYPERV_RUNTIME:
7236 case VIR_DOMAIN_HYPERV_SYNIC:
7237 case VIR_DOMAIN_HYPERV_STIMER:
7238 case VIR_DOMAIN_HYPERV_RESET:
7239 case VIR_DOMAIN_HYPERV_FREQUENCIES:
7240 case VIR_DOMAIN_HYPERV_REENLIGHTENMENT:
7241 case VIR_DOMAIN_HYPERV_TLBFLUSH:
7242 case VIR_DOMAIN_HYPERV_IPI:
7243 case VIR_DOMAIN_HYPERV_EVMCS:
7244 if (def->hyperv_features[i] == VIR_TRISTATE_SWITCH_ON)
7245 virBufferAsprintf(&buf, ",hv_%s",
7246 virDomainHypervTypeToString(i));
7247 break;
7249 case VIR_DOMAIN_HYPERV_SPINLOCKS:
7250 if (def->hyperv_features[i] == VIR_TRISTATE_SWITCH_ON)
7251 virBufferAsprintf(&buf, ",hv_spinlocks=0x%x",
7252 def->hyperv_spinlocks);
7253 break;
7255 case VIR_DOMAIN_HYPERV_VENDOR_ID:
7256 if (def->hyperv_features[i] == VIR_TRISTATE_SWITCH_ON)
7257 virBufferAsprintf(&buf, ",hv_vendor_id=%s",
7258 def->hyperv_vendor_id);
7259 break;
7261 /* coverity[dead_error_begin] */
7262 case VIR_DOMAIN_HYPERV_LAST:
7263 break;
7268 for (i = 0; i < def->npanics; i++) {
7269 if (def->panics[i]->model == VIR_DOMAIN_PANIC_MODEL_HYPERV) {
7270 virBufferAddLit(&buf, ",hv_crash");
7271 break;
7275 if (def->features[VIR_DOMAIN_FEATURE_KVM] == VIR_TRISTATE_SWITCH_ON) {
7276 for (i = 0; i < VIR_DOMAIN_KVM_LAST; i++) {
7277 switch ((virDomainKVM) i) {
7278 case VIR_DOMAIN_KVM_HIDDEN:
7279 if (def->kvm_features[i] == VIR_TRISTATE_SWITCH_ON)
7280 virBufferAddLit(&buf, ",kvm=off");
7281 break;
7283 /* coverity[dead_error_begin] */
7284 case VIR_DOMAIN_KVM_LAST:
7285 break;
7290 if (def->features[VIR_DOMAIN_FEATURE_PMU]) {
7291 virTristateSwitch pmu = def->features[VIR_DOMAIN_FEATURE_PMU];
7292 virBufferAsprintf(&buf, ",pmu=%s",
7293 virTristateSwitchTypeToString(pmu));
7296 if (def->cpu && def->cpu->cache) {
7297 virCPUCacheDefPtr cache = def->cpu->cache;
7298 bool hostOff = false;
7299 bool l3Off = false;
7301 switch (cache->mode) {
7302 case VIR_CPU_CACHE_MODE_EMULATE:
7303 virBufferAddLit(&buf, ",l3-cache=on");
7304 hostOff = true;
7305 break;
7307 case VIR_CPU_CACHE_MODE_PASSTHROUGH:
7308 virBufferAddLit(&buf, ",host-cache-info=on");
7309 l3Off = true;
7310 break;
7312 case VIR_CPU_CACHE_MODE_DISABLE:
7313 hostOff = l3Off = true;
7314 break;
7316 case VIR_CPU_CACHE_MODE_LAST:
7317 break;
7320 if (hostOff &&
7321 def->cpu->mode == VIR_CPU_MODE_HOST_PASSTHROUGH &&
7322 virQEMUCapsGet(qemuCaps, QEMU_CAPS_CPU_CACHE))
7323 virBufferAddLit(&buf, ",host-cache-info=off");
7325 if (l3Off &&
7326 virQEMUCapsGet(qemuCaps, QEMU_CAPS_CPU_CACHE))
7327 virBufferAddLit(&buf, ",l3-cache=off");
7330 if (virBufferCheckError(&cpu_buf) < 0)
7331 goto cleanup;
7332 if (virBufferCheckError(&buf) < 0)
7333 goto cleanup;
7335 cpu = virBufferContentAndReset(&cpu_buf);
7336 cpu_flags = virBufferContentAndReset(&buf);
7338 if (cpu_flags && !cpu) {
7339 const char *default_model;
7341 switch ((int)def->os.arch) {
7342 case VIR_ARCH_I686:
7343 default_model = "qemu32";
7344 break;
7345 case VIR_ARCH_X86_64:
7346 default_model = "qemu64";
7347 break;
7348 default:
7349 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7350 _("CPU flags requested but can't determine "
7351 "default CPU for arch %s"),
7352 virArchToString(def->os.arch));
7353 goto cleanup;
7356 if (VIR_STRDUP(cpu, default_model) < 0)
7357 goto cleanup;
7360 if (cpu) {
7361 virCommandAddArg(cmd, "-cpu");
7362 virCommandAddArgFormat(cmd, "%s%s", cpu, NULLSTR_EMPTY(cpu_flags));
7365 ret = 0;
7367 cleanup:
7368 VIR_FREE(cpu);
7369 VIR_FREE(cpu_flags);
7370 virBufferFreeAndReset(&buf);
7371 virBufferFreeAndReset(&cpu_buf);
7372 return ret;
7376 static bool
7377 qemuAppendKeyWrapMachineParm(virBuffer *buf, virQEMUCapsPtr qemuCaps,
7378 int flag, const char *pname, int pstate)
7380 if (pstate != VIR_TRISTATE_SWITCH_ABSENT) {
7381 if (!virQEMUCapsGet(qemuCaps, flag)) {
7382 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7383 _("%s is not available with this QEMU binary"), pname);
7384 return false;
7387 virBufferAsprintf(buf, ",%s=%s", pname,
7388 virTristateSwitchTypeToString(pstate));
7391 return true;
7394 static bool
7395 qemuAppendKeyWrapMachineParms(virBuffer *buf, virQEMUCapsPtr qemuCaps,
7396 const virDomainKeyWrapDef *keywrap)
7398 if (!qemuAppendKeyWrapMachineParm(buf, qemuCaps, QEMU_CAPS_AES_KEY_WRAP,
7399 "aes-key-wrap", keywrap->aes))
7400 return false;
7402 if (!qemuAppendKeyWrapMachineParm(buf, qemuCaps, QEMU_CAPS_DEA_KEY_WRAP,
7403 "dea-key-wrap", keywrap->dea))
7404 return false;
7406 return true;
7410 static void
7411 qemuAppendLoadparmMachineParm(virBuffer *buf,
7412 const virDomainDef *def)
7414 size_t i = 0;
7416 for (i = 0; i < def->ndisks; i++) {
7417 virDomainDiskDefPtr disk = def->disks[i];
7419 if (disk->info.bootIndex == 1 && disk->info.loadparm) {
7420 virBufferAsprintf(buf, ",loadparm=%s", disk->info.loadparm);
7421 return;
7425 /* Network boot device */
7426 for (i = 0; i < def->nnets; i++) {
7427 virDomainNetDefPtr net = def->nets[i];
7429 if (net->info.bootIndex == 1 && net->info.loadparm) {
7430 virBufferAsprintf(buf, ",loadparm=%s", net->info.loadparm);
7431 return;
7437 static int
7438 qemuBuildNameCommandLine(virCommandPtr cmd,
7439 virQEMUDriverConfigPtr cfg,
7440 const virDomainDef *def,
7441 virQEMUCapsPtr qemuCaps)
7443 virBuffer buf = VIR_BUFFER_INITIALIZER;
7445 virCommandAddArg(cmd, "-name");
7447 /* The 'guest' option let's us handle a name with '=' embedded in it */
7448 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NAME_GUEST))
7449 virBufferAddLit(&buf, "guest=");
7451 virQEMUBuildBufferEscapeComma(&buf, def->name);
7453 if (cfg->setProcessName)
7454 virBufferAsprintf(&buf, ",process=qemu:%s", def->name);
7456 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NAME_DEBUG_THREADS))
7457 virBufferAddLit(&buf, ",debug-threads=on");
7459 virCommandAddArgBuffer(cmd, &buf);
7461 return 0;
7464 static int
7465 qemuBuildMachineCommandLine(virCommandPtr cmd,
7466 virQEMUDriverConfigPtr cfg,
7467 const virDomainDef *def,
7468 virQEMUCapsPtr qemuCaps)
7470 virTristateSwitch vmport = def->features[VIR_DOMAIN_FEATURE_VMPORT];
7471 virTristateSwitch smm = def->features[VIR_DOMAIN_FEATURE_SMM];
7472 virCPUDefPtr cpu = def->cpu;
7473 virBuffer buf = VIR_BUFFER_INITIALIZER;
7474 size_t i;
7475 int ret = -1;
7477 /* This should *never* be NULL, since we always provide
7478 * a machine in the capabilities data for QEMU. So this
7479 * check is just here as a safety in case the unexpected
7480 * happens */
7481 if (!def->os.machine)
7482 return 0;
7484 virCommandAddArg(cmd, "-machine");
7485 virBufferAdd(&buf, def->os.machine, -1);
7487 switch ((virDomainVirtType)def->virtType) {
7488 case VIR_DOMAIN_VIRT_QEMU:
7489 virBufferAddLit(&buf, ",accel=tcg");
7490 break;
7492 case VIR_DOMAIN_VIRT_KVM:
7493 virBufferAddLit(&buf, ",accel=kvm");
7494 break;
7496 case VIR_DOMAIN_VIRT_KQEMU:
7497 case VIR_DOMAIN_VIRT_XEN:
7498 case VIR_DOMAIN_VIRT_LXC:
7499 case VIR_DOMAIN_VIRT_UML:
7500 case VIR_DOMAIN_VIRT_OPENVZ:
7501 case VIR_DOMAIN_VIRT_TEST:
7502 case VIR_DOMAIN_VIRT_VMWARE:
7503 case VIR_DOMAIN_VIRT_HYPERV:
7504 case VIR_DOMAIN_VIRT_VBOX:
7505 case VIR_DOMAIN_VIRT_PHYP:
7506 case VIR_DOMAIN_VIRT_PARALLELS:
7507 case VIR_DOMAIN_VIRT_BHYVE:
7508 case VIR_DOMAIN_VIRT_VZ:
7509 case VIR_DOMAIN_VIRT_NONE:
7510 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7511 _("the QEMU binary does not support %s"),
7512 virDomainVirtTypeToString(def->virtType));
7513 return -1;
7515 case VIR_DOMAIN_VIRT_LAST:
7516 default:
7517 virReportEnumRangeError(virDomainVirtType, def->virtType);
7518 return -1;
7521 /* To avoid the collision of creating USB controllers when calling
7522 * machine->init in QEMU, it needs to set usb=off
7524 virBufferAddLit(&buf, ",usb=off");
7526 if (vmport) {
7527 if (!virQEMUCapsSupportsVmport(qemuCaps, def)) {
7528 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7529 _("vmport is not available "
7530 "with this QEMU binary"));
7531 goto cleanup;
7534 virBufferAsprintf(&buf, ",vmport=%s",
7535 virTristateSwitchTypeToString(vmport));
7538 if (smm)
7539 virBufferAsprintf(&buf, ",smm=%s", virTristateSwitchTypeToString(smm));
7541 if (def->mem.dump_core) {
7542 virBufferAsprintf(&buf, ",dump-guest-core=%s",
7543 virTristateSwitchTypeToString(def->mem.dump_core));
7544 } else {
7545 virBufferAsprintf(&buf, ",dump-guest-core=%s",
7546 cfg->dumpGuestCore ? "on" : "off");
7549 if (def->mem.nosharepages) {
7550 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MEM_MERGE)) {
7551 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7552 _("disable shared memory is not available "
7553 "with this QEMU binary"));
7554 goto cleanup;
7557 virBufferAddLit(&buf, ",mem-merge=off");
7560 if (def->keywrap &&
7561 !qemuAppendKeyWrapMachineParms(&buf, qemuCaps, def->keywrap))
7562 goto cleanup;
7564 if (def->features[VIR_DOMAIN_FEATURE_GIC] == VIR_TRISTATE_SWITCH_ON) {
7565 bool hasGICVersionOption = virQEMUCapsGet(qemuCaps,
7566 QEMU_CAPS_MACH_VIRT_GIC_VERSION);
7568 switch ((virGICVersion) def->gic_version) {
7569 case VIR_GIC_VERSION_2:
7570 if (!hasGICVersionOption) {
7571 /* If the gic-version option is not available, we can't
7572 * configure the GIC; however, we know that before the
7573 * option was introduced the guests would always get a
7574 * GICv2, so in order to maintain compatibility with
7575 * those old QEMU versions all we need to do is stop
7576 * early instead of erroring out */
7577 break;
7579 ATTRIBUTE_FALLTHROUGH;
7581 case VIR_GIC_VERSION_3:
7582 case VIR_GIC_VERSION_HOST:
7583 if (!hasGICVersionOption) {
7584 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7585 _("gic-version option is not available "
7586 "with this QEMU binary"));
7587 goto cleanup;
7590 virBufferAsprintf(&buf, ",gic-version=%s",
7591 virGICVersionTypeToString(def->gic_version));
7592 break;
7594 case VIR_GIC_VERSION_NONE:
7595 case VIR_GIC_VERSION_LAST:
7596 default:
7597 break;
7601 /* qemuDomainDeviceDefValidate() already made sure we have one of
7602 * QEMU_CAPS_DEVICE_INTEL_IOMMU or QEMU_CAPS_MACHINE_IOMMU: here we
7603 * handle the latter case, while the former is taken care of in
7604 * qemuBuildIOMMUCommandLine() */
7605 if (def->iommu &&
7606 virQEMUCapsGet(qemuCaps, QEMU_CAPS_MACHINE_IOMMU)) {
7607 switch (def->iommu->model) {
7608 case VIR_DOMAIN_IOMMU_MODEL_INTEL:
7609 virBufferAddLit(&buf, ",iommu=on");
7610 break;
7611 case VIR_DOMAIN_IOMMU_MODEL_LAST:
7612 break;
7616 for (i = 0; i < def->nmems; i++) {
7617 if (def->mems[i]->model == VIR_DOMAIN_MEMORY_MODEL_NVDIMM) {
7618 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_NVDIMM)) {
7619 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7620 _("nvdimm isn't supported by this QEMU binary"));
7621 goto cleanup;
7623 virBufferAddLit(&buf, ",nvdimm=on");
7624 break;
7628 if (def->features[VIR_DOMAIN_FEATURE_IOAPIC] != VIR_DOMAIN_IOAPIC_NONE) {
7629 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MACHINE_KERNEL_IRQCHIP)) {
7630 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7631 _("I/O APIC tuning is not supported by this "
7632 "QEMU binary"));
7633 goto cleanup;
7635 switch ((virDomainIOAPIC) def->features[VIR_DOMAIN_FEATURE_IOAPIC]) {
7636 case VIR_DOMAIN_IOAPIC_QEMU:
7637 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MACHINE_KERNEL_IRQCHIP_SPLIT)) {
7638 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7639 _("split I/O APIC is not supported by this "
7640 "QEMU binary"));
7641 goto cleanup;
7643 virBufferAddLit(&buf, ",kernel_irqchip=split");
7644 break;
7645 case VIR_DOMAIN_IOAPIC_KVM:
7646 virBufferAddLit(&buf, ",kernel_irqchip=on");
7647 break;
7648 case VIR_DOMAIN_IOAPIC_NONE:
7649 case VIR_DOMAIN_IOAPIC_LAST:
7650 break;
7654 if (def->features[VIR_DOMAIN_FEATURE_HPT] == VIR_TRISTATE_SWITCH_ON) {
7656 if (def->hpt_resizing != VIR_DOMAIN_HPT_RESIZING_NONE) {
7657 const char *str;
7659 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MACHINE_PSERIES_RESIZE_HPT)) {
7660 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7661 _("HTP resizing is not supported by this "
7662 "QEMU binary"));
7663 goto cleanup;
7666 str = virDomainHPTResizingTypeToString(def->hpt_resizing);
7667 if (!str) {
7668 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7669 _("Invalid setting for HPT resizing"));
7670 goto cleanup;
7673 virBufferAsprintf(&buf, ",resize-hpt=%s", str);
7676 if (def->hpt_maxpagesize > 0) {
7677 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MACHINE_PSERIES_CAP_HPT_MAX_PAGE_SIZE)) {
7678 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7679 _("Configuring the page size for HPT guests "
7680 "is not supported by this QEMU binary"));
7681 goto cleanup;
7684 virBufferAsprintf(&buf, ",cap-hpt-max-page-size=%lluk",
7685 def->hpt_maxpagesize);
7689 if (def->features[VIR_DOMAIN_FEATURE_HTM] != VIR_TRISTATE_SWITCH_ABSENT) {
7690 const char *str;
7692 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MACHINE_PSERIES_CAP_HTM)) {
7693 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7694 _("HTM configuration is not supported by this "
7695 "QEMU binary"));
7696 goto cleanup;
7699 str = virTristateSwitchTypeToString(def->features[VIR_DOMAIN_FEATURE_HTM]);
7700 if (!str) {
7701 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7702 _("Invalid setting for HTM state"));
7703 goto cleanup;
7706 virBufferAsprintf(&buf, ",cap-htm=%s", str);
7709 if (def->features[VIR_DOMAIN_FEATURE_NESTED_HV] != VIR_TRISTATE_SWITCH_ABSENT) {
7710 const char *str;
7712 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MACHINE_PSERIES_CAP_NESTED_HV)) {
7713 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7714 _("Nested HV configuration is not supported by "
7715 "this QEMU binary"));
7716 goto cleanup;
7719 str = virTristateSwitchTypeToString(def->features[VIR_DOMAIN_FEATURE_NESTED_HV]);
7720 if (!str) {
7721 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7722 _("Invalid setting for nested HV state"));
7723 goto cleanup;
7726 virBufferAsprintf(&buf, ",cap-nested-hv=%s", str);
7729 if (cpu && cpu->model &&
7730 cpu->mode == VIR_CPU_MODE_HOST_MODEL &&
7731 qemuDomainIsPSeries(def) &&
7732 virQEMUCapsGet(qemuCaps, QEMU_CAPS_MACHINE_PSERIES_MAX_CPU_COMPAT)) {
7733 virBufferAsprintf(&buf, ",max-cpu-compat=%s", cpu->model);
7736 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_LOADPARM))
7737 qemuAppendLoadparmMachineParm(&buf, def);
7739 if (def->sev)
7740 virBufferAddLit(&buf, ",memory-encryption=sev0");
7742 virCommandAddArgBuffer(cmd, &buf);
7744 ret = 0;
7745 cleanup:
7746 virBufferFreeAndReset(&buf);
7747 return ret;
7751 static void
7752 qemuBuildTSEGCommandLine(virCommandPtr cmd,
7753 const virDomainDef *def)
7755 if (!def->tseg_specified)
7756 return;
7758 virCommandAddArg(cmd, "-global");
7760 /* PostParse callback guarantees that the size is divisible by 1 MiB */
7761 virCommandAddArgFormat(cmd, "mch.extended-tseg-mbytes=%llu",
7762 def->tseg_size >> 20);
7766 static int
7767 qemuBuildSmpCommandLine(virCommandPtr cmd,
7768 virDomainDefPtr def)
7770 char *smp;
7771 virBuffer buf = VIR_BUFFER_INITIALIZER;
7772 unsigned int maxvcpus = virDomainDefGetVcpusMax(def);
7773 unsigned int nvcpus = 0;
7774 virDomainVcpuDefPtr vcpu;
7775 size_t i;
7777 /* count non-hotpluggable enabled vcpus. Hotpluggable ones will be added
7778 * in a different way */
7779 for (i = 0; i < maxvcpus; i++) {
7780 vcpu = virDomainDefGetVcpu(def, i);
7781 if (vcpu->online && vcpu->hotpluggable == VIR_TRISTATE_BOOL_NO)
7782 nvcpus++;
7785 virCommandAddArg(cmd, "-smp");
7787 virBufferAsprintf(&buf, "%u", nvcpus);
7789 if (nvcpus != maxvcpus)
7790 virBufferAsprintf(&buf, ",maxcpus=%u", maxvcpus);
7791 /* sockets, cores, and threads are either all zero
7792 * or all non-zero, thus checking one of them is enough */
7793 if (def->cpu && def->cpu->sockets) {
7794 virBufferAsprintf(&buf, ",sockets=%u", def->cpu->sockets);
7795 virBufferAsprintf(&buf, ",cores=%u", def->cpu->cores);
7796 virBufferAsprintf(&buf, ",threads=%u", def->cpu->threads);
7797 } else {
7798 virBufferAsprintf(&buf, ",sockets=%u", virDomainDefGetVcpusMax(def));
7799 virBufferAsprintf(&buf, ",cores=%u", 1);
7800 virBufferAsprintf(&buf, ",threads=%u", 1);
7803 if (virBufferCheckError(&buf) < 0)
7804 return -1;
7806 smp = virBufferContentAndReset(&buf);
7807 virCommandAddArg(cmd, smp);
7808 VIR_FREE(smp);
7810 return 0;
7814 static int
7815 qemuBuildMemPathStr(virQEMUDriverConfigPtr cfg,
7816 const virDomainDef *def,
7817 virCommandPtr cmd,
7818 qemuDomainObjPrivatePtr priv)
7820 const long system_page_size = virGetSystemPageSizeKB();
7821 char *mem_path = NULL;
7823 /* There are two cases where we want to put -mem-path onto
7824 * the command line: First one is when there are no guest
7825 * NUMA nodes and hugepages are configured. The second one is
7826 * if user requested file allocation. */
7827 if (def->mem.nhugepages &&
7828 def->mem.hugepages[0].size != system_page_size) {
7829 unsigned long long pagesize = def->mem.hugepages[0].size;
7830 if (!pagesize &&
7831 qemuBuildMemoryGetDefaultPagesize(cfg, &pagesize) < 0)
7832 return -1;
7833 if (qemuGetDomainHupageMemPath(def, cfg, pagesize, &mem_path) < 0)
7834 return -1;
7835 } else if (def->mem.source == VIR_DOMAIN_MEMORY_SOURCE_FILE) {
7836 if (qemuGetMemoryBackingPath(def, cfg, "ram", &mem_path) < 0)
7837 return -1;
7838 } else {
7839 return 0;
7842 if (def->mem.allocation != VIR_DOMAIN_MEMORY_ALLOCATION_IMMEDIATE) {
7843 virCommandAddArgList(cmd, "-mem-prealloc", NULL);
7844 priv->memPrealloc = true;
7847 virCommandAddArgList(cmd, "-mem-path", mem_path, NULL);
7848 VIR_FREE(mem_path);
7850 return 0;
7854 static int
7855 qemuBuildMemCommandLine(virCommandPtr cmd,
7856 virQEMUDriverConfigPtr cfg,
7857 const virDomainDef *def,
7858 virQEMUCapsPtr qemuCaps,
7859 qemuDomainObjPrivatePtr priv)
7861 if (qemuDomainDefValidateMemoryHotplug(def, qemuCaps, NULL) < 0)
7862 return -1;
7864 virCommandAddArg(cmd, "-m");
7866 if (virDomainDefHasMemoryHotplug(def)) {
7867 /* Use the 'k' suffix to let qemu handle the units */
7868 virCommandAddArgFormat(cmd, "size=%lluk,slots=%u,maxmem=%lluk",
7869 virDomainDefGetMemoryInitial(def),
7870 def->mem.memory_slots,
7871 def->mem.max_memory);
7873 } else {
7874 virCommandAddArgFormat(cmd, "%llu",
7875 virDomainDefGetMemoryInitial(def) / 1024);
7878 if (def->mem.allocation == VIR_DOMAIN_MEMORY_ALLOCATION_IMMEDIATE) {
7879 virCommandAddArgList(cmd, "-mem-prealloc", NULL);
7880 priv->memPrealloc = true;
7884 * Add '-mem-path' (and '-mem-prealloc') parameter here if
7885 * the hugepages and no numa node is specified.
7887 if (!virDomainNumaGetNodeCount(def->numa) &&
7888 qemuBuildMemPathStr(cfg, def, cmd, priv) < 0)
7889 return -1;
7891 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_OVERCOMMIT)) {
7892 virCommandAddArg(cmd, "-overcommit");
7893 virCommandAddArgFormat(cmd, "mem-lock=%s", def->mem.locked ? "on" : "off");
7894 } else {
7895 virCommandAddArg(cmd, "-realtime");
7896 virCommandAddArgFormat(cmd, "mlock=%s",
7897 def->mem.locked ? "on" : "off");
7900 return 0;
7904 static int
7905 qemuBuildIOThreadCommandLine(virCommandPtr cmd,
7906 const virDomainDef *def)
7908 size_t i;
7910 if (def->niothreadids == 0)
7911 return 0;
7913 /* Create iothread objects using the defined iothreadids list
7914 * and the defined id and name from the list. These may be used
7915 * by a disk definition which will associate to an iothread by
7916 * supplying a value of an id from the list
7918 for (i = 0; i < def->niothreadids; i++) {
7919 virCommandAddArg(cmd, "-object");
7920 virCommandAddArgFormat(cmd, "iothread,id=iothread%u",
7921 def->iothreadids[i]->iothread_id);
7924 return 0;
7928 static int
7929 qemuBuildNumaArgStr(virQEMUDriverConfigPtr cfg,
7930 virDomainDefPtr def,
7931 virCommandPtr cmd,
7932 qemuDomainObjPrivatePtr priv)
7934 size_t i, j;
7935 virQEMUCapsPtr qemuCaps = priv->qemuCaps;
7936 virBuffer buf = VIR_BUFFER_INITIALIZER;
7937 char *cpumask = NULL, *tmpmask = NULL, *next = NULL;
7938 virBufferPtr nodeBackends = NULL;
7939 bool needBackend = false;
7940 int rc;
7941 int ret = -1;
7942 size_t ncells = virDomainNumaGetNodeCount(def->numa);
7943 const long system_page_size = virGetSystemPageSizeKB();
7944 bool numa_distances = false;
7946 if (virDomainNumatuneHasPerNodeBinding(def->numa) &&
7947 !(virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_MEMORY_RAM) ||
7948 virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_MEMORY_FILE) ||
7949 virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_MEMORY_MEMFD))) {
7950 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7951 _("Per-node memory binding is not supported "
7952 "with this QEMU"));
7953 goto cleanup;
7956 if (def->mem.nhugepages &&
7957 def->mem.hugepages[0].size != system_page_size &&
7958 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_MEMORY_FILE)) {
7959 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7960 _("huge pages per NUMA node are not "
7961 "supported with this QEMU"));
7962 goto cleanup;
7965 if (!virDomainNumatuneNodesetIsAvailable(def->numa, priv->autoNodeset))
7966 goto cleanup;
7968 if (VIR_ALLOC_N(nodeBackends, ncells) < 0)
7969 goto cleanup;
7971 /* using of -numa memdev= cannot be combined with -numa mem=, thus we
7972 * need to check which approach to use */
7973 for (i = 0; i < ncells; i++) {
7974 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_MEMORY_RAM) ||
7975 virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_MEMORY_FILE) ||
7976 virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_MEMORY_MEMFD)) {
7978 if ((rc = qemuBuildMemoryCellBackendStr(def, cfg, i, priv,
7979 &nodeBackends[i])) < 0)
7980 goto cleanup;
7982 if (rc == 0)
7983 needBackend = true;
7984 } else {
7985 if (virDomainNumaGetNodeMemoryAccessMode(def->numa, i)) {
7986 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7987 _("Shared memory mapping is not supported "
7988 "with this QEMU"));
7989 goto cleanup;
7994 if (!needBackend &&
7995 qemuBuildMemPathStr(cfg, def, cmd, priv) < 0)
7996 goto cleanup;
7998 for (i = 0; i < ncells; i++) {
7999 VIR_FREE(cpumask);
8000 if (!(cpumask = virBitmapFormat(virDomainNumaGetNodeCpumask(def->numa, i))))
8001 goto cleanup;
8003 if (strchr(cpumask, ',') &&
8004 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_NUMA)) {
8005 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8006 _("disjoint NUMA cpu ranges are not supported "
8007 "with this QEMU"));
8008 goto cleanup;
8011 if (needBackend) {
8012 virCommandAddArg(cmd, "-object");
8013 virCommandAddArgBuffer(cmd, &nodeBackends[i]);
8016 virCommandAddArg(cmd, "-numa");
8017 virBufferAsprintf(&buf, "node,nodeid=%zu", i);
8019 for (tmpmask = cpumask; tmpmask; tmpmask = next) {
8020 if ((next = strchr(tmpmask, ',')))
8021 *(next++) = '\0';
8022 virBufferAddLit(&buf, ",cpus=");
8023 virBufferAdd(&buf, tmpmask, -1);
8026 if (needBackend)
8027 virBufferAsprintf(&buf, ",memdev=ram-node%zu", i);
8028 else
8029 virBufferAsprintf(&buf, ",mem=%llu",
8030 virDomainNumaGetNodeMemorySize(def->numa, i) / 1024);
8032 virCommandAddArgBuffer(cmd, &buf);
8035 /* If NUMA node distance is specified for at least one pair
8036 * of nodes, we have to specify all the distances. Even
8037 * though they might be the default ones. */
8038 for (i = 0; i < ncells; i++) {
8039 for (j = 0; j < ncells; j++) {
8040 if (virDomainNumaNodeDistanceIsUsingDefaults(def->numa, i, j))
8041 continue;
8043 numa_distances = true;
8044 break;
8046 if (numa_distances)
8047 break;
8050 if (numa_distances) {
8051 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_NUMA_DIST)) {
8052 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8053 _("setting NUMA distances is not "
8054 "supported with this qemu"));
8055 goto cleanup;
8058 for (i = 0; i < ncells; i++) {
8059 for (j = 0; j < ncells; j++) {
8060 size_t distance = virDomainNumaGetNodeDistance(def->numa, i, j);
8062 virCommandAddArg(cmd, "-numa");
8063 virBufferAsprintf(&buf, "dist,src=%zu,dst=%zu,val=%zu", i, j, distance);
8065 virCommandAddArgBuffer(cmd, &buf);
8070 ret = 0;
8072 cleanup:
8073 VIR_FREE(cpumask);
8075 if (nodeBackends) {
8076 for (i = 0; i < ncells; i++)
8077 virBufferFreeAndReset(&nodeBackends[i]);
8079 VIR_FREE(nodeBackends);
8082 virBufferFreeAndReset(&buf);
8083 return ret;
8087 static int
8088 qemuBuildMemoryDeviceCommandLine(virCommandPtr cmd,
8089 virQEMUDriverConfigPtr cfg,
8090 virDomainDefPtr def,
8091 qemuDomainObjPrivatePtr priv)
8093 size_t i;
8095 /* memory hotplug requires NUMA to be enabled - we already checked
8096 * that memory devices are present only when NUMA is */
8097 for (i = 0; i < def->nmems; i++) {
8098 virBuffer buf = VIR_BUFFER_INITIALIZER;
8099 char *dimmStr;
8101 if (qemuBuildMemoryDimmBackendStr(&buf, def->mems[i], def, cfg, priv) < 0)
8102 return -1;
8104 virCommandAddArg(cmd, "-object");
8105 virCommandAddArgBuffer(cmd, &buf);
8107 if (!(dimmStr = qemuBuildMemoryDeviceStr(def->mems[i], priv)))
8108 return -1;
8110 virCommandAddArgList(cmd, "-device", dimmStr, NULL);
8112 VIR_FREE(dimmStr);
8115 return 0;
8119 static int
8120 qemuBuildGraphicsSDLCommandLine(virQEMUDriverConfigPtr cfg ATTRIBUTE_UNUSED,
8121 virCommandPtr cmd,
8122 virQEMUCapsPtr qemuCaps ATTRIBUTE_UNUSED,
8123 virDomainGraphicsDefPtr graphics)
8125 int ret = -1;
8126 virBuffer opt = VIR_BUFFER_INITIALIZER;
8128 if (graphics->data.sdl.xauth)
8129 virCommandAddEnvPair(cmd, "XAUTHORITY", graphics->data.sdl.xauth);
8130 if (graphics->data.sdl.display)
8131 virCommandAddEnvPair(cmd, "DISPLAY", graphics->data.sdl.display);
8132 if (graphics->data.sdl.fullscreen)
8133 virCommandAddArg(cmd, "-full-screen");
8135 /* If using SDL for video, then we should just let it
8136 * use QEMU's host audio drivers, possibly SDL too
8137 * User can set these two before starting libvirtd
8139 virCommandAddEnvPassBlockSUID(cmd, "QEMU_AUDIO_DRV", NULL);
8140 virCommandAddEnvPassBlockSUID(cmd, "SDL_AUDIODRIVER", NULL);
8142 virCommandAddArg(cmd, "-display");
8143 virBufferAddLit(&opt, "sdl");
8145 if (graphics->data.sdl.gl != VIR_TRISTATE_BOOL_ABSENT) {
8146 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SDL_GL)) {
8147 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8148 _("OpenGL for SDL is not supported with this QEMU "
8149 "binary"));
8150 goto cleanup;
8153 virBufferAsprintf(&opt, ",gl=%s",
8154 virTristateSwitchTypeToString(graphics->data.sdl.gl));
8158 if (virBufferCheckError(&opt) < 0)
8159 goto cleanup;
8161 virCommandAddArgBuffer(cmd, &opt);
8163 ret = 0;
8164 cleanup:
8165 virBufferFreeAndReset(&opt);
8166 return ret;
8170 static int
8171 qemuBuildGraphicsVNCCommandLine(virQEMUDriverConfigPtr cfg,
8172 virCommandPtr cmd,
8173 virQEMUCapsPtr qemuCaps,
8174 virDomainGraphicsDefPtr graphics)
8176 virBuffer opt = VIR_BUFFER_INITIALIZER;
8177 virDomainGraphicsListenDefPtr glisten = NULL;
8178 bool escapeAddr;
8180 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VNC)) {
8181 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8182 _("vnc graphics are not supported with this QEMU"));
8183 goto error;
8186 if (!(glisten = virDomainGraphicsGetListen(graphics, 0))) {
8187 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8188 _("missing listen element"));
8189 goto error;
8192 switch (glisten->type) {
8193 case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_SOCKET:
8194 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VNC_MULTI_SERVERS))
8195 virBufferAddLit(&opt, "vnc=unix:");
8196 else
8197 virBufferAddLit(&opt, "unix:");
8198 virQEMUBuildBufferEscapeComma(&opt, glisten->socket);
8199 break;
8201 case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS:
8202 case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK:
8203 if (!graphics->data.vnc.autoport &&
8204 (graphics->data.vnc.port < 5900 ||
8205 graphics->data.vnc.port > 65535)) {
8206 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8207 _("vnc port must be in range [5900,65535]"));
8208 goto error;
8211 if (glisten->address) {
8212 escapeAddr = strchr(glisten->address, ':') != NULL;
8213 if (escapeAddr)
8214 virBufferAsprintf(&opt, "[%s]", glisten->address);
8215 else
8216 virBufferAdd(&opt, glisten->address, -1);
8218 virBufferAsprintf(&opt, ":%d",
8219 graphics->data.vnc.port - 5900);
8221 if (graphics->data.vnc.websocket)
8222 virBufferAsprintf(&opt, ",websocket=%d", graphics->data.vnc.websocket);
8223 break;
8225 case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NONE:
8226 virBufferAddLit(&opt, "none");
8227 break;
8229 case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_LAST:
8230 break;
8233 if (graphics->data.vnc.sharePolicy) {
8234 virBufferAsprintf(&opt, ",share=%s",
8235 virDomainGraphicsVNCSharePolicyTypeToString(
8236 graphics->data.vnc.sharePolicy));
8239 if (graphics->data.vnc.auth.passwd || cfg->vncPassword)
8240 virBufferAddLit(&opt, ",password");
8242 if (cfg->vncTLS) {
8243 qemuDomainGraphicsPrivatePtr gfxPriv = QEMU_DOMAIN_GRAPHICS_PRIVATE(graphics);
8244 if (gfxPriv->tlsAlias) {
8245 const char *secretAlias = NULL;
8247 if (gfxPriv->secinfo) {
8248 if (qemuBuildObjectSecretCommandLine(cmd,
8249 gfxPriv->secinfo) < 0)
8250 goto error;
8251 secretAlias = gfxPriv->secinfo->s.aes.alias;
8254 if (qemuBuildTLSx509CommandLine(cmd,
8255 cfg->vncTLSx509certdir,
8256 true,
8257 cfg->vncTLSx509verify,
8258 secretAlias,
8259 gfxPriv->tlsAlias,
8260 qemuCaps) < 0)
8261 goto error;
8263 virBufferAsprintf(&opt, ",tls-creds=%s", gfxPriv->tlsAlias);
8264 } else {
8265 virBufferAddLit(&opt, ",tls");
8266 if (cfg->vncTLSx509verify) {
8267 virBufferAddLit(&opt, ",x509verify=");
8268 virQEMUBuildBufferEscapeComma(&opt, cfg->vncTLSx509certdir);
8269 } else {
8270 virBufferAddLit(&opt, ",x509=");
8271 virQEMUBuildBufferEscapeComma(&opt, cfg->vncTLSx509certdir);
8276 if (cfg->vncSASL) {
8277 virBufferAddLit(&opt, ",sasl");
8279 if (cfg->vncSASLdir)
8280 virCommandAddEnvPair(cmd, "SASL_CONF_PATH", cfg->vncSASLdir);
8282 /* TODO: Support ACLs later */
8285 virCommandAddArg(cmd, "-vnc");
8286 virCommandAddArgBuffer(cmd, &opt);
8287 if (graphics->data.vnc.keymap)
8288 virCommandAddArgList(cmd, "-k", graphics->data.vnc.keymap, NULL);
8290 /* Unless user requested it, set the audio backend to none, to
8291 * prevent it opening the host OS audio devices, since that causes
8292 * security issues and might not work when using VNC.
8294 if (cfg->vncAllowHostAudio)
8295 virCommandAddEnvPassBlockSUID(cmd, "QEMU_AUDIO_DRV", NULL);
8296 else
8297 virCommandAddEnvString(cmd, "QEMU_AUDIO_DRV=none");
8299 return 0;
8301 error:
8302 virBufferFreeAndReset(&opt);
8303 return -1;
8307 static int
8308 qemuBuildGraphicsSPICECommandLine(virQEMUDriverConfigPtr cfg,
8309 virCommandPtr cmd,
8310 virQEMUCapsPtr qemuCaps,
8311 virDomainGraphicsDefPtr graphics)
8313 virBuffer opt = VIR_BUFFER_INITIALIZER;
8314 virDomainGraphicsListenDefPtr glisten = NULL;
8315 int port = graphics->data.spice.port;
8316 int tlsPort = graphics->data.spice.tlsPort;
8317 size_t i;
8318 bool hasSecure = false;
8319 bool hasInsecure = false;
8321 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SPICE)) {
8322 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8323 _("spice graphics are not supported with this QEMU"));
8324 goto error;
8327 if (!(glisten = virDomainGraphicsGetListen(graphics, 0))) {
8328 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8329 _("missing listen element"));
8330 goto error;
8333 switch (glisten->type) {
8334 case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_SOCKET:
8335 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SPICE_UNIX)) {
8336 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8337 _("unix socket for spice graphics are not supported "
8338 "with this QEMU"));
8339 goto error;
8342 virBufferAddLit(&opt, "unix,addr=");
8343 virQEMUBuildBufferEscapeComma(&opt, glisten->socket);
8344 virBufferAddLit(&opt, ",");
8345 hasInsecure = true;
8346 break;
8348 case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS:
8349 case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK:
8350 if (port > 0) {
8351 virBufferAsprintf(&opt, "port=%u,", port);
8352 hasInsecure = true;
8355 if (tlsPort > 0) {
8356 if (!cfg->spiceTLS) {
8357 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8358 _("spice TLS port set in XML configuration, "
8359 "but TLS is disabled in qemu.conf"));
8360 goto error;
8362 virBufferAsprintf(&opt, "tls-port=%u,", tlsPort);
8363 hasSecure = true;
8366 if (port > 0 || tlsPort > 0) {
8367 if (glisten->address)
8368 virBufferAsprintf(&opt, "addr=%s,", glisten->address);
8371 break;
8373 case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NONE:
8374 /* QEMU requires either port or tls-port to be specified if there is no
8375 * other argument. Use a dummy port=0. */
8376 virBufferAddLit(&opt, "port=0,");
8377 hasInsecure = true;
8378 break;
8379 case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_LAST:
8380 break;
8383 if (cfg->spiceSASL) {
8384 virBufferAddLit(&opt, "sasl,");
8386 if (cfg->spiceSASLdir)
8387 virCommandAddEnvPair(cmd, "SASL_CONF_PATH",
8388 cfg->spiceSASLdir);
8390 /* TODO: Support ACLs later */
8393 if (graphics->data.spice.mousemode) {
8394 switch (graphics->data.spice.mousemode) {
8395 case VIR_DOMAIN_GRAPHICS_SPICE_MOUSE_MODE_SERVER:
8396 virBufferAddLit(&opt, "agent-mouse=off,");
8397 break;
8398 case VIR_DOMAIN_GRAPHICS_SPICE_MOUSE_MODE_CLIENT:
8399 virBufferAddLit(&opt, "agent-mouse=on,");
8400 break;
8401 case VIR_DOMAIN_GRAPHICS_SPICE_MOUSE_MODE_DEFAULT:
8402 break;
8403 case VIR_DOMAIN_GRAPHICS_SPICE_MOUSE_MODE_LAST:
8404 default:
8405 virReportEnumRangeError(virDomainGraphicsSpiceMouseMode,
8406 graphics->data.spice.mousemode);
8407 goto error;
8411 /* In the password case we set it via monitor command, to avoid
8412 * making it visible on CLI, so there's no use of password=XXX
8413 * in this bit of the code */
8414 if (!graphics->data.spice.auth.passwd &&
8415 !cfg->spicePassword)
8416 virBufferAddLit(&opt, "disable-ticketing,");
8418 if (hasSecure) {
8419 virBufferAddLit(&opt, "x509-dir=");
8420 virQEMUBuildBufferEscapeComma(&opt, cfg->spiceTLSx509certdir);
8421 virBufferAddLit(&opt, ",");
8424 switch (graphics->data.spice.defaultMode) {
8425 case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_SECURE:
8426 if (!hasSecure) {
8427 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8428 _("spice defaultMode secure requested in XML "
8429 "configuration, but TLS connection is not "
8430 "available"));
8431 goto error;
8433 virBufferAddLit(&opt, "tls-channel=default,");
8434 break;
8435 case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_INSECURE:
8436 if (!hasInsecure) {
8437 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8438 _("spice defaultMode insecure requested in XML "
8439 "configuration, but plaintext connection is not "
8440 "available"));
8441 goto error;
8443 virBufferAddLit(&opt, "plaintext-channel=default,");
8444 break;
8445 case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_ANY:
8446 case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_LAST:
8447 /* nothing */
8448 break;
8451 for (i = 0; i < VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_LAST; i++) {
8452 switch (graphics->data.spice.channels[i]) {
8453 case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_SECURE:
8454 if (!hasSecure) {
8455 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8456 _("spice secure channels set in XML "
8457 "configuration, but TLS connection is not "
8458 "available"));
8459 goto error;
8461 virBufferAsprintf(&opt, "tls-channel=%s,",
8462 virDomainGraphicsSpiceChannelNameTypeToString(i));
8463 break;
8465 case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_INSECURE:
8466 if (!hasInsecure) {
8467 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8468 _("spice insecure channels set in XML "
8469 "configuration, but plaintext connection "
8470 "is not available"));
8471 goto error;
8473 virBufferAsprintf(&opt, "plaintext-channel=%s,",
8474 virDomainGraphicsSpiceChannelNameTypeToString(i));
8475 break;
8477 case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_ANY:
8478 break;
8482 if (graphics->data.spice.image)
8483 virBufferAsprintf(&opt, "image-compression=%s,",
8484 virDomainGraphicsSpiceImageCompressionTypeToString(graphics->data.spice.image));
8485 if (graphics->data.spice.jpeg)
8486 virBufferAsprintf(&opt, "jpeg-wan-compression=%s,",
8487 virDomainGraphicsSpiceJpegCompressionTypeToString(graphics->data.spice.jpeg));
8488 if (graphics->data.spice.zlib)
8489 virBufferAsprintf(&opt, "zlib-glz-wan-compression=%s,",
8490 virDomainGraphicsSpiceZlibCompressionTypeToString(graphics->data.spice.zlib));
8491 if (graphics->data.spice.playback)
8492 virBufferAsprintf(&opt, "playback-compression=%s,",
8493 virTristateSwitchTypeToString(graphics->data.spice.playback));
8494 if (graphics->data.spice.streaming)
8495 virBufferAsprintf(&opt, "streaming-video=%s,",
8496 virDomainGraphicsSpiceStreamingModeTypeToString(graphics->data.spice.streaming));
8497 if (graphics->data.spice.copypaste == VIR_TRISTATE_BOOL_NO)
8498 virBufferAddLit(&opt, "disable-copy-paste,");
8500 if (graphics->data.spice.filetransfer == VIR_TRISTATE_BOOL_NO) {
8501 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SPICE_FILE_XFER_DISABLE)) {
8502 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8503 _("This QEMU can't disable file transfers through spice"));
8504 goto error;
8505 } else {
8506 virBufferAddLit(&opt, "disable-agent-file-xfer,");
8510 if (graphics->data.spice.gl == VIR_TRISTATE_BOOL_YES) {
8511 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SPICE_GL)) {
8512 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8513 _("This QEMU doesn't support spice OpenGL"));
8514 goto error;
8517 /* spice.gl is a TristateBool, but qemu expects on/off: use
8518 * TristateSwitch helper */
8519 virBufferAsprintf(&opt, "gl=%s,",
8520 virTristateSwitchTypeToString(graphics->data.spice.gl));
8522 if (graphics->data.spice.rendernode) {
8523 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SPICE_RENDERNODE)) {
8524 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8525 _("This QEMU doesn't support spice OpenGL rendernode"));
8526 goto error;
8529 virBufferAddLit(&opt, "rendernode=");
8530 virQEMUBuildBufferEscapeComma(&opt, graphics->data.spice.rendernode);
8531 virBufferAddLit(&opt, ",");
8535 /* Turn on seamless migration unconditionally. If migration destination
8536 * doesn't support it, it fallbacks to previous migration algorithm silently. */
8537 virBufferAddLit(&opt, "seamless-migration=on,");
8539 virBufferTrim(&opt, ",", -1);
8541 virCommandAddArg(cmd, "-spice");
8542 virCommandAddArgBuffer(cmd, &opt);
8543 if (graphics->data.spice.keymap)
8544 virCommandAddArgList(cmd, "-k",
8545 graphics->data.spice.keymap, NULL);
8546 /* SPICE includes native support for tunnelling audio, so we
8547 * set the audio backend to point at SPICE's own driver
8549 virCommandAddEnvString(cmd, "QEMU_AUDIO_DRV=spice");
8551 return 0;
8553 error:
8554 virBufferFreeAndReset(&opt);
8555 return -1;
8559 static int
8560 qemuBuildGraphicsEGLHeadlessCommandLine(virQEMUDriverConfigPtr cfg ATTRIBUTE_UNUSED,
8561 virCommandPtr cmd,
8562 virQEMUCapsPtr qemuCaps,
8563 virDomainGraphicsDefPtr graphics)
8565 int ret = -1;
8566 virBuffer opt = VIR_BUFFER_INITIALIZER;
8568 virBufferAddLit(&opt, "egl-headless");
8570 if (graphics->data.egl_headless.rendernode) {
8571 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_EGL_HEADLESS_RENDERNODE)) {
8572 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8573 _("This QEMU doesn't support OpenGL rendernode "
8574 "with egl-headless graphics type"));
8575 goto cleanup;
8578 virBufferAddLit(&opt, ",rendernode=");
8579 virQEMUBuildBufferEscapeComma(&opt,
8580 graphics->data.egl_headless.rendernode);
8583 if (virBufferCheckError(&opt) < 0)
8584 goto cleanup;
8586 virCommandAddArg(cmd, "-display");
8587 virCommandAddArgBuffer(cmd, &opt);
8589 ret = 0;
8590 cleanup:
8591 virBufferFreeAndReset(&opt);
8592 return ret;
8596 static int
8597 qemuBuildGraphicsCommandLine(virQEMUDriverConfigPtr cfg,
8598 virCommandPtr cmd,
8599 virDomainDefPtr def,
8600 virQEMUCapsPtr qemuCaps)
8602 size_t i;
8604 for (i = 0; i < def->ngraphics; i++) {
8605 virDomainGraphicsDefPtr graphics = def->graphics[i];
8607 switch (graphics->type) {
8608 case VIR_DOMAIN_GRAPHICS_TYPE_SDL:
8609 if (qemuBuildGraphicsSDLCommandLine(cfg, cmd,
8610 qemuCaps, graphics) < 0)
8611 return -1;
8613 break;
8614 case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
8615 if (qemuBuildGraphicsVNCCommandLine(cfg, cmd,
8616 qemuCaps, graphics) < 0)
8617 return -1;
8619 break;
8620 case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
8621 if (qemuBuildGraphicsSPICECommandLine(cfg, cmd,
8622 qemuCaps, graphics) < 0)
8623 return -1;
8625 break;
8626 case VIR_DOMAIN_GRAPHICS_TYPE_EGL_HEADLESS:
8627 if (qemuBuildGraphicsEGLHeadlessCommandLine(cfg, cmd,
8628 qemuCaps, graphics) < 0)
8629 return -1;
8631 break;
8632 case VIR_DOMAIN_GRAPHICS_TYPE_RDP:
8633 case VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP:
8634 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8635 _("unsupported graphics type '%s'"),
8636 virDomainGraphicsTypeToString(graphics->type));
8637 return -1;
8638 case VIR_DOMAIN_GRAPHICS_TYPE_LAST:
8639 default:
8640 virReportEnumRangeError(virDomainGraphicsType, graphics->type);
8641 return -1;
8645 return 0;
8648 static int
8649 qemuInterfaceVhostuserConnect(virQEMUDriverPtr driver,
8650 virLogManagerPtr logManager,
8651 virSecurityManagerPtr secManager,
8652 virCommandPtr cmd,
8653 virDomainDefPtr def,
8654 virDomainNetDefPtr net,
8655 virQEMUCapsPtr qemuCaps,
8656 char **chardev)
8658 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
8659 int ret = -1;
8661 switch ((virDomainChrType)net->data.vhostuser->type) {
8662 case VIR_DOMAIN_CHR_TYPE_UNIX:
8663 if (!(*chardev = qemuBuildChrChardevStr(logManager, secManager,
8664 cmd, cfg, def,
8665 net->data.vhostuser,
8666 net->info.alias, qemuCaps, 0)))
8667 goto cleanup;
8668 break;
8670 case VIR_DOMAIN_CHR_TYPE_NULL:
8671 case VIR_DOMAIN_CHR_TYPE_VC:
8672 case VIR_DOMAIN_CHR_TYPE_PTY:
8673 case VIR_DOMAIN_CHR_TYPE_DEV:
8674 case VIR_DOMAIN_CHR_TYPE_FILE:
8675 case VIR_DOMAIN_CHR_TYPE_PIPE:
8676 case VIR_DOMAIN_CHR_TYPE_STDIO:
8677 case VIR_DOMAIN_CHR_TYPE_UDP:
8678 case VIR_DOMAIN_CHR_TYPE_TCP:
8679 case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
8680 case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
8681 case VIR_DOMAIN_CHR_TYPE_NMDM:
8682 case VIR_DOMAIN_CHR_TYPE_LAST:
8683 virReportError(VIR_ERR_INTERNAL_ERROR,
8684 _("vhost-user type '%s' not supported"),
8685 virDomainChrTypeToString(net->data.vhostuser->type));
8686 goto cleanup;
8689 ret = 0;
8690 cleanup:
8691 virObjectUnref(cfg);
8692 return ret;
8695 static int
8696 qemuBuildInterfaceCommandLine(virQEMUDriverPtr driver,
8697 virLogManagerPtr logManager,
8698 virSecurityManagerPtr secManager,
8699 virCommandPtr cmd,
8700 virDomainDefPtr def,
8701 virDomainNetDefPtr net,
8702 virQEMUCapsPtr qemuCaps,
8703 unsigned int bootindex,
8704 virNetDevVPortProfileOp vmop,
8705 bool standalone,
8706 size_t *nnicindexes,
8707 int **nicindexes)
8709 int ret = -1;
8710 char *nic = NULL;
8711 char *host = NULL;
8712 char *chardev = NULL;
8713 int *tapfd = NULL;
8714 size_t tapfdSize = 0;
8715 int *vhostfd = NULL;
8716 size_t vhostfdSize = 0;
8717 char **tapfdName = NULL;
8718 char **vhostfdName = NULL;
8719 virDomainNetType actualType = virDomainNetGetActualType(net);
8720 virNetDevBandwidthPtr actualBandwidth;
8721 bool requireNicdev = false;
8722 size_t i;
8725 if (!bootindex)
8726 bootindex = net->info.bootIndex;
8728 /* Currently nothing besides TAP devices supports multiqueue. */
8729 if (net->driver.virtio.queues > 0 &&
8730 !(actualType == VIR_DOMAIN_NET_TYPE_NETWORK ||
8731 actualType == VIR_DOMAIN_NET_TYPE_BRIDGE ||
8732 actualType == VIR_DOMAIN_NET_TYPE_DIRECT ||
8733 actualType == VIR_DOMAIN_NET_TYPE_ETHERNET ||
8734 actualType == VIR_DOMAIN_NET_TYPE_VHOSTUSER)) {
8735 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8736 _("Multiqueue network is not supported for: %s"),
8737 virDomainNetTypeToString(actualType));
8738 return -1;
8741 /* and only TAP devices support nwfilter rules */
8742 if (net->filter) {
8743 virNetDevVPortProfilePtr vport = virDomainNetGetActualVirtPortProfile(net);
8744 if (!(actualType == VIR_DOMAIN_NET_TYPE_NETWORK ||
8745 actualType == VIR_DOMAIN_NET_TYPE_BRIDGE ||
8746 actualType == VIR_DOMAIN_NET_TYPE_ETHERNET)) {
8747 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8748 _("filterref is not supported for "
8749 "network interfaces of type %s"),
8750 virDomainNetTypeToString(actualType));
8751 return -1;
8753 if (vport && vport->virtPortType != VIR_NETDEV_VPORT_PROFILE_NONE) {
8754 /* currently none of the defined virtualport types support iptables */
8755 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8756 _("filterref is not supported for "
8757 "network interfaces with virtualport type %s"),
8758 virNetDevVPortTypeToString(vport->virtPortType));
8759 return -1;
8763 if (net->backend.tap &&
8764 !(actualType == VIR_DOMAIN_NET_TYPE_NETWORK ||
8765 actualType == VIR_DOMAIN_NET_TYPE_BRIDGE ||
8766 actualType == VIR_DOMAIN_NET_TYPE_ETHERNET)) {
8767 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8768 _("Custom tap device path is not supported for: %s"),
8769 virDomainNetTypeToString(actualType));
8770 return -1;
8773 switch (actualType) {
8774 case VIR_DOMAIN_NET_TYPE_NETWORK:
8775 case VIR_DOMAIN_NET_TYPE_BRIDGE:
8776 tapfdSize = net->driver.virtio.queues;
8777 if (!tapfdSize)
8778 tapfdSize = 1;
8780 if (VIR_ALLOC_N(tapfd, tapfdSize) < 0 ||
8781 VIR_ALLOC_N(tapfdName, tapfdSize) < 0)
8782 goto cleanup;
8784 memset(tapfd, -1, tapfdSize * sizeof(tapfd[0]));
8786 if (qemuInterfaceBridgeConnect(def, driver, net,
8787 tapfd, &tapfdSize) < 0)
8788 goto cleanup;
8789 break;
8791 case VIR_DOMAIN_NET_TYPE_DIRECT:
8792 tapfdSize = net->driver.virtio.queues;
8793 if (!tapfdSize)
8794 tapfdSize = 1;
8796 if (VIR_ALLOC_N(tapfd, tapfdSize) < 0 ||
8797 VIR_ALLOC_N(tapfdName, tapfdSize) < 0)
8798 goto cleanup;
8800 memset(tapfd, -1, tapfdSize * sizeof(tapfd[0]));
8802 if (qemuInterfaceDirectConnect(def, driver, net,
8803 tapfd, tapfdSize, vmop) < 0)
8804 goto cleanup;
8805 break;
8807 case VIR_DOMAIN_NET_TYPE_ETHERNET:
8808 tapfdSize = net->driver.virtio.queues;
8809 if (!tapfdSize)
8810 tapfdSize = 1;
8812 if (VIR_ALLOC_N(tapfd, tapfdSize) < 0 ||
8813 VIR_ALLOC_N(tapfdName, tapfdSize) < 0)
8814 goto cleanup;
8816 memset(tapfd, -1, tapfdSize * sizeof(tapfd[0]));
8818 if (qemuInterfaceEthernetConnect(def, driver, net,
8819 tapfd, tapfdSize) < 0)
8820 goto cleanup;
8821 break;
8823 case VIR_DOMAIN_NET_TYPE_HOSTDEV:
8824 /* NET_TYPE_HOSTDEV devices are really hostdev devices, so
8825 * their commandlines are constructed with other hostdevs.
8827 ret = 0;
8828 goto cleanup;
8829 break;
8831 case VIR_DOMAIN_NET_TYPE_VHOSTUSER:
8832 requireNicdev = true;
8834 if (net->driver.virtio.queues > 1 &&
8835 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_VHOSTUSER_MULTIQUEUE)) {
8836 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8837 _("multi-queue is not supported for vhost-user "
8838 "with this QEMU binary"));
8839 goto cleanup;
8842 if (qemuInterfaceVhostuserConnect(driver, logManager, secManager,
8843 cmd, def, net, qemuCaps, &chardev) < 0)
8844 goto cleanup;
8846 if (virNetDevOpenvswitchGetVhostuserIfname(net->data.vhostuser->data.nix.path,
8847 &net->ifname) < 0)
8848 goto cleanup;
8850 break;
8852 case VIR_DOMAIN_NET_TYPE_USER:
8853 case VIR_DOMAIN_NET_TYPE_SERVER:
8854 case VIR_DOMAIN_NET_TYPE_CLIENT:
8855 case VIR_DOMAIN_NET_TYPE_MCAST:
8856 case VIR_DOMAIN_NET_TYPE_INTERNAL:
8857 case VIR_DOMAIN_NET_TYPE_UDP:
8858 case VIR_DOMAIN_NET_TYPE_LAST:
8859 /* nada */
8860 break;
8863 /* For types whose implementations use a netdev on the host, add
8864 * an entry to nicindexes for passing on to systemd.
8866 switch ((virDomainNetType)actualType) {
8867 case VIR_DOMAIN_NET_TYPE_ETHERNET:
8868 case VIR_DOMAIN_NET_TYPE_NETWORK:
8869 case VIR_DOMAIN_NET_TYPE_BRIDGE:
8870 case VIR_DOMAIN_NET_TYPE_DIRECT:
8872 int nicindex;
8874 /* network and bridge use a tap device, and direct uses a
8875 * macvtap device
8877 if (virQEMUDriverIsPrivileged(driver) && nicindexes && nnicindexes &&
8878 net->ifname) {
8879 if (virNetDevGetIndex(net->ifname, &nicindex) < 0 ||
8880 VIR_APPEND_ELEMENT(*nicindexes, *nnicindexes, nicindex) < 0)
8881 goto cleanup;
8883 break;
8886 case VIR_DOMAIN_NET_TYPE_USER:
8887 case VIR_DOMAIN_NET_TYPE_VHOSTUSER:
8888 case VIR_DOMAIN_NET_TYPE_SERVER:
8889 case VIR_DOMAIN_NET_TYPE_CLIENT:
8890 case VIR_DOMAIN_NET_TYPE_MCAST:
8891 case VIR_DOMAIN_NET_TYPE_UDP:
8892 case VIR_DOMAIN_NET_TYPE_INTERNAL:
8893 case VIR_DOMAIN_NET_TYPE_HOSTDEV:
8894 case VIR_DOMAIN_NET_TYPE_LAST:
8895 /* These types don't use a network device on the host, but
8896 * instead use some other type of connection to the emulated
8897 * device in the qemu process.
8899 * (Note that hostdev can't be considered as "using a network
8900 * device", because by the time it is being used, it has been
8901 * detached from the hostside network driver so it doesn't show
8902 * up in the list of interfaces on the host - it's just some
8903 * PCI device.)
8905 break;
8908 /* Set bandwidth or warn if requested and not supported. */
8909 actualBandwidth = virDomainNetGetActualBandwidth(net);
8910 if (actualBandwidth) {
8911 if (virNetDevSupportBandwidth(actualType)) {
8912 if (virNetDevBandwidthSet(net->ifname, actualBandwidth, false,
8913 !virDomainNetTypeSharesHostView(net)) < 0)
8914 goto cleanup;
8915 } else {
8916 VIR_WARN("setting bandwidth on interfaces of "
8917 "type '%s' is not implemented yet",
8918 virDomainNetTypeToString(actualType));
8922 if (net->mtu &&
8923 virNetDevSetMTU(net->ifname, net->mtu) < 0)
8924 goto cleanup;
8926 if ((actualType == VIR_DOMAIN_NET_TYPE_NETWORK ||
8927 actualType == VIR_DOMAIN_NET_TYPE_BRIDGE ||
8928 actualType == VIR_DOMAIN_NET_TYPE_ETHERNET ||
8929 actualType == VIR_DOMAIN_NET_TYPE_DIRECT) &&
8930 !standalone) {
8931 /* Attempt to use vhost-net mode for these types of
8932 network device */
8933 vhostfdSize = net->driver.virtio.queues;
8934 if (!vhostfdSize)
8935 vhostfdSize = 1;
8937 if (VIR_ALLOC_N(vhostfd, vhostfdSize) < 0 ||
8938 VIR_ALLOC_N(vhostfdName, vhostfdSize))
8939 goto cleanup;
8941 memset(vhostfd, -1, vhostfdSize * sizeof(vhostfd[0]));
8943 if (qemuInterfaceOpenVhostNet(def, net, vhostfd, &vhostfdSize) < 0)
8944 goto cleanup;
8947 for (i = 0; i < tapfdSize; i++) {
8948 if (qemuSecuritySetTapFDLabel(driver->securityManager,
8949 def, tapfd[i]) < 0)
8950 goto cleanup;
8951 if (virAsprintf(&tapfdName[i], "%d", tapfd[i]) < 0)
8952 goto cleanup;
8953 virCommandPassFD(cmd, tapfd[i],
8954 VIR_COMMAND_PASS_FD_CLOSE_PARENT);
8955 tapfd[i] = -1;
8958 for (i = 0; i < vhostfdSize; i++) {
8959 if (virAsprintf(&vhostfdName[i], "%d", vhostfd[i]) < 0)
8960 goto cleanup;
8961 virCommandPassFD(cmd, vhostfd[i],
8962 VIR_COMMAND_PASS_FD_CLOSE_PARENT);
8963 vhostfd[i] = -1;
8966 if (chardev)
8967 virCommandAddArgList(cmd, "-chardev", chardev, NULL);
8969 if (!(host = qemuBuildHostNetStr(net, driver,
8970 tapfdName, tapfdSize,
8971 vhostfdName, vhostfdSize)))
8972 goto cleanup;
8973 virCommandAddArgList(cmd, "-netdev", host, NULL);
8975 /* Possible combinations:
8977 * Old way: -netdev type=tap,id=netdev1 \
8978 * -net nic,model=e1000,netdev=netdev1
8979 * New way: -netdev type=tap,id=netdev1 -device e1000,id=netdev1
8981 if (qemuDomainSupportsNicdev(def, net)) {
8982 if (qemuCommandAddExtDevice(cmd, &net->info) < 0)
8983 goto cleanup;
8985 if (!(nic = qemuBuildNicDevStr(def, net, bootindex,
8986 net->driver.virtio.queues, qemuCaps)))
8987 goto cleanup;
8988 virCommandAddArgList(cmd, "-device", nic, NULL);
8989 } else if (!requireNicdev) {
8990 if (qemuCommandAddExtDevice(cmd, &net->info) < 0)
8991 goto cleanup;
8993 if (!(nic = qemuBuildLegacyNicStr(net)))
8994 goto cleanup;
8995 virCommandAddArgList(cmd, "-net", nic, NULL);
8996 } else {
8997 virReportError(VIR_ERR_INTERNAL_ERROR,
8998 "%s", _("Nicdev support unavailable"));
8999 goto cleanup;
9002 ret = 0;
9003 cleanup:
9004 if (ret < 0) {
9005 virErrorPtr saved_err = virSaveLastError();
9006 virDomainConfNWFilterTeardown(net);
9007 virSetError(saved_err);
9008 virFreeError(saved_err);
9010 for (i = 0; vhostfd && i < vhostfdSize; i++) {
9011 if (ret < 0)
9012 VIR_FORCE_CLOSE(vhostfd[i]);
9013 if (vhostfdName)
9014 VIR_FREE(vhostfdName[i]);
9016 VIR_FREE(vhostfdName);
9017 for (i = 0; tapfd && i < tapfdSize; i++) {
9018 if (ret < 0)
9019 VIR_FORCE_CLOSE(tapfd[i]);
9020 if (tapfdName)
9021 VIR_FREE(tapfdName[i]);
9023 VIR_FREE(tapfdName);
9024 VIR_FREE(vhostfd);
9025 VIR_FREE(tapfd);
9026 VIR_FREE(chardev);
9027 VIR_FREE(host);
9028 VIR_FREE(nic);
9029 return ret;
9033 /* NOTE: Not using const virDomainDef here since eventually a call is made
9034 * into qemuSecuritySetTapFDLabel which calls it's driver
9035 * API domainSetSecurityTapFDLabel that doesn't use the const format.
9037 static int
9038 qemuBuildNetCommandLine(virQEMUDriverPtr driver,
9039 virLogManagerPtr logManager,
9040 virSecurityManagerPtr secManager,
9041 virCommandPtr cmd,
9042 virDomainDefPtr def,
9043 virQEMUCapsPtr qemuCaps,
9044 virNetDevVPortProfileOp vmop,
9045 bool standalone,
9046 size_t *nnicindexes,
9047 int **nicindexes,
9048 unsigned int *bootHostdevNet)
9050 size_t i;
9051 int last_good_net = -1;
9052 virErrorPtr originalError = NULL;
9054 if (def->nnets) {
9055 unsigned int bootNet = 0;
9057 /* convert <boot dev='network'/> to bootindex since we didn't emit -boot n */
9058 for (i = 0; i < def->os.nBootDevs; i++) {
9059 if (def->os.bootDevs[i] == VIR_DOMAIN_BOOT_NET) {
9060 bootNet = i + 1;
9061 break;
9065 for (i = 0; i < def->nnets; i++) {
9066 virDomainNetDefPtr net = def->nets[i];
9068 if (qemuBuildInterfaceCommandLine(driver, logManager, secManager, cmd, def, net,
9069 qemuCaps, bootNet, vmop,
9070 standalone, nnicindexes,
9071 nicindexes) < 0)
9072 goto error;
9074 last_good_net = i;
9075 /* if this interface is a type='hostdev' interface and we
9076 * haven't yet added a "bootindex" parameter to an
9077 * emulated network device, save the bootindex - hostdev
9078 * interface commandlines will be built later on when we
9079 * cycle through all the hostdevs, and we'll use it then.
9081 if (virDomainNetGetActualType(net) == VIR_DOMAIN_NET_TYPE_HOSTDEV &&
9082 *bootHostdevNet == 0) {
9083 *bootHostdevNet = bootNet;
9085 bootNet = 0;
9088 return 0;
9090 error:
9091 /* free up any resources in the network driver
9092 * but don't overwrite the original error */
9093 originalError = virSaveLastError();
9094 for (i = 0; last_good_net != -1 && i <= last_good_net; i++)
9095 virDomainConfNWFilterTeardown(def->nets[i]);
9096 virSetError(originalError);
9097 virFreeError(originalError);
9098 return -1;
9102 static const char *
9103 qemuBuildSmartcardFindCCIDController(const virDomainDef *def,
9104 const virDomainSmartcardDef *smartcard)
9106 size_t i;
9108 /* Should never happen. But doesn't hurt to check. */
9109 if (smartcard->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID)
9110 return NULL;
9112 for (i = 0; i < def->ncontrollers; i++) {
9113 const virDomainControllerDef *tmp = def->controllers[i];
9115 if (tmp->type != VIR_DOMAIN_CONTROLLER_TYPE_CCID)
9116 continue;
9118 if (tmp->idx != smartcard->info.addr.ccid.controller)
9119 continue;
9121 return tmp->info.alias;
9124 return NULL;
9128 static int
9129 qemuBuildSmartcardCommandLine(virLogManagerPtr logManager,
9130 virSecurityManagerPtr secManager,
9131 virCommandPtr cmd,
9132 virQEMUDriverConfigPtr cfg,
9133 const virDomainDef *def,
9134 virQEMUCapsPtr qemuCaps,
9135 bool chardevStdioLogd)
9137 size_t i;
9138 virDomainSmartcardDefPtr smartcard;
9139 char *devstr;
9140 virBuffer opt = VIR_BUFFER_INITIALIZER;
9141 const char *database;
9142 const char *contAlias = NULL;
9143 unsigned int cdevflags = QEMU_BUILD_CHARDEV_TCP_NOWAIT |
9144 QEMU_BUILD_CHARDEV_UNIX_FD_PASS;
9145 if (chardevStdioLogd)
9146 cdevflags |= QEMU_BUILD_CHARDEV_FILE_LOGD;
9148 if (!def->nsmartcards)
9149 return 0;
9151 smartcard = def->smartcards[0];
9153 /* -device usb-ccid was already emitted along with other
9154 * controllers. For now, qemu handles only one smartcard. */
9155 if (def->nsmartcards > 1 ||
9156 smartcard->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID ||
9157 smartcard->info.addr.ccid.controller != 0 ||
9158 smartcard->info.addr.ccid.slot != 0) {
9159 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9160 _("this QEMU binary lacks multiple smartcard "
9161 "support"));
9162 virBufferFreeAndReset(&opt);
9163 return -1;
9166 switch (smartcard->type) {
9167 case VIR_DOMAIN_SMARTCARD_TYPE_HOST:
9168 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_CCID_EMULATED)) {
9169 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9170 _("this QEMU binary lacks smartcard host "
9171 "mode support"));
9172 return -1;
9175 virBufferAddLit(&opt, "ccid-card-emulated,backend=nss-emulated");
9176 break;
9178 case VIR_DOMAIN_SMARTCARD_TYPE_HOST_CERTIFICATES:
9179 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_CCID_EMULATED)) {
9180 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9181 _("this QEMU binary lacks smartcard host "
9182 "mode support"));
9183 return -1;
9186 virBufferAddLit(&opt, "ccid-card-emulated,backend=certificates");
9187 for (i = 0; i < VIR_DOMAIN_SMARTCARD_NUM_CERTIFICATES; i++) {
9188 virBufferAsprintf(&opt, ",cert%zu=", i + 1);
9189 virQEMUBuildBufferEscapeComma(&opt, smartcard->data.cert.file[i]);
9191 if (smartcard->data.cert.database) {
9192 database = smartcard->data.cert.database;
9193 } else {
9194 database = VIR_DOMAIN_SMARTCARD_DEFAULT_DATABASE;
9196 virBufferAddLit(&opt, ",db=");
9197 virQEMUBuildBufferEscapeComma(&opt, database);
9198 break;
9200 case VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH:
9201 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_CCID_PASSTHRU)) {
9202 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9203 _("this QEMU binary lacks smartcard "
9204 "passthrough mode support"));
9205 return -1;
9208 if (!(devstr = qemuBuildChrChardevStr(logManager, secManager,
9209 cmd, cfg, def,
9210 smartcard->data.passthru,
9211 smartcard->info.alias,
9212 qemuCaps, cdevflags))) {
9213 virBufferFreeAndReset(&opt);
9214 return -1;
9216 virCommandAddArg(cmd, "-chardev");
9217 virCommandAddArg(cmd, devstr);
9218 VIR_FREE(devstr);
9220 virBufferAsprintf(&opt, "ccid-card-passthru,chardev=char%s",
9221 smartcard->info.alias);
9222 break;
9224 default:
9225 virReportError(VIR_ERR_INTERNAL_ERROR,
9226 _("unexpected smartcard type %d"),
9227 smartcard->type);
9228 virBufferFreeAndReset(&opt);
9229 return -1;
9232 if (!(contAlias = qemuBuildSmartcardFindCCIDController(def,
9233 smartcard))) {
9234 virReportError(VIR_ERR_INTERNAL_ERROR,
9235 _("Unable to find controller for %s"),
9236 smartcard->info.alias);
9237 return -1;
9240 virCommandAddArg(cmd, "-device");
9241 virBufferAsprintf(&opt, ",id=%s,bus=%s.0", smartcard->info.alias, contAlias);
9242 virCommandAddArgBuffer(cmd, &opt);
9244 return 0;
9248 static char *
9249 qemuBuildShmemDevLegacyStr(virDomainDefPtr def,
9250 virDomainShmemDefPtr shmem,
9251 virQEMUCapsPtr qemuCaps)
9253 virBuffer buf = VIR_BUFFER_INITIALIZER;
9255 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_IVSHMEM)) {
9256 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9257 _("ivshmem device is not supported "
9258 "with this QEMU binary"));
9259 return NULL;
9262 virBufferAddLit(&buf, "ivshmem");
9263 virBufferAsprintf(&buf, ",id=%s", shmem->info.alias);
9265 if (shmem->size)
9266 virBufferAsprintf(&buf, ",size=%llum", shmem->size >> 20);
9268 if (!shmem->server.enabled) {
9269 virBufferAsprintf(&buf, ",shm=%s", shmem->name);
9270 } else {
9271 virBufferAsprintf(&buf, ",chardev=char%s", shmem->info.alias);
9272 if (shmem->msi.enabled) {
9273 virBufferAddLit(&buf, ",msi=on");
9274 if (shmem->msi.vectors)
9275 virBufferAsprintf(&buf, ",vectors=%u", shmem->msi.vectors);
9276 if (shmem->msi.ioeventfd)
9277 virBufferAsprintf(&buf, ",ioeventfd=%s",
9278 virTristateSwitchTypeToString(shmem->msi.ioeventfd));
9282 if (qemuBuildDeviceAddressStr(&buf, def, &shmem->info, qemuCaps) < 0)
9283 goto error;
9285 if (virBufferCheckError(&buf) < 0)
9286 goto error;
9288 return virBufferContentAndReset(&buf);
9290 error:
9291 virBufferFreeAndReset(&buf);
9292 return NULL;
9295 char *
9296 qemuBuildShmemDevStr(virDomainDefPtr def,
9297 virDomainShmemDefPtr shmem,
9298 virQEMUCapsPtr qemuCaps)
9300 virBuffer buf = VIR_BUFFER_INITIALIZER;
9302 if ((shmem->model == VIR_DOMAIN_SHMEM_MODEL_IVSHMEM_PLAIN &&
9303 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_IVSHMEM_PLAIN)) ||
9304 (shmem->model == VIR_DOMAIN_SHMEM_MODEL_IVSHMEM_DOORBELL &&
9305 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_IVSHMEM_DOORBELL))) {
9306 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9307 _("shmem model '%s' is not supported "
9308 "by this QEMU binary"),
9309 virDomainShmemModelTypeToString(shmem->model));
9310 return NULL;
9313 virBufferAdd(&buf, virDomainShmemModelTypeToString(shmem->model), -1);
9314 virBufferAsprintf(&buf, ",id=%s", shmem->info.alias);
9316 if (shmem->server.enabled)
9317 virBufferAsprintf(&buf, ",chardev=char%s", shmem->info.alias);
9318 else
9319 virBufferAsprintf(&buf, ",memdev=shmmem-%s", shmem->info.alias);
9321 if (shmem->msi.vectors)
9322 virBufferAsprintf(&buf, ",vectors=%u", shmem->msi.vectors);
9323 if (shmem->msi.ioeventfd) {
9324 virBufferAsprintf(&buf, ",ioeventfd=%s",
9325 virTristateSwitchTypeToString(shmem->msi.ioeventfd));
9328 if (qemuBuildDeviceAddressStr(&buf, def, &shmem->info, qemuCaps) < 0) {
9329 virBufferFreeAndReset(&buf);
9330 return NULL;
9333 if (virBufferCheckError(&buf) < 0)
9334 return NULL;
9336 return virBufferContentAndReset(&buf);
9340 virJSONValuePtr
9341 qemuBuildShmemBackendMemProps(virDomainShmemDefPtr shmem)
9343 char *mem_alias = NULL;
9344 char *mem_path = NULL;
9345 virJSONValuePtr ret = NULL;
9347 if (virAsprintf(&mem_path, "/dev/shm/%s", shmem->name) < 0)
9348 return NULL;
9350 if (virAsprintf(&mem_alias, "shmmem-%s", shmem->info.alias) < 0)
9351 goto cleanup;
9353 qemuMonitorCreateObjectProps(&ret, "memory-backend-file", mem_alias,
9354 "s:mem-path", mem_path,
9355 "U:size", shmem->size,
9356 "b:share", true,
9357 NULL);
9359 cleanup:
9360 VIR_FREE(mem_alias);
9361 VIR_FREE(mem_path);
9362 return ret;
9366 static int
9367 qemuBuildShmemCommandLine(virLogManagerPtr logManager,
9368 virSecurityManagerPtr secManager,
9369 virCommandPtr cmd,
9370 virQEMUDriverConfigPtr cfg,
9371 virDomainDefPtr def,
9372 virDomainShmemDefPtr shmem,
9373 virQEMUCapsPtr qemuCaps,
9374 bool chardevStdioLogd)
9376 virJSONValuePtr memProps = NULL;
9377 virBuffer buf = VIR_BUFFER_INITIALIZER;
9378 char *devstr = NULL;
9379 int rc;
9380 unsigned int cdevflags = QEMU_BUILD_CHARDEV_TCP_NOWAIT |
9381 QEMU_BUILD_CHARDEV_UNIX_FD_PASS;
9382 if (chardevStdioLogd)
9383 cdevflags |= QEMU_BUILD_CHARDEV_FILE_LOGD;
9385 if (shmem->size) {
9387 * Thanks to our parsing code, we have a guarantee that the
9388 * size is power of two and is at least a mebibyte in size.
9389 * But because it may change in the future, the checks are
9390 * doubled in here.
9392 if (shmem->size & (shmem->size - 1)) {
9393 virReportError(VIR_ERR_XML_ERROR, "%s",
9394 _("shmem size must be a power of two"));
9395 return -1;
9397 if (shmem->size < 1024 * 1024) {
9398 virReportError(VIR_ERR_XML_ERROR, "%s",
9399 _("shmem size must be at least 1 MiB (1024 KiB)"));
9400 return -1;
9404 if (shmem->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
9405 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9406 _("only 'pci' addresses are supported for the "
9407 "shared memory device"));
9408 return -1;
9411 switch ((virDomainShmemModel)shmem->model) {
9412 case VIR_DOMAIN_SHMEM_MODEL_IVSHMEM:
9413 devstr = qemuBuildShmemDevLegacyStr(def, shmem, qemuCaps);
9414 break;
9416 case VIR_DOMAIN_SHMEM_MODEL_IVSHMEM_PLAIN:
9417 if (!(memProps = qemuBuildShmemBackendMemProps(shmem)))
9418 return -1;
9420 rc = virQEMUBuildObjectCommandlineFromJSON(&buf, memProps);
9421 virJSONValueFree(memProps);
9423 if (rc < 0)
9424 return -1;
9426 virCommandAddArg(cmd, "-object");
9427 virCommandAddArgBuffer(cmd, &buf);
9429 ATTRIBUTE_FALLTHROUGH;
9430 case VIR_DOMAIN_SHMEM_MODEL_IVSHMEM_DOORBELL:
9431 devstr = qemuBuildShmemDevStr(def, shmem, qemuCaps);
9432 break;
9434 case VIR_DOMAIN_SHMEM_MODEL_LAST:
9435 break;
9438 if (!devstr)
9439 return -1;
9441 if (qemuCommandAddExtDevice(cmd, &shmem->info) < 0) {
9442 VIR_FREE(devstr);
9443 return -1;
9446 virCommandAddArgList(cmd, "-device", devstr, NULL);
9447 VIR_FREE(devstr);
9449 if (shmem->server.enabled) {
9450 devstr = qemuBuildChrChardevStr(logManager, secManager,
9451 cmd, cfg, def,
9452 &shmem->server.chr,
9453 shmem->info.alias, qemuCaps,
9454 cdevflags);
9455 if (!devstr)
9456 return -1;
9458 virCommandAddArgList(cmd, "-chardev", devstr, NULL);
9459 VIR_FREE(devstr);
9462 return 0;
9466 static virQEMUCapsFlags
9467 qemuChrSerialTargetModelToCaps(virDomainChrSerialTargetModel targetModel)
9469 switch (targetModel) {
9470 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_ISA_SERIAL:
9471 return QEMU_CAPS_DEVICE_ISA_SERIAL;
9472 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_USB_SERIAL:
9473 return QEMU_CAPS_DEVICE_USB_SERIAL;
9474 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_PCI_SERIAL:
9475 return QEMU_CAPS_DEVICE_PCI_SERIAL;
9476 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SPAPR_VTY:
9477 return QEMU_CAPS_DEVICE_SPAPR_VTY;
9478 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SCLPCONSOLE:
9479 return QEMU_CAPS_DEVICE_SCLPCONSOLE;
9480 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SCLPLMCONSOLE:
9481 return QEMU_CAPS_DEVICE_SCLPLMCONSOLE;
9482 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_PL011:
9483 return QEMU_CAPS_DEVICE_PL011;
9484 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_16550A:
9485 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_NONE:
9486 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_LAST:
9487 break;
9490 return 0;
9494 static int
9495 qemuBuildChrDeviceCommandLine(virCommandPtr cmd,
9496 const virDomainDef *def,
9497 virDomainChrDefPtr chr,
9498 virQEMUCapsPtr qemuCaps)
9500 char *devstr = NULL;
9502 if (qemuBuildChrDeviceStr(&devstr, def, chr, qemuCaps) < 0)
9503 return -1;
9505 virCommandAddArgList(cmd, "-device", devstr, NULL);
9506 VIR_FREE(devstr);
9507 return 0;
9511 static bool
9512 qemuChrIsPlatformDevice(const virDomainDef *def,
9513 virDomainChrDefPtr chr)
9515 if (def->os.arch == VIR_ARCH_ARMV6L ||
9516 def->os.arch == VIR_ARCH_ARMV7L ||
9517 def->os.arch == VIR_ARCH_AARCH64) {
9519 /* pl011 (used on mach-virt) is a platform device */
9520 if (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL &&
9521 chr->targetType == VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SYSTEM &&
9522 chr->targetModel == VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_PL011) {
9523 return true;
9527 if (ARCH_IS_RISCV(def->os.arch)) {
9529 /* 16550a (used by riscv/virt guests) is a platform device */
9530 if (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL &&
9531 chr->targetType == VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SYSTEM &&
9532 chr->targetModel == VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_16550A) {
9533 return true;
9537 /* If we got all the way here and we're still stuck with the default
9538 * target type for a serial device, it means we have no clue what kind of
9539 * device we're talking about and we must treat it as a platform device. */
9540 if (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL &&
9541 chr->targetType == VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_NONE) {
9542 return true;
9545 return false;
9549 static int
9550 qemuBuildSerialCommandLine(virLogManagerPtr logManager,
9551 virSecurityManagerPtr secManager,
9552 virCommandPtr cmd,
9553 virQEMUDriverConfigPtr cfg,
9554 const virDomainDef *def,
9555 virQEMUCapsPtr qemuCaps,
9556 bool chardevStdioLogd)
9558 size_t i;
9559 bool havespice = false;
9560 unsigned int cdevflags = QEMU_BUILD_CHARDEV_TCP_NOWAIT |
9561 QEMU_BUILD_CHARDEV_UNIX_FD_PASS;
9562 if (chardevStdioLogd)
9563 cdevflags |= QEMU_BUILD_CHARDEV_FILE_LOGD;
9565 if (def->nserials) {
9566 for (i = 0; i < def->ngraphics && !havespice; i++) {
9567 if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE)
9568 havespice = true;
9572 for (i = 0; i < def->nserials; i++) {
9573 virDomainChrDefPtr serial = def->serials[i];
9574 char *devstr;
9576 if (serial->source->type == VIR_DOMAIN_CHR_TYPE_SPICEPORT && !havespice)
9577 continue;
9579 if (!(devstr = qemuBuildChrChardevStr(logManager, secManager,
9580 cmd, cfg, def,
9581 serial->source,
9582 serial->info.alias,
9583 qemuCaps, cdevflags)))
9584 return -1;
9585 virCommandAddArg(cmd, "-chardev");
9586 virCommandAddArg(cmd, devstr);
9587 VIR_FREE(devstr);
9589 /* If the device is not a platform device, build the devstr */
9590 if (!qemuChrIsPlatformDevice(def, serial)) {
9591 if (qemuBuildChrDeviceCommandLine(cmd, def, serial, qemuCaps) < 0)
9592 return -1;
9593 } else {
9594 virQEMUCapsFlags caps;
9596 caps = qemuChrSerialTargetModelToCaps(serial->targetModel);
9598 if (caps && !virQEMUCapsGet(qemuCaps, caps)) {
9599 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9600 _("'%s' is not supported in this QEMU binary"),
9601 virDomainChrSerialTargetModelTypeToString(serial->targetModel));
9602 return -1;
9605 virCommandAddArg(cmd, "-serial");
9606 virCommandAddArgFormat(cmd, "chardev:char%s", serial->info.alias);
9610 return 0;
9614 static int
9615 qemuBuildParallelsCommandLine(virLogManagerPtr logManager,
9616 virSecurityManagerPtr secManager,
9617 virCommandPtr cmd,
9618 virQEMUDriverConfigPtr cfg,
9619 const virDomainDef *def,
9620 virQEMUCapsPtr qemuCaps,
9621 bool chardevStdioLogd)
9623 size_t i;
9624 unsigned int cdevflags = QEMU_BUILD_CHARDEV_TCP_NOWAIT |
9625 QEMU_BUILD_CHARDEV_UNIX_FD_PASS;
9626 if (chardevStdioLogd)
9627 cdevflags |= QEMU_BUILD_CHARDEV_FILE_LOGD;
9629 for (i = 0; i < def->nparallels; i++) {
9630 virDomainChrDefPtr parallel = def->parallels[i];
9631 char *devstr;
9633 if (!(devstr = qemuBuildChrChardevStr(logManager, secManager,
9634 cmd, cfg, def,
9635 parallel->source,
9636 parallel->info.alias,
9637 qemuCaps, cdevflags)))
9638 return -1;
9639 virCommandAddArg(cmd, "-chardev");
9640 virCommandAddArg(cmd, devstr);
9641 VIR_FREE(devstr);
9643 if (qemuBuildChrDeviceCommandLine(cmd, def, parallel,
9644 qemuCaps) < 0)
9645 return -1;
9648 return 0;
9652 static int
9653 qemuBuildChannelsCommandLine(virLogManagerPtr logManager,
9654 virSecurityManagerPtr secManager,
9655 virCommandPtr cmd,
9656 virQEMUDriverConfigPtr cfg,
9657 const virDomainDef *def,
9658 virQEMUCapsPtr qemuCaps,
9659 bool chardevStdioLogd)
9661 size_t i;
9662 unsigned int cdevflags = QEMU_BUILD_CHARDEV_TCP_NOWAIT |
9663 QEMU_BUILD_CHARDEV_UNIX_FD_PASS;
9664 if (chardevStdioLogd)
9665 cdevflags |= QEMU_BUILD_CHARDEV_FILE_LOGD;
9667 for (i = 0; i < def->nchannels; i++) {
9668 virDomainChrDefPtr channel = def->channels[i];
9669 char *devstr;
9671 switch (channel->targetType) {
9672 case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_GUESTFWD:
9673 if (!(devstr = qemuBuildChrChardevStr(logManager, secManager,
9674 cmd, cfg, def,
9675 channel->source,
9676 channel->info.alias,
9677 qemuCaps, cdevflags)))
9678 return -1;
9679 virCommandAddArg(cmd, "-chardev");
9680 virCommandAddArg(cmd, devstr);
9681 VIR_FREE(devstr);
9683 if (qemuBuildChrDeviceStr(&devstr, def, channel, qemuCaps) < 0)
9684 return -1;
9685 virCommandAddArgList(cmd, "-netdev", devstr, NULL);
9686 VIR_FREE(devstr);
9687 break;
9689 case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO:
9690 if (!(devstr = qemuBuildChrChardevStr(logManager, secManager,
9691 cmd, cfg, def,
9692 channel->source,
9693 channel->info.alias,
9694 qemuCaps, cdevflags)))
9695 return -1;
9696 virCommandAddArg(cmd, "-chardev");
9697 virCommandAddArg(cmd, devstr);
9698 VIR_FREE(devstr);
9700 if (qemuBuildChrDeviceCommandLine(cmd, def, channel, qemuCaps) < 0)
9701 return -1;
9702 break;
9706 return 0;
9710 static int
9711 qemuBuildConsoleCommandLine(virLogManagerPtr logManager,
9712 virSecurityManagerPtr secManager,
9713 virCommandPtr cmd,
9714 virQEMUDriverConfigPtr cfg,
9715 const virDomainDef *def,
9716 virQEMUCapsPtr qemuCaps,
9717 bool chardevStdioLogd)
9719 size_t i;
9720 unsigned int cdevflags = QEMU_BUILD_CHARDEV_TCP_NOWAIT |
9721 QEMU_BUILD_CHARDEV_UNIX_FD_PASS;
9722 if (chardevStdioLogd)
9723 cdevflags |= QEMU_BUILD_CHARDEV_FILE_LOGD;
9725 /* Explicit console devices */
9726 for (i = 0; i < def->nconsoles; i++) {
9727 virDomainChrDefPtr console = def->consoles[i];
9728 char *devstr;
9730 switch (console->targetType) {
9731 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SCLP:
9732 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_SCLPCONSOLE)) {
9733 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9734 _("sclpconsole is not supported in this QEMU binary"));
9735 return -1;
9738 if (!(devstr = qemuBuildChrChardevStr(logManager, secManager,
9739 cmd, cfg, def,
9740 console->source,
9741 console->info.alias,
9742 qemuCaps, cdevflags)))
9743 return -1;
9744 virCommandAddArg(cmd, "-chardev");
9745 virCommandAddArg(cmd, devstr);
9746 VIR_FREE(devstr);
9748 if (qemuBuildChrDeviceCommandLine(cmd, def, console, qemuCaps) < 0)
9749 return -1;
9750 break;
9752 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SCLPLM:
9753 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_SCLPLMCONSOLE)) {
9754 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9755 _("sclplmconsole is not supported in this QEMU binary"));
9756 return -1;
9759 if (!(devstr = qemuBuildChrChardevStr(logManager, secManager,
9760 cmd, cfg, def,
9761 console->source,
9762 console->info.alias,
9763 qemuCaps, cdevflags)))
9764 return -1;
9765 virCommandAddArg(cmd, "-chardev");
9766 virCommandAddArg(cmd, devstr);
9767 VIR_FREE(devstr);
9769 if (qemuBuildChrDeviceCommandLine(cmd, def, console, qemuCaps) < 0)
9770 return -1;
9771 break;
9773 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_VIRTIO:
9774 if (!(devstr = qemuBuildChrChardevStr(logManager, secManager,
9775 cmd, cfg, def,
9776 console->source,
9777 console->info.alias,
9778 qemuCaps, cdevflags)))
9779 return -1;
9780 virCommandAddArg(cmd, "-chardev");
9781 virCommandAddArg(cmd, devstr);
9782 VIR_FREE(devstr);
9784 if (qemuBuildChrDeviceCommandLine(cmd, def, console, qemuCaps) < 0)
9785 return -1;
9786 break;
9788 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL:
9789 break;
9791 default:
9792 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9793 _("unsupported console target type %s"),
9794 NULLSTR(virDomainChrConsoleTargetTypeToString(console->targetType)));
9795 return -1;
9799 return 0;
9803 char *
9804 qemuBuildRedirdevDevStr(const virDomainDef *def,
9805 virDomainRedirdevDefPtr dev,
9806 virQEMUCapsPtr qemuCaps)
9808 size_t i;
9809 virBuffer buf = VIR_BUFFER_INITIALIZER;
9810 virDomainRedirFilterDefPtr redirfilter = def->redirfilter;
9812 if (dev->bus != VIR_DOMAIN_REDIRDEV_BUS_USB) {
9813 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9814 _("Redirection bus %s is not supported by QEMU"),
9815 virDomainRedirdevBusTypeToString(dev->bus));
9816 goto error;
9819 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_USB_REDIR)) {
9820 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9821 _("USB redirection is not supported "
9822 "by this version of QEMU"));
9823 goto error;
9826 virBufferAsprintf(&buf, "usb-redir,chardev=char%s,id=%s",
9827 dev->info.alias, dev->info.alias);
9829 if (redirfilter && redirfilter->nusbdevs) {
9830 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_USB_REDIR_FILTER)) {
9831 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9832 _("USB redirection filter is not "
9833 "supported by this version of QEMU"));
9834 goto error;
9837 virBufferAddLit(&buf, ",filter=");
9839 for (i = 0; i < redirfilter->nusbdevs; i++) {
9840 virDomainRedirFilterUSBDevDefPtr usbdev = redirfilter->usbdevs[i];
9841 if (usbdev->usbClass >= 0)
9842 virBufferAsprintf(&buf, "0x%02X:", usbdev->usbClass);
9843 else
9844 virBufferAddLit(&buf, "-1:");
9846 if (usbdev->vendor >= 0)
9847 virBufferAsprintf(&buf, "0x%04X:", usbdev->vendor);
9848 else
9849 virBufferAddLit(&buf, "-1:");
9851 if (usbdev->product >= 0)
9852 virBufferAsprintf(&buf, "0x%04X:", usbdev->product);
9853 else
9854 virBufferAddLit(&buf, "-1:");
9856 if (usbdev->version >= 0)
9857 virBufferAsprintf(&buf, "0x%04X:", usbdev->version);
9858 else
9859 virBufferAddLit(&buf, "-1:");
9861 virBufferAsprintf(&buf, "%u", usbdev->allow);
9862 if (i < redirfilter->nusbdevs -1)
9863 virBufferAddLit(&buf, "|");
9867 if (dev->info.bootIndex)
9868 virBufferAsprintf(&buf, ",bootindex=%u", dev->info.bootIndex);
9870 if (qemuBuildDeviceAddressStr(&buf, def, &dev->info, qemuCaps) < 0)
9871 goto error;
9873 if (virBufferCheckError(&buf) < 0)
9874 goto error;
9876 return virBufferContentAndReset(&buf);
9878 error:
9879 virBufferFreeAndReset(&buf);
9880 return NULL;
9884 static int
9885 qemuBuildRedirdevCommandLine(virLogManagerPtr logManager,
9886 virSecurityManagerPtr secManager,
9887 virCommandPtr cmd,
9888 virQEMUDriverConfigPtr cfg,
9889 const virDomainDef *def,
9890 virQEMUCapsPtr qemuCaps,
9891 bool chardevStdioLogd)
9893 size_t i;
9894 unsigned int cdevflags = QEMU_BUILD_CHARDEV_TCP_NOWAIT |
9895 QEMU_BUILD_CHARDEV_UNIX_FD_PASS;
9896 if (chardevStdioLogd)
9897 cdevflags |= QEMU_BUILD_CHARDEV_FILE_LOGD;
9899 for (i = 0; i < def->nredirdevs; i++) {
9900 virDomainRedirdevDefPtr redirdev = def->redirdevs[i];
9901 char *devstr;
9903 if (!(devstr = qemuBuildChrChardevStr(logManager, secManager,
9904 cmd, cfg, def,
9905 redirdev->source,
9906 redirdev->info.alias,
9907 qemuCaps, cdevflags))) {
9908 return -1;
9911 virCommandAddArg(cmd, "-chardev");
9912 virCommandAddArg(cmd, devstr);
9913 VIR_FREE(devstr);
9915 virCommandAddArg(cmd, "-device");
9916 if (!(devstr = qemuBuildRedirdevDevStr(def, redirdev, qemuCaps)))
9917 return -1;
9918 virCommandAddArg(cmd, devstr);
9919 VIR_FREE(devstr);
9922 return 0;
9926 static void
9927 qemuBuildDomainLoaderCommandLine(virCommandPtr cmd,
9928 virDomainDefPtr def)
9930 virDomainLoaderDefPtr loader = def->os.loader;
9931 virBuffer buf = VIR_BUFFER_INITIALIZER;
9932 int unit = 0;
9934 if (!loader)
9935 return;
9937 switch ((virDomainLoader) loader->type) {
9938 case VIR_DOMAIN_LOADER_TYPE_ROM:
9939 virCommandAddArg(cmd, "-bios");
9940 virCommandAddArg(cmd, loader->path);
9941 break;
9943 case VIR_DOMAIN_LOADER_TYPE_PFLASH:
9945 if (loader->secure == VIR_TRISTATE_BOOL_YES) {
9946 virCommandAddArgList(cmd,
9947 "-global",
9948 "driver=cfi.pflash01,property=secure,value=on",
9949 NULL);
9952 virBufferAddLit(&buf, "file=");
9953 virQEMUBuildBufferEscapeComma(&buf, loader->path);
9954 virBufferAsprintf(&buf, ",if=pflash,format=raw,unit=%d", unit);
9955 unit++;
9957 if (loader->readonly) {
9958 virBufferAsprintf(&buf, ",readonly=%s",
9959 virTristateSwitchTypeToString(loader->readonly));
9962 virCommandAddArg(cmd, "-drive");
9963 virCommandAddArgBuffer(cmd, &buf);
9965 if (loader->nvram) {
9966 virBufferFreeAndReset(&buf);
9967 virBufferAddLit(&buf, "file=");
9968 virQEMUBuildBufferEscapeComma(&buf, loader->nvram);
9969 virBufferAsprintf(&buf, ",if=pflash,format=raw,unit=%d", unit);
9971 virCommandAddArg(cmd, "-drive");
9972 virCommandAddArgBuffer(cmd, &buf);
9974 break;
9976 case VIR_DOMAIN_LOADER_TYPE_NONE:
9977 case VIR_DOMAIN_LOADER_TYPE_LAST:
9978 /* nada */
9979 break;
9982 virBufferFreeAndReset(&buf);
9986 static char *
9987 qemuBuildTPMDevStr(const virDomainDef *def,
9988 virQEMUCapsPtr qemuCaps)
9990 virBuffer buf = VIR_BUFFER_INITIALIZER;
9991 const virDomainTPMDef *tpm = def->tpm;
9992 const char *model = virDomainTPMModelTypeToString(tpm->model);
9993 virQEMUCapsFlags flag;
9995 switch (tpm->model) {
9996 case VIR_DOMAIN_TPM_MODEL_TIS:
9997 flag = QEMU_CAPS_DEVICE_TPM_TIS;
9998 break;
9999 case VIR_DOMAIN_TPM_MODEL_CRB:
10000 flag = QEMU_CAPS_DEVICE_TPM_CRB;
10001 break;
10002 case VIR_DOMAIN_TPM_MODEL_LAST:
10003 default:
10004 virReportEnumRangeError(virDomainTPMModel, tpm->model);
10005 goto error;
10008 if (!virQEMUCapsGet(qemuCaps, flag)) {
10009 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10010 _("The QEMU executable %s does not support TPM "
10011 "model %s"),
10012 def->emulator, model);
10013 goto error;
10016 virBufferAsprintf(&buf, "%s,tpmdev=tpm-%s,id=%s",
10017 model, tpm->info.alias, tpm->info.alias);
10019 if (virBufferCheckError(&buf) < 0)
10020 goto error;
10022 return virBufferContentAndReset(&buf);
10024 error:
10025 virBufferFreeAndReset(&buf);
10026 return NULL;
10030 /* this function is exported so that tests can mock the FDs */
10032 qemuBuildTPMOpenBackendFDs(const char *tpmdev,
10033 const char *cancel_path,
10034 int *tpmfd,
10035 int *cancelfd)
10037 if ((*tpmfd = open(tpmdev, O_RDWR)) < 0) {
10038 virReportSystemError(errno, _("Could not open TPM device %s"),
10039 tpmdev);
10040 return -1;
10043 if ((*cancelfd = open(cancel_path, O_WRONLY)) < 0) {
10044 virReportSystemError(errno,
10045 _("Could not open TPM device's cancel "
10046 "path %s"), cancel_path);
10047 VIR_FORCE_CLOSE(*tpmfd);
10048 return -1;
10051 return 0;
10055 static char *
10056 qemuBuildTPMBackendStr(const virDomainDef *def,
10057 virCommandPtr cmd,
10058 virQEMUCapsPtr qemuCaps,
10059 int *tpmfd,
10060 int *cancelfd,
10061 char **chardev)
10063 const virDomainTPMDef *tpm = def->tpm;
10064 virBuffer buf = VIR_BUFFER_INITIALIZER;
10065 const char *type = NULL;
10066 char *cancel_path = NULL;
10067 char *devset = NULL;
10068 char *cancelset = NULL;
10069 const char *tpmdev;
10071 *tpmfd = -1;
10072 *cancelfd = -1;
10074 switch (tpm->type) {
10075 case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
10076 case VIR_DOMAIN_TPM_TYPE_EMULATOR:
10077 type = virDomainTPMBackendTypeToString(tpm->type);
10078 break;
10079 case VIR_DOMAIN_TPM_TYPE_LAST:
10080 goto error;
10083 virBufferAsprintf(&buf, "%s,id=tpm-%s", type, tpm->info.alias);
10085 switch (tpm->type) {
10086 case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
10087 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_TPM_PASSTHROUGH))
10088 goto no_support;
10090 tpmdev = tpm->data.passthrough.source.data.file.path;
10091 if (!(cancel_path = virTPMCreateCancelPath(tpmdev)))
10092 goto error;
10094 if (qemuBuildTPMOpenBackendFDs(tpmdev, cancel_path, tpmfd, cancelfd) < 0)
10095 goto error;
10097 virCommandPassFD(cmd, *tpmfd, VIR_COMMAND_PASS_FD_CLOSE_PARENT);
10098 virCommandPassFD(cmd, *cancelfd, VIR_COMMAND_PASS_FD_CLOSE_PARENT);
10100 if (!(devset = qemuVirCommandGetDevSet(cmd, *tpmfd)) ||
10101 !(cancelset = qemuVirCommandGetDevSet(cmd, *cancelfd)))
10102 goto error;
10104 virBufferAddLit(&buf, ",path=");
10105 virQEMUBuildBufferEscapeComma(&buf, devset);
10107 virBufferAddLit(&buf, ",cancel-path=");
10108 virQEMUBuildBufferEscapeComma(&buf, cancelset);
10110 VIR_FREE(devset);
10111 VIR_FREE(cancelset);
10112 VIR_FREE(cancel_path);
10114 break;
10115 case VIR_DOMAIN_TPM_TYPE_EMULATOR:
10116 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_TPM_EMULATOR))
10117 goto no_support;
10119 virBufferAddLit(&buf, ",chardev=chrtpm");
10121 if (virAsprintf(chardev, "socket,id=chrtpm,path=%s",
10122 tpm->data.emulator.source.data.nix.path) < 0)
10123 goto error;
10125 break;
10126 case VIR_DOMAIN_TPM_TYPE_LAST:
10127 goto error;
10130 if (virBufferCheckError(&buf) < 0)
10131 goto error;
10133 return virBufferContentAndReset(&buf);
10135 no_support:
10136 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10137 _("The QEMU executable %s does not support TPM "
10138 "backend type %s"),
10139 def->emulator, type);
10141 error:
10142 VIR_FREE(devset);
10143 VIR_FREE(cancel_path);
10145 virBufferFreeAndReset(&buf);
10146 return NULL;
10150 static int
10151 qemuBuildTPMCommandLine(virCommandPtr cmd,
10152 const virDomainDef *def,
10153 virQEMUCapsPtr qemuCaps)
10155 char *optstr;
10156 char *chardev = NULL;
10157 int tpmfd = -1;
10158 int cancelfd = -1;
10159 char *fdset;
10161 if (!def->tpm)
10162 return 0;
10164 if (!(optstr = qemuBuildTPMBackendStr(def, cmd, qemuCaps,
10165 &tpmfd, &cancelfd,
10166 &chardev)))
10167 return -1;
10169 virCommandAddArgList(cmd, "-tpmdev", optstr, NULL);
10170 VIR_FREE(optstr);
10172 if (chardev) {
10173 virCommandAddArgList(cmd, "-chardev", chardev, NULL);
10174 VIR_FREE(chardev);
10177 if (tpmfd >= 0) {
10178 fdset = qemuVirCommandGetFDSet(cmd, tpmfd);
10179 if (!fdset)
10180 return -1;
10182 virCommandAddArgList(cmd, "-add-fd", fdset, NULL);
10183 VIR_FREE(fdset);
10186 if (cancelfd >= 0) {
10187 fdset = qemuVirCommandGetFDSet(cmd, cancelfd);
10188 if (!fdset)
10189 return -1;
10191 virCommandAddArgList(cmd, "-add-fd", fdset, NULL);
10192 VIR_FREE(fdset);
10195 if (!(optstr = qemuBuildTPMDevStr(def, qemuCaps)))
10196 return -1;
10198 virCommandAddArgList(cmd, "-device", optstr, NULL);
10199 VIR_FREE(optstr);
10201 return 0;
10204 static int
10205 qemuBuildSEVCommandLine(virDomainObjPtr vm, virCommandPtr cmd,
10206 virDomainSEVDefPtr sev)
10208 virBuffer buf = VIR_BUFFER_INITIALIZER;
10209 qemuDomainObjPrivatePtr priv = vm->privateData;
10210 char *path = NULL;
10211 int ret = -1;
10213 if (!sev)
10214 return 0;
10216 VIR_DEBUG("policy=0x%x cbitpos=%d reduced_phys_bits=%d",
10217 sev->policy, sev->cbitpos, sev->reduced_phys_bits);
10219 virBufferAsprintf(&buf, "sev-guest,id=sev0,cbitpos=%d", sev->cbitpos);
10220 virBufferAsprintf(&buf, ",reduced-phys-bits=%d", sev->reduced_phys_bits);
10221 virBufferAsprintf(&buf, ",policy=0x%x", sev->policy);
10223 if (sev->dh_cert) {
10224 if (virAsprintf(&path, "%s/dh_cert.base64", priv->libDir) < 0)
10225 goto cleanup;
10226 virBufferAsprintf(&buf, ",dh-cert-file=%s", path);
10227 VIR_FREE(path);
10230 if (sev->session) {
10231 if (virAsprintf(&path, "%s/session.base64", priv->libDir) < 0)
10232 goto cleanup;
10233 virBufferAsprintf(&buf, ",session-file=%s", path);
10234 VIR_FREE(path);
10237 virCommandAddArg(cmd, "-object");
10238 virCommandAddArgBuffer(cmd, &buf);
10239 ret = 0;
10240 cleanup:
10241 virBufferFreeAndReset(&buf);
10242 return ret;
10245 static int
10246 qemuBuildVMCoreInfoCommandLine(virCommandPtr cmd,
10247 const virDomainDef *def,
10248 virQEMUCapsPtr qemuCaps)
10250 virTristateSwitch vmci = def->features[VIR_DOMAIN_FEATURE_VMCOREINFO];
10252 if (vmci != VIR_TRISTATE_SWITCH_ON)
10253 return 0;
10255 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VMCOREINFO)) {
10256 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10257 _("vmcoreinfo is not available "
10258 "with this QEMU binary"));
10259 return -1;
10262 virCommandAddArgList(cmd, "-device", "vmcoreinfo", NULL);
10263 return 0;
10267 static int
10268 qemuBuildPanicCommandLine(virCommandPtr cmd,
10269 const virDomainDef *def,
10270 virQEMUCapsPtr qemuCaps)
10272 size_t i;
10274 for (i = 0; i < def->npanics; i++) {
10275 switch ((virDomainPanicModel) def->panics[i]->model) {
10276 case VIR_DOMAIN_PANIC_MODEL_S390:
10277 /* For s390 guests, the hardware provides the same
10278 * functionality as the pvpanic device. The address
10279 * cannot be configured by the user */
10280 if (!ARCH_IS_S390(def->os.arch)) {
10281 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10282 _("only S390 guests support "
10283 "panic device of model 's390'"));
10284 return -1;
10286 if (def->panics[i]->info.type !=
10287 VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
10288 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10289 _("setting the panic device address is not "
10290 "supported for model 's390'"));
10291 return -1;
10293 break;
10295 case VIR_DOMAIN_PANIC_MODEL_HYPERV:
10296 /* Panic with model 'hyperv' is not a device, it should
10297 * be configured in cpu commandline. The address
10298 * cannot be configured by the user */
10299 if (!ARCH_IS_X86(def->os.arch)) {
10300 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10301 _("only i686 and x86_64 guests support "
10302 "panic device of model 'hyperv'"));
10303 return -1;
10305 if (def->panics[i]->info.type !=
10306 VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
10307 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10308 _("setting the panic device address is not "
10309 "supported for model 'hyperv'"));
10310 return -1;
10312 break;
10314 case VIR_DOMAIN_PANIC_MODEL_PSERIES:
10315 /* For pSeries guests, the firmware provides the same
10316 * functionality as the pvpanic device. The address
10317 * cannot be configured by the user */
10318 if (!qemuDomainIsPSeries(def)) {
10319 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10320 _("only pSeries guests support panic device "
10321 "of model 'pseries'"));
10322 return -1;
10324 if (def->panics[i]->info.type !=
10325 VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
10326 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10327 _("setting the panic device address is not "
10328 "supported for model 'pseries'"));
10329 return -1;
10331 break;
10333 case VIR_DOMAIN_PANIC_MODEL_ISA:
10334 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_PANIC)) {
10335 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10336 _("the QEMU binary does not support the "
10337 "ISA panic device"));
10338 return -1;
10341 switch (def->panics[i]->info.type) {
10342 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_ISA:
10343 virCommandAddArg(cmd, "-device");
10344 virCommandAddArgFormat(cmd, "pvpanic,ioport=%d",
10345 def->panics[i]->info.addr.isa.iobase);
10346 break;
10348 case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE:
10349 virCommandAddArgList(cmd, "-device", "pvpanic", NULL);
10350 break;
10352 default:
10353 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10354 _("panic is supported only "
10355 "with ISA address type"));
10356 return -1;
10359 /* default model value was changed before in post parse */
10360 case VIR_DOMAIN_PANIC_MODEL_DEFAULT:
10361 case VIR_DOMAIN_PANIC_MODEL_LAST:
10362 break;
10366 return 0;
10370 static virJSONValuePtr
10371 qemuBuildPRManagerInfoPropsInternal(const char *alias,
10372 const char *path)
10374 virJSONValuePtr ret = NULL;
10376 if (qemuMonitorCreateObjectProps(&ret,
10377 "pr-manager-helper", alias,
10378 "s:path", path, NULL) < 0)
10379 return NULL;
10381 return ret;
10386 * qemuBuildPRManagedManagerInfoProps:
10388 * Build the JSON properties for the pr-manager object corresponding to the PR
10389 * daemon managed by libvirt.
10391 virJSONValuePtr
10392 qemuBuildPRManagedManagerInfoProps(qemuDomainObjPrivatePtr priv)
10394 char *path = NULL;
10395 virJSONValuePtr ret = NULL;
10397 if (!(path = qemuDomainGetManagedPRSocketPath(priv)))
10398 return NULL;
10400 ret = qemuBuildPRManagerInfoPropsInternal(qemuDomainGetManagedPRAlias(),
10401 path);
10403 VIR_FREE(path);
10404 return ret;
10409 * qemuBuildPRManagerInfoProps:
10410 * @src: storage source
10412 * Build the JSON properties for the pr-manager object.
10414 virJSONValuePtr
10415 qemuBuildPRManagerInfoProps(virStorageSourcePtr src)
10417 return qemuBuildPRManagerInfoPropsInternal(src->pr->mgralias, src->pr->path);
10421 static int
10422 qemuBuildManagedPRCommandLine(virCommandPtr cmd,
10423 const virDomainDef *def,
10424 qemuDomainObjPrivatePtr priv)
10426 virBuffer buf = VIR_BUFFER_INITIALIZER;
10427 virJSONValuePtr props = NULL;
10428 int ret = -1;
10430 if (!virDomainDefHasManagedPR(def))
10431 return 0;
10433 if (!(props = qemuBuildPRManagedManagerInfoProps(priv)))
10434 return -1;
10436 if (virQEMUBuildObjectCommandlineFromJSON(&buf, props) < 0)
10437 goto cleanup;
10439 virCommandAddArg(cmd, "-object");
10440 virCommandAddArgBuffer(cmd, &buf);
10442 ret = 0;
10443 cleanup:
10444 virBufferFreeAndReset(&buf);
10445 virJSONValueFree(props);
10446 return ret;
10451 * qemuBuildCommandLineValidate:
10453 * Prior to taking the plunge and building a long command line only
10454 * to find some configuration option isn't valid, let's do a couple
10455 * of checks and fail early.
10457 * Returns 0 on success, returns -1 and messages what the issue is.
10459 static int
10460 qemuBuildCommandLineValidate(virQEMUDriverPtr driver,
10461 const virDomainDef *def)
10463 size_t i;
10464 int sdl = 0;
10465 int vnc = 0;
10466 int spice = 0;
10467 int egl_headless = 0;
10469 if (!virQEMUDriverIsPrivileged(driver)) {
10470 /* If we have no cgroups then we can have no tunings that
10471 * require them */
10473 if (virMemoryLimitIsSet(def->mem.hard_limit) ||
10474 virMemoryLimitIsSet(def->mem.soft_limit) ||
10475 virMemoryLimitIsSet(def->mem.swap_hard_limit)) {
10476 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10477 _("Memory tuning is not available in session mode"));
10478 return -1;
10481 if (def->blkio.weight) {
10482 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10483 _("Block I/O tuning is not available in session mode"));
10484 return -1;
10487 if (def->cputune.sharesSpecified || def->cputune.period ||
10488 def->cputune.quota || def->cputune.global_period ||
10489 def->cputune.global_quota || def->cputune.emulator_period ||
10490 def->cputune.emulator_quota || def->cputune.iothread_period ||
10491 def->cputune.iothread_quota) {
10492 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10493 _("CPU tuning is not available in session mode"));
10494 return -1;
10498 for (i = 0; i < def->ngraphics; ++i) {
10499 switch (def->graphics[i]->type) {
10500 case VIR_DOMAIN_GRAPHICS_TYPE_SDL:
10501 ++sdl;
10502 break;
10503 case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
10504 ++vnc;
10505 break;
10506 case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
10507 ++spice;
10508 break;
10509 case VIR_DOMAIN_GRAPHICS_TYPE_EGL_HEADLESS:
10510 ++egl_headless;
10511 break;
10512 case VIR_DOMAIN_GRAPHICS_TYPE_RDP:
10513 case VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP:
10514 case VIR_DOMAIN_GRAPHICS_TYPE_LAST:
10515 break;
10519 if (sdl > 1 || vnc > 1 || spice > 1 || egl_headless > 1) {
10520 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10521 _("only 1 graphics device of each type "
10522 "(sdl, vnc, spice, headless) is supported"));
10523 return -1;
10526 if (def->virtType == VIR_DOMAIN_VIRT_XEN ||
10527 def->os.type == VIR_DOMAIN_OSTYPE_XEN ||
10528 def->os.type == VIR_DOMAIN_OSTYPE_LINUX) {
10529 virReportError(VIR_ERR_INTERNAL_ERROR,
10530 _("qemu emulator '%s' does not support xen"),
10531 def->emulator);
10532 return -1;
10535 return 0;
10539 static int
10540 qemuBuildSeccompSandboxCommandLine(virCommandPtr cmd,
10541 virQEMUDriverConfigPtr cfg,
10542 virQEMUCapsPtr qemuCaps ATTRIBUTE_UNUSED)
10544 if (cfg->seccompSandbox == 0) {
10545 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_SECCOMP_SANDBOX))
10546 virCommandAddArgList(cmd, "-sandbox", "off", NULL);
10547 return 0;
10550 /* Use blacklist by default if supported */
10551 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_SECCOMP_BLACKLIST)) {
10552 virCommandAddArgList(cmd, "-sandbox",
10553 "on,obsolete=deny,elevateprivileges=deny,"
10554 "spawn=deny,resourcecontrol=deny",
10555 NULL);
10556 return 0;
10559 /* Seccomp whitelist is opt-in */
10560 if (cfg->seccompSandbox > 0)
10561 virCommandAddArgList(cmd, "-sandbox", "on", NULL);
10563 return 0;
10568 char *
10569 qemuBuildVsockDevStr(virDomainDefPtr def,
10570 virDomainVsockDefPtr vsock,
10571 virQEMUCapsPtr qemuCaps,
10572 const char *fdprefix)
10574 qemuDomainVsockPrivatePtr priv = (qemuDomainVsockPrivatePtr)vsock->privateData;
10575 virBuffer buf = VIR_BUFFER_INITIALIZER;
10576 char *ret = NULL;
10579 if (qemuBuildVirtioDevStr(&buf, "vhost-vsock", qemuCaps,
10580 VIR_DOMAIN_DEVICE_VSOCK, vsock) < 0) {
10581 goto cleanup;
10584 virBufferAsprintf(&buf, ",id=%s", vsock->info.alias);
10585 virBufferAsprintf(&buf, ",guest-cid=%u", vsock->guest_cid);
10586 virBufferAsprintf(&buf, ",vhostfd=%s%u", fdprefix, priv->vhostfd);
10587 if (qemuBuildDeviceAddressStr(&buf, def, &vsock->info, qemuCaps) < 0)
10588 goto cleanup;
10590 if (virBufferCheckError(&buf) < 0)
10591 goto cleanup;
10593 ret = virBufferContentAndReset(&buf);
10595 cleanup:
10596 virBufferFreeAndReset(&buf);
10597 return ret;
10601 static int
10602 qemuBuildVsockCommandLine(virCommandPtr cmd,
10603 virDomainDefPtr def,
10604 virDomainVsockDefPtr vsock,
10605 virQEMUCapsPtr qemuCaps)
10607 qemuDomainVsockPrivatePtr priv = (qemuDomainVsockPrivatePtr)vsock->privateData;
10608 char *devstr = NULL;
10609 int ret = -1;
10611 if (!(devstr = qemuBuildVsockDevStr(def, vsock, qemuCaps, "")))
10612 goto cleanup;
10614 virCommandPassFD(cmd, priv->vhostfd, VIR_COMMAND_PASS_FD_CLOSE_PARENT);
10615 priv->vhostfd = -1;
10617 if (qemuCommandAddExtDevice(cmd, &vsock->info) < 0)
10618 goto cleanup;
10620 virCommandAddArgList(cmd, "-device", devstr, NULL);
10622 ret = 0;
10623 cleanup:
10624 VIR_FREE(devstr);
10625 return ret;
10630 * Constructs a argv suitable for launching qemu with config defined
10631 * for a given virtual machine.
10633 virCommandPtr
10634 qemuBuildCommandLine(virQEMUDriverPtr driver,
10635 virLogManagerPtr logManager,
10636 virSecurityManagerPtr secManager,
10637 virDomainObjPtr vm,
10638 const char *migrateURI,
10639 virDomainMomentObjPtr snapshot,
10640 virNetDevVPortProfileOp vmop,
10641 bool standalone,
10642 bool enableFips,
10643 size_t *nnicindexes,
10644 int **nicindexes)
10646 size_t i;
10647 char uuid[VIR_UUID_STRING_BUFLEN];
10648 virCommandPtr cmd = NULL;
10649 virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
10650 unsigned int bootHostdevNet = 0;
10651 qemuDomainObjPrivatePtr priv = vm->privateData;
10652 virDomainDefPtr def = vm->def;
10653 virQEMUCapsPtr qemuCaps = priv->qemuCaps;
10654 bool chardevStdioLogd = priv->chardevStdioLogd;
10656 VIR_DEBUG("driver=%p def=%p mon=%p json=%d "
10657 "qemuCaps=%p migrateURI=%s snapshot=%p vmop=%d",
10658 driver, def, priv->monConfig, priv->monJSON,
10659 qemuCaps, migrateURI, snapshot, vmop);
10661 if (qemuBuildCommandLineValidate(driver, def) < 0)
10662 goto error;
10664 cmd = virCommandNew(def->emulator);
10666 virCommandAddEnvPassCommon(cmd);
10668 /* For system QEMU we want to set both HOME and all the XDG variables to
10669 * libDir/qemu otherwise apps QEMU links to might try to access the default
10670 * home dir '/' which would always result in a permission issue.
10672 * For session QEMU, we only want to set XDG_CACHE_HOME as cache data
10673 * may be purged at any time and that should not affect any app. We
10674 * do want VMs to integrate with services in user's session so we're
10675 * not re-setting any other env variables
10677 if (!driver->privileged) {
10678 virCommandAddEnvFormat(cmd, "XDG_CACHE_HOME=%s/%s",
10679 priv->libDir, ".cache");
10680 } else {
10681 virCommandAddEnvPair(cmd, "HOME", priv->libDir);
10682 virCommandAddEnvXDG(cmd, priv->libDir);
10685 if (qemuBuildNameCommandLine(cmd, cfg, def, qemuCaps) < 0)
10686 goto error;
10688 if (!standalone)
10689 virCommandAddArg(cmd, "-S"); /* freeze CPU */
10691 if (qemuBuildMasterKeyCommandLine(cmd, priv) < 0)
10692 goto error;
10694 if (qemuBuildManagedPRCommandLine(cmd, def, priv) < 0)
10695 goto error;
10697 if (enableFips)
10698 virCommandAddArg(cmd, "-enable-fips");
10700 if (qemuBuildMachineCommandLine(cmd, cfg, def, qemuCaps) < 0)
10701 goto error;
10703 qemuBuildTSEGCommandLine(cmd, def);
10705 if (qemuBuildCpuCommandLine(cmd, driver, def, qemuCaps) < 0)
10706 goto error;
10708 qemuBuildDomainLoaderCommandLine(cmd, def);
10710 if (!migrateURI && !snapshot && qemuDomainAlignMemorySizes(def) < 0)
10711 goto error;
10713 if (qemuBuildMemCommandLine(cmd, cfg, def, qemuCaps, priv) < 0)
10714 goto error;
10716 if (qemuBuildSmpCommandLine(cmd, def) < 0)
10717 goto error;
10719 if (qemuBuildIOThreadCommandLine(cmd, def) < 0)
10720 goto error;
10722 if (virDomainNumaGetNodeCount(def->numa) &&
10723 qemuBuildNumaArgStr(cfg, def, cmd, priv) < 0)
10724 goto error;
10726 if (qemuBuildMemoryDeviceCommandLine(cmd, cfg, def, priv) < 0)
10727 goto error;
10729 virUUIDFormat(def->uuid, uuid);
10730 virCommandAddArgList(cmd, "-uuid", uuid, NULL);
10732 if (qemuBuildSmbiosCommandLine(cmd, driver, def) < 0)
10733 goto error;
10735 if (qemuBuildVMGenIDCommandLine(cmd, def, qemuCaps) < 0)
10736 goto error;
10739 * NB, -nographic *MUST* come before any serial, or monitor
10740 * or parallel port flags due to QEMU craziness, where it
10741 * decides to change the serial port & monitor to be on stdout
10742 * if you ask for nographic. So we have to make sure we override
10743 * these defaults ourselves...
10745 if (!def->ngraphics) {
10746 virCommandAddArg(cmd, "-display");
10747 virCommandAddArg(cmd, "none");
10749 if (cfg->nogfxAllowHostAudio)
10750 virCommandAddEnvPassBlockSUID(cmd, "QEMU_AUDIO_DRV", NULL);
10751 else
10752 virCommandAddEnvString(cmd, "QEMU_AUDIO_DRV=none");
10755 /* Disable global config files and default devices */
10756 virCommandAddArg(cmd, "-no-user-config");
10757 virCommandAddArg(cmd, "-nodefaults");
10759 if (qemuBuildSgaCommandLine(cmd, def, qemuCaps) < 0)
10760 goto error;
10762 if (qemuBuildMonitorCommandLine(logManager, secManager, cmd, cfg, def, priv) < 0)
10763 goto error;
10765 if (qemuBuildClockCommandLine(cmd, def, qemuCaps) < 0)
10766 goto error;
10768 if (qemuBuildPMCommandLine(cmd, def, priv) < 0)
10769 goto error;
10771 if (qemuBuildBootCommandLine(cmd, def, qemuCaps) < 0)
10772 goto error;
10774 if (qemuBuildIOMMUCommandLine(cmd, def, qemuCaps) < 0)
10775 goto error;
10777 if (qemuBuildGlobalControllerCommandLine(cmd, def, qemuCaps) < 0)
10778 goto error;
10780 if (qemuBuildControllersCommandLine(cmd, def, qemuCaps) < 0)
10781 goto error;
10783 if (qemuBuildHubCommandLine(cmd, def, qemuCaps) < 0)
10784 goto error;
10786 if (qemuBuildControllersByTypeCommandLine(cmd, def, qemuCaps,
10787 VIR_DOMAIN_CONTROLLER_TYPE_CCID) < 0)
10788 goto error;
10790 if (qemuBuildDisksCommandLine(cmd, def, qemuCaps) < 0)
10791 goto error;
10793 if (qemuBuildFSDevCommandLine(cmd, def, qemuCaps) < 0)
10794 goto error;
10796 if (qemuBuildNetCommandLine(driver, logManager, secManager, cmd, def,
10797 qemuCaps, vmop, standalone,
10798 nnicindexes, nicindexes, &bootHostdevNet) < 0)
10799 goto error;
10801 if (qemuBuildSmartcardCommandLine(logManager, secManager, cmd, cfg, def, qemuCaps,
10802 chardevStdioLogd) < 0)
10803 goto error;
10805 if (qemuBuildSerialCommandLine(logManager, secManager, cmd, cfg, def, qemuCaps,
10806 chardevStdioLogd) < 0)
10807 goto error;
10809 if (qemuBuildParallelsCommandLine(logManager, secManager, cmd, cfg, def, qemuCaps,
10810 chardevStdioLogd) < 0)
10811 goto error;
10813 if (qemuBuildChannelsCommandLine(logManager, secManager, cmd, cfg, def, qemuCaps,
10814 chardevStdioLogd) < 0)
10815 goto error;
10817 if (qemuBuildConsoleCommandLine(logManager, secManager, cmd, cfg, def, qemuCaps,
10818 chardevStdioLogd) < 0)
10819 goto error;
10821 if (qemuBuildTPMCommandLine(cmd, def, qemuCaps) < 0)
10822 goto error;
10824 if (qemuBuildInputCommandLine(cmd, def, qemuCaps) < 0)
10825 goto error;
10827 if (qemuBuildGraphicsCommandLine(cfg, cmd, def, qemuCaps) < 0)
10828 goto error;
10830 if (qemuBuildVideoCommandLine(cmd, def, qemuCaps) < 0)
10831 goto error;
10833 if (qemuBuildSoundCommandLine(cmd, def, qemuCaps) < 0)
10834 goto error;
10836 if (qemuBuildWatchdogCommandLine(cmd, def, qemuCaps) < 0)
10837 goto error;
10839 if (qemuBuildRedirdevCommandLine(logManager, secManager, cmd, cfg, def, qemuCaps,
10840 chardevStdioLogd) < 0)
10841 goto error;
10843 if (qemuBuildHostdevCommandLine(cmd, def, qemuCaps, &bootHostdevNet) < 0)
10844 goto error;
10846 if (migrateURI)
10847 virCommandAddArgList(cmd, "-incoming", migrateURI, NULL);
10849 if (qemuBuildMemballoonCommandLine(cmd, def, qemuCaps) < 0)
10850 goto error;
10852 if (qemuBuildRNGCommandLine(logManager, secManager, cmd, cfg, def, qemuCaps,
10853 chardevStdioLogd) < 0)
10854 goto error;
10856 if (qemuBuildNVRAMCommandLine(cmd, def, qemuCaps) < 0)
10857 goto error;
10859 if (qemuBuildVMCoreInfoCommandLine(cmd, def, qemuCaps) < 0)
10860 goto error;
10862 if (qemuBuildSEVCommandLine(vm, cmd, def->sev) < 0)
10863 goto error;
10865 if (snapshot)
10866 virCommandAddArgList(cmd, "-loadvm", snapshot->def->name, NULL);
10868 if (def->namespaceData) {
10869 qemuDomainCmdlineDefPtr qemucmd;
10871 qemucmd = def->namespaceData;
10872 for (i = 0; i < qemucmd->num_args; i++)
10873 virCommandAddArg(cmd, qemucmd->args[i]);
10874 for (i = 0; i < qemucmd->num_env; i++)
10875 virCommandAddEnvPair(cmd, qemucmd->env_name[i],
10876 NULLSTR_EMPTY(qemucmd->env_value[i]));
10879 if (qemuBuildSeccompSandboxCommandLine(cmd, cfg, qemuCaps) < 0)
10880 goto error;
10882 if (qemuBuildPanicCommandLine(cmd, def, qemuCaps) < 0)
10883 goto error;
10885 for (i = 0; i < def->nshmems; i++) {
10886 if (qemuBuildShmemCommandLine(logManager, secManager, cmd, cfg,
10887 def, def->shmems[i], qemuCaps,
10888 chardevStdioLogd))
10889 goto error;
10892 if (def->vsock &&
10893 qemuBuildVsockCommandLine(cmd, def, def->vsock, qemuCaps) < 0)
10894 goto error;
10896 /* In some situations, eg. VFIO passthrough, QEMU might need to lock a
10897 * significant amount of memory, so we need to set the limit accordingly */
10898 virCommandSetMaxMemLock(cmd, qemuDomainGetMemLockLimitBytes(def));
10900 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_MSG_TIMESTAMP) &&
10901 cfg->logTimestamp)
10902 virCommandAddArgList(cmd, "-msg", "timestamp=on", NULL);
10904 virObjectUnref(cfg);
10905 return cmd;
10907 error:
10908 virObjectUnref(cfg);
10909 virCommandFree(cmd);
10910 return NULL;
10914 /* This function generates the correct '-device' string for character
10915 * devices of each architecture.
10917 static int
10918 qemuBuildSerialChrDeviceStr(char **deviceStr,
10919 const virDomainDef *def,
10920 virDomainChrDefPtr serial,
10921 virQEMUCapsPtr qemuCaps)
10923 virBuffer cmd = VIR_BUFFER_INITIALIZER;
10924 virQEMUCapsFlags caps;
10926 switch ((virDomainChrSerialTargetModel) serial->targetModel) {
10927 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_ISA_SERIAL:
10928 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_USB_SERIAL:
10929 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_PCI_SERIAL:
10930 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SPAPR_VTY:
10931 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SCLPCONSOLE:
10932 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_SCLPLMCONSOLE:
10934 caps = qemuChrSerialTargetModelToCaps(serial->targetModel);
10936 if (caps && !virQEMUCapsGet(qemuCaps, caps)) {
10937 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10938 _("'%s' is not supported in this QEMU binary"),
10939 virDomainChrSerialTargetModelTypeToString(serial->targetModel));
10940 goto error;
10942 break;
10944 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_PL011:
10945 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_16550A:
10946 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_NONE:
10947 case VIR_DOMAIN_CHR_SERIAL_TARGET_MODEL_LAST:
10948 /* Except from _LAST, which is just a guard value and will never
10949 * be used, all of the above are platform devices, which means
10950 * qemuBuildSerialCommandLine() will have taken the appropriate
10951 * branch and we will not have ended up here. */
10952 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
10953 _("Invalid target model for serial device"));
10954 goto error;
10957 virBufferAsprintf(&cmd, "%s,chardev=char%s,id=%s",
10958 virDomainChrSerialTargetModelTypeToString(serial->targetModel),
10959 serial->info.alias, serial->info.alias);
10961 if (qemuBuildDeviceAddressStr(&cmd, def, &serial->info, qemuCaps) < 0)
10962 goto error;
10964 if (virBufferCheckError(&cmd) < 0)
10965 goto error;
10967 *deviceStr = virBufferContentAndReset(&cmd);
10968 return 0;
10970 error:
10971 virBufferFreeAndReset(&cmd);
10972 return -1;
10975 static int
10976 qemuBuildParallelChrDeviceStr(char **deviceStr,
10977 virDomainChrDefPtr chr)
10979 if (virAsprintf(deviceStr, "isa-parallel,chardev=char%s,id=%s",
10980 chr->info.alias, chr->info.alias) < 0)
10981 return -1;
10982 return 0;
10985 static int
10986 qemuBuildChannelChrDeviceStr(char **deviceStr,
10987 const virDomainDef *def,
10988 virDomainChrDefPtr chr)
10990 int ret = -1;
10991 char *addr = NULL;
10992 int port;
10994 switch ((virDomainChrChannelTargetType)chr->targetType) {
10995 case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_GUESTFWD:
10997 addr = virSocketAddrFormat(chr->target.addr);
10998 if (!addr)
10999 return ret;
11000 port = virSocketAddrGetPort(chr->target.addr);
11002 if (virAsprintf(deviceStr,
11003 "user,guestfwd=tcp:%s:%i-chardev:char%s,id=%s",
11004 addr, port, chr->info.alias, chr->info.alias) < 0)
11005 goto cleanup;
11006 break;
11008 case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO:
11009 if (!(*deviceStr = qemuBuildVirtioSerialPortDevStr(def, chr)))
11010 goto cleanup;
11011 break;
11013 case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_XEN:
11014 case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_NONE:
11015 case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_LAST:
11016 return ret;
11019 ret = 0;
11020 cleanup:
11021 VIR_FREE(addr);
11022 return ret;
11025 static int
11026 qemuBuildConsoleChrDeviceStr(char **deviceStr,
11027 const virDomainDef *def,
11028 virDomainChrDefPtr chr)
11030 int ret = -1;
11032 switch ((virDomainChrConsoleTargetType)chr->targetType) {
11033 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SCLP:
11034 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SCLPLM:
11035 if (!(*deviceStr = qemuBuildSclpDevStr(chr)))
11036 goto cleanup;
11037 break;
11039 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_VIRTIO:
11040 if (!(*deviceStr = qemuBuildVirtioSerialPortDevStr(def, chr)))
11041 goto cleanup;
11042 break;
11044 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL:
11045 break;
11047 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_NONE:
11048 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_XEN:
11049 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_UML:
11050 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_LXC:
11051 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_OPENVZ:
11052 case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_LAST:
11053 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11054 _("unsupported console target type %s"),
11055 NULLSTR(virDomainChrConsoleTargetTypeToString(chr->targetType)));
11056 goto cleanup;
11059 ret = 0;
11060 cleanup:
11061 return ret;
11065 qemuBuildChrDeviceStr(char **deviceStr,
11066 const virDomainDef *vmdef,
11067 virDomainChrDefPtr chr,
11068 virQEMUCapsPtr qemuCaps)
11070 int ret = -1;
11072 switch ((virDomainChrDeviceType)chr->deviceType) {
11073 case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
11074 ret = qemuBuildSerialChrDeviceStr(deviceStr, vmdef, chr, qemuCaps);
11075 break;
11077 case VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL:
11078 ret = qemuBuildParallelChrDeviceStr(deviceStr, chr);
11079 break;
11081 case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
11082 ret = qemuBuildChannelChrDeviceStr(deviceStr, vmdef, chr);
11083 break;
11085 case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
11086 ret = qemuBuildConsoleChrDeviceStr(deviceStr, vmdef, chr);
11087 break;
11089 case VIR_DOMAIN_CHR_DEVICE_TYPE_LAST:
11090 return ret;
11093 return ret;
11097 virJSONValuePtr
11098 qemuBuildHotpluggableCPUProps(const virDomainVcpuDef *vcpu)
11100 qemuDomainVcpuPrivatePtr vcpupriv = QEMU_DOMAIN_VCPU_PRIVATE(vcpu);
11101 virJSONValuePtr ret = NULL;
11103 if (virJSONValueObjectCreate(&ret, "s:driver", vcpupriv->type,
11104 "s:id", vcpupriv->alias, NULL) < 0)
11105 goto error;
11107 if (vcpupriv->socket_id != -1 &&
11108 virJSONValueObjectAdd(ret, "i:socket-id", vcpupriv->socket_id, NULL) < 0)
11109 goto error;
11111 if (vcpupriv->core_id != -1 &&
11112 virJSONValueObjectAdd(ret, "i:core-id", vcpupriv->core_id, NULL) < 0)
11113 goto error;
11115 if (vcpupriv->thread_id != -1 &&
11116 virJSONValueObjectAdd(ret, "i:thread-id", vcpupriv->thread_id, NULL) < 0)
11117 goto error;
11119 if (vcpupriv->node_id != -1 &&
11120 virJSONValueObjectAdd(ret, "i:node-id", vcpupriv->node_id, NULL) < 0)
11121 goto error;
11123 return ret;
11125 error:
11126 virJSONValueFree(ret);
11127 return NULL;
11132 * qemuBuildStorageSourceAttachPrepareDrive:
11133 * @disk: disk object to prepare
11134 * @qemuCaps: qemu capabilities object
11135 * @driveBoot: bootable flag for disks which don't have -device part
11137 * Prepare qemuBlockStorageSourceAttachDataPtr for use with the old approach
11138 * using -drive/drive_add. See qemuBlockStorageSourceAttachPrepareBlockdev.
11140 qemuBlockStorageSourceAttachDataPtr
11141 qemuBuildStorageSourceAttachPrepareDrive(virDomainDiskDefPtr disk,
11142 virQEMUCapsPtr qemuCaps)
11144 VIR_AUTOPTR(qemuBlockStorageSourceAttachData) data = NULL;
11145 qemuBlockStorageSourceAttachDataPtr ret = NULL;
11147 if (VIR_ALLOC(data) < 0)
11148 return NULL;
11150 if (!(data->driveCmd = qemuBuildDriveStr(disk, qemuCaps)) ||
11151 !(data->driveAlias = qemuAliasDiskDriveFromDisk(disk)))
11152 return NULL;
11154 VIR_STEAL_PTR(ret, data);
11156 return ret;
11161 * qemuBuildStorageSourceAttachPrepareCommon:
11162 * @src: storage source
11163 * @data: already initialized data for disk source addition
11164 * @qemuCaps: qemu capabilities object
11166 * Prepare data for configuration associated with the disk source such as
11167 * secrets/TLS/pr objects etc ...
11170 qemuBuildStorageSourceAttachPrepareCommon(virStorageSourcePtr src,
11171 qemuBlockStorageSourceAttachDataPtr data,
11172 virQEMUCapsPtr qemuCaps)
11174 qemuDomainStorageSourcePrivatePtr srcpriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
11176 if (src->pr &&
11177 !virStoragePRDefIsManaged(src->pr) &&
11178 !(data->prmgrProps = qemuBuildPRManagerInfoProps(src)))
11179 return -1;
11181 if (srcpriv) {
11182 if (srcpriv->secinfo &&
11183 srcpriv->secinfo->type == VIR_DOMAIN_SECRET_INFO_TYPE_AES &&
11184 qemuBuildSecretInfoProps(srcpriv->secinfo, &data->authsecretProps) < 0)
11185 return -1;
11187 if (srcpriv->encinfo &&
11188 qemuBuildSecretInfoProps(srcpriv->encinfo, &data->encryptsecretProps) < 0)
11189 return -1;
11192 if (src->haveTLS == VIR_TRISTATE_BOOL_YES &&
11193 qemuBuildTLSx509BackendProps(src->tlsCertdir, false, true, src->tlsAlias,
11194 NULL, qemuCaps, &data->tlsProps) < 0)
11195 return -1;
11197 return 0;