Imported Upstream version 1.2.5
[archive/platform/upstream/libvirt.git] / src / qemu / qemu_command.c
1 /*
2  * qemu_command.c: QEMU command generation
3  *
4  * Copyright (C) 2006-2014 Red Hat, Inc.
5  * Copyright (C) 2006 Daniel P. Berrange
6  *
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.
11  *
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.
16  *
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/>.
20  *
21  * Author: Daniel P. Berrange <berrange@redhat.com>
22  */
23
24 #include <config.h>
25
26 #include "qemu_command.h"
27 #include "qemu_hostdev.h"
28 #include "qemu_capabilities.h"
29 #include "cpu/cpu.h"
30 #include "dirname.h"
31 #include "passfd.h"
32 #include "viralloc.h"
33 #include "virlog.h"
34 #include "virarch.h"
35 #include "virerror.h"
36 #include "virfile.h"
37 #include "virnetdev.h"
38 #include "virstring.h"
39 #include "virtime.h"
40 #include "viruuid.h"
41 #include "c-ctype.h"
42 #include "domain_nwfilter.h"
43 #include "domain_addr.h"
44 #include "domain_audit.h"
45 #include "domain_conf.h"
46 #include "snapshot_conf.h"
47 #include "storage_conf.h"
48 #include "network/bridge_driver.h"
49 #include "virnetdevtap.h"
50 #include "base64.h"
51 #include "device_conf.h"
52 #include "virstoragefile.h"
53 #include "virtpm.h"
54 #include "virscsi.h"
55 #if defined(__linux__)
56 # include <linux/capability.h>
57 #endif
58
59 #include <sys/stat.h>
60 #include <fcntl.h>
61
62 #define VIR_FROM_THIS VIR_FROM_QEMU
63
64 VIR_LOG_INIT("qemu.qemu_command");
65
66 #define VIO_ADDR_NET 0x1000ul
67 #define VIO_ADDR_SCSI 0x2000ul
68 #define VIO_ADDR_SERIAL 0x30000000ul
69 #define VIO_ADDR_NVRAM 0x3000ul
70
71 VIR_ENUM_DECL(virDomainDiskQEMUBus)
72 VIR_ENUM_IMPL(virDomainDiskQEMUBus, VIR_DOMAIN_DISK_BUS_LAST,
73               "ide",
74               "floppy",
75               "scsi",
76               "virtio",
77               "xen",
78               "usb",
79               "uml",
80               "sata",
81               "sd")
82
83
84 VIR_ENUM_DECL(qemuDiskCacheV1)
85 VIR_ENUM_DECL(qemuDiskCacheV2)
86
87 VIR_ENUM_IMPL(qemuDiskCacheV1, VIR_DOMAIN_DISK_CACHE_LAST,
88               "default",
89               "off",
90               "off",  /* writethrough not supported, so for safety, disable */
91               "on",   /* Old 'on' was equivalent to 'writeback' */
92               "off",  /* directsync not supported, for safety, disable */
93               "off"); /* unsafe not supported, for safety, disable */
94
95 VIR_ENUM_IMPL(qemuDiskCacheV2, VIR_DOMAIN_DISK_CACHE_LAST,
96               "default",
97               "none",
98               "writethrough",
99               "writeback",
100               "directsync",
101               "unsafe");
102
103 VIR_ENUM_DECL(qemuVideo)
104
105 VIR_ENUM_IMPL(qemuVideo, VIR_DOMAIN_VIDEO_TYPE_LAST,
106               "std",
107               "cirrus",
108               "vmware",
109               "", /* no arg needed for xen */
110               "", /* don't support vbox */
111               "qxl");
112
113 VIR_ENUM_DECL(qemuDeviceVideo)
114
115 VIR_ENUM_IMPL(qemuDeviceVideo, VIR_DOMAIN_VIDEO_TYPE_LAST,
116               "VGA",
117               "cirrus-vga",
118               "vmware-svga",
119               "", /* no device for xen */
120               "", /* don't support vbox */
121               "qxl-vga");
122
123 VIR_ENUM_DECL(qemuSoundCodec)
124
125 VIR_ENUM_IMPL(qemuSoundCodec, VIR_DOMAIN_SOUND_CODEC_TYPE_LAST,
126               "hda-duplex",
127               "hda-micro");
128
129 VIR_ENUM_DECL(qemuControllerModelUSB)
130
131 VIR_ENUM_IMPL(qemuControllerModelUSB, VIR_DOMAIN_CONTROLLER_MODEL_USB_LAST,
132               "piix3-usb-uhci",
133               "piix4-usb-uhci",
134               "usb-ehci",
135               "ich9-usb-ehci1",
136               "ich9-usb-uhci1",
137               "ich9-usb-uhci2",
138               "ich9-usb-uhci3",
139               "vt82c686b-usb-uhci",
140               "pci-ohci",
141               "nec-usb-xhci",
142               "none");
143
144 VIR_ENUM_DECL(qemuDomainFSDriver)
145 VIR_ENUM_IMPL(qemuDomainFSDriver, VIR_DOMAIN_FS_DRIVER_TYPE_LAST,
146               "local",
147               "local",
148               "handle",
149               NULL,
150               NULL);
151
152
153 /**
154  * qemuPhysIfaceConnect:
155  * @def: the definition of the VM (needed by 802.1Qbh and audit)
156  * @driver: pointer to the driver instance
157  * @net: pointer to he VM's interface description with direct device type
158  * @qemuCaps: flags for qemu
159  * @vmop: VM operation type
160  *
161  * Returns a filedescriptor on success or -1 in case of error.
162  */
163 int
164 qemuPhysIfaceConnect(virDomainDefPtr def,
165                      virQEMUDriverPtr driver,
166                      virDomainNetDefPtr net,
167                      virQEMUCapsPtr qemuCaps,
168                      virNetDevVPortProfileOp vmop)
169 {
170     int rc;
171     char *res_ifname = NULL;
172     int vnet_hdr = 0;
173     virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
174
175     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VNET_HDR) &&
176         net->model && STREQ(net->model, "virtio"))
177         vnet_hdr = 1;
178
179     rc = virNetDevMacVLanCreateWithVPortProfile(
180         net->ifname, &net->mac,
181         virDomainNetGetActualDirectDev(net),
182         virDomainNetGetActualDirectMode(net),
183         true, vnet_hdr, def->uuid,
184         virDomainNetGetActualVirtPortProfile(net),
185         &res_ifname,
186         vmop, cfg->stateDir,
187         virDomainNetGetActualBandwidth(net));
188     if (rc >= 0) {
189         if (virSecurityManagerSetTapFDLabel(driver->securityManager,
190                                             def, rc) < 0)
191             goto error;
192
193         virDomainAuditNetDevice(def, net, res_ifname, true);
194         VIR_FREE(net->ifname);
195         net->ifname = res_ifname;
196     }
197
198     virObjectUnref(cfg);
199     return rc;
200
201  error:
202     ignore_value(virNetDevMacVLanDeleteWithVPortProfile(
203                      res_ifname, &net->mac,
204                      virDomainNetGetActualDirectDev(net),
205                      virDomainNetGetActualDirectMode(net),
206                      virDomainNetGetActualVirtPortProfile(net),
207                      cfg->stateDir));
208     VIR_FREE(res_ifname);
209     virObjectUnref(cfg);
210     return -1;
211 }
212
213
214 /**
215  * qemuCreateInBridgePortWithHelper:
216  * @cfg: the configuration object in which the helper name is looked up
217  * @brname: the bridge name
218  * @ifname: the returned interface name
219  * @macaddr: the returned MAC address
220  * @tapfd: file descriptor return value for the new tap device
221  * @flags: OR of virNetDevTapCreateFlags:
222
223  *   VIR_NETDEV_TAP_CREATE_VNET_HDR
224  *     - Enable IFF_VNET_HDR on the tap device
225  *
226  * This function creates a new tap device on a bridge using an external
227  * helper.  The final name for the bridge will be stored in @ifname.
228  *
229  * Returns 0 in case of success or -1 on failure
230  */
231 static int qemuCreateInBridgePortWithHelper(virQEMUDriverConfigPtr cfg,
232                                             const char *brname,
233                                             char **ifname,
234                                             int *tapfd,
235                                             unsigned int flags)
236 {
237     virCommandPtr cmd;
238     int pair[2] = { -1, -1 };
239
240     if ((flags & ~VIR_NETDEV_TAP_CREATE_VNET_HDR) != VIR_NETDEV_TAP_CREATE_IFUP)
241         return -1;
242
243     if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) < 0) {
244         virReportSystemError(errno, "%s", _("failed to create socket"));
245         return -1;
246     }
247
248     cmd = virCommandNew(cfg->bridgeHelperName);
249     if (flags & VIR_NETDEV_TAP_CREATE_VNET_HDR)
250         virCommandAddArgFormat(cmd, "--use-vnet");
251     virCommandAddArgFormat(cmd, "--br=%s", brname);
252     virCommandAddArgFormat(cmd, "--fd=%d", pair[1]);
253     virCommandPassFD(cmd, pair[1],
254                      VIR_COMMAND_PASS_FD_CLOSE_PARENT);
255     virCommandClearCaps(cmd);
256 #ifdef CAP_NET_ADMIN
257     virCommandAllowCap(cmd, CAP_NET_ADMIN);
258 #endif
259     if (virCommandRunAsync(cmd, NULL) < 0) {
260         *tapfd = -1;
261         goto cleanup;
262     }
263
264     do {
265         *tapfd = recvfd(pair[0], 0);
266     } while (*tapfd < 0 && errno == EINTR);
267     if (*tapfd < 0) {
268         virReportSystemError(errno, "%s",
269                              _("failed to retrieve file descriptor for interface"));
270         goto cleanup;
271     }
272
273     if (virNetDevTapGetName(*tapfd, ifname) < 0 ||
274         virCommandWait(cmd, NULL) < 0) {
275         VIR_FORCE_CLOSE(*tapfd);
276         *tapfd = -1;
277     }
278
279  cleanup:
280     virCommandFree(cmd);
281     VIR_FORCE_CLOSE(pair[0]);
282     return *tapfd < 0 ? -1 : 0;
283 }
284
285 int
286 qemuNetworkIfaceConnect(virDomainDefPtr def,
287                         virConnectPtr conn,
288                         virQEMUDriverPtr driver,
289                         virDomainNetDefPtr net,
290                         virQEMUCapsPtr qemuCaps,
291                         int *tapfd,
292                         int *tapfdSize)
293 {
294     char *brname = NULL;
295     int ret = -1;
296     unsigned int tap_create_flags = VIR_NETDEV_TAP_CREATE_IFUP;
297     bool template_ifname = false;
298     int actualType = virDomainNetGetActualType(net);
299     virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
300
301     if (actualType == VIR_DOMAIN_NET_TYPE_NETWORK) {
302         bool fail = false;
303         virErrorPtr errobj;
304         virNetworkPtr network = virNetworkLookupByName(conn,
305                                                        net->data.network.name);
306         if (!network)
307             return ret;
308
309         if (!(brname = virNetworkGetBridgeName(network)))
310            fail = true;
311
312         /* Make sure any above failure is preserved */
313         errobj = virSaveLastError();
314         virNetworkFree(network);
315         virSetError(errobj);
316         virFreeError(errobj);
317
318         if (fail)
319             return ret;
320
321     } else if (actualType == VIR_DOMAIN_NET_TYPE_BRIDGE) {
322         if (VIR_STRDUP(brname, virDomainNetGetActualBridgeName(net)) < 0)
323             return ret;
324     } else {
325         virReportError(VIR_ERR_INTERNAL_ERROR,
326                        _("Network type %d is not supported"),
327                        virDomainNetGetActualType(net));
328         return ret;
329     }
330
331     if (!net->ifname ||
332         STRPREFIX(net->ifname, VIR_NET_GENERATED_PREFIX) ||
333         strchr(net->ifname, '%')) {
334         VIR_FREE(net->ifname);
335         if (VIR_STRDUP(net->ifname, VIR_NET_GENERATED_PREFIX "%d") < 0)
336             goto cleanup;
337         /* avoid exposing vnet%d in getXMLDesc or error outputs */
338         template_ifname = true;
339     }
340
341     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VNET_HDR) &&
342         net->model && STREQ(net->model, "virtio")) {
343         tap_create_flags |= VIR_NETDEV_TAP_CREATE_VNET_HDR;
344     }
345
346     if (cfg->privileged) {
347         if (virNetDevTapCreateInBridgePort(brname, &net->ifname, &net->mac,
348                                            def->uuid, tapfd, *tapfdSize,
349                                            virDomainNetGetActualVirtPortProfile(net),
350                                            virDomainNetGetActualVlan(net),
351                                            tap_create_flags) < 0) {
352             virDomainAuditNetDevice(def, net, "/dev/net/tun", false);
353             goto cleanup;
354         }
355     } else {
356         if (qemuCreateInBridgePortWithHelper(cfg, brname,
357                                              &net->ifname,
358                                              tapfd, tap_create_flags) < 0) {
359             virDomainAuditNetDevice(def, net, "/dev/net/tun", false);
360             goto cleanup;
361         }
362         /* qemuCreateInBridgePortWithHelper can only create a single FD */
363         if (*tapfdSize > 1) {
364             VIR_WARN("Ignoring multiqueue network request");
365             *tapfdSize = 1;
366         }
367     }
368
369     virDomainAuditNetDevice(def, net, "/dev/net/tun", true);
370
371     if (cfg->macFilter &&
372         ebtablesAddForwardAllowIn(driver->ebtables,
373                                   net->ifname,
374                                   &net->mac) < 0)
375         goto cleanup;
376
377     if (virNetDevBandwidthSet(net->ifname,
378                               virDomainNetGetActualBandwidth(net),
379                               false) < 0) {
380         virReportError(VIR_ERR_INTERNAL_ERROR,
381                        _("cannot set bandwidth limits on %s"),
382                        net->ifname);
383         goto cleanup;
384     }
385
386     if (net->filter && net->ifname &&
387         virDomainConfNWFilterInstantiate(conn, def->uuid, net) < 0) {
388         goto cleanup;
389     }
390
391     ret = 0;
392
393  cleanup:
394     if (ret < 0) {
395         size_t i;
396         for (i = 0; i < *tapfdSize && tapfd[i] >= 0; i++)
397             VIR_FORCE_CLOSE(tapfd[i]);
398         if (template_ifname)
399             VIR_FREE(net->ifname);
400     }
401     VIR_FREE(brname);
402     virObjectUnref(cfg);
403
404     return ret;
405 }
406
407 static bool
408 qemuDomainSupportsNicdev(virDomainDefPtr def,
409                          virQEMUCapsPtr qemuCaps,
410                          virDomainNetDefPtr net)
411 {
412     if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE))
413         return false;
414
415     /* non-virtio ARM nics require legacy -net nic */
416     if (((def->os.arch == VIR_ARCH_ARMV7L) ||
417         (def->os.arch == VIR_ARCH_AARCH64)) &&
418         net->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO)
419         return false;
420
421     return true;
422 }
423
424 static bool
425 qemuDomainSupportsNetdev(virDomainDefPtr def,
426                          virQEMUCapsPtr qemuCaps,
427                          virDomainNetDefPtr net)
428 {
429     if (!qemuDomainSupportsNicdev(def, qemuCaps, net))
430         return false;
431     return virQEMUCapsGet(qemuCaps, QEMU_CAPS_NETDEV);
432 }
433
434 /**
435  * qemuOpenVhostNet:
436  * @def: domain definition
437  * @net: network definition
438  * @qemuCaps: qemu binary capabilities
439  * @vhostfd: array of opened vhost-net device
440  * @vhostfdSize: number of file descriptors in @vhostfd array
441  *
442  * Open vhost-net, multiple times - if requested.
443  * In case, no vhost-net is needed, @vhostfdSize is set to 0
444  * and 0 is returned.
445  *
446  * Returns: 0 on success
447  *         -1 on failure
448  */
449 int
450 qemuOpenVhostNet(virDomainDefPtr def,
451                  virDomainNetDefPtr net,
452                  virQEMUCapsPtr qemuCaps,
453                  int *vhostfd,
454                  int *vhostfdSize)
455 {
456     size_t i;
457
458     /* If running a plain QEMU guest, or
459      * if the config says explicitly to not use vhost, return now*/
460     if (def->virtType != VIR_DOMAIN_VIRT_KVM ||
461         net->driver.virtio.name == VIR_DOMAIN_NET_BACKEND_TYPE_QEMU) {
462         *vhostfdSize = 0;
463         return 0;
464     }
465
466     /* If qemu doesn't support vhost-net mode (including the -netdev command
467      * option), don't try to open the device.
468      */
469     if (!(virQEMUCapsGet(qemuCaps, QEMU_CAPS_VHOST_NET) &&
470           qemuDomainSupportsNetdev(def, qemuCaps, net))) {
471         if (net->driver.virtio.name == VIR_DOMAIN_NET_BACKEND_TYPE_VHOST) {
472             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
473                            "%s", _("vhost-net is not supported with "
474                                    "this QEMU binary"));
475             return -1;
476         }
477         *vhostfdSize = 0;
478         return 0;
479     }
480
481     /* If the nic model isn't virtio, don't try to open. */
482     if (!(net->model && STREQ(net->model, "virtio"))) {
483         if (net->driver.virtio.name == VIR_DOMAIN_NET_BACKEND_TYPE_VHOST) {
484             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
485                            "%s", _("vhost-net is only supported for "
486                                    "virtio network interfaces"));
487             return -1;
488         }
489         *vhostfdSize = 0;
490         return 0;
491     }
492
493     for (i = 0; i < *vhostfdSize; i++) {
494         vhostfd[i] = open("/dev/vhost-net", O_RDWR);
495
496         /* If the config says explicitly to use vhost and we couldn't open it,
497          * report an error.
498          */
499         if (vhostfd[i] < 0) {
500             virDomainAuditNetDevice(def, net, "/dev/vhost-net", false);
501             if (net->driver.virtio.name == VIR_DOMAIN_NET_BACKEND_TYPE_VHOST) {
502                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
503                                "%s", _("vhost-net was requested for an interface, "
504                                        "but is unavailable"));
505                 goto error;
506             }
507             VIR_WARN("Unable to open vhost-net. Opened so far %zu, requested %d",
508                      i, *vhostfdSize);
509             *vhostfdSize = i;
510             break;
511         }
512     }
513     virDomainAuditNetDevice(def, net, "/dev/vhost-net", *vhostfdSize);
514     return 0;
515
516  error:
517     while (i--)
518         VIR_FORCE_CLOSE(vhostfd[i]);
519
520     return -1;
521 }
522
523 int
524 qemuNetworkPrepareDevices(virDomainDefPtr def)
525 {
526     int ret = -1;
527     size_t i;
528
529     for (i = 0; i < def->nnets; i++) {
530         virDomainNetDefPtr net = def->nets[i];
531         int actualType;
532
533         /* If appropriate, grab a physical device from the configured
534          * network's pool of devices, or resolve bridge device name
535          * to the one defined in the network definition.
536          */
537         if (networkAllocateActualDevice(def, net) < 0)
538             goto cleanup;
539
540         actualType = virDomainNetGetActualType(net);
541         if (actualType == VIR_DOMAIN_NET_TYPE_HOSTDEV &&
542             net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
543             /* Each type='hostdev' network device must also have a
544              * corresponding entry in the hostdevs array. For netdevs
545              * that are hardcoded as type='hostdev', this is already
546              * done by the parser, but for those allocated from a
547              * network / determined at runtime, we need to do it
548              * separately.
549              */
550             virDomainHostdevDefPtr hostdev = virDomainNetGetActualHostdev(net);
551
552             if (virDomainHostdevFind(def, hostdev, NULL) >= 0) {
553                 virReportError(VIR_ERR_INTERNAL_ERROR,
554                                _("PCI device %04x:%02x:%02x.%x "
555                                  "allocated from network %s is already "
556                                  "in use by domain %s"),
557                                hostdev->source.subsys.u.pci.addr.domain,
558                                hostdev->source.subsys.u.pci.addr.bus,
559                                hostdev->source.subsys.u.pci.addr.slot,
560                                hostdev->source.subsys.u.pci.addr.function,
561                                net->data.network.name,
562                                def->name);
563                 goto cleanup;
564             }
565             if (virDomainHostdevInsert(def, hostdev) < 0)
566                 goto cleanup;
567         }
568     }
569     ret = 0;
570  cleanup:
571     return ret;
572 }
573
574 static int qemuDomainDeviceAliasIndex(const virDomainDeviceInfo *info,
575                                       const char *prefix)
576 {
577     int idx;
578
579     if (!info->alias)
580         return -1;
581     if (!STRPREFIX(info->alias, prefix))
582         return -1;
583
584     if (virStrToLong_i(info->alias + strlen(prefix), NULL, 10, &idx) < 0)
585         return -1;
586
587     return idx;
588 }
589
590
591 int qemuDomainNetVLAN(virDomainNetDefPtr def)
592 {
593     return qemuDomainDeviceAliasIndex(&def->info, "net");
594 }
595
596
597 /* Names used before -drive existed */
598 static int qemuAssignDeviceDiskAliasLegacy(virDomainDiskDefPtr disk)
599 {
600     char *dev_name;
601
602     if (VIR_STRDUP(dev_name,
603                    disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM &&
604                    STREQ(disk->dst, "hdc") ? "cdrom" : disk->dst) < 0)
605         return -1;
606     disk->info.alias = dev_name;
607     return 0;
608 }
609
610
611 char *qemuDeviceDriveHostAlias(virDomainDiskDefPtr disk,
612                                virQEMUCapsPtr qemuCaps)
613 {
614     char *ret;
615
616     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
617         ignore_value(virAsprintf(&ret, "%s%s", QEMU_DRIVE_HOST_PREFIX,
618                                  disk->info.alias));
619     } else {
620         ignore_value(VIR_STRDUP(ret, disk->info.alias));
621     }
622     return ret;
623 }
624
625
626 /* Names used before -drive supported the id= option */
627 static int qemuAssignDeviceDiskAliasFixed(virDomainDiskDefPtr disk)
628 {
629     int busid, devid;
630     int ret;
631     char *dev_name;
632
633     if (virDiskNameToBusDeviceIndex(disk, &busid, &devid) < 0) {
634         virReportError(VIR_ERR_INTERNAL_ERROR,
635                        _("cannot convert disk '%s' to bus/device index"),
636                        disk->dst);
637         return -1;
638     }
639
640     switch (disk->bus) {
641     case VIR_DOMAIN_DISK_BUS_IDE:
642         if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK)
643             ret = virAsprintf(&dev_name, "ide%d-hd%d", busid, devid);
644         else
645             ret = virAsprintf(&dev_name, "ide%d-cd%d", busid, devid);
646         break;
647     case VIR_DOMAIN_DISK_BUS_SCSI:
648         if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK)
649             ret = virAsprintf(&dev_name, "scsi%d-hd%d", busid, devid);
650         else
651             ret = virAsprintf(&dev_name, "scsi%d-cd%d", busid, devid);
652         break;
653     case VIR_DOMAIN_DISK_BUS_FDC:
654         ret = virAsprintf(&dev_name, "floppy%d", devid);
655         break;
656     case VIR_DOMAIN_DISK_BUS_VIRTIO:
657         ret = virAsprintf(&dev_name, "virtio%d", devid);
658         break;
659     case VIR_DOMAIN_DISK_BUS_XEN:
660         ret = virAsprintf(&dev_name, "xenblk%d", devid);
661         break;
662     case VIR_DOMAIN_DISK_BUS_SD:
663         ret = virAsprintf(&dev_name, "sd%d", devid);
664         break;
665     default:
666         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
667                        _("Unsupported disk name mapping for bus '%s'"),
668                        virDomainDiskBusTypeToString(disk->bus));
669         return -1;
670     }
671
672     if (ret == -1)
673         return -1;
674
675     disk->info.alias = dev_name;
676
677     return 0;
678 }
679
680 static int
681 qemuSetSCSIControllerModel(virDomainDefPtr def,
682                            virQEMUCapsPtr qemuCaps,
683                            int *model)
684 {
685     if (*model > 0) {
686         switch (*model) {
687         case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC:
688             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_LSI)) {
689                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
690                                _("This QEMU doesn't support "
691                                  "the LSI 53C895A SCSI controller"));
692                 return -1;
693             }
694             break;
695         case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI:
696             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_SCSI)) {
697                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
698                                _("This QEMU doesn't support "
699                                  "virtio scsi controller"));
700                 return -1;
701             }
702             break;
703         case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_IBMVSCSI:
704             /*TODO: need checking work here if necessary */
705             break;
706         case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1078:
707             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_MEGASAS)) {
708                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
709                                _("This QEMU doesn't support "
710                                  "the LSI SAS1078 controller"));
711                 return -1;
712             }
713             break;
714         default:
715             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
716                            _("Unsupported controller model: %s"),
717                            virDomainControllerModelSCSITypeToString(*model));
718             return -1;
719         }
720     } else {
721         if ((def->os.arch == VIR_ARCH_PPC64) &&
722             STREQ(def->os.machine, "pseries")) {
723             *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_IBMVSCSI;
724         } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_LSI)) {
725             *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC;
726         } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_SCSI)) {
727             *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI;
728         } else {
729             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
730                            _("Unable to determine model for scsi controller"));
731             return -1;
732         }
733     }
734
735     return 0;
736 }
737
738 /* Our custom -drive naming scheme used with id= */
739 static int
740 qemuAssignDeviceDiskAliasCustom(virDomainDefPtr def,
741                                 virDomainDiskDefPtr disk,
742                                 virQEMUCapsPtr qemuCaps)
743 {
744     const char *prefix = virDomainDiskBusTypeToString(disk->bus);
745     int controllerModel = -1;
746
747     if (disk->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE) {
748         if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI) {
749             controllerModel =
750                 virDomainDeviceFindControllerModel(def, &disk->info,
751                                                    VIR_DOMAIN_CONTROLLER_TYPE_SCSI);
752
753             if ((qemuSetSCSIControllerModel(def, qemuCaps, &controllerModel)) < 0)
754                 return -1;
755         }
756
757         if (disk->bus != VIR_DOMAIN_DISK_BUS_SCSI ||
758             controllerModel == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC) {
759             if (virAsprintf(&disk->info.alias, "%s%d-%d-%d", prefix,
760                             disk->info.addr.drive.controller,
761                             disk->info.addr.drive.bus,
762                             disk->info.addr.drive.unit) < 0)
763                 return -1;
764         } else {
765             if (virAsprintf(&disk->info.alias, "%s%d-%d-%d-%d", prefix,
766                             disk->info.addr.drive.controller,
767                             disk->info.addr.drive.bus,
768                             disk->info.addr.drive.target,
769                             disk->info.addr.drive.unit) < 0)
770                 return -1;
771         }
772     } else {
773         int idx = virDiskNameToIndex(disk->dst);
774         if (virAsprintf(&disk->info.alias, "%s-disk%d", prefix, idx) < 0)
775             return -1;
776     }
777
778     return 0;
779 }
780
781
782 int
783 qemuAssignDeviceDiskAlias(virDomainDefPtr vmdef,
784                           virDomainDiskDefPtr def,
785                           virQEMUCapsPtr qemuCaps)
786 {
787     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE)) {
788         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE))
789             return qemuAssignDeviceDiskAliasCustom(vmdef, def, qemuCaps);
790         else
791             return qemuAssignDeviceDiskAliasFixed(def);
792     } else {
793         return qemuAssignDeviceDiskAliasLegacy(def);
794     }
795 }
796
797
798 int
799 qemuAssignDeviceNetAlias(virDomainDefPtr def, virDomainNetDefPtr net, int idx)
800 {
801     if (idx == -1) {
802         size_t i;
803         idx = 0;
804         for (i = 0; i < def->nnets; i++) {
805             int thisidx;
806
807             if (virDomainNetGetActualType(def->nets[i])
808                 == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
809                 /* type='hostdev' interfaces have a hostdev%d alias */
810                continue;
811             }
812             if ((thisidx = qemuDomainDeviceAliasIndex(&def->nets[i]->info, "net")) < 0) {
813                 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
814                                _("Unable to determine device index for network device"));
815                 return -1;
816             }
817             if (thisidx >= idx)
818                 idx = thisidx + 1;
819         }
820     }
821
822     if (virAsprintf(&net->info.alias, "net%d", idx) < 0)
823         return -1;
824     return 0;
825 }
826
827
828 int
829 qemuAssignDeviceHostdevAlias(virDomainDefPtr def, virDomainHostdevDefPtr hostdev, int idx)
830 {
831     if (idx == -1) {
832         size_t i;
833         idx = 0;
834         for (i = 0; i < def->nhostdevs; i++) {
835             int thisidx;
836             if ((thisidx = qemuDomainDeviceAliasIndex(def->hostdevs[i]->info, "hostdev")) < 0) {
837                 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
838                                _("Unable to determine device index for hostdev device"));
839                 return -1;
840             }
841             if (thisidx >= idx)
842                 idx = thisidx + 1;
843         }
844     }
845
846     if (virAsprintf(&hostdev->info->alias, "hostdev%d", idx) < 0)
847         return -1;
848
849     return 0;
850 }
851
852
853 int
854 qemuAssignDeviceRedirdevAlias(virDomainDefPtr def, virDomainRedirdevDefPtr redirdev, int idx)
855 {
856     if (idx == -1) {
857         size_t i;
858         idx = 0;
859         for (i = 0; i < def->nredirdevs; i++) {
860             int thisidx;
861             if ((thisidx = qemuDomainDeviceAliasIndex(&def->redirdevs[i]->info, "redir")) < 0) {
862                 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
863                                _("Unable to determine device index for redirected device"));
864                 return -1;
865             }
866             if (thisidx >= idx)
867                 idx = thisidx + 1;
868         }
869     }
870
871     if (virAsprintf(&redirdev->info.alias, "redir%d", idx) < 0)
872         return -1;
873     return 0;
874 }
875
876
877 int
878 qemuAssignDeviceControllerAlias(virDomainControllerDefPtr controller)
879 {
880     const char *prefix = virDomainControllerTypeToString(controller->type);
881
882     if (controller->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI) {
883         /* only pcie-root uses a different naming convention
884          * ("pcie.0"), because it is hardcoded that way in qemu. All
885          * other buses use the consistent "pci.%u".
886          */
887         if (controller->model == VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT)
888             return virAsprintf(&controller->info.alias, "pcie.%d", controller->idx);
889         else
890             return virAsprintf(&controller->info.alias, "pci.%d", controller->idx);
891     }
892
893     return virAsprintf(&controller->info.alias, "%s%d", prefix, controller->idx);
894 }
895
896 static ssize_t
897 qemuGetNextChrDevIndex(virDomainDefPtr def,
898                        virDomainChrDefPtr chr,
899                        const char *prefix)
900 {
901     const virDomainChrDef **arrPtr;
902     size_t cnt;
903     size_t i;
904     ssize_t idx = 0;
905     const char *prefix2 = NULL;
906
907     if (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE)
908         prefix2 = "serial";
909
910     virDomainChrGetDomainPtrs(def, chr->deviceType, &arrPtr, &cnt);
911
912     for (i = 0; i < cnt; i++) {
913         ssize_t thisidx;
914         if (((thisidx = qemuDomainDeviceAliasIndex(&arrPtr[i]->info, prefix)) < 0) &&
915             (prefix2 &&
916              (thisidx = qemuDomainDeviceAliasIndex(&arrPtr[i]->info, prefix2)) < 0)) {
917             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
918                            _("Unable to determine device index for character device"));
919             return -1;
920         }
921         if (thisidx >= idx)
922             idx = thisidx + 1;
923     }
924
925     return idx;
926 }
927
928
929 int
930 qemuAssignDeviceChrAlias(virDomainDefPtr def,
931                          virDomainChrDefPtr chr,
932                          ssize_t idx)
933 {
934     const char *prefix = NULL;
935
936     switch ((enum virDomainChrDeviceType) chr->deviceType) {
937     case VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL:
938         prefix = "parallel";
939         break;
940
941     case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
942         prefix = "serial";
943         break;
944
945     case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
946         prefix = "console";
947         break;
948
949     case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
950         prefix = "channel";
951         break;
952
953     case VIR_DOMAIN_CHR_DEVICE_TYPE_LAST:
954         return -1;
955     }
956
957     if (idx == -1 && (idx = qemuGetNextChrDevIndex(def, chr, prefix)) < 0)
958         return -1;
959
960     return virAsprintf(&chr->info.alias, "%s%zd", prefix, idx);
961 }
962
963 int
964 qemuAssignDeviceAliases(virDomainDefPtr def, virQEMUCapsPtr qemuCaps)
965 {
966     size_t i;
967
968     for (i = 0; i < def->ndisks; i++) {
969         if (qemuAssignDeviceDiskAlias(def, def->disks[i], qemuCaps) < 0)
970             return -1;
971     }
972     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NET_NAME) ||
973         virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
974         for (i = 0; i < def->nnets; i++) {
975             /* type='hostdev' interfaces are also on the hostdevs list,
976              * and will have their alias assigned with other hostdevs.
977              */
978             if (virDomainNetGetActualType(def->nets[i])
979                 != VIR_DOMAIN_NET_TYPE_HOSTDEV &&
980                 qemuAssignDeviceNetAlias(def, def->nets[i], i) < 0) {
981                 return -1;
982             }
983         }
984     }
985
986     if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE))
987         return 0;
988
989     for (i = 0; i < def->nfss; i++) {
990         if (virAsprintf(&def->fss[i]->info.alias, "fs%zu", i) < 0)
991             return -1;
992     }
993     for (i = 0; i < def->nsounds; i++) {
994         if (virAsprintf(&def->sounds[i]->info.alias, "sound%zu", i) < 0)
995             return -1;
996     }
997     for (i = 0; i < def->nhostdevs; i++) {
998         if (qemuAssignDeviceHostdevAlias(def, def->hostdevs[i], i) < 0)
999             return -1;
1000     }
1001     for (i = 0; i < def->nredirdevs; i++) {
1002         if (qemuAssignDeviceRedirdevAlias(def, def->redirdevs[i], i) < 0)
1003             return -1;
1004     }
1005     for (i = 0; i < def->nvideos; i++) {
1006         if (virAsprintf(&def->videos[i]->info.alias, "video%zu", i) < 0)
1007             return -1;
1008     }
1009     for (i = 0; i < def->ncontrollers; i++) {
1010         if (qemuAssignDeviceControllerAlias(def->controllers[i]) < 0)
1011             return -1;
1012     }
1013     for (i = 0; i < def->ninputs; i++) {
1014         if (virAsprintf(&def->inputs[i]->info.alias, "input%zu", i) < 0)
1015             return -1;
1016     }
1017     for (i = 0; i < def->nparallels; i++) {
1018         if (qemuAssignDeviceChrAlias(def, def->parallels[i], i) < 0)
1019             return -1;
1020     }
1021     for (i = 0; i < def->nserials; i++) {
1022         if (qemuAssignDeviceChrAlias(def, def->serials[i], i) < 0)
1023             return -1;
1024     }
1025     for (i = 0; i < def->nchannels; i++) {
1026         if (qemuAssignDeviceChrAlias(def, def->channels[i], i) < 0)
1027             return -1;
1028     }
1029     for (i = 0; i < def->nconsoles; i++) {
1030         if (qemuAssignDeviceChrAlias(def, def->consoles[i], i) < 0)
1031             return -1;
1032     }
1033     for (i = 0; i < def->nhubs; i++) {
1034         if (virAsprintf(&def->hubs[i]->info.alias, "hub%zu", i) < 0)
1035             return -1;
1036     }
1037     for (i = 0; i < def->nsmartcards; i++) {
1038         if (virAsprintf(&def->smartcards[i]->info.alias, "smartcard%zu", i) < 0)
1039             return -1;
1040     }
1041     if (def->watchdog) {
1042         if (virAsprintf(&def->watchdog->info.alias, "watchdog%d", 0) < 0)
1043             return -1;
1044     }
1045     if (def->memballoon) {
1046         if (virAsprintf(&def->memballoon->info.alias, "balloon%d", 0) < 0)
1047             return -1;
1048     }
1049     if (def->rng) {
1050         if (virAsprintf(&def->rng->info.alias, "rng%d", 0) < 0)
1051             return -1;
1052     }
1053     if (def->tpm) {
1054         if (virAsprintf(&def->tpm->info.alias, "tpm%d", 0) < 0)
1055             return -1;
1056     }
1057
1058     return 0;
1059 }
1060
1061 /* S390 ccw bus support */
1062
1063 struct _qemuDomainCCWAddressSet {
1064     virHashTablePtr defined;
1065     virDomainDeviceCCWAddress next;
1066 };
1067
1068 static char*
1069 qemuCCWAddressAsString(virDomainDeviceCCWAddressPtr addr)
1070 {
1071     char *addrstr = NULL;
1072
1073     ignore_value(virAsprintf(&addrstr, "%x.%x.%04x",
1074                              addr->cssid,
1075                              addr->ssid,
1076                              addr->devno));
1077     return addrstr;
1078 }
1079
1080 static int
1081 qemuCCWAdressIncrement(virDomainDeviceCCWAddressPtr addr)
1082 {
1083     virDomainDeviceCCWAddress ccwaddr = *addr;
1084
1085     /* We are not touching subchannel sets and channel subsystems */
1086     if (++ccwaddr.devno > VIR_DOMAIN_DEVICE_CCW_MAX_DEVNO)
1087         return -1;
1088
1089     *addr = ccwaddr;
1090     return 0;
1091 }
1092
1093
1094 int qemuDomainCCWAddressAssign(virDomainDeviceInfoPtr dev,
1095                                qemuDomainCCWAddressSetPtr addrs,
1096                                bool autoassign)
1097 {
1098     int ret = -1;
1099     char *addr = NULL;
1100
1101     if (dev->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW)
1102         return 0;
1103
1104     if (!autoassign && dev->addr.ccw.assigned) {
1105         if (!(addr = qemuCCWAddressAsString(&dev->addr.ccw)))
1106             goto cleanup;
1107
1108         if (virHashLookup(addrs->defined, addr)) {
1109             virReportError(VIR_ERR_XML_ERROR,
1110                            _("The CCW devno '%s' is in use already "),
1111                            addr);
1112             goto cleanup;
1113         }
1114     } else if (autoassign && !dev->addr.ccw.assigned) {
1115         if (!(addr = qemuCCWAddressAsString(&addrs->next)) < 0)
1116             goto cleanup;
1117
1118         while (virHashLookup(addrs->defined, addr)) {
1119             if (qemuCCWAdressIncrement(&addrs->next) < 0) {
1120                 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1121                                _("There are no more free CCW devnos."));
1122                 goto cleanup;
1123             }
1124             VIR_FREE(addr);
1125             addr = qemuCCWAddressAsString(&addrs->next);
1126         }
1127         dev->addr.ccw = addrs->next;
1128         dev->addr.ccw.assigned = true;
1129     } else {
1130         return 0;
1131     }
1132
1133     if (virHashAddEntry(addrs->defined, addr, addr) < 0)
1134         goto cleanup;
1135     else
1136         addr = NULL; /* memory will be freed by hash table */
1137
1138     ret = 0;
1139
1140  cleanup:
1141     VIR_FREE(addr);
1142     return ret;
1143 }
1144
1145 static void
1146 qemuDomainPrimeVirtioDeviceAddresses(virDomainDefPtr def,
1147                                      enum virDomainDeviceAddressType type)
1148 {
1149     /*
1150        declare address-less virtio devices to be of address type 'type'
1151        disks, networks, consoles, controllers, memballoon and rng in this
1152        order
1153     */
1154     size_t i;
1155
1156     for (i = 0; i < def->ndisks; i++) {
1157         if (def->disks[i]->bus == VIR_DOMAIN_DISK_BUS_VIRTIO &&
1158             def->disks[i]->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
1159             def->disks[i]->info.type = type;
1160     }
1161
1162     for (i = 0; i < def->nnets; i++) {
1163         if (STREQ(def->nets[i]->model, "virtio") &&
1164             def->nets[i]->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
1165             def->nets[i]->info.type = type;
1166         }
1167     }
1168
1169     for (i = 0; i < def->ncontrollers; i++) {
1170         if ((def->controllers[i]->type ==
1171              VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL ||
1172              def->controllers[i]->type ==
1173              VIR_DOMAIN_CONTROLLER_TYPE_SCSI) &&
1174             def->controllers[i]->info.type ==
1175             VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
1176             def->controllers[i]->info.type = type;
1177     }
1178
1179     if (def->memballoon &&
1180         def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO &&
1181         def->memballoon->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
1182         def->memballoon->info.type = type;
1183
1184     if (def->rng &&
1185         def->rng->model == VIR_DOMAIN_RNG_MODEL_VIRTIO &&
1186         def->rng->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
1187         def->rng->info.type = type;
1188 }
1189
1190 static int
1191 qemuDomainCCWAddressAllocate(virDomainDefPtr def ATTRIBUTE_UNUSED,
1192                              virDomainDeviceDefPtr dev ATTRIBUTE_UNUSED,
1193                              virDomainDeviceInfoPtr info,
1194                              void *data)
1195 {
1196     return qemuDomainCCWAddressAssign(info, data, true);
1197 }
1198
1199 static int
1200 qemuDomainCCWAddressValidate(virDomainDefPtr def ATTRIBUTE_UNUSED,
1201                              virDomainDeviceDefPtr dev ATTRIBUTE_UNUSED,
1202                              virDomainDeviceInfoPtr info,
1203                              void *data)
1204 {
1205     return qemuDomainCCWAddressAssign(info, data, false);
1206 }
1207
1208 static int
1209 qemuDomainCCWAddressReleaseAddr(qemuDomainCCWAddressSetPtr addrs,
1210                                 virDomainDeviceInfoPtr dev)
1211 {
1212     char *addr;
1213     int ret;
1214
1215     addr = qemuCCWAddressAsString(&(dev->addr.ccw));
1216     if (!addr)
1217         return -1;
1218
1219     if ((ret = virHashRemoveEntry(addrs->defined, addr)) == 0 &&
1220         dev->addr.ccw.cssid == addrs->next.cssid &&
1221         dev->addr.ccw.ssid == addrs->next.ssid &&
1222         dev->addr.ccw.devno < addrs->next.devno) {
1223         addrs->next.devno = dev->addr.ccw.devno;
1224         addrs->next.assigned = false;
1225     }
1226
1227     VIR_FREE(addr);
1228
1229     return ret;
1230 }
1231
1232 void qemuDomainCCWAddressSetFree(qemuDomainCCWAddressSetPtr addrs)
1233 {
1234     if (!addrs)
1235         return;
1236
1237     virHashFree(addrs->defined);
1238     VIR_FREE(addrs);
1239 }
1240
1241 static qemuDomainCCWAddressSetPtr
1242 qemuDomainCCWAddressSetCreate(void)
1243 {
1244      qemuDomainCCWAddressSetPtr addrs = NULL;
1245
1246     if (VIR_ALLOC(addrs) < 0)
1247         goto error;
1248
1249     if (!(addrs->defined = virHashCreate(10, virHashValueFree)))
1250         goto error;
1251
1252     /* must use cssid = 0xfe (254) for virtio-ccw devices */
1253     addrs->next.cssid = 254;
1254     addrs->next.ssid = 0;
1255     addrs->next.devno = 0;
1256     addrs->next.assigned = 0;
1257     return addrs;
1258
1259  error:
1260     qemuDomainCCWAddressSetFree(addrs);
1261     return NULL;
1262 }
1263
1264 /*
1265  * Three steps populating CCW devnos
1266  * 1. Allocate empty address set
1267  * 2. Gather addresses with explicit devno
1268  * 3. Assign defaults to the rest
1269  */
1270 static int
1271 qemuDomainAssignS390Addresses(virDomainDefPtr def,
1272                               virQEMUCapsPtr qemuCaps,
1273                               virDomainObjPtr obj)
1274 {
1275     int ret = -1;
1276     qemuDomainCCWAddressSetPtr addrs = NULL;
1277     qemuDomainObjPrivatePtr priv = NULL;
1278
1279     if (STREQLEN(def->os.machine, "s390-ccw", 8) &&
1280         virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_CCW)) {
1281         qemuDomainPrimeVirtioDeviceAddresses(
1282             def, VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW);
1283
1284         if (!(addrs = qemuDomainCCWAddressSetCreate()))
1285             goto cleanup;
1286
1287         if (virDomainDeviceInfoIterate(def, qemuDomainCCWAddressValidate,
1288                                        addrs) < 0)
1289             goto cleanup;
1290
1291         if (virDomainDeviceInfoIterate(def, qemuDomainCCWAddressAllocate,
1292                                        addrs) < 0)
1293             goto cleanup;
1294     } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_S390)) {
1295         /* deal with legacy virtio-s390 */
1296         qemuDomainPrimeVirtioDeviceAddresses(
1297             def, VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390);
1298     }
1299
1300     if (obj && obj->privateData) {
1301         priv = obj->privateData;
1302         if (addrs) {
1303             /* if this is the live domain object, we persist the CCW addresses*/
1304             qemuDomainCCWAddressSetFree(priv->ccwaddrs);
1305             priv->persistentAddrs = 1;
1306             priv->ccwaddrs = addrs;
1307             addrs = NULL;
1308         } else {
1309             priv->persistentAddrs = 0;
1310         }
1311     }
1312     ret = 0;
1313
1314  cleanup:
1315     qemuDomainCCWAddressSetFree(addrs);
1316
1317     return ret;
1318 }
1319
1320 static int
1321 qemuDomainAssignARMVirtioMMIOAddresses(virDomainDefPtr def,
1322                                        virQEMUCapsPtr qemuCaps)
1323 {
1324     if (((def->os.arch == VIR_ARCH_ARMV7L) ||
1325         (def->os.arch == VIR_ARCH_AARCH64)) &&
1326         (STRPREFIX(def->os.machine, "vexpress-") ||
1327             STREQ(def->os.machine, "virt")) &&
1328         virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIRTIO_MMIO)) {
1329         qemuDomainPrimeVirtioDeviceAddresses(
1330             def, VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO);
1331     }
1332     return 0;
1333 }
1334
1335 static int
1336 qemuSpaprVIOFindByReg(virDomainDefPtr def ATTRIBUTE_UNUSED,
1337                       virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
1338                       virDomainDeviceInfoPtr info, void *opaque)
1339 {
1340     virDomainDeviceInfoPtr target = opaque;
1341
1342     if (info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO)
1343         return 0;
1344
1345     /* Match a dev that has a reg, is not us, and has a matching reg */
1346     if (info->addr.spaprvio.has_reg && info != target &&
1347         info->addr.spaprvio.reg == target->addr.spaprvio.reg)
1348         /* Has to be < 0 so virDomainDeviceInfoIterate() will exit */
1349         return -1;
1350
1351     return 0;
1352 }
1353
1354 static int
1355 qemuAssignSpaprVIOAddress(virDomainDefPtr def, virDomainDeviceInfoPtr info,
1356                           unsigned long long default_reg)
1357 {
1358     bool user_reg;
1359     int ret;
1360
1361     if (info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO)
1362         return 0;
1363
1364     /* Check if the user has assigned the reg already, if so use it */
1365     user_reg = info->addr.spaprvio.has_reg;
1366     if (!user_reg) {
1367         info->addr.spaprvio.reg = default_reg;
1368         info->addr.spaprvio.has_reg = true;
1369     }
1370
1371     ret = virDomainDeviceInfoIterate(def, qemuSpaprVIOFindByReg, info);
1372     while (ret != 0) {
1373         if (user_reg) {
1374             virReportError(VIR_ERR_XML_ERROR,
1375                            _("spapr-vio address %#llx already in use"),
1376                            info->addr.spaprvio.reg);
1377             return -EEXIST;
1378         }
1379
1380         /* We assigned the reg, so try a new value */
1381         info->addr.spaprvio.reg += 0x1000;
1382         ret = virDomainDeviceInfoIterate(def, qemuSpaprVIOFindByReg, info);
1383     }
1384
1385     return 0;
1386 }
1387
1388 int qemuDomainAssignSpaprVIOAddresses(virDomainDefPtr def,
1389                                       virQEMUCapsPtr qemuCaps)
1390 {
1391     size_t i;
1392     int ret = -1;
1393     int model;
1394
1395     /* Default values match QEMU. See spapr_(llan|vscsi|vty).c */
1396
1397     for (i = 0; i < def->nnets; i++) {
1398         if (def->nets[i]->model &&
1399             STREQ(def->nets[i]->model, "spapr-vlan"))
1400             def->nets[i]->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO;
1401         if (qemuAssignSpaprVIOAddress(def, &def->nets[i]->info,
1402                                       VIO_ADDR_NET) < 0)
1403             goto cleanup;
1404     }
1405
1406     for (i = 0; i < def->ncontrollers; i++) {
1407         model = def->controllers[i]->model;
1408         if (def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI) {
1409             if (qemuSetSCSIControllerModel(def, qemuCaps, &model) < 0)
1410                 goto cleanup;
1411         }
1412
1413         if (model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_IBMVSCSI &&
1414             def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI)
1415             def->controllers[i]->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO;
1416         if (qemuAssignSpaprVIOAddress(def, &def->controllers[i]->info,
1417                                       VIO_ADDR_SCSI) < 0)
1418             goto cleanup;
1419     }
1420
1421     for (i = 0; i < def->nserials; i++) {
1422         if (def->serials[i]->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL &&
1423             (def->os.arch == VIR_ARCH_PPC64) &&
1424             STREQ(def->os.machine, "pseries"))
1425             def->serials[i]->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO;
1426         if (qemuAssignSpaprVIOAddress(def, &def->serials[i]->info,
1427                                       VIO_ADDR_SERIAL) < 0)
1428             goto cleanup;
1429     }
1430
1431     if (def->nvram) {
1432         if (def->os.arch == VIR_ARCH_PPC64 &&
1433             STREQ(def->os.machine, "pseries"))
1434             def->nvram->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO;
1435         if (qemuAssignSpaprVIOAddress(def, &def->nvram->info,
1436                                       VIO_ADDR_NVRAM) < 0)
1437             goto cleanup;
1438     }
1439
1440     /* No other devices are currently supported on spapr-vio */
1441
1442     ret = 0;
1443
1444  cleanup:
1445     return ret;
1446 }
1447
1448
1449 static int
1450 qemuCollectPCIAddress(virDomainDefPtr def ATTRIBUTE_UNUSED,
1451                       virDomainDeviceDefPtr device,
1452                       virDomainDeviceInfoPtr info,
1453                       void *opaque)
1454 {
1455     virDomainPCIAddressSetPtr addrs = opaque;
1456     int ret = -1;
1457     virDevicePCIAddressPtr addr = &info->addr.pci;
1458     bool entireSlot;
1459     /* flags may be changed from default below */
1460     virDomainPCIConnectFlags flags = (VIR_PCI_CONNECT_HOTPLUGGABLE |
1461                                       VIR_PCI_CONNECT_TYPE_PCI);
1462
1463     if ((info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)
1464         || ((device->type == VIR_DOMAIN_DEVICE_HOSTDEV) &&
1465             (device->data.hostdev->parent.type != VIR_DOMAIN_DEVICE_NONE))) {
1466         /* If a hostdev has a parent, its info will be a part of the
1467          * parent, and will have its address collected during the scan
1468          * of the parent's device type.
1469         */
1470         return 0;
1471     }
1472
1473     /* Change flags according to differing requirements of different
1474      * devices.
1475      */
1476     switch (device->type) {
1477     case VIR_DOMAIN_DEVICE_CONTROLLER:
1478         switch (device->data.controller->type) {
1479         case  VIR_DOMAIN_CONTROLLER_TYPE_PCI:
1480             switch (device->data.controller->model) {
1481             case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
1482                 /* pci-bridge needs a PCI slot, but it isn't
1483                  * hot-pluggable, so it doesn't need a hot-pluggable slot.
1484                  */
1485                 flags = VIR_PCI_CONNECT_TYPE_PCI;
1486                 break;
1487             case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
1488                 /* pci-bridge needs a PCIe slot, but it isn't
1489                  * hot-pluggable, so it doesn't need a hot-pluggable slot.
1490                  */
1491                 flags = VIR_PCI_CONNECT_TYPE_PCIE;
1492                 break;
1493             default:
1494                 break;
1495             }
1496             break;
1497
1498         case VIR_DOMAIN_CONTROLLER_TYPE_SATA:
1499             /* SATA controllers aren't hot-plugged, and can be put in
1500              * either a PCI or PCIe slot
1501              */
1502             flags = VIR_PCI_CONNECT_TYPE_PCI | VIR_PCI_CONNECT_TYPE_PCIE;
1503             break;
1504
1505         case VIR_DOMAIN_CONTROLLER_TYPE_USB:
1506            /* allow UHCI and EHCI controllers to be manually placed on
1507             * the PCIe bus (but don't put them there automatically)
1508             */
1509            switch (device->data.controller->model) {
1510            case VIR_DOMAIN_CONTROLLER_MODEL_USB_EHCI:
1511            case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_EHCI1:
1512            case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI1:
1513            case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI2:
1514            case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI3:
1515            case VIR_DOMAIN_CONTROLLER_MODEL_USB_VT82C686B_UHCI:
1516               flags = (VIR_PCI_CONNECT_TYPE_PCI |
1517                        VIR_PCI_CONNECT_TYPE_EITHER_IF_CONFIG);
1518               break;
1519            case VIR_DOMAIN_CONTROLLER_MODEL_USB_NEC_XHCI:
1520               /* should this be PCIE-only? Or do we need to allow PCI
1521                * for backward compatibility?
1522                */
1523               flags = VIR_PCI_CONNECT_TYPE_PCI | VIR_PCI_CONNECT_TYPE_PCIE;
1524               break;
1525            case VIR_DOMAIN_CONTROLLER_MODEL_USB_PCI_OHCI:
1526            case VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX3_UHCI:
1527            case VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX4_UHCI:
1528               /* Allow these for PCI only */
1529               break;
1530            }
1531         }
1532         break;
1533
1534     case VIR_DOMAIN_DEVICE_SOUND:
1535         switch (device->data.sound->model) {
1536         case VIR_DOMAIN_SOUND_MODEL_ICH6:
1537         case VIR_DOMAIN_SOUND_MODEL_ICH9:
1538             flags = (VIR_PCI_CONNECT_TYPE_PCI |
1539                      VIR_PCI_CONNECT_TYPE_EITHER_IF_CONFIG);
1540             break;
1541         }
1542         break;
1543
1544     case VIR_DOMAIN_DEVICE_VIDEO:
1545         /* video cards aren't hot-plugged, and can be put in either a
1546          * PCI or PCIe slot
1547          */
1548         flags = VIR_PCI_CONNECT_TYPE_PCI | VIR_PCI_CONNECT_TYPE_PCIE;
1549         break;
1550     }
1551
1552     /* Ignore implicit controllers on slot 0:0:1.0:
1553      * implicit IDE controller on 0:0:1.1 (no qemu command line)
1554      * implicit USB controller on 0:0:1.2 (-usb)
1555      *
1556      * If the machine does have a PCI bus, they will get reserved
1557      * in qemuAssignDevicePCISlots().
1558      */
1559
1560     /* These are the IDE and USB controllers in the PIIX3, hardcoded
1561      * to bus 0 slot 1.  They cannot be attached to a PCIe slot, only
1562      * PCI.
1563      */
1564     if (device->type == VIR_DOMAIN_DEVICE_CONTROLLER && addr->domain == 0 &&
1565         addr->bus == 0 && addr->slot == 1) {
1566         virDomainControllerDefPtr cont = device->data.controller;
1567
1568         if ((cont->type == VIR_DOMAIN_CONTROLLER_TYPE_IDE && cont->idx == 0 &&
1569              addr->function == 1) ||
1570             (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_USB && cont->idx == 0 &&
1571              (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX3_UHCI ||
1572               cont->model == -1) && addr->function == 2)) {
1573             /* Note the check for nbuses > 0 - if there are no PCI
1574              * buses, we skip this check. This is a quirk required for
1575              * some machinetypes such as s390, which pretend to have a
1576              * PCI bus for long enough to generate the "-usb" on the
1577              * commandline, but that don't really care if a PCI bus
1578              * actually exists. */
1579             if (addrs->nbuses > 0 &&
1580                 !(addrs->buses[0].flags & VIR_PCI_CONNECT_TYPE_PCI)) {
1581                 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1582                                _("Bus 0 must be PCI for integrated PIIX3 "
1583                                  "USB or IDE controllers"));
1584                 return -1;
1585             } else {
1586                 return 0;
1587             }
1588         }
1589     }
1590
1591     entireSlot = (addr->function == 0 &&
1592                   addr->multi != VIR_DEVICE_ADDRESS_PCI_MULTI_ON);
1593
1594     if (virDomainPCIAddressReserveAddr(addrs, addr, flags,
1595                                        entireSlot, true) < 0)
1596         goto cleanup;
1597
1598     ret = 0;
1599  cleanup:
1600     return ret;
1601 }
1602
1603 static bool
1604 qemuDomainSupportsPCI(virDomainDefPtr def)
1605 {
1606     if ((def->os.arch != VIR_ARCH_ARMV7L) && (def->os.arch != VIR_ARCH_AARCH64))
1607         return true;
1608
1609     if (STREQ(def->os.machine, "versatilepb"))
1610         return true;
1611
1612     return false;
1613 }
1614
1615 int
1616 qemuDomainAssignPCIAddresses(virDomainDefPtr def,
1617                              virQEMUCapsPtr qemuCaps,
1618                              virDomainObjPtr obj)
1619 {
1620     int ret = -1;
1621     virDomainPCIAddressSetPtr addrs = NULL;
1622     qemuDomainObjPrivatePtr priv = NULL;
1623
1624     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
1625         int max_idx = -1;
1626         int nbuses = 0;
1627         size_t i;
1628         int rv;
1629         virDomainPCIConnectFlags flags = VIR_PCI_CONNECT_TYPE_PCI;
1630
1631         for (i = 0; i < def->ncontrollers; i++) {
1632             if (def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI) {
1633                 if ((int) def->controllers[i]->idx > max_idx)
1634                     max_idx = def->controllers[i]->idx;
1635             }
1636         }
1637
1638         nbuses = max_idx + 1;
1639
1640         if (nbuses > 0 &&
1641             virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_PCI_BRIDGE)) {
1642             virDomainDeviceInfo info;
1643
1644             /* 1st pass to figure out how many PCI bridges we need */
1645             if (!(addrs = qemuDomainPCIAddressSetCreate(def, nbuses, true)))
1646                 goto cleanup;
1647             if (qemuAssignDevicePCISlots(def, qemuCaps, addrs) < 0)
1648                 goto cleanup;
1649             /* Reserve 1 extra slot for a (potential) bridge */
1650             if (virDomainPCIAddressReserveNextSlot(addrs, &info, flags) < 0)
1651                 goto cleanup;
1652
1653             for (i = 1; i < addrs->nbuses; i++) {
1654                 virDomainPCIAddressBusPtr bus = &addrs->buses[i];
1655
1656                 if ((rv = virDomainDefMaybeAddController(
1657                          def, VIR_DOMAIN_CONTROLLER_TYPE_PCI,
1658                          i, bus->model)) < 0)
1659                     goto cleanup;
1660                 /* If we added a new bridge, we will need one more address */
1661                 if (rv > 0 && virDomainPCIAddressReserveNextSlot(addrs, &info,
1662                                                                  flags) < 0)
1663                         goto cleanup;
1664             }
1665             nbuses = addrs->nbuses;
1666             virDomainPCIAddressSetFree(addrs);
1667             addrs = NULL;
1668
1669         } else if (max_idx > 0) {
1670             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1671                            _("PCI bridges are not supported "
1672                              "by this QEMU binary"));
1673             goto cleanup;
1674         }
1675
1676         if (!(addrs = qemuDomainPCIAddressSetCreate(def, nbuses, false)))
1677             goto cleanup;
1678
1679         if (qemuDomainSupportsPCI(def)) {
1680             if (qemuAssignDevicePCISlots(def, qemuCaps, addrs) < 0)
1681                 goto cleanup;
1682         }
1683     }
1684
1685     if (obj && obj->privateData) {
1686         priv = obj->privateData;
1687         if (addrs) {
1688             /* if this is the live domain object, we persist the PCI addresses*/
1689             virDomainPCIAddressSetFree(priv->pciaddrs);
1690             priv->persistentAddrs = 1;
1691             priv->pciaddrs = addrs;
1692             addrs = NULL;
1693         } else {
1694             priv->persistentAddrs = 0;
1695         }
1696     }
1697
1698     ret = 0;
1699
1700  cleanup:
1701     virDomainPCIAddressSetFree(addrs);
1702
1703     return ret;
1704 }
1705
1706 int qemuDomainAssignAddresses(virDomainDefPtr def,
1707                               virQEMUCapsPtr qemuCaps,
1708                               virDomainObjPtr obj)
1709 {
1710     int rc;
1711
1712     rc = qemuDomainAssignSpaprVIOAddresses(def, qemuCaps);
1713     if (rc)
1714         return rc;
1715
1716     rc = qemuDomainAssignS390Addresses(def, qemuCaps, obj);
1717     if (rc)
1718         return rc;
1719
1720     rc = qemuDomainAssignARMVirtioMMIOAddresses(def, qemuCaps);
1721     if (rc)
1722         return rc;
1723
1724     return qemuDomainAssignPCIAddresses(def, qemuCaps, obj);
1725 }
1726
1727
1728 virDomainPCIAddressSetPtr
1729 qemuDomainPCIAddressSetCreate(virDomainDefPtr def,
1730                               unsigned int nbuses,
1731                               bool dryRun)
1732 {
1733     virDomainPCIAddressSetPtr addrs;
1734     size_t i;
1735
1736     if ((addrs = virDomainPCIAddressSetAlloc(nbuses)) == NULL)
1737         return NULL;
1738
1739     addrs->nbuses = nbuses;
1740     addrs->dryRun = dryRun;
1741
1742     /* As a safety measure, set default model='pci-root' for first pci
1743      * controller and 'pci-bridge' for all subsequent. After setting
1744      * those defaults, then scan the config and set the actual model
1745      * for all addrs[idx]->bus that already have a corresponding
1746      * controller in the config.
1747      *
1748      */
1749     if (nbuses > 0)
1750        virDomainPCIAddressBusSetModel(&addrs->buses[0],
1751                                       VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT);
1752     for (i = 1; i < nbuses; i++) {
1753         virDomainPCIAddressBusSetModel(&addrs->buses[i],
1754                                        VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE);
1755     }
1756
1757     for (i = 0; i < def->ncontrollers; i++) {
1758         size_t idx = def->controllers[i]->idx;
1759
1760         if (def->controllers[i]->type != VIR_DOMAIN_CONTROLLER_TYPE_PCI)
1761             continue;
1762
1763         if (idx >= addrs->nbuses) {
1764             virReportError(VIR_ERR_INTERNAL_ERROR,
1765                            _("Inappropriate new pci controller index %zu "
1766                              "not found in addrs"), idx);
1767             goto error;
1768         }
1769
1770         if (virDomainPCIAddressBusSetModel(&addrs->buses[idx],
1771                                            def->controllers[i]->model) < 0)
1772             goto error;
1773         }
1774
1775     if (virDomainDeviceInfoIterate(def, qemuCollectPCIAddress, addrs) < 0)
1776         goto error;
1777
1778     return addrs;
1779
1780  error:
1781     virDomainPCIAddressSetFree(addrs);
1782     return NULL;
1783 }
1784
1785
1786 void
1787 qemuDomainReleaseDeviceAddress(virDomainObjPtr vm,
1788                                virDomainDeviceInfoPtr info,
1789                                const char *devstr)
1790 {
1791     qemuDomainObjPrivatePtr priv = vm->privateData;
1792
1793     if (!devstr)
1794         devstr = info->alias;
1795
1796     if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW &&
1797         STREQLEN(vm->def->os.machine, "s390-ccw", 8) &&
1798         virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_CCW) &&
1799         qemuDomainCCWAddressReleaseAddr(priv->ccwaddrs, info) < 0)
1800         VIR_WARN("Unable to release CCW address on %s",
1801                  NULLSTR(devstr));
1802     else if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI &&
1803              virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE) &&
1804              virDomainPCIAddressReleaseSlot(priv->pciaddrs,
1805                                             &info->addr.pci) < 0)
1806         VIR_WARN("Unable to release PCI address on %s",
1807                  NULLSTR(devstr));
1808 }
1809
1810
1811 #define IS_USB2_CONTROLLER(ctrl) \
1812     (((ctrl)->type == VIR_DOMAIN_CONTROLLER_TYPE_USB) && \
1813      ((ctrl)->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_EHCI1 || \
1814       (ctrl)->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI1 || \
1815       (ctrl)->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI2 || \
1816       (ctrl)->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI3))
1817
1818
1819 static int
1820 qemuValidateDevicePCISlotsPIIX3(virDomainDefPtr def,
1821                                 virQEMUCapsPtr qemuCaps,
1822                                 virDomainPCIAddressSetPtr addrs)
1823 {
1824     int ret = -1;
1825     size_t i;
1826     virDevicePCIAddress tmp_addr;
1827     bool qemuDeviceVideoUsable = virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIDEO_PRIMARY);
1828     char *addrStr = NULL;
1829     virDomainPCIConnectFlags flags = VIR_PCI_CONNECT_HOTPLUGGABLE | VIR_PCI_CONNECT_TYPE_PCI;
1830
1831     /* Verify that first IDE and USB controllers (if any) is on the PIIX3, fn 1 */
1832     for (i = 0; i < def->ncontrollers; i++) {
1833         /* First IDE controller lives on the PIIX3 at slot=1, function=1 */
1834         if (def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_IDE &&
1835             def->controllers[i]->idx == 0) {
1836             if (def->controllers[i]->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
1837                 if (def->controllers[i]->info.addr.pci.domain != 0 ||
1838                     def->controllers[i]->info.addr.pci.bus != 0 ||
1839                     def->controllers[i]->info.addr.pci.slot != 1 ||
1840                     def->controllers[i]->info.addr.pci.function != 1) {
1841                     virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1842                                    _("Primary IDE controller must have PCI address 0:0:1.1"));
1843                     goto cleanup;
1844                 }
1845             } else {
1846                 def->controllers[i]->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
1847                 def->controllers[i]->info.addr.pci.domain = 0;
1848                 def->controllers[i]->info.addr.pci.bus = 0;
1849                 def->controllers[i]->info.addr.pci.slot = 1;
1850                 def->controllers[i]->info.addr.pci.function = 1;
1851             }
1852         } else if (def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
1853                    def->controllers[i]->idx == 0 &&
1854                    (def->controllers[i]->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX3_UHCI ||
1855                     def->controllers[i]->model == -1)) {
1856             if (def->controllers[i]->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
1857                 if (def->controllers[i]->info.addr.pci.domain != 0 ||
1858                     def->controllers[i]->info.addr.pci.bus != 0 ||
1859                     def->controllers[i]->info.addr.pci.slot != 1 ||
1860                     def->controllers[i]->info.addr.pci.function != 2) {
1861                     virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1862                                    _("PIIX3 USB controller must have PCI address 0:0:1.2"));
1863                     goto cleanup;
1864                 }
1865             } else {
1866                 def->controllers[i]->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
1867                 def->controllers[i]->info.addr.pci.domain = 0;
1868                 def->controllers[i]->info.addr.pci.bus = 0;
1869                 def->controllers[i]->info.addr.pci.slot = 1;
1870                 def->controllers[i]->info.addr.pci.function = 2;
1871             }
1872         }
1873     }
1874
1875     /* PIIX3 (ISA bridge, IDE controller, something else unknown, USB controller)
1876      * hardcoded slot=1, multifunction device
1877      */
1878     if (addrs->nbuses) {
1879         memset(&tmp_addr, 0, sizeof(tmp_addr));
1880         tmp_addr.slot = 1;
1881         if (virDomainPCIAddressReserveSlot(addrs, &tmp_addr, flags) < 0)
1882             goto cleanup;
1883     }
1884
1885     if (def->nvideos > 0) {
1886         /* Because the PIIX3 integrated IDE/USB controllers are
1887          * already at slot 1, when qemu looks for the first free slot
1888          * to place the VGA controller (which is always the first
1889          * device added after integrated devices), it *always* ends up
1890          * at slot 2.
1891          */
1892         virDomainVideoDefPtr primaryVideo = def->videos[0];
1893         if (primaryVideo->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
1894             memset(&tmp_addr, 0, sizeof(tmp_addr));
1895             tmp_addr.slot = 2;
1896
1897             if (!(addrStr = virDomainPCIAddressAsString(&tmp_addr)))
1898                 goto cleanup;
1899             if (!virDomainPCIAddressValidate(addrs, &tmp_addr,
1900                                              addrStr, flags, false))
1901                 goto cleanup;
1902
1903             if (virDomainPCIAddressSlotInUse(addrs, &tmp_addr)) {
1904                 if (qemuDeviceVideoUsable) {
1905                     if (virDomainPCIAddressReserveNextSlot(addrs,
1906                                                            &primaryVideo->info,
1907                                                            flags) < 0)
1908                         goto cleanup;
1909                 } else {
1910                     virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1911                                    _("PCI address 0:0:2.0 is in use, "
1912                                      "QEMU needs it for primary video"));
1913                     goto cleanup;
1914                 }
1915             } else {
1916                 if (virDomainPCIAddressReserveSlot(addrs, &tmp_addr, flags) < 0)
1917                     goto cleanup;
1918                 primaryVideo->info.addr.pci = tmp_addr;
1919                 primaryVideo->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
1920             }
1921         } else if (!qemuDeviceVideoUsable) {
1922             if (primaryVideo->info.addr.pci.domain != 0 ||
1923                 primaryVideo->info.addr.pci.bus != 0 ||
1924                 primaryVideo->info.addr.pci.slot != 2 ||
1925                 primaryVideo->info.addr.pci.function != 0) {
1926                 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1927                                _("Primary video card must have PCI address 0:0:2.0"));
1928                 goto cleanup;
1929             }
1930             /* If TYPE == PCI, then qemuCollectPCIAddress() function
1931              * has already reserved the address, so we must skip */
1932         }
1933     } else if (addrs->nbuses && !qemuDeviceVideoUsable) {
1934         memset(&tmp_addr, 0, sizeof(tmp_addr));
1935         tmp_addr.slot = 2;
1936
1937         if (virDomainPCIAddressSlotInUse(addrs, &tmp_addr)) {
1938             VIR_DEBUG("PCI address 0:0:2.0 in use, future addition of a video"
1939                       " device will not be possible without manual"
1940                       " intervention");
1941             virResetLastError();
1942         } else if (virDomainPCIAddressReserveSlot(addrs, &tmp_addr, flags) < 0) {
1943             goto cleanup;
1944         }
1945     }
1946     ret = 0;
1947  cleanup:
1948     VIR_FREE(addrStr);
1949     return ret;
1950 }
1951
1952
1953 static bool
1954 qemuDomainMachineIsQ35(virDomainDefPtr def)
1955 {
1956     return (STRPREFIX(def->os.machine, "pc-q35") ||
1957             STREQ(def->os.machine, "q35"));
1958 }
1959
1960
1961 static bool
1962 qemuDomainMachineIsI440FX(virDomainDefPtr def)
1963 {
1964     return (STREQ(def->os.machine, "pc") ||
1965             STRPREFIX(def->os.machine, "pc-0.") ||
1966             STRPREFIX(def->os.machine, "pc-1.") ||
1967             STRPREFIX(def->os.machine, "pc-i440") ||
1968             STRPREFIX(def->os.machine, "rhel"));
1969 }
1970
1971
1972 static int
1973 qemuDomainValidateDevicePCISlotsQ35(virDomainDefPtr def,
1974                                     virQEMUCapsPtr qemuCaps,
1975                                     virDomainPCIAddressSetPtr addrs)
1976 {
1977     int ret = -1;
1978     size_t i;
1979     virDevicePCIAddress tmp_addr;
1980     bool qemuDeviceVideoUsable = virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIDEO_PRIMARY);
1981     char *addrStr = NULL;
1982     virDomainPCIConnectFlags flags = VIR_PCI_CONNECT_TYPE_PCIE;
1983
1984     for (i = 0; i < def->ncontrollers; i++) {
1985         switch (def->controllers[i]->type) {
1986         case VIR_DOMAIN_CONTROLLER_TYPE_SATA:
1987             /* Verify that the first SATA controller is at 00:1F.2 the
1988              * q35 machine type *always* has a SATA controller at this
1989              * address.
1990              */
1991             if (def->controllers[i]->idx == 0) {
1992                 if (def->controllers[i]->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
1993                     if (def->controllers[i]->info.addr.pci.domain != 0 ||
1994                         def->controllers[i]->info.addr.pci.bus != 0 ||
1995                         def->controllers[i]->info.addr.pci.slot != 0x1F ||
1996                         def->controllers[i]->info.addr.pci.function != 2) {
1997                         virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1998                                        _("Primary SATA controller must have PCI address 0:0:1f.2"));
1999                         goto cleanup;
2000                     }
2001                 } else {
2002                     def->controllers[i]->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
2003                     def->controllers[i]->info.addr.pci.domain = 0;
2004                     def->controllers[i]->info.addr.pci.bus = 0;
2005                     def->controllers[i]->info.addr.pci.slot = 0x1F;
2006                     def->controllers[i]->info.addr.pci.function = 2;
2007                 }
2008             }
2009             break;
2010
2011         case VIR_DOMAIN_CONTROLLER_TYPE_PCI:
2012             if (def->controllers[i]->model == VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE &&
2013                 def->controllers[i]->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
2014                 /* Try to assign this bridge to 00:1E.0 (because that
2015                 * is its standard location on real hardware) unless
2016                 * it's already taken, but don't insist on it.
2017                 */
2018                 memset(&tmp_addr, 0, sizeof(tmp_addr));
2019                 tmp_addr.slot = 0x1E;
2020                 if (!virDomainPCIAddressSlotInUse(addrs, &tmp_addr)) {
2021                     if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr,
2022                                                        flags, true, false) < 0)
2023                         goto cleanup;
2024                     def->controllers[i]->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
2025                     def->controllers[i]->info.addr.pci.domain = 0;
2026                     def->controllers[i]->info.addr.pci.bus = 0;
2027                     def->controllers[i]->info.addr.pci.slot = 0x1E;
2028                     def->controllers[i]->info.addr.pci.function = 0;
2029                 }
2030             }
2031             break;
2032         }
2033     }
2034
2035     /* Reserve slot 0x1F function 0 (ISA bridge, not in config model)
2036      * and function 3 (SMBus, also not (yet) in config model). As with
2037      * the SATA controller, these devices are always present in a q35
2038      * machine; there is no way to not have them.
2039      */
2040     if (addrs->nbuses) {
2041         memset(&tmp_addr, 0, sizeof(tmp_addr));
2042         tmp_addr.slot = 0x1F;
2043         tmp_addr.function = 0;
2044         tmp_addr.multi = 1;
2045         if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags,
2046                                            false, false) < 0)
2047            goto cleanup;
2048         tmp_addr.function = 3;
2049         tmp_addr.multi = 0;
2050         if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags,
2051                                            false, false) < 0)
2052            goto cleanup;
2053     }
2054
2055     if (def->nvideos > 0) {
2056         /* NB: unlike the pc machinetypes, on q35 machinetypes the
2057          * integrated devices are at slot 0x1f, so when qemu looks for
2058          * the first free lot for the first VGA, it will always be at
2059          * slot 1 (which was used up by the integrated PIIX3 devices
2060          * on pc machinetypes).
2061          */
2062         virDomainVideoDefPtr primaryVideo = def->videos[0];
2063         if (primaryVideo->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
2064             memset(&tmp_addr, 0, sizeof(tmp_addr));
2065             tmp_addr.slot = 1;
2066
2067             if (!(addrStr = virDomainPCIAddressAsString(&tmp_addr)))
2068                 goto cleanup;
2069             if (!virDomainPCIAddressValidate(addrs, &tmp_addr,
2070                                              addrStr, flags, false))
2071                 goto cleanup;
2072
2073             if (virDomainPCIAddressSlotInUse(addrs, &tmp_addr)) {
2074                 if (qemuDeviceVideoUsable) {
2075                     if (virDomainPCIAddressReserveNextSlot(addrs,
2076                                                            &primaryVideo->info,
2077                                                            flags) < 0)
2078                         goto cleanup;
2079                 } else {
2080                     virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2081                                    _("PCI address 0:0:1.0 is in use, "
2082                                      "QEMU needs it for primary video"));
2083                     goto cleanup;
2084                 }
2085             } else {
2086                 if (virDomainPCIAddressReserveSlot(addrs, &tmp_addr, flags) < 0)
2087                     goto cleanup;
2088                 primaryVideo->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
2089                 primaryVideo->info.addr.pci = tmp_addr;
2090             }
2091         } else if (!qemuDeviceVideoUsable) {
2092             if (primaryVideo->info.addr.pci.domain != 0 ||
2093                 primaryVideo->info.addr.pci.bus != 0 ||
2094                 primaryVideo->info.addr.pci.slot != 1 ||
2095                 primaryVideo->info.addr.pci.function != 0) {
2096                 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2097                                _("Primary video card must have PCI address 0:0:1.0"));
2098                 goto cleanup;
2099             }
2100             /* If TYPE == PCI, then qemuCollectPCIAddress() function
2101              * has already reserved the address, so we must skip */
2102         }
2103     } else if (addrs->nbuses && !qemuDeviceVideoUsable) {
2104         memset(&tmp_addr, 0, sizeof(tmp_addr));
2105         tmp_addr.slot = 1;
2106
2107         if (virDomainPCIAddressSlotInUse(addrs, &tmp_addr)) {
2108             VIR_DEBUG("PCI address 0:0:1.0 in use, future addition of a video"
2109                       " device will not be possible without manual"
2110                       " intervention");
2111             virResetLastError();
2112         } else if (virDomainPCIAddressReserveSlot(addrs, &tmp_addr, flags) < 0) {
2113             goto cleanup;
2114         }
2115     }
2116     ret = 0;
2117  cleanup:
2118     VIR_FREE(addrStr);
2119     return ret;
2120 }
2121
2122
2123 /*
2124  * This assigns static PCI slots to all configured devices.
2125  * The ordering here is chosen to match the ordering used
2126  * with old QEMU < 0.12, so that if a user updates a QEMU
2127  * host from old QEMU to QEMU >= 0.12, their guests should
2128  * get PCI addresses in the same order as before.
2129  *
2130  * NB, if they previously hotplugged devices then all bets
2131  * are off. Hotplug for old QEMU was unfixably broken wrt
2132  * to stable PCI addressing.
2133  *
2134  * Order is:
2135  *
2136  *  - Host bridge (slot 0)
2137  *  - PIIX3 ISA bridge, IDE controller, something else unknown, USB controller (slot 1)
2138  *  - Video (slot 2)
2139  *
2140  * Incrementally assign slots from 3 onwards:
2141  *
2142  *  - Net
2143  *  - Sound
2144  *  - SCSI controllers
2145  *  - VirtIO block
2146  *  - VirtIO balloon
2147  *  - Host device passthrough
2148  *  - Watchdog (not IB700)
2149  *
2150  * Prior to this function being invoked, qemuCollectPCIAddress() will have
2151  * added all existing PCI addresses from the 'def' to 'addrs'. Thus this
2152  * function must only try to reserve addresses if info.type == NONE and
2153  * skip over info.type == PCI
2154  */
2155 int
2156 qemuAssignDevicePCISlots(virDomainDefPtr def,
2157                          virQEMUCapsPtr qemuCaps,
2158                          virDomainPCIAddressSetPtr addrs)
2159 {
2160     size_t i, j;
2161     virDomainPCIConnectFlags flags;
2162     virDevicePCIAddress tmp_addr;
2163
2164     if ((STRPREFIX(def->os.machine, "pc-0.") ||
2165         STRPREFIX(def->os.machine, "pc-1.") ||
2166         STRPREFIX(def->os.machine, "pc-i440") ||
2167         STREQ(def->os.machine, "pc") ||
2168         STRPREFIX(def->os.machine, "rhel")) &&
2169         qemuValidateDevicePCISlotsPIIX3(def, qemuCaps, addrs) < 0) {
2170         goto error;
2171     }
2172
2173     if (qemuDomainMachineIsQ35(def) &&
2174         qemuDomainValidateDevicePCISlotsQ35(def, qemuCaps, addrs) < 0) {
2175         goto error;
2176     }
2177
2178     /* PCI controllers */
2179     for (i = 0; i < def->ncontrollers; i++) {
2180         if (def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI) {
2181             if (def->controllers[i]->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
2182                 continue;
2183             switch (def->controllers[i]->model) {
2184             case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
2185             case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
2186                 /* pci-root and pcie-root are implicit in the machine,
2187                  * and needs no address */
2188                 continue;
2189             case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
2190                 /* pci-bridge doesn't require hot-plug
2191                  * (although it does provide hot-plug in its slots)
2192                  */
2193                 flags = VIR_PCI_CONNECT_TYPE_PCI;
2194                 break;
2195             case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
2196                 /* dmi-to-pci-bridge requires a non-hotplug PCIe
2197                  * slot
2198                  */
2199                 flags = VIR_PCI_CONNECT_TYPE_PCIE;
2200                 break;
2201             default:
2202                 flags = VIR_PCI_CONNECT_HOTPLUGGABLE | VIR_PCI_CONNECT_TYPE_PCI;
2203                 break;
2204             }
2205             if (virDomainPCIAddressReserveNextSlot(addrs,
2206                                                    &def->controllers[i]->info,
2207                                                    flags) < 0)
2208                 goto error;
2209         }
2210     }
2211
2212     flags = VIR_PCI_CONNECT_HOTPLUGGABLE | VIR_PCI_CONNECT_TYPE_PCI;
2213
2214     for (i = 0; i < def->nfss; i++) {
2215         if (def->fss[i]->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
2216             continue;
2217
2218         /* Only support VirtIO-9p-pci so far. If that changes,
2219          * we might need to skip devices here */
2220         if (virDomainPCIAddressReserveNextSlot(addrs, &def->fss[i]->info,
2221                                                flags) < 0)
2222             goto error;
2223     }
2224
2225     /* Network interfaces */
2226     for (i = 0; i < def->nnets; i++) {
2227         /* type='hostdev' network devices might be USB, and are also
2228          * in hostdevs list anyway, so handle them with other hostdevs
2229          * instead of here.
2230          */
2231         if ((def->nets[i]->type == VIR_DOMAIN_NET_TYPE_HOSTDEV) ||
2232             (def->nets[i]->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)) {
2233             continue;
2234         }
2235         if (virDomainPCIAddressReserveNextSlot(addrs, &def->nets[i]->info,
2236                                                flags) < 0)
2237             goto error;
2238     }
2239
2240     /* Sound cards */
2241     for (i = 0; i < def->nsounds; i++) {
2242         if (def->sounds[i]->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
2243             continue;
2244         /* Skip ISA sound card, and PCSPK */
2245         if (def->sounds[i]->model == VIR_DOMAIN_SOUND_MODEL_SB16 ||
2246             def->sounds[i]->model == VIR_DOMAIN_SOUND_MODEL_PCSPK)
2247             continue;
2248
2249         if (virDomainPCIAddressReserveNextSlot(addrs, &def->sounds[i]->info,
2250                                                flags) < 0)
2251             goto error;
2252     }
2253
2254     /* Device controllers (SCSI, USB, but not IDE, FDC or CCID) */
2255     for (i = 0; i < def->ncontrollers; i++) {
2256         /* PCI controllers have been dealt with earlier */
2257         if (def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI)
2258             continue;
2259
2260         /* USB controller model 'none' doesn't need a PCI address */
2261         if (def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
2262             def->controllers[i]->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE)
2263             continue;
2264
2265         /* FDC lives behind the ISA bridge; CCID is a usb device */
2266         if (def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_FDC ||
2267             def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_CCID)
2268             continue;
2269
2270         /* First IDE controller lives on the PIIX3 at slot=1, function=1,
2271            dealt with earlier on*/
2272         if (def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_IDE &&
2273             def->controllers[i]->idx == 0)
2274             continue;
2275
2276         if (def->controllers[i]->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO)
2277             continue;
2278         if (def->controllers[i]->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
2279             continue;
2280
2281         /* USB2 needs special handling to put all companions in the same slot */
2282         if (IS_USB2_CONTROLLER(def->controllers[i])) {
2283             virDevicePCIAddress addr = { 0, 0, 0, 0, false };
2284             memset(&tmp_addr, 0, sizeof(tmp_addr));
2285             for (j = 0; j < i; j++) {
2286                 if (IS_USB2_CONTROLLER(def->controllers[j]) &&
2287                     def->controllers[j]->idx == def->controllers[i]->idx) {
2288                     addr = def->controllers[j]->info.addr.pci;
2289                     break;
2290                 }
2291             }
2292
2293             switch (def->controllers[i]->model) {
2294             case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_EHCI1:
2295                 addr.function = 7;
2296                 break;
2297             case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI1:
2298                 addr.function = 0;
2299                 addr.multi = VIR_DEVICE_ADDRESS_PCI_MULTI_ON;
2300                 break;
2301             case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI2:
2302                 addr.function = 1;
2303                 break;
2304             case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI3:
2305                 addr.function = 2;
2306                 break;
2307             }
2308
2309             if (addr.slot == 0) {
2310                 /* This is the first part of the controller, so need
2311                  * to find a free slot & then reserve a function */
2312                 if (virDomainPCIAddressGetNextSlot(addrs, &tmp_addr, flags) < 0)
2313                     goto error;
2314
2315                 addr.bus = tmp_addr.bus;
2316                 addr.slot = tmp_addr.slot;
2317
2318                 addrs->lastaddr = addr;
2319                 addrs->lastaddr.function = 0;
2320                 addrs->lastaddr.multi = 0;
2321             }
2322             /* Finally we can reserve the slot+function */
2323             if (virDomainPCIAddressReserveAddr(addrs, &addr, flags,
2324                                                false, false) < 0)
2325                 goto error;
2326
2327             def->controllers[i]->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
2328             def->controllers[i]->info.addr.pci = addr;
2329         } else {
2330             if (virDomainPCIAddressReserveNextSlot(addrs,
2331                                                    &def->controllers[i]->info,
2332                                                    flags) < 0)
2333                 goto error;
2334         }
2335     }
2336
2337     /* Disks (VirtIO only for now) */
2338     for (i = 0; i < def->ndisks; i++) {
2339         /* Only VirtIO disks use PCI addrs */
2340         if (def->disks[i]->bus != VIR_DOMAIN_DISK_BUS_VIRTIO)
2341             continue;
2342
2343         /* don't touch s390 devices */
2344         if (def->disks[i]->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI ||
2345             def->disks[i]->info.type ==
2346             VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390 ||
2347             def->disks[i]->info.type ==
2348             VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW)
2349             continue;
2350
2351         if (def->disks[i]->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
2352             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2353                            _("virtio only support device address type 'PCI'"));
2354             goto error;
2355         }
2356
2357         if (virDomainPCIAddressReserveNextSlot(addrs, &def->disks[i]->info,
2358                                                flags) < 0)
2359             goto error;
2360     }
2361
2362     /* Host PCI devices */
2363     for (i = 0; i < def->nhostdevs; i++) {
2364         if (def->hostdevs[i]->info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
2365             continue;
2366         if (def->hostdevs[i]->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
2367             def->hostdevs[i]->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI)
2368             continue;
2369
2370         if (virDomainPCIAddressReserveNextSlot(addrs,
2371                                                def->hostdevs[i]->info,
2372                                                flags) < 0)
2373             goto error;
2374     }
2375
2376     /* VirtIO balloon */
2377     if (def->memballoon &&
2378         def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO &&
2379         def->memballoon->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
2380         if (virDomainPCIAddressReserveNextSlot(addrs,
2381                                                &def->memballoon->info,
2382                                                flags) < 0)
2383             goto error;
2384     }
2385
2386     /* VirtIO RNG */
2387     if (def->rng &&
2388         def->rng->model == VIR_DOMAIN_RNG_MODEL_VIRTIO &&
2389         def->rng->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
2390         if (virDomainPCIAddressReserveNextSlot(addrs,
2391                                                &def->rng->info, flags) < 0)
2392             goto error;
2393     }
2394
2395     /* A watchdog - skip IB700, it is not a PCI device */
2396     if (def->watchdog &&
2397         def->watchdog->model != VIR_DOMAIN_WATCHDOG_MODEL_IB700 &&
2398         def->watchdog->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
2399         if (virDomainPCIAddressReserveNextSlot(addrs, &def->watchdog->info,
2400                                                flags) < 0)
2401             goto error;
2402     }
2403
2404     /* Assign a PCI slot to the primary video card if there is not an
2405      * assigned address. */
2406     if (def->nvideos > 0 &&
2407         def->videos[0]->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
2408         if (virDomainPCIAddressReserveNextSlot(addrs, &def->videos[0]->info,
2409                                                flags) < 0)
2410             goto error;
2411     }
2412     /* Further non-primary video cards which have to be qxl type */
2413     for (i = 1; i < def->nvideos; i++) {
2414         if (def->videos[i]->type != VIR_DOMAIN_VIDEO_TYPE_QXL) {
2415             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2416                            _("non-primary video device must be type of 'qxl'"));
2417             goto error;
2418         }
2419         if (def->videos[i]->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
2420             continue;
2421         if (virDomainPCIAddressReserveNextSlot(addrs, &def->videos[i]->info,
2422                                                flags) < 0)
2423             goto error;
2424     }
2425     for (i = 0; i < def->ninputs; i++) {
2426         /* Nada - none are PCI based (yet) */
2427     }
2428     for (i = 0; i < def->nparallels; i++) {
2429         /* Nada - none are PCI based (yet) */
2430     }
2431     for (i = 0; i < def->nserials; i++) {
2432         /* Nada - none are PCI based (yet) */
2433     }
2434     for (i = 0; i < def->nchannels; i++) {
2435         /* Nada - none are PCI based (yet) */
2436     }
2437     for (i = 0; i < def->nhubs; i++) {
2438         /* Nada - none are PCI based (yet) */
2439     }
2440
2441     return 0;
2442
2443  error:
2444     return -1;
2445 }
2446
2447 static void
2448 qemuUSBId(virBufferPtr buf, int idx)
2449 {
2450     if (idx == 0)
2451         virBufferAddLit(buf, "usb");
2452     else
2453         virBufferAsprintf(buf, "usb%d", idx);
2454 }
2455
2456 static int
2457 qemuBuildDeviceAddressStr(virBufferPtr buf,
2458                           virDomainDefPtr domainDef,
2459                           virDomainDeviceInfoPtr info,
2460                           virQEMUCapsPtr qemuCaps)
2461 {
2462     int ret = -1;
2463     char *devStr = NULL;
2464
2465     if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
2466         const char *contAlias = NULL;
2467         size_t i;
2468
2469         if (!(devStr = virDomainPCIAddressAsString(&info->addr.pci)))
2470             goto cleanup;
2471         for (i = 0; i < domainDef->ncontrollers; i++) {
2472             virDomainControllerDefPtr cont = domainDef->controllers[i];
2473
2474             if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI &&
2475                 cont->idx == info->addr.pci.bus) {
2476                 contAlias = cont->info.alias;
2477                 if (!contAlias) {
2478                     virReportError(VIR_ERR_INTERNAL_ERROR,
2479                                    _("Device alias was not set for PCI "
2480                                      "controller with index %u required "
2481                                      "for device at address %s"),
2482                                    info->addr.pci.bus, devStr);
2483                     goto cleanup;
2484                 }
2485                 break;
2486             }
2487         }
2488         if (!contAlias) {
2489             virReportError(VIR_ERR_INTERNAL_ERROR,
2490                            _("Could not find PCI "
2491                              "controller with index %u required "
2492                              "for device at address %s"),
2493                            info->addr.pci.bus, devStr);
2494             goto cleanup;
2495         }
2496
2497         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_PCI_MULTIFUNCTION)) {
2498             if (info->addr.pci.function != 0) {
2499                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2500                                _("Only PCI device addresses with function=0 "
2501                                  "are supported with this QEMU binary"));
2502                 goto cleanup;
2503             }
2504             if (info->addr.pci.multi == VIR_DEVICE_ADDRESS_PCI_MULTI_ON) {
2505                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2506                                _("'multifunction=on' is not supported with "
2507                                  "this QEMU binary"));
2508                 goto cleanup;
2509             }
2510         }
2511
2512         /*
2513          * PCI bridge support is required for multiple buses
2514          * 'pci.%u' is the ID of the bridge as specified in
2515          * qemuBuildControllerDevStr
2516          *
2517          * PCI_MULTIBUS capability indicates that the implicit
2518          * PCI bus is named 'pci.0' instead of 'pci'.
2519          */
2520         if (info->addr.pci.bus != 0) {
2521             if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_PCI_BRIDGE)) {
2522                 virBufferAsprintf(buf, ",bus=%s", contAlias);
2523             } else {
2524                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2525                                _("Multiple PCI buses are not supported "
2526                                  "with this QEMU binary"));
2527                 goto cleanup;
2528             }
2529         } else {
2530             if (virQEMUCapsHasPCIMultiBus(qemuCaps, domainDef)) {
2531                 virBufferAsprintf(buf, ",bus=%s", contAlias);
2532             } else {
2533                 virBufferAddLit(buf, ",bus=pci");
2534             }
2535         }
2536         if (info->addr.pci.multi == VIR_DEVICE_ADDRESS_PCI_MULTI_ON)
2537             virBufferAddLit(buf, ",multifunction=on");
2538         else if (info->addr.pci.multi == VIR_DEVICE_ADDRESS_PCI_MULTI_OFF)
2539             virBufferAddLit(buf, ",multifunction=off");
2540         virBufferAsprintf(buf, ",addr=0x%x", info->addr.pci.slot);
2541         if (info->addr.pci.function != 0)
2542            virBufferAsprintf(buf, ".0x%x", info->addr.pci.function);
2543     } else if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB) {
2544         virBufferAddLit(buf, ",bus=");
2545         qemuUSBId(buf, info->addr.usb.bus);
2546         virBufferAsprintf(buf, ".0,port=%s", info->addr.usb.port);
2547     } else if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO) {
2548         if (info->addr.spaprvio.has_reg)
2549             virBufferAsprintf(buf, ",reg=0x%llx", info->addr.spaprvio.reg);
2550     } else if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW) {
2551         if (info->addr.ccw.assigned)
2552             virBufferAsprintf(buf, ",devno=%x.%x.%04x",
2553                               info->addr.ccw.cssid,
2554                               info->addr.ccw.ssid,
2555                               info->addr.ccw.devno);
2556     }
2557
2558     ret = 0;
2559  cleanup:
2560     VIR_FREE(devStr);
2561     return ret;
2562 }
2563
2564 static int
2565 qemuBuildRomStr(virBufferPtr buf,
2566                 virDomainDeviceInfoPtr info,
2567                 virQEMUCapsPtr qemuCaps)
2568 {
2569     if (info->rombar || info->romfile) {
2570         if (info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
2571             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2572                            "%s", _("rombar and romfile are supported only for PCI devices"));
2573             return -1;
2574         }
2575         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_PCI_ROMBAR)) {
2576             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2577                            "%s", _("rombar and romfile not supported in this QEMU binary"));
2578             return -1;
2579         }
2580
2581         switch (info->rombar) {
2582         case VIR_DOMAIN_PCI_ROMBAR_OFF:
2583             virBufferAddLit(buf, ",rombar=0");
2584             break;
2585         case VIR_DOMAIN_PCI_ROMBAR_ON:
2586             virBufferAddLit(buf, ",rombar=1");
2587             break;
2588         default:
2589             break;
2590         }
2591         if (info->romfile)
2592            virBufferAsprintf(buf, ",romfile=%s", info->romfile);
2593     }
2594     return 0;
2595 }
2596
2597 static int
2598 qemuBuildIoEventFdStr(virBufferPtr buf,
2599                       enum virDomainIoEventFd use,
2600                       virQEMUCapsPtr qemuCaps)
2601 {
2602     if (use && virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_IOEVENTFD))
2603         virBufferAsprintf(buf, ",ioeventfd=%s",
2604                           virDomainIoEventFdTypeToString(use));
2605     return 0;
2606 }
2607
2608 #define QEMU_SERIAL_PARAM_ACCEPTED_CHARS \
2609   "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"
2610
2611 static int
2612 qemuSafeSerialParamValue(const char *value)
2613 {
2614     if (strspn(value, QEMU_SERIAL_PARAM_ACCEPTED_CHARS) != strlen(value)) {
2615         virReportError(VIR_ERR_INTERNAL_ERROR,
2616                        _("driver serial '%s' contains unsafe characters"),
2617                        value);
2618         return -1;
2619     }
2620
2621     return 0;
2622 }
2623
2624 static char *
2625 qemuGetSecretString(virConnectPtr conn,
2626                     const char *scheme,
2627                     bool encoded,
2628                     int diskSecretType,
2629                     char *username,
2630                     unsigned char *uuid, char *usage,
2631                     virSecretUsageType secretUsageType)
2632 {
2633     size_t secret_size;
2634     virSecretPtr sec = NULL;
2635     char *secret = NULL;
2636     char uuidStr[VIR_UUID_STRING_BUFLEN];
2637
2638     /* look up secret */
2639     switch (diskSecretType) {
2640     case VIR_STORAGE_SECRET_TYPE_UUID:
2641         sec = virSecretLookupByUUID(conn, uuid);
2642         virUUIDFormat(uuid, uuidStr);
2643         break;
2644     case VIR_STORAGE_SECRET_TYPE_USAGE:
2645         sec = virSecretLookupByUsage(conn, secretUsageType, usage);
2646         break;
2647     }
2648
2649     if (!sec) {
2650         if (diskSecretType == VIR_STORAGE_SECRET_TYPE_UUID) {
2651             virReportError(VIR_ERR_NO_SECRET,
2652                            _("%s no secret matches uuid '%s'"),
2653                            scheme, uuidStr);
2654         } else {
2655             virReportError(VIR_ERR_NO_SECRET,
2656                            _("%s no secret matches usage value '%s'"),
2657                            scheme, usage);
2658         }
2659         goto cleanup;
2660     }
2661
2662     secret = (char *)conn->secretDriver->secretGetValue(sec, &secret_size, 0,
2663                                                         VIR_SECRET_GET_VALUE_INTERNAL_CALL);
2664     if (!secret) {
2665         if (diskSecretType == VIR_STORAGE_SECRET_TYPE_UUID) {
2666             virReportError(VIR_ERR_INTERNAL_ERROR,
2667                            _("could not get value of the secret for "
2668                              "username '%s' using uuid '%s'"),
2669                            username, uuidStr);
2670         } else {
2671             virReportError(VIR_ERR_INTERNAL_ERROR,
2672                            _("could not get value of the secret for "
2673                              "username '%s' using usage value '%s'"),
2674                            username, usage);
2675         }
2676         goto cleanup;
2677     }
2678
2679     if (encoded) {
2680         char *base64 = NULL;
2681
2682         base64_encode_alloc(secret, secret_size, &base64);
2683         VIR_FREE(secret);
2684         if (!base64) {
2685             virReportOOMError();
2686             goto cleanup;
2687         }
2688         secret = base64;
2689     }
2690
2691  cleanup:
2692     virObjectUnref(sec);
2693     return secret;
2694 }
2695
2696
2697 static int qemuAddRBDHost(virDomainDiskDefPtr disk, char *hostport)
2698 {
2699     char *port;
2700     size_t skip;
2701     char **parts;
2702
2703     if (VIR_EXPAND_N(disk->src.hosts, disk->src.nhosts, 1) < 0)
2704         return -1;
2705
2706     if ((port = strchr(hostport, ']'))) {
2707         /* ipv6, strip brackets */
2708         hostport += 1;
2709         skip = 3;
2710     } else {
2711         port = strstr(hostport, "\\:");
2712         skip = 2;
2713     }
2714
2715     if (port) {
2716         *port = '\0';
2717         port += skip;
2718         if (VIR_STRDUP(disk->src.hosts[disk->src.nhosts - 1].port, port) < 0)
2719             goto error;
2720     } else {
2721         if (VIR_STRDUP(disk->src.hosts[disk->src.nhosts - 1].port, "6789") < 0)
2722             goto error;
2723     }
2724
2725     parts = virStringSplit(hostport, "\\:", 0);
2726     if (!parts)
2727         goto error;
2728     disk->src.hosts[disk->src.nhosts-1].name = virStringJoin((const char **)parts, ":");
2729     virStringFreeList(parts);
2730     if (!disk->src.hosts[disk->src.nhosts-1].name)
2731         goto error;
2732
2733     disk->src.hosts[disk->src.nhosts-1].transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
2734     disk->src.hosts[disk->src.nhosts-1].socket = NULL;
2735
2736     return 0;
2737
2738  error:
2739     VIR_FREE(disk->src.hosts[disk->src.nhosts-1].port);
2740     VIR_FREE(disk->src.hosts[disk->src.nhosts-1].name);
2741     return -1;
2742 }
2743
2744 /* disk->src initially has everything after the rbd: prefix */
2745 static int qemuParseRBDString(virDomainDiskDefPtr disk)
2746 {
2747     char *options = NULL;
2748     char *p, *e, *next;
2749
2750     p = strchr(disk->src.path, ':');
2751     if (p) {
2752         if (VIR_STRDUP(options, p + 1) < 0)
2753             goto error;
2754         *p = '\0';
2755     }
2756
2757     /* options */
2758     if (!options)
2759         return 0; /* all done */
2760
2761     p = options;
2762     while (*p) {
2763         /* find : delimiter or end of string */
2764         for (e = p; *e && *e != ':'; ++e) {
2765             if (*e == '\\') {
2766                 e++;
2767                 if (*e == '\0')
2768                     break;
2769             }
2770         }
2771         if (*e == '\0') {
2772             next = e;    /* last kv pair */
2773         } else {
2774             next = e + 1;
2775             *e = '\0';
2776         }
2777
2778         if (STRPREFIX(p, "id=") &&
2779             VIR_STRDUP(disk->src.auth.username, p + strlen("id=")) < 0)
2780             goto error;
2781         if (STRPREFIX(p, "mon_host=")) {
2782             char *h, *sep;
2783
2784             h = p + strlen("mon_host=");
2785             while (h < e) {
2786                 for (sep = h; sep < e; ++sep) {
2787                     if (*sep == '\\' && (sep[1] == ',' ||
2788                                          sep[1] == ';' ||
2789                                          sep[1] == ' ')) {
2790                         *sep = '\0';
2791                         sep += 2;
2792                         break;
2793                     }
2794                 }
2795                 if (qemuAddRBDHost(disk, h) < 0)
2796                     goto error;
2797
2798                 h = sep;
2799             }
2800         }
2801
2802         p = next;
2803     }
2804     VIR_FREE(options);
2805     return 0;
2806
2807  error:
2808     VIR_FREE(options);
2809     return -1;
2810 }
2811
2812 static int
2813 qemuParseDriveURIString(virDomainDiskDefPtr def, virURIPtr uri,
2814                         const char *scheme)
2815 {
2816     int ret = -1;
2817     char *transp = NULL;
2818     char *sock = NULL;
2819     char *volimg = NULL;
2820     char *secret = NULL;
2821
2822     if (VIR_ALLOC(def->src.hosts) < 0)
2823         goto error;
2824
2825     transp = strchr(uri->scheme, '+');
2826     if (transp)
2827         *transp++ = 0;
2828
2829     if (!STREQ(uri->scheme, scheme)) {
2830         virReportError(VIR_ERR_INTERNAL_ERROR,
2831                        _("Invalid transport/scheme '%s'"), uri->scheme);
2832         goto error;
2833     }
2834
2835     if (!transp) {
2836         def->src.hosts->transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
2837     } else {
2838         def->src.hosts->transport = virStorageNetHostTransportTypeFromString(transp);
2839         if (def->src.hosts->transport < 0) {
2840             virReportError(VIR_ERR_INTERNAL_ERROR,
2841                            _("Invalid %s transport type '%s'"), scheme, transp);
2842             goto error;
2843         }
2844     }
2845     def->src.nhosts = 0; /* set to 1 once everything succeeds */
2846
2847     if (def->src.hosts->transport != VIR_STORAGE_NET_HOST_TRANS_UNIX) {
2848         if (VIR_STRDUP(def->src.hosts->name, uri->server) < 0)
2849             goto error;
2850
2851         if (virAsprintf(&def->src.hosts->port, "%d", uri->port) < 0)
2852             goto error;
2853     } else {
2854         def->src.hosts->name = NULL;
2855         def->src.hosts->port = 0;
2856         if (uri->query) {
2857             if (STRPREFIX(uri->query, "socket=")) {
2858                 sock = strchr(uri->query, '=') + 1;
2859                 if (VIR_STRDUP(def->src.hosts->socket, sock) < 0)
2860                     goto error;
2861             } else {
2862                 virReportError(VIR_ERR_INTERNAL_ERROR,
2863                                _("Invalid query parameter '%s'"), uri->query);
2864                 goto error;
2865             }
2866         }
2867     }
2868     if (uri->path) {
2869         volimg = uri->path + 1; /* skip the prefix slash */
2870         VIR_FREE(def->src.path);
2871         if (VIR_STRDUP(def->src.path, volimg) < 0)
2872             goto error;
2873     } else {
2874         VIR_FREE(def->src.path);
2875     }
2876
2877     if (uri->user) {
2878         secret = strchr(uri->user, ':');
2879         if (secret)
2880             *secret = '\0';
2881
2882         if (VIR_STRDUP(def->src.auth.username, uri->user) < 0)
2883             goto error;
2884     }
2885
2886     def->src.nhosts = 1;
2887     ret = 0;
2888
2889  cleanup:
2890     virURIFree(uri);
2891
2892     return ret;
2893
2894  error:
2895     virStorageNetHostDefClear(def->src.hosts);
2896     VIR_FREE(def->src.hosts);
2897     goto cleanup;
2898 }
2899
2900 static int
2901 qemuParseGlusterString(virDomainDiskDefPtr def)
2902 {
2903     virURIPtr uri = NULL;
2904
2905     if (!(uri = virURIParse(def->src.path)))
2906         return -1;
2907
2908     return qemuParseDriveURIString(def, uri, "gluster");
2909 }
2910
2911 static int
2912 qemuParseISCSIString(virDomainDiskDefPtr def)
2913 {
2914     virURIPtr uri = NULL;
2915     char *slash;
2916     unsigned lun;
2917
2918     if (!(uri = virURIParse(def->src.path)))
2919         return -1;
2920
2921     if (uri->path &&
2922         (slash = strchr(uri->path + 1, '/')) != NULL) {
2923
2924         if (slash[1] == '\0')
2925             *slash = '\0';
2926         else if (virStrToLong_ui(slash + 1, NULL, 10, &lun) == -1) {
2927             virReportError(VIR_ERR_INTERNAL_ERROR,
2928                            _("invalid name '%s' for iSCSI disk"),
2929                            def->src.path);
2930             return -1;
2931         }
2932     }
2933
2934     return qemuParseDriveURIString(def, uri, "iscsi");
2935 }
2936
2937 static int
2938 qemuParseNBDString(virDomainDiskDefPtr disk)
2939 {
2940     virStorageNetHostDefPtr h = NULL;
2941     char *host, *port;
2942     char *src;
2943
2944     virURIPtr uri = NULL;
2945
2946     if (strstr(disk->src.path, "://")) {
2947         if (!(uri = virURIParse(disk->src.path)))
2948             return -1;
2949         return qemuParseDriveURIString(disk, uri, "nbd");
2950     }
2951
2952     if (VIR_ALLOC(h) < 0)
2953         goto error;
2954
2955     host = disk->src.path + strlen("nbd:");
2956     if (STRPREFIX(host, "unix:/")) {
2957         src = strchr(host + strlen("unix:"), ':');
2958         if (src)
2959             *src++ = '\0';
2960
2961         h->transport = VIR_STORAGE_NET_HOST_TRANS_UNIX;
2962         if (VIR_STRDUP(h->socket, host + strlen("unix:")) < 0)
2963             goto error;
2964     } else {
2965         port = strchr(host, ':');
2966         if (!port) {
2967             virReportError(VIR_ERR_INTERNAL_ERROR,
2968                            _("cannot parse nbd filename '%s'"), disk->src.path);
2969             goto error;
2970         }
2971
2972         *port++ = '\0';
2973         if (VIR_STRDUP(h->name, host) < 0)
2974             goto error;
2975
2976         src = strchr(port, ':');
2977         if (src)
2978             *src++ = '\0';
2979
2980         if (VIR_STRDUP(h->port, port) < 0)
2981             goto error;
2982     }
2983
2984     if (src && STRPREFIX(src, "exportname=")) {
2985         if (VIR_STRDUP(src, strchr(src, '=') + 1) < 0)
2986             goto error;
2987     } else {
2988         src = NULL;
2989     }
2990
2991     VIR_FREE(disk->src.path);
2992     disk->src.path = src;
2993     disk->src.nhosts = 1;
2994     disk->src.hosts = h;
2995     return 0;
2996
2997  error:
2998     virStorageNetHostDefClear(h);
2999     VIR_FREE(h);
3000     return -1;
3001 }
3002
3003
3004 static int
3005 qemuNetworkDriveGetPort(int protocol,
3006                         const char *port)
3007 {
3008     int ret = 0;
3009
3010     if (port) {
3011         if (virStrToLong_i(port, NULL, 10, &ret) < 0) {
3012             virReportError(VIR_ERR_INTERNAL_ERROR,
3013                            _("failed to parse port number '%s'"),
3014                            port);
3015             return -1;
3016         }
3017
3018         return ret;
3019     }
3020
3021     switch ((virStorageNetProtocol) protocol) {
3022         case VIR_STORAGE_NET_PROTOCOL_HTTP:
3023             return 80;
3024
3025         case VIR_STORAGE_NET_PROTOCOL_HTTPS:
3026             return 443;
3027
3028         case VIR_STORAGE_NET_PROTOCOL_FTP:
3029             return 21;
3030
3031         case VIR_STORAGE_NET_PROTOCOL_FTPS:
3032             return 990;
3033
3034         case VIR_STORAGE_NET_PROTOCOL_TFTP:
3035             return 69;
3036
3037         case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
3038             return 7000;
3039
3040         case VIR_STORAGE_NET_PROTOCOL_NBD:
3041             return 10809;
3042
3043         case VIR_STORAGE_NET_PROTOCOL_ISCSI:
3044         case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
3045             /* no default port specified */
3046             return 0;
3047
3048         case VIR_STORAGE_NET_PROTOCOL_RBD:
3049         case VIR_STORAGE_NET_PROTOCOL_LAST:
3050         case VIR_STORAGE_NET_PROTOCOL_NONE:
3051             /* not applicable */
3052             return -1;
3053     }
3054
3055     return -1;
3056 }
3057
3058 #define QEMU_DEFAULT_NBD_PORT "10809"
3059
3060 static char *
3061 qemuBuildNetworkDriveURI(int protocol,
3062                          const char *src,
3063                          const char *volume,
3064                          size_t nhosts,
3065                          virStorageNetHostDefPtr hosts,
3066                          const char *username,
3067                          const char *secret)
3068 {
3069     char *ret = NULL;
3070     virBuffer buf = VIR_BUFFER_INITIALIZER;
3071     virURIPtr uri = NULL;
3072     size_t i;
3073
3074     switch ((virStorageNetProtocol) protocol) {
3075         case VIR_STORAGE_NET_PROTOCOL_NBD:
3076             if (nhosts != 1) {
3077                 virReportError(VIR_ERR_INTERNAL_ERROR,
3078                                _("protocol '%s' accepts only one host"),
3079                                virStorageNetProtocolTypeToString(protocol));
3080                 goto cleanup;
3081             }
3082
3083             if (!((hosts->name && strchr(hosts->name, ':')) ||
3084                   (hosts->transport == VIR_STORAGE_NET_HOST_TRANS_TCP &&
3085                    !hosts->name) ||
3086                   (hosts->transport == VIR_STORAGE_NET_HOST_TRANS_UNIX &&
3087                    hosts->socket &&
3088                    hosts->socket[0] != '/'))) {
3089
3090                 virBufferAddLit(&buf, "nbd:");
3091
3092                 switch (hosts->transport) {
3093                 case VIR_STORAGE_NET_HOST_TRANS_TCP:
3094                     virBufferStrcat(&buf, hosts->name, NULL);
3095                     virBufferAsprintf(&buf, ":%s",
3096                                       hosts->port ? hosts->port :
3097                                       QEMU_DEFAULT_NBD_PORT);
3098                     break;
3099
3100                 case VIR_STORAGE_NET_HOST_TRANS_UNIX:
3101                     if (!hosts->socket) {
3102                         virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3103                                        _("socket attribute required for "
3104                                          "unix transport"));
3105                         goto cleanup;
3106                     }
3107
3108                     virBufferAsprintf(&buf, "unix:%s", hosts->socket);
3109                     break;
3110
3111                 default:
3112                     virReportError(VIR_ERR_INTERNAL_ERROR,
3113                                    _("nbd does not support transport '%s'"),
3114                                    virStorageNetHostTransportTypeToString(hosts->transport));
3115                     goto cleanup;
3116                 }
3117
3118                 if (src)
3119                     virBufferAsprintf(&buf, ":exportname=%s", src);
3120
3121                 if (virBufferError(&buf) < 0) {
3122                     virReportOOMError();
3123                     goto cleanup;
3124                 }
3125
3126                 ret = virBufferContentAndReset(&buf);
3127                 goto cleanup;
3128             }
3129             /* fallthrough */
3130             /* NBD code uses same formatting scheme as others in some cases */
3131
3132         case VIR_STORAGE_NET_PROTOCOL_HTTP:
3133         case VIR_STORAGE_NET_PROTOCOL_HTTPS:
3134         case VIR_STORAGE_NET_PROTOCOL_FTP:
3135         case VIR_STORAGE_NET_PROTOCOL_FTPS:
3136         case VIR_STORAGE_NET_PROTOCOL_TFTP:
3137         case VIR_STORAGE_NET_PROTOCOL_ISCSI:
3138         case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
3139             if (nhosts != 1) {
3140                 virReportError(VIR_ERR_INTERNAL_ERROR,
3141                                _("protocol '%s' accepts only one host"),
3142                                virStorageNetProtocolTypeToString(protocol));
3143                 goto cleanup;
3144             }
3145
3146             if (VIR_ALLOC(uri) < 0)
3147                 goto cleanup;
3148
3149             if (hosts->transport == VIR_STORAGE_NET_HOST_TRANS_TCP) {
3150                 if (VIR_STRDUP(uri->scheme,
3151                                virStorageNetProtocolTypeToString(protocol)) < 0)
3152                     goto cleanup;
3153             } else {
3154                 if (virAsprintf(&uri->scheme, "%s+%s",
3155                                 virStorageNetProtocolTypeToString(protocol),
3156                                 virStorageNetHostTransportTypeToString(hosts->transport)) < 0)
3157                     goto cleanup;
3158             }
3159
3160             if ((uri->port = qemuNetworkDriveGetPort(protocol, hosts->port)) < 0)
3161                 goto cleanup;
3162
3163             if (src) {
3164                 if (volume) {
3165                     if (virAsprintf(&uri->path, "/%s%s",
3166                                     volume, src) < 0)
3167                         goto cleanup;
3168                 } else {
3169                     if (virAsprintf(&uri->path, "%s%s",
3170                                     src[0] == '/' ? "" : "/",
3171                                     src) < 0)
3172                         goto cleanup;
3173                 }
3174             }
3175
3176             if (hosts->socket &&
3177                 virAsprintf(&uri->query, "socket=%s", hosts->socket) < 0)
3178                 goto cleanup;
3179
3180             if (username) {
3181                 if (secret) {
3182                     if (virAsprintf(&uri->user, "%s:%s", username, secret) < 0)
3183                         goto cleanup;
3184                 } else {
3185                     if (VIR_STRDUP(uri->user, username) < 0)
3186                         goto cleanup;
3187                 }
3188             }
3189
3190             if (VIR_STRDUP(uri->server, hosts->name) < 0)
3191                 goto cleanup;
3192
3193             ret = virURIFormat(uri);
3194
3195             break;
3196
3197         case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
3198             if (!src) {
3199                 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3200                                _("missing disk source for 'sheepdog' protocol"));
3201                 goto cleanup;
3202             }
3203
3204             if (nhosts == 0) {
3205                 if (virAsprintf(&ret, "sheepdog:%s", src) < 0)
3206                     goto cleanup;
3207             } else if (nhosts == 1) {
3208                 if (virAsprintf(&ret, "sheepdog:%s:%s:%s",
3209                                 hosts->name,
3210                                 hosts->port ? hosts->port : "7000",
3211                                 src) < 0)
3212                     goto cleanup;
3213             } else {
3214                 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3215                                _("protocol 'sheepdog' accepts up to one host"));
3216                 goto cleanup;
3217             }
3218
3219             break;
3220
3221         case VIR_STORAGE_NET_PROTOCOL_RBD:
3222             if (strchr(src, ':')) {
3223                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
3224                                _("':' not allowed in RBD source volume name '%s'"),
3225                                src);
3226                 goto cleanup;
3227             }
3228
3229             virBufferStrcat(&buf, "rbd:", src, NULL);
3230
3231             if (username) {
3232                 virBufferEscape(&buf, '\\', ":", ":id=%s", username);
3233                 virBufferEscape(&buf, '\\', ":",
3234                                 ":key=%s:auth_supported=cephx\\;none",
3235                                 secret);
3236             } else {
3237                 virBufferAddLit(&buf, ":auth_supported=none");
3238             }
3239
3240             if (nhosts > 0) {
3241                 virBufferAddLit(&buf, ":mon_host=");
3242                 for (i = 0; i < nhosts; i++) {
3243                     if (i)
3244                         virBufferAddLit(&buf, "\\;");
3245
3246                     /* assume host containing : is ipv6 */
3247                     if (strchr(hosts[i].name, ':'))
3248                         virBufferEscape(&buf, '\\', ":", "[%s]", hosts[i].name);
3249                     else
3250                         virBufferAsprintf(&buf, "%s", hosts[i].name);
3251
3252                     if (hosts[i].port)
3253                         virBufferAsprintf(&buf, "\\:%s", hosts[i].port);
3254                 }
3255             }
3256
3257             if (virBufferError(&buf) < 0) {
3258                 virReportOOMError();
3259                 goto cleanup;
3260             }
3261
3262             ret = virBufferContentAndReset(&buf);
3263             break;
3264
3265
3266         case VIR_STORAGE_NET_PROTOCOL_LAST:
3267         case VIR_STORAGE_NET_PROTOCOL_NONE:
3268             goto cleanup;
3269     }
3270
3271  cleanup:
3272     virBufferFreeAndReset(&buf);
3273     virURIFree(uri);
3274
3275     return ret;
3276 }
3277
3278
3279 int
3280 qemuGetDriveSourceString(virStorageSourcePtr src,
3281                          virConnectPtr conn,
3282                          char **source)
3283 {
3284     int actualType = virStorageSourceGetActualType(src);
3285     char *secret = NULL;
3286     char *username = NULL;
3287     int ret = -1;
3288
3289     *source = NULL;
3290
3291     if (conn) {
3292         if (actualType == VIR_STORAGE_TYPE_NETWORK &&
3293             src->auth.username &&
3294             (src->protocol == VIR_STORAGE_NET_PROTOCOL_ISCSI ||
3295              src->protocol == VIR_STORAGE_NET_PROTOCOL_RBD)) {
3296             bool encode = false;
3297             int secretType = VIR_SECRET_USAGE_TYPE_ISCSI;
3298             const char *protocol = virStorageNetProtocolTypeToString(src->protocol);
3299
3300             username = src->auth.username;
3301
3302             if (src->protocol == VIR_STORAGE_NET_PROTOCOL_RBD) {
3303                 /* qemu requires the secret to be encoded for RBD */
3304                 encode = true;
3305                 secretType = VIR_SECRET_USAGE_TYPE_CEPH;
3306             }
3307
3308             if (!(secret = qemuGetSecretString(conn,
3309                                                protocol,
3310                                                encode,
3311                                                src->auth.secretType,
3312                                                username,
3313                                                src->auth.secret.uuid,
3314                                                src->auth.secret.usage,
3315                                                secretType)))
3316                 goto cleanup;
3317         }
3318     }
3319
3320     switch ((virStorageType) actualType) {
3321     case VIR_STORAGE_TYPE_BLOCK:
3322     case VIR_STORAGE_TYPE_FILE:
3323     case VIR_STORAGE_TYPE_DIR:
3324         if (!src->path) {
3325             ret = 1;
3326             goto cleanup;
3327         }
3328
3329         if (VIR_STRDUP(*source, src->path) < 0)
3330             goto cleanup;
3331
3332         break;
3333
3334     case VIR_STORAGE_TYPE_NETWORK:
3335         if (!(*source = qemuBuildNetworkDriveURI(src->protocol,
3336                                                  src->path,
3337                                                  src->volume,
3338                                                  src->nhosts,
3339                                                  src->hosts,
3340                                                  username,
3341                                                  secret)))
3342             goto cleanup;
3343         break;
3344
3345     case VIR_STORAGE_TYPE_VOLUME:
3346     case VIR_STORAGE_TYPE_NONE:
3347     case VIR_STORAGE_TYPE_LAST:
3348         break;
3349     }
3350
3351     ret = 0;
3352
3353  cleanup:
3354     VIR_FREE(secret);
3355     return ret;
3356 }
3357
3358
3359 char *
3360 qemuBuildDriveStr(virConnectPtr conn,
3361                   virDomainDiskDefPtr disk,
3362                   bool bootable,
3363                   virQEMUCapsPtr qemuCaps)
3364 {
3365     virBuffer opt = VIR_BUFFER_INITIALIZER;
3366     const char *bus = virDomainDiskQEMUBusTypeToString(disk->bus);
3367     const char *trans =
3368         virDomainDiskGeometryTransTypeToString(disk->geometry.trans);
3369     int idx = virDiskNameToIndex(disk->dst);
3370     int busid = -1, unitid = -1;
3371     char *source = NULL;
3372     int actualType = virStorageSourceGetActualType(&disk->src);
3373
3374     if (idx < 0) {
3375         virReportError(VIR_ERR_INTERNAL_ERROR,
3376                        _("unsupported disk type '%s'"), disk->dst);
3377         goto error;
3378     }
3379
3380     switch (disk->bus) {
3381     case VIR_DOMAIN_DISK_BUS_SCSI:
3382         if (disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE) {
3383             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3384                            _("unexpected address type for scsi disk"));
3385             goto error;
3386         }
3387
3388         /* Setting bus= attr for SCSI drives, causes a controller
3389          * to be created. Yes this is slightly odd. It is not possible
3390          * to have > 1 bus on a SCSI controller (yet). */
3391         if (disk->info.addr.drive.bus != 0) {
3392             virReportError(VIR_ERR_INTERNAL_ERROR,
3393                            "%s", _("SCSI controller only supports 1 bus"));
3394             goto error;
3395         }
3396         busid = disk->info.addr.drive.controller;
3397         unitid = disk->info.addr.drive.unit;
3398         break;
3399
3400     case VIR_DOMAIN_DISK_BUS_IDE:
3401         if (disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE) {
3402             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3403                            _("unexpected address type for ide disk"));
3404             goto error;
3405         }
3406         /* We can only have 1 IDE controller (currently) */
3407         if (disk->info.addr.drive.controller != 0) {
3408             virReportError(VIR_ERR_INTERNAL_ERROR,
3409                            _("Only 1 %s controller is supported"), bus);
3410             goto error;
3411         }
3412         busid = disk->info.addr.drive.bus;
3413         unitid = disk->info.addr.drive.unit;
3414         break;
3415
3416     case VIR_DOMAIN_DISK_BUS_FDC:
3417         if (disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE) {
3418             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3419                            _("unexpected address type for fdc disk"));
3420             goto error;
3421         }
3422         /* We can only have 1 FDC controller (currently) */
3423         if (disk->info.addr.drive.controller != 0) {
3424             virReportError(VIR_ERR_INTERNAL_ERROR,
3425                            _("Only 1 %s controller is supported"), bus);
3426             goto error;
3427         }
3428         /* We can only have 1 FDC bus (currently) */
3429         if (disk->info.addr.drive.bus != 0) {
3430             virReportError(VIR_ERR_INTERNAL_ERROR,
3431                            _("Only 1 %s bus is supported"), bus);
3432             goto error;
3433         }
3434         if (disk->info.addr.drive.target != 0) {
3435             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3436                            _("target must be 0 for controller fdc"));
3437             goto error;
3438         }
3439         unitid = disk->info.addr.drive.unit;
3440
3441         break;
3442
3443     case VIR_DOMAIN_DISK_BUS_VIRTIO:
3444         idx = -1;
3445         break;
3446
3447     case VIR_DOMAIN_DISK_BUS_XEN:
3448     case VIR_DOMAIN_DISK_BUS_SD:
3449         /* Xen and SD have no address type currently, so assign
3450          * based on index */
3451         break;
3452     }
3453
3454     if (qemuGetDriveSourceString(&disk->src, conn, &source) < 0)
3455         goto error;
3456
3457     if (source &&
3458         !((disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY ||
3459            disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM) &&
3460           disk->tray_status == VIR_DOMAIN_DISK_TRAY_OPEN)) {
3461
3462         virBufferAddLit(&opt, "file=");
3463
3464         switch (actualType) {
3465         case VIR_STORAGE_TYPE_DIR:
3466             /* QEMU only supports magic FAT format for now */
3467             if (disk->src.format > 0 &&
3468                 disk->src.format != VIR_STORAGE_FILE_FAT) {
3469                 virReportError(VIR_ERR_INTERNAL_ERROR,
3470                                _("unsupported disk driver type for '%s'"),
3471                                virStorageFileFormatTypeToString(disk->src.format));
3472                 goto error;
3473             }
3474
3475             if (!disk->readonly) {
3476                 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3477                                _("cannot create virtual FAT disks in read-write mode"));
3478                 goto error;
3479             }
3480
3481             virBufferAddLit(&opt, "fat:");
3482
3483             if (disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY)
3484                 virBufferAddLit(&opt, "floppy:");
3485
3486             break;
3487
3488         case VIR_STORAGE_TYPE_BLOCK:
3489             if (disk->tray_status == VIR_DOMAIN_DISK_TRAY_OPEN) {
3490                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3491                                disk->src.type == VIR_STORAGE_TYPE_VOLUME ?
3492                                _("tray status 'open' is invalid for block type volume") :
3493                                _("tray status 'open' is invalid for block type disk"));
3494                 goto error;
3495             }
3496
3497             break;
3498
3499         default:
3500             break;
3501         }
3502
3503         virBufferEscape(&opt, ',', ",", "%s,", source);
3504     }
3505     VIR_FREE(source);
3506
3507     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE))
3508         virBufferAddLit(&opt, "if=none");
3509     else
3510         virBufferAsprintf(&opt, "if=%s", bus);
3511
3512     if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
3513         if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI) {
3514             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_CD))
3515                 virBufferAddLit(&opt, ",media=cdrom");
3516         } else if (disk->bus == VIR_DOMAIN_DISK_BUS_IDE) {
3517             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_IDE_CD))
3518                 virBufferAddLit(&opt, ",media=cdrom");
3519         } else {
3520             virBufferAddLit(&opt, ",media=cdrom");
3521         }
3522     }
3523
3524     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
3525         virBufferAsprintf(&opt, ",id=%s%s", QEMU_DRIVE_HOST_PREFIX, disk->info.alias);
3526     } else {
3527         if (busid == -1 && unitid == -1) {
3528             if (idx != -1)
3529                 virBufferAsprintf(&opt, ",index=%d", idx);
3530         } else {
3531             if (busid != -1)
3532                 virBufferAsprintf(&opt, ",bus=%d", busid);
3533             if (unitid != -1)
3534                 virBufferAsprintf(&opt, ",unit=%d", unitid);
3535         }
3536     }
3537     if (bootable &&
3538         virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_BOOT) &&
3539         (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK ||
3540          disk->device == VIR_DOMAIN_DISK_DEVICE_LUN) &&
3541         disk->bus != VIR_DOMAIN_DISK_BUS_IDE)
3542         virBufferAddLit(&opt, ",boot=on");
3543     if (disk->readonly &&
3544         virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_READONLY))
3545         virBufferAddLit(&opt, ",readonly=on");
3546     if (disk->transient) {
3547         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3548                        _("transient disks not supported yet"));
3549         goto error;
3550     }
3551     if (disk->src.format > 0 &&
3552         disk->src.type != VIR_STORAGE_TYPE_DIR &&
3553         virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_FORMAT))
3554         virBufferAsprintf(&opt, ",format=%s",
3555                           virStorageFileFormatTypeToString(disk->src.format));
3556
3557     /* generate geometry command string */
3558     if (disk->geometry.cylinders > 0 &&
3559         disk->geometry.heads > 0 &&
3560         disk->geometry.sectors > 0) {
3561
3562         virBufferAsprintf(&opt, ",cyls=%u,heads=%u,secs=%u",
3563                           disk->geometry.cylinders,
3564                           disk->geometry.heads,
3565                           disk->geometry.sectors);
3566
3567         if (disk->geometry.trans != VIR_DOMAIN_DISK_TRANS_DEFAULT)
3568             virBufferEscapeString(&opt, ",trans=%s", trans);
3569     }
3570
3571     if (disk->serial &&
3572         virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_SERIAL)) {
3573         if (qemuSafeSerialParamValue(disk->serial) < 0)
3574             goto error;
3575         virBufferAsprintf(&opt, ",serial=%s", disk->serial);
3576     }
3577
3578     if (disk->cachemode) {
3579         const char *mode = NULL;
3580
3581         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_CACHE_V2)) {
3582             mode = qemuDiskCacheV2TypeToString(disk->cachemode);
3583
3584             if (disk->cachemode == VIR_DOMAIN_DISK_CACHE_DIRECTSYNC &&
3585                 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_CACHE_DIRECTSYNC)) {
3586                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3587                                _("disk cache mode 'directsync' is not "
3588                                  "supported by this QEMU"));
3589                 goto error;
3590             } else if (disk->cachemode == VIR_DOMAIN_DISK_CACHE_UNSAFE &&
3591                 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_CACHE_UNSAFE)) {
3592                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3593                                _("disk cache mode 'unsafe' is not "
3594                                  "supported by this QEMU"));
3595                 goto error;
3596             }
3597         } else {
3598             mode = qemuDiskCacheV1TypeToString(disk->cachemode);
3599         }
3600
3601         virBufferAsprintf(&opt, ",cache=%s", mode);
3602     } else if (disk->shared && !disk->readonly) {
3603         virBufferAddLit(&opt, ",cache=off");
3604     }
3605
3606     if (disk->copy_on_read) {
3607         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_COPY_ON_READ)) {
3608             virBufferAsprintf(&opt, ",copy-on-read=%s",
3609                               virDomainDiskCopyOnReadTypeToString(disk->copy_on_read));
3610         } else {
3611             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3612                            _("copy_on_read is not supported by this QEMU binary"));
3613             goto error;
3614         }
3615     }
3616
3617     if (disk->discard) {
3618         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_DISCARD)) {
3619             virBufferAsprintf(&opt, ",discard=%s",
3620                               virDomainDiskDiscardTypeToString(disk->discard));
3621         } else {
3622             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3623                            _("discard is not supported by this QEMU binary"));
3624             goto error;
3625         }
3626     }
3627
3628     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_MONITOR_JSON)) {
3629         const char *wpolicy = NULL, *rpolicy = NULL;
3630
3631         if (disk->error_policy)
3632             wpolicy = virDomainDiskErrorPolicyTypeToString(disk->error_policy);
3633         if (disk->rerror_policy)
3634             rpolicy = virDomainDiskErrorPolicyTypeToString(disk->rerror_policy);
3635
3636         if (disk->error_policy == VIR_DOMAIN_DISK_ERROR_POLICY_ENOSPACE) {
3637             /* in the case of enospace, the option is spelled
3638              * differently in qemu, and it's only valid for werror,
3639              * not for rerror, so leave leave rerror NULL.
3640              */
3641             wpolicy = "enospc";
3642         } else if (!rpolicy) {
3643             /* for other policies, rpolicy can match wpolicy */
3644             rpolicy = wpolicy;
3645         }
3646
3647         if (wpolicy)
3648             virBufferAsprintf(&opt, ",werror=%s", wpolicy);
3649         if (rpolicy)
3650             virBufferAsprintf(&opt, ",rerror=%s", rpolicy);
3651     }
3652
3653     if (disk->iomode) {
3654         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_AIO)) {
3655             virBufferAsprintf(&opt, ",aio=%s",
3656                               virDomainDiskIoTypeToString(disk->iomode));
3657         } else {
3658             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3659                            _("disk aio mode not supported with this "
3660                              "QEMU binary"));
3661             goto error;
3662         }
3663     }
3664
3665     /* block I/O throttling */
3666     if ((disk->blkdeviotune.total_bytes_sec ||
3667          disk->blkdeviotune.read_bytes_sec ||
3668          disk->blkdeviotune.write_bytes_sec ||
3669          disk->blkdeviotune.total_iops_sec ||
3670          disk->blkdeviotune.read_iops_sec ||
3671          disk->blkdeviotune.write_iops_sec) &&
3672         !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_IOTUNE)) {
3673         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3674                        _("block I/O throttling not supported with this "
3675                          "QEMU binary"));
3676         goto error;
3677     }
3678
3679     if (disk->blkdeviotune.total_bytes_sec) {
3680         virBufferAsprintf(&opt, ",bps=%llu",
3681                           disk->blkdeviotune.total_bytes_sec);
3682     }
3683
3684     if (disk->blkdeviotune.read_bytes_sec) {
3685         virBufferAsprintf(&opt, ",bps_rd=%llu",
3686                           disk->blkdeviotune.read_bytes_sec);
3687     }
3688
3689     if (disk->blkdeviotune.write_bytes_sec) {
3690         virBufferAsprintf(&opt, ",bps_wr=%llu",
3691                           disk->blkdeviotune.write_bytes_sec);
3692     }
3693
3694     if (disk->blkdeviotune.total_iops_sec) {
3695         virBufferAsprintf(&opt, ",iops=%llu",
3696                           disk->blkdeviotune.total_iops_sec);
3697     }
3698
3699     if (disk->blkdeviotune.read_iops_sec) {
3700         virBufferAsprintf(&opt, ",iops_rd=%llu",
3701                           disk->blkdeviotune.read_iops_sec);
3702     }
3703
3704     if (disk->blkdeviotune.write_iops_sec) {
3705         virBufferAsprintf(&opt, ",iops_wr=%llu",
3706                           disk->blkdeviotune.write_iops_sec);
3707     }
3708
3709     if (virBufferError(&opt)) {
3710         virReportOOMError();
3711         goto error;
3712     }
3713
3714     return virBufferContentAndReset(&opt);
3715
3716  error:
3717     VIR_FREE(source);
3718     virBufferFreeAndReset(&opt);
3719     return NULL;
3720 }
3721
3722 char *
3723 qemuBuildDriveDevStr(virDomainDefPtr def,
3724                      virDomainDiskDefPtr disk,
3725                      int bootindex,
3726                      virQEMUCapsPtr qemuCaps)
3727 {
3728     virBuffer opt = VIR_BUFFER_INITIALIZER;
3729     const char *bus = virDomainDiskQEMUBusTypeToString(disk->bus);
3730     int idx = virDiskNameToIndex(disk->dst);
3731     int controllerModel;
3732
3733     if (idx < 0) {
3734         virReportError(VIR_ERR_INTERNAL_ERROR,
3735                        _("unsupported disk type '%s'"), disk->dst);
3736         goto error;
3737     }
3738
3739     if (disk->wwn) {
3740         if ((disk->bus != VIR_DOMAIN_DISK_BUS_IDE) &&
3741             (disk->bus != VIR_DOMAIN_DISK_BUS_SCSI)) {
3742             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3743                            _("Only ide and scsi disk support wwn"));
3744             goto error;
3745         }
3746     }
3747
3748     if ((disk->vendor || disk->product) &&
3749         disk->bus != VIR_DOMAIN_DISK_BUS_SCSI) {
3750             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3751                            _("Only scsi disk supports vendor and product"));
3752             goto error;
3753     }
3754
3755     if (disk->device == VIR_DOMAIN_DISK_DEVICE_LUN) {
3756         /* make sure that both the bus and the qemu binary support
3757          *  type='lun' (SG_IO).
3758          */
3759         if (disk->bus != VIR_DOMAIN_DISK_BUS_VIRTIO &&
3760             disk->bus != VIR_DOMAIN_DISK_BUS_SCSI) {
3761             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
3762                            _("disk device='lun' is not supported for bus='%s'"),
3763                            bus);
3764             goto error;
3765         }
3766         if (disk->src.type == VIR_STORAGE_TYPE_NETWORK) {
3767             if (disk->src.protocol != VIR_STORAGE_NET_PROTOCOL_ISCSI) {
3768                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
3769                                _("disk device='lun' is not supported for protocol='%s'"),
3770                                virStorageNetProtocolTypeToString(disk->src.protocol));
3771                 goto error;
3772             }
3773         } else if (!virDomainDiskSourceIsBlockType(disk)) {
3774             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3775                            _("disk device='lun' is only valid for block type disk source"));
3776             goto error;
3777         }
3778         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_BLK_SG_IO)) {
3779             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3780                            _("disk device='lun' is not supported by this QEMU"));
3781             goto error;
3782         }
3783         if (disk->wwn) {
3784             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3785                            _("Setting wwn is not supported for lun device"));
3786             goto error;
3787         }
3788         if (disk->vendor || disk->product) {
3789             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3790                            _("Setting vendor or product is not supported "
3791                              "for lun device"));
3792             goto error;
3793         }
3794     }
3795
3796     switch (disk->bus) {
3797     case VIR_DOMAIN_DISK_BUS_IDE:
3798         if (disk->info.addr.drive.target != 0) {
3799             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3800                            _("target must be 0 for ide controller"));
3801             goto error;
3802         }
3803
3804         if (disk->wwn &&
3805             !virQEMUCapsGet(qemuCaps, QEMU_CAPS_IDE_DRIVE_WWN)) {
3806             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3807                            _("Setting wwn for ide disk is not supported "
3808                              "by this QEMU"));
3809             goto error;
3810         }
3811
3812         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_IDE_CD)) {
3813             if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM)
3814                 virBufferAddLit(&opt, "ide-cd");
3815             else
3816                 virBufferAddLit(&opt, "ide-hd");
3817         } else {
3818             virBufferAddLit(&opt, "ide-drive");
3819         }
3820
3821         virBufferAsprintf(&opt, ",bus=ide.%d,unit=%d",
3822                           disk->info.addr.drive.bus,
3823                           disk->info.addr.drive.unit);
3824         break;
3825     case VIR_DOMAIN_DISK_BUS_SCSI:
3826         if (disk->device == VIR_DOMAIN_DISK_DEVICE_LUN) {
3827             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_BLOCK)) {
3828                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3829                                _("This QEMU doesn't support scsi-block for "
3830                                  "lun passthrough"));
3831                 goto error;
3832             }
3833         }
3834
3835         if (disk->wwn &&
3836             !virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_DISK_WWN)) {
3837             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3838                            _("Setting wwn for scsi disk is not supported "
3839                              "by this QEMU"));
3840             goto error;
3841         }
3842
3843         /* Properties wwn, vendor and product were introduced in the
3844          * same QEMU release (1.2.0).
3845          */
3846         if ((disk->vendor || disk->product) &&
3847             !virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_DISK_WWN)) {
3848             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3849                            _("Setting vendor or product for scsi disk is not "
3850                              "supported by this QEMU"));
3851             goto error;
3852         }
3853
3854         controllerModel =
3855             virDomainDeviceFindControllerModel(def, &disk->info,
3856                                                VIR_DOMAIN_CONTROLLER_TYPE_SCSI);
3857         if ((qemuSetSCSIControllerModel(def, qemuCaps, &controllerModel)) < 0)
3858             goto error;
3859
3860         if (controllerModel == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC) {
3861             if (disk->info.addr.drive.target != 0) {
3862                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3863                                _("target must be 0 for controller "
3864                                  "model 'lsilogic'"));
3865                 goto error;
3866             }
3867
3868             if (disk->device == VIR_DOMAIN_DISK_DEVICE_LUN) {
3869                 virBufferAddLit(&opt, "scsi-block");
3870             } else {
3871                 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_CD)) {
3872                     if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM)
3873                         virBufferAddLit(&opt, "scsi-cd");
3874                     else
3875                         virBufferAddLit(&opt, "scsi-hd");
3876                 } else {
3877                     virBufferAddLit(&opt, "scsi-disk");
3878                 }
3879             }
3880
3881             virBufferAsprintf(&opt, ",bus=scsi%d.%d,scsi-id=%d",
3882                               disk->info.addr.drive.controller,
3883                               disk->info.addr.drive.bus,
3884                               disk->info.addr.drive.unit);
3885         } else {
3886             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_DISK_CHANNEL)) {
3887                 if (disk->info.addr.drive.target > 7) {
3888                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3889                                    _("This QEMU doesn't support target "
3890                                      "greater than 7"));
3891                     goto error;
3892                 }
3893
3894                 if ((disk->info.addr.drive.bus != disk->info.addr.drive.unit) &&
3895                     (disk->info.addr.drive.bus != 0)) {
3896                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3897                                    _("This QEMU only supports both bus and "
3898                                      "unit equal to 0"));
3899                     goto error;
3900                 }
3901             }
3902
3903             if (disk->device != VIR_DOMAIN_DISK_DEVICE_LUN) {
3904                 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_CD)) {
3905                     if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM)
3906                         virBufferAddLit(&opt, "scsi-cd");
3907                     else
3908                         virBufferAddLit(&opt, "scsi-hd");
3909                 } else {
3910                     virBufferAddLit(&opt, "scsi-disk");
3911                 }
3912             } else {
3913                 virBufferAddLit(&opt, "scsi-block");
3914             }
3915
3916             virBufferAsprintf(&opt, ",bus=scsi%d.0,channel=%d,scsi-id=%d,lun=%d",
3917                               disk->info.addr.drive.controller,
3918                               disk->info.addr.drive.bus,
3919                               disk->info.addr.drive.target,
3920                               disk->info.addr.drive.unit);
3921         }
3922         break;
3923     case VIR_DOMAIN_DISK_BUS_SATA:
3924         if (disk->info.addr.drive.bus != 0) {
3925             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3926                            _("bus must be 0 for ide controller"));
3927             goto error;
3928         }
3929         if (disk->info.addr.drive.target != 0) {
3930             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3931                            _("target must be 0 for ide controller"));
3932             goto error;
3933         }
3934
3935         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_IDE_CD)) {
3936             if (disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM)
3937                 virBufferAddLit(&opt, "ide-cd");
3938             else
3939                 virBufferAddLit(&opt, "ide-hd");
3940         } else {
3941             virBufferAddLit(&opt, "ide-drive");
3942         }
3943
3944         if (qemuDomainMachineIsQ35(def) &&
3945             disk->info.addr.drive.controller == 0) {
3946             /* Q35 machines have an implicit ahci (sata) controller at
3947              * 00:1F.2 which for some reason is hardcoded with the id
3948              * "ide" instead of the seemingly more reasonable "ahci0"
3949              * or "sata0".
3950              */
3951             virBufferAsprintf(&opt, ",bus=ide.%d", disk->info.addr.drive.unit);
3952         } else {
3953             /* All other ahci controllers have been created by
3954              * libvirt, and we gave them the id "ahci${n}" where ${n}
3955              * is the controller number. So we identify them that way.
3956              */
3957             virBufferAsprintf(&opt, ",bus=ahci%d.%d",
3958                               disk->info.addr.drive.controller,
3959                               disk->info.addr.drive.unit);
3960         }
3961         break;
3962     case VIR_DOMAIN_DISK_BUS_VIRTIO:
3963         if (disk->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW) {
3964             virBufferAddLit(&opt, "virtio-blk-ccw");
3965         } else if (disk->info.type ==
3966                    VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390) {
3967             virBufferAddLit(&opt, "virtio-blk-s390");
3968         } else if (disk->info.type ==
3969                    VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO) {
3970             virBufferAddLit(&opt, "virtio-blk-device");
3971         } else {
3972             virBufferAddLit(&opt, "virtio-blk-pci");
3973         }
3974         qemuBuildIoEventFdStr(&opt, disk->ioeventfd, qemuCaps);
3975         if (disk->event_idx &&
3976             virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_BLK_EVENT_IDX)) {
3977             virBufferAsprintf(&opt, ",event_idx=%s",
3978                               virDomainVirtioEventIdxTypeToString(disk->event_idx));
3979         }
3980         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_BLK_SCSI)) {
3981             /* if sg_io is true but the scsi option isn't supported,
3982              * that means it's just always on in this version of qemu.
3983              */
3984             virBufferAsprintf(&opt, ",scsi=%s",
3985                               (disk->device == VIR_DOMAIN_DISK_DEVICE_LUN)
3986                               ? "on" : "off");
3987         }
3988         if (qemuBuildDeviceAddressStr(&opt, def, &disk->info, qemuCaps) < 0)
3989             goto error;
3990         break;
3991     case VIR_DOMAIN_DISK_BUS_USB:
3992         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_USB_STORAGE)) {
3993             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3994                            _("This QEMU doesn't support '-device "
3995                              "usb-storage'"));
3996             goto error;
3997
3998         }
3999         virBufferAddLit(&opt, "usb-storage");
4000
4001         if (qemuBuildDeviceAddressStr(&opt, def, &disk->info, qemuCaps) < 0)
4002             goto error;
4003         break;
4004     default:
4005         virReportError(VIR_ERR_INTERNAL_ERROR,
4006                        _("unsupported disk bus '%s' with device setup"), bus);
4007         goto error;
4008     }
4009     virBufferAsprintf(&opt, ",drive=%s%s", QEMU_DRIVE_HOST_PREFIX, disk->info.alias);
4010     virBufferAsprintf(&opt, ",id=%s", disk->info.alias);
4011     if (bootindex && virQEMUCapsGet(qemuCaps, QEMU_CAPS_BOOTINDEX))
4012         virBufferAsprintf(&opt, ",bootindex=%d", bootindex);
4013     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_BLOCKIO)) {
4014         if (disk->blockio.logical_block_size > 0)
4015             virBufferAsprintf(&opt, ",logical_block_size=%u",
4016                               disk->blockio.logical_block_size);
4017         if (disk->blockio.physical_block_size > 0)
4018             virBufferAsprintf(&opt, ",physical_block_size=%u",
4019                               disk->blockio.physical_block_size);
4020     }
4021
4022     if (disk->wwn) {
4023         if (STRPREFIX(disk->wwn, "0x"))
4024             virBufferAsprintf(&opt, ",wwn=%s", disk->wwn);
4025         else
4026             virBufferAsprintf(&opt, ",wwn=0x%s", disk->wwn);
4027     }
4028
4029     if (disk->vendor)
4030         virBufferAsprintf(&opt, ",vendor=%s", disk->vendor);
4031
4032     if (disk->product)
4033         virBufferAsprintf(&opt, ",product=%s", disk->product);
4034
4035     if (disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
4036         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_USB_STORAGE_REMOVABLE)) {
4037             if (disk->removable == VIR_DOMAIN_FEATURE_STATE_ON)
4038                 virBufferAddLit(&opt, ",removable=on");
4039             else
4040                 virBufferAddLit(&opt, ",removable=off");
4041         } else {
4042             if (disk->removable != VIR_DOMAIN_FEATURE_STATE_DEFAULT) {
4043                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4044                                _("This QEMU doesn't support setting the "
4045                                  "removable flag of USB storage devices"));
4046                 goto error;
4047             }
4048         }
4049     }
4050
4051     if (virBufferError(&opt)) {
4052         virReportOOMError();
4053         goto error;
4054     }
4055
4056     return virBufferContentAndReset(&opt);
4057
4058  error:
4059     virBufferFreeAndReset(&opt);
4060     return NULL;
4061 }
4062
4063
4064 char *qemuBuildFSStr(virDomainFSDefPtr fs,
4065                      virQEMUCapsPtr qemuCaps ATTRIBUTE_UNUSED)
4066 {
4067     virBuffer opt = VIR_BUFFER_INITIALIZER;
4068     const char *driver = qemuDomainFSDriverTypeToString(fs->fsdriver);
4069     const char *wrpolicy = virDomainFSWrpolicyTypeToString(fs->wrpolicy);
4070
4071     if (fs->type != VIR_DOMAIN_FS_TYPE_MOUNT) {
4072         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4073                        _("only supports mount filesystem type"));
4074         goto error;
4075     }
4076
4077     if (!driver) {
4078         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4079                        _("Filesystem driver type not supported"));
4080         goto error;
4081     }
4082     virBufferAdd(&opt, driver, -1);
4083
4084     if (fs->fsdriver == VIR_DOMAIN_FS_DRIVER_TYPE_PATH ||
4085         fs->fsdriver == VIR_DOMAIN_FS_DRIVER_TYPE_DEFAULT) {
4086         if (fs->accessmode == VIR_DOMAIN_FS_ACCESSMODE_MAPPED) {
4087             virBufferAddLit(&opt, ",security_model=mapped");
4088         } else if (fs->accessmode == VIR_DOMAIN_FS_ACCESSMODE_PASSTHROUGH) {
4089             virBufferAddLit(&opt, ",security_model=passthrough");
4090         } else if (fs->accessmode == VIR_DOMAIN_FS_ACCESSMODE_SQUASH) {
4091             virBufferAddLit(&opt, ",security_model=none");
4092         }
4093     } else {
4094         /* For other fs drivers, default(passthru) should always
4095          * be supported */
4096         if (fs->accessmode != VIR_DOMAIN_FS_ACCESSMODE_PASSTHROUGH) {
4097             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4098                            _("only supports passthrough accessmode"));
4099             goto error;
4100         }
4101     }
4102
4103     if (fs->wrpolicy) {
4104        if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_FSDEV_WRITEOUT)) {
4105            virBufferAsprintf(&opt, ",writeout=%s", wrpolicy);
4106        } else {
4107            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4108                           _("filesystem writeout not supported"));
4109            goto error;
4110        }
4111     }
4112
4113     virBufferAsprintf(&opt, ",id=%s%s", QEMU_FSDEV_HOST_PREFIX, fs->info.alias);
4114     virBufferAsprintf(&opt, ",path=%s", fs->src);
4115
4116     if (fs->readonly) {
4117         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_FSDEV_READONLY)) {
4118             virBufferAddLit(&opt, ",readonly");
4119         } else {
4120             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4121                            _("readonly filesystem is not supported by this "
4122                              "QEMU binary"));
4123             goto error;
4124         }
4125     }
4126
4127     if (virBufferError(&opt)) {
4128         virReportOOMError();
4129         goto error;
4130     }
4131
4132     return virBufferContentAndReset(&opt);
4133
4134  error:
4135     virBufferFreeAndReset(&opt);
4136     return NULL;
4137 }
4138
4139
4140 char *
4141 qemuBuildFSDevStr(virDomainDefPtr def,
4142                   virDomainFSDefPtr fs,
4143                   virQEMUCapsPtr qemuCaps)
4144 {
4145     virBuffer opt = VIR_BUFFER_INITIALIZER;
4146
4147     if (fs->type != VIR_DOMAIN_FS_TYPE_MOUNT) {
4148         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4149                        _("can only passthrough directories"));
4150         goto error;
4151     }
4152
4153     virBufferAddLit(&opt, "virtio-9p-pci");
4154     virBufferAsprintf(&opt, ",id=%s", fs->info.alias);
4155     virBufferAsprintf(&opt, ",fsdev=%s%s", QEMU_FSDEV_HOST_PREFIX, fs->info.alias);
4156     virBufferAsprintf(&opt, ",mount_tag=%s", fs->dst);
4157
4158     if (qemuBuildDeviceAddressStr(&opt, def, &fs->info, qemuCaps) < 0)
4159         goto error;
4160
4161     if (virBufferError(&opt)) {
4162         virReportOOMError();
4163         goto error;
4164     }
4165
4166     return virBufferContentAndReset(&opt);
4167
4168  error:
4169     virBufferFreeAndReset(&opt);
4170     return NULL;
4171 }
4172
4173
4174 static int
4175 qemuControllerModelUSBToCaps(int model)
4176 {
4177     switch (model) {
4178     case VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX3_UHCI:
4179         return QEMU_CAPS_PIIX3_USB_UHCI;
4180     case VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX4_UHCI:
4181         return QEMU_CAPS_PIIX4_USB_UHCI;
4182     case VIR_DOMAIN_CONTROLLER_MODEL_USB_EHCI:
4183         return QEMU_CAPS_USB_EHCI;
4184     case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_EHCI1:
4185     case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI1:
4186     case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI2:
4187     case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI3:
4188         return QEMU_CAPS_ICH9_USB_EHCI1;
4189     case VIR_DOMAIN_CONTROLLER_MODEL_USB_VT82C686B_UHCI:
4190         return QEMU_CAPS_VT82C686B_USB_UHCI;
4191     case VIR_DOMAIN_CONTROLLER_MODEL_USB_PCI_OHCI:
4192         return QEMU_CAPS_PCI_OHCI;
4193     case VIR_DOMAIN_CONTROLLER_MODEL_USB_NEC_XHCI:
4194         return QEMU_CAPS_NEC_USB_XHCI;
4195     default:
4196         return -1;
4197     }
4198 }
4199
4200
4201 static int
4202 qemuBuildUSBControllerDevStr(virDomainDefPtr domainDef,
4203                              virDomainControllerDefPtr def,
4204                              virQEMUCapsPtr qemuCaps,
4205                              virBuffer *buf)
4206 {
4207     const char *smodel;
4208     int model, flags;
4209
4210     model = def->model;
4211
4212     if (model == -1) {
4213         if (domainDef->os.arch == VIR_ARCH_PPC64)
4214             model = VIR_DOMAIN_CONTROLLER_MODEL_USB_PCI_OHCI;
4215         else
4216             model = VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX3_UHCI;
4217     }
4218
4219     smodel = qemuControllerModelUSBTypeToString(model);
4220     flags = qemuControllerModelUSBToCaps(model);
4221
4222     if (flags == -1 || !virQEMUCapsGet(qemuCaps, flags)) {
4223         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4224                        _("%s not supported in this QEMU binary"), smodel);
4225         return -1;
4226     }
4227
4228     virBufferAsprintf(buf, "%s", smodel);
4229
4230     if (def->info.mastertype == VIR_DOMAIN_CONTROLLER_MASTER_USB) {
4231         virBufferAddLit(buf, ",masterbus=");
4232         qemuUSBId(buf, def->idx);
4233         virBufferAsprintf(buf, ".0,firstport=%d", def->info.master.usb.startport);
4234     } else {
4235         virBufferAddLit(buf, ",id=");
4236         qemuUSBId(buf, def->idx);
4237     }
4238
4239     return 0;
4240 }
4241
4242 char *
4243 qemuBuildControllerDevStr(virDomainDefPtr domainDef,
4244                           virDomainControllerDefPtr def,
4245                           virQEMUCapsPtr qemuCaps,
4246                           int *nusbcontroller)
4247 {
4248     virBuffer buf = VIR_BUFFER_INITIALIZER;
4249     int model;
4250
4251     if (def->queues &&
4252         !(def->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI &&
4253           def->model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI)) {
4254         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4255                        _("'queues' is only supported by virtio-scsi controller"));
4256         return NULL;
4257     }
4258
4259     switch (def->type) {
4260     case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
4261         model = def->model;
4262         if ((qemuSetSCSIControllerModel(domainDef, qemuCaps, &model)) < 0)
4263             return NULL;
4264
4265         switch (model) {
4266         case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI:
4267             if (def->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW)
4268                 virBufferAddLit(&buf, "virtio-scsi-ccw");
4269             else if (def->info.type ==
4270                      VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390)
4271                 virBufferAddLit(&buf, "virtio-scsi-s390");
4272             else if (def->info.type ==
4273                      VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO)
4274                 virBufferAddLit(&buf, "virtio-scsi-device");
4275             else
4276                 virBufferAddLit(&buf, "virtio-scsi-pci");
4277             break;
4278         case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC:
4279             virBufferAddLit(&buf, "lsi");
4280             break;
4281         case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_IBMVSCSI:
4282             virBufferAddLit(&buf, "spapr-vscsi");
4283             break;
4284         case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1078:
4285             virBufferAddLit(&buf, "megasas");
4286             break;
4287         default:
4288             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4289                            _("Unsupported controller model: %s"),
4290                            virDomainControllerModelSCSITypeToString(def->model));
4291         }
4292         virBufferAsprintf(&buf, ",id=scsi%d", def->idx);
4293         break;
4294
4295     case VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL:
4296         if (def->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
4297             virBufferAddLit(&buf, "virtio-serial-pci");
4298         } else if (def->info.type ==
4299                    VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW) {
4300             virBufferAddLit(&buf, "virtio-serial-ccw");
4301         } else if (def->info.type ==
4302                    VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390) {
4303             virBufferAddLit(&buf, "virtio-serial-s390");
4304         } else if (def->info.type ==
4305                    VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO) {
4306             virBufferAddLit(&buf, "virtio-serial-device");
4307         } else {
4308             virBufferAddLit(&buf, "virtio-serial");
4309         }
4310         virBufferAsprintf(&buf, ",id=" QEMU_VIRTIO_SERIAL_PREFIX "%d",
4311                           def->idx);
4312         if (def->opts.vioserial.ports != -1) {
4313             virBufferAsprintf(&buf, ",max_ports=%d",
4314                               def->opts.vioserial.ports);
4315         }
4316         if (def->opts.vioserial.vectors != -1) {
4317             virBufferAsprintf(&buf, ",vectors=%d",
4318                               def->opts.vioserial.vectors);
4319         }
4320         break;
4321
4322     case VIR_DOMAIN_CONTROLLER_TYPE_CCID:
4323         virBufferAsprintf(&buf, "usb-ccid,id=ccid%d", def->idx);
4324         break;
4325
4326     case VIR_DOMAIN_CONTROLLER_TYPE_SATA:
4327         virBufferAsprintf(&buf, "ahci,id=ahci%d", def->idx);
4328         break;
4329
4330     case VIR_DOMAIN_CONTROLLER_TYPE_USB:
4331         if (qemuBuildUSBControllerDevStr(domainDef, def, qemuCaps, &buf) == -1)
4332             goto error;
4333
4334         if (nusbcontroller)
4335             *nusbcontroller += 1;
4336
4337         break;
4338
4339     case VIR_DOMAIN_CONTROLLER_TYPE_PCI:
4340         switch (def->model) {
4341         case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
4342             if (def->idx == 0) {
4343                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4344                                _("PCI bridge index should be > 0"));
4345                 goto error;
4346             }
4347             virBufferAsprintf(&buf, "pci-bridge,chassis_nr=%d,id=pci.%d",
4348                               def->idx, def->idx);
4349             break;
4350         case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
4351             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_DMI_TO_PCI_BRIDGE)) {
4352                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4353                                _("The dmi-to-pci-bridge (i82801b11-bridge) "
4354                                  "controller is not supported in this QEMU binary"));
4355                 goto error;
4356             }
4357             if (def->idx == 0) {
4358                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4359                                _("dmi-to-pci-bridge index should be > 0"));
4360                 goto error;
4361             }
4362             virBufferAsprintf(&buf, "i82801b11-bridge,id=pci.%d", def->idx);
4363             break;
4364         case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
4365         case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
4366             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
4367                            _("wrong function called for pci-root/pcie-root"));
4368             return NULL;
4369         }
4370         break;
4371
4372     /* We always get an IDE controller, whether we want it or not. */
4373     case VIR_DOMAIN_CONTROLLER_TYPE_IDE:
4374     default:
4375         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4376                        _("Unknown controller type: %s"),
4377                        virDomainControllerTypeToString(def->type));
4378         goto error;
4379     }
4380
4381     if (def->queues)
4382         virBufferAsprintf(&buf, ",num_queues=%u", def->queues);
4383
4384     if (qemuBuildDeviceAddressStr(&buf, domainDef, &def->info, qemuCaps) < 0)
4385         goto error;
4386
4387     if (virBufferError(&buf)) {
4388         virReportOOMError();
4389         goto error;
4390     }
4391
4392     return virBufferContentAndReset(&buf);
4393
4394  error:
4395     virBufferFreeAndReset(&buf);
4396     return NULL;
4397 }
4398
4399
4400 char *
4401 qemuBuildNicStr(virDomainNetDefPtr net,
4402                 const char *prefix,
4403                 int vlan)
4404 {
4405     char *str;
4406     char macaddr[VIR_MAC_STRING_BUFLEN];
4407
4408     ignore_value(virAsprintf(&str,
4409                              "%smacaddr=%s,vlan=%d%s%s%s%s",
4410                              prefix ? prefix : "",
4411                              virMacAddrFormat(&net->mac, macaddr),
4412                              vlan,
4413                              (net->model ? ",model=" : ""),
4414                              (net->model ? net->model : ""),
4415                              (net->info.alias ? ",name=" : ""),
4416                              (net->info.alias ? net->info.alias : "")));
4417     return str;
4418 }
4419
4420
4421 char *
4422 qemuBuildNicDevStr(virDomainDefPtr def,
4423                    virDomainNetDefPtr net,
4424                    int vlan,
4425                    int bootindex,
4426                    int vhostfdSize,
4427                    virQEMUCapsPtr qemuCaps)
4428 {
4429     virBuffer buf = VIR_BUFFER_INITIALIZER;
4430     const char *nic = net->model;
4431     bool usingVirtio = false;
4432     char macaddr[VIR_MAC_STRING_BUFLEN];
4433
4434     if (STREQ(net->model, "virtio")) {
4435         if (net->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW)
4436             nic = "virtio-net-ccw";
4437         else if (net->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390)
4438             nic = "virtio-net-s390";
4439         else if (net->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO)
4440             nic = "virtio-net-device";
4441         else
4442             nic = "virtio-net-pci";
4443
4444         usingVirtio = true;
4445     }
4446
4447     virBufferAdd(&buf, nic, -1);
4448     if (usingVirtio && net->driver.virtio.txmode) {
4449         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_TX_ALG)) {
4450             virBufferAddLit(&buf, ",tx=");
4451             switch (net->driver.virtio.txmode) {
4452                 case VIR_DOMAIN_NET_VIRTIO_TX_MODE_IOTHREAD:
4453                     virBufferAddLit(&buf, "bh");
4454                     break;
4455
4456                 case VIR_DOMAIN_NET_VIRTIO_TX_MODE_TIMER:
4457                     virBufferAddLit(&buf, "timer");
4458                     break;
4459                 default:
4460                     /* this should never happen, if it does, we need
4461                      * to add another case to this switch.
4462                      */
4463                     virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
4464                                    _("unrecognized virtio-net-pci 'tx' option"));
4465                     goto error;
4466             }
4467         } else {
4468             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4469                            _("virtio-net-pci 'tx' option not supported in this QEMU binary"));
4470             goto error;
4471         }
4472     }
4473     if (usingVirtio) {
4474         qemuBuildIoEventFdStr(&buf, net->driver.virtio.ioeventfd, qemuCaps);
4475         if (net->driver.virtio.event_idx &&
4476             virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_NET_EVENT_IDX)) {
4477             virBufferAsprintf(&buf, ",event_idx=%s",
4478                               virDomainVirtioEventIdxTypeToString(net->driver.virtio.event_idx));
4479         }
4480     }
4481     if (usingVirtio && vhostfdSize > 1) {
4482         /* As advised at http://www.linux-kvm.org/page/Multiqueue
4483          * we should add vectors=2*N+2 where N is the vhostfdSize */
4484         virBufferAsprintf(&buf, ",mq=on,vectors=%d", 2 * vhostfdSize + 2);
4485     }
4486     if (vlan == -1)
4487         virBufferAsprintf(&buf, ",netdev=host%s", net->info.alias);
4488     else
4489         virBufferAsprintf(&buf, ",vlan=%d", vlan);
4490     virBufferAsprintf(&buf, ",id=%s", net->info.alias);
4491     virBufferAsprintf(&buf, ",mac=%s",
4492                       virMacAddrFormat(&net->mac, macaddr));
4493     if (qemuBuildDeviceAddressStr(&buf, def, &net->info, qemuCaps) < 0)
4494         goto error;
4495     if (qemuBuildRomStr(&buf, &net->info, qemuCaps) < 0)
4496        goto error;
4497     if (bootindex && virQEMUCapsGet(qemuCaps, QEMU_CAPS_BOOTINDEX))
4498         virBufferAsprintf(&buf, ",bootindex=%d", bootindex);
4499
4500     if (virBufferError(&buf)) {
4501         virReportOOMError();
4502         goto error;
4503     }
4504
4505     return virBufferContentAndReset(&buf);
4506
4507  error:
4508     virBufferFreeAndReset(&buf);
4509     return NULL;
4510 }
4511
4512
4513 char *
4514 qemuBuildHostNetStr(virDomainNetDefPtr net,
4515                     virQEMUDriverPtr driver,
4516                     char type_sep,
4517                     int vlan,
4518                     char **tapfd,
4519                     int tapfdSize,
4520                     char **vhostfd,
4521                     int vhostfdSize)
4522 {
4523     bool is_tap = false;
4524     virBuffer buf = VIR_BUFFER_INITIALIZER;
4525     enum virDomainNetType netType = virDomainNetGetActualType(net);
4526     virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
4527     size_t i;
4528
4529     if (net->script && netType != VIR_DOMAIN_NET_TYPE_ETHERNET) {
4530         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4531                        _("scripts are not supported on interfaces of type %s"),
4532                        virDomainNetTypeToString(netType));
4533         virObjectUnref(cfg);
4534         return NULL;
4535     }
4536
4537     switch (netType) {
4538     /*
4539      * If type='bridge', and we're running as privileged user
4540      * or -netdev bridge is not supported then it will fall
4541      * through, -net tap,fd
4542      */
4543     case VIR_DOMAIN_NET_TYPE_BRIDGE:
4544     case VIR_DOMAIN_NET_TYPE_NETWORK:
4545     case VIR_DOMAIN_NET_TYPE_DIRECT:
4546         virBufferAsprintf(&buf, "tap%c", type_sep);
4547         /* for one tapfd 'fd=' shall be used,
4548          * for more than one 'fds=' is the right choice */
4549         if (tapfdSize == 1) {
4550             virBufferAsprintf(&buf, "fd=%s", tapfd[0]);
4551         } else {
4552             virBufferAddLit(&buf, "fds=");
4553             for (i = 0; i < tapfdSize; i++) {
4554                 if (i)
4555                     virBufferAddChar(&buf, ':');
4556                 virBufferAdd(&buf, tapfd[i], -1);
4557             }
4558         }
4559         type_sep = ',';
4560         is_tap = true;
4561         break;
4562
4563     case VIR_DOMAIN_NET_TYPE_ETHERNET:
4564         virBufferAddLit(&buf, "tap");
4565         if (net->ifname) {
4566             virBufferAsprintf(&buf, "%cifname=%s", type_sep, net->ifname);
4567             type_sep = ',';
4568         }
4569         if (net->script) {
4570             virBufferAsprintf(&buf, "%cscript=%s", type_sep,
4571                               net->script);
4572             type_sep = ',';
4573         }
4574         is_tap = true;
4575         break;
4576
4577     case VIR_DOMAIN_NET_TYPE_CLIENT:
4578        virBufferAsprintf(&buf, "socket%cconnect=%s:%d",
4579                          type_sep,
4580                          net->data.socket.address,
4581                          net->data.socket.port);
4582        type_sep = ',';
4583        break;
4584
4585     case VIR_DOMAIN_NET_TYPE_SERVER:
4586        virBufferAsprintf(&buf, "socket%clisten=%s:%d",
4587                          type_sep,
4588                          net->data.socket.address,
4589                          net->data.socket.port);
4590        type_sep = ',';
4591        break;
4592
4593     case VIR_DOMAIN_NET_TYPE_MCAST:
4594        virBufferAsprintf(&buf, "socket%cmcast=%s:%d",
4595                          type_sep,
4596                          net->data.socket.address,
4597                          net->data.socket.port);
4598        type_sep = ',';
4599        break;
4600
4601     case VIR_DOMAIN_NET_TYPE_USER:
4602     default:
4603         virBufferAddLit(&buf, "user");
4604         break;
4605     }
4606
4607     if (vlan >= 0) {
4608         virBufferAsprintf(&buf, "%cvlan=%d", type_sep, vlan);
4609         if (net->info.alias)
4610             virBufferAsprintf(&buf, ",name=host%s",
4611                               net->info.alias);
4612     } else {
4613         virBufferAsprintf(&buf, "%cid=host%s",
4614                           type_sep, net->info.alias);
4615     }
4616
4617     if (is_tap) {
4618         if (vhostfdSize) {
4619             virBufferAddLit(&buf, ",vhost=on,");
4620             if (vhostfdSize == 1) {
4621                 virBufferAsprintf(&buf, "vhostfd=%s", vhostfd[0]);
4622             } else {
4623                 virBufferAddLit(&buf, "vhostfds=");
4624                 for (i = 0; i < vhostfdSize; i++) {
4625                     if (i)
4626                         virBufferAddChar(&buf, ':');
4627                     virBufferAdd(&buf, vhostfd[i], -1);
4628                 }
4629             }
4630         }
4631         if (net->tune.sndbuf_specified)
4632             virBufferAsprintf(&buf, ",sndbuf=%lu", net->tune.sndbuf);
4633     }
4634
4635     virObjectUnref(cfg);
4636
4637     if (virBufferError(&buf)) {
4638         virBufferFreeAndReset(&buf);
4639         virReportOOMError();
4640         return NULL;
4641     }
4642
4643     return virBufferContentAndReset(&buf);
4644 }
4645
4646
4647 char *
4648 qemuBuildWatchdogDevStr(virDomainDefPtr def,
4649                         virDomainWatchdogDefPtr dev,
4650                         virQEMUCapsPtr qemuCaps)
4651 {
4652     virBuffer buf = VIR_BUFFER_INITIALIZER;
4653
4654     const char *model = virDomainWatchdogModelTypeToString(dev->model);
4655     if (!model) {
4656         virReportError(VIR_ERR_INTERNAL_ERROR,
4657                        "%s", _("missing watchdog model"));
4658         goto error;
4659     }
4660
4661     virBufferAsprintf(&buf, "%s,id=%s", model, dev->info.alias);
4662     if (qemuBuildDeviceAddressStr(&buf, def, &dev->info, qemuCaps) < 0)
4663         goto error;
4664
4665     if (virBufferError(&buf)) {
4666         virReportOOMError();
4667         goto error;
4668     }
4669
4670     return virBufferContentAndReset(&buf);
4671
4672  error:
4673     virBufferFreeAndReset(&buf);
4674     return NULL;
4675 }
4676
4677
4678 char *
4679 qemuBuildMemballoonDevStr(virDomainDefPtr def,
4680                           virDomainMemballoonDefPtr dev,
4681                           virQEMUCapsPtr qemuCaps)
4682 {
4683     virBuffer buf = VIR_BUFFER_INITIALIZER;
4684
4685     switch (dev->info.type) {
4686         case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI:
4687             virBufferAddLit(&buf, "virtio-balloon-pci");
4688             break;
4689         case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW:
4690             virBufferAddLit(&buf, "virtio-balloon-ccw");
4691             break;
4692         case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO:
4693             virBufferAddLit(&buf, "virtio-balloon-device");
4694             break;
4695         default:
4696             virReportError(VIR_ERR_XML_ERROR,
4697                            _("memballoon unsupported with address type '%s'"),
4698                            virDomainDeviceAddressTypeToString(dev->info.type));
4699             goto error;
4700     }
4701
4702     virBufferAsprintf(&buf, ",id=%s", dev->info.alias);
4703     if (qemuBuildDeviceAddressStr(&buf, def, &dev->info, qemuCaps) < 0)
4704         goto error;
4705
4706     if (virBufferError(&buf)) {
4707         virReportOOMError();
4708         goto error;
4709     }
4710
4711     return virBufferContentAndReset(&buf);
4712
4713  error:
4714     virBufferFreeAndReset(&buf);
4715     return NULL;
4716 }
4717
4718 static char *
4719 qemuBuildNVRAMDevStr(virDomainNVRAMDefPtr dev)
4720 {
4721     virBuffer buf = VIR_BUFFER_INITIALIZER;
4722
4723     if (dev->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO &&
4724         dev->info.addr.spaprvio.has_reg) {
4725         virBufferAsprintf(&buf, "spapr-nvram.reg=0x%llx",
4726                           dev->info.addr.spaprvio.reg);
4727     } else {
4728         virReportError(VIR_ERR_XML_ERROR, "%s",
4729                        _("nvram address type must be spaprvio"));
4730         goto error;
4731     }
4732
4733     if (virBufferError(&buf)) {
4734         virReportOOMError();
4735         goto error;
4736     }
4737
4738     return virBufferContentAndReset(&buf);
4739
4740  error:
4741     virBufferFreeAndReset(&buf);
4742     return NULL;
4743 }
4744
4745 char *
4746 qemuBuildUSBInputDevStr(virDomainDefPtr def,
4747                         virDomainInputDefPtr dev,
4748                         virQEMUCapsPtr qemuCaps)
4749 {
4750     virBuffer buf = VIR_BUFFER_INITIALIZER;
4751
4752     switch (dev->type) {
4753     case VIR_DOMAIN_INPUT_TYPE_MOUSE:
4754         virBufferAsprintf(&buf, "usb-mouse,id=%s", dev->info.alias);
4755         break;
4756     case VIR_DOMAIN_INPUT_TYPE_TABLET:
4757         virBufferAsprintf(&buf, "usb-tablet,id=%s", dev->info.alias);
4758         break;
4759     case VIR_DOMAIN_INPUT_TYPE_KBD:
4760         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_USB_KBD))
4761             goto error;
4762         virBufferAsprintf(&buf, "usb-kbd,id=%s", dev->info.alias);
4763         break;
4764     }
4765
4766     if (qemuBuildDeviceAddressStr(&buf, def, &dev->info, qemuCaps) < 0)
4767         goto error;
4768
4769     if (virBufferError(&buf)) {
4770         virReportOOMError();
4771         goto error;
4772     }
4773
4774     return virBufferContentAndReset(&buf);
4775
4776  error:
4777     virBufferFreeAndReset(&buf);
4778     return NULL;
4779 }
4780
4781
4782 char *
4783 qemuBuildSoundDevStr(virDomainDefPtr def,
4784                      virDomainSoundDefPtr sound,
4785                      virQEMUCapsPtr qemuCaps)
4786 {
4787     virBuffer buf = VIR_BUFFER_INITIALIZER;
4788     const char *model = virDomainSoundModelTypeToString(sound->model);
4789
4790     if (!model) {
4791         virReportError(VIR_ERR_INTERNAL_ERROR,
4792                        "%s", _("invalid sound model"));
4793         goto error;
4794     }
4795
4796     /* Hack for devices with different names in QEMU and libvirt */
4797     switch (sound->model) {
4798     case VIR_DOMAIN_SOUND_MODEL_ES1370:
4799         model = "ES1370";
4800         break;
4801     case VIR_DOMAIN_SOUND_MODEL_AC97:
4802         model = "AC97";
4803         break;
4804     case VIR_DOMAIN_SOUND_MODEL_ICH6:
4805         model = "intel-hda";
4806         break;
4807     case VIR_DOMAIN_SOUND_MODEL_ICH9:
4808         model = "ich9-intel-hda";
4809         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_ICH9_INTEL_HDA)) {
4810             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4811                            _("The ich9-intel-hda audio controller "
4812                              "is not supported in this QEMU binary"));
4813             goto error;
4814         }
4815         break;
4816     }
4817
4818     virBufferAsprintf(&buf, "%s,id=%s", model, sound->info.alias);
4819     if (qemuBuildDeviceAddressStr(&buf, def, &sound->info, qemuCaps) < 0)
4820         goto error;
4821
4822     if (virBufferError(&buf)) {
4823         virReportOOMError();
4824         goto error;
4825     }
4826
4827     return virBufferContentAndReset(&buf);
4828
4829  error:
4830     virBufferFreeAndReset(&buf);
4831     return NULL;
4832 }
4833
4834
4835 static int
4836 qemuSoundCodecTypeToCaps(int type)
4837 {
4838     switch (type) {
4839     case VIR_DOMAIN_SOUND_CODEC_TYPE_DUPLEX:
4840         return QEMU_CAPS_HDA_DUPLEX;
4841     case VIR_DOMAIN_SOUND_CODEC_TYPE_MICRO:
4842         return QEMU_CAPS_HDA_MICRO;
4843     default:
4844         return -1;
4845     }
4846 }
4847
4848
4849 static char *
4850 qemuBuildSoundCodecStr(virDomainSoundDefPtr sound,
4851                        virDomainSoundCodecDefPtr codec,
4852                        virQEMUCapsPtr qemuCaps)
4853 {
4854     virBuffer buf = VIR_BUFFER_INITIALIZER;
4855     const char *stype;
4856     int type, flags;
4857
4858     type = codec->type;
4859     stype = qemuSoundCodecTypeToString(type);
4860     flags = qemuSoundCodecTypeToCaps(type);
4861
4862     if (flags == -1 || !virQEMUCapsGet(qemuCaps, flags)) {
4863         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4864                        _("%s not supported in this QEMU binary"), stype);
4865         goto error;
4866     }
4867
4868     virBufferAsprintf(&buf, "%s,id=%s-codec%d,bus=%s.0,cad=%d",
4869                       stype, sound->info.alias, codec->cad, sound->info.alias, codec->cad);
4870
4871     return virBufferContentAndReset(&buf);
4872
4873  error:
4874     virBufferFreeAndReset(&buf);
4875     return NULL;
4876 }
4877
4878 static char *
4879 qemuBuildDeviceVideoStr(virDomainDefPtr def,
4880                         virDomainVideoDefPtr video,
4881                         virQEMUCapsPtr qemuCaps,
4882                         bool primary)
4883 {
4884     virBuffer buf = VIR_BUFFER_INITIALIZER;
4885     const char *model;
4886
4887     if (primary) {
4888         model = qemuDeviceVideoTypeToString(video->type);
4889         if (!model || STREQ(model, "")) {
4890             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4891                            _("video type %s is not supported with QEMU"),
4892                            virDomainVideoTypeToString(video->type));
4893             goto error;
4894         }
4895     } else {
4896         if (video->type != VIR_DOMAIN_VIDEO_TYPE_QXL) {
4897             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4898                            "%s", _("non-primary video device must be type of 'qxl'"));
4899             goto error;
4900         }
4901
4902         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_QXL)) {
4903             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4904                            "%s", _("only one video card is currently supported"));
4905             goto error;
4906         }
4907
4908         model = "qxl";
4909     }
4910
4911     virBufferAsprintf(&buf, "%s,id=%s", model, video->info.alias);
4912
4913     if (video->type == VIR_DOMAIN_VIDEO_TYPE_QXL) {
4914         if (video->vram > (UINT_MAX / 1024)) {
4915             virReportError(VIR_ERR_OVERFLOW,
4916                            _("value for 'vram' must be less than '%u'"),
4917                            UINT_MAX / 1024);
4918             goto error;
4919         }
4920         if (video->ram > (UINT_MAX / 1024)) {
4921             virReportError(VIR_ERR_OVERFLOW,
4922                            _("value for 'ram' must be less than '%u'"),
4923                            UINT_MAX / 1024);
4924             goto error;
4925         }
4926
4927         /* QEMU accepts bytes for ram_size. */
4928         virBufferAsprintf(&buf, ",ram_size=%u", video->ram * 1024);
4929
4930         /* QEMU accepts bytes for vram_size. */
4931         virBufferAsprintf(&buf, ",vram_size=%u", video->vram * 1024);
4932     }
4933
4934     if (qemuBuildDeviceAddressStr(&buf, def, &video->info, qemuCaps) < 0)
4935         goto error;
4936
4937     if (virBufferError(&buf)) {
4938         virReportOOMError();
4939         goto error;
4940     }
4941
4942     return virBufferContentAndReset(&buf);
4943
4944  error:
4945     virBufferFreeAndReset(&buf);
4946     return NULL;
4947 }
4948
4949
4950 int
4951 qemuOpenPCIConfig(virDomainHostdevDefPtr dev)
4952 {
4953     char *path = NULL;
4954     int configfd = -1;
4955
4956     if (virAsprintf(&path, "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/config",
4957                     dev->source.subsys.u.pci.addr.domain,
4958                     dev->source.subsys.u.pci.addr.bus,
4959                     dev->source.subsys.u.pci.addr.slot,
4960                     dev->source.subsys.u.pci.addr.function) < 0)
4961         return -1;
4962
4963     configfd = open(path, O_RDWR, 0);
4964
4965     if (configfd < 0)
4966         virReportSystemError(errno, _("Failed opening %s"), path);
4967
4968     VIR_FREE(path);
4969
4970     return configfd;
4971 }
4972
4973 char *
4974 qemuBuildPCIHostdevDevStr(virDomainDefPtr def,
4975                           virDomainHostdevDefPtr dev,
4976                           const char *configfd,
4977                           virQEMUCapsPtr qemuCaps)
4978 {
4979     virBuffer buf = VIR_BUFFER_INITIALIZER;
4980     int backend = dev->source.subsys.u.pci.backend;
4981
4982     /* caller has to assign proper passthrough backend type */
4983     switch ((virDomainHostdevSubsysPCIBackendType) backend) {
4984     case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_KVM:
4985         virBufferAddLit(&buf, "pci-assign");
4986         if (configfd && *configfd)
4987             virBufferAsprintf(&buf, ",configfd=%s", configfd);
4988         break;
4989
4990     case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO:
4991         virBufferAddLit(&buf, "vfio-pci");
4992         break;
4993
4994     default:
4995         virReportError(VIR_ERR_INTERNAL_ERROR,
4996                        _("invalid PCI passthrough type '%s'"),
4997                        virDomainHostdevSubsysPCIBackendTypeToString(backend));
4998         break;
4999     }
5000
5001     virBufferAddLit(&buf, ",host=");
5002     if (dev->source.subsys.u.pci.addr.domain) {
5003         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_HOST_PCI_MULTIDOMAIN)) {
5004             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5005                            _("non-zero domain='%.4x' in host device PCI address "
5006                              "not supported in this QEMU binary"),
5007                            dev->source.subsys.u.pci.addr.domain);
5008             goto error;
5009         }
5010         virBufferAsprintf(&buf, "%.4x:", dev->source.subsys.u.pci.addr.domain);
5011     }
5012     virBufferAsprintf(&buf, "%.2x:%.2x.%.1x",
5013                       dev->source.subsys.u.pci.addr.bus,
5014                       dev->source.subsys.u.pci.addr.slot,
5015                       dev->source.subsys.u.pci.addr.function);
5016     virBufferAsprintf(&buf, ",id=%s", dev->info->alias);
5017     if (dev->info->bootIndex)
5018         virBufferAsprintf(&buf, ",bootindex=%d", dev->info->bootIndex);
5019     if (qemuBuildDeviceAddressStr(&buf, def, dev->info, qemuCaps) < 0)
5020         goto error;
5021     if (qemuBuildRomStr(&buf, dev->info, qemuCaps) < 0)
5022        goto error;
5023
5024     if (virBufferError(&buf)) {
5025         virReportOOMError();
5026         goto error;
5027     }
5028
5029     return virBufferContentAndReset(&buf);
5030
5031  error:
5032     virBufferFreeAndReset(&buf);
5033     return NULL;
5034 }
5035
5036
5037 char *
5038 qemuBuildPCIHostdevPCIDevStr(virDomainHostdevDefPtr dev,
5039                              virQEMUCapsPtr qemuCaps)
5040 {
5041     char *ret = NULL;
5042
5043     if (dev->source.subsys.u.pci.addr.domain) {
5044         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_HOST_PCI_MULTIDOMAIN)) {
5045             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5046                            _("non-zero domain='%.4x' in host device PCI address "
5047                              "not supported in this QEMU binary"),
5048                            dev->source.subsys.u.pci.addr.domain);
5049             goto cleanup;
5050         }
5051         ignore_value(virAsprintf(&ret, "host=%.4x:%.2x:%.2x.%.1x",
5052                                  dev->source.subsys.u.pci.addr.domain,
5053                                  dev->source.subsys.u.pci.addr.bus,
5054                                  dev->source.subsys.u.pci.addr.slot,
5055                                  dev->source.subsys.u.pci.addr.function));
5056     } else {
5057         ignore_value(virAsprintf(&ret, "host=%.2x:%.2x.%.1x",
5058                                  dev->source.subsys.u.pci.addr.bus,
5059                                  dev->source.subsys.u.pci.addr.slot,
5060                                  dev->source.subsys.u.pci.addr.function));
5061     }
5062  cleanup:
5063     return ret;
5064 }
5065
5066
5067 char *
5068 qemuBuildRedirdevDevStr(virDomainDefPtr def,
5069                         virDomainRedirdevDefPtr dev,
5070                         virQEMUCapsPtr qemuCaps)
5071 {
5072     size_t i;
5073     virBuffer buf = VIR_BUFFER_INITIALIZER;
5074     virDomainRedirFilterDefPtr redirfilter = def->redirfilter;
5075
5076     if (dev->bus != VIR_DOMAIN_REDIRDEV_BUS_USB) {
5077         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5078                        _("Redirection bus %s is not supported by QEMU"),
5079                        virDomainRedirdevBusTypeToString(dev->bus));
5080         goto error;
5081     }
5082
5083     if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_USB_REDIR)) {
5084         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5085                        _("USB redirection is not supported "
5086                          "by this version of QEMU"));
5087         goto error;
5088     }
5089
5090     virBufferAsprintf(&buf, "usb-redir,chardev=char%s,id=%s",
5091                       dev->info.alias,
5092                       dev->info.alias);
5093
5094     if (redirfilter && redirfilter->nusbdevs) {
5095         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_USB_REDIR_FILTER)) {
5096             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5097                            _("USB redirection filter is not "
5098                              "supported by this version of QEMU"));
5099             goto error;
5100         }
5101
5102         virBufferAddLit(&buf, ",filter=");
5103
5104         for (i = 0; i < redirfilter->nusbdevs; i++) {
5105             virDomainRedirFilterUSBDevDefPtr usbdev = redirfilter->usbdevs[i];
5106             if (usbdev->usbClass >= 0)
5107                 virBufferAsprintf(&buf, "0x%02X:", usbdev->usbClass);
5108             else
5109                 virBufferAddLit(&buf, "-1:");
5110
5111             if (usbdev->vendor >= 0)
5112                 virBufferAsprintf(&buf, "0x%04X:", usbdev->vendor);
5113             else
5114                 virBufferAddLit(&buf, "-1:");
5115
5116             if (usbdev->product >= 0)
5117                 virBufferAsprintf(&buf, "0x%04X:", usbdev->product);
5118             else
5119                 virBufferAddLit(&buf, "-1:");
5120
5121             if (usbdev->version >= 0)
5122                 virBufferAsprintf(&buf, "0x%04X:", usbdev->version);
5123             else
5124                 virBufferAddLit(&buf, "-1:");
5125
5126             virBufferAsprintf(&buf, "%u", usbdev->allow);
5127             if (i < redirfilter->nusbdevs -1)
5128                 virBufferAddLit(&buf, "|");
5129         }
5130     }
5131
5132     if (dev->info.bootIndex) {
5133         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_USB_REDIR_BOOTINDEX)) {
5134             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5135                            _("USB redirection booting is not "
5136                              "supported by this version of QEMU"));
5137             goto error;
5138         }
5139         virBufferAsprintf(&buf, ",bootindex=%d", dev->info.bootIndex);
5140     }
5141
5142     if (qemuBuildDeviceAddressStr(&buf, def, &dev->info, qemuCaps) < 0)
5143         goto error;
5144
5145     if (virBufferError(&buf)) {
5146         virReportOOMError();
5147         goto error;
5148     }
5149
5150     return virBufferContentAndReset(&buf);
5151
5152  error:
5153     virBufferFreeAndReset(&buf);
5154     return NULL;
5155 }
5156
5157 char *
5158 qemuBuildUSBHostdevDevStr(virDomainDefPtr def,
5159                           virDomainHostdevDefPtr dev,
5160                           virQEMUCapsPtr qemuCaps)
5161 {
5162     virBuffer buf = VIR_BUFFER_INITIALIZER;
5163
5164     if (!dev->missing &&
5165         !dev->source.subsys.u.usb.bus &&
5166         !dev->source.subsys.u.usb.device) {
5167         virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
5168                        _("USB host device is missing bus/device information"));
5169         return NULL;
5170     }
5171
5172     virBufferAddLit(&buf, "usb-host");
5173     if (!dev->missing) {
5174         virBufferAsprintf(&buf, ",hostbus=%d,hostaddr=%d",
5175                           dev->source.subsys.u.usb.bus,
5176                           dev->source.subsys.u.usb.device);
5177     }
5178     virBufferAsprintf(&buf, ",id=%s", dev->info->alias);
5179     if (dev->info->bootIndex)
5180         virBufferAsprintf(&buf, ",bootindex=%d", dev->info->bootIndex);
5181
5182     if (qemuBuildDeviceAddressStr(&buf, def, dev->info, qemuCaps) < 0)
5183         goto error;
5184
5185     if (virBufferError(&buf)) {
5186         virReportOOMError();
5187         goto error;
5188     }
5189
5190     return virBufferContentAndReset(&buf);
5191
5192  error:
5193     virBufferFreeAndReset(&buf);
5194     return NULL;
5195 }
5196
5197
5198 char *
5199 qemuBuildHubDevStr(virDomainDefPtr def,
5200                    virDomainHubDefPtr dev,
5201                    virQEMUCapsPtr qemuCaps)
5202 {
5203     virBuffer buf = VIR_BUFFER_INITIALIZER;
5204
5205     if (dev->type != VIR_DOMAIN_HUB_TYPE_USB) {
5206         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5207                        _("hub type %s not supported"),
5208                        virDomainHubTypeToString(dev->type));
5209         goto error;
5210     }
5211
5212     if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_USB_HUB)) {
5213         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5214                        _("usb-hub not supported by QEMU binary"));
5215         goto error;
5216     }
5217
5218     virBufferAddLit(&buf, "usb-hub");
5219     virBufferAsprintf(&buf, ",id=%s", dev->info.alias);
5220     if (qemuBuildDeviceAddressStr(&buf, def, &dev->info, qemuCaps) < 0)
5221         goto error;
5222
5223     if (virBufferError(&buf)) {
5224         virReportOOMError();
5225         goto error;
5226     }
5227
5228     return virBufferContentAndReset(&buf);
5229
5230  error:
5231     virBufferFreeAndReset(&buf);
5232     return NULL;
5233 }
5234
5235
5236 char *
5237 qemuBuildUSBHostdevUSBDevStr(virDomainHostdevDefPtr dev)
5238 {
5239     char *ret = NULL;
5240
5241     if (dev->missing) {
5242         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5243                        _("This QEMU doesn't not support missing USB devices"));
5244         return NULL;
5245     }
5246
5247     if (!dev->source.subsys.u.usb.bus &&
5248         !dev->source.subsys.u.usb.device) {
5249         virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
5250                        _("USB host device is missing bus/device information"));
5251         return NULL;
5252     }
5253
5254     ignore_value(virAsprintf(&ret, "host:%d.%d",
5255                              dev->source.subsys.u.usb.bus,
5256                              dev->source.subsys.u.usb.device));
5257     return ret;
5258 }
5259
5260 char *
5261 qemuBuildSCSIHostdevDrvStr(virDomainHostdevDefPtr dev,
5262                            virQEMUCapsPtr qemuCaps ATTRIBUTE_UNUSED,
5263                            qemuBuildCommandLineCallbacksPtr callbacks)
5264 {
5265     virBuffer buf = VIR_BUFFER_INITIALIZER;
5266     char *sg = NULL;
5267
5268     sg = (callbacks->qemuGetSCSIDeviceSgName)(NULL,
5269                                               dev->source.subsys.u.scsi.adapter,
5270                                               dev->source.subsys.u.scsi.bus,
5271                                               dev->source.subsys.u.scsi.target,
5272                                               dev->source.subsys.u.scsi.unit);
5273     if (!sg)
5274         goto error;
5275
5276     virBufferAsprintf(&buf, "file=/dev/%s,if=none", sg);
5277     virBufferAsprintf(&buf, ",id=%s-%s",
5278                       virDomainDeviceAddressTypeToString(dev->info->type),
5279                       dev->info->alias);
5280
5281     if (dev->readonly) {
5282         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_READONLY)) {
5283             virBufferAddLit(&buf, ",readonly=on");
5284         } else {
5285             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5286                            _("this qemu doesn't support 'readonly' "
5287                              "for -drive"));
5288             goto error;
5289         }
5290     }
5291
5292     if (virBufferError(&buf)) {
5293         virReportOOMError();
5294         goto error;
5295     }
5296
5297     VIR_FREE(sg);
5298     return virBufferContentAndReset(&buf);
5299  error:
5300     VIR_FREE(sg);
5301     virBufferFreeAndReset(&buf);
5302     return NULL;
5303 }
5304
5305 char *
5306 qemuBuildSCSIHostdevDevStr(virDomainDefPtr def,
5307                            virDomainHostdevDefPtr dev,
5308                            virQEMUCapsPtr qemuCaps)
5309 {
5310     virBuffer buf = VIR_BUFFER_INITIALIZER;
5311     int model = -1;
5312
5313     model = virDomainDeviceFindControllerModel(def, dev->info,
5314                                                VIR_DOMAIN_CONTROLLER_TYPE_SCSI);
5315
5316     if (qemuSetSCSIControllerModel(def, qemuCaps, &model) < 0)
5317         goto error;
5318
5319     if (model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC) {
5320         if (dev->info->addr.drive.target != 0) {
5321            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5322                            _("target must be 0 for scsi host device "
5323                              "if its controller model is 'lsilogic'"));
5324             goto error;
5325         }
5326
5327         if (dev->info->addr.drive.unit > 7) {
5328             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5329                            _("unit must be not more than 7 for scsi host "
5330                              "device if its controller model is 'lsilogic'"));
5331             goto error;
5332         }
5333     }
5334
5335     virBufferAddLit(&buf, "scsi-generic");
5336
5337     if (model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC) {
5338         virBufferAsprintf(&buf, ",bus=scsi%d.%d,scsi-id=%d",
5339                           dev->info->addr.drive.controller,
5340                           dev->info->addr.drive.bus,
5341                           dev->info->addr.drive.unit);
5342     } else {
5343         virBufferAsprintf(&buf, ",bus=scsi%d.0,channel=%d,scsi-id=%d,lun=%d",
5344                           dev->info->addr.drive.controller,
5345                           dev->info->addr.drive.bus,
5346                           dev->info->addr.drive.target,
5347                           dev->info->addr.drive.unit);
5348     }
5349
5350     virBufferAsprintf(&buf, ",drive=%s-%s,id=%s",
5351                       virDomainDeviceAddressTypeToString(dev->info->type),
5352                       dev->info->alias, dev->info->alias);
5353
5354     if (dev->info->bootIndex)
5355         virBufferAsprintf(&buf, ",bootindex=%d", dev->info->bootIndex);
5356
5357     if (virBufferError(&buf)) {
5358         virReportOOMError();
5359         goto error;
5360     }
5361
5362     return virBufferContentAndReset(&buf);
5363  error:
5364     virBufferFreeAndReset(&buf);
5365     return NULL;
5366 }
5367
5368 /* This function outputs a -chardev command line option which describes only the
5369  * host side of the character device */
5370 static char *
5371 qemuBuildChrChardevStr(virDomainChrSourceDefPtr dev, const char *alias,
5372                        virQEMUCapsPtr qemuCaps)
5373 {
5374     virBuffer buf = VIR_BUFFER_INITIALIZER;
5375     bool telnet;
5376
5377     switch (dev->type) {
5378     case VIR_DOMAIN_CHR_TYPE_NULL:
5379         virBufferAsprintf(&buf, "null,id=char%s", alias);
5380         break;
5381
5382     case VIR_DOMAIN_CHR_TYPE_VC:
5383         virBufferAsprintf(&buf, "vc,id=char%s", alias);
5384         break;
5385
5386     case VIR_DOMAIN_CHR_TYPE_PTY:
5387         virBufferAsprintf(&buf, "pty,id=char%s", alias);
5388         break;
5389
5390     case VIR_DOMAIN_CHR_TYPE_DEV:
5391         virBufferAsprintf(&buf, "%s,id=char%s,path=%s",
5392                           STRPREFIX(alias, "parallel") ? "parport" : "tty",
5393                           alias, dev->data.file.path);
5394         break;
5395
5396     case VIR_DOMAIN_CHR_TYPE_FILE:
5397         virBufferAsprintf(&buf, "file,id=char%s,path=%s", alias,
5398                           dev->data.file.path);
5399         break;
5400
5401     case VIR_DOMAIN_CHR_TYPE_PIPE:
5402         virBufferAsprintf(&buf, "pipe,id=char%s,path=%s", alias,
5403                           dev->data.file.path);
5404         break;
5405
5406     case VIR_DOMAIN_CHR_TYPE_STDIO:
5407         virBufferAsprintf(&buf, "stdio,id=char%s", alias);
5408         break;
5409
5410     case VIR_DOMAIN_CHR_TYPE_UDP: {
5411         const char *connectHost = dev->data.udp.connectHost;
5412         const char *bindHost = dev->data.udp.bindHost;
5413         const char *bindService = dev->data.udp.bindService;
5414
5415         if (connectHost == NULL)
5416             connectHost = "";
5417         if (bindHost == NULL)
5418             bindHost = "";
5419         if (bindService == NULL)
5420             bindService = "0";
5421
5422         virBufferAsprintf(&buf,
5423                           "udp,id=char%s,host=%s,port=%s,localaddr=%s,"
5424                           "localport=%s",
5425                           alias,
5426                           connectHost,
5427                           dev->data.udp.connectService,
5428                           bindHost, bindService);
5429         break;
5430     }
5431     case VIR_DOMAIN_CHR_TYPE_TCP:
5432         telnet = dev->data.tcp.protocol == VIR_DOMAIN_CHR_TCP_PROTOCOL_TELNET;
5433         virBufferAsprintf(&buf,
5434                           "socket,id=char%s,host=%s,port=%s%s%s",
5435                           alias,
5436                           dev->data.tcp.host,
5437                           dev->data.tcp.service,
5438                           telnet ? ",telnet" : "",
5439                           dev->data.tcp.listen ? ",server,nowait" : "");
5440         break;
5441
5442     case VIR_DOMAIN_CHR_TYPE_UNIX:
5443         virBufferAsprintf(&buf,
5444                           "socket,id=char%s,path=%s%s",
5445                           alias,
5446                           dev->data.nix.path,
5447                           dev->data.nix.listen ? ",server,nowait" : "");
5448         break;
5449
5450     case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
5451         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_CHARDEV_SPICEVMC)) {
5452             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5453                            _("spicevmc not supported in this QEMU binary"));
5454             goto error;
5455         }
5456         virBufferAsprintf(&buf, "spicevmc,id=char%s,name=%s", alias,
5457                           virDomainChrSpicevmcTypeToString(dev->data.spicevmc));
5458         break;
5459
5460     case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
5461         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_CHARDEV_SPICEPORT)) {
5462             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5463                            _("spiceport not supported in this QEMU binary"));
5464             goto error;
5465         }
5466         virBufferAsprintf(&buf, "spiceport,id=char%s,name=%s", alias,
5467                           dev->data.spiceport.channel);
5468         break;
5469
5470     default:
5471         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5472                        _("unsupported chardev '%s'"),
5473                        virDomainChrTypeToString(dev->type));
5474         goto error;
5475     }
5476
5477     if (virBufferError(&buf)) {
5478         virReportOOMError();
5479         goto error;
5480     }
5481
5482     return virBufferContentAndReset(&buf);
5483
5484  error:
5485     virBufferFreeAndReset(&buf);
5486     return NULL;
5487 }
5488
5489
5490 static char *
5491 qemuBuildChrArgStr(virDomainChrSourceDefPtr dev, const char *prefix)
5492 {
5493     virBuffer buf = VIR_BUFFER_INITIALIZER;
5494
5495     if (prefix)
5496         virBufferAdd(&buf, prefix, strlen(prefix));
5497
5498     switch ((enum virDomainChrType)dev->type) {
5499     case VIR_DOMAIN_CHR_TYPE_NULL:
5500         virBufferAddLit(&buf, "null");
5501         break;
5502
5503     case VIR_DOMAIN_CHR_TYPE_VC:
5504         virBufferAddLit(&buf, "vc");
5505         break;
5506
5507     case VIR_DOMAIN_CHR_TYPE_PTY:
5508         virBufferAddLit(&buf, "pty");
5509         break;
5510
5511     case VIR_DOMAIN_CHR_TYPE_DEV:
5512         virBufferStrcat(&buf, dev->data.file.path, NULL);
5513         break;
5514
5515     case VIR_DOMAIN_CHR_TYPE_FILE:
5516         virBufferAsprintf(&buf, "file:%s", dev->data.file.path);
5517         break;
5518
5519     case VIR_DOMAIN_CHR_TYPE_PIPE:
5520         virBufferAsprintf(&buf, "pipe:%s", dev->data.file.path);
5521         break;
5522
5523     case VIR_DOMAIN_CHR_TYPE_STDIO:
5524         virBufferAddLit(&buf, "stdio");
5525         break;
5526
5527     case VIR_DOMAIN_CHR_TYPE_UDP: {
5528         const char *connectHost = dev->data.udp.connectHost;
5529         const char *bindHost = dev->data.udp.bindHost;
5530         const char *bindService  = dev->data.udp.bindService;
5531
5532         if (connectHost == NULL)
5533             connectHost = "";
5534         if (bindHost == NULL)
5535             bindHost = "";
5536         if (bindService == NULL)
5537             bindService = "0";
5538
5539         virBufferAsprintf(&buf, "udp:%s:%s@%s:%s",
5540                           connectHost,
5541                           dev->data.udp.connectService,
5542                           bindHost,
5543                           bindService);
5544         break;
5545     }
5546     case VIR_DOMAIN_CHR_TYPE_TCP:
5547         if (dev->data.tcp.protocol == VIR_DOMAIN_CHR_TCP_PROTOCOL_TELNET) {
5548             virBufferAsprintf(&buf, "telnet:%s:%s%s",
5549                               dev->data.tcp.host,
5550                               dev->data.tcp.service,
5551                               dev->data.tcp.listen ? ",server,nowait" : "");
5552         } else {
5553             virBufferAsprintf(&buf, "tcp:%s:%s%s",
5554                               dev->data.tcp.host,
5555                               dev->data.tcp.service,
5556                               dev->data.tcp.listen ? ",server,nowait" : "");
5557         }
5558         break;
5559
5560     case VIR_DOMAIN_CHR_TYPE_UNIX:
5561         virBufferAsprintf(&buf, "unix:%s%s",
5562                           dev->data.nix.path,
5563                           dev->data.nix.listen ? ",server,nowait" : "");
5564         break;
5565
5566     case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
5567     case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
5568     case VIR_DOMAIN_CHR_TYPE_NMDM:
5569     case VIR_DOMAIN_CHR_TYPE_LAST:
5570         break;
5571     }
5572
5573     if (virBufferError(&buf)) {
5574         virReportOOMError();
5575         goto error;
5576     }
5577
5578     return virBufferContentAndReset(&buf);
5579
5580  error:
5581     virBufferFreeAndReset(&buf);
5582     return NULL;
5583 }
5584
5585
5586 static char *
5587 qemuBuildVirtioSerialPortDevStr(virDomainChrDefPtr dev,
5588                                 virQEMUCapsPtr qemuCaps)
5589 {
5590     virBuffer buf = VIR_BUFFER_INITIALIZER;
5591     switch (dev->deviceType) {
5592     case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
5593         virBufferAddLit(&buf, "virtconsole");
5594         break;
5595     case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
5596         /* Legacy syntax  '-device spicevmc' */
5597         if (dev->source.type == VIR_DOMAIN_CHR_TYPE_SPICEVMC &&
5598             virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_SPICEVMC)) {
5599             virBufferAddLit(&buf, "spicevmc");
5600         } else {
5601             virBufferAddLit(&buf, "virtserialport");
5602         }
5603         break;
5604     default:
5605         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5606                        _("Cannot use virtio serial for parallel/serial devices"));
5607         return NULL;
5608     }
5609
5610     if (dev->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
5611         dev->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW &&
5612         dev->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390) {
5613         /* Check it's a virtio-serial address */
5614         if (dev->info.type !=
5615             VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL)
5616         {
5617             virReportError(VIR_ERR_INTERNAL_ERROR,
5618                            "%s", _("virtio serial device has invalid address type"));
5619             goto error;
5620         }
5621
5622         virBufferAsprintf(&buf,
5623                           ",bus=" QEMU_VIRTIO_SERIAL_PREFIX "%d.%d",
5624                           dev->info.addr.vioserial.controller,
5625                           dev->info.addr.vioserial.bus);
5626         virBufferAsprintf(&buf,
5627                           ",nr=%d",
5628                           dev->info.addr.vioserial.port);
5629     }
5630
5631     if (dev->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL &&
5632         dev->source.type == VIR_DOMAIN_CHR_TYPE_SPICEVMC &&
5633         dev->target.name &&
5634         STRNEQ(dev->target.name, "com.redhat.spice.0")) {
5635         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5636                        _("Unsupported spicevmc target name '%s'"),
5637                        dev->target.name);
5638         goto error;
5639     }
5640
5641     if (!(dev->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL &&
5642           dev->source.type == VIR_DOMAIN_CHR_TYPE_SPICEVMC &&
5643           virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_SPICEVMC))) {
5644         virBufferAsprintf(&buf, ",chardev=char%s,id=%s",
5645                           dev->info.alias, dev->info.alias);
5646         if (dev->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL) {
5647             virBufferAsprintf(&buf, ",name=%s", dev->target.name
5648                               ? dev->target.name : "com.redhat.spice.0");
5649         }
5650     } else {
5651         virBufferAsprintf(&buf, ",id=%s", dev->info.alias);
5652     }
5653     if (virBufferError(&buf)) {
5654         virReportOOMError();
5655         goto error;
5656     }
5657
5658     return virBufferContentAndReset(&buf);
5659
5660  error:
5661     virBufferFreeAndReset(&buf);
5662     return NULL;
5663 }
5664
5665 static char *
5666 qemuBuildSclpDevStr(virDomainChrDefPtr dev)
5667 {
5668     virBuffer buf = VIR_BUFFER_INITIALIZER;
5669     if (dev->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE) {
5670         switch (dev->targetType) {
5671         case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SCLP:
5672             virBufferAddLit(&buf, "sclpconsole");
5673             break;
5674         case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SCLPLM:
5675             virBufferAddLit(&buf, "sclplmconsole");
5676             break;
5677         }
5678     } else {
5679         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5680                        _("Cannot use slcp with devices other than console"));
5681         goto error;
5682     }
5683     virBufferAsprintf(&buf, ",chardev=char%s,id=%s",
5684                       dev->info.alias, dev->info.alias);
5685     if (virBufferError(&buf)) {
5686         virReportOOMError();
5687         goto error;
5688     }
5689
5690     return virBufferContentAndReset(&buf);
5691
5692  error:
5693     virBufferFreeAndReset(&buf);
5694     return NULL;
5695 }
5696
5697
5698 static int
5699 qemuBuildRNGBackendArgs(virCommandPtr cmd,
5700                         virDomainRNGDefPtr dev,
5701                         virQEMUCapsPtr qemuCaps)
5702 {
5703     virBuffer buf = VIR_BUFFER_INITIALIZER;
5704     char *backend = NULL;
5705     int ret = -1;
5706
5707     switch ((enum virDomainRNGBackend) dev->backend) {
5708     case VIR_DOMAIN_RNG_BACKEND_RANDOM:
5709         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_RNG_RANDOM)) {
5710             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5711                            _("this qemu doesn't support the rng-random "
5712                              "backend"));
5713             goto cleanup;
5714         }
5715
5716         virBufferAsprintf(&buf, "rng-random,id=%s", dev->info.alias);
5717         if (dev->source.file)
5718             virBufferAsprintf(&buf, ",filename=%s", dev->source.file);
5719
5720         virCommandAddArg(cmd, "-object");
5721         virCommandAddArgBuffer(cmd, &buf);
5722         break;
5723
5724     case VIR_DOMAIN_RNG_BACKEND_EGD:
5725
5726         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_RNG_EGD)) {
5727             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
5728                            _("this qemu doesn't support the rng-egd "
5729                              "backend"));
5730             goto cleanup;
5731         }
5732
5733         if (!(backend = qemuBuildChrChardevStr(dev->source.chardev,
5734                                                dev->info.alias, qemuCaps)))
5735             goto cleanup;
5736
5737         virCommandAddArgList(cmd, "-chardev", backend, NULL);
5738
5739         virCommandAddArg(cmd, "-object");
5740         virCommandAddArgFormat(cmd, "rng-egd,chardev=char%s,id=%s",
5741                                dev->info.alias, dev->info.alias);
5742         break;
5743
5744     case VIR_DOMAIN_RNG_BACKEND_LAST:
5745         break;
5746     }
5747
5748     ret = 0;
5749
5750  cleanup:
5751     virBufferFreeAndReset(&buf);
5752     VIR_FREE(backend);
5753     return ret;
5754 }
5755
5756
5757 static int
5758 qemuBuildRNGDeviceArgs(virCommandPtr cmd,
5759                        virDomainDefPtr def,
5760                        virDomainRNGDefPtr dev,
5761                        virQEMUCapsPtr qemuCaps)
5762 {
5763     virBuffer buf = VIR_BUFFER_INITIALIZER;
5764     int ret = -1;
5765
5766     if (dev->model != VIR_DOMAIN_RNG_MODEL_VIRTIO ||
5767         !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIRTIO_RNG)) {
5768         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5769                        _("this qemu doesn't support RNG device type '%s'"),
5770                        virDomainRNGModelTypeToString(dev->model));
5771         goto cleanup;
5772     }
5773
5774     if (dev->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW)
5775         virBufferAsprintf(&buf, "virtio-rng-ccw,rng=%s", dev->info.alias);
5776     else if (dev->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390)
5777         virBufferAsprintf(&buf, "virtio-rng-s390,rng=%s", dev->info.alias);
5778     else if (dev->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO)
5779         virBufferAsprintf(&buf, "virtio-rng-device,rng=%s", dev->info.alias);
5780     else
5781         virBufferAsprintf(&buf, "virtio-rng-pci,rng=%s", dev->info.alias);
5782
5783     if (dev->rate > 0) {
5784         virBufferAsprintf(&buf, ",max-bytes=%u", dev->rate);
5785         if (dev->period)
5786             virBufferAsprintf(&buf, ",period=%u", dev->period);
5787         else
5788             virBufferAddLit(&buf, ",period=1000");
5789     }
5790
5791     if (qemuBuildDeviceAddressStr(&buf, def, &dev->info, qemuCaps) < 0)
5792         goto cleanup;
5793
5794     virCommandAddArg(cmd, "-device");
5795     virCommandAddArgBuffer(cmd, &buf);
5796
5797     ret = 0;
5798
5799  cleanup:
5800     virBufferFreeAndReset(&buf);
5801     return ret;
5802 }
5803
5804
5805 static char *qemuBuildTPMBackendStr(const virDomainDef *def,
5806                                     virQEMUCapsPtr qemuCaps,
5807                                     const char *emulator)
5808 {
5809     const virDomainTPMDef *tpm = def->tpm;
5810     virBuffer buf = VIR_BUFFER_INITIALIZER;
5811     const char *type = virDomainTPMBackendTypeToString(tpm->type);
5812     char *cancel_path;
5813     const char *tpmdev;
5814
5815     virBufferAsprintf(&buf, "%s,id=tpm-%s", type, tpm->info.alias);
5816
5817     switch (tpm->type) {
5818     case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
5819         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_TPM_PASSTHROUGH))
5820             goto no_support;
5821
5822         tpmdev = tpm->data.passthrough.source.data.file.path;
5823         if (!(cancel_path = virTPMCreateCancelPath(tpmdev)))
5824             goto error;
5825
5826         virBufferAddLit(&buf, ",path=");
5827         virBufferEscape(&buf, ',', ",", "%s", tpmdev);
5828
5829         virBufferAddLit(&buf, ",cancel-path=");
5830         virBufferEscape(&buf, ',', ",", "%s", cancel_path);
5831         VIR_FREE(cancel_path);
5832
5833         break;
5834     case VIR_DOMAIN_TPM_TYPE_LAST:
5835         goto error;
5836     }
5837
5838     if (virBufferError(&buf)) {
5839         virReportOOMError();
5840         goto error;
5841     }
5842
5843     return virBufferContentAndReset(&buf);
5844
5845  no_support:
5846     virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5847                    _("The QEMU executable %s does not support TPM "
5848                      "backend type %s"),
5849                    emulator, type);
5850
5851  error:
5852     virBufferFreeAndReset(&buf);
5853     return NULL;
5854 }
5855
5856
5857 static char *qemuBuildTPMDevStr(const virDomainDef *def,
5858                                 virQEMUCapsPtr qemuCaps,
5859                                 const char *emulator)
5860 {
5861     virBuffer buf = VIR_BUFFER_INITIALIZER;
5862     const virDomainTPMDef *tpm = def->tpm;
5863     const char *model = virDomainTPMModelTypeToString(tpm->model);
5864
5865     if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_TPM_TIS)) {
5866         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5867                        _("The QEMU executable %s does not support TPM "
5868                        "model %s"),
5869                        emulator, model);
5870         goto error;
5871     }
5872
5873     virBufferAsprintf(&buf, "%s,tpmdev=tpm-%s,id=%s",
5874                       model, tpm->info.alias, tpm->info.alias);
5875
5876     if (virBufferError(&buf)) {
5877         virReportOOMError();
5878         goto error;
5879     }
5880
5881     return virBufferContentAndReset(&buf);
5882
5883  error:
5884     virBufferFreeAndReset(&buf);
5885     return NULL;
5886 }
5887
5888
5889 static char *qemuBuildSmbiosBiosStr(virSysinfoDefPtr def)
5890 {
5891     virBuffer buf = VIR_BUFFER_INITIALIZER;
5892
5893     if ((def->bios_vendor == NULL) && (def->bios_version == NULL) &&
5894         (def->bios_date == NULL) && (def->bios_release == NULL))
5895         return NULL;
5896
5897     virBufferAddLit(&buf, "type=0");
5898
5899     /* 0:Vendor */
5900     if (def->bios_vendor)
5901         virBufferAsprintf(&buf, ",vendor=%s", def->bios_vendor);
5902     /* 0:BIOS Version */
5903     if (def->bios_version)
5904         virBufferAsprintf(&buf, ",version=%s", def->bios_version);
5905     /* 0:BIOS Release Date */
5906     if (def->bios_date)
5907         virBufferAsprintf(&buf, ",date=%s", def->bios_date);
5908     /* 0:System BIOS Major Release and 0:System BIOS Minor Release */
5909     if (def->bios_release)
5910         virBufferAsprintf(&buf, ",release=%s", def->bios_release);
5911
5912     if (virBufferError(&buf)) {
5913         virReportOOMError();
5914         goto error;
5915     }
5916
5917     return virBufferContentAndReset(&buf);
5918
5919  error:
5920     virBufferFreeAndReset(&buf);
5921     return NULL;
5922 }
5923
5924 static char *qemuBuildSmbiosSystemStr(virSysinfoDefPtr def, bool skip_uuid)
5925 {
5926     virBuffer buf = VIR_BUFFER_INITIALIZER;
5927
5928     if ((def->system_manufacturer == NULL) && (def->system_sku == NULL) &&
5929         (def->system_product == NULL) && (def->system_version == NULL) &&
5930         (def->system_serial == NULL) && (def->system_family == NULL) &&
5931         (def->system_uuid == NULL || skip_uuid))
5932         return NULL;
5933
5934     virBufferAddLit(&buf, "type=1");
5935
5936     /* 1:Manufacturer */
5937     if (def->system_manufacturer)
5938         virBufferAsprintf(&buf, ",manufacturer=%s",
5939                           def->system_manufacturer);
5940      /* 1:Product Name */
5941     if (def->system_product)
5942         virBufferAsprintf(&buf, ",product=%s", def->system_product);
5943     /* 1:Version */
5944     if (def->system_version)
5945         virBufferAsprintf(&buf, ",version=%s", def->system_version);
5946     /* 1:Serial Number */
5947     if (def->system_serial)
5948         virBufferAsprintf(&buf, ",serial=%s", def->system_serial);
5949     /* 1:UUID */
5950     if (def->system_uuid && !skip_uuid)
5951         virBufferAsprintf(&buf, ",uuid=%s", def->system_uuid);
5952     /* 1:SKU Number */
5953     if (def->system_sku)
5954         virBufferAsprintf(&buf, ",sku=%s", def->system_sku);
5955     /* 1:Family */
5956     if (def->system_family)
5957         virBufferAsprintf(&buf, ",family=%s", def->system_family);
5958
5959     if (virBufferError(&buf)) {
5960         virReportOOMError();
5961         goto error;
5962     }
5963
5964     return virBufferContentAndReset(&buf);
5965
5966  error:
5967     virBufferFreeAndReset(&buf);
5968     return NULL;
5969 }
5970
5971 static char *
5972 qemuBuildClockArgStr(virDomainClockDefPtr def)
5973 {
5974     virBuffer buf = VIR_BUFFER_INITIALIZER;
5975
5976     switch (def->offset) {
5977     case VIR_DOMAIN_CLOCK_OFFSET_UTC:
5978         virBufferAddLit(&buf, "base=utc");
5979         break;
5980
5981     case VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME:
5982     case VIR_DOMAIN_CLOCK_OFFSET_TIMEZONE:
5983         virBufferAddLit(&buf, "base=localtime");
5984         break;
5985
5986     case VIR_DOMAIN_CLOCK_OFFSET_VARIABLE: {
5987         time_t now = time(NULL);
5988         struct tm nowbits;
5989
5990         if (def->data.variable.basis == VIR_DOMAIN_CLOCK_BASIS_LOCALTIME) {
5991             long localOffset;
5992
5993             /* in the case of basis='localtime', rather than trying to
5994              * keep that basis (and associated offset from UTC) in the
5995              * status and deal with adding in the difference each time
5996              * there is an RTC_CHANGE event, it is simpler and less
5997              * error prone to just convert the adjustment an offset
5998              * from UTC right now (and change the status to
5999              * "basis='utc' to reflect this). This eliminates
6000              * potential errors in both RTC_CHANGE events and in
6001              * migration (in the case that the status of DST, or the
6002              * timezone of the destination host, changed relative to
6003              * startup).
6004              */
6005             if (virTimeLocalOffsetFromUTC(&localOffset) < 0)
6006                goto error;
6007             def->data.variable.adjustment += localOffset;
6008             def->data.variable.basis = VIR_DOMAIN_CLOCK_BASIS_UTC;
6009         }
6010
6011         now += def->data.variable.adjustment;
6012         gmtime_r(&now, &nowbits);
6013
6014         /* when an RTC_CHANGE event is received from qemu, we need to
6015          * have the adjustment used at domain start time available to
6016          * compute the new offset from UTC. As this new value is
6017          * itself stored in def->data.variable.adjustment, we need to
6018          * save a copy of it now.
6019         */
6020         def->data.variable.adjustment0 = def->data.variable.adjustment;
6021
6022         virBufferAsprintf(&buf, "base=%d-%02d-%02dT%02d:%02d:%02d",
6023                           nowbits.tm_year + 1900,
6024                           nowbits.tm_mon + 1,
6025                           nowbits.tm_mday,
6026                           nowbits.tm_hour,
6027                           nowbits.tm_min,
6028                           nowbits.tm_sec);
6029     }   break;
6030
6031     default:
6032         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6033                        _("unsupported clock offset '%s'"),
6034                        virDomainClockOffsetTypeToString(def->offset));
6035         goto error;
6036     }
6037
6038     /* Look for an 'rtc' timer element, and add in appropriate clock= and driftfix= */
6039     size_t i;
6040     for (i = 0; i < def->ntimers; i++) {
6041         if (def->timers[i]->name == VIR_DOMAIN_TIMER_NAME_RTC) {
6042             switch (def->timers[i]->track) {
6043             case -1: /* unspecified - use hypervisor default */
6044                 break;
6045             case VIR_DOMAIN_TIMER_TRACK_BOOT:
6046                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6047                                _("unsupported rtc timer track '%s'"),
6048                                virDomainTimerTrackTypeToString(def->timers[i]->track));
6049                 goto error;
6050             case VIR_DOMAIN_TIMER_TRACK_GUEST:
6051                 virBufferAddLit(&buf, ",clock=vm");
6052                 break;
6053             case VIR_DOMAIN_TIMER_TRACK_WALL:
6054                 virBufferAddLit(&buf, ",clock=host");
6055                 break;
6056             }
6057
6058             switch (def->timers[i]->tickpolicy) {
6059             case -1:
6060             case VIR_DOMAIN_TIMER_TICKPOLICY_DELAY:
6061                 /* This is the default - missed ticks delivered when
6062                    next scheduled, at normal rate */
6063                 break;
6064             case VIR_DOMAIN_TIMER_TICKPOLICY_CATCHUP:
6065                 /* deliver ticks at a faster rate until caught up */
6066                 virBufferAddLit(&buf, ",driftfix=slew");
6067                 break;
6068             case VIR_DOMAIN_TIMER_TICKPOLICY_MERGE:
6069             case VIR_DOMAIN_TIMER_TICKPOLICY_DISCARD:
6070                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6071                                _("unsupported rtc timer tickpolicy '%s'"),
6072                                virDomainTimerTickpolicyTypeToString(def->timers[i]->tickpolicy));
6073                 goto error;
6074             }
6075             break; /* no need to check other timers - there is only one rtc */
6076         }
6077     }
6078
6079     if (virBufferError(&buf)) {
6080         virReportOOMError();
6081         goto error;
6082     }
6083
6084     return virBufferContentAndReset(&buf);
6085
6086  error:
6087     virBufferFreeAndReset(&buf);
6088     return NULL;
6089 }
6090
6091
6092 static int
6093 qemuBuildCpuArgStr(virQEMUDriverPtr driver,
6094                    const virDomainDef *def,
6095                    const char *emulator,
6096                    virQEMUCapsPtr qemuCaps,
6097                    virArch hostarch,
6098                    char **opt,
6099                    bool *hasHwVirt,
6100                    bool migrating)
6101 {
6102     virCPUDefPtr host = NULL;
6103     virCPUDefPtr guest = NULL;
6104     virCPUDefPtr cpu = NULL;
6105     size_t ncpus = 0;
6106     char **cpus = NULL;
6107     const char *default_model;
6108     virCPUDataPtr data = NULL;
6109     bool have_cpu = false;
6110     char *compare_msg = NULL;
6111     int ret = -1;
6112     virBuffer buf = VIR_BUFFER_INITIALIZER;
6113     size_t i;
6114     virCapsPtr caps = NULL;
6115
6116     *hasHwVirt = false;
6117
6118     if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
6119         goto cleanup;
6120
6121     host = caps->host.cpu;
6122
6123     if (def->os.arch == VIR_ARCH_I686)
6124         default_model = "qemu32";
6125     else
6126         default_model = "qemu64";
6127
6128     if (def->cpu &&
6129         (def->cpu->mode != VIR_CPU_MODE_CUSTOM || def->cpu->model)) {
6130         virCPUCompareResult cmp;
6131         const char *preferred;
6132
6133         if (!host ||
6134             !host->model ||
6135             (ncpus = virQEMUCapsGetCPUDefinitions(qemuCaps, &cpus)) == 0) {
6136             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6137                            _("CPU specification not supported by hypervisor"));
6138             goto cleanup;
6139         }
6140
6141         if (!(cpu = virCPUDefCopy(def->cpu)))
6142             goto cleanup;
6143
6144         if (cpu->mode != VIR_CPU_MODE_CUSTOM &&
6145             !migrating &&
6146             cpuUpdate(cpu, host) < 0)
6147             goto cleanup;
6148
6149         cmp = cpuGuestData(host, cpu, &data, &compare_msg);
6150         switch (cmp) {
6151         case VIR_CPU_COMPARE_INCOMPATIBLE:
6152             if (compare_msg) {
6153                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6154                                _("guest and host CPU are not compatible: %s"),
6155                                compare_msg);
6156             } else {
6157                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6158                                _("guest CPU is not compatible with host CPU"));
6159             }
6160             /* fall through */
6161         case VIR_CPU_COMPARE_ERROR:
6162             goto cleanup;
6163
6164         default:
6165             break;
6166         }
6167
6168         /* Only 'svm' requires --enable-nesting. The nested
6169          * 'vmx' patches now simply hook off the CPU features
6170          */
6171         if (def->os.arch == VIR_ARCH_X86_64 ||
6172             def->os.arch == VIR_ARCH_I686) {
6173             int hasSVM = cpuHasFeature(data, "svm");
6174             if (hasSVM < 0)
6175                 goto cleanup;
6176             *hasHwVirt = hasSVM > 0 ? true : false;
6177         }
6178
6179         if (cpu->mode == VIR_CPU_MODE_HOST_PASSTHROUGH) {
6180             const char *mode = virCPUModeTypeToString(cpu->mode);
6181             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_CPU_HOST)) {
6182                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6183                                _("CPU mode '%s' is not supported by QEMU"
6184                                  " binary"), mode);
6185                 goto cleanup;
6186             }
6187             if (def->virtType != VIR_DOMAIN_VIRT_KVM) {
6188                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6189                                _("CPU mode '%s' is only supported with kvm"),
6190                                mode);
6191                 goto cleanup;
6192             }
6193             virBufferAddLit(&buf, "host");
6194         } else {
6195             if (VIR_ALLOC(guest) < 0)
6196                 goto cleanup;
6197             if (VIR_STRDUP(guest->vendor_id, cpu->vendor_id) < 0)
6198                 goto cleanup;
6199
6200             guest->arch = host->arch;
6201             if (cpu->match == VIR_CPU_MATCH_MINIMUM)
6202                 preferred = host->model;
6203             else
6204                 preferred = cpu->model;
6205
6206             guest->type = VIR_CPU_TYPE_GUEST;
6207             guest->fallback = cpu->fallback;
6208             if (cpuDecode(guest, data, (const char **)cpus, ncpus, preferred) < 0)
6209                 goto cleanup;
6210
6211             virBufferAdd(&buf, guest->model, -1);
6212             if (guest->vendor_id)
6213                 virBufferAsprintf(&buf, ",vendor=%s", guest->vendor_id);
6214             for (i = 0; i < guest->nfeatures; i++) {
6215                 char sign;
6216                 if (guest->features[i].policy == VIR_CPU_FEATURE_DISABLE)
6217                     sign = '-';
6218                 else
6219                     sign = '+';
6220
6221                 virBufferAsprintf(&buf, ",%c%s", sign, guest->features[i].name);
6222             }
6223         }
6224         have_cpu = true;
6225     } else {
6226         /*
6227          * Need to force a 32-bit guest CPU type if
6228          *
6229          *  1. guest OS is i686
6230          *  2. host OS is x86_64
6231          *  3. emulator is qemu-kvm or kvm
6232          *
6233          * Or
6234          *
6235          *  1. guest OS is i686
6236          *  2. emulator is qemu-system-x86_64
6237          */
6238         if (def->os.arch == VIR_ARCH_I686 &&
6239             ((hostarch == VIR_ARCH_X86_64 &&
6240               strstr(emulator, "kvm")) ||
6241              strstr(emulator, "x86_64"))) {
6242             virBufferAdd(&buf, default_model, -1);
6243             have_cpu = true;
6244         }
6245     }
6246
6247     /* Handle paravirtual timers  */
6248     for (i = 0; i < def->clock.ntimers; i++) {
6249         virDomainTimerDefPtr timer = def->clock.timers[i];
6250
6251         if (timer->present == -1)
6252             continue;
6253
6254         if (timer->name == VIR_DOMAIN_TIMER_NAME_KVMCLOCK) {
6255             virBufferAsprintf(&buf, "%s,%ckvmclock",
6256                               have_cpu ? "" : default_model,
6257                               timer->present ? '+' : '-');
6258             have_cpu = true;
6259         } else if (timer->name == VIR_DOMAIN_TIMER_NAME_HYPERVCLOCK &&
6260                    timer->present) {
6261             virBufferAsprintf(&buf, "%s,hv_time",
6262                               have_cpu ? "" : default_model);
6263             have_cpu = true;
6264         }
6265     }
6266
6267     if (def->apic_eoi) {
6268         char sign;
6269         if (def->apic_eoi == VIR_DOMAIN_FEATURE_STATE_ON)
6270             sign = '+';
6271         else
6272             sign = '-';
6273
6274         virBufferAsprintf(&buf, "%s,%ckvm_pv_eoi",
6275                           have_cpu ? "" : default_model,
6276                           sign);
6277         have_cpu = true;
6278     }
6279
6280     if (def->features[VIR_DOMAIN_FEATURE_PVSPINLOCK]) {
6281         char sign;
6282         if (def->features[VIR_DOMAIN_FEATURE_PVSPINLOCK] == VIR_DOMAIN_FEATURE_STATE_ON)
6283             sign = '+';
6284         else
6285             sign = '-';
6286
6287         virBufferAsprintf(&buf, "%s,%ckvm_pv_unhalt",
6288                           have_cpu ? "" : default_model,
6289                           sign);
6290         have_cpu = true;
6291     }
6292
6293     if (def->features[VIR_DOMAIN_FEATURE_HYPERV] == VIR_DOMAIN_FEATURE_STATE_ON) {
6294         if (!have_cpu) {
6295             virBufferAdd(&buf, default_model, -1);
6296             have_cpu = true;
6297         }
6298
6299         for (i = 0; i < VIR_DOMAIN_HYPERV_LAST; i++) {
6300             switch ((enum virDomainHyperv) i) {
6301             case VIR_DOMAIN_HYPERV_RELAXED:
6302             case VIR_DOMAIN_HYPERV_VAPIC:
6303                 if (def->hyperv_features[i] == VIR_DOMAIN_FEATURE_STATE_ON)
6304                     virBufferAsprintf(&buf, ",hv_%s",
6305                                       virDomainHypervTypeToString(i));
6306                 break;
6307
6308             case VIR_DOMAIN_HYPERV_SPINLOCKS:
6309                 if (def->hyperv_features[i] == VIR_DOMAIN_FEATURE_STATE_ON)
6310                     virBufferAsprintf(&buf, ",hv_spinlocks=0x%x",
6311                                       def->hyperv_spinlocks);
6312                 break;
6313
6314             case VIR_DOMAIN_HYPERV_LAST:
6315                 break;
6316             }
6317         }
6318     }
6319
6320     if (virBufferError(&buf)) {
6321         virReportOOMError();
6322         goto cleanup;
6323     }
6324
6325     *opt = virBufferContentAndReset(&buf);
6326
6327     ret = 0;
6328
6329  cleanup:
6330     VIR_FREE(compare_msg);
6331     cpuDataFree(data);
6332     virCPUDefFree(guest);
6333     virCPUDefFree(cpu);
6334     virObjectUnref(caps);
6335     return ret;
6336 }
6337
6338 static int
6339 qemuBuildObsoleteAccelArg(virCommandPtr cmd,
6340                           const virDomainDef *def,
6341                           virQEMUCapsPtr qemuCaps)
6342 {
6343     bool disableKQEMU = false;
6344     bool enableKQEMU = false;
6345     bool disableKVM = false;
6346     bool enableKVM = false;
6347
6348     switch (def->virtType) {
6349     case VIR_DOMAIN_VIRT_QEMU:
6350         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_KQEMU))
6351             disableKQEMU = true;
6352         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_KVM))
6353             disableKVM = true;
6354         break;
6355
6356     case VIR_DOMAIN_VIRT_KQEMU:
6357         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_KVM))
6358             disableKVM = true;
6359
6360         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_ENABLE_KQEMU)) {
6361             enableKQEMU = true;
6362         } else if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_KQEMU)) {
6363             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6364                            _("the QEMU binary does not support kqemu"));
6365             return -1;
6366         }
6367         break;
6368
6369     case VIR_DOMAIN_VIRT_KVM:
6370         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_KQEMU))
6371             disableKQEMU = true;
6372
6373         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_ENABLE_KVM)) {
6374             enableKVM = true;
6375         } else if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_KVM)) {
6376             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6377                            _("the QEMU binary does not support kvm"));
6378             return -1;
6379         }
6380         break;
6381
6382     case VIR_DOMAIN_VIRT_XEN:
6383         /* XXX better check for xenner */
6384         break;
6385
6386     default:
6387         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6388                        _("the QEMU binary does not support %s"),
6389                        virDomainVirtTypeToString(def->virtType));
6390         return -1;
6391     }
6392
6393     if (disableKQEMU)
6394         virCommandAddArg(cmd, "-no-kqemu");
6395     else if (enableKQEMU)
6396         virCommandAddArgList(cmd, "-enable-kqemu", "-kernel-kqemu", NULL);
6397     if (disableKVM)
6398         virCommandAddArg(cmd, "-no-kvm");
6399     if (enableKVM)
6400         virCommandAddArg(cmd, "-enable-kvm");
6401
6402     return 0;
6403 }
6404
6405 static int
6406 qemuBuildMachineArgStr(virCommandPtr cmd,
6407                        const virDomainDef *def,
6408                        virQEMUCapsPtr qemuCaps)
6409 {
6410     bool obsoleteAccel = false;
6411
6412     /* This should *never* be NULL, since we always provide
6413      * a machine in the capabilities data for QEMU. So this
6414      * check is just here as a safety in case the unexpected
6415      * happens */
6416     if (!def->os.machine)
6417         return 0;
6418
6419     if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MACHINE_OPT)) {
6420         /* if no parameter to the machine type is needed, we still use
6421          * '-M' to keep the most of the compatibility with older versions.
6422          */
6423         virCommandAddArgList(cmd, "-M", def->os.machine, NULL);
6424         if (def->mem.dump_core) {
6425             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6426                            _("dump-guest-core is not available "
6427                              "with this QEMU binary"));
6428             return -1;
6429         }
6430
6431         if (def->mem.nosharepages) {
6432             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6433                            _("disable shared memory is not available "
6434                              "with this QEMU binary"));
6435              return -1;
6436         }
6437
6438         obsoleteAccel = true;
6439     } else {
6440         virBuffer buf = VIR_BUFFER_INITIALIZER;
6441
6442         virCommandAddArg(cmd, "-machine");
6443         virBufferAdd(&buf, def->os.machine, -1);
6444
6445         if (def->virtType == VIR_DOMAIN_VIRT_QEMU)
6446             virBufferAddLit(&buf, ",accel=tcg");
6447         else if (def->virtType == VIR_DOMAIN_VIRT_KVM)
6448             virBufferAddLit(&buf, ",accel=kvm");
6449         else
6450             obsoleteAccel = true;
6451
6452         /* To avoid the collision of creating USB controllers when calling
6453          * machine->init in QEMU, it needs to set usb=off
6454          */
6455         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_MACHINE_USB_OPT))
6456             virBufferAddLit(&buf, ",usb=off");
6457
6458         if (def->mem.dump_core) {
6459             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DUMP_GUEST_CORE)) {
6460                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6461                                _("dump-guest-core is not available "
6462                                  "with this QEMU binary"));
6463                 virBufferFreeAndReset(&buf);
6464                 return -1;
6465             }
6466
6467             virBufferAsprintf(&buf, ",dump-guest-core=%s",
6468                               virDomainMemDumpTypeToString(def->mem.dump_core));
6469         }
6470
6471         if (def->mem.nosharepages) {
6472             if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_MEM_MERGE)) {
6473                 virBufferAddLit(&buf, ",mem-merge=off");
6474             } else {
6475                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6476                                _("disable shared memory is not available "
6477                                  "with this QEMU binary"));
6478                 virBufferFreeAndReset(&buf);
6479                 return -1;
6480             }
6481         }
6482
6483         virCommandAddArgBuffer(cmd, &buf);
6484     }
6485
6486     if (obsoleteAccel &&
6487         qemuBuildObsoleteAccelArg(cmd, def, qemuCaps) < 0)
6488         return -1;
6489
6490     return 0;
6491 }
6492
6493 static char *
6494 qemuBuildSmpArgStr(const virDomainDef *def,
6495                    virQEMUCapsPtr qemuCaps)
6496 {
6497     virBuffer buf = VIR_BUFFER_INITIALIZER;
6498
6499     virBufferAsprintf(&buf, "%u", def->vcpus);
6500
6501     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_SMP_TOPOLOGY)) {
6502         if (def->vcpus != def->maxvcpus)
6503             virBufferAsprintf(&buf, ",maxcpus=%u", def->maxvcpus);
6504         /* sockets, cores, and threads are either all zero
6505          * or all non-zero, thus checking one of them is enough */
6506         if (def->cpu && def->cpu->sockets) {
6507             virBufferAsprintf(&buf, ",sockets=%u", def->cpu->sockets);
6508             virBufferAsprintf(&buf, ",cores=%u", def->cpu->cores);
6509             virBufferAsprintf(&buf, ",threads=%u", def->cpu->threads);
6510         }
6511         else {
6512             virBufferAsprintf(&buf, ",sockets=%u", def->maxvcpus);
6513             virBufferAsprintf(&buf, ",cores=%u", 1);
6514             virBufferAsprintf(&buf, ",threads=%u", 1);
6515         }
6516     } else if (def->vcpus != def->maxvcpus) {
6517         virBufferFreeAndReset(&buf);
6518         /* FIXME - consider hot-unplugging cpus after boot for older qemu */
6519         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6520                        _("setting current vcpu count less than maximum is "
6521                          "not supported with this QEMU binary"));
6522         return NULL;
6523     }
6524
6525     if (virBufferError(&buf)) {
6526         virBufferFreeAndReset(&buf);
6527         virReportOOMError();
6528         return NULL;
6529     }
6530
6531     return virBufferContentAndReset(&buf);
6532 }
6533
6534 static int
6535 qemuBuildNumaArgStr(const virDomainDef *def, virCommandPtr cmd)
6536 {
6537     size_t i;
6538     virBuffer buf = VIR_BUFFER_INITIALIZER;
6539     char *cpumask = NULL;
6540     int ret = -1;
6541
6542     for (i = 0; i < def->cpu->ncells; i++) {
6543         VIR_FREE(cpumask);
6544         virCommandAddArg(cmd, "-numa");
6545         virBufferAsprintf(&buf, "node,nodeid=%d", def->cpu->cells[i].cellid);
6546         virBufferAddLit(&buf, ",cpus=");
6547         if (!(cpumask = virBitmapFormat(def->cpu->cells[i].cpumask)))
6548             goto cleanup;
6549
6550         /* Up through qemu 1.4, -numa does not accept a cpus
6551          * argument any more complex than start-stop.
6552          *
6553          * XXX For qemu 1.5, the syntax has not yet been decided;
6554          * but when it is, we need a capability bit and
6555          * translation of our cpumask into the qemu syntax.  */
6556         if (strchr(cpumask, ',')) {
6557             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6558                            _("disjoint NUMA cpu ranges are not supported "
6559                              "with this QEMU"));
6560             goto cleanup;
6561         }
6562         virBufferAdd(&buf, cpumask, -1);
6563         def->cpu->cells[i].mem = VIR_DIV_UP(def->cpu->cells[i].mem,
6564                                             1024) * 1024;
6565         virBufferAsprintf(&buf, ",mem=%d", def->cpu->cells[i].mem / 1024);
6566
6567         if (virBufferError(&buf)) {
6568             virReportOOMError();
6569             goto cleanup;
6570         }
6571
6572         virCommandAddArgBuffer(cmd, &buf);
6573     }
6574     ret = 0;
6575
6576  cleanup:
6577     VIR_FREE(cpumask);
6578     virBufferFreeAndReset(&buf);
6579     return ret;
6580 }
6581
6582
6583 static int
6584 qemuBuildGraphicsVNCCommandLine(virQEMUDriverConfigPtr cfg,
6585                                 virCommandPtr cmd,
6586                                 virDomainDefPtr def,
6587                                 virQEMUCapsPtr qemuCaps,
6588                                 virDomainGraphicsDefPtr graphics)
6589 {
6590     virBuffer opt = VIR_BUFFER_INITIALIZER;
6591     const char *listenNetwork;
6592     const char *listenAddr = NULL;
6593     char *netAddr = NULL;
6594     bool escapeAddr;
6595     int ret;
6596
6597     if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VNC)) {
6598         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6599                        _("vnc graphics are not supported with this QEMU"));
6600         goto error;
6601     }
6602
6603     if (graphics->data.vnc.socket || cfg->vncAutoUnixSocket) {
6604         if (!graphics->data.vnc.socket &&
6605             virAsprintf(&graphics->data.vnc.socket,
6606                         "%s/%s.vnc", cfg->libDir, def->name) == -1)
6607             goto error;
6608
6609         virBufferAsprintf(&opt, "unix:%s", graphics->data.vnc.socket);
6610
6611     } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VNC_COLON)) {
6612         switch (virDomainGraphicsListenGetType(graphics, 0)) {
6613         case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS:
6614             listenAddr = virDomainGraphicsListenGetAddress(graphics, 0);
6615             break;
6616
6617         case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK:
6618             listenNetwork = virDomainGraphicsListenGetNetwork(graphics, 0);
6619             if (!listenNetwork)
6620                 break;
6621             ret = networkGetNetworkAddress(listenNetwork, &netAddr);
6622             if (ret <= -2) {
6623                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6624                                "%s", _("network-based listen not possible, "
6625                                        "network driver not present"));
6626                 goto error;
6627             }
6628             if (ret < 0) {
6629                 virReportError(VIR_ERR_XML_ERROR,
6630                                _("listen network '%s' had no usable address"),
6631                                listenNetwork);
6632                 goto error;
6633             }
6634             listenAddr = netAddr;
6635             /* store the address we found in the <graphics> element so it will
6636              * show up in status. */
6637             if (virDomainGraphicsListenSetAddress(graphics, 0,
6638                                                   listenAddr, -1, false) < 0)
6639                goto error;
6640             break;
6641         }
6642
6643         if (!listenAddr)
6644             listenAddr = cfg->vncListen;
6645
6646         escapeAddr = strchr(listenAddr, ':') != NULL;
6647         if (escapeAddr)
6648             virBufferAsprintf(&opt, "[%s]", listenAddr);
6649         else
6650             virBufferAdd(&opt, listenAddr, -1);
6651         virBufferAsprintf(&opt, ":%d",
6652                           graphics->data.vnc.port - 5900);
6653
6654         VIR_FREE(netAddr);
6655     } else {
6656         virBufferAsprintf(&opt, "%d",
6657                           graphics->data.vnc.port - 5900);
6658     }
6659
6660     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VNC_COLON)) {
6661         if (!graphics->data.vnc.socket &&
6662             graphics->data.vnc.websocket) {
6663                 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VNC_WEBSOCKET)) {
6664                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6665                                    _("VNC WebSockets are not supported "
6666                                      "with this QEMU binary"));
6667                     goto error;
6668                 }
6669                 virBufferAsprintf(&opt, ",websocket=%d", graphics->data.vnc.websocket);
6670             }
6671
6672         if (graphics->data.vnc.sharePolicy) {
6673             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VNC_SHARE_POLICY)) {
6674                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6675                                _("vnc display sharing policy is not "
6676                                  "supported with this QEMU"));
6677                 goto error;
6678             }
6679
6680             virBufferAsprintf(&opt, ",share=%s",
6681                               virDomainGraphicsVNCSharePolicyTypeToString(
6682                               graphics->data.vnc.sharePolicy));
6683         }
6684
6685         if (graphics->data.vnc.auth.passwd || cfg->vncPassword)
6686             virBufferAddLit(&opt, ",password");
6687
6688         if (cfg->vncTLS) {
6689             virBufferAddLit(&opt, ",tls");
6690             if (cfg->vncTLSx509verify)
6691                 virBufferAsprintf(&opt, ",x509verify=%s", cfg->vncTLSx509certdir);
6692             else
6693                 virBufferAsprintf(&opt, ",x509=%s", cfg->vncTLSx509certdir);
6694         }
6695
6696         if (cfg->vncSASL) {
6697             virBufferAddLit(&opt, ",sasl");
6698
6699             if (cfg->vncSASLdir)
6700                 virCommandAddEnvPair(cmd, "SASL_CONF_DIR", cfg->vncSASLdir);
6701
6702             /* TODO: Support ACLs later */
6703         }
6704     }
6705
6706     virCommandAddArg(cmd, "-vnc");
6707     virCommandAddArgBuffer(cmd, &opt);
6708     if (graphics->data.vnc.keymap)
6709         virCommandAddArgList(cmd, "-k", graphics->data.vnc.keymap, NULL);
6710
6711     /* Unless user requested it, set the audio backend to none, to
6712      * prevent it opening the host OS audio devices, since that causes
6713      * security issues and might not work when using VNC.
6714      */
6715     if (cfg->vncAllowHostAudio)
6716         virCommandAddEnvPassBlockSUID(cmd, "QEMU_AUDIO_DRV", NULL);
6717     else
6718         virCommandAddEnvString(cmd, "QEMU_AUDIO_DRV=none");
6719
6720     return 0;
6721
6722  error:
6723     VIR_FREE(netAddr);
6724     virBufferFreeAndReset(&opt);
6725     return -1;
6726 }
6727
6728
6729 static int
6730 qemuBuildGraphicsSPICECommandLine(virQEMUDriverConfigPtr cfg,
6731                                   virCommandPtr cmd,
6732                                   virQEMUCapsPtr qemuCaps,
6733                                   virDomainGraphicsDefPtr graphics)
6734 {
6735     virBuffer opt = VIR_BUFFER_INITIALIZER;
6736     const char *listenNetwork;
6737     const char *listenAddr = NULL;
6738     char *netAddr = NULL;
6739     int ret;
6740     int defaultMode = graphics->data.spice.defaultMode;
6741     int port = graphics->data.spice.port;
6742     int tlsPort = graphics->data.spice.tlsPort;
6743     size_t i;
6744
6745     if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SPICE)) {
6746         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6747                        _("spice graphics are not supported with this QEMU"));
6748         goto error;
6749     }
6750
6751     if (port > 0 || tlsPort <= 0)
6752         virBufferAsprintf(&opt, "port=%u", port);
6753
6754     if (tlsPort > 0) {
6755         if (!cfg->spiceTLS) {
6756             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6757                            _("spice TLS port set in XML configuration,"
6758                              " but TLS is disabled in qemu.conf"));
6759             goto error;
6760         }
6761         if (port > 0)
6762             virBufferAddChar(&opt, ',');
6763         virBufferAsprintf(&opt, "tls-port=%u", tlsPort);
6764     }
6765
6766     if (cfg->spiceSASL) {
6767         virBufferAddLit(&opt, ",sasl");
6768
6769         if (cfg->spiceSASLdir)
6770             virCommandAddEnvPair(cmd, "SASL_CONF_PATH",
6771                                  cfg->spiceSASLdir);
6772
6773         /* TODO: Support ACLs later */
6774     }
6775
6776     switch (virDomainGraphicsListenGetType(graphics, 0)) {
6777     case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS:
6778         listenAddr = virDomainGraphicsListenGetAddress(graphics, 0);
6779         break;
6780
6781     case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK:
6782         listenNetwork = virDomainGraphicsListenGetNetwork(graphics, 0);
6783         if (!listenNetwork)
6784             break;
6785         ret = networkGetNetworkAddress(listenNetwork, &netAddr);
6786         if (ret <= -2) {
6787             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6788                            "%s", _("network-based listen not possible, "
6789                                    "network driver not present"));
6790             goto error;
6791         }
6792         if (ret < 0) {
6793             virReportError(VIR_ERR_XML_ERROR,
6794                            _("listen network '%s' had no usable address"),
6795                            listenNetwork);
6796             goto error;
6797         }
6798         listenAddr = netAddr;
6799         /* store the address we found in the <graphics> element so it will
6800          * show up in status. */
6801         if (virDomainGraphicsListenSetAddress(graphics, 0,
6802                                               listenAddr, -1, false) < 0)
6803            goto error;
6804         break;
6805     }
6806
6807     if (!listenAddr)
6808         listenAddr = cfg->spiceListen;
6809     if (listenAddr)
6810         virBufferAsprintf(&opt, ",addr=%s", listenAddr);
6811
6812     VIR_FREE(netAddr);
6813
6814     if (graphics->data.spice.mousemode) {
6815         switch (graphics->data.spice.mousemode) {
6816         case VIR_DOMAIN_GRAPHICS_SPICE_MOUSE_MODE_SERVER:
6817             virBufferAddLit(&opt, ",agent-mouse=off");
6818             break;
6819         case VIR_DOMAIN_GRAPHICS_SPICE_MOUSE_MODE_CLIENT:
6820             virBufferAddLit(&opt, ",agent-mouse=on");
6821             break;
6822         default:
6823             break;
6824         }
6825     }
6826
6827     /* In the password case we set it via monitor command, to avoid
6828      * making it visible on CLI, so there's no use of password=XXX
6829      * in this bit of the code */
6830     if (!graphics->data.spice.auth.passwd &&
6831         !cfg->spicePassword)
6832         virBufferAddLit(&opt, ",disable-ticketing");
6833
6834     if (tlsPort > 0)
6835         virBufferAsprintf(&opt, ",x509-dir=%s", cfg->spiceTLSx509certdir);
6836
6837     switch (defaultMode) {
6838     case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_SECURE:
6839         virBufferAddLit(&opt, ",tls-channel=default");
6840         break;
6841     case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_INSECURE:
6842         virBufferAddLit(&opt, ",plaintext-channel=default");
6843         break;
6844     case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_ANY:
6845         /* nothing */
6846         break;
6847     }
6848
6849     for (i = 0; i < VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_LAST; i++) {
6850         switch (graphics->data.spice.channels[i]) {
6851         case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_SECURE:
6852             if (tlsPort <= 0) {
6853                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6854                                _("spice secure channels set in XML configuration, "
6855                                  "but TLS port is not provided"));
6856                 goto error;
6857             }
6858             virBufferAsprintf(&opt, ",tls-channel=%s",
6859                               virDomainGraphicsSpiceChannelNameTypeToString(i));
6860             break;
6861
6862         case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_INSECURE:
6863             if (port <= 0) {
6864                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6865                                _("spice insecure channels set in XML "
6866                                  "configuration, but plain port is not provided"));
6867                 goto error;
6868             }
6869             virBufferAsprintf(&opt, ",plaintext-channel=%s",
6870                               virDomainGraphicsSpiceChannelNameTypeToString(i));
6871             break;
6872
6873         case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_ANY:
6874             switch (defaultMode) {
6875             case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_SECURE:
6876                 if (tlsPort <= 0) {
6877                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6878                                    _("spice defaultMode secure requested in XML "
6879                                      "configuration but TLS port not provided"));
6880                     goto error;
6881                 }
6882                 break;
6883
6884             case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_INSECURE:
6885                 if (port <= 0) {
6886                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6887                                    _("spice defaultMode insecure requested in XML "
6888                                      "configuration but plain port not provided"));
6889                     goto error;
6890                 }
6891                 break;
6892
6893             case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_ANY:
6894                 /* don't care */
6895             break;
6896             }
6897         }
6898     }
6899
6900     if (graphics->data.spice.image)
6901         virBufferAsprintf(&opt, ",image-compression=%s",
6902                           virDomainGraphicsSpiceImageCompressionTypeToString(graphics->data.spice.image));
6903     if (graphics->data.spice.jpeg)
6904         virBufferAsprintf(&opt, ",jpeg-wan-compression=%s",
6905                           virDomainGraphicsSpiceJpegCompressionTypeToString(graphics->data.spice.jpeg));
6906     if (graphics->data.spice.zlib)
6907         virBufferAsprintf(&opt, ",zlib-glz-wan-compression=%s",
6908                           virDomainGraphicsSpiceZlibCompressionTypeToString(graphics->data.spice.zlib));
6909     if (graphics->data.spice.playback)
6910         virBufferAsprintf(&opt, ",playback-compression=%s",
6911                           virDomainGraphicsSpicePlaybackCompressionTypeToString(graphics->data.spice.playback));
6912     if (graphics->data.spice.streaming)
6913         virBufferAsprintf(&opt, ",streaming-video=%s",
6914                           virDomainGraphicsSpiceStreamingModeTypeToString(graphics->data.spice.streaming));
6915     if (graphics->data.spice.copypaste == VIR_DOMAIN_GRAPHICS_SPICE_CLIPBOARD_COPYPASTE_NO)
6916         virBufferAddLit(&opt, ",disable-copy-paste");
6917     if (graphics->data.spice.filetransfer == VIR_DOMAIN_GRAPHICS_SPICE_AGENT_FILE_TRANSFER_NO) {
6918         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SPICE_FILE_XFER_DISABLE)) {
6919            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6920                           _("This QEMU can't disable file transfers through spice"));
6921             goto error;
6922         } else {
6923             virBufferAddLit(&opt, ",disable-agent-file-xfer");
6924         }
6925     }
6926
6927     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_SEAMLESS_MIGRATION)) {
6928         /* If qemu supports seamless migration turn it
6929          * unconditionally on. If migration destination
6930          * doesn't support it, it fallbacks to previous
6931          * migration algorithm silently. */
6932         virBufferAddLit(&opt, ",seamless-migration=on");
6933     }
6934
6935     virCommandAddArg(cmd, "-spice");
6936     virCommandAddArgBuffer(cmd, &opt);
6937     if (graphics->data.spice.keymap)
6938         virCommandAddArgList(cmd, "-k",
6939                              graphics->data.spice.keymap, NULL);
6940     /* SPICE includes native support for tunnelling audio, so we
6941      * set the audio backend to point at SPICE's own driver
6942      */
6943     virCommandAddEnvString(cmd, "QEMU_AUDIO_DRV=spice");
6944
6945     return 0;
6946
6947  error:
6948     VIR_FREE(netAddr);
6949     virBufferFreeAndReset(&opt);
6950     return -1;
6951 }
6952
6953 static int
6954 qemuBuildGraphicsCommandLine(virQEMUDriverConfigPtr cfg,
6955                              virCommandPtr cmd,
6956                              virDomainDefPtr def,
6957                              virQEMUCapsPtr qemuCaps,
6958                              virDomainGraphicsDefPtr graphics)
6959 {
6960     switch ((enum virDomainGraphicsType) graphics->type) {
6961     case VIR_DOMAIN_GRAPHICS_TYPE_SDL:
6962         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_0_10) &&
6963             !virQEMUCapsGet(qemuCaps, QEMU_CAPS_SDL)) {
6964             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6965                            _("sdl not supported by '%s'"), def->emulator);
6966             return -1;
6967         }
6968
6969         if (graphics->data.sdl.xauth)
6970             virCommandAddEnvPair(cmd, "XAUTHORITY", graphics->data.sdl.xauth);
6971         if (graphics->data.sdl.display)
6972             virCommandAddEnvPair(cmd, "DISPLAY", graphics->data.sdl.display);
6973         if (graphics->data.sdl.fullscreen)
6974             virCommandAddArg(cmd, "-full-screen");
6975
6976         /* If using SDL for video, then we should just let it
6977          * use QEMU's host audio drivers, possibly SDL too
6978          * User can set these two before starting libvirtd
6979          */
6980         virCommandAddEnvPassBlockSUID(cmd, "QEMU_AUDIO_DRV", NULL);
6981         virCommandAddEnvPassBlockSUID(cmd, "SDL_AUDIODRIVER", NULL);
6982
6983         /* New QEMU has this flag to let us explicitly ask for
6984          * SDL graphics. This is better than relying on the
6985          * default, since the default changes :-( */
6986         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_SDL))
6987             virCommandAddArg(cmd, "-sdl");
6988
6989         break;
6990
6991     case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
6992         return qemuBuildGraphicsVNCCommandLine(cfg, cmd, def, qemuCaps, graphics);
6993
6994     case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
6995         return qemuBuildGraphicsSPICECommandLine(cfg, cmd, qemuCaps, graphics);
6996
6997     case VIR_DOMAIN_GRAPHICS_TYPE_RDP:
6998     case VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP:
6999     case VIR_DOMAIN_GRAPHICS_TYPE_LAST:
7000         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7001                        _("unsupported graphics type '%s'"),
7002                        virDomainGraphicsTypeToString(graphics->type));
7003         return -1;
7004     }
7005
7006     return 0;
7007 }
7008
7009 static int
7010 qemuBuildInterfaceCommandLine(virCommandPtr cmd,
7011                               virQEMUDriverPtr driver,
7012                               virConnectPtr conn,
7013                               virDomainDefPtr def,
7014                               virDomainNetDefPtr net,
7015                               virQEMUCapsPtr qemuCaps,
7016                               int vlan,
7017                               int bootindex,
7018                               virNetDevVPortProfileOp vmop,
7019                               bool standalone)
7020 {
7021     int ret = -1;
7022     char *nic = NULL, *host = NULL;
7023     int *tapfd = NULL;
7024     int tapfdSize = 0;
7025     int *vhostfd = NULL;
7026     int vhostfdSize = 0;
7027     char **tapfdName = NULL;
7028     char **vhostfdName = NULL;
7029     int actualType = virDomainNetGetActualType(net);
7030     size_t i;
7031
7032     if (actualType == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
7033         /* NET_TYPE_HOSTDEV devices are really hostdev devices, so
7034          * their commandlines are constructed with other hostdevs.
7035          */
7036         return 0;
7037     }
7038
7039     if (!bootindex)
7040         bootindex = net->info.bootIndex;
7041
7042     /* Currently nothing besides TAP devices supports multiqueue. */
7043     if (net->driver.virtio.queues > 0 &&
7044         !(actualType == VIR_DOMAIN_NET_TYPE_NETWORK ||
7045           actualType == VIR_DOMAIN_NET_TYPE_BRIDGE)) {
7046         virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7047                        _("Multiqueue network is not supported for: %s"),
7048                        virDomainNetTypeToString(actualType));
7049         return -1;
7050     }
7051
7052     if (actualType == VIR_DOMAIN_NET_TYPE_NETWORK ||
7053         actualType == VIR_DOMAIN_NET_TYPE_BRIDGE) {
7054         tapfdSize = net->driver.virtio.queues;
7055         if (!tapfdSize)
7056             tapfdSize = 1;
7057
7058         if (VIR_ALLOC_N(tapfd, tapfdSize) < 0 ||
7059             VIR_ALLOC_N(tapfdName, tapfdSize) < 0)
7060             goto cleanup;
7061
7062         memset(tapfd, -1, tapfdSize * sizeof(tapfd[0]));
7063
7064         if (qemuNetworkIfaceConnect(def, conn, driver, net,
7065                                     qemuCaps, tapfd, &tapfdSize) < 0)
7066             goto cleanup;
7067     } else if (actualType == VIR_DOMAIN_NET_TYPE_DIRECT) {
7068         if (VIR_ALLOC(tapfd) < 0 || VIR_ALLOC(tapfdName) < 0)
7069             goto cleanup;
7070         tapfdSize = 1;
7071         tapfd[0] = qemuPhysIfaceConnect(def, driver, net,
7072                                         qemuCaps, vmop);
7073         if (tapfd[0] < 0)
7074             goto cleanup;
7075     }
7076
7077     if ((actualType == VIR_DOMAIN_NET_TYPE_NETWORK ||
7078          actualType == VIR_DOMAIN_NET_TYPE_BRIDGE ||
7079          actualType == VIR_DOMAIN_NET_TYPE_ETHERNET ||
7080          actualType == VIR_DOMAIN_NET_TYPE_DIRECT) &&
7081         !standalone) {
7082         /* Attempt to use vhost-net mode for these types of
7083            network device */
7084         vhostfdSize = net->driver.virtio.queues;
7085         if (!vhostfdSize)
7086             vhostfdSize = 1;
7087
7088         if (VIR_ALLOC_N(vhostfd, vhostfdSize) < 0 ||
7089             VIR_ALLOC_N(vhostfdName, vhostfdSize))
7090             goto cleanup;
7091
7092         memset(vhostfd, -1, vhostfdSize * sizeof(vhostfd[0]));
7093
7094         if (qemuOpenVhostNet(def, net, qemuCaps, vhostfd, &vhostfdSize) < 0)
7095             goto cleanup;
7096     }
7097
7098     for (i = 0; i < tapfdSize; i++) {
7099         virCommandPassFD(cmd, tapfd[i],
7100                          VIR_COMMAND_PASS_FD_CLOSE_PARENT);
7101         if (virAsprintf(&tapfdName[i], "%d", tapfd[i]) < 0)
7102             goto cleanup;
7103     }
7104
7105     for (i = 0; i < vhostfdSize; i++) {
7106         virCommandPassFD(cmd, vhostfd[i],
7107                          VIR_COMMAND_PASS_FD_CLOSE_PARENT);
7108         if (virAsprintf(&vhostfdName[i], "%d", vhostfd[i]) < 0)
7109             goto cleanup;
7110     }
7111
7112     /* Possible combinations:
7113      *
7114      *  1. Old way:   -net nic,model=e1000,vlan=1 -net tap,vlan=1
7115      *  2. Semi-new:  -device e1000,vlan=1        -net tap,vlan=1
7116      *  3. Best way:  -netdev type=tap,id=netdev1 -device e1000,id=netdev1
7117      *
7118      * NB, no support for -netdev without use of -device
7119      */
7120     if (qemuDomainSupportsNetdev(def, qemuCaps, net)) {
7121         if (!(host = qemuBuildHostNetStr(net, driver,
7122                                          ',', vlan,
7123                                          tapfdName, tapfdSize,
7124                                          vhostfdName, vhostfdSize)))
7125             goto cleanup;
7126         virCommandAddArgList(cmd, "-netdev", host, NULL);
7127     }
7128     if (qemuDomainSupportsNicdev(def, qemuCaps, net)) {
7129         if (!(nic = qemuBuildNicDevStr(def, net, vlan, bootindex,
7130                                        vhostfdSize, qemuCaps)))
7131             goto cleanup;
7132         virCommandAddArgList(cmd, "-device", nic, NULL);
7133     } else {
7134         if (!(nic = qemuBuildNicStr(net, "nic,", vlan)))
7135             goto cleanup;
7136         virCommandAddArgList(cmd, "-net", nic, NULL);
7137     }
7138     if (!qemuDomainSupportsNetdev(def, qemuCaps, net)) {
7139         if (!(host = qemuBuildHostNetStr(net, driver,
7140                                          ',', vlan,
7141                                          tapfdName, tapfdSize,
7142                                          vhostfdName, vhostfdSize)))
7143             goto cleanup;
7144         virCommandAddArgList(cmd, "-net", host, NULL);
7145     }
7146
7147     ret = 0;
7148  cleanup:
7149     if (ret < 0) {
7150         virErrorPtr saved_err = virSaveLastError();
7151         virDomainConfNWFilterTeardown(net);
7152         virSetError(saved_err);
7153         virFreeError(saved_err);
7154     }
7155     for (i = 0; tapfd && i < tapfdSize && tapfd[i] >= 0; i++) {
7156         if (ret < 0)
7157             VIR_FORCE_CLOSE(tapfd[i]);
7158         if (tapfdName)
7159             VIR_FREE(tapfdName[i]);
7160     }
7161     for (i = 0; vhostfd && i < vhostfdSize && vhostfd[i] >= 0; i++) {
7162         if (ret < 0)
7163             VIR_FORCE_CLOSE(vhostfd[i]);
7164         if (vhostfdName)
7165             VIR_FREE(vhostfdName[i]);
7166     }
7167     VIR_FREE(tapfd);
7168     VIR_FREE(vhostfd);
7169     VIR_FREE(nic);
7170     VIR_FREE(host);
7171     VIR_FREE(tapfdName);
7172     VIR_FREE(vhostfdName);
7173     return ret;
7174 }
7175
7176 static int
7177 qemuBuildChrDeviceCommandLine(virCommandPtr cmd,
7178                               virDomainDefPtr def,
7179                               virDomainChrDefPtr chr,
7180                               virQEMUCapsPtr qemuCaps)
7181 {
7182     char *devstr = NULL;
7183
7184     if (qemuBuildChrDeviceStr(&devstr, def, chr, qemuCaps) < 0)
7185         return -1;
7186
7187     virCommandAddArgList(cmd, "-device", devstr, NULL);
7188     VIR_FREE(devstr);
7189     return 0;
7190 }
7191
7192 qemuBuildCommandLineCallbacks buildCommandLineCallbacks = {
7193     .qemuGetSCSIDeviceSgName = virSCSIDeviceGetSgName,
7194 };
7195
7196 /*
7197  * Constructs a argv suitable for launching qemu with config defined
7198  * for a given virtual machine.
7199  *
7200  * XXX 'conn' is only required to resolve network -> bridge name
7201  * figure out how to remove this requirement some day
7202  */
7203 virCommandPtr
7204 qemuBuildCommandLine(virConnectPtr conn,
7205                      virQEMUDriverPtr driver,
7206                      virDomainDefPtr def,
7207                      virDomainChrSourceDefPtr monitor_chr,
7208                      bool monitor_json,
7209                      virQEMUCapsPtr qemuCaps,
7210                      const char *migrateFrom,
7211                      int migrateFd,
7212                      virDomainSnapshotObjPtr snapshot,
7213                      virNetDevVPortProfileOp vmop,
7214                      qemuBuildCommandLineCallbacksPtr callbacks,
7215                      bool standalone)
7216 {
7217     virErrorPtr originalError = NULL;
7218     size_t i, j;
7219     const char *emulator;
7220     char uuid[VIR_UUID_STRING_BUFLEN];
7221     char *cpu;
7222     char *smp;
7223     int last_good_net = -1;
7224     bool hasHwVirt = false;
7225     virCommandPtr cmd = NULL;
7226     bool allowReboot = true;
7227     bool emitBootindex = false;
7228     int sdl = 0;
7229     int vnc = 0;
7230     int spice = 0;
7231     int usbcontroller = 0;
7232     int actualSerials = 0;
7233     bool usblegacy = false;
7234     bool mlock = false;
7235     int contOrder[] = {
7236         /* We don't add an explicit IDE or FD controller because the
7237          * provided PIIX4 device already includes one. It isn't possible to
7238          * remove the PIIX4.
7239          *
7240          * We don't add PCI root controller either, because it's implicit,
7241          * but we do add PCI bridges. */
7242         VIR_DOMAIN_CONTROLLER_TYPE_PCI,
7243         VIR_DOMAIN_CONTROLLER_TYPE_USB,
7244         VIR_DOMAIN_CONTROLLER_TYPE_SCSI,
7245         VIR_DOMAIN_CONTROLLER_TYPE_SATA,
7246         VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL,
7247         VIR_DOMAIN_CONTROLLER_TYPE_CCID,
7248     };
7249     virArch hostarch = virArchFromHost();
7250     virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
7251
7252     VIR_DEBUG("conn=%p driver=%p def=%p mon=%p json=%d "
7253               "qemuCaps=%p migrateFrom=%s migrateFD=%d "
7254               "snapshot=%p vmop=%d",
7255               conn, driver, def, monitor_chr, monitor_json,
7256               qemuCaps, migrateFrom, migrateFd, snapshot, vmop);
7257
7258     virUUIDFormat(def->uuid, uuid);
7259
7260     emulator = def->emulator;
7261
7262     if (!cfg->privileged) {
7263         /* If we have no cgroups than we can have no tunings that
7264          * require them */
7265
7266         if (def->mem.hard_limit || def->mem.soft_limit ||
7267             def->mem.min_guarantee || def->mem.swap_hard_limit) {
7268             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7269                            _("Memory tuning is not available in session mode"));
7270             goto error;
7271         }
7272
7273         if (def->blkio.weight || def->blkio.ndevices) {
7274             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7275                            _("Block I/O tuning is not available in session mode"));
7276             goto error;
7277         }
7278
7279         if (def->cputune.sharesSpecified || def->cputune.period ||
7280             def->cputune.quota || def->cputune.emulator_period ||
7281             def->cputune.emulator_quota) {
7282             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7283                            _("CPU tuning is not available in session mode"));
7284             goto error;
7285         }
7286     }
7287
7288     for (i = 0; i < def->ngraphics; ++i) {
7289         switch (def->graphics[i]->type) {
7290         case VIR_DOMAIN_GRAPHICS_TYPE_SDL:
7291             ++sdl;
7292             break;
7293         case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
7294             ++vnc;
7295             break;
7296         case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
7297             ++spice;
7298             break;
7299         }
7300     }
7301
7302     /*
7303      * do not use boot=on for drives when not using KVM since this
7304      * is not supported at all in upstream QEmu.
7305      */
7306     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_KVM) &&
7307         (def->virtType == VIR_DOMAIN_VIRT_QEMU))
7308         virQEMUCapsClear(qemuCaps, QEMU_CAPS_DRIVE_BOOT);
7309
7310     cmd = virCommandNew(emulator);
7311
7312     virCommandAddEnvPassCommon(cmd);
7313
7314     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NAME)) {
7315         virCommandAddArg(cmd, "-name");
7316         if (cfg->setProcessName &&
7317             virQEMUCapsGet(qemuCaps, QEMU_CAPS_NAME_PROCESS)) {
7318             virCommandAddArgFormat(cmd, "%s,process=qemu:%s",
7319                                    def->name, def->name);
7320         } else {
7321             virCommandAddArg(cmd, def->name);
7322         }
7323     }
7324
7325     if (!standalone)
7326         virCommandAddArg(cmd, "-S"); /* freeze CPU */
7327
7328     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_ENABLE_FIPS))
7329         virCommandAddArg(cmd, "-enable-fips");
7330
7331     if (qemuBuildMachineArgStr(cmd, def, qemuCaps) < 0)
7332         goto error;
7333
7334     if (qemuBuildCpuArgStr(driver, def, emulator, qemuCaps,
7335                            hostarch, &cpu, &hasHwVirt, !!migrateFrom) < 0)
7336         goto error;
7337
7338     if (cpu) {
7339         virCommandAddArgList(cmd, "-cpu", cpu, NULL);
7340         VIR_FREE(cpu);
7341
7342         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NESTING) &&
7343             hasHwVirt)
7344             virCommandAddArg(cmd, "-enable-nesting");
7345     }
7346
7347     if (def->os.loader) {
7348         virCommandAddArg(cmd, "-bios");
7349         virCommandAddArg(cmd, def->os.loader);
7350     }
7351
7352     /* Set '-m MB' based on maxmem, because the lower 'memory' limit
7353      * is set post-startup using the balloon driver. If balloon driver
7354      * is not supported, then they're out of luck anyway.  Update the
7355      * XML to reflect our rounding.
7356      */
7357     virCommandAddArg(cmd, "-m");
7358     def->mem.max_balloon = VIR_DIV_UP(def->mem.max_balloon, 1024) * 1024;
7359     virCommandAddArgFormat(cmd, "%llu", def->mem.max_balloon / 1024);
7360     if (def->mem.hugepage_backed) {
7361         if (!cfg->hugetlbfsMount) {
7362             virReportError(VIR_ERR_INTERNAL_ERROR,
7363                            "%s", _("hugetlbfs filesystem is not mounted"));
7364             goto error;
7365         }
7366         if (!cfg->hugepagePath) {
7367             virReportError(VIR_ERR_INTERNAL_ERROR,
7368                            "%s", _("hugepages are disabled by administrator config"));
7369             goto error;
7370         }
7371         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MEM_PATH)) {
7372             virReportError(VIR_ERR_INTERNAL_ERROR,
7373                            _("hugepage backing not supported by '%s'"),
7374                            def->emulator);
7375             goto error;
7376         }
7377         virCommandAddArgList(cmd, "-mem-prealloc", "-mem-path",
7378                              cfg->hugepagePath, NULL);
7379     }
7380
7381     if (def->mem.locked && !virQEMUCapsGet(qemuCaps, QEMU_CAPS_MLOCK)) {
7382         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7383                        _("memory locking not supported by QEMU binary"));
7384         goto error;
7385     }
7386     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_MLOCK)) {
7387         virCommandAddArg(cmd, "-realtime");
7388         virCommandAddArgFormat(cmd, "mlock=%s",
7389                                def->mem.locked ? "on" : "off");
7390     }
7391     mlock = def->mem.locked;
7392
7393     virCommandAddArg(cmd, "-smp");
7394     if (!(smp = qemuBuildSmpArgStr(def, qemuCaps)))
7395         goto error;
7396     virCommandAddArg(cmd, smp);
7397     VIR_FREE(smp);
7398
7399     if (def->cpu && def->cpu->ncells)
7400         if (qemuBuildNumaArgStr(def, cmd) < 0)
7401             goto error;
7402
7403     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_UUID))
7404         virCommandAddArgList(cmd, "-uuid", uuid, NULL);
7405     if (def->virtType == VIR_DOMAIN_VIRT_XEN ||
7406         STREQ(def->os.type, "xen") ||
7407         STREQ(def->os.type, "linux")) {
7408         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DOMID)) {
7409             virCommandAddArg(cmd, "-domid");
7410             virCommandAddArgFormat(cmd, "%d", def->id);
7411         } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_XEN_DOMID)) {
7412             virCommandAddArg(cmd, "-xen-attach");
7413             virCommandAddArg(cmd, "-xen-domid");
7414             virCommandAddArgFormat(cmd, "%d", def->id);
7415         } else {
7416             virReportError(VIR_ERR_INTERNAL_ERROR,
7417                            _("qemu emulator '%s' does not support xen"),
7418                            def->emulator);
7419             goto error;
7420         }
7421     }
7422
7423     if ((def->os.smbios_mode != VIR_DOMAIN_SMBIOS_NONE) &&
7424         (def->os.smbios_mode != VIR_DOMAIN_SMBIOS_EMULATE)) {
7425         virSysinfoDefPtr source = NULL;
7426         bool skip_uuid = false;
7427
7428         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SMBIOS_TYPE)) {
7429             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7430                            _("the QEMU binary %s does not support smbios settings"),
7431                            emulator);
7432             goto error;
7433         }
7434
7435         /* should we really error out or just warn in those cases ? */
7436         if (def->os.smbios_mode == VIR_DOMAIN_SMBIOS_HOST) {
7437             if (driver->hostsysinfo == NULL) {
7438                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7439                                _("Host SMBIOS information is not available"));
7440                 goto error;
7441             }
7442             source = driver->hostsysinfo;
7443             /* Host and guest uuid must differ, by definition of UUID. */
7444             skip_uuid = true;
7445         } else if (def->os.smbios_mode == VIR_DOMAIN_SMBIOS_SYSINFO) {
7446             if (def->sysinfo == NULL) {
7447                 virReportError(VIR_ERR_XML_ERROR,
7448                                _("Domain '%s' sysinfo are not available"),
7449                                def->name);
7450                 goto error;
7451             }
7452             source = def->sysinfo;
7453             /* domain_conf guaranteed that system_uuid matches guest uuid. */
7454         }
7455         if (source != NULL) {
7456             char *smbioscmd;
7457
7458             smbioscmd = qemuBuildSmbiosBiosStr(source);
7459             if (smbioscmd != NULL) {
7460                 virCommandAddArgList(cmd, "-smbios", smbioscmd, NULL);
7461                 VIR_FREE(smbioscmd);
7462             }
7463             smbioscmd = qemuBuildSmbiosSystemStr(source, skip_uuid);
7464             if (smbioscmd != NULL) {
7465                 virCommandAddArgList(cmd, "-smbios", smbioscmd, NULL);
7466                 VIR_FREE(smbioscmd);
7467             }
7468         }
7469     }
7470
7471     /*
7472      * NB, -nographic *MUST* come before any serial, or monitor
7473      * or parallel port flags due to QEMU craziness, where it
7474      * decides to change the serial port & monitor to be on stdout
7475      * if you ask for nographic. So we have to make sure we override
7476      * these defaults ourselves...
7477      */
7478     if (!def->graphics) {
7479         virCommandAddArg(cmd, "-nographic");
7480
7481         if (cfg->nogfxAllowHostAudio)
7482             virCommandAddEnvPassBlockSUID(cmd, "QEMU_AUDIO_DRV", NULL);
7483         else
7484             virCommandAddEnvString(cmd, "QEMU_AUDIO_DRV=none");
7485     }
7486
7487     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
7488         /* Disable global config files and default devices */
7489         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NO_USER_CONFIG))
7490             virCommandAddArg(cmd, "-no-user-config");
7491         else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NODEFCONFIG))
7492             virCommandAddArg(cmd, "-nodefconfig");
7493         virCommandAddArg(cmd, "-nodefaults");
7494     }
7495
7496     /* Serial graphics adapter */
7497     if (def->os.bios.useserial == VIR_DOMAIN_BIOS_USESERIAL_YES) {
7498         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
7499             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
7500                            _("qemu does not support -device"));
7501             goto error;
7502         }
7503         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SGA)) {
7504             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
7505                            _("qemu does not support SGA"));
7506             goto error;
7507         }
7508         if (!def->nserials) {
7509             virReportError(VIR_ERR_XML_ERROR, "%s",
7510                            _("need at least one serial port to use SGA"));
7511             goto error;
7512         }
7513         virCommandAddArgList(cmd, "-device", "sga", NULL);
7514     }
7515
7516     if (monitor_chr) {
7517         char *chrdev;
7518         /* Use -chardev if it's available */
7519         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_CHARDEV)) {
7520
7521             virCommandAddArg(cmd, "-chardev");
7522             if (!(chrdev = qemuBuildChrChardevStr(monitor_chr, "monitor",
7523                                                   qemuCaps)))
7524                 goto error;
7525             virCommandAddArg(cmd, chrdev);
7526             VIR_FREE(chrdev);
7527
7528             virCommandAddArg(cmd, "-mon");
7529             virCommandAddArgFormat(cmd,
7530                                    "chardev=charmonitor,id=monitor,mode=%s",
7531                                    monitor_json ? "control" : "readline");
7532         } else {
7533             const char *prefix = NULL;
7534             if (monitor_json)
7535                 prefix = "control,";
7536
7537             virCommandAddArg(cmd, "-monitor");
7538             if (!(chrdev = qemuBuildChrArgStr(monitor_chr, prefix)))
7539                 goto error;
7540             virCommandAddArg(cmd, chrdev);
7541             VIR_FREE(chrdev);
7542         }
7543     }
7544
7545     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_RTC)) {
7546         char *rtcopt;
7547         virCommandAddArg(cmd, "-rtc");
7548         if (!(rtcopt = qemuBuildClockArgStr(&def->clock)))
7549             goto error;
7550         virCommandAddArg(cmd, rtcopt);
7551         VIR_FREE(rtcopt);
7552     } else {
7553         switch (def->clock.offset) {
7554         case VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME:
7555         case VIR_DOMAIN_CLOCK_OFFSET_TIMEZONE:
7556             virCommandAddArg(cmd, "-localtime");
7557             break;
7558
7559         case VIR_DOMAIN_CLOCK_OFFSET_UTC:
7560             /* Nothing, its the default */
7561             break;
7562
7563         default:
7564             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7565                            _("unsupported clock offset '%s'"),
7566                            virDomainClockOffsetTypeToString(def->clock.offset));
7567             goto error;
7568         }
7569     }
7570     if (def->clock.offset == VIR_DOMAIN_CLOCK_OFFSET_TIMEZONE &&
7571         def->clock.data.timezone) {
7572         virCommandAddEnvPair(cmd, "TZ", def->clock.data.timezone);
7573     }
7574
7575     for (i = 0; i < def->clock.ntimers; i++) {
7576         switch ((enum virDomainTimerNameType) def->clock.timers[i]->name) {
7577         case VIR_DOMAIN_TIMER_NAME_PLATFORM:
7578         case VIR_DOMAIN_TIMER_NAME_TSC:
7579             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7580                            _("unsupported timer type (name) '%s'"),
7581                            virDomainTimerNameTypeToString(def->clock.timers[i]->name));
7582             goto error;
7583
7584         case VIR_DOMAIN_TIMER_NAME_KVMCLOCK:
7585         case VIR_DOMAIN_TIMER_NAME_HYPERVCLOCK:
7586             /* Timers above are handled when building -cpu.  */
7587         case VIR_DOMAIN_TIMER_NAME_LAST:
7588             break;
7589
7590         case VIR_DOMAIN_TIMER_NAME_RTC:
7591             /* This has already been taken care of (in qemuBuildClockArgStr)
7592                if QEMU_CAPS_RTC is set (mutually exclusive with
7593                QEMUD_FLAG_RTC_TD_HACK) */
7594             if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_RTC_TD_HACK)) {
7595                 switch (def->clock.timers[i]->tickpolicy) {
7596                 case -1:
7597                 case VIR_DOMAIN_TIMER_TICKPOLICY_DELAY:
7598                     /* the default - do nothing */
7599                     break;
7600                 case VIR_DOMAIN_TIMER_TICKPOLICY_CATCHUP:
7601                     virCommandAddArg(cmd, "-rtc-td-hack");
7602                     break;
7603                 case VIR_DOMAIN_TIMER_TICKPOLICY_MERGE:
7604                 case VIR_DOMAIN_TIMER_TICKPOLICY_DISCARD:
7605                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7606                                    _("unsupported rtc tickpolicy '%s'"),
7607                                    virDomainTimerTickpolicyTypeToString(def->clock.timers[i]->tickpolicy));
7608                     goto error;
7609                 }
7610             } else if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_RTC)
7611                        && (def->clock.timers[i]->tickpolicy
7612                            != VIR_DOMAIN_TIMER_TICKPOLICY_DELAY)
7613                        && (def->clock.timers[i]->tickpolicy != -1)) {
7614                 /* a non-default rtc policy was given, but there is no
7615                    way to implement it in this version of qemu */
7616                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7617                                _("unsupported rtc tickpolicy '%s'"),
7618                                virDomainTimerTickpolicyTypeToString(def->clock.timers[i]->tickpolicy));
7619                 goto error;
7620             }
7621             break;
7622
7623         case VIR_DOMAIN_TIMER_NAME_PIT:
7624             switch (def->clock.timers[i]->tickpolicy) {
7625             case -1:
7626             case VIR_DOMAIN_TIMER_TICKPOLICY_DELAY:
7627                 /* delay is the default if we don't have kernel
7628                    (-no-kvm-pit), otherwise, the default is catchup. */
7629                 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_KVM_PIT_TICK_POLICY))
7630                     virCommandAddArgList(cmd, "-global",
7631                                          "kvm-pit.lost_tick_policy=discard", NULL);
7632                 else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NO_KVM_PIT))
7633                     virCommandAddArg(cmd, "-no-kvm-pit-reinjection");
7634                 break;
7635             case VIR_DOMAIN_TIMER_TICKPOLICY_CATCHUP:
7636                 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NO_KVM_PIT) ||
7637                     virQEMUCapsGet(qemuCaps, QEMU_CAPS_KVM_PIT_TICK_POLICY)) {
7638                     /* do nothing - this is default for kvm-pit */
7639                 } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_TDF)) {
7640                     /* -tdf switches to 'catchup' with userspace pit. */
7641                     virCommandAddArg(cmd, "-tdf");
7642                 } else {
7643                     /* can't catchup if we have neither pit mode */
7644                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7645                                    _("unsupported pit tickpolicy '%s'"),
7646                                    virDomainTimerTickpolicyTypeToString(def->clock.timers[i]->tickpolicy));
7647                     goto error;
7648                 }
7649                 break;
7650             case VIR_DOMAIN_TIMER_TICKPOLICY_MERGE:
7651             case VIR_DOMAIN_TIMER_TICKPOLICY_DISCARD:
7652                 /* no way to support these modes for pit in qemu */
7653                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7654                                _("unsupported pit tickpolicy '%s'"),
7655                                virDomainTimerTickpolicyTypeToString(def->clock.timers[i]->tickpolicy));
7656                 goto error;
7657             }
7658             break;
7659
7660         case VIR_DOMAIN_TIMER_NAME_HPET:
7661             /* the only meaningful attribute for hpet is "present". If
7662              * present is -1, that means it wasn't specified, and
7663              * should be left at the default for the
7664              * hypervisor. "default" when -no-hpet exists is "yes",
7665              * and when -no-hpet doesn't exist is "no". "confusing"?
7666              * "yes"! */
7667
7668             if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NO_HPET)) {
7669                 if (def->clock.timers[i]->present == 0)
7670                     virCommandAddArg(cmd, "-no-hpet");
7671             } else {
7672                 /* no hpet timer available. The only possible action
7673                    is to raise an error if present="yes" */
7674                 if (def->clock.timers[i]->present == 1) {
7675                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7676                                    "%s", _("hpet timer is not supported"));
7677                     goto error;
7678                 }
7679             }
7680             break;
7681         }
7682     }
7683
7684     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NO_REBOOT)) {
7685         /* Only add -no-reboot option if each event destroys domain */
7686         if (def->onReboot == VIR_DOMAIN_LIFECYCLE_DESTROY &&
7687             def->onPoweroff == VIR_DOMAIN_LIFECYCLE_DESTROY &&
7688             def->onCrash == VIR_DOMAIN_LIFECYCLE_DESTROY) {
7689             allowReboot = false;
7690             virCommandAddArg(cmd, "-no-reboot");
7691         }
7692     }
7693
7694     /* If JSON monitor is enabled, we can receive an event
7695      * when QEMU stops. If we use no-shutdown, then we can
7696      * watch for this event and do a soft/warm reboot.
7697      */
7698     if (monitor_json && allowReboot &&
7699         virQEMUCapsGet(qemuCaps, QEMU_CAPS_NO_SHUTDOWN)) {
7700         virCommandAddArg(cmd, "-no-shutdown");
7701     }
7702
7703     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_NO_ACPI)) {
7704         if (def->features[VIR_DOMAIN_FEATURE_ACPI] != VIR_DOMAIN_FEATURE_STATE_ON)
7705             virCommandAddArg(cmd, "-no-acpi");
7706     }
7707
7708     if (def->pm.s3) {
7709         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DISABLE_S3)) {
7710             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7711                            "%s", _("setting ACPI S3 not supported"));
7712             goto error;
7713         }
7714         virCommandAddArg(cmd, "-global");
7715         virCommandAddArgFormat(cmd, "PIIX4_PM.disable_s3=%d",
7716                                def->pm.s3 == VIR_DOMAIN_PM_STATE_DISABLED);
7717     }
7718
7719     if (def->pm.s4) {
7720         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DISABLE_S4)) {
7721             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7722                            "%s", _("setting ACPI S4 not supported"));
7723             goto error;
7724         }
7725         virCommandAddArg(cmd, "-global");
7726         virCommandAddArgFormat(cmd, "PIIX4_PM.disable_s4=%d",
7727                                def->pm.s4 == VIR_DOMAIN_PM_STATE_DISABLED);
7728     }
7729
7730     if (!def->os.bootloader) {
7731         int boot_nparams = 0;
7732         virBuffer boot_buf = VIR_BUFFER_INITIALIZER;
7733         /*
7734          * We prefer using explicit bootindex=N parameters for predictable
7735          * results even though domain XML doesn't use per device boot elements.
7736          * However, we can't use bootindex if boot menu was requested.
7737          */
7738         if (!def->os.nBootDevs) {
7739             /* def->os.nBootDevs is guaranteed to be > 0 unless per-device boot
7740              * configuration is used
7741              */
7742             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_BOOTINDEX)) {
7743                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7744                                _("hypervisor lacks deviceboot feature"));
7745                 goto error;
7746             }
7747             emitBootindex = true;
7748         } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_BOOTINDEX) &&
7749                    (def->os.bootmenu != VIR_DOMAIN_BOOT_MENU_ENABLED ||
7750                     !virQEMUCapsGet(qemuCaps, QEMU_CAPS_BOOT_MENU))) {
7751             emitBootindex = true;
7752         }
7753
7754         if (!emitBootindex) {
7755             char boot[VIR_DOMAIN_BOOT_LAST+1];
7756
7757             for (i = 0; i < def->os.nBootDevs; i++) {
7758                 switch (def->os.bootDevs[i]) {
7759                 case VIR_DOMAIN_BOOT_CDROM:
7760                     boot[i] = 'd';
7761                     break;
7762                 case VIR_DOMAIN_BOOT_FLOPPY:
7763                     boot[i] = 'a';
7764                     break;
7765                 case VIR_DOMAIN_BOOT_DISK:
7766                     boot[i] = 'c';
7767                     break;
7768                 case VIR_DOMAIN_BOOT_NET:
7769                     boot[i] = 'n';
7770                     break;
7771                 default:
7772                     boot[i] = 'c';
7773                     break;
7774                 }
7775             }
7776             boot[def->os.nBootDevs] = '\0';
7777
7778             virBufferAsprintf(&boot_buf, "%s", boot);
7779             boot_nparams++;
7780         }
7781
7782         if (def->os.bootmenu) {
7783             if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_BOOT_MENU)) {
7784                 if (boot_nparams++)
7785                     virBufferAddChar(&boot_buf, ',');
7786
7787                 if (def->os.bootmenu == VIR_DOMAIN_BOOT_MENU_ENABLED)
7788                     virBufferAddLit(&boot_buf, "menu=on");
7789                 else
7790                     virBufferAddLit(&boot_buf, "menu=off");
7791             } else {
7792                 /* We cannot emit an error when bootmenu is enabled but
7793                  * unsupported because of backward compatibility */
7794                 VIR_WARN("bootmenu is enabled but not "
7795                          "supported by this QEMU binary");
7796             }
7797         }
7798
7799         if (def->os.bios.rt_set) {
7800             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_REBOOT_TIMEOUT)) {
7801                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7802                                _("reboot timeout is not supported "
7803                                  "by this QEMU binary"));
7804                 virBufferFreeAndReset(&boot_buf);
7805                 goto error;
7806             }
7807
7808             if (boot_nparams++)
7809                 virBufferAddChar(&boot_buf, ',');
7810
7811             virBufferAsprintf(&boot_buf,
7812                               "reboot-timeout=%d",
7813                               def->os.bios.rt_delay);
7814         }
7815
7816         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_BOOT_STRICT)) {
7817             if (boot_nparams++)
7818                 virBufferAddChar(&boot_buf, ',');
7819             virBufferAddLit(&boot_buf, "strict=on");
7820         }
7821
7822         if (boot_nparams > 0) {
7823             virCommandAddArg(cmd, "-boot");
7824
7825             if (virBufferError(&boot_buf)) {
7826                 virReportOOMError();
7827                 goto error;
7828             }
7829
7830             if (boot_nparams < 2 || emitBootindex) {
7831                 virCommandAddArgBuffer(cmd, &boot_buf);
7832                 virBufferFreeAndReset(&boot_buf);
7833             } else {
7834                 char *str = virBufferContentAndReset(&boot_buf);
7835                 virCommandAddArgFormat(cmd,
7836                                        "order=%s",
7837                                        str);
7838                 VIR_FREE(str);
7839             }
7840         }
7841
7842         if (def->os.kernel)
7843             virCommandAddArgList(cmd, "-kernel", def->os.kernel, NULL);
7844         if (def->os.initrd)
7845             virCommandAddArgList(cmd, "-initrd", def->os.initrd, NULL);
7846         if (def->os.cmdline)
7847             virCommandAddArgList(cmd, "-append", def->os.cmdline, NULL);
7848         if (def->os.dtb) {
7849             if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DTB)) {
7850                 virCommandAddArgList(cmd, "-dtb", def->os.dtb, NULL);
7851             } else {
7852                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7853                                _("dtb is not supported with this QEMU binary"));
7854                 goto error;
7855             }
7856         }
7857     } else {
7858         virCommandAddArgList(cmd, "-bootloader", def->os.bootloader, NULL);
7859     }
7860
7861     for (i = 0; i < def->ncontrollers; i++) {
7862         virDomainControllerDefPtr cont = def->controllers[i];
7863         if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI &&
7864             cont->opts.pciopts.pcihole64) {
7865             const char *hoststr = NULL;
7866             bool cap = false;
7867             bool machine = false;
7868
7869             switch (cont->model) {
7870             case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
7871                 hoststr = "i440FX-pcihost";
7872                 cap = virQEMUCapsGet(qemuCaps, QEMU_CAPS_I440FX_PCI_HOLE64_SIZE);
7873                 machine = qemuDomainMachineIsI440FX(def);
7874                 break;
7875
7876             case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
7877                 hoststr = "q35-pcihost";
7878                 cap = virQEMUCapsGet(qemuCaps, QEMU_CAPS_Q35_PCI_HOLE64_SIZE);
7879                 machine = qemuDomainMachineIsQ35(def);
7880                 break;
7881
7882             default:
7883                 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
7884                                _("64-bit PCI hole setting is only for root"
7885                                  " PCI controllers"));
7886                 goto error;
7887             }
7888
7889             if (!machine) {
7890                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7891                              _("Setting the 64-bit PCI hole size is not "
7892                              "supported for machine '%s'"), def->os.machine);
7893                 goto error;
7894             }
7895             if (!cap) {
7896                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7897                                _("64-bit PCI hole size setting is not supported "
7898                                  "with this QEMU binary"));
7899                 goto error;
7900             }
7901
7902             virCommandAddArg(cmd, "-global");
7903             virCommandAddArgFormat(cmd, "%s.pci-hole64-size=%luK", hoststr,
7904                                    cont->opts.pciopts.pcihole64size);
7905         }
7906     }
7907
7908     for (i = 0; i < def->ndisks; i++) {
7909         virDomainDiskDefPtr disk = def->disks[i];
7910
7911         if (disk->src.driverName != NULL &&
7912             !STREQ(disk->src.driverName, "qemu")) {
7913             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7914                            _("unsupported driver name '%s' for disk '%s'"),
7915                            disk->src.driverName, disk->src.path);
7916             goto error;
7917         }
7918     }
7919
7920     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
7921         for (j = 0; j < ARRAY_CARDINALITY(contOrder); j++) {
7922             for (i = 0; i < def->ncontrollers; i++) {
7923                 virDomainControllerDefPtr cont = def->controllers[i];
7924
7925                 if (cont->type != contOrder[j])
7926                     continue;
7927
7928                 /* Also, skip USB controllers with type none.*/
7929                 if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
7930                     cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE) {
7931                     usbcontroller = -1; /* mark we don't want a controller */
7932                     continue;
7933                 }
7934
7935                 /* Skip pci-root/pcie-root */
7936                 if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI &&
7937                     (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT ||
7938                      cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT)) {
7939                     continue;
7940                 }
7941
7942                 /* Only recent QEMU implements a SATA (AHCI) controller */
7943                 if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_SATA) {
7944                     if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_ICH9_AHCI)) {
7945                         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7946                                        _("SATA is not supported with this "
7947                                          "QEMU binary"));
7948                         goto error;
7949                     } else if (cont->idx == 0 && qemuDomainMachineIsQ35(def)) {
7950                         /* first SATA controller on Q35 machines is implicit */
7951                         continue;
7952                     } else {
7953                         char *devstr;
7954
7955                         virCommandAddArg(cmd, "-device");
7956                         if (!(devstr = qemuBuildControllerDevStr(def, cont,
7957                                                                  qemuCaps, NULL)))
7958                             goto error;
7959
7960                         virCommandAddArg(cmd, devstr);
7961                         VIR_FREE(devstr);
7962                     }
7963                 } else if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
7964                            cont->model == -1 &&
7965                            !qemuDomainMachineIsQ35(def) &&
7966                            (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_PIIX3_USB_UHCI) ||
7967                             (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_PCI_OHCI) &&
7968                              def->os.arch == VIR_ARCH_PPC64))) {
7969                     if (usblegacy) {
7970                         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7971                                        _("Multiple legacy USB controllers are "
7972                                          "not supported"));
7973                         goto error;
7974                     }
7975                     usblegacy = true;
7976                 } else {
7977                     virCommandAddArg(cmd, "-device");
7978
7979                     char *devstr;
7980                     if (!(devstr = qemuBuildControllerDevStr(def, cont, qemuCaps,
7981                                                              &usbcontroller)))
7982                         goto error;
7983
7984                     virCommandAddArg(cmd, devstr);
7985                     VIR_FREE(devstr);
7986                 }
7987             }
7988         }
7989     }
7990
7991     if (usbcontroller == 0 && !qemuDomainMachineIsQ35(def))
7992         virCommandAddArg(cmd, "-usb");
7993
7994     for (i = 0; i < def->nhubs; i++) {
7995         virDomainHubDefPtr hub = def->hubs[i];
7996         char *optstr;
7997
7998         virCommandAddArg(cmd, "-device");
7999         if (!(optstr = qemuBuildHubDevStr(def, hub, qemuCaps)))
8000             goto error;
8001         virCommandAddArg(cmd, optstr);
8002         VIR_FREE(optstr);
8003     }
8004
8005     /* If QEMU supports -drive param instead of old -hda, -hdb, -cdrom .. */
8006     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE)) {
8007         int bootCD = 0, bootFloppy = 0, bootDisk = 0;
8008
8009         if ((virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE_BOOT) || emitBootindex)) {
8010             /* bootDevs will get translated into either bootindex=N or boot=on
8011              * depending on what qemu supports */
8012             for (i = 0; i < def->os.nBootDevs; i++) {
8013                 switch (def->os.bootDevs[i]) {
8014                 case VIR_DOMAIN_BOOT_CDROM:
8015                     bootCD = i + 1;
8016                     break;
8017                 case VIR_DOMAIN_BOOT_FLOPPY:
8018                     bootFloppy = i + 1;
8019                     break;
8020                 case VIR_DOMAIN_BOOT_DISK:
8021                     bootDisk = i + 1;
8022                     break;
8023                 }
8024             }
8025         }
8026
8027         for (i = 0; i < def->ndisks; i++) {
8028             char *optstr;
8029             int bootindex = 0;
8030             virDomainDiskDefPtr disk = def->disks[i];
8031             bool withDeviceArg = false;
8032             bool deviceFlagMasked = false;
8033
8034             /* Unless we have -device, then USB disks need special
8035                handling */
8036             if ((disk->bus == VIR_DOMAIN_DISK_BUS_USB) &&
8037                 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
8038                 if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
8039                     virCommandAddArg(cmd, "-usbdevice");
8040                     virCommandAddArgFormat(cmd, "disk:%s", disk->src.path);
8041                 } else {
8042                     virReportError(VIR_ERR_INTERNAL_ERROR,
8043                                    _("unsupported usb disk type for '%s'"),
8044                                    disk->src.path);
8045                     goto error;
8046                 }
8047                 continue;
8048             }
8049
8050             switch (disk->device) {
8051             case VIR_DOMAIN_DISK_DEVICE_CDROM:
8052                 bootindex = bootCD;
8053                 bootCD = 0;
8054                 break;
8055             case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
8056                 bootindex = bootFloppy;
8057                 bootFloppy = 0;
8058                 break;
8059             case VIR_DOMAIN_DISK_DEVICE_DISK:
8060             case VIR_DOMAIN_DISK_DEVICE_LUN:
8061                 bootindex = bootDisk;
8062                 bootDisk = 0;
8063                 break;
8064             }
8065
8066             virCommandAddArg(cmd, "-drive");
8067
8068             /* Unfortunately it is not possible to use
8069                -device for floppies, xen PV, or SD
8070                devices. Fortunately, those don't need
8071                static PCI addresses, so we don't really
8072                care that we can't use -device */
8073             if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
8074                 if (disk->bus != VIR_DOMAIN_DISK_BUS_XEN &&
8075                     disk->bus != VIR_DOMAIN_DISK_BUS_SD) {
8076                     withDeviceArg = true;
8077                 } else {
8078                     virQEMUCapsClear(qemuCaps, QEMU_CAPS_DEVICE);
8079                     deviceFlagMasked = true;
8080                 }
8081             }
8082             optstr = qemuBuildDriveStr(conn, disk,
8083                                        emitBootindex ? false : !!bootindex,
8084                                        qemuCaps);
8085             if (deviceFlagMasked)
8086                 virQEMUCapsSet(qemuCaps, QEMU_CAPS_DEVICE);
8087             if (!optstr)
8088                 goto error;
8089             virCommandAddArg(cmd, optstr);
8090             VIR_FREE(optstr);
8091
8092             if (!emitBootindex)
8093                 bootindex = 0;
8094             else if (disk->info.bootIndex)
8095                 bootindex = disk->info.bootIndex;
8096
8097             if (withDeviceArg) {
8098                 if (disk->bus == VIR_DOMAIN_DISK_BUS_FDC) {
8099                     virCommandAddArg(cmd, "-global");
8100                     virCommandAddArgFormat(cmd, "isa-fdc.drive%c=drive-%s",
8101                                            disk->info.addr.drive.unit
8102                                            ? 'B' : 'A',
8103                                            disk->info.alias);
8104
8105                     if (bootindex) {
8106                         virCommandAddArg(cmd, "-global");
8107                         virCommandAddArgFormat(cmd, "isa-fdc.bootindex%c=%d",
8108                                                disk->info.addr.drive.unit
8109                                                ? 'B' : 'A',
8110                                                bootindex);
8111                     }
8112                 } else {
8113                     virCommandAddArg(cmd, "-device");
8114
8115                     if (!(optstr = qemuBuildDriveDevStr(def, disk, bootindex,
8116                                                         qemuCaps)))
8117                         goto error;
8118                     virCommandAddArg(cmd, optstr);
8119                     VIR_FREE(optstr);
8120                 }
8121             }
8122         }
8123     } else {
8124         for (i = 0; i < def->ndisks; i++) {
8125             char dev[NAME_MAX];
8126             char *file;
8127             const char *fmt;
8128             virDomainDiskDefPtr disk = def->disks[i];
8129
8130             if ((disk->src.type == VIR_STORAGE_TYPE_BLOCK) &&
8131                 (disk->tray_status == VIR_DOMAIN_DISK_TRAY_OPEN)) {
8132                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8133                                _("tray status 'open' is invalid for "
8134                                  "block type disk"));
8135                 goto error;
8136             }
8137
8138             if (disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
8139                 if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
8140                     virCommandAddArg(cmd, "-usbdevice");
8141                     virCommandAddArgFormat(cmd, "disk:%s", disk->src.path);
8142                 } else {
8143                     virReportError(VIR_ERR_INTERNAL_ERROR,
8144                                    _("unsupported usb disk type for '%s'"),
8145                                    disk->src.path);
8146                     goto error;
8147                 }
8148                 continue;
8149             }
8150
8151             if (STREQ(disk->dst, "hdc") &&
8152                 disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
8153                 if (disk->src.path) {
8154                     snprintf(dev, NAME_MAX, "-%s", "cdrom");
8155                 } else {
8156                     continue;
8157                 }
8158             } else {
8159                 if (STRPREFIX(disk->dst, "hd") ||
8160                     STRPREFIX(disk->dst, "fd")) {
8161                     snprintf(dev, NAME_MAX, "-%s", disk->dst);
8162                 } else {
8163                     virReportError(VIR_ERR_INTERNAL_ERROR,
8164                                    _("unsupported disk type '%s'"), disk->dst);
8165                     goto error;
8166                 }
8167             }
8168
8169             if (disk->src.type == VIR_STORAGE_TYPE_DIR) {
8170                 /* QEMU only supports magic FAT format for now */
8171                 if (disk->src.format > 0 &&
8172                     disk->src.format != VIR_STORAGE_FILE_FAT) {
8173                     virReportError(VIR_ERR_INTERNAL_ERROR,
8174                                    _("unsupported disk driver type for '%s'"),
8175                                    virStorageFileFormatTypeToString(disk->src.format));
8176                     goto error;
8177                 }
8178                 if (!disk->readonly) {
8179                     virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8180                                    _("cannot create virtual FAT disks in read-write mode"));
8181                     goto error;
8182                 }
8183                 if (disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY)
8184                     fmt = "fat:floppy:%s";
8185                 else
8186                     fmt = "fat:%s";
8187
8188                 if (virAsprintf(&file, fmt, disk->src) < 0)
8189                     goto error;
8190             } else if (disk->src.type == VIR_STORAGE_TYPE_NETWORK) {
8191                 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8192                                _("network disks are only supported with -drive"));
8193                 goto error;
8194             } else {
8195                 if (VIR_STRDUP(file, disk->src.path) < 0) {
8196                     goto error;
8197                 }
8198             }
8199
8200             /* Don't start with source if the tray is open for
8201              * CDROM and Floppy device.
8202              */
8203             if (!((disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY ||
8204                    disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM) &&
8205                   disk->tray_status == VIR_DOMAIN_DISK_TRAY_OPEN))
8206                 virCommandAddArgList(cmd, dev, file, NULL);
8207             VIR_FREE(file);
8208         }
8209     }
8210
8211     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_FSDEV)) {
8212         for (i = 0; i < def->nfss; i++) {
8213             char *optstr;
8214             virDomainFSDefPtr fs = def->fss[i];
8215
8216             virCommandAddArg(cmd, "-fsdev");
8217             if (!(optstr = qemuBuildFSStr(fs, qemuCaps)))
8218                 goto error;
8219             virCommandAddArg(cmd, optstr);
8220             VIR_FREE(optstr);
8221
8222             virCommandAddArg(cmd, "-device");
8223             if (!(optstr = qemuBuildFSDevStr(def, fs, qemuCaps)))
8224                 goto error;
8225             virCommandAddArg(cmd, optstr);
8226             VIR_FREE(optstr);
8227         }
8228     } else {
8229         if (def->nfss) {
8230             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8231                            _("filesystem passthrough not supported by this QEMU"));
8232             goto error;
8233         }
8234     }
8235
8236     if (!def->nnets) {
8237         /* If we have -device, then we set -nodefault already */
8238         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE))
8239             virCommandAddArgList(cmd, "-net", "none", NULL);
8240     } else {
8241         int bootNet = 0;
8242
8243         if (emitBootindex) {
8244             /* convert <boot dev='network'/> to bootindex since we didn't emit
8245              * -boot n
8246              */
8247             for (i = 0; i < def->os.nBootDevs; i++) {
8248                 if (def->os.bootDevs[i] == VIR_DOMAIN_BOOT_NET) {
8249                     bootNet = i + 1;
8250                     break;
8251                 }
8252             }
8253         }
8254
8255         for (i = 0; i < def->nnets; i++) {
8256             virDomainNetDefPtr net = def->nets[i];
8257             int vlan;
8258
8259             /* VLANs are not used with -netdev, so don't record them */
8260             if (qemuDomainSupportsNetdev(def, qemuCaps, net))
8261                 vlan = -1;
8262             else
8263                 vlan = i;
8264
8265             if (qemuBuildInterfaceCommandLine(cmd, driver, conn, def, net,
8266                                               qemuCaps, vlan, bootNet, vmop,
8267                                               standalone) < 0)
8268                 goto error;
8269             last_good_net = i;
8270             bootNet = 0;
8271         }
8272     }
8273
8274     if (def->nsmartcards) {
8275         /* -device usb-ccid was already emitted along with other
8276          * controllers.  For now, qemu handles only one smartcard.  */
8277         virDomainSmartcardDefPtr smartcard = def->smartcards[0];
8278         char *devstr;
8279         virBuffer opt = VIR_BUFFER_INITIALIZER;
8280         const char *database;
8281
8282         if (def->nsmartcards > 1 ||
8283             smartcard->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID ||
8284             smartcard->info.addr.ccid.controller != 0 ||
8285             smartcard->info.addr.ccid.slot != 0) {
8286             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8287                            _("this QEMU binary lacks multiple smartcard "
8288                              "support"));
8289             virBufferFreeAndReset(&opt);
8290             goto error;
8291         }
8292
8293         switch (smartcard->type) {
8294         case VIR_DOMAIN_SMARTCARD_TYPE_HOST:
8295             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_CHARDEV) ||
8296                 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_CCID_EMULATED)) {
8297                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8298                                _("this QEMU binary lacks smartcard host "
8299                                  "mode support"));
8300                 goto error;
8301             }
8302
8303             virBufferAddLit(&opt, "ccid-card-emulated,backend=nss-emulated");
8304             break;
8305
8306         case VIR_DOMAIN_SMARTCARD_TYPE_HOST_CERTIFICATES:
8307             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_CHARDEV) ||
8308                 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_CCID_EMULATED)) {
8309                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8310                                _("this QEMU binary lacks smartcard host "
8311                                  "mode support"));
8312                 goto error;
8313             }
8314
8315             virBufferAddLit(&opt, "ccid-card-emulated,backend=certificates");
8316             for (j = 0; j < VIR_DOMAIN_SMARTCARD_NUM_CERTIFICATES; j++) {
8317                 if (strchr(smartcard->data.cert.file[j], ',')) {
8318                     virBufferFreeAndReset(&opt);
8319                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8320                                    _("invalid certificate name: %s"),
8321                                    smartcard->data.cert.file[j]);
8322                     goto error;
8323                 }
8324                 virBufferAsprintf(&opt, ",cert%zu=%s", j + 1,
8325                                   smartcard->data.cert.file[j]);
8326             }
8327             if (smartcard->data.cert.database) {
8328                 if (strchr(smartcard->data.cert.database, ',')) {
8329                     virBufferFreeAndReset(&opt);
8330                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8331                                    _("invalid database name: %s"),
8332                                    smartcard->data.cert.database);
8333                     goto error;
8334                 }
8335                 database = smartcard->data.cert.database;
8336             } else {
8337                 database = VIR_DOMAIN_SMARTCARD_DEFAULT_DATABASE;
8338             }
8339             virBufferAsprintf(&opt, ",db=%s", database);
8340             break;
8341
8342         case VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH:
8343             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_CHARDEV) ||
8344                 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_CCID_PASSTHRU)) {
8345                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8346                                _("this QEMU binary lacks smartcard "
8347                                  "passthrough mode support"));
8348                 goto error;
8349             }
8350
8351             virCommandAddArg(cmd, "-chardev");
8352             if (!(devstr = qemuBuildChrChardevStr(&smartcard->data.passthru,
8353                                                   smartcard->info.alias,
8354                                                   qemuCaps))) {
8355                 virBufferFreeAndReset(&opt);
8356                 goto error;
8357             }
8358             virCommandAddArg(cmd, devstr);
8359             VIR_FREE(devstr);
8360
8361             virBufferAsprintf(&opt, "ccid-card-passthru,chardev=char%s",
8362                               smartcard->info.alias);
8363             break;
8364
8365         default:
8366             virReportError(VIR_ERR_INTERNAL_ERROR,
8367                            _("unexpected smartcard type %d"),
8368                            smartcard->type);
8369             virBufferFreeAndReset(&opt);
8370             goto error;
8371         }
8372         virCommandAddArg(cmd, "-device");
8373         virBufferAsprintf(&opt, ",id=%s,bus=ccid0.0", smartcard->info.alias);
8374         virCommandAddArgBuffer(cmd, &opt);
8375     }
8376
8377     for (i = 0; i < def->nserials; i++) {
8378         virDomainChrDefPtr serial = def->serials[i];
8379         char *devstr;
8380
8381         if (serial->source.type == VIR_DOMAIN_CHR_TYPE_SPICEPORT && !spice)
8382             continue;
8383
8384         /* Use -chardev with -device if they are available */
8385         if (virQEMUCapsSupportsChardev(def, qemuCaps, serial)) {
8386             virCommandAddArg(cmd, "-chardev");
8387             if (!(devstr = qemuBuildChrChardevStr(&serial->source,
8388                                                   serial->info.alias,
8389                                                   qemuCaps)))
8390                 goto error;
8391             virCommandAddArg(cmd, devstr);
8392             VIR_FREE(devstr);
8393
8394             if (qemuBuildChrDeviceCommandLine(cmd, def, serial, qemuCaps) < 0)
8395                 goto error;
8396         } else {
8397             virCommandAddArg(cmd, "-serial");
8398             if (!(devstr = qemuBuildChrArgStr(&serial->source, NULL)))
8399                 goto error;
8400             virCommandAddArg(cmd, devstr);
8401             VIR_FREE(devstr);
8402         }
8403         actualSerials++;
8404     }
8405
8406     /* If we have -device, then we set -nodefault already */
8407     if (!actualSerials && !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE))
8408             virCommandAddArgList(cmd, "-serial", "none", NULL);
8409
8410     if (!def->nparallels) {
8411         /* If we have -device, then we set -nodefault already */
8412         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE))
8413             virCommandAddArgList(cmd, "-parallel", "none", NULL);
8414     } else {
8415         for (i = 0; i < def->nparallels; i++) {
8416             virDomainChrDefPtr parallel = def->parallels[i];
8417             char *devstr;
8418
8419             /* Use -chardev with -device if they are available */
8420             if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_CHARDEV) &&
8421                 virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
8422                 virCommandAddArg(cmd, "-chardev");
8423                 if (!(devstr = qemuBuildChrChardevStr(&parallel->source,
8424                                                       parallel->info.alias,
8425                                                       qemuCaps)))
8426                     goto error;
8427                 virCommandAddArg(cmd, devstr);
8428                 VIR_FREE(devstr);
8429
8430                 if (qemuBuildChrDeviceCommandLine(cmd, def, parallel, qemuCaps) < 0)
8431                     goto error;
8432             } else {
8433                 virCommandAddArg(cmd, "-parallel");
8434                 if (!(devstr = qemuBuildChrArgStr(&parallel->source, NULL)))
8435                       goto error;
8436                 virCommandAddArg(cmd, devstr);
8437                 VIR_FREE(devstr);
8438             }
8439         }
8440     }
8441
8442     for (i = 0; i < def->nchannels; i++) {
8443         virDomainChrDefPtr channel = def->channels[i];
8444         char *devstr;
8445
8446         switch (channel->targetType) {
8447         case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_GUESTFWD:
8448             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_CHARDEV) ||
8449                 !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
8450                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8451                                "%s", _("guestfwd requires QEMU to support -chardev & -device"));
8452                 goto error;
8453             }
8454
8455             virCommandAddArg(cmd, "-chardev");
8456             if (!(devstr = qemuBuildChrChardevStr(&channel->source,
8457                                                   channel->info.alias,
8458                                                   qemuCaps)))
8459                 goto error;
8460             virCommandAddArg(cmd, devstr);
8461             VIR_FREE(devstr);
8462
8463             if (qemuBuildChrDeviceStr(&devstr, def, channel, qemuCaps) < 0)
8464                 goto error;
8465             virCommandAddArgList(cmd, "-netdev", devstr, NULL);
8466             VIR_FREE(devstr);
8467             break;
8468
8469         case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO:
8470             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
8471                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8472                                _("virtio channel requires QEMU to support -device"));
8473                 goto error;
8474             }
8475
8476             if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_SPICEVMC) &&
8477                 channel->source.type == VIR_DOMAIN_CHR_TYPE_SPICEVMC) {
8478                 /* spicevmc was originally introduced via a -device
8479                  * with a backend internal to qemu; although we prefer
8480                  * the newer -chardev interface.  */
8481                 ;
8482             } else {
8483                 virCommandAddArg(cmd, "-chardev");
8484                 if (!(devstr = qemuBuildChrChardevStr(&channel->source,
8485                                                       channel->info.alias,
8486                                                       qemuCaps)))
8487                     goto error;
8488                 virCommandAddArg(cmd, devstr);
8489                 VIR_FREE(devstr);
8490             }
8491
8492             if (qemuBuildChrDeviceCommandLine(cmd, def, channel, qemuCaps) < 0)
8493                 goto error;
8494             break;
8495         }
8496     }
8497
8498     /* Explicit console devices */
8499     for (i = 0; i < def->nconsoles; i++) {
8500         virDomainChrDefPtr console = def->consoles[i];
8501         char *devstr;
8502
8503         switch (console->targetType) {
8504         case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SCLP:
8505         case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SCLPLM:
8506             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
8507                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8508                                _("sclp console requires QEMU to support -device"));
8509                 goto error;
8510             }
8511             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCLP_S390)) {
8512                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8513                                _("sclp console requires QEMU to support s390-sclp"));
8514                 goto error;
8515             }
8516
8517             virCommandAddArg(cmd, "-chardev");
8518             if (!(devstr = qemuBuildChrChardevStr(&console->source,
8519                                                   console->info.alias,
8520                                                   qemuCaps)))
8521                 goto error;
8522             virCommandAddArg(cmd, devstr);
8523             VIR_FREE(devstr);
8524
8525             if (qemuBuildChrDeviceCommandLine(cmd, def, console, qemuCaps) < 0)
8526                 goto error;
8527             break;
8528
8529         case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_VIRTIO:
8530             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
8531                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8532                                _("virtio channel requires QEMU to support -device"));
8533                 goto error;
8534             }
8535
8536             virCommandAddArg(cmd, "-chardev");
8537             if (!(devstr = qemuBuildChrChardevStr(&console->source,
8538                                                   console->info.alias,
8539                                                   qemuCaps)))
8540                 goto error;
8541             virCommandAddArg(cmd, devstr);
8542             VIR_FREE(devstr);
8543
8544             if (qemuBuildChrDeviceCommandLine(cmd, def, console, qemuCaps) < 0)
8545                 goto error;
8546             break;
8547
8548         case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL:
8549             break;
8550
8551         default:
8552             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8553                            _("unsupported console target type %s"),
8554                            NULLSTR(virDomainChrConsoleTargetTypeToString(console->targetType)));
8555             goto error;
8556         }
8557     }
8558
8559     if (def->tpm) {
8560         char *optstr;
8561
8562         if (!(optstr = qemuBuildTPMBackendStr(def, qemuCaps, emulator)))
8563             goto error;
8564
8565         virCommandAddArgList(cmd, "-tpmdev", optstr, NULL);
8566         VIR_FREE(optstr);
8567
8568         if (!(optstr = qemuBuildTPMDevStr(def, qemuCaps, emulator)))
8569             goto error;
8570
8571         virCommandAddArgList(cmd, "-device", optstr, NULL);
8572         VIR_FREE(optstr);
8573     }
8574
8575     for (i = 0; i < def->ninputs; i++) {
8576         virDomainInputDefPtr input = def->inputs[i];
8577
8578         if (input->bus == VIR_DOMAIN_INPUT_BUS_USB) {
8579             if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
8580                 char *optstr;
8581                 virCommandAddArg(cmd, "-device");
8582                 if (!(optstr = qemuBuildUSBInputDevStr(def, input, qemuCaps)))
8583                     goto error;
8584                 virCommandAddArg(cmd, optstr);
8585                 VIR_FREE(optstr);
8586             } else {
8587                 switch (input->type) {
8588                     case VIR_DOMAIN_INPUT_TYPE_MOUSE:
8589                         virCommandAddArgList(cmd, "-usbdevice", "mouse", NULL);
8590                         break;
8591                     case VIR_DOMAIN_INPUT_TYPE_TABLET:
8592                         virCommandAddArgList(cmd, "-usbdevice", "tablet", NULL);
8593                         break;
8594                     case VIR_DOMAIN_INPUT_TYPE_KBD:
8595                         virCommandAddArgList(cmd, "-usbdevice", "keyboard", NULL);
8596                         break;
8597                 }
8598             }
8599         }
8600     }
8601
8602     if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_0_10) && sdl + vnc + spice > 1) {
8603         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8604                        _("only 1 graphics device is supported"));
8605         goto error;
8606     }
8607     if (sdl > 1 || vnc > 1 || spice > 1) {
8608         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8609                        _("only 1 graphics device of each type "
8610                          "(sdl, vnc, spice) is supported"));
8611         goto error;
8612     }
8613
8614     for (i = 0; i < def->ngraphics; ++i) {
8615         if (qemuBuildGraphicsCommandLine(cfg, cmd, def, qemuCaps,
8616                                          def->graphics[i]) < 0)
8617             goto error;
8618     }
8619
8620     if (def->nvideos > 0) {
8621         int primaryVideoType = def->videos[0]->type;
8622         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIDEO_PRIMARY) &&
8623              ((primaryVideoType == VIR_DOMAIN_VIDEO_TYPE_VGA &&
8624                  virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VGA)) ||
8625              (primaryVideoType == VIR_DOMAIN_VIDEO_TYPE_CIRRUS &&
8626                  virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_CIRRUS_VGA)) ||
8627              (primaryVideoType == VIR_DOMAIN_VIDEO_TYPE_VMVGA &&
8628                  virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VMWARE_SVGA)) ||
8629              (primaryVideoType == VIR_DOMAIN_VIDEO_TYPE_QXL &&
8630                  virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_QXL_VGA)))
8631            ) {
8632             for (i = 0; i < def->nvideos; i++) {
8633                 char *str;
8634                 virCommandAddArg(cmd, "-device");
8635                 if (!(str = qemuBuildDeviceVideoStr(def, def->videos[i], qemuCaps, !i)))
8636                     goto error;
8637
8638                 virCommandAddArg(cmd, str);
8639                 VIR_FREE(str);
8640             }
8641         } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VGA)) {
8642             if (primaryVideoType == VIR_DOMAIN_VIDEO_TYPE_XEN) {
8643                 /* nothing - vga has no effect on Xen pvfb */
8644             } else {
8645                 if ((primaryVideoType == VIR_DOMAIN_VIDEO_TYPE_QXL) &&
8646                     !virQEMUCapsGet(qemuCaps, QEMU_CAPS_VGA_QXL)) {
8647                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8648                                    _("This QEMU does not support QXL graphics adapters"));
8649                     goto error;
8650                 }
8651
8652                 const char *vgastr = qemuVideoTypeToString(primaryVideoType);
8653                 if (!vgastr || STREQ(vgastr, "")) {
8654                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8655                                    _("video type %s is not supported with QEMU"),
8656                                    virDomainVideoTypeToString(primaryVideoType));
8657                     goto error;
8658                 }
8659
8660                 virCommandAddArgList(cmd, "-vga", vgastr, NULL);
8661
8662                 if (def->videos[0]->type == VIR_DOMAIN_VIDEO_TYPE_QXL &&
8663                     (def->videos[0]->vram || def->videos[0]->ram) &&
8664                     virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
8665                     const char *dev = (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_QXL_VGA)
8666                                        ? "qxl-vga" : "qxl");
8667                     int ram = def->videos[0]->ram;
8668                     int vram = def->videos[0]->vram;
8669
8670                     if (vram > (UINT_MAX / 1024)) {
8671                         virReportError(VIR_ERR_OVERFLOW,
8672                                _("value for 'vram' must be less than '%u'"),
8673                                        UINT_MAX / 1024);
8674                         goto error;
8675                     }
8676                     if (ram > (UINT_MAX / 1024)) {
8677                         virReportError(VIR_ERR_OVERFLOW,
8678                            _("value for 'ram' must be less than '%u'"),
8679                                        UINT_MAX / 1024);
8680                         goto error;
8681                     }
8682
8683                     if (ram) {
8684                         virCommandAddArg(cmd, "-global");
8685                         virCommandAddArgFormat(cmd, "%s.ram_size=%u",
8686                                                dev, ram * 1024);
8687                     }
8688                     if (vram) {
8689                         virCommandAddArg(cmd, "-global");
8690                         virCommandAddArgFormat(cmd, "%s.vram_size=%u",
8691                                                dev, vram * 1024);
8692                     }
8693                 }
8694             }
8695
8696             if (def->nvideos > 1) {
8697                 if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
8698                     for (i = 1; i < def->nvideos; i++) {
8699                         char *str;
8700                         if (def->videos[i]->type != VIR_DOMAIN_VIDEO_TYPE_QXL) {
8701                             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8702                                            _("video type %s is only valid as primary video card"),
8703                                            virDomainVideoTypeToString(def->videos[0]->type));
8704                             goto error;
8705                         }
8706
8707                         virCommandAddArg(cmd, "-device");
8708
8709                         if (!(str = qemuBuildDeviceVideoStr(def, def->videos[i], qemuCaps, false)))
8710                             goto error;
8711
8712                         virCommandAddArg(cmd, str);
8713                         VIR_FREE(str);
8714                     }
8715                 } else {
8716                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8717                                    "%s", _("only one video card is currently supported"));
8718                     goto error;
8719                 }
8720             }
8721         } else {
8722
8723             switch (def->videos[0]->type) {
8724             case VIR_DOMAIN_VIDEO_TYPE_VGA:
8725                 virCommandAddArg(cmd, "-std-vga");
8726                 break;
8727
8728             case VIR_DOMAIN_VIDEO_TYPE_VMVGA:
8729                 virCommandAddArg(cmd, "-vmwarevga");
8730                 break;
8731
8732             case VIR_DOMAIN_VIDEO_TYPE_XEN:
8733             case VIR_DOMAIN_VIDEO_TYPE_CIRRUS:
8734                 /* No special args - this is the default */
8735                 break;
8736
8737             default:
8738                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8739                                _("video type %s is not supported with this QEMU"),
8740                                virDomainVideoTypeToString(def->videos[0]->type));
8741                 goto error;
8742             }
8743
8744             if (def->nvideos > 1) {
8745                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8746                                "%s", _("only one video card is currently supported"));
8747                 goto error;
8748             }
8749         }
8750
8751     } else {
8752         /* If we have -device, then we set -nodefault already */
8753         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE) &&
8754             virQEMUCapsGet(qemuCaps, QEMU_CAPS_VGA) &&
8755             virQEMUCapsGet(qemuCaps, QEMU_CAPS_VGA_NONE))
8756             virCommandAddArgList(cmd, "-vga", "none", NULL);
8757     }
8758
8759     /* Add sound hardware */
8760     if (def->nsounds) {
8761         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
8762             for (i = 0; i < def->nsounds; i++) {
8763                 virDomainSoundDefPtr sound = def->sounds[i];
8764                 char *str = NULL;
8765
8766                 /* Sadly pcspk device doesn't use -device syntax. Fortunately
8767                  * we don't need to set any PCI address on it, so we don't
8768                  * mind too much */
8769                 if (sound->model == VIR_DOMAIN_SOUND_MODEL_PCSPK) {
8770                     virCommandAddArgList(cmd, "-soundhw", "pcspk", NULL);
8771                 } else {
8772                     virCommandAddArg(cmd, "-device");
8773                     if (!(str = qemuBuildSoundDevStr(def, sound, qemuCaps)))
8774                         goto error;
8775
8776                     virCommandAddArg(cmd, str);
8777                     VIR_FREE(str);
8778                     if (sound->model == VIR_DOMAIN_SOUND_MODEL_ICH6 ||
8779                         sound->model == VIR_DOMAIN_SOUND_MODEL_ICH9) {
8780                         char *codecstr = NULL;
8781
8782                         for (j = 0; j < sound->ncodecs; j++) {
8783                             virCommandAddArg(cmd, "-device");
8784                             if (!(codecstr = qemuBuildSoundCodecStr(sound, sound->codecs[j], qemuCaps))) {
8785                                 goto error;
8786
8787                             }
8788                             virCommandAddArg(cmd, codecstr);
8789                             VIR_FREE(codecstr);
8790                         }
8791                         if (j == 0) {
8792                             virDomainSoundCodecDef codec = {
8793                                 VIR_DOMAIN_SOUND_CODEC_TYPE_DUPLEX,
8794                                 0
8795                             };
8796                             virCommandAddArg(cmd, "-device");
8797                             if (!(codecstr = qemuBuildSoundCodecStr(sound, &codec, qemuCaps))) {
8798                                 goto error;
8799
8800                             }
8801                             virCommandAddArg(cmd, codecstr);
8802                             VIR_FREE(codecstr);
8803                         }
8804                     }
8805                 }
8806             }
8807         } else {
8808             int size = 100;
8809             char *modstr;
8810             if (VIR_ALLOC_N(modstr, size+1) < 0)
8811                 goto error;
8812
8813             for (i = 0; i < def->nsounds && size > 0; i++) {
8814                 virDomainSoundDefPtr sound = def->sounds[i];
8815                 const char *model = virDomainSoundModelTypeToString(sound->model);
8816                 if (!model) {
8817                     VIR_FREE(modstr);
8818                     virReportError(VIR_ERR_INTERNAL_ERROR,
8819                                    "%s", _("invalid sound model"));
8820                     goto error;
8821                 }
8822
8823                 if (sound->model == VIR_DOMAIN_SOUND_MODEL_ICH6 ||
8824                     sound->model == VIR_DOMAIN_SOUND_MODEL_ICH9) {
8825                     VIR_FREE(modstr);
8826                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8827                                    _("this QEMU binary lacks hda support"));
8828                     goto error;
8829                 }
8830
8831                 strncat(modstr, model, size);
8832                 size -= strlen(model);
8833                 if (i < (def->nsounds - 1))
8834                     strncat(modstr, ",", size--);
8835             }
8836             virCommandAddArgList(cmd, "-soundhw", modstr, NULL);
8837             VIR_FREE(modstr);
8838         }
8839     }
8840
8841     /* Add watchdog hardware */
8842     if (def->watchdog) {
8843         virDomainWatchdogDefPtr watchdog = def->watchdog;
8844         char *optstr;
8845
8846         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
8847             virCommandAddArg(cmd, "-device");
8848
8849             optstr = qemuBuildWatchdogDevStr(def, watchdog, qemuCaps);
8850             if (!optstr)
8851                 goto error;
8852         } else {
8853             virCommandAddArg(cmd, "-watchdog");
8854
8855             const char *model = virDomainWatchdogModelTypeToString(watchdog->model);
8856             if (!model) {
8857                 virReportError(VIR_ERR_INTERNAL_ERROR,
8858                                "%s", _("missing watchdog model"));
8859                 goto error;
8860             }
8861
8862             if (VIR_STRDUP(optstr, model) < 0)
8863                 goto error;
8864         }
8865         virCommandAddArg(cmd, optstr);
8866         VIR_FREE(optstr);
8867
8868         int act = watchdog->action;
8869         if (act == VIR_DOMAIN_WATCHDOG_ACTION_DUMP)
8870             act = VIR_DOMAIN_WATCHDOG_ACTION_PAUSE;
8871         const char *action = virDomainWatchdogActionTypeToString(act);
8872         if (!action) {
8873             virReportError(VIR_ERR_INTERNAL_ERROR,
8874                            "%s", _("invalid watchdog action"));
8875             goto error;
8876         }
8877         virCommandAddArgList(cmd, "-watchdog-action", action, NULL);
8878     }
8879
8880     /* Add redirected devices */
8881     for (i = 0; i < def->nredirdevs; i++) {
8882         virDomainRedirdevDefPtr redirdev = def->redirdevs[i];
8883         char *devstr;
8884
8885         virCommandAddArg(cmd, "-chardev");
8886         if (!(devstr = qemuBuildChrChardevStr(&redirdev->source.chr,
8887                                               redirdev->info.alias,
8888                                               qemuCaps))) {
8889             goto error;
8890         }
8891
8892         virCommandAddArg(cmd, devstr);
8893         VIR_FREE(devstr);
8894
8895         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE))
8896             goto error;
8897
8898         virCommandAddArg(cmd, "-device");
8899         if (!(devstr = qemuBuildRedirdevDevStr(def, redirdev, qemuCaps)))
8900             goto error;
8901         virCommandAddArg(cmd, devstr);
8902         VIR_FREE(devstr);
8903     }
8904
8905     /* Add host passthrough hardware */
8906     for (i = 0; i < def->nhostdevs; i++) {
8907         virDomainHostdevDefPtr hostdev = def->hostdevs[i];
8908         char *devstr;
8909
8910         if (hostdev->info->bootIndex) {
8911             if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
8912                 (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
8913                  hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB &&
8914                  hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI)) {
8915                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8916                                _("booting from assigned devices is only "
8917                                  "supported for PCI, USB and SCSI devices"));
8918                 goto error;
8919             } else {
8920                 if (hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI) {
8921                     if (hostdev->source.subsys.u.pci.backend
8922                         == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
8923                         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VFIO_PCI_BOOTINDEX)) {
8924                             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8925                                            _("booting from PCI devices assigned with VFIO "
8926                                              "is not supported with this version of qemu"));
8927                             goto error;
8928                         }
8929                     } else {
8930                         if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_PCI_BOOTINDEX)) {
8931                             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8932                                            _("booting from assigned PCI devices is not "
8933                                              "supported with this version of qemu"));
8934                             goto error;
8935                         }
8936                     }
8937                 }
8938                 if (hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB &&
8939                     !virQEMUCapsGet(qemuCaps, QEMU_CAPS_USB_HOST_BOOTINDEX)) {
8940                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8941                                    _("booting from assigned USB devices is not "
8942                                      "supported with this version of qemu"));
8943                     goto error;
8944                 }
8945                 if (hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
8946                     !virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_SCSI_GENERIC_BOOTINDEX)) {
8947                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8948                                    _("booting from assigned SCSI devices is not"
8949                                      " supported with this version of qemu"));
8950                     goto error;
8951                 }
8952             }
8953         }
8954
8955         /* USB */
8956         if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
8957             hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
8958
8959             if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
8960                 virCommandAddArg(cmd, "-device");
8961                 if (!(devstr = qemuBuildUSBHostdevDevStr(def, hostdev, qemuCaps)))
8962                     goto error;
8963                 virCommandAddArg(cmd, devstr);
8964                 VIR_FREE(devstr);
8965             } else {
8966                 virCommandAddArg(cmd, "-usbdevice");
8967                 if (!(devstr = qemuBuildUSBHostdevUSBDevStr(hostdev)))
8968                     goto error;
8969                 virCommandAddArg(cmd, devstr);
8970                 VIR_FREE(devstr);
8971             }
8972         }
8973
8974         /* PCI */
8975         if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
8976             hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI) {
8977             int backend = hostdev->source.subsys.u.pci.backend;
8978
8979             if (backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
8980                 if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VFIO_PCI)) {
8981                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8982                                    _("VFIO PCI device assignment is not "
8983                                      "supported by this version of qemu"));
8984                     goto error;
8985                 }
8986                 /* VFIO requires all of the guest's memory to be locked
8987                  * resident */
8988                 mlock = true;
8989             }
8990
8991             if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
8992                 char *configfd_name = NULL;
8993                 if ((backend != VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) &&
8994                     virQEMUCapsGet(qemuCaps, QEMU_CAPS_PCI_CONFIGFD)) {
8995                     int configfd = qemuOpenPCIConfig(hostdev);
8996
8997                     if (configfd >= 0) {
8998                         if (virAsprintf(&configfd_name, "%d", configfd) < 0) {
8999                             VIR_FORCE_CLOSE(configfd);
9000                             goto error;
9001                         }
9002
9003                         virCommandPassFD(cmd, configfd,
9004                                          VIR_COMMAND_PASS_FD_CLOSE_PARENT);
9005                     }
9006                 }
9007                 virCommandAddArg(cmd, "-device");
9008                 devstr = qemuBuildPCIHostdevDevStr(def, hostdev, configfd_name, qemuCaps);
9009                 VIR_FREE(configfd_name);
9010                 if (!devstr)
9011                     goto error;
9012                 virCommandAddArg(cmd, devstr);
9013                 VIR_FREE(devstr);
9014             } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_PCIDEVICE)) {
9015                 virCommandAddArg(cmd, "-pcidevice");
9016                 if (!(devstr = qemuBuildPCIHostdevPCIDevStr(hostdev, qemuCaps)))
9017                     goto error;
9018                 virCommandAddArg(cmd, devstr);
9019                 VIR_FREE(devstr);
9020             } else {
9021                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9022                                _("PCI device assignment is not supported by this version of qemu"));
9023                 goto error;
9024             }
9025         }
9026
9027         /* SCSI */
9028         if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
9029             hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI) {
9030             if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DRIVE) &&
9031                 virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE) &&
9032                 virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_SCSI_GENERIC)) {
9033                 char *drvstr;
9034
9035                 virCommandAddArg(cmd, "-drive");
9036                 if (!(drvstr = qemuBuildSCSIHostdevDrvStr(hostdev, qemuCaps, callbacks)))
9037                     goto error;
9038                 virCommandAddArg(cmd, drvstr);
9039                 VIR_FREE(drvstr);
9040
9041                 virCommandAddArg(cmd, "-device");
9042                 if (!(devstr = qemuBuildSCSIHostdevDevStr(def, hostdev, qemuCaps)))
9043                     goto error;
9044                 virCommandAddArg(cmd, devstr);
9045                 VIR_FREE(devstr);
9046             } else {
9047                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9048                                _("SCSI passthrough is not supported by this version of qemu"));
9049                 goto error;
9050             }
9051         }
9052     }
9053
9054     /* Migration is very annoying due to wildly varying syntax &
9055      * capabilities over time of KVM / QEMU codebases.
9056      */
9057     if (migrateFrom) {
9058         virCommandAddArg(cmd, "-incoming");
9059         if (STRPREFIX(migrateFrom, "tcp")) {
9060             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MIGRATE_QEMU_TCP)) {
9061                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9062                                "%s", _("TCP migration is not supported with "
9063                                        "this QEMU binary"));
9064                 goto error;
9065             }
9066             virCommandAddArg(cmd, migrateFrom);
9067         } else if (STREQ(migrateFrom, "stdio")) {
9068             if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_MIGRATE_QEMU_FD)) {
9069                 virCommandAddArgFormat(cmd, "fd:%d", migrateFd);
9070                 virCommandPassFD(cmd, migrateFd, 0);
9071             } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_MIGRATE_QEMU_EXEC)) {
9072                 virCommandAddArg(cmd, "exec:cat");
9073                 virCommandSetInputFD(cmd, migrateFd);
9074             } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_MIGRATE_KVM_STDIO)) {
9075                 virCommandAddArg(cmd, migrateFrom);
9076                 virCommandSetInputFD(cmd, migrateFd);
9077             } else {
9078                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9079                                "%s", _("STDIO migration is not supported "
9080                                        "with this QEMU binary"));
9081                 goto error;
9082             }
9083         } else if (STRPREFIX(migrateFrom, "exec")) {
9084             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MIGRATE_QEMU_EXEC)) {
9085                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9086                                "%s", _("EXEC migration is not supported "
9087                                        "with this QEMU binary"));
9088                 goto error;
9089             }
9090             virCommandAddArg(cmd, migrateFrom);
9091         } else if (STRPREFIX(migrateFrom, "fd")) {
9092             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MIGRATE_QEMU_FD)) {
9093                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9094                                "%s", _("FD migration is not supported "
9095                                        "with this QEMU binary"));
9096                 goto error;
9097             }
9098             virCommandAddArg(cmd, migrateFrom);
9099             virCommandPassFD(cmd, migrateFd, 0);
9100         } else if (STRPREFIX(migrateFrom, "unix")) {
9101             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MIGRATE_QEMU_UNIX)) {
9102                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9103                                "%s", _("UNIX migration is not supported "
9104                                        "with this QEMU binary"));
9105                 goto error;
9106             }
9107             virCommandAddArg(cmd, migrateFrom);
9108         } else {
9109             virReportError(VIR_ERR_INTERNAL_ERROR,
9110                            "%s", _("unknown migration protocol"));
9111             goto error;
9112         }
9113     }
9114
9115     /* QEMU changed its default behavior to not include the virtio balloon
9116      * device.  Explicitly request it to ensure it will be present.
9117      *
9118      * NB: Earlier we declared that VirtIO balloon will always be in
9119      * slot 0x3 on bus 0x0
9120      */
9121     if (STREQLEN(def->os.machine, "s390-virtio", 10) &&
9122         virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_S390) && def->memballoon)
9123         def->memballoon->model = VIR_DOMAIN_MEMBALLOON_MODEL_NONE;
9124
9125     if (def->memballoon &&
9126         def->memballoon->model != VIR_DOMAIN_MEMBALLOON_MODEL_NONE) {
9127         if (def->memballoon->model != VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO) {
9128             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9129                            _("Memory balloon device type '%s' is not supported by this version of qemu"),
9130                            virDomainMemballoonModelTypeToString(def->memballoon->model));
9131             goto error;
9132         }
9133         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE)) {
9134             char *optstr;
9135             virCommandAddArg(cmd, "-device");
9136
9137             optstr = qemuBuildMemballoonDevStr(def, def->memballoon, qemuCaps);
9138             if (!optstr)
9139                 goto error;
9140             virCommandAddArg(cmd, optstr);
9141             VIR_FREE(optstr);
9142         } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_BALLOON)) {
9143             virCommandAddArgList(cmd, "-balloon", "virtio", NULL);
9144         }
9145     }
9146
9147     if (def->rng) {
9148         /* add the RNG source backend */
9149         if (qemuBuildRNGBackendArgs(cmd, def->rng, qemuCaps) < 0)
9150             goto error;
9151
9152         /* add the device */
9153         if (qemuBuildRNGDeviceArgs(cmd, def, def->rng, qemuCaps) < 0)
9154             goto error;
9155     }
9156
9157     if (def->nvram) {
9158         if (def->os.arch == VIR_ARCH_PPC64 &&
9159             STREQ(def->os.machine, "pseries")) {
9160             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_NVRAM)) {
9161                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9162                                _("nvram device is not supported by "
9163                                  "this QEMU binary"));
9164                 goto error;
9165             }
9166
9167             char *optstr;
9168             virCommandAddArg(cmd, "-global");
9169             optstr = qemuBuildNVRAMDevStr(def->nvram);
9170             if (!optstr)
9171                 goto error;
9172             if (optstr)
9173                 virCommandAddArg(cmd, optstr);
9174             VIR_FREE(optstr);
9175         } else {
9176             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9177                           _("nvram device is only supported for PPC64"));
9178             goto error;
9179         }
9180     }
9181     if (snapshot)
9182         virCommandAddArgList(cmd, "-loadvm", snapshot->def->name, NULL);
9183
9184     if (def->namespaceData) {
9185         qemuDomainCmdlineDefPtr qemucmd;
9186
9187         qemucmd = def->namespaceData;
9188         for (i = 0; i < qemucmd->num_args; i++)
9189             virCommandAddArg(cmd, qemucmd->args[i]);
9190         for (i = 0; i < qemucmd->num_env; i++)
9191             virCommandAddEnvPair(cmd, qemucmd->env_name[i],
9192                                  qemucmd->env_value[i]
9193                                  ? qemucmd->env_value[i] : "");
9194     }
9195
9196     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_SECCOMP_SANDBOX)) {
9197         if (cfg->seccompSandbox == 0)
9198             virCommandAddArgList(cmd, "-sandbox", "off", NULL);
9199         else if (cfg->seccompSandbox > 0)
9200             virCommandAddArgList(cmd, "-sandbox", "on", NULL);
9201     } else if (cfg->seccompSandbox > 0) {
9202         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9203                        _("QEMU does not support seccomp sandboxes"));
9204         goto error;
9205     }
9206
9207     if (def->panic) {
9208         if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_PANIC)) {
9209             if (def->panic->info.addr.isa.iobase > 0) {
9210                 virCommandAddArg(cmd, "-device");
9211                 virCommandAddArgFormat(cmd, "pvpanic,ioport=%d",
9212                                        def->panic->info.addr.isa.iobase);
9213             } else {
9214                 virCommandAddArgList(cmd, "-device", "pvpanic", NULL);
9215             }
9216         } else {
9217             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9218                            _("your QEMU is too old to support pvpanic"));
9219             goto error;
9220         }
9221     }
9222
9223     if (mlock) {
9224         unsigned long long memKB;
9225
9226         /* VFIO requires all of the guest's memory to be
9227          * locked resident, plus some amount for IO
9228          * space. Alex Williamson suggested adding 1GiB for IO
9229          * space just to be safe (some finer tuning might be
9230          * nice, though).
9231          */
9232         memKB = def->mem.hard_limit ?
9233             def->mem.hard_limit : def->mem.max_balloon + 1024 * 1024;
9234         virCommandSetMaxMemLock(cmd, memKB * 1024);
9235     }
9236
9237     if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_MSG_TIMESTAMP) &&
9238         cfg->logTimestamp)
9239         virCommandAddArgList(cmd, "-msg", "timestamp=on", NULL);
9240
9241     virObjectUnref(cfg);
9242     return cmd;
9243
9244  error:
9245     virObjectUnref(cfg);
9246     /* free up any resources in the network driver
9247      * but don't overwrite the original error */
9248     originalError = virSaveLastError();
9249     for (i = 0; last_good_net != -1 && i <= last_good_net; i++)
9250         virDomainConfNWFilterTeardown(def->nets[i]);
9251     virSetError(originalError);
9252     virFreeError(originalError);
9253     virCommandFree(cmd);
9254     return NULL;
9255 }
9256
9257 /* This function generates the correct '-device' string for character
9258  * devices of each architecture.
9259  */
9260 static int
9261 qemuBuildSerialChrDeviceStr(char **deviceStr,
9262                             virDomainDefPtr def,
9263                             virDomainChrDefPtr serial,
9264                             virQEMUCapsPtr qemuCaps,
9265                             virArch arch,
9266                             char *machine)
9267 {
9268     virBuffer cmd = VIR_BUFFER_INITIALIZER;
9269
9270     if ((arch == VIR_ARCH_PPC64) && STREQ(machine, "pseries")) {
9271         if (serial->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL &&
9272             serial->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO) {
9273             virBufferAsprintf(&cmd, "spapr-vty,chardev=char%s",
9274                               serial->info.alias);
9275             if (qemuBuildDeviceAddressStr(&cmd, def, &serial->info, qemuCaps) < 0)
9276                 goto error;
9277         }
9278     } else {
9279         virBufferAsprintf(&cmd, "%s,chardev=char%s,id=%s",
9280                           virDomainChrSerialTargetTypeToString(serial->targetType),
9281                           serial->info.alias, serial->info.alias);
9282
9283         if (serial->targetType == VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_USB) {
9284             if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_USB_SERIAL)) {
9285                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9286                                _("usb-serial is not supported in this QEMU binary"));
9287                 goto error;
9288             }
9289
9290             if (serial->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
9291                 serial->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB) {
9292                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9293                                _("usb-serial requires address of usb type"));
9294                 goto error;
9295             }
9296
9297             if (qemuBuildDeviceAddressStr(&cmd, def, &serial->info, qemuCaps) < 0)
9298                 goto error;
9299         }
9300     }
9301
9302     if (virBufferError(&cmd)) {
9303         virReportOOMError();
9304         goto error;
9305     }
9306
9307     *deviceStr = virBufferContentAndReset(&cmd);
9308     return 0;
9309
9310  error:
9311     virBufferFreeAndReset(&cmd);
9312     return -1;
9313 }
9314
9315 static int
9316 qemuBuildParallelChrDeviceStr(char **deviceStr,
9317                               virDomainChrDefPtr chr)
9318 {
9319     if (virAsprintf(deviceStr, "isa-parallel,chardev=char%s,id=%s",
9320                     chr->info.alias, chr->info.alias) < 0) {
9321         virReportOOMError();
9322         return -1;
9323     }
9324     return 0;
9325 }
9326
9327 static int
9328 qemuBuildChannelChrDeviceStr(char **deviceStr,
9329                              virDomainChrDefPtr chr,
9330                              virQEMUCapsPtr qemuCaps)
9331 {
9332     int ret = -1;
9333     char *addr = NULL;
9334     int port;
9335
9336     switch ((enum virDomainChrChannelTargetType) chr->targetType) {
9337     case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_GUESTFWD:
9338
9339         addr = virSocketAddrFormat(chr->target.addr);
9340         if (!addr)
9341             return ret;
9342         port = virSocketAddrGetPort(chr->target.addr);
9343
9344         if (virAsprintf(deviceStr,
9345                         "user,guestfwd=tcp:%s:%i,chardev=char%s,id=user-%s",
9346                         addr, port, chr->info.alias, chr->info.alias) < 0) {
9347             virReportOOMError();
9348             goto cleanup;
9349         }
9350         break;
9351
9352     case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO:
9353         if (!(*deviceStr = qemuBuildVirtioSerialPortDevStr(chr, qemuCaps)))
9354                 goto cleanup;
9355         break;
9356
9357     case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_NONE:
9358     case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_LAST:
9359         return ret;
9360     }
9361
9362     ret = 0;
9363  cleanup:
9364     VIR_FREE(addr);
9365     return ret;
9366 }
9367
9368 static int
9369 qemuBuildConsoleChrDeviceStr(char **deviceStr,
9370                              virDomainChrDefPtr chr,
9371                              virQEMUCapsPtr qemuCaps)
9372 {
9373     int ret = -1;
9374
9375     switch ((enum virDomainChrConsoleTargetType) chr->targetType) {
9376     case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SCLP:
9377     case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SCLPLM:
9378         if (!(*deviceStr = qemuBuildSclpDevStr(chr)))
9379             goto cleanup;
9380         break;
9381
9382     case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_VIRTIO:
9383         if (!(*deviceStr = qemuBuildVirtioSerialPortDevStr(chr, qemuCaps)))
9384             goto cleanup;
9385         break;
9386
9387     case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL:
9388     case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_NONE:
9389     case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_XEN:
9390     case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_UML:
9391     case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_LXC:
9392     case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_OPENVZ:
9393     case VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_LAST:
9394         break;
9395     }
9396
9397     ret = 0;
9398  cleanup:
9399     return ret;
9400 }
9401
9402 int
9403 qemuBuildChrDeviceStr(char **deviceStr,
9404                       virDomainDefPtr vmdef,
9405                       virDomainChrDefPtr chr,
9406                       virQEMUCapsPtr qemuCaps)
9407 {
9408     int ret = -1;
9409
9410     switch ((enum virDomainChrDeviceType) chr->deviceType) {
9411     case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
9412         ret = qemuBuildSerialChrDeviceStr(deviceStr, vmdef, chr, qemuCaps,
9413                                           vmdef->os.arch,
9414                                           vmdef->os.machine);
9415         break;
9416
9417     case VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL:
9418         ret = qemuBuildParallelChrDeviceStr(deviceStr, chr);
9419         break;
9420
9421     case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
9422         ret = qemuBuildChannelChrDeviceStr(deviceStr, chr, qemuCaps);
9423         break;
9424
9425     case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
9426         ret = qemuBuildConsoleChrDeviceStr(deviceStr, chr, qemuCaps);
9427         break;
9428
9429     case VIR_DOMAIN_CHR_DEVICE_TYPE_LAST:
9430         return ret;
9431     }
9432
9433     return ret;
9434 }
9435
9436
9437 /*
9438  * This method takes a string representing a QEMU command line ARGV set
9439  * optionally prefixed by a list of environment variables. It then tries
9440  * to split it up into a NULL terminated list of env & argv, splitting
9441  * on space
9442  */
9443 static int qemuStringToArgvEnv(const char *args,
9444                                char ***retenv,
9445                                char ***retargv)
9446 {
9447     char **arglist = NULL;
9448     size_t argcount = 0;
9449     size_t argalloc = 0;
9450     size_t envend;
9451     size_t i;
9452     const char *curr = args;
9453     const char *start;
9454     char **progenv = NULL;
9455     char **progargv = NULL;
9456
9457     /* Iterate over string, splitting on sequences of ' ' */
9458     while (curr && *curr != '\0') {
9459         char *arg;
9460         const char *next;
9461
9462         start = curr;
9463         /* accept a space in CEPH_ARGS */
9464         if (STRPREFIX(curr, "CEPH_ARGS=-m ")) {
9465             start += strlen("CEPH_ARGS=-m ");
9466         }
9467         if (*start == '\'') {
9468             if (start == curr)
9469                 curr++;
9470             next = strchr(start + 1, '\'');
9471         } else if (*start == '"') {
9472             if (start == curr)
9473                 curr++;
9474             next = strchr(start + 1, '"');
9475         } else {
9476             next = strchr(start, ' ');
9477         }
9478         if (!next)
9479             next = strchr(curr, '\n');
9480
9481         if (VIR_STRNDUP(arg, curr, next ? next - curr : -1) < 0)
9482             goto error;
9483
9484         if (next && (*next == '\'' || *next == '"'))
9485             next++;
9486
9487         if (VIR_RESIZE_N(arglist, argalloc, argcount, 2) < 0) {
9488             VIR_FREE(arg);
9489             goto error;
9490         }
9491
9492         arglist[argcount++] = arg;
9493         arglist[argcount] = NULL;
9494
9495         while (next && c_isspace(*next))
9496             next++;
9497
9498         curr = next;
9499     }
9500
9501     /* Iterate over list of args, finding first arg not containing
9502      * the '=' character (eg, skip over env vars FOO=bar) */
9503     for (envend = 0; ((envend < argcount) &&
9504                        (strchr(arglist[envend], '=') != NULL));
9505          envend++)
9506         ; /* nada */
9507
9508     /* Copy the list of env vars */
9509     if (envend > 0) {
9510         if (VIR_REALLOC_N(progenv, envend+1) < 0)
9511             goto error;
9512         for (i = 0; i < envend; i++)
9513             progenv[i] = arglist[i];
9514         progenv[i] = NULL;
9515     }
9516
9517     /* Copy the list of argv */
9518     if (VIR_REALLOC_N(progargv, argcount-envend + 1) < 0)
9519         goto error;
9520     for (i = envend; i < argcount; i++)
9521         progargv[i-envend] = arglist[i];
9522     progargv[i-envend] = NULL;
9523
9524     VIR_FREE(arglist);
9525
9526     *retenv = progenv;
9527     *retargv = progargv;
9528
9529     return 0;
9530
9531  error:
9532     VIR_FREE(progenv);
9533     VIR_FREE(progargv);
9534     virStringFreeList(arglist);
9535     return -1;
9536 }
9537
9538
9539 /*
9540  * Search for a named env variable, and return the value part
9541  */
9542 static const char *qemuFindEnv(char **progenv,
9543                                const char *name)
9544 {
9545     size_t i;
9546     int len = strlen(name);
9547
9548     for (i = 0; progenv && progenv[i]; i++) {
9549         if (STREQLEN(progenv[i], name, len) &&
9550             progenv[i][len] == '=')
9551             return progenv[i] + len + 1;
9552     }
9553     return NULL;
9554 }
9555
9556 /*
9557  * Takes a string containing a set of key=value,key=value,key...
9558  * parameters and splits them up, returning two arrays with
9559  * the individual keys and values. If allowEmptyValue is nonzero,
9560  * the "=value" part is optional and if a key with no value is found,
9561  * NULL is be placed into corresponding place in retvalues.
9562  */
9563 int
9564 qemuParseKeywords(const char *str,
9565                   char ***retkeywords,
9566                   char ***retvalues,
9567                   int *retnkeywords,
9568                   int allowEmptyValue)
9569 {
9570     int keywordCount = 0;
9571     int keywordAlloc = 0;
9572     char **keywords = NULL;
9573     char **values = NULL;
9574     const char *start = str;
9575     const char *end;
9576     size_t i;
9577
9578     *retkeywords = NULL;
9579     *retvalues = NULL;
9580     *retnkeywords = 0;
9581     end = start + strlen(str);
9582
9583     while (start) {
9584         const char *separator;
9585         const char *endmark;
9586         char *keyword;
9587         char *value = NULL;
9588
9589         endmark = start;
9590         do {
9591             /* Qemu accepts ',,' as an escape for a literal comma;
9592              * skip past those here while searching for the end of the
9593              * value, then strip them down below */
9594             endmark = strchr(endmark, ',');
9595         } while (endmark && endmark[1] == ',' && (endmark += 2));
9596         if (!endmark)
9597             endmark = end;
9598         if (!(separator = strchr(start, '=')))
9599             separator = end;
9600
9601         if (separator >= endmark) {
9602             if (!allowEmptyValue) {
9603                 virReportError(VIR_ERR_INTERNAL_ERROR,
9604                                _("malformed keyword arguments in '%s'"), str);
9605                 goto error;
9606             }
9607             separator = endmark;
9608         }
9609
9610         if (VIR_STRNDUP(keyword, start, separator - start) < 0)
9611             goto error;
9612
9613         if (separator < endmark) {
9614             separator++;
9615             if (VIR_STRNDUP(value, separator, endmark - separator) < 0) {
9616                 VIR_FREE(keyword);
9617                 goto error;
9618             }
9619             if (strchr(value, ',')) {
9620                 char *p = strchr(value, ',') + 1;
9621                 char *q = p + 1;
9622                 while (*q) {
9623                     if (*q == ',')
9624                         q++;
9625                     *p++ = *q++;
9626                 }
9627                 *p = '\0';
9628             }
9629         }
9630
9631         if (keywordAlloc == keywordCount) {
9632             if (VIR_REALLOC_N(keywords, keywordAlloc + 10) < 0 ||
9633                 VIR_REALLOC_N(values, keywordAlloc + 10) < 0) {
9634                 VIR_FREE(keyword);
9635                 VIR_FREE(value);
9636                 goto error;
9637             }
9638             keywordAlloc += 10;
9639         }
9640
9641         keywords[keywordCount] = keyword;
9642         values[keywordCount] = value;
9643         keywordCount++;
9644
9645         start = endmark < end ? endmark + 1 : NULL;
9646     }
9647
9648     *retkeywords = keywords;
9649     *retvalues = values;
9650     *retnkeywords = keywordCount;
9651     return 0;
9652
9653  error:
9654     for (i = 0; i < keywordCount; i++) {
9655         VIR_FREE(keywords[i]);
9656         VIR_FREE(values[i]);
9657     }
9658     VIR_FREE(keywords);
9659     VIR_FREE(values);
9660     return -1;
9661 }
9662
9663 /*
9664  * Tries to parse new style QEMU -drive  args.
9665  *
9666  * eg -drive file=/dev/HostVG/VirtData1,if=ide,index=1
9667  *
9668  * Will fail if not using the 'index' keyword
9669  */
9670 static virDomainDiskDefPtr
9671 qemuParseCommandLineDisk(virDomainXMLOptionPtr xmlopt,
9672                          const char *val,
9673                          virDomainDefPtr dom,
9674                          int nvirtiodisk,
9675                          bool old_style_ceph_args)
9676 {
9677     virDomainDiskDefPtr def = NULL;
9678     char **keywords;
9679     char **values;
9680     int nkeywords;
9681     size_t i;
9682     int idx = -1;
9683     int busid = -1;
9684     int unitid = -1;
9685     int trans = VIR_DOMAIN_DISK_TRANS_DEFAULT;
9686
9687     if (qemuParseKeywords(val,
9688                           &keywords,
9689                           &values,
9690                           &nkeywords,
9691                           0) < 0)
9692         return NULL;
9693
9694     if (VIR_ALLOC(def) < 0)
9695         goto cleanup;
9696
9697     if (((dom->os.arch == VIR_ARCH_PPC64) &&
9698         dom->os.machine && STREQ(dom->os.machine, "pseries")))
9699         def->bus = VIR_DOMAIN_DISK_BUS_SCSI;
9700     else
9701        def->bus = VIR_DOMAIN_DISK_BUS_IDE;
9702     def->device = VIR_DOMAIN_DISK_DEVICE_DISK;
9703     def->src.type = VIR_STORAGE_TYPE_FILE;
9704
9705     for (i = 0; i < nkeywords; i++) {
9706         if (STREQ(keywords[i], "file")) {
9707             if (values[i] && STRNEQ(values[i], "")) {
9708                 def->src.path = values[i];
9709                 values[i] = NULL;
9710                 if (STRPREFIX(def->src.path, "/dev/"))
9711                     def->src.type = VIR_STORAGE_TYPE_BLOCK;
9712                 else if (STRPREFIX(def->src.path, "nbd:") ||
9713                          STRPREFIX(def->src.path, "nbd+")) {
9714                     def->src.type = VIR_STORAGE_TYPE_NETWORK;
9715                     def->src.protocol = VIR_STORAGE_NET_PROTOCOL_NBD;
9716
9717                     if (qemuParseNBDString(def) < 0)
9718                         goto error;
9719                 } else if (STRPREFIX(def->src.path, "rbd:")) {
9720                     char *p = def->src.path;
9721
9722                     def->src.type = VIR_STORAGE_TYPE_NETWORK;
9723                     def->src.protocol = VIR_STORAGE_NET_PROTOCOL_RBD;
9724                     if (VIR_STRDUP(def->src.path, p + strlen("rbd:")) < 0)
9725                         goto error;
9726                     /* old-style CEPH_ARGS env variable is parsed later */
9727                     if (!old_style_ceph_args && qemuParseRBDString(def) < 0) {
9728                         VIR_FREE(p);
9729                         goto error;
9730                     }
9731
9732                     VIR_FREE(p);
9733                 } else if (STRPREFIX(def->src.path, "gluster:") ||
9734                            STRPREFIX(def->src.path, "gluster+")) {
9735                     def->src.type = VIR_STORAGE_TYPE_NETWORK;
9736                     def->src.protocol = VIR_STORAGE_NET_PROTOCOL_GLUSTER;
9737
9738                     if (qemuParseGlusterString(def) < 0)
9739                         goto error;
9740                 } else if (STRPREFIX(def->src.path, "iscsi:")) {
9741                     def->src.type = VIR_STORAGE_TYPE_NETWORK;
9742                     def->src.protocol = VIR_STORAGE_NET_PROTOCOL_ISCSI;
9743
9744                     if (qemuParseISCSIString(def) < 0)
9745                         goto error;
9746                 } else if (STRPREFIX(def->src.path, "sheepdog:")) {
9747                     char *p = def->src.path;
9748                     char *port, *vdi;
9749
9750                     def->src.type = VIR_STORAGE_TYPE_NETWORK;
9751                     def->src.protocol = VIR_STORAGE_NET_PROTOCOL_SHEEPDOG;
9752                     if (VIR_STRDUP(def->src.path, p + strlen("sheepdog:")) < 0)
9753                         goto error;
9754                     VIR_FREE(p);
9755
9756                     /* def->src.path must be [vdiname] or [host]:[port]:[vdiname] */
9757                     port = strchr(def->src.path, ':');
9758                     if (port) {
9759                         *port = '\0';
9760                         vdi = strchr(port + 1, ':');
9761                         if (!vdi) {
9762                             *port = ':';
9763                             virReportError(VIR_ERR_INTERNAL_ERROR,
9764                                            _("cannot parse sheepdog filename '%s'"),
9765                                            def->src.path);
9766                             goto error;
9767                         }
9768                         port++;
9769                         *vdi++ = '\0';
9770                         if (VIR_ALLOC(def->src.hosts) < 0)
9771                             goto error;
9772                         def->src.nhosts = 1;
9773                         def->src.hosts->name = def->src.path;
9774                         if (VIR_STRDUP(def->src.hosts->port, port) < 0)
9775                             goto error;
9776                         def->src.hosts->transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
9777                         def->src.hosts->socket = NULL;
9778                         if (VIR_STRDUP(def->src.path, vdi) < 0)
9779                             goto error;
9780                     }
9781                 } else
9782                     def->src.type = VIR_STORAGE_TYPE_FILE;
9783             } else {
9784                 def->src.type = VIR_STORAGE_TYPE_FILE;
9785             }
9786         } else if (STREQ(keywords[i], "if")) {
9787             if (STREQ(values[i], "ide")) {
9788                 def->bus = VIR_DOMAIN_DISK_BUS_IDE;
9789                 if (((dom->os.arch == VIR_ARCH_PPC64) &&
9790                      dom->os.machine && STREQ(dom->os.machine, "pseries"))) {
9791                     virReportError(VIR_ERR_INTERNAL_ERROR,
9792                                    _("pseries systems do not support ide devices '%s'"), val);
9793                     goto error;
9794                 }
9795             } else if (STREQ(values[i], "scsi"))
9796                 def->bus = VIR_DOMAIN_DISK_BUS_SCSI;
9797             else if (STREQ(values[i], "virtio"))
9798                 def->bus = VIR_DOMAIN_DISK_BUS_VIRTIO;
9799             else if (STREQ(values[i], "xen"))
9800                 def->bus = VIR_DOMAIN_DISK_BUS_XEN;
9801             else if (STREQ(values[i], "sd"))
9802                 def->bus = VIR_DOMAIN_DISK_BUS_SD;
9803         } else if (STREQ(keywords[i], "media")) {
9804             if (STREQ(values[i], "cdrom")) {
9805                 def->device = VIR_DOMAIN_DISK_DEVICE_CDROM;
9806                 def->readonly = true;
9807             } else if (STREQ(values[i], "floppy"))
9808                 def->device = VIR_DOMAIN_DISK_DEVICE_FLOPPY;
9809         } else if (STREQ(keywords[i], "format")) {
9810             if (VIR_STRDUP(def->src.driverName, "qemu") < 0)
9811                 goto error;
9812             def->src.format = virStorageFileFormatTypeFromString(values[i]);
9813         } else if (STREQ(keywords[i], "cache")) {
9814             if (STREQ(values[i], "off") ||
9815                 STREQ(values[i], "none"))
9816                 def->cachemode = VIR_DOMAIN_DISK_CACHE_DISABLE;
9817             else if (STREQ(values[i], "writeback") ||
9818                      STREQ(values[i], "on"))
9819                 def->cachemode = VIR_DOMAIN_DISK_CACHE_WRITEBACK;
9820             else if (STREQ(values[i], "writethrough"))
9821                 def->cachemode = VIR_DOMAIN_DISK_CACHE_WRITETHRU;
9822             else if (STREQ(values[i], "directsync"))
9823                 def->cachemode = VIR_DOMAIN_DISK_CACHE_DIRECTSYNC;
9824             else if (STREQ(values[i], "unsafe"))
9825                 def->cachemode = VIR_DOMAIN_DISK_CACHE_UNSAFE;
9826         } else if (STREQ(keywords[i], "werror")) {
9827             if (STREQ(values[i], "stop"))
9828                 def->error_policy = VIR_DOMAIN_DISK_ERROR_POLICY_STOP;
9829             else if (STREQ(values[i], "report"))
9830                 def->error_policy = VIR_DOMAIN_DISK_ERROR_POLICY_REPORT;
9831             else if (STREQ(values[i], "ignore"))
9832                 def->error_policy = VIR_DOMAIN_DISK_ERROR_POLICY_IGNORE;
9833             else if (STREQ(values[i], "enospc"))
9834                 def->error_policy = VIR_DOMAIN_DISK_ERROR_POLICY_ENOSPACE;
9835         } else if (STREQ(keywords[i], "rerror")) {
9836             if (STREQ(values[i], "stop"))
9837                 def->rerror_policy = VIR_DOMAIN_DISK_ERROR_POLICY_STOP;
9838             else if (STREQ(values[i], "report"))
9839                 def->rerror_policy = VIR_DOMAIN_DISK_ERROR_POLICY_REPORT;
9840             else if (STREQ(values[i], "ignore"))
9841                 def->rerror_policy = VIR_DOMAIN_DISK_ERROR_POLICY_IGNORE;
9842         } else if (STREQ(keywords[i], "index")) {
9843             if (virStrToLong_i(values[i], NULL, 10, &idx) < 0) {
9844                 virReportError(VIR_ERR_INTERNAL_ERROR,
9845                                _("cannot parse drive index '%s'"), val);
9846                 goto error;
9847             }
9848         } else if (STREQ(keywords[i], "bus")) {
9849             if (virStrToLong_i(values[i], NULL, 10, &busid) < 0) {
9850                 virReportError(VIR_ERR_INTERNAL_ERROR,
9851                                _("cannot parse drive bus '%s'"), val);
9852                 goto error;
9853             }
9854         } else if (STREQ(keywords[i], "unit")) {
9855             if (virStrToLong_i(values[i], NULL, 10, &unitid) < 0) {
9856                 virReportError(VIR_ERR_INTERNAL_ERROR,
9857                                _("cannot parse drive unit '%s'"), val);
9858                 goto error;
9859             }
9860         } else if (STREQ(keywords[i], "readonly")) {
9861             if ((values[i] == NULL) || STREQ(values[i], "on"))
9862                 def->readonly = true;
9863         } else if (STREQ(keywords[i], "aio")) {
9864             if ((def->iomode = virDomainDiskIoTypeFromString(values[i])) < 0) {
9865                 virReportError(VIR_ERR_INTERNAL_ERROR,
9866                                _("cannot parse io mode '%s'"), values[i]);
9867                 goto error;
9868             }
9869         } else if (STREQ(keywords[i], "cyls")) {
9870             if (virStrToLong_ui(values[i], NULL, 10,
9871                                 &(def->geometry.cylinders)) < 0) {
9872                 virDomainDiskDefFree(def);
9873                 def = NULL;
9874                 virReportError(VIR_ERR_INTERNAL_ERROR,
9875                                _("cannot parse cylinders value'%s'"),
9876                                values[i]);
9877                 goto error;
9878             }
9879         } else if (STREQ(keywords[i], "heads")) {
9880             if (virStrToLong_ui(values[i], NULL, 10,
9881                                 &(def->geometry.heads)) < 0) {
9882                 virDomainDiskDefFree(def);
9883                 def = NULL;
9884                 virReportError(VIR_ERR_INTERNAL_ERROR,
9885                                _("cannot parse heads value'%s'"),
9886                                values[i]);
9887                 goto error;
9888             }
9889         } else if (STREQ(keywords[i], "secs")) {
9890             if (virStrToLong_ui(values[i], NULL, 10,
9891                                 &(def->geometry.sectors)) < 0) {
9892                 virDomainDiskDefFree(def);
9893                 def = NULL;
9894                 virReportError(VIR_ERR_INTERNAL_ERROR,
9895                                _("cannot parse sectors value'%s'"),
9896                                values[i]);
9897                 goto error;
9898             }
9899         } else if (STREQ(keywords[i], "trans")) {
9900             def->geometry.trans =
9901                 virDomainDiskGeometryTransTypeFromString(values[i]);
9902             if ((trans < VIR_DOMAIN_DISK_TRANS_DEFAULT) ||
9903                 (trans >= VIR_DOMAIN_DISK_TRANS_LAST)) {
9904                 virDomainDiskDefFree(def);
9905                 def = NULL;
9906                 virReportError(VIR_ERR_INTERNAL_ERROR,
9907                                _("cannot parse translation value'%s'"),
9908                                values[i]);
9909                 goto error;
9910             }
9911         }
9912     }
9913
9914     if (def->rerror_policy == def->error_policy)
9915         def->rerror_policy = 0;
9916
9917     if (!def->src.path &&
9918         def->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
9919         def->src.type != VIR_STORAGE_TYPE_NETWORK) {
9920         virReportError(VIR_ERR_INTERNAL_ERROR,
9921                        _("missing file parameter in drive '%s'"), val);
9922         goto error;
9923     }
9924     if (idx == -1 &&
9925         def->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
9926         idx = nvirtiodisk;
9927
9928     if (idx == -1 &&
9929         unitid == -1 &&
9930         busid == -1) {
9931         virReportError(VIR_ERR_INTERNAL_ERROR,
9932                        _("missing index/unit/bus parameter in drive '%s'"),
9933                        val);
9934         goto error;
9935     }
9936
9937     if (idx == -1) {
9938         if (unitid == -1)
9939             unitid = 0;
9940         if (busid == -1)
9941             busid = 0;
9942         switch (def->bus) {
9943         case VIR_DOMAIN_DISK_BUS_IDE:
9944             idx = (busid * 2) + unitid;
9945             break;
9946         case VIR_DOMAIN_DISK_BUS_SCSI:
9947             idx = (busid * 7) + unitid;
9948             break;
9949         default:
9950             idx = unitid;
9951             break;
9952         }
9953     }
9954
9955     if (def->bus == VIR_DOMAIN_DISK_BUS_IDE) {
9956         ignore_value(VIR_STRDUP(def->dst, "hda"));
9957     } else if (def->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
9958                def->bus == VIR_DOMAIN_DISK_BUS_SD) {
9959         ignore_value(VIR_STRDUP(def->dst, "sda"));
9960     } else if (def->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
9961         ignore_value(VIR_STRDUP(def->dst, "vda"));
9962     } else if (def->bus == VIR_DOMAIN_DISK_BUS_XEN) {
9963         ignore_value(VIR_STRDUP(def->dst, "xvda"));
9964     } else {
9965         ignore_value(VIR_STRDUP(def->dst, "hda"));
9966     }
9967
9968     if (!def->dst)
9969         goto error;
9970     if (STREQ(def->dst, "xvda"))
9971         def->dst[3] = 'a' + idx;
9972     else
9973         def->dst[2] = 'a' + idx;
9974
9975     if (virDomainDiskDefAssignAddress(xmlopt, def) < 0) {
9976         virReportError(VIR_ERR_INTERNAL_ERROR,
9977                        _("invalid device name '%s'"), def->dst);
9978         virDomainDiskDefFree(def);
9979         def = NULL;
9980         goto cleanup;
9981     }
9982
9983  cleanup:
9984     for (i = 0; i < nkeywords; i++) {
9985         VIR_FREE(keywords[i]);
9986         VIR_FREE(values[i]);
9987     }
9988     VIR_FREE(keywords);
9989     VIR_FREE(values);
9990     return def;
9991
9992  error:
9993     virDomainDiskDefFree(def);
9994     def = NULL;
9995     goto cleanup;
9996 }
9997
9998 /*
9999  * Tries to find a NIC definition matching a vlan we want
10000  */
10001 static const char *
10002 qemuFindNICForVLAN(int nnics,
10003                    const char **nics,
10004                    int wantvlan)
10005 {
10006     size_t i;
10007     for (i = 0; i < nnics; i++) {
10008         int gotvlan;
10009         const char *tmp = strstr(nics[i], "vlan=");
10010         char *end;
10011         if (!tmp)
10012             continue;
10013
10014         tmp += strlen("vlan=");
10015
10016         if (virStrToLong_i(tmp, &end, 10, &gotvlan) < 0) {
10017             virReportError(VIR_ERR_INTERNAL_ERROR,
10018                            _("cannot parse NIC vlan in '%s'"), nics[i]);
10019             return NULL;
10020         }
10021
10022         if (gotvlan == wantvlan)
10023             return nics[i];
10024     }
10025
10026     if (wantvlan == 0 && nnics > 0)
10027         return nics[0];
10028
10029     virReportError(VIR_ERR_INTERNAL_ERROR,
10030                    _("cannot find NIC definition for vlan %d"), wantvlan);
10031     return NULL;
10032 }
10033
10034
10035 /*
10036  * Tries to parse a QEMU -net backend argument. Gets given
10037  * a list of all known -net frontend arguments to try and
10038  * match up against. Horribly complicated stuff
10039  */
10040 static virDomainNetDefPtr
10041 qemuParseCommandLineNet(virDomainXMLOptionPtr xmlopt,
10042                         const char *val,
10043                         int nnics,
10044                         const char **nics)
10045 {
10046     virDomainNetDefPtr def = NULL;
10047     char **keywords = NULL;
10048     char **values = NULL;
10049     int nkeywords;
10050     const char *nic;
10051     int wantvlan = 0;
10052     const char *tmp;
10053     bool genmac = true;
10054     size_t i;
10055
10056     tmp = strchr(val, ',');
10057
10058     if (tmp) {
10059         if (qemuParseKeywords(tmp+1,
10060                               &keywords,
10061                               &values,
10062                               &nkeywords,
10063                               0) < 0)
10064             return NULL;
10065     } else {
10066         nkeywords = 0;
10067     }
10068
10069     if (VIR_ALLOC(def) < 0)
10070         goto cleanup;
10071
10072     /* 'tap' could turn into libvirt type=ethernet, type=bridge or
10073      * type=network, but we can't tell, so use the generic config */
10074     if (STRPREFIX(val, "tap,"))
10075         def->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
10076     else if (STRPREFIX(val, "socket"))
10077         def->type = VIR_DOMAIN_NET_TYPE_CLIENT;
10078     else if (STRPREFIX(val, "user"))
10079         def->type = VIR_DOMAIN_NET_TYPE_USER;
10080     else
10081         def->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
10082
10083     for (i = 0; i < nkeywords; i++) {
10084         if (STREQ(keywords[i], "vlan")) {
10085             if (virStrToLong_i(values[i], NULL, 10, &wantvlan) < 0) {
10086                 virReportError(VIR_ERR_INTERNAL_ERROR,
10087                                _("cannot parse vlan in '%s'"), val);
10088                 virDomainNetDefFree(def);
10089                 def = NULL;
10090                 goto cleanup;
10091             }
10092         } else if (def->type == VIR_DOMAIN_NET_TYPE_ETHERNET &&
10093                    STREQ(keywords[i], "script") && STRNEQ(values[i], "")) {
10094             def->script = values[i];
10095             values[i] = NULL;
10096         } else if (def->type == VIR_DOMAIN_NET_TYPE_ETHERNET &&
10097                    STREQ(keywords[i], "ifname")) {
10098             def->ifname = values[i];
10099             values[i] = NULL;
10100         }
10101     }
10102
10103
10104     /* Done parsing the nic backend. Now to try and find corresponding
10105      * frontend, based off vlan number. NB this assumes a 1-1 mapping
10106      */
10107
10108     nic = qemuFindNICForVLAN(nnics, nics, wantvlan);
10109     if (!nic) {
10110         virDomainNetDefFree(def);
10111         def = NULL;
10112         goto cleanup;
10113     }
10114
10115     if (!STRPREFIX(nic, "nic")) {
10116         virReportError(VIR_ERR_INTERNAL_ERROR,
10117                        _("cannot parse NIC definition '%s'"), nic);
10118         virDomainNetDefFree(def);
10119         def = NULL;
10120         goto cleanup;
10121     }
10122
10123     for (i = 0; i < nkeywords; i++) {
10124         VIR_FREE(keywords[i]);
10125         VIR_FREE(values[i]);
10126     }
10127     VIR_FREE(keywords);
10128     VIR_FREE(values);
10129
10130     if (STRPREFIX(nic, "nic,")) {
10131         if (qemuParseKeywords(nic + strlen("nic,"),
10132                               &keywords,
10133                               &values,
10134                               &nkeywords,
10135                               0) < 0) {
10136             virDomainNetDefFree(def);
10137             def = NULL;
10138             goto cleanup;
10139         }
10140     } else {
10141         nkeywords = 0;
10142     }
10143
10144     for (i = 0; i < nkeywords; i++) {
10145         if (STREQ(keywords[i], "macaddr")) {
10146             genmac = false;
10147             if (virMacAddrParse(values[i], &def->mac) < 0) {
10148                 virReportError(VIR_ERR_INTERNAL_ERROR,
10149                                _("unable to parse mac address '%s'"),
10150                                values[i]);
10151                 virDomainNetDefFree(def);
10152                 def = NULL;
10153                 goto cleanup;
10154             }
10155         } else if (STREQ(keywords[i], "model")) {
10156             def->model = values[i];
10157             values[i] = NULL;
10158         } else if (STREQ(keywords[i], "vhost")) {
10159             if ((values[i] == NULL) || STREQ(values[i], "on")) {
10160                 def->driver.virtio.name = VIR_DOMAIN_NET_BACKEND_TYPE_VHOST;
10161             } else if (STREQ(keywords[i], "off")) {
10162                 def->driver.virtio.name = VIR_DOMAIN_NET_BACKEND_TYPE_QEMU;
10163             }
10164         } else if (STREQ(keywords[i], "sndbuf") && values[i]) {
10165             if (virStrToLong_ul(values[i], NULL, 10, &def->tune.sndbuf) < 0) {
10166                 virReportError(VIR_ERR_INTERNAL_ERROR,
10167                                _("cannot parse sndbuf size in '%s'"), val);
10168                 virDomainNetDefFree(def);
10169                 def = NULL;
10170                 goto cleanup;
10171             }
10172             def->tune.sndbuf_specified = true;
10173         }
10174     }
10175
10176     if (genmac)
10177         virDomainNetGenerateMAC(xmlopt, &def->mac);
10178
10179  cleanup:
10180     for (i = 0; i < nkeywords; i++) {
10181         VIR_FREE(keywords[i]);
10182         VIR_FREE(values[i]);
10183     }
10184     VIR_FREE(keywords);
10185     VIR_FREE(values);
10186     return def;
10187 }
10188
10189
10190 /*
10191  * Tries to parse a QEMU PCI device
10192  */
10193 static virDomainHostdevDefPtr
10194 qemuParseCommandLinePCI(const char *val)
10195 {
10196     int bus = 0, slot = 0, func = 0;
10197     const char *start;
10198     char *end;
10199     virDomainHostdevDefPtr def = virDomainHostdevDefAlloc();
10200
10201     if (!def)
10202        goto error;
10203
10204     if (!STRPREFIX(val, "host=")) {
10205         virReportError(VIR_ERR_INTERNAL_ERROR,
10206                        _("unknown PCI device syntax '%s'"), val);
10207         goto error;
10208     }
10209
10210     start = val + strlen("host=");
10211     if (virStrToLong_i(start, &end, 16, &bus) < 0 || *end != ':') {
10212         virReportError(VIR_ERR_INTERNAL_ERROR,
10213                        _("cannot extract PCI device bus '%s'"), val);
10214         goto error;
10215     }
10216     start = end + 1;
10217     if (virStrToLong_i(start, &end, 16, &slot) < 0 || *end != '.') {
10218         virReportError(VIR_ERR_INTERNAL_ERROR,
10219                        _("cannot extract PCI device slot '%s'"), val);
10220         goto error;
10221     }
10222     start = end + 1;
10223     if (virStrToLong_i(start, NULL, 16, &func) < 0) {
10224         virReportError(VIR_ERR_INTERNAL_ERROR,
10225                        _("cannot extract PCI device function '%s'"), val);
10226         goto error;
10227     }
10228
10229     def->mode = VIR_DOMAIN_HOSTDEV_MODE_SUBSYS;
10230     def->managed = true;
10231     def->source.subsys.type = VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI;
10232     def->source.subsys.u.pci.addr.bus = bus;
10233     def->source.subsys.u.pci.addr.slot = slot;
10234     def->source.subsys.u.pci.addr.function = func;
10235     return def;
10236
10237  error:
10238     virDomainHostdevDefFree(def);
10239     return NULL;
10240 }
10241
10242
10243 /*
10244  * Tries to parse a QEMU USB device
10245  */
10246 static virDomainHostdevDefPtr
10247 qemuParseCommandLineUSB(const char *val)
10248 {
10249     virDomainHostdevDefPtr def = virDomainHostdevDefAlloc();
10250     int first = 0, second = 0;
10251     const char *start;
10252     char *end;
10253
10254     if (!def)
10255        goto error;
10256
10257     if (!STRPREFIX(val, "host:")) {
10258         virReportError(VIR_ERR_INTERNAL_ERROR,
10259                        _("unknown USB device syntax '%s'"), val);
10260         goto error;
10261     }
10262
10263     start = val + strlen("host:");
10264     if (strchr(start, ':')) {
10265         if (virStrToLong_i(start, &end, 16, &first) < 0 || *end != ':') {
10266             virReportError(VIR_ERR_INTERNAL_ERROR,
10267                            _("cannot extract USB device vendor '%s'"), val);
10268             goto error;
10269         }
10270         start = end + 1;
10271         if (virStrToLong_i(start, NULL, 16, &second) < 0) {
10272             virReportError(VIR_ERR_INTERNAL_ERROR,
10273                            _("cannot extract USB device product '%s'"), val);
10274             goto error;
10275         }
10276     } else {
10277         if (virStrToLong_i(start, &end, 10, &first) < 0 || *end != '.') {
10278             virReportError(VIR_ERR_INTERNAL_ERROR,
10279                            _("cannot extract USB device bus '%s'"), val);
10280             goto error;
10281         }
10282         start = end + 1;
10283         if (virStrToLong_i(start, NULL, 10, &second) < 0) {
10284             virReportError(VIR_ERR_INTERNAL_ERROR,
10285                            _("cannot extract USB device address '%s'"), val);
10286             goto error;
10287         }
10288     }
10289
10290     def->mode = VIR_DOMAIN_HOSTDEV_MODE_SUBSYS;
10291     def->managed = false;
10292     def->source.subsys.type = VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB;
10293     if (*end == '.') {
10294         def->source.subsys.u.usb.bus = first;
10295         def->source.subsys.u.usb.device = second;
10296     } else {
10297         def->source.subsys.u.usb.vendor = first;
10298         def->source.subsys.u.usb.product = second;
10299     }
10300     return def;
10301
10302  error:
10303     virDomainHostdevDefFree(def);
10304     return NULL;
10305 }
10306
10307
10308 /*
10309  * Tries to parse a QEMU serial/parallel device
10310  */
10311 static int
10312 qemuParseCommandLineChr(virDomainChrSourceDefPtr source,
10313                         const char *val)
10314 {
10315     if (STREQ(val, "null")) {
10316         source->type = VIR_DOMAIN_CHR_TYPE_NULL;
10317     } else if (STREQ(val, "vc")) {
10318         source->type = VIR_DOMAIN_CHR_TYPE_VC;
10319     } else if (STREQ(val, "pty")) {
10320         source->type = VIR_DOMAIN_CHR_TYPE_PTY;
10321     } else if (STRPREFIX(val, "file:")) {
10322         source->type = VIR_DOMAIN_CHR_TYPE_FILE;
10323         if (VIR_STRDUP(source->data.file.path, val + strlen("file:")) < 0)
10324             goto error;
10325     } else if (STRPREFIX(val, "pipe:")) {
10326         source->type = VIR_DOMAIN_CHR_TYPE_PIPE;
10327         if (VIR_STRDUP(source->data.file.path, val + strlen("pipe:")) < 0)
10328             goto error;
10329     } else if (STREQ(val, "stdio")) {
10330         source->type = VIR_DOMAIN_CHR_TYPE_STDIO;
10331     } else if (STRPREFIX(val, "udp:")) {
10332         const char *svc1, *host2, *svc2;
10333         source->type = VIR_DOMAIN_CHR_TYPE_UDP;
10334         val += strlen("udp:");
10335         svc1 = strchr(val, ':');
10336         host2 = svc1 ? strchr(svc1, '@') : NULL;
10337         svc2 = host2 ? strchr(host2, ':') : NULL;
10338
10339         if (svc1 && svc1 != val &&
10340             VIR_STRNDUP(source->data.udp.connectHost, val, svc1 - val) < 0)
10341             goto error;
10342
10343         if (svc1) {
10344             svc1++;
10345             if (VIR_STRNDUP(source->data.udp.connectService, svc1,
10346                             host2 ? host2 - svc1 : strlen(svc1)) < 0)
10347                 goto error;
10348         }
10349
10350         if (host2) {
10351             host2++;
10352             if (svc2 && svc2 != host2 &&
10353                 VIR_STRNDUP(source->data.udp.bindHost, host2, svc2 - host2) < 0)
10354                 goto error;
10355         }
10356
10357         if (svc2) {
10358             svc2++;
10359             if (STRNEQ(svc2, "0")) {
10360                 if (VIR_STRDUP(source->data.udp.bindService, svc2) < 0)
10361                     goto error;
10362             }
10363         }
10364     } else if (STRPREFIX(val, "tcp:") ||
10365                STRPREFIX(val, "telnet:")) {
10366         const char *opt, *svc;
10367         source->type = VIR_DOMAIN_CHR_TYPE_TCP;
10368         if (STRPREFIX(val, "tcp:")) {
10369             val += strlen("tcp:");
10370         } else {
10371             val += strlen("telnet:");
10372             source->data.tcp.protocol = VIR_DOMAIN_CHR_TCP_PROTOCOL_TELNET;
10373         }
10374         svc = strchr(val, ':');
10375         if (!svc) {
10376             virReportError(VIR_ERR_INTERNAL_ERROR,
10377                            _("cannot find port number in character device %s"), val);
10378             goto error;
10379         }
10380         opt = strchr(svc, ',');
10381         if (opt && strstr(opt, "server"))
10382             source->data.tcp.listen = true;
10383
10384         if (VIR_STRNDUP(source->data.tcp.host, val, svc - val) < 0)
10385             goto error;
10386         svc++;
10387         if (VIR_STRNDUP(source->data.tcp.service, svc, opt ? opt - svc : -1) < 0)
10388             goto error;
10389     } else if (STRPREFIX(val, "unix:")) {
10390         const char *opt;
10391         val += strlen("unix:");
10392         opt = strchr(val, ',');
10393         source->type = VIR_DOMAIN_CHR_TYPE_UNIX;
10394         if (VIR_STRNDUP(source->data.nix.path, val, opt ? opt - val : -1) < 0)
10395             goto error;
10396
10397     } else if (STRPREFIX(val, "/dev")) {
10398         source->type = VIR_DOMAIN_CHR_TYPE_DEV;
10399         if (VIR_STRDUP(source->data.file.path, val) < 0)
10400             goto error;
10401     } else {
10402         virReportError(VIR_ERR_INTERNAL_ERROR,
10403                        _("unknown character device syntax %s"), val);
10404         goto error;
10405     }
10406
10407     return 0;
10408
10409  error:
10410     return -1;
10411 }
10412
10413
10414 static virCPUDefPtr
10415 qemuInitGuestCPU(virDomainDefPtr dom)
10416 {
10417     if (!dom->cpu) {
10418         virCPUDefPtr cpu;
10419
10420         if (VIR_ALLOC(cpu) < 0)
10421             return NULL;
10422
10423         cpu->type = VIR_CPU_TYPE_GUEST;
10424         cpu->match = VIR_CPU_MATCH_EXACT;
10425         dom->cpu = cpu;
10426     }
10427
10428     return dom->cpu;
10429 }
10430
10431
10432 static int
10433 qemuParseCommandLineCPU(virDomainDefPtr dom,
10434                         const char *val)
10435 {
10436     virCPUDefPtr cpu = NULL;
10437     char **tokens;
10438     char **hv_tokens = NULL;
10439     char *model = NULL;
10440     int ret = -1;
10441     size_t i;
10442
10443     if (!(tokens = virStringSplit(val, ",", 0)))
10444         goto cleanup;
10445
10446     if (tokens[0] == NULL)
10447         goto syntax;
10448
10449     for (i = 0; tokens[i] != NULL; i++) {
10450         if (*tokens[i] == '\0')
10451             goto syntax;
10452
10453         if (i == 0) {
10454             if (VIR_STRDUP(model, tokens[i]) < 0)
10455                 goto cleanup;
10456
10457             if (!STREQ(model, "qemu32") && !STREQ(model, "qemu64")) {
10458                 if (!(cpu = qemuInitGuestCPU(dom)))
10459                     goto cleanup;
10460
10461                 cpu->model = model;
10462                 model = NULL;
10463             }
10464         } else if (*tokens[i] == '+' || *tokens[i] == '-') {
10465             const char *feature = tokens[i] + 1; /* '+' or '-' */
10466             int policy;
10467
10468             if (*tokens[i] == '+')
10469                 policy = VIR_CPU_FEATURE_REQUIRE;
10470             else
10471                 policy = VIR_CPU_FEATURE_DISABLE;
10472
10473             if (*feature == '\0')
10474                 goto syntax;
10475
10476             if (dom->os.arch != VIR_ARCH_X86_64 &&
10477                 dom->os.arch != VIR_ARCH_I686) {
10478                 virReportError(VIR_ERR_INTERNAL_ERROR,
10479                                _("%s platform doesn't support CPU features'"),
10480                                virArchToString(dom->os.arch));
10481                 goto cleanup;
10482              }
10483
10484             if (STREQ(feature, "kvmclock")) {
10485                 bool present = (policy == VIR_CPU_FEATURE_REQUIRE);
10486                 size_t j;
10487
10488                 for (j = 0; j < dom->clock.ntimers; j++) {
10489                     if (dom->clock.timers[j]->name == VIR_DOMAIN_TIMER_NAME_KVMCLOCK)
10490                         break;
10491                 }
10492
10493                 if (j == dom->clock.ntimers) {
10494                     virDomainTimerDefPtr timer;
10495                     if (VIR_ALLOC(timer) < 0 ||
10496                         VIR_APPEND_ELEMENT_COPY(dom->clock.timers,
10497                                                 dom->clock.ntimers, timer) < 0) {
10498                         VIR_FREE(timer);
10499                         goto cleanup;
10500                     }
10501                     timer->name = VIR_DOMAIN_TIMER_NAME_KVMCLOCK;
10502                     timer->present = present;
10503                     timer->tickpolicy = -1;
10504                     timer->track = -1;
10505                     timer->mode = -1;
10506                 } else if (dom->clock.timers[j]->present != -1 &&
10507                     dom->clock.timers[j]->present != present) {
10508                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10509                                    _("conflicting occurrences of kvmclock feature"));
10510                     goto cleanup;
10511                 }
10512             } else if (STREQ(feature, "kvm_pv_eoi")) {
10513                 if (policy == VIR_CPU_FEATURE_REQUIRE)
10514                     dom->apic_eoi = VIR_DOMAIN_FEATURE_STATE_ON;
10515                 else
10516                     dom->apic_eoi = VIR_DOMAIN_FEATURE_STATE_OFF;
10517             } else {
10518                 if (!cpu) {
10519                     if (!(cpu = qemuInitGuestCPU(dom)))
10520                         goto cleanup;
10521
10522                     cpu->model = model;
10523                     model = NULL;
10524                 }
10525
10526                 if (virCPUDefAddFeature(cpu, feature, policy) < 0)
10527                     goto cleanup;
10528             }
10529         } else if (STRPREFIX(tokens[i], "hv_")) {
10530             const char *token = tokens[i] + 3; /* "hv_" */
10531             const char *feature, *value;
10532             int f;
10533
10534             if (*token == '\0')
10535                 goto syntax;
10536
10537             if (!(hv_tokens = virStringSplit(token, "=", 2)))
10538                 goto cleanup;
10539
10540             feature = hv_tokens[0];
10541             value = hv_tokens[1];
10542
10543             if (*feature == '\0')
10544                 goto syntax;
10545
10546             dom->features[VIR_DOMAIN_FEATURE_HYPERV] = VIR_DOMAIN_FEATURE_STATE_ON;
10547
10548             if ((f = virDomainHypervTypeFromString(feature)) < 0) {
10549                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10550                                _("unsupported HyperV Enlightenment feature "
10551                                  "'%s'"), feature);
10552                 goto cleanup;
10553             }
10554
10555             switch ((enum virDomainHyperv) f) {
10556             case VIR_DOMAIN_HYPERV_RELAXED:
10557             case VIR_DOMAIN_HYPERV_VAPIC:
10558                 if (value) {
10559                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10560                                    _("HyperV feature '%s' should not "
10561                                      "have a value"), feature);
10562                     goto cleanup;
10563                 }
10564                 dom->hyperv_features[f] = VIR_DOMAIN_FEATURE_STATE_ON;
10565                 break;
10566
10567             case VIR_DOMAIN_HYPERV_SPINLOCKS:
10568                 dom->hyperv_features[f] = VIR_DOMAIN_FEATURE_STATE_ON;
10569                 if (!value) {
10570                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10571                                    _("missing HyperV spinlock retry count"));
10572                     goto cleanup;
10573                 }
10574
10575                 if (virStrToLong_ui(value, NULL, 0, &dom->hyperv_spinlocks) < 0) {
10576                     virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10577                                    _("cannot parse HyperV spinlock retry count"));
10578                     goto cleanup;
10579                 }
10580
10581                 if (dom->hyperv_spinlocks < 0xFFF)
10582                     dom->hyperv_spinlocks = 0xFFF;
10583                 break;
10584
10585             case VIR_DOMAIN_HYPERV_LAST:
10586                 break;
10587             }
10588             virStringFreeList(hv_tokens);
10589             hv_tokens = NULL;
10590         }
10591     }
10592
10593     if (dom->os.arch == VIR_ARCH_X86_64) {
10594         bool is_32bit = false;
10595         if (cpu) {
10596             virCPUDataPtr cpuData = NULL;
10597
10598             if (cpuEncode(VIR_ARCH_X86_64, cpu, NULL, &cpuData,
10599                           NULL, NULL, NULL, NULL) < 0)
10600                 goto cleanup;
10601
10602             is_32bit = (cpuHasFeature(cpuData, "lm") != 1);
10603             cpuDataFree(cpuData);
10604         } else if (model) {
10605             is_32bit = STREQ(model, "qemu32");
10606         }
10607
10608         if (is_32bit)
10609             dom->os.arch = VIR_ARCH_I686;
10610     }
10611
10612     ret = 0;
10613
10614  cleanup:
10615     VIR_FREE(model);
10616     virStringFreeList(tokens);
10617     virStringFreeList(hv_tokens);
10618     return ret;
10619
10620  syntax:
10621     virReportError(VIR_ERR_INTERNAL_ERROR,
10622                    _("unknown CPU syntax '%s'"), val);
10623     goto cleanup;
10624 }
10625
10626
10627 static int
10628 qemuParseCommandLineSmp(virDomainDefPtr dom,
10629                         const char *val)
10630 {
10631     unsigned int sockets = 0;
10632     unsigned int cores = 0;
10633     unsigned int threads = 0;
10634     unsigned int maxcpus = 0;
10635     size_t i;
10636     int nkws;
10637     char **kws;
10638     char **vals;
10639     int n;
10640     char *end;
10641     int ret;
10642
10643     if (qemuParseKeywords(val, &kws, &vals, &nkws, 1) < 0)
10644         return -1;
10645
10646     for (i = 0; i < nkws; i++) {
10647         if (vals[i] == NULL) {
10648             if (i > 0 ||
10649                 virStrToLong_i(kws[i], &end, 10, &n) < 0 || *end != '\0')
10650                 goto syntax;
10651             dom->vcpus = n;
10652         } else {
10653             if (virStrToLong_i(vals[i], &end, 10, &n) < 0 || *end != '\0')
10654                 goto syntax;
10655             if (STREQ(kws[i], "sockets"))
10656                 sockets = n;
10657             else if (STREQ(kws[i], "cores"))
10658                 cores = n;
10659             else if (STREQ(kws[i], "threads"))
10660                 threads = n;
10661             else if (STREQ(kws[i], "maxcpus"))
10662                 maxcpus = n;
10663             else
10664                 goto syntax;
10665         }
10666     }
10667
10668     dom->maxvcpus = maxcpus ? maxcpus : dom->vcpus;
10669
10670     if (sockets && cores && threads) {
10671         virCPUDefPtr cpu;
10672
10673         if (!(cpu = qemuInitGuestCPU(dom)))
10674             goto error;
10675         cpu->sockets = sockets;
10676         cpu->cores = cores;
10677         cpu->threads = threads;
10678     } else if (sockets || cores || threads)
10679         goto syntax;
10680
10681     ret = 0;
10682
10683  cleanup:
10684     for (i = 0; i < nkws; i++) {
10685         VIR_FREE(kws[i]);
10686         VIR_FREE(vals[i]);
10687     }
10688     VIR_FREE(kws);
10689     VIR_FREE(vals);
10690
10691     return ret;
10692
10693  syntax:
10694     virReportError(VIR_ERR_INTERNAL_ERROR,
10695                    _("cannot parse CPU topology '%s'"), val);
10696  error:
10697     ret = -1;
10698     goto cleanup;
10699 }
10700
10701
10702 static void
10703 qemuParseCommandLineBootDevs(virDomainDefPtr def, const char *str)
10704 {
10705     int n, b = 0;
10706
10707     for (n = 0; str[n] && b < VIR_DOMAIN_BOOT_LAST; n++) {
10708         if (str[n] == 'a')
10709             def->os.bootDevs[b++] = VIR_DOMAIN_BOOT_FLOPPY;
10710         else if (str[n] == 'c')
10711             def->os.bootDevs[b++] = VIR_DOMAIN_BOOT_DISK;
10712         else if (str[n] == 'd')
10713             def->os.bootDevs[b++] = VIR_DOMAIN_BOOT_CDROM;
10714         else if (str[n] == 'n')
10715             def->os.bootDevs[b++] = VIR_DOMAIN_BOOT_NET;
10716         else if (str[n] == ',')
10717             break;
10718     }
10719     def->os.nBootDevs = b;
10720 }
10721
10722
10723 /*
10724  * Analyse the env and argv settings and reconstruct a
10725  * virDomainDefPtr representing these settings as closely
10726  * as is practical. This is not an exact science....
10727  */
10728 static virDomainDefPtr
10729 qemuParseCommandLine(virCapsPtr qemuCaps,
10730                      virDomainXMLOptionPtr xmlopt,
10731                      char **progenv,
10732                      char **progargv,
10733                      char **pidfile,
10734                      virDomainChrSourceDefPtr *monConfig,
10735                      bool *monJSON)
10736 {
10737     virDomainDefPtr def;
10738     size_t i;
10739     bool nographics = false;
10740     bool fullscreen = false;
10741     char *path;
10742     size_t nnics = 0;
10743     const char **nics = NULL;
10744     int video = VIR_DOMAIN_VIDEO_TYPE_CIRRUS;
10745     int nvirtiodisk = 0;
10746     qemuDomainCmdlineDefPtr cmd = NULL;
10747     virDomainDiskDefPtr disk = NULL;
10748     const char *ceph_args = qemuFindEnv(progenv, "CEPH_ARGS");
10749
10750     if (pidfile)
10751         *pidfile = NULL;
10752     if (monConfig)
10753         *monConfig = NULL;
10754     if (monJSON)
10755         *monJSON = false;
10756
10757     if (!progargv[0]) {
10758         virReportError(VIR_ERR_INTERNAL_ERROR,
10759                        "%s", _("no emulator path found"));
10760         return NULL;
10761     }
10762
10763     if (VIR_ALLOC(def) < 0)
10764         goto error;
10765
10766     /* allocate the cmdlinedef up-front; if it's unused, we'll free it later */
10767     if (VIR_ALLOC(cmd) < 0)
10768         goto error;
10769
10770     if (virUUIDGenerate(def->uuid) < 0) {
10771         virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
10772                        _("failed to generate uuid"));
10773         goto error;
10774     }
10775
10776     def->id = -1;
10777     def->mem.cur_balloon = def->mem.max_balloon = 64 * 1024;
10778     def->maxvcpus = 1;
10779     def->vcpus = 1;
10780     def->clock.offset = VIR_DOMAIN_CLOCK_OFFSET_UTC;
10781
10782     def->onReboot = VIR_DOMAIN_LIFECYCLE_RESTART;
10783     def->onCrash = VIR_DOMAIN_LIFECYCLE_DESTROY;
10784     def->onPoweroff = VIR_DOMAIN_LIFECYCLE_DESTROY;
10785     def->virtType = VIR_DOMAIN_VIRT_QEMU;
10786     if (VIR_STRDUP(def->emulator, progargv[0]) < 0)
10787         goto error;
10788
10789     if (!(path = last_component(def->emulator)))
10790         goto error;
10791
10792     if (strstr(path, "xenner")) {
10793         def->virtType = VIR_DOMAIN_VIRT_KVM;
10794         if (VIR_STRDUP(def->os.type, "xen") < 0)
10795             goto error;
10796     } else {
10797         if (VIR_STRDUP(def->os.type, "hvm") < 0)
10798             goto error;
10799         if (strstr(path, "kvm")) {
10800             def->virtType = VIR_DOMAIN_VIRT_KVM;
10801             def->features[VIR_DOMAIN_FEATURE_PAE] = VIR_DOMAIN_FEATURE_STATE_ON;
10802         }
10803     }
10804
10805     if (def->virtType == VIR_DOMAIN_VIRT_KVM)
10806         def->os.arch = qemuCaps->host.arch;
10807     else if (STRPREFIX(path, "qemu-system-"))
10808         def->os.arch = virArchFromString(path + strlen("qemu-system-"));
10809     else
10810         def->os.arch = VIR_ARCH_I686;
10811
10812     if ((def->os.arch == VIR_ARCH_I686) ||
10813         (def->os.arch == VIR_ARCH_X86_64))
10814         def->features[VIR_DOMAIN_FEATURE_ACPI] = VIR_DOMAIN_FEATURE_STATE_ON;
10815
10816 #define WANT_VALUE()                                                   \
10817     const char *val = progargv[++i];                                   \
10818     if (!val) {                                                        \
10819         virReportError(VIR_ERR_INTERNAL_ERROR,                         \
10820                        _("missing value for %s argument"), arg);       \
10821         goto error;                                                    \
10822     }
10823
10824     /* One initial loop to get list of NICs, so we
10825      * can correlate them later */
10826     for (i = 1; progargv[i]; i++) {
10827         const char *arg = progargv[i];
10828         /* Make sure we have a single - for all options to
10829            simplify next logic */
10830         if (STRPREFIX(arg, "--"))
10831             arg++;
10832
10833         if (STREQ(arg, "-net")) {
10834             WANT_VALUE();
10835             if (STRPREFIX(val, "nic") &&
10836                 VIR_APPEND_ELEMENT(nics, nnics, val) < 0)
10837                 goto error;
10838         }
10839     }
10840
10841     /* Now the real processing loop */
10842     for (i = 1; progargv[i]; i++) {
10843         const char *arg = progargv[i];
10844         /* Make sure we have a single - for all options to
10845            simplify next logic */
10846         if (STRPREFIX(arg, "--"))
10847             arg++;
10848
10849         if (STREQ(arg, "-vnc")) {
10850             virDomainGraphicsDefPtr vnc;
10851             char *tmp;
10852             WANT_VALUE();
10853             if (VIR_ALLOC(vnc) < 0)
10854                 goto error;
10855             vnc->type = VIR_DOMAIN_GRAPHICS_TYPE_VNC;
10856
10857             if (STRPREFIX(val, "unix:")) {
10858                 /* -vnc unix:/some/big/path */
10859                 if (VIR_STRDUP(vnc->data.vnc.socket, val + 5) < 0) {
10860                     virDomainGraphicsDefFree(vnc);
10861                     goto error;
10862                 }
10863             } else {
10864                 /*
10865                  * -vnc 127.0.0.1:4
10866                  * -vnc [2001:1:2:3:4:5:1234:1234]:4
10867                  * -vnc some.host.name:4
10868                  */
10869                 char *opts;
10870                 char *port;
10871                 const char *sep = ":";
10872                 if (val[0] == '[')
10873                     sep = "]:";
10874                 tmp = strstr(val, sep);
10875                 if (!tmp) {
10876                     virDomainGraphicsDefFree(vnc);
10877                     virReportError(VIR_ERR_INTERNAL_ERROR,
10878                                    _("missing VNC port number in '%s'"), val);
10879                     goto error;
10880                 }
10881                 port = tmp + strlen(sep);
10882                 if (virStrToLong_i(port, &opts, 10,
10883                                    &vnc->data.vnc.port) < 0) {
10884                     virDomainGraphicsDefFree(vnc);
10885                     virReportError(VIR_ERR_INTERNAL_ERROR,
10886                                    _("cannot parse VNC port '%s'"), port);
10887                     goto error;
10888                 }
10889                 if (val[0] == '[')
10890                     virDomainGraphicsListenSetAddress(vnc, 0,
10891                                                       val+1, tmp-(val+1), true);
10892                 else
10893                     virDomainGraphicsListenSetAddress(vnc, 0,
10894                                                       val, tmp-val, true);
10895                 if (!virDomainGraphicsListenGetAddress(vnc, 0)) {
10896                     virDomainGraphicsDefFree(vnc);
10897                     goto error;
10898                 }
10899
10900                 if (*opts == ',') {
10901                     char *orig_opts;
10902
10903                     if (VIR_STRDUP(orig_opts, opts + 1) < 0) {
10904                         virDomainGraphicsDefFree(vnc);
10905                         goto error;
10906                     }
10907                     opts = orig_opts;
10908
10909                     while (opts && *opts) {
10910                         char *nextopt = strchr(opts, ',');
10911                         if (nextopt)
10912                             *(nextopt++) = '\0';
10913
10914                         if (STRPREFIX(opts, "websocket")) {
10915                             char *websocket = opts + strlen("websocket");
10916                             if (*(websocket++) == '=' &&
10917                                 *websocket) {
10918                                 /* If the websocket continues with
10919                                  * '=<something>', we'll parse it */
10920                                 if (virStrToLong_i(websocket,
10921                                                    NULL, 0,
10922                                                    &vnc->data.vnc.websocket) < 0) {
10923                                     virReportError(VIR_ERR_INTERNAL_ERROR,
10924                                                    _("cannot parse VNC "
10925                                                      "WebSocket port '%s'"),
10926                                                    websocket);
10927                                     virDomainGraphicsDefFree(vnc);
10928                                     VIR_FREE(orig_opts);
10929                                     goto error;
10930                                 }
10931                             } else {
10932                                 /* Otherwise, we'll compute the port the same
10933                                  * way QEMU does, by adding a 5700 to the
10934                                  * display value. */
10935                                 vnc->data.vnc.websocket =
10936                                     vnc->data.vnc.port + 5700;
10937                             }
10938                         } else if (STRPREFIX(opts, "share=")) {
10939                             char *sharePolicy = opts + strlen("share=");
10940                             if (sharePolicy && *sharePolicy) {
10941                                 int policy =
10942                                     virDomainGraphicsVNCSharePolicyTypeFromString(sharePolicy);
10943
10944                                 if (policy < 0) {
10945                                     virReportError(VIR_ERR_INTERNAL_ERROR,
10946                                                    _("unknown vnc display sharing policy '%s'"),
10947                                                      sharePolicy);
10948                                     virDomainGraphicsDefFree(vnc);
10949                                     VIR_FREE(orig_opts);
10950                                     goto error;
10951                                 } else {
10952                                     vnc->data.vnc.sharePolicy = policy;
10953                                 }
10954                             } else {
10955                                 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
10956                                                _("missing vnc sharing policy"));
10957                                 virDomainGraphicsDefFree(vnc);
10958                                 VIR_FREE(orig_opts);
10959                                 goto error;
10960                             }
10961                         }
10962
10963                         opts = nextopt;
10964                     }
10965                     VIR_FREE(orig_opts);
10966                 }
10967                 vnc->data.vnc.port += 5900;
10968                 vnc->data.vnc.autoport = false;
10969             }
10970
10971             if (VIR_APPEND_ELEMENT(def->graphics, def->ngraphics, vnc) < 0) {
10972                 virDomainGraphicsDefFree(vnc);
10973                 goto error;
10974             }
10975         } else if (STREQ(arg, "-m")) {
10976             int mem;
10977             WANT_VALUE();
10978             if (virStrToLong_i(val, NULL, 10, &mem) < 0) {
10979                 virReportError(VIR_ERR_INTERNAL_ERROR, \
10980                                _("cannot parse memory level '%s'"), val);
10981                 goto error;
10982             }
10983             def->mem.cur_balloon = def->mem.max_balloon = mem * 1024;
10984         } else if (STREQ(arg, "-smp")) {
10985             WANT_VALUE();
10986             if (qemuParseCommandLineSmp(def, val) < 0)
10987                 goto error;
10988         } else if (STREQ(arg, "-uuid")) {
10989             WANT_VALUE();
10990             if (virUUIDParse(val, def->uuid) < 0) {
10991                 virReportError(VIR_ERR_INTERNAL_ERROR, \
10992                                _("cannot parse UUID '%s'"), val);
10993                 goto error;
10994             }
10995         } else if (STRPREFIX(arg, "-hd") ||
10996                    STRPREFIX(arg, "-sd") ||
10997                    STRPREFIX(arg, "-fd") ||
10998                    STREQ(arg, "-cdrom")) {
10999             WANT_VALUE();
11000             if (VIR_ALLOC(disk) < 0)
11001                 goto error;
11002
11003             if (STRPREFIX(val, "/dev/"))
11004                 disk->src.type = VIR_STORAGE_TYPE_BLOCK;
11005             else if (STRPREFIX(val, "nbd:")) {
11006                 disk->src.type = VIR_STORAGE_TYPE_NETWORK;
11007                 disk->src.protocol = VIR_STORAGE_NET_PROTOCOL_NBD;
11008             } else if (STRPREFIX(val, "rbd:")) {
11009                 disk->src.type = VIR_STORAGE_TYPE_NETWORK;
11010                 disk->src.protocol = VIR_STORAGE_NET_PROTOCOL_RBD;
11011                 val += strlen("rbd:");
11012             } else if (STRPREFIX(val, "gluster")) {
11013                 disk->src.type = VIR_STORAGE_TYPE_NETWORK;
11014                 disk->src.protocol = VIR_STORAGE_NET_PROTOCOL_GLUSTER;
11015             } else if (STRPREFIX(val, "sheepdog:")) {
11016                 disk->src.type = VIR_STORAGE_TYPE_NETWORK;
11017                 disk->src.protocol = VIR_STORAGE_NET_PROTOCOL_SHEEPDOG;
11018                 val += strlen("sheepdog:");
11019             } else
11020                 disk->src.type = VIR_STORAGE_TYPE_FILE;
11021             if (STREQ(arg, "-cdrom")) {
11022                 disk->device = VIR_DOMAIN_DISK_DEVICE_CDROM;
11023                 if (((def->os.arch == VIR_ARCH_PPC64) &&
11024                     def->os.machine && STREQ(def->os.machine, "pseries")))
11025                     disk->bus = VIR_DOMAIN_DISK_BUS_SCSI;
11026                 if (VIR_STRDUP(disk->dst, "hdc") < 0)
11027                     goto error;
11028                 disk->readonly = true;
11029             } else {
11030                 if (STRPREFIX(arg, "-fd")) {
11031                     disk->device = VIR_DOMAIN_DISK_DEVICE_FLOPPY;
11032                     disk->bus = VIR_DOMAIN_DISK_BUS_FDC;
11033                 } else {
11034                     disk->device = VIR_DOMAIN_DISK_DEVICE_DISK;
11035                     if (STRPREFIX(arg, "-hd"))
11036                         disk->bus = VIR_DOMAIN_DISK_BUS_IDE;
11037                     else
11038                         disk->bus = VIR_DOMAIN_DISK_BUS_SCSI;
11039                    if (((def->os.arch == VIR_ARCH_PPC64) &&
11040                        def->os.machine && STREQ(def->os.machine, "pseries")))
11041                        disk->bus = VIR_DOMAIN_DISK_BUS_SCSI;
11042                 }
11043                 if (VIR_STRDUP(disk->dst, arg + 1) < 0)
11044                     goto error;
11045             }
11046             if (VIR_STRDUP(disk->src.path, val) < 0)
11047                 goto error;
11048
11049             if (disk->src.type == VIR_STORAGE_TYPE_NETWORK) {
11050                 char *port;
11051
11052                 switch ((virStorageNetProtocol) disk->src.protocol) {
11053                 case VIR_STORAGE_NET_PROTOCOL_NBD:
11054                     if (qemuParseNBDString(disk) < 0)
11055                         goto error;
11056                     break;
11057                 case VIR_STORAGE_NET_PROTOCOL_RBD:
11058                     /* old-style CEPH_ARGS env variable is parsed later */
11059                     if (!ceph_args && qemuParseRBDString(disk) < 0)
11060                         goto error;
11061                     break;
11062                 case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
11063                     /* disk->src must be [vdiname] or [host]:[port]:[vdiname] */
11064                     port = strchr(disk->src.path, ':');
11065                     if (port) {
11066                         char *vdi;
11067
11068                         *port++ = '\0';
11069                         vdi = strchr(port, ':');
11070                         if (!vdi) {
11071                             virReportError(VIR_ERR_INTERNAL_ERROR,
11072                                            _("cannot parse sheepdog filename '%s'"), val);
11073                             goto error;
11074                         }
11075                         *vdi++ = '\0';
11076                         if (VIR_ALLOC(disk->src.hosts) < 0)
11077                             goto error;
11078                         disk->src.nhosts = 1;
11079                         disk->src.hosts->name = disk->src.path;
11080                         if (VIR_STRDUP(disk->src.hosts->port, port) < 0)
11081                             goto error;
11082                         if (VIR_STRDUP(disk->src.path, vdi) < 0)
11083                             goto error;
11084                     }
11085                     break;
11086                 case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
11087                     if (qemuParseGlusterString(disk) < 0)
11088                         goto error;
11089
11090                     break;
11091                 case VIR_STORAGE_NET_PROTOCOL_ISCSI:
11092                     if (qemuParseISCSIString(disk) < 0)
11093                         goto error;
11094
11095                     break;
11096                 case VIR_STORAGE_NET_PROTOCOL_HTTP:
11097                 case VIR_STORAGE_NET_PROTOCOL_HTTPS:
11098                 case VIR_STORAGE_NET_PROTOCOL_FTP:
11099                 case VIR_STORAGE_NET_PROTOCOL_FTPS:
11100                 case VIR_STORAGE_NET_PROTOCOL_TFTP:
11101                 case VIR_STORAGE_NET_PROTOCOL_LAST:
11102                 case VIR_STORAGE_NET_PROTOCOL_NONE:
11103                     /* ignored for now */
11104                     break;
11105                 }
11106             }
11107
11108             if (virDomainDiskDefAssignAddress(xmlopt, disk) < 0) {
11109                 virReportError(VIR_ERR_INTERNAL_ERROR,
11110                                _("Cannot assign address for device name '%s'"),
11111                                disk->dst);
11112                 goto error;
11113             }
11114
11115             if (VIR_APPEND_ELEMENT(def->disks, def->ndisks, disk) < 0)
11116                 goto error;
11117         } else if (STREQ(arg, "-no-acpi")) {
11118             def->features[VIR_DOMAIN_FEATURE_ACPI] = VIR_DOMAIN_FEATURE_STATE_DEFAULT;
11119         } else if (STREQ(arg, "-no-reboot")) {
11120             def->onReboot = VIR_DOMAIN_LIFECYCLE_DESTROY;
11121         } else if (STREQ(arg, "-no-kvm")) {
11122             def->virtType = VIR_DOMAIN_VIRT_QEMU;
11123         } else if (STREQ(arg, "-enable-kvm")) {
11124             def->virtType = VIR_DOMAIN_VIRT_KVM;
11125         } else if (STREQ(arg, "-nographic")) {
11126             nographics = true;
11127         } else if (STREQ(arg, "-full-screen")) {
11128             fullscreen = true;
11129         } else if (STREQ(arg, "-localtime")) {
11130             def->clock.offset = VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME;
11131         } else if (STREQ(arg, "-kernel")) {
11132             WANT_VALUE();
11133             if (VIR_STRDUP(def->os.kernel, val) < 0)
11134                 goto error;
11135         } else if (STREQ(arg, "-bios")) {
11136             WANT_VALUE();
11137             if (VIR_STRDUP(def->os.loader, val) < 0)
11138                 goto error;
11139         } else if (STREQ(arg, "-initrd")) {
11140             WANT_VALUE();
11141             if (VIR_STRDUP(def->os.initrd, val) < 0)
11142                 goto error;
11143         } else if (STREQ(arg, "-append")) {
11144             WANT_VALUE();
11145             if (VIR_STRDUP(def->os.cmdline, val) < 0)
11146                 goto error;
11147         } else if (STREQ(arg, "-dtb")) {
11148             WANT_VALUE();
11149             if (VIR_STRDUP(def->os.dtb, val) < 0)
11150                 goto error;
11151         } else if (STREQ(arg, "-boot")) {
11152             const char *token = NULL;
11153             WANT_VALUE();
11154
11155             if (!strchr(val, ','))
11156                 qemuParseCommandLineBootDevs(def, val);
11157             else {
11158                 token = val;
11159                 while (token && *token) {
11160                     if (STRPREFIX(token, "order=")) {
11161                         token += strlen("order=");
11162                         qemuParseCommandLineBootDevs(def, token);
11163                     } else if (STRPREFIX(token, "menu=on")) {
11164                         def->os.bootmenu = 1;
11165                     } else if (STRPREFIX(token, "reboot-timeout=")) {
11166                         int num;
11167                         char *endptr;
11168                         if (virStrToLong_i(token + strlen("reboot-timeout="),
11169                                            &endptr, 10, &num) < 0 ||
11170                             (*endptr != '\0' && endptr != strchr(token, ','))) {
11171                             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
11172                                            _("cannot parse reboot-timeout value"));
11173                             goto error;
11174                         }
11175                         if (num > 65535)
11176                             num = 65535;
11177                         else if (num < -1)
11178                             num = -1;
11179                         def->os.bios.rt_delay = num;
11180                         def->os.bios.rt_set = true;
11181                     }
11182                     token = strchr(token, ',');
11183                     /* This incrementation has to be done here in order to make it
11184                      * possible to pass the token pointer properly into the loop */
11185                     if (token)
11186                         token++;
11187                 }
11188             }
11189         } else if (STREQ(arg, "-name")) {
11190             char *process;
11191             WANT_VALUE();
11192             process = strstr(val, ",process=");
11193             if (process == NULL) {
11194                 if (VIR_STRDUP(def->name, val) < 0)
11195                     goto error;
11196             } else {
11197                 if (VIR_STRNDUP(def->name, val, process - val) < 0)
11198                     goto error;
11199             }
11200             if (STREQ(def->name, ""))
11201                 VIR_FREE(def->name);
11202         } else if (STREQ(arg, "-M") ||
11203                    STREQ(arg, "-machine")) {
11204             char **list;
11205             char *param;
11206             size_t j = 0;
11207
11208             /* -machine [type=]name[,prop[=value][,...]]
11209              * Set os.machine only if first parameter lacks '=' or
11210              * contains explicit type='...' */
11211             WANT_VALUE();
11212             if (!(list = virStringSplit(val, ",", 0)))
11213                 goto error;
11214             param = list[0];
11215
11216             if (STRPREFIX(param, "type="))
11217                 param += strlen("type=");
11218             if (!strchr(param, '=')) {
11219                 if (VIR_STRDUP(def->os.machine, param) < 0) {
11220                     virStringFreeList(list);
11221                     goto error;
11222                 }
11223                 j++;
11224             }
11225
11226             /* handle all remaining "-machine" parameters */
11227             while ((param = list[j++])) {
11228                 if (STRPREFIX(param, "dump-guest-core=")) {
11229                     param += strlen("dump-guest-core=");
11230                     def->mem.dump_core = virDomainMemDumpTypeFromString(param);
11231                     if (def->mem.dump_core <= 0)
11232                         def->mem.dump_core = VIR_DOMAIN_MEM_DUMP_DEFAULT;
11233                 } else if (STRPREFIX(param, "mem-merge=off")) {
11234                     def->mem.nosharepages = true;
11235                 } else if (STRPREFIX(param, "accel=kvm")) {
11236                     def->virtType = VIR_DOMAIN_VIRT_KVM;
11237                     def->features[VIR_DOMAIN_FEATURE_PAE] = VIR_DOMAIN_FEATURE_STATE_ON;
11238                 }
11239             }
11240             virStringFreeList(list);
11241         } else if (STREQ(arg, "-serial")) {
11242             WANT_VALUE();
11243             if (STRNEQ(val, "none")) {
11244                 virDomainChrDefPtr chr;
11245
11246                 if (!(chr = virDomainChrDefNew()))
11247                     goto error;
11248
11249                 if (qemuParseCommandLineChr(&chr->source, val) < 0) {
11250                     virDomainChrDefFree(chr);
11251                     goto error;
11252                 }
11253                 chr->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL;
11254                 chr->target.port = def->nserials;
11255                 if (VIR_APPEND_ELEMENT(def->serials, def->nserials, chr) < 0) {
11256                     virDomainChrDefFree(chr);
11257                     goto error;
11258                 }
11259             }
11260         } else if (STREQ(arg, "-parallel")) {
11261             WANT_VALUE();
11262             if (STRNEQ(val, "none")) {
11263                 virDomainChrDefPtr chr;
11264
11265                 if (!(chr = virDomainChrDefNew()))
11266                     goto error;
11267
11268                 if (qemuParseCommandLineChr(&chr->source, val) < 0) {
11269                     virDomainChrDefFree(chr);
11270                     goto error;
11271                 }
11272                 chr->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL;
11273                 chr->target.port = def->nparallels;
11274                 if (VIR_APPEND_ELEMENT(def->parallels, def->nparallels, chr) < 0) {
11275                     virDomainChrDefFree(chr);
11276                     goto error;
11277                 }
11278             }
11279         } else if (STREQ(arg, "-usbdevice")) {
11280             WANT_VALUE();
11281             if (STREQ(val, "tablet") ||
11282                 STREQ(val, "mouse") ||
11283                 STREQ(val, "keyboard")) {
11284                 virDomainInputDefPtr input;
11285                 if (VIR_ALLOC(input) < 0)
11286                     goto error;
11287                 input->bus = VIR_DOMAIN_INPUT_BUS_USB;
11288                 if (STREQ(val, "tablet"))
11289                     input->type = VIR_DOMAIN_INPUT_TYPE_TABLET;
11290                 else if (STREQ(val, "mouse"))
11291                     input->type = VIR_DOMAIN_INPUT_TYPE_MOUSE;
11292                 else
11293                     input->type = VIR_DOMAIN_INPUT_TYPE_KBD;
11294
11295                 if (VIR_APPEND_ELEMENT(def->inputs, def->ninputs, input) < 0) {
11296                     virDomainInputDefFree(input);
11297                     goto error;
11298                 }
11299             } else if (STRPREFIX(val, "disk:")) {
11300                 if (VIR_ALLOC(disk) < 0)
11301                     goto error;
11302                 if (VIR_STRDUP(disk->src.path, val + strlen("disk:")) < 0)
11303                     goto error;
11304                 if (STRPREFIX(disk->src.path, "/dev/"))
11305                     disk->src.type = VIR_STORAGE_TYPE_BLOCK;
11306                 else
11307                     disk->src.type = VIR_STORAGE_TYPE_FILE;
11308                 disk->device = VIR_DOMAIN_DISK_DEVICE_DISK;
11309                 disk->bus = VIR_DOMAIN_DISK_BUS_USB;
11310                 disk->removable = VIR_DOMAIN_FEATURE_STATE_DEFAULT;
11311                 if (VIR_STRDUP(disk->dst, "sda") < 0)
11312                     goto error;
11313                 if (VIR_APPEND_ELEMENT(def->disks, def->ndisks, disk) < 0)
11314                     goto error;
11315             } else {
11316                 virDomainHostdevDefPtr hostdev;
11317                 if (!(hostdev = qemuParseCommandLineUSB(val)))
11318                     goto error;
11319                 if (VIR_APPEND_ELEMENT(def->hostdevs, def->nhostdevs, hostdev) < 0) {
11320                     virDomainHostdevDefFree(hostdev);
11321                     goto error;
11322                 }
11323             }
11324         } else if (STREQ(arg, "-net")) {
11325             WANT_VALUE();
11326             if (!STRPREFIX(val, "nic") && STRNEQ(val, "none")) {
11327                 virDomainNetDefPtr net;
11328                 if (!(net = qemuParseCommandLineNet(xmlopt, val, nnics, nics)))
11329                     goto error;
11330                 if (VIR_APPEND_ELEMENT(def->nets, def->nnets, net) < 0) {
11331                     virDomainNetDefFree(net);
11332                     goto error;
11333                 }
11334             }
11335         } else if (STREQ(arg, "-drive")) {
11336             WANT_VALUE();
11337             if (!(disk = qemuParseCommandLineDisk(xmlopt, val, def,
11338                                                   nvirtiodisk,
11339                                                   ceph_args != NULL)))
11340                 goto error;
11341             if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
11342                 nvirtiodisk++;
11343             if (VIR_APPEND_ELEMENT(def->disks, def->ndisks, disk) < 0)
11344                 goto error;
11345         } else if (STREQ(arg, "-pcidevice")) {
11346             virDomainHostdevDefPtr hostdev;
11347             WANT_VALUE();
11348             if (!(hostdev = qemuParseCommandLinePCI(val)))
11349                 goto error;
11350             if (VIR_APPEND_ELEMENT(def->hostdevs, def->nhostdevs, hostdev) < 0) {
11351                 virDomainHostdevDefFree(hostdev);
11352                 goto error;
11353             }
11354         } else if (STREQ(arg, "-soundhw")) {
11355             const char *start;
11356             WANT_VALUE();
11357             start = val;
11358             while (start) {
11359                 const char *tmp = strchr(start, ',');
11360                 int type = -1;
11361                 if (STRPREFIX(start, "pcspk")) {
11362                     type = VIR_DOMAIN_SOUND_MODEL_PCSPK;
11363                 } else if (STRPREFIX(start, "sb16")) {
11364                     type = VIR_DOMAIN_SOUND_MODEL_SB16;
11365                 } else if (STRPREFIX(start, "es1370")) {
11366                     type = VIR_DOMAIN_SOUND_MODEL_ES1370;
11367                 } else if (STRPREFIX(start, "ac97")) {
11368                     type = VIR_DOMAIN_SOUND_MODEL_AC97;
11369                 } else if (STRPREFIX(start, "hda")) {
11370                     type = VIR_DOMAIN_SOUND_MODEL_ICH6;
11371                 }
11372
11373                 if (type != -1) {
11374                     virDomainSoundDefPtr snd;
11375                     if (VIR_ALLOC(snd) < 0)
11376                         goto error;
11377                     snd->model = type;
11378                     if (VIR_APPEND_ELEMENT(def->sounds, def->nsounds, snd) < 0) {
11379                         VIR_FREE(snd);
11380                         goto error;
11381                     }
11382                 }
11383
11384                 start = tmp ? tmp + 1 : NULL;
11385             }
11386         } else if (STREQ(arg, "-watchdog")) {
11387             WANT_VALUE();
11388             int model = virDomainWatchdogModelTypeFromString(val);
11389
11390             if (model != -1) {
11391                 virDomainWatchdogDefPtr wd;
11392                 if (VIR_ALLOC(wd) < 0)
11393                     goto error;
11394                 wd->model = model;
11395                 wd->action = VIR_DOMAIN_WATCHDOG_ACTION_RESET;
11396                 def->watchdog = wd;
11397             }
11398         } else if (STREQ(arg, "-watchdog-action") && def->watchdog) {
11399             WANT_VALUE();
11400             int action = virDomainWatchdogActionTypeFromString(val);
11401
11402             if (action != -1)
11403                 def->watchdog->action = action;
11404         } else if (STREQ(arg, "-bootloader")) {
11405             WANT_VALUE();
11406             if (VIR_STRDUP(def->os.bootloader, val) < 0)
11407                 goto error;
11408         } else if (STREQ(arg, "-vmwarevga")) {
11409             video = VIR_DOMAIN_VIDEO_TYPE_VMVGA;
11410         } else if (STREQ(arg, "-std-vga")) {
11411             video = VIR_DOMAIN_VIDEO_TYPE_VGA;
11412         } else if (STREQ(arg, "-vga")) {
11413             WANT_VALUE();
11414             if (STRNEQ(val, "none")) {
11415                 video = qemuVideoTypeFromString(val);
11416                 if (video < 0) {
11417                     virReportError(VIR_ERR_INTERNAL_ERROR,
11418                                    _("unknown video adapter type '%s'"), val);
11419                     goto error;
11420                 }
11421             }
11422         } else if (STREQ(arg, "-cpu")) {
11423             WANT_VALUE();
11424             if (qemuParseCommandLineCPU(def, val) < 0)
11425                 goto error;
11426         } else if (STREQ(arg, "-domid")) {
11427             WANT_VALUE();
11428             /* ignore, generted on the fly */
11429         } else if (STREQ(arg, "-usb")) {
11430             virDomainControllerDefPtr ctldef;
11431             if (VIR_ALLOC(ctldef) < 0)
11432                 goto error;
11433             ctldef->type = VIR_DOMAIN_CONTROLLER_TYPE_USB;
11434             ctldef->idx = 0;
11435             ctldef->model = -1;
11436             if (virDomainControllerInsert(def, ctldef) < 0) {
11437                 VIR_FREE(ctldef);
11438                 goto error;
11439             }
11440         } else if (STREQ(arg, "-pidfile")) {
11441             WANT_VALUE();
11442             if (pidfile)
11443                 if (VIR_STRDUP(*pidfile, val) < 0)
11444                     goto error;
11445         } else if (STREQ(arg, "-incoming")) {
11446             WANT_VALUE();
11447             /* ignore, used via restore/migrate APIs */
11448         } else if (STREQ(arg, "-monitor")) {
11449             WANT_VALUE();
11450             if (monConfig) {
11451                 virDomainChrSourceDefPtr chr;
11452
11453                 if (VIR_ALLOC(chr) < 0)
11454                     goto error;
11455
11456                 if (qemuParseCommandLineChr(chr, val) < 0) {
11457                     virDomainChrSourceDefFree(chr);
11458                     goto error;
11459                 }
11460
11461                 *monConfig = chr;
11462             }
11463         } else if (STREQ(arg, "-global") &&
11464                    STRPREFIX(progargv[i + 1], "PIIX4_PM.disable_s3=")) {
11465             /* We want to parse only the known "-global" parameters,
11466              * so the ones that we don't know are still added to the
11467              * namespace */
11468             WANT_VALUE();
11469
11470             val += strlen("PIIX4_PM.disable_s3=");
11471             if (STREQ(val, "0"))
11472                 def->pm.s3 = VIR_DOMAIN_PM_STATE_ENABLED;
11473             else if (STREQ(val, "1"))
11474                 def->pm.s3 = VIR_DOMAIN_PM_STATE_DISABLED;
11475             else {
11476                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11477                                _("invalid value for disable_s3 parameter: "
11478                                  "'%s'"), val);
11479                 goto error;
11480             }
11481
11482         } else if (STREQ(arg, "-global") &&
11483                    STRPREFIX(progargv[i + 1], "PIIX4_PM.disable_s4=")) {
11484
11485             WANT_VALUE();
11486
11487             val += strlen("PIIX4_PM.disable_s4=");
11488             if (STREQ(val, "0"))
11489                 def->pm.s4 = VIR_DOMAIN_PM_STATE_ENABLED;
11490             else if (STREQ(val, "1"))
11491                 def->pm.s4 = VIR_DOMAIN_PM_STATE_DISABLED;
11492             else {
11493                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11494                                _("invalid value for disable_s4 parameter: "
11495                                  "'%s'"), val);
11496                 goto error;
11497             }
11498
11499         } else if (STREQ(arg, "-global") &&
11500                    STRPREFIX(progargv[i + 1], "spapr-nvram.reg=")) {
11501             WANT_VALUE();
11502
11503             if (VIR_ALLOC(def->nvram) < 0)
11504                 goto error;
11505
11506             def->nvram->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO;
11507             def->nvram->info.addr.spaprvio.has_reg = true;
11508
11509             val += strlen("spapr-nvram.reg=");
11510             if (virStrToLong_ull(val, NULL, 16,
11511                                  &def->nvram->info.addr.spaprvio.reg) < 0) {
11512                 virReportError(VIR_ERR_INTERNAL_ERROR,
11513                                _("cannot parse nvram's address '%s'"), val);
11514                 goto error;
11515             }
11516         } else if (STREQ(arg, "-S")) {
11517             /* ignore, always added by libvirt */
11518         } else {
11519             char *tmp = NULL;
11520             /* something we can't yet parse.  Add it to the qemu namespace
11521              * cmdline/environment advanced options and hope for the best
11522              */
11523             VIR_WARN("unknown QEMU argument '%s', adding to the qemu namespace",
11524                      arg);
11525             if (VIR_STRDUP(tmp, arg) < 0 ||
11526                 VIR_APPEND_ELEMENT(cmd->args, cmd->num_args, tmp) < 0) {
11527                 VIR_FREE(tmp);
11528                 goto error;
11529             }
11530         }
11531     }
11532
11533 #undef WANT_VALUE
11534     if (def->ndisks > 0 && ceph_args) {
11535         char *hosts, *port, *saveptr = NULL, *token;
11536         virDomainDiskDefPtr first_rbd_disk = NULL;
11537         for (i = 0; i < def->ndisks; i++) {
11538             if (def->disks[i]->src.type == VIR_STORAGE_TYPE_NETWORK &&
11539                 def->disks[i]->src.protocol == VIR_STORAGE_NET_PROTOCOL_RBD) {
11540                 first_rbd_disk = def->disks[i];
11541                 break;
11542             }
11543         }
11544
11545         if (!first_rbd_disk) {
11546             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
11547                            _("CEPH_ARGS was set without an rbd disk"));
11548             goto error;
11549         }
11550
11551         /* CEPH_ARGS should be: -m host1[:port1][,host2[:port2]]... */
11552         if (!STRPREFIX(ceph_args, "-m ")) {
11553             virReportError(VIR_ERR_INTERNAL_ERROR,
11554                            _("could not parse CEPH_ARGS '%s'"), ceph_args);
11555             goto error;
11556         }
11557         if (VIR_STRDUP(hosts, strchr(ceph_args, ' ') + 1) < 0)
11558             goto error;
11559         first_rbd_disk->src.nhosts = 0;
11560         token = strtok_r(hosts, ",", &saveptr);
11561         while (token != NULL) {
11562             if (VIR_REALLOC_N(first_rbd_disk->src.hosts,
11563                               first_rbd_disk->src.nhosts + 1) < 0) {
11564                 VIR_FREE(hosts);
11565                 goto error;
11566             }
11567             port = strchr(token, ':');
11568             if (port) {
11569                 *port++ = '\0';
11570                 if (VIR_STRDUP(port, port) < 0) {
11571                     VIR_FREE(hosts);
11572                     goto error;
11573                 }
11574             }
11575             first_rbd_disk->src.hosts[first_rbd_disk->src.nhosts].port = port;
11576             if (VIR_STRDUP(first_rbd_disk->src.hosts[first_rbd_disk->src.nhosts].name,
11577                            token) < 0) {
11578                 VIR_FREE(hosts);
11579                 goto error;
11580             }
11581             first_rbd_disk->src.hosts[first_rbd_disk->src.nhosts].transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
11582             first_rbd_disk->src.hosts[first_rbd_disk->src.nhosts].socket = NULL;
11583
11584             first_rbd_disk->src.nhosts++;
11585             token = strtok_r(NULL, ",", &saveptr);
11586         }
11587         VIR_FREE(hosts);
11588
11589         if (first_rbd_disk->src.nhosts == 0) {
11590             virReportError(VIR_ERR_INTERNAL_ERROR,
11591                            _("found no rbd hosts in CEPH_ARGS '%s'"), ceph_args);
11592             goto error;
11593         }
11594     }
11595
11596     if (!def->os.machine) {
11597         const char *defaultMachine =
11598                         virCapabilitiesDefaultGuestMachine(qemuCaps,
11599                                                            def->os.type,
11600                                                            def->os.arch,
11601                                                            virDomainVirtTypeToString(def->virtType));
11602         if (defaultMachine != NULL)
11603             if (VIR_STRDUP(def->os.machine, defaultMachine) < 0)
11604                 goto error;
11605     }
11606
11607     if (!nographics && def->ngraphics == 0) {
11608         virDomainGraphicsDefPtr sdl;
11609         const char *display = qemuFindEnv(progenv, "DISPLAY");
11610         const char *xauth = qemuFindEnv(progenv, "XAUTHORITY");
11611         if (VIR_ALLOC(sdl) < 0)
11612             goto error;
11613         sdl->type = VIR_DOMAIN_GRAPHICS_TYPE_SDL;
11614         sdl->data.sdl.fullscreen = fullscreen;
11615         if (VIR_STRDUP(sdl->data.sdl.display, display) < 0) {
11616             VIR_FREE(sdl);
11617             goto error;
11618         }
11619         if (VIR_STRDUP(sdl->data.sdl.xauth, xauth) < 0) {
11620             VIR_FREE(sdl);
11621             goto error;
11622         }
11623
11624         if (VIR_APPEND_ELEMENT(def->graphics, def->ngraphics, sdl) < 0) {
11625             virDomainGraphicsDefFree(sdl);
11626             goto error;
11627         }
11628     }
11629
11630     if (def->ngraphics) {
11631         virDomainVideoDefPtr vid;
11632         if (VIR_ALLOC(vid) < 0)
11633             goto error;
11634         if (def->virtType == VIR_DOMAIN_VIRT_XEN)
11635             vid->type = VIR_DOMAIN_VIDEO_TYPE_XEN;
11636         else
11637             vid->type = video;
11638         vid->vram = virDomainVideoDefaultRAM(def, vid->type);
11639         vid->ram = vid->type == VIR_DOMAIN_VIDEO_TYPE_QXL ?
11640                        virDomainVideoDefaultRAM(def, vid->type) : 0;
11641         vid->heads = 1;
11642
11643         if (VIR_APPEND_ELEMENT(def->videos, def->nvideos, vid) < 0) {
11644             virDomainVideoDefFree(vid);
11645             goto error;
11646         }
11647     }
11648
11649     /*
11650      * having a balloon is the default, define one with type="none" to avoid it
11651      */
11652     if (!def->memballoon) {
11653         virDomainMemballoonDefPtr memballoon;
11654         if (VIR_ALLOC(memballoon) < 0)
11655             goto error;
11656         memballoon->model = VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO;
11657
11658         def->memballoon = memballoon;
11659     }
11660
11661     VIR_FREE(nics);
11662
11663     if (virDomainDefAddImplicitControllers(def) < 0)
11664         goto error;
11665
11666     if (virDomainDefPostParse(def, qemuCaps, xmlopt) < 0)
11667         goto error;
11668
11669     if (cmd->num_args || cmd->num_env) {
11670         def->ns = *virDomainXMLOptionGetNamespace(xmlopt);
11671         def->namespaceData = cmd;
11672     }
11673     else
11674         qemuDomainCmdlineDefFree(cmd);
11675
11676     return def;
11677
11678  error:
11679     virDomainDiskDefFree(disk);
11680     qemuDomainCmdlineDefFree(cmd);
11681     virDomainDefFree(def);
11682     VIR_FREE(nics);
11683     if (monConfig) {
11684         virDomainChrSourceDefFree(*monConfig);
11685         *monConfig = NULL;
11686     }
11687     if (pidfile)
11688         VIR_FREE(*pidfile);
11689     return NULL;
11690 }
11691
11692
11693 virDomainDefPtr qemuParseCommandLineString(virCapsPtr qemuCaps,
11694                                            virDomainXMLOptionPtr xmlopt,
11695                                            const char *args,
11696                                            char **pidfile,
11697                                            virDomainChrSourceDefPtr *monConfig,
11698                                            bool *monJSON)
11699 {
11700     char **progenv = NULL;
11701     char **progargv = NULL;
11702     virDomainDefPtr def = NULL;
11703
11704     if (qemuStringToArgvEnv(args, &progenv, &progargv) < 0)
11705         goto cleanup;
11706
11707     def = qemuParseCommandLine(qemuCaps, xmlopt, progenv, progargv,
11708                                pidfile, monConfig, monJSON);
11709
11710  cleanup:
11711     virStringFreeList(progargv);
11712     virStringFreeList(progenv);
11713
11714     return def;
11715 }
11716
11717
11718 static int qemuParseProcFileStrings(int pid_value,
11719                                     const char *name,
11720                                     char ***list)
11721 {
11722     char *path = NULL;
11723     int ret = -1;
11724     char *data = NULL;
11725     ssize_t len;
11726     char *tmp;
11727     size_t nstr = 0;
11728     char **str = NULL;
11729
11730     if (virAsprintf(&path, "/proc/%d/%s", pid_value, name) < 0)
11731         goto cleanup;
11732
11733     if ((len = virFileReadAll(path, 1024*128, &data)) < 0)
11734         goto cleanup;
11735
11736     tmp = data;
11737     while (tmp < (data + len)) {
11738         if (VIR_EXPAND_N(str, nstr, 1) < 0)
11739             goto cleanup;
11740
11741         if (VIR_STRDUP(str[nstr-1], tmp) < 0)
11742             goto cleanup;
11743         /* Skip arg */
11744         tmp += strlen(tmp);
11745         /* Skip \0 separator */
11746         tmp++;
11747     }
11748
11749     if (VIR_EXPAND_N(str, nstr, 1) < 0)
11750         goto cleanup;
11751
11752     str[nstr-1] = NULL;
11753
11754     ret = nstr-1;
11755     *list = str;
11756
11757  cleanup:
11758     if (ret < 0)
11759         virStringFreeList(str);
11760     VIR_FREE(data);
11761     VIR_FREE(path);
11762     return ret;
11763 }
11764
11765 virDomainDefPtr qemuParseCommandLinePid(virCapsPtr qemuCaps,
11766                                         virDomainXMLOptionPtr xmlopt,
11767                                         pid_t pid,
11768                                         char **pidfile,
11769                                         virDomainChrSourceDefPtr *monConfig,
11770                                         bool *monJSON)
11771 {
11772     virDomainDefPtr def = NULL;
11773     char **progargv = NULL;
11774     char **progenv = NULL;
11775     char *exepath = NULL;
11776     char *emulator;
11777
11778     /* The parser requires /proc/pid, which only exists on platforms
11779      * like Linux where pid_t fits in int.  */
11780     if ((int) pid != pid ||
11781         qemuParseProcFileStrings(pid, "cmdline", &progargv) < 0 ||
11782         qemuParseProcFileStrings(pid, "environ", &progenv) < 0)
11783         goto cleanup;
11784
11785     if (!(def = qemuParseCommandLine(qemuCaps, xmlopt, progenv, progargv,
11786                                      pidfile, monConfig, monJSON)))
11787         goto cleanup;
11788
11789     if (virAsprintf(&exepath, "/proc/%d/exe", (int) pid) < 0)
11790         goto cleanup;
11791
11792     if (virFileResolveLink(exepath, &emulator) < 0) {
11793         virReportSystemError(errno,
11794                              _("Unable to resolve %s for pid %u"),
11795                              exepath, (int) pid);
11796         goto cleanup;
11797     }
11798     VIR_FREE(def->emulator);
11799     def->emulator = emulator;
11800
11801  cleanup:
11802     VIR_FREE(exepath);
11803     virStringFreeList(progargv);
11804     virStringFreeList(progenv);
11805     return def;
11806 }