domain_conf.c 694.6 KB
Newer Older
1 2 3
/*
 * domain_conf.c: domain XML processing
 *
M
Martin Kletzander 已提交
4
 * Copyright (C) 2006-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006-2008 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25 26
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <dirent.h>
27
#include <fcntl.h>
E
Eric Blake 已提交
28
#include <strings.h>
29 30
#include <sys/stat.h>
#include <unistd.h>
31

A
Ansis Atteka 已提交
32
#include "internal.h"
33
#include "virerror.h"
34
#include "datatypes.h"
35
#include "domain_conf.h"
36
#include "snapshot_conf.h"
37
#include "viralloc.h"
38
#include "verify.h"
39
#include "virxml.h"
40
#include "viruuid.h"
41
#include "virbuffer.h"
42
#include "virlog.h"
43
#include "nwfilter_conf.h"
44
#include "storage_conf.h"
45
#include "virstoragefile.h"
E
Eric Blake 已提交
46
#include "virfile.h"
47
#include "virbitmap.h"
M
Matthias Bolte 已提交
48
#include "count-one-bits.h"
49
#include "secret_conf.h"
50 51
#include "netdev_vport_profile_conf.h"
#include "netdev_bandwidth_conf.h"
52
#include "netdev_vlan_conf.h"
53
#include "device_conf.h"
54
#include "virtpm.h"
55
#include "virstring.h"
56

57 58
#define VIR_FROM_THIS VIR_FROM_DOMAIN

59 60
VIR_LOG_INIT("conf.domain_conf");

M
Matthias Bolte 已提交
61 62 63 64
/* virDomainVirtType is used to set bits in the expectedVirtTypes bitmask,
 * verify that it doesn't overflow an unsigned int when shifting */
verify(VIR_DOMAIN_VIRT_LAST <= 32);

65 66 67 68 69 70 71 72 73

struct _virDomainObjList {
    virObjectLockable parent;

    /* uuid string -> virDomainObj  mapping
     * for O(1), lockless lookup-by-uuid */
    virHashTable *objs;
};

74 75 76

/* This structure holds various callbacks and data needed
 * while parsing and creating domain XMLs */
77
struct _virDomainXMLOption {
78 79
    virObject parent;

80 81 82
    /* XML parser callbacks and defaults */
    virDomainDefParserConfig config;

83 84 85 86 87 88 89 90
    /* domain private data management callbacks */
    virDomainXMLPrivateDataCallbacks privateData;

    /* XML namespace callbacks */
    virDomainXMLNamespace ns;
 };


91
/* Private flags used internally by virDomainSaveStatus and
92
 * virDomainLoadStatus, in addition to the public virDomainXMLFlags. */
93
typedef enum {
94
   /* dump internal domain status information */
95
   VIR_DOMAIN_XML_INTERNAL_STATUS          = 1 << 16,
96
   /* dump/parse <actual> element */
97
   VIR_DOMAIN_XML_INTERNAL_ACTUAL_NET      = 1 << 17,
98
   /* dump/parse original states of host PCI device */
99 100 101 102
   VIR_DOMAIN_XML_INTERNAL_PCI_ORIG_STATES = 1 << 18,
   VIR_DOMAIN_XML_INTERNAL_ALLOW_ROM       = 1 << 19,
   VIR_DOMAIN_XML_INTERNAL_ALLOW_BOOT      = 1 << 20,
   VIR_DOMAIN_XML_INTERNAL_CLOCK_ADJUST    = 1 << 21,
103 104
   /* parse only source half of <disk> */
   VIR_DOMAIN_XML_INTERNAL_DISK_SOURCE     = 1 << 22,
105 106
} virDomainXMLInternalFlags;

107 108 109 110 111 112 113 114 115 116 117
#define DUMPXML_FLAGS                           \
    (VIR_DOMAIN_XML_SECURE |                    \
     VIR_DOMAIN_XML_INACTIVE |                  \
     VIR_DOMAIN_XML_UPDATE_CPU |                \
     VIR_DOMAIN_XML_MIGRATABLE)

verify(((VIR_DOMAIN_XML_INTERNAL_STATUS |
         VIR_DOMAIN_XML_INTERNAL_ACTUAL_NET |
         VIR_DOMAIN_XML_INTERNAL_PCI_ORIG_STATES |
         VIR_DOMAIN_XML_INTERNAL_ALLOW_ROM |
         VIR_DOMAIN_XML_INTERNAL_ALLOW_BOOT |
118 119
         VIR_DOMAIN_XML_INTERNAL_CLOCK_ADJUST |
         VIR_DOMAIN_XML_INTERNAL_DISK_SOURCE)
120 121
        & DUMPXML_FLAGS) == 0);

122 123 124 125 126
VIR_ENUM_IMPL(virDomainTaint, VIR_DOMAIN_TAINT_LAST,
              "custom-argv",
              "custom-monitor",
              "high-privileges",
              "shell-scripts",
127
              "disk-probing",
128
              "external-launch",
129 130
              "host-cpu",
              "hook-script");
131

132 133 134 135 136 137 138 139 140 141
VIR_ENUM_IMPL(virDomainVirt, VIR_DOMAIN_VIRT_LAST,
              "qemu",
              "kqemu",
              "kvm",
              "xen",
              "lxc",
              "uml",
              "openvz",
              "test",
              "vmware",
142
              "hyperv",
D
Daniel Veillard 已提交
143
              "vbox",
D
Dmitry Guryanov 已提交
144
              "phyp",
R
Roman Bogorodskiy 已提交
145 146
              "parallels",
              "bhyve")
147 148 149 150 151 152 153 154 155 156

VIR_ENUM_IMPL(virDomainBoot, VIR_DOMAIN_BOOT_LAST,
              "fd",
              "cdrom",
              "hd",
              "network")

VIR_ENUM_IMPL(virDomainFeature, VIR_DOMAIN_FEATURE_LAST,
              "acpi",
              "apic",
J
Jim Fehlig 已提交
157
              "pae",
158
              "hap",
159
              "viridian",
160
              "privnet",
161
              "hyperv",
162
              "kvm",
163 164
              "pvspinlock",
              "capabilities")
165

166 167 168 169 170
VIR_ENUM_IMPL(virDomainCapabilitiesPolicy, VIR_DOMAIN_CAPABILITIES_POLICY_LAST,
              "default",
              "allow",
              "deny")

171
VIR_ENUM_IMPL(virDomainHyperv, VIR_DOMAIN_HYPERV_LAST,
172 173 174
              "relaxed",
              "vapic",
              "spinlocks")
175

176 177 178
VIR_ENUM_IMPL(virDomainKVM, VIR_DOMAIN_KVM_LAST,
              "hidden")

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
VIR_ENUM_IMPL(virDomainCapsFeature, VIR_DOMAIN_CAPS_FEATURE_LAST,
              "audit_control",
              "audit_write",
              "block_suspend",
              "chown",
              "dac_override",
              "dac_read_search",
              "fowner",
              "fsetid",
              "ipc_lock",
              "ipc_owner",
              "kill",
              "lease",
              "linux_immutable",
              "mac_admin",
              "mac_override",
              "mknod",
              "net_admin",
              "net_bind_service",
              "net_broadcast",
              "net_raw",
              "setgid",
              "setfcap",
              "setpcap",
              "setuid",
              "sys_admin",
              "sys_boot",
              "sys_chroot",
              "sys_module",
              "sys_nice",
              "sys_pacct",
              "sys_ptrace",
              "sys_rawio",
              "sys_resource",
              "sys_time",
              "sys_tty_config",
              "syslog",
              "wake_alarm")

218 219 220 221 222 223
VIR_ENUM_IMPL(virDomainLifecycle, VIR_DOMAIN_LIFECYCLE_LAST,
              "destroy",
              "restart",
              "rename-restart",
              "preserve")

224 225 226 227 228 229 230 231
VIR_ENUM_IMPL(virDomainLifecycleCrash, VIR_DOMAIN_LIFECYCLE_CRASH_LAST,
              "destroy",
              "restart",
              "rename-restart",
              "preserve",
              "coredump-destroy",
              "coredump-restart")

232 233 234 235 236 237 238
VIR_ENUM_IMPL(virDomainLockFailure, VIR_DOMAIN_LOCK_FAILURE_LAST,
              "default",
              "poweroff",
              "restart",
              "pause",
              "ignore")

239
VIR_ENUM_IMPL(virDomainDevice, VIR_DOMAIN_DEVICE_LAST,
240
              "none",
241
              "disk",
242
              "lease",
243 244 245 246
              "filesystem",
              "interface",
              "input",
              "sound",
247
              "video",
R
Richard Jones 已提交
248
              "hostdev",
249
              "watchdog",
250
              "controller",
M
Marc-André Lureau 已提交
251
              "graphics",
252
              "hub",
253 254 255
              "redirdev",
              "smartcard",
              "chr",
256
              "memballoon",
L
Li Zhang 已提交
257
              "nvram",
258
              "rng",
259
              "shmem",
260 261
              "tpm",
              "panic")
262

263 264
VIR_ENUM_IMPL(virDomainDeviceAddress, VIR_DOMAIN_DEVICE_ADDRESS_TYPE_LAST,
              "none",
265
              "pci",
266
              "drive",
E
Eric Blake 已提交
267
              "virtio-serial",
268
              "ccid",
269
              "usb",
270
              "spapr-vio",
271
              "virtio-s390",
272
              "ccw",
H
Hu Tao 已提交
273 274
              "virtio-mmio",
              "isa")
275

276 277 278
VIR_ENUM_IMPL(virDomainDiskDevice, VIR_DOMAIN_DISK_DEVICE_LAST,
              "disk",
              "cdrom",
279 280
              "floppy",
              "lun")
281

J
J.B. Joret 已提交
282 283 284 285 286 287
VIR_ENUM_IMPL(virDomainDiskGeometryTrans, VIR_DOMAIN_DISK_TRANS_LAST,
              "default",
              "none",
              "auto",
              "lba")

288 289 290 291 292
VIR_ENUM_IMPL(virDomainDiskBus, VIR_DOMAIN_DISK_BUS_LAST,
              "ide",
              "fdc",
              "scsi",
              "virtio",
293
              "xen",
294
              "usb",
295
              "uml",
296 297
              "sata",
              "sd")
298

299 300 301 302
VIR_ENUM_IMPL(virDomainDiskCache, VIR_DOMAIN_DISK_CACHE_LAST,
              "default",
              "none",
              "writethrough",
303
              "writeback",
304 305
              "directsync",
              "unsafe")
306

307 308 309
VIR_ENUM_IMPL(virDomainDiskErrorPolicy, VIR_DOMAIN_DISK_ERROR_POLICY_LAST,
              "default",
              "stop",
310
              "report",
311 312
              "ignore",
              "enospace")
313

M
Matthias Dahl 已提交
314 315 316 317
VIR_ENUM_IMPL(virDomainDiskIo, VIR_DOMAIN_DISK_IO_LAST,
              "default",
              "native",
              "threads")
O
Osier Yang 已提交
318

319
VIR_ENUM_IMPL(virDomainDeviceSGIO, VIR_DOMAIN_DEVICE_SGIO_LAST,
O
Osier Yang 已提交
320 321 322 323
              "default",
              "filtered",
              "unfiltered")

324 325 326 327
VIR_ENUM_IMPL(virDomainController, VIR_DOMAIN_CONTROLLER_TYPE_LAST,
              "ide",
              "fdc",
              "scsi",
328
              "sata",
E
Eric Blake 已提交
329
              "virtio-serial",
330
              "ccid",
J
Ján Tomko 已提交
331 332 333 334 335
              "usb",
              "pci")

VIR_ENUM_IMPL(virDomainControllerModelPCI, VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST,
              "pci-root",
L
Laine Stump 已提交
336
              "pcie-root",
337 338
              "pci-bridge",
              "dmi-to-pci-bridge")
339

340
VIR_ENUM_IMPL(virDomainControllerModelSCSI, VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LAST,
341
              "auto",
342 343
              "buslogic",
              "lsilogic",
344
              "lsisas1068",
345
              "vmpvscsi",
346
              "ibmvscsi",
347 348
              "virtio-scsi",
              "lsisas1078");
349

M
Marc-André Lureau 已提交
350 351 352 353 354 355 356 357 358
VIR_ENUM_IMPL(virDomainControllerModelUSB, VIR_DOMAIN_CONTROLLER_MODEL_USB_LAST,
              "piix3-uhci",
              "piix4-uhci",
              "ehci",
              "ich9-ehci1",
              "ich9-uhci1",
              "ich9-uhci2",
              "ich9-uhci3",
              "vt82c686b-uhci",
G
Gerd Hoffmann 已提交
359
              "pci-ohci",
360 361
              "nec-xhci",
              "none")
M
Marc-André Lureau 已提交
362

363 364 365 366
VIR_ENUM_IMPL(virDomainFS, VIR_DOMAIN_FS_TYPE_LAST,
              "mount",
              "block",
              "file",
367
              "template",
368 369
              "ram",
              "bind")
370

371
VIR_ENUM_IMPL(virDomainFSDriver, VIR_DOMAIN_FS_DRIVER_TYPE_LAST,
372 373
              "default",
              "path",
374
              "handle",
375 376
              "loop",
              "nbd")
377

378 379 380 381 382
VIR_ENUM_IMPL(virDomainFSAccessMode, VIR_DOMAIN_FS_ACCESSMODE_LAST,
              "passthrough",
              "mapped",
              "squash")

383 384 385
VIR_ENUM_IMPL(virDomainFSWrpolicy, VIR_DOMAIN_FS_WRPOLICY_LAST,
              "default",
              "immediate")
386

387 388 389
VIR_ENUM_IMPL(virDomainNet, VIR_DOMAIN_NET_TYPE_LAST,
              "user",
              "ethernet",
M
Michele Paolino 已提交
390
              "vhostuser",
391 392 393 394
              "server",
              "client",
              "mcast",
              "network",
D
Daniel Veillard 已提交
395
              "bridge",
396
              "internal",
397 398
              "direct",
              "hostdev")
399

400 401 402 403 404
VIR_ENUM_IMPL(virDomainNetBackend, VIR_DOMAIN_NET_BACKEND_TYPE_LAST,
              "default",
              "qemu",
              "vhost")

405 406 407 408 409
VIR_ENUM_IMPL(virDomainNetVirtioTxMode, VIR_DOMAIN_NET_VIRTIO_TX_MODE_LAST,
              "default",
              "iothread",
              "timer")

410 411 412 413 414
VIR_ENUM_IMPL(virDomainNetInterfaceLinkState, VIR_DOMAIN_NET_INTERFACE_LINK_STATE_LAST,
              "default",
              "up",
              "down")

415 416 417 418 419
VIR_ENUM_IMPL(virDomainChrDeviceState, VIR_DOMAIN_CHR_DEVICE_STATE_LAST,
              "default",
              "connected",
              "disconnected");

G
Guannan Ren 已提交
420 421 422 423 424
VIR_ENUM_IMPL(virDomainChrSerialTarget,
              VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_LAST,
              "isa-serial",
              "usb-serial")

425 426
VIR_ENUM_IMPL(virDomainChrChannelTarget,
              VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_LAST,
427
              "none",
428 429 430
              "guestfwd",
              "virtio")

431 432
VIR_ENUM_IMPL(virDomainChrConsoleTarget,
              VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_LAST,
433
              "none",
434 435
              "serial",
              "xen",
C
Cole Robinson 已提交
436
              "uml",
437 438
              "virtio",
              "lxc",
439 440 441
              "openvz",
              "sclp",
              "sclplm")
442

443
VIR_ENUM_IMPL(virDomainChrDevice, VIR_DOMAIN_CHR_DEVICE_TYPE_LAST,
444 445
              "parallel",
              "serial",
446
              "console",
447
              "channel")
448

449 450 451 452 453 454 455 456 457 458
VIR_ENUM_IMPL(virDomainChr, VIR_DOMAIN_CHR_TYPE_LAST,
              "null",
              "vc",
              "pty",
              "dev",
              "file",
              "pipe",
              "stdio",
              "udp",
              "tcp",
459
              "unix",
460
              "spicevmc",
461 462
              "spiceport",
              "nmdm")
463

464 465 466 467 468 469
VIR_ENUM_IMPL(virDomainChrTcpProtocol, VIR_DOMAIN_CHR_TCP_PROTOCOL_LAST,
              "raw",
              "telnet",
              "telnets",
              "tls")

E
Eric Blake 已提交
470 471
VIR_ENUM_IMPL(virDomainChrSpicevmc, VIR_DOMAIN_CHR_SPICEVMC_LAST,
              "vdagent",
472 473
              "smartcard",
              "usbredir")
E
Eric Blake 已提交
474

E
Eric Blake 已提交
475 476 477 478 479
VIR_ENUM_IMPL(virDomainSmartcard, VIR_DOMAIN_SMARTCARD_TYPE_LAST,
              "host",
              "host-certificates",
              "passthrough")

480 481 482 483
VIR_ENUM_IMPL(virDomainSoundCodec, VIR_DOMAIN_SOUND_CODEC_TYPE_LAST,
              "duplex",
              "micro")

484 485 486
VIR_ENUM_IMPL(virDomainSoundModel, VIR_DOMAIN_SOUND_MODEL_LAST,
              "sb16",
              "es1370",
487
              "pcspk",
488
              "ac97",
489
              "ich6",
490 491
              "ich9",
              "usb")
492

493 494
VIR_ENUM_IMPL(virDomainMemballoonModel, VIR_DOMAIN_MEMBALLOON_MODEL_LAST,
              "virtio",
495
              "xen",
496 497
              "none")

498 499 500 501 502 503
VIR_ENUM_IMPL(virDomainSmbiosMode, VIR_DOMAIN_SMBIOS_LAST,
              "none",
              "emulate",
              "host",
              "sysinfo")

R
Richard Jones 已提交
504 505 506 507 508 509 510 511 512
VIR_ENUM_IMPL(virDomainWatchdogModel, VIR_DOMAIN_WATCHDOG_MODEL_LAST,
              "i6300esb",
              "ib700")

VIR_ENUM_IMPL(virDomainWatchdogAction, VIR_DOMAIN_WATCHDOG_ACTION_LAST,
              "reset",
              "shutdown",
              "poweroff",
              "pause",
H
Hu Tao 已提交
513
              "dump",
R
Richard Jones 已提交
514 515
              "none")

516 517 518 519 520
VIR_ENUM_IMPL(virDomainVideo, VIR_DOMAIN_VIDEO_TYPE_LAST,
              "vga",
              "cirrus",
              "vmvga",
              "xen",
521 522
              "vbox",
              "qxl")
523

524 525
VIR_ENUM_IMPL(virDomainInput, VIR_DOMAIN_INPUT_TYPE_LAST,
              "mouse",
L
Li Zhang 已提交
526 527
              "tablet",
              "keyboard")
528 529 530 531 532 533 534 535

VIR_ENUM_IMPL(virDomainInputBus, VIR_DOMAIN_INPUT_BUS_LAST,
              "ps2",
              "usb",
              "xen")

VIR_ENUM_IMPL(virDomainGraphics, VIR_DOMAIN_GRAPHICS_TYPE_LAST,
              "sdl",
536 537
              "vnc",
              "rdp",
538 539
              "desktop",
              "spice")
540

541 542 543 544 545
VIR_ENUM_IMPL(virDomainGraphicsListen, VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_LAST,
              "none",
              "address",
              "network")

546 547 548 549 550 551 552
VIR_ENUM_IMPL(virDomainGraphicsAuthConnected,
              VIR_DOMAIN_GRAPHICS_AUTH_CONNECTED_LAST,
              "default",
              "fail",
              "disconnect",
              "keep")

553 554 555 556 557 558 559
VIR_ENUM_IMPL(virDomainGraphicsVNCSharePolicy,
              VIR_DOMAIN_GRAPHICS_VNC_SHARE_LAST,
              "default",
              "allow-exclusive",
              "force-shared",
              "ignore")

560 561 562 563 564 565 566
VIR_ENUM_IMPL(virDomainGraphicsSpiceChannelName,
              VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_LAST,
              "main",
              "display",
              "inputs",
              "cursor",
              "playback",
E
Eric Blake 已提交
567
              "record",
568 569
              "smartcard",
              "usbredir");
570 571 572 573 574 575 576

VIR_ENUM_IMPL(virDomainGraphicsSpiceChannelMode,
              VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_LAST,
              "any",
              "secure",
              "insecure");

577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
VIR_ENUM_IMPL(virDomainGraphicsSpiceImageCompression,
              VIR_DOMAIN_GRAPHICS_SPICE_IMAGE_COMPRESSION_LAST,
              "default",
              "auto_glz",
              "auto_lz",
              "quic",
              "glz",
              "lz",
              "off");

VIR_ENUM_IMPL(virDomainGraphicsSpiceJpegCompression,
              VIR_DOMAIN_GRAPHICS_SPICE_JPEG_COMPRESSION_LAST,
              "default",
              "auto",
              "never",
              "always");

VIR_ENUM_IMPL(virDomainGraphicsSpiceZlibCompression,
              VIR_DOMAIN_GRAPHICS_SPICE_ZLIB_COMPRESSION_LAST,
              "default",
              "auto",
              "never",
              "always");

P
Peng Zhou 已提交
601 602 603 604 605 606
VIR_ENUM_IMPL(virDomainGraphicsSpiceMouseMode,
              VIR_DOMAIN_GRAPHICS_SPICE_MOUSE_MODE_LAST,
              "default",
              "server",
              "client");

607 608 609 610 611 612 613
VIR_ENUM_IMPL(virDomainGraphicsSpiceStreamingMode,
              VIR_DOMAIN_GRAPHICS_SPICE_STREAMING_MODE_LAST,
              "default",
              "filter",
              "all",
              "off");

614 615 616 617 618 619
VIR_ENUM_IMPL(virDomainHostdevMode, VIR_DOMAIN_HOSTDEV_MODE_LAST,
              "subsystem",
              "capabilities")

VIR_ENUM_IMPL(virDomainHostdevSubsys, VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_LAST,
              "usb",
H
Han Cheng 已提交
620 621
              "pci",
              "scsi")
622

623
VIR_ENUM_IMPL(virDomainHostdevSubsysPCIBackend,
624 625 626
              VIR_DOMAIN_HOSTDEV_PCI_BACKEND_TYPE_LAST,
              "default",
              "kvm",
627 628
              "vfio",
              "xen")
629

J
John Ferlan 已提交
630 631 632 633 634
VIR_ENUM_IMPL(virDomainHostdevSubsysSCSIProtocol,
              VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_LAST,
              "adapter",
              "iscsi")

635 636
VIR_ENUM_IMPL(virDomainHostdevCaps, VIR_DOMAIN_HOSTDEV_CAPS_TYPE_LAST,
              "storage",
637 638
              "misc",
              "net")
639

640 641 642 643 644 645 646
VIR_ENUM_IMPL(virDomainHub, VIR_DOMAIN_HUB_TYPE_LAST,
              "usb")

VIR_ENUM_IMPL(virDomainRedirdevBus, VIR_DOMAIN_REDIRDEV_BUS_LAST,
              "usb")

VIR_ENUM_IMPL(virDomainState, VIR_DOMAIN_LAST,
647 648 649 650 651 652
              "nostate",
              "running",
              "blocked",
              "paused",
              "shutdown",
              "shutoff",
O
Osier Yang 已提交
653 654
              "crashed",
              "pmsuspended")
655

J
Jiri Denemark 已提交
656 657 658 659 660 661 662 663 664 665 666
VIR_ENUM_IMPL(virDomainNostateReason, VIR_DOMAIN_NOSTATE_LAST,
              "unknown")

VIR_ENUM_IMPL(virDomainRunningReason, VIR_DOMAIN_RUNNING_LAST,
              "unknown",
              "booted",
              "migrated",
              "restored",
              "from snapshot",
              "unpaused",
              "migration canceled",
667
              "save canceled",
668 669
              "wakeup",
              "crashed")
J
Jiri Denemark 已提交
670 671 672 673 674 675 676 677 678 679 680 681

VIR_ENUM_IMPL(virDomainBlockedReason, VIR_DOMAIN_BLOCKED_LAST,
              "unknown")

VIR_ENUM_IMPL(virDomainPausedReason, VIR_DOMAIN_PAUSED_LAST,
              "unknown",
              "user",
              "migration",
              "save",
              "dump",
              "ioerror",
              "watchdog",
682
              "from snapshot",
683
              "shutdown",
684 685
              "snapshot",
              "panicked")
J
Jiri Denemark 已提交
686 687 688

VIR_ENUM_IMPL(virDomainShutdownReason, VIR_DOMAIN_SHUTDOWN_LAST,
              "unknown",
689
              "user")
J
Jiri Denemark 已提交
690 691 692 693 694 695 696 697 698 699 700 701

VIR_ENUM_IMPL(virDomainShutoffReason, VIR_DOMAIN_SHUTOFF_LAST,
              "unknown",
              "shutdown",
              "destroyed",
              "crashed",
              "migrated",
              "saved",
              "failed",
              "from snapshot")

VIR_ENUM_IMPL(virDomainCrashedReason, VIR_DOMAIN_CRASHED_LAST,
702 703
              "unknown",
              "panicked")
J
Jiri Denemark 已提交
704

705 706 707
VIR_ENUM_IMPL(virDomainPMSuspendedReason, VIR_DOMAIN_PMSUSPENDED_LAST,
              "unknown")

708
VIR_ENUM_IMPL(virDomainSeclabel, VIR_DOMAIN_SECLABEL_LAST,
709 710
              "default",
              "none",
711 712 713
              "dynamic",
              "static")

714 715
VIR_ENUM_IMPL(virDomainClockOffset, VIR_DOMAIN_CLOCK_OFFSET_LAST,
              "utc",
716
              "localtime",
717 718
              "variable",
              "timezone");
719

720 721 722 723
VIR_ENUM_IMPL(virDomainClockBasis, VIR_DOMAIN_CLOCK_BASIS_LAST,
              "utc",
              "localtime");

724 725 726 727 728
VIR_ENUM_IMPL(virDomainTimerName, VIR_DOMAIN_TIMER_NAME_LAST,
              "platform",
              "pit",
              "rtc",
              "hpet",
P
Paolo Bonzini 已提交
729
              "tsc",
730 731
              "kvmclock",
              "hypervclock");
732

733 734 735 736
VIR_ENUM_IMPL(virDomainTimerTrack, VIR_DOMAIN_TIMER_TRACK_LAST,
              "boot",
              "guest",
              "wall");
737 738 739 740 741 742 743 744 745 746 747

VIR_ENUM_IMPL(virDomainTimerTickpolicy, VIR_DOMAIN_TIMER_TICKPOLICY_LAST,
              "delay",
              "catchup",
              "merge",
              "discard");

VIR_ENUM_IMPL(virDomainTimerMode, VIR_DOMAIN_TIMER_MODE_LAST,
              "auto",
              "native",
              "emulate",
748 749
              "paravirt",
              "smpsafe");
750

751 752 753 754 755 756
VIR_ENUM_IMPL(virDomainStartupPolicy, VIR_DOMAIN_STARTUP_POLICY_LAST,
              "default",
              "mandatory",
              "requisite",
              "optional");

O
Osier Yang 已提交
757 758 759 760
VIR_ENUM_IMPL(virDomainCpuPlacementMode, VIR_DOMAIN_CPU_PLACEMENT_MODE_LAST,
              "static",
              "auto");

761 762 763 764
VIR_ENUM_IMPL(virDomainDiskTray, VIR_DOMAIN_DISK_TRAY_LAST,
              "closed",
              "open");

765 766 767 768 769 770 771 772 773
VIR_ENUM_IMPL(virDomainRNGModel,
              VIR_DOMAIN_RNG_MODEL_LAST,
              "virtio");

VIR_ENUM_IMPL(virDomainRNGBackend,
              VIR_DOMAIN_RNG_BACKEND_LAST,
              "random",
              "egd");

774 775 776 777 778 779
VIR_ENUM_IMPL(virDomainTPMModel, VIR_DOMAIN_TPM_MODEL_LAST,
              "tpm-tis")

VIR_ENUM_IMPL(virDomainTPMBackend, VIR_DOMAIN_TPM_TYPE_LAST,
              "passthrough")

O
Osier Yang 已提交
780 781
VIR_ENUM_IMPL(virDomainDiskDiscard, VIR_DOMAIN_DISK_DISCARD_LAST,
              "default",
O
Osier Yang 已提交
782 783
              "unmap",
              "ignore")
784

785 786 787 788 789 790
VIR_ENUM_IMPL(virDomainDiskMirrorState, VIR_DOMAIN_DISK_MIRROR_STATE_LAST,
              "none",
              "yes",
              "abort",
              "pivot")

791 792 793 794 795
VIR_ENUM_IMPL(virDomainLoader,
              VIR_DOMAIN_LOADER_TYPE_LAST,
              "rom",
              "pflash")

E
Eric Blake 已提交
796 797 798 799 800 801
/* Internal mapping: subset of block job types that can be present in
 * <mirror> XML (remaining types are not two-phase). */
VIR_ENUM_DECL(virDomainBlockJob)
VIR_ENUM_IMPL(virDomainBlockJob, VIR_DOMAIN_BLOCK_JOB_TYPE_LAST,
              "", "", "copy", "", "active-commit")

802 803 804
#define VIR_DOMAIN_XML_WRITE_FLAGS  VIR_DOMAIN_XML_SECURE
#define VIR_DOMAIN_XML_READ_FLAGS   VIR_DOMAIN_XML_INACTIVE

805
static virClassPtr virDomainObjClass;
806
static virClassPtr virDomainObjListClass;
807
static virClassPtr virDomainXMLOptionClass;
808
static void virDomainObjDispose(void *obj);
809
static void virDomainObjListDispose(void *obj);
810
static void virDomainXMLOptionClassDispose(void *obj);
811 812 813

static int virDomainObjOnceInit(void)
{
814
    if (!(virDomainObjClass = virClassNew(virClassForObjectLockable(),
815
                                          "virDomainObj",
816 817 818 819
                                          sizeof(virDomainObj),
                                          virDomainObjDispose)))
        return -1;

820 821 822 823 824 825
    if (!(virDomainObjListClass = virClassNew(virClassForObjectLockable(),
                                              "virDomainObjList",
                                              sizeof(virDomainObjList),
                                              virDomainObjListDispose)))
        return -1;

826 827 828
    if (!(virDomainXMLOptionClass = virClassNew(virClassForObject(),
                                                "virDomainXMLOption",
                                                sizeof(virDomainXMLOption),
829
                                                virDomainXMLOptionClassDispose)))
830 831
        return -1;

832 833 834 835 836
    return 0;
}

VIR_ONCE_GLOBAL_INIT(virDomainObj)

837

838 839 840 841 842 843 844 845 846 847
static void
virDomainXMLOptionClassDispose(void *obj)
{
    virDomainXMLOptionPtr xmlopt = obj;

    if (xmlopt->config.privFree)
        (xmlopt->config.privFree)(xmlopt->config.priv);
}


848
/**
849
 * virDomainXMLOptionNew:
850 851 852
 *
 * Allocate a new domain XML configuration
 */
853
virDomainXMLOptionPtr
854 855
virDomainXMLOptionNew(virDomainDefParserConfigPtr config,
                      virDomainXMLPrivateDataCallbacksPtr priv,
856
                      virDomainXMLNamespacePtr xmlns)
857
{
858
    virDomainXMLOptionPtr xmlopt;
859 860 861 862

    if (virDomainObjInitialize() < 0)
        return NULL;

863
    if (!(xmlopt = virObjectNew(virDomainXMLOptionClass)))
864 865 866
        return NULL;

    if (priv)
867
        xmlopt->privateData = *priv;
868

869 870 871
    if (config)
        xmlopt->config = *config;

872
    if (xmlns)
873
        xmlopt->ns = *xmlns;
874

875 876 877 878 879 880 881 882 883 884 885 886
    /* Technically this forbids to use one of Xerox's MAC address prefixes in
     * our hypervisor drivers. This shouldn't ever be a problem.
     *
     * Use the KVM prefix as default as it's in the privately administered
     * range */
    if (xmlopt->config.macPrefix[0] == 0 &&
        xmlopt->config.macPrefix[1] == 0 &&
        xmlopt->config.macPrefix[2] == 0) {
        xmlopt->config.macPrefix[0] = 0x52;
        xmlopt->config.macPrefix[1] = 0x54;
    }

887
    return xmlopt;
888 889 890
}

/**
891
 * virDomainXMLOptionGetNamespace:
892
 *
893
 * @xmlopt: XML parser configuration object
894 895
 *
 * Returns a pointer to the stored namespace structure.
896
 * The lifetime of the pointer is equal to @xmlopt;
897 898
 */
virDomainXMLNamespacePtr
899
virDomainXMLOptionGetNamespace(virDomainXMLOptionPtr xmlopt)
900
{
901
    return &xmlopt->ns;
902 903 904
}


905
void
906
virBlkioDeviceArrayClear(virBlkioDevicePtr devices,
907
                         int ndevices)
908
{
909
    size_t i;
910 911

    for (i = 0; i < ndevices; i++)
912
        VIR_FREE(devices[i].path);
913 914 915
}

/**
916
 * virDomainBlkioDeviceParseXML
917 918 919 920 921 922
 *
 * this function parses a XML node:
 *
 *   <device>
 *     <path>/fully/qualified/device/path</path>
 *     <weight>weight</weight>
923 924 925 926
 *     <read_bytes_sec>bps</read_bytes_sec>
 *     <write_bytes_sec>bps</write_bytes_sec>
 *     <read_iops_sec>iops</read_iops_sec>
 *     <write_iops_sec>iops</write_iops_sec>
927 928
 *   </device>
 *
929
 * and fills a virBlkioDevicePtr struct.
930 931
 */
static int
932
virDomainBlkioDeviceParseXML(xmlNodePtr root,
933
                             virBlkioDevicePtr dev)
934
{
935
    char *c = NULL;
936 937 938 939 940
    xmlNodePtr node;

    node = root->children;
    while (node) {
        if (node->type == XML_ELEMENT_NODE) {
941 942
            if (xmlStrEqual(node->name, BAD_CAST "path") && !dev->path) {
                dev->path = (char *)xmlNodeGetContent(node);
943 944
            } else if (xmlStrEqual(node->name, BAD_CAST "weight")) {
                c = (char *)xmlNodeGetContent(node);
945
                if (virStrToLong_ui(c, NULL, 10, &dev->weight) < 0) {
946 947 948
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("could not parse weight %s"),
                                   c);
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
                        goto error;
                }
                VIR_FREE(c);
            } else if (xmlStrEqual(node->name, BAD_CAST "read_bytes_sec")) {
                c = (char *)xmlNodeGetContent(node);
                if (virStrToLong_ull(c, NULL, 10, &dev->rbps) < 0) {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("could not parse read bytes sec %s"),
                                   c);
                    goto error;
                }
                VIR_FREE(c);
            } else if (xmlStrEqual(node->name, BAD_CAST "write_bytes_sec")) {
                c = (char *)xmlNodeGetContent(node);
                if (virStrToLong_ull(c, NULL, 10, &dev->wbps) < 0) {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("could not parse write bytes sec %s"),
                                   c);
                    goto error;
                }
                VIR_FREE(c);
            } else if (xmlStrEqual(node->name, BAD_CAST "read_iops_sec")) {
                c = (char *)xmlNodeGetContent(node);
                if (virStrToLong_ui(c, NULL, 10, &dev->riops) < 0) {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("could not parse read iops sec %s"),
                                   c);
                    goto error;
                }
                VIR_FREE(c);
            } else if (xmlStrEqual(node->name, BAD_CAST "write_iops_sec")) {
                c = (char *)xmlNodeGetContent(node);
                if (virStrToLong_ui(c, NULL, 10, &dev->wiops) < 0) {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("could not parse write iops sec %s"),
                                   c);
                    goto error;
986 987 988 989 990 991
                }
                VIR_FREE(c);
            }
        }
        node = node->next;
    }
992
    if (!dev->path) {
993 994
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("missing per-device path"));
995 996 997 998
        return -1;
    }

    return 0;
999

1000
 error:
1001 1002 1003
    VIR_FREE(c);
    VIR_FREE(dev->path);
    return -1;
1004 1005 1006 1007
}



1008
static void
1009
virDomainObjListDataFree(void *payload, const void *name ATTRIBUTE_UNUSED)
1010 1011
{
    virDomainObjPtr obj = payload;
1012
    virObjectUnref(obj);
1013 1014
}

1015
virDomainObjListPtr virDomainObjListNew(void)
1016
{
1017 1018
    virDomainObjListPtr doms;

1019 1020 1021 1022
    if (virDomainObjInitialize() < 0)
        return NULL;

    if (!(doms = virObjectLockableNew(virDomainObjListClass)))
1023 1024
        return NULL;

1025 1026
    if (!(doms->objs = virHashCreate(50, virDomainObjListDataFree))) {
        virObjectUnref(doms);
1027 1028
        return NULL;
    }
1029

1030
    return doms;
1031
}
1032

1033

1034
static void virDomainObjListDispose(void *obj)
1035
{
1036 1037
    virDomainObjListPtr doms = obj;

1038
    virHashFree(doms->objs);
1039 1040 1041 1042
}


static int virDomainObjListSearchID(const void *payload,
1043
                                    const void *name ATTRIBUTE_UNUSED,
1044 1045 1046 1047 1048 1049
                                    const void *data)
{
    virDomainObjPtr obj = (virDomainObjPtr)payload;
    const int *id = data;
    int want = 0;

1050
    virObjectLock(obj);
D
Daniel P. Berrange 已提交
1051
    if (virDomainObjIsActive(obj) &&
1052 1053
        obj->def->id == *id)
        want = 1;
1054
    virObjectUnlock(obj);
1055 1056 1057
    return want;
}

1058
virDomainObjPtr virDomainObjListFindByID(virDomainObjListPtr doms,
1059
                                         int id)
1060 1061
{
    virDomainObjPtr obj;
1062
    virObjectLock(doms);
1063 1064
    obj = virHashSearch(doms->objs, virDomainObjListSearchID, &id);
    if (obj)
1065
        virObjectLock(obj);
1066
    virObjectUnlock(doms);
1067
    return obj;
1068 1069 1070
}


1071
virDomainObjPtr virDomainObjListFindByUUID(virDomainObjListPtr doms,
1072
                                           const unsigned char *uuid)
1073
{
1074 1075
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virDomainObjPtr obj;
1076

1077
    virObjectLock(doms);
1078
    virUUIDFormat(uuid, uuidstr);
1079

1080 1081
    obj = virHashLookup(doms->objs, uuidstr);
    if (obj)
1082
        virObjectLock(obj);
1083
    virObjectUnlock(doms);
1084 1085 1086 1087
    return obj;
}

static int virDomainObjListSearchName(const void *payload,
1088
                                      const void *name ATTRIBUTE_UNUSED,
1089 1090 1091 1092 1093
                                      const void *data)
{
    virDomainObjPtr obj = (virDomainObjPtr)payload;
    int want = 0;

1094
    virObjectLock(obj);
1095 1096
    if (STREQ(obj->def->name, (const char *)data))
        want = 1;
1097
    virObjectUnlock(obj);
1098
    return want;
1099 1100
}

1101
virDomainObjPtr virDomainObjListFindByName(virDomainObjListPtr doms,
1102
                                           const char *name)
1103
{
1104
    virDomainObjPtr obj;
1105
    virObjectLock(doms);
1106 1107
    obj = virHashSearch(doms->objs, virDomainObjListSearchName, name);
    if (obj)
1108
        virObjectLock(obj);
1109
    virObjectUnlock(doms);
1110
    return obj;
1111 1112
}

1113 1114

bool virDomainObjTaint(virDomainObjPtr obj,
1115
                       virDomainTaintFlags taint)
1116
{
E
Eric Blake 已提交
1117
    unsigned int flag = (1 << taint);
1118 1119 1120 1121 1122 1123 1124 1125

    if (obj->taint & flag)
        return false;

    obj->taint |= flag;
    return true;
}

1126 1127 1128 1129 1130 1131 1132 1133 1134
static void
virDomainDeviceInfoFree(virDomainDeviceInfoPtr info)
{
    if (info) {
        virDomainDeviceInfoClear(info);
        VIR_FREE(info);
    }
}

1135

1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
static void
virDomainGraphicsAuthDefClear(virDomainGraphicsAuthDefPtr def)
{
    if (!def)
        return;

    VIR_FREE(def->passwd);

    /* Don't free def */
}

1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
static void
virDomainGraphicsListenDefClear(virDomainGraphicsListenDefPtr def)
{
    if (!def)
        return;

    VIR_FREE(def->address);
    VIR_FREE(def->network);
    return;
}

1158

1159 1160
void virDomainGraphicsDefFree(virDomainGraphicsDefPtr def)
{
1161
    size_t i;
1162

1163 1164 1165
    if (!def)
        return;

1166
    switch ((virDomainGraphicsType)def->type) {
1167
    case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
1168
        VIR_FREE(def->data.vnc.socket);
1169
        VIR_FREE(def->data.vnc.keymap);
1170
        virDomainGraphicsAuthDefClear(&def->data.vnc.auth);
1171 1172 1173 1174 1175 1176
        break;

    case VIR_DOMAIN_GRAPHICS_TYPE_SDL:
        VIR_FREE(def->data.sdl.display);
        VIR_FREE(def->data.sdl.xauth);
        break;
1177 1178 1179 1180 1181 1182 1183

    case VIR_DOMAIN_GRAPHICS_TYPE_RDP:
        break;

    case VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP:
        VIR_FREE(def->data.desktop.display);
        break;
1184 1185 1186

    case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
        VIR_FREE(def->data.spice.keymap);
1187
        virDomainGraphicsAuthDefClear(&def->data.spice.auth);
1188
        break;
1189 1190 1191

    case VIR_DOMAIN_GRAPHICS_TYPE_LAST:
        break;
1192 1193
    }

1194 1195
    for (i = 0; i < def->nListens; i++)
        virDomainGraphicsListenDefClear(&def->listens[i]);
1196 1197
    VIR_FREE(def->listens);

1198 1199 1200 1201 1202 1203 1204 1205
    VIR_FREE(def);
}

void virDomainInputDefFree(virDomainInputDefPtr def)
{
    if (!def)
        return;

1206
    virDomainDeviceInfoClear(&def->info);
1207 1208 1209
    VIR_FREE(def);
}

1210
void virDomainLeaseDefFree(virDomainLeaseDefPtr def)
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
{
    if (!def)
        return;

    VIR_FREE(def->lockspace);
    VIR_FREE(def->key);
    VIR_FREE(def->path);

    VIR_FREE(def);
}

1222

1223 1224 1225 1226 1227
virDomainDiskDefPtr
virDomainDiskDefNew(void)
{
    virDomainDiskDefPtr ret;

1228 1229 1230 1231
    if (VIR_ALLOC(ret) < 0)
        return NULL;
    if (VIR_ALLOC(ret->src) < 0)
        VIR_FREE(ret);
1232 1233 1234 1235
    return ret;
}


1236 1237 1238 1239 1240 1241
void
virDomainDiskDefFree(virDomainDiskDefPtr def)
{
    if (!def)
        return;

1242
    virStorageSourceFree(def->src);
1243 1244
    VIR_FREE(def->serial);
    VIR_FREE(def->dst);
1245
    virStorageSourceFree(def->mirror);
1246 1247 1248 1249
    VIR_FREE(def->wwn);
    VIR_FREE(def->vendor);
    VIR_FREE(def->product);
    virDomainDeviceInfoClear(&def->info);
1250

1251 1252 1253
    VIR_FREE(def);
}

1254

1255 1256 1257
int
virDomainDiskGetType(virDomainDiskDefPtr def)
{
1258
    return def->src->type;
1259 1260 1261 1262 1263 1264
}


void
virDomainDiskSetType(virDomainDiskDefPtr def, int type)
{
1265
    def->src->type = type;
1266 1267 1268 1269 1270 1271
}


const char *
virDomainDiskGetSource(virDomainDiskDefPtr def)
{
1272
    return def->src->path;
1273 1274 1275 1276 1277 1278 1279
}


int
virDomainDiskSetSource(virDomainDiskDefPtr def, const char *src)
{
    int ret;
1280
    char *tmp = def->src->path;
1281

1282
    ret = VIR_STRDUP(def->src->path, src);
1283
    if (ret < 0)
1284
        def->src->path = tmp;
1285 1286 1287 1288 1289 1290 1291 1292 1293
    else
        VIR_FREE(tmp);
    return ret;
}


const char *
virDomainDiskGetDriver(virDomainDiskDefPtr def)
{
1294
    return def->src->driverName;
1295 1296 1297 1298 1299 1300 1301
}


int
virDomainDiskSetDriver(virDomainDiskDefPtr def, const char *name)
{
    int ret;
1302
    char *tmp = def->src->driverName;
1303

1304
    ret = VIR_STRDUP(def->src->driverName, name);
1305
    if (ret < 0)
1306
        def->src->driverName = tmp;
1307 1308 1309 1310 1311 1312 1313 1314 1315
    else
        VIR_FREE(tmp);
    return ret;
}


int
virDomainDiskGetFormat(virDomainDiskDefPtr def)
{
1316
    return def->src->format;
1317 1318 1319 1320 1321 1322
}


void
virDomainDiskSetFormat(virDomainDiskDefPtr def, int format)
{
1323
    def->src->format = format;
1324 1325 1326
}


1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
void virDomainControllerDefFree(virDomainControllerDefPtr def)
{
    if (!def)
        return;

    virDomainDeviceInfoClear(&def->info);

    VIR_FREE(def);
}

1337 1338 1339 1340 1341 1342 1343
void virDomainFSDefFree(virDomainFSDefPtr def)
{
    if (!def)
        return;

    VIR_FREE(def->src);
    VIR_FREE(def->dst);
1344
    virDomainDeviceInfoClear(&def->info);
1345 1346 1347 1348

    VIR_FREE(def);
}

1349 1350 1351 1352 1353 1354 1355 1356
void
virDomainActualNetDefFree(virDomainActualNetDefPtr def)
{
    if (!def)
        return;

    switch (def->type) {
    case VIR_DOMAIN_NET_TYPE_BRIDGE:
1357
    case VIR_DOMAIN_NET_TYPE_NETWORK:
1358 1359 1360 1361 1362
        VIR_FREE(def->data.bridge.brname);
        break;
    case VIR_DOMAIN_NET_TYPE_DIRECT:
        VIR_FREE(def->data.direct.linkdev);
        break;
1363 1364 1365
    case VIR_DOMAIN_NET_TYPE_HOSTDEV:
        virDomainHostdevDefClear(&def->data.hostdev.def);
        break;
1366 1367 1368 1369
    default:
        break;
    }

1370
    VIR_FREE(def->virtPortProfile);
1371
    virNetDevBandwidthFree(def->bandwidth);
1372
    virNetDevVlanClear(&def->vlan);
1373 1374 1375
    VIR_FREE(def);
}

1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
void virDomainNetDefFree(virDomainNetDefPtr def)
{
    if (!def)
        return;

    VIR_FREE(def->model);

    switch (def->type) {
    case VIR_DOMAIN_NET_TYPE_ETHERNET:
        VIR_FREE(def->data.ethernet.dev);
        VIR_FREE(def->data.ethernet.ipaddr);
        break;

M
Michele Paolino 已提交
1389 1390 1391 1392
    case VIR_DOMAIN_NET_TYPE_VHOSTUSER:
        virDomainChrSourceDefFree(def->data.vhostuser);
        break;

1393 1394 1395 1396 1397 1398 1399 1400
    case VIR_DOMAIN_NET_TYPE_SERVER:
    case VIR_DOMAIN_NET_TYPE_CLIENT:
    case VIR_DOMAIN_NET_TYPE_MCAST:
        VIR_FREE(def->data.socket.address);
        break;

    case VIR_DOMAIN_NET_TYPE_NETWORK:
        VIR_FREE(def->data.network.name);
1401 1402
        VIR_FREE(def->data.network.portgroup);
        virDomainActualNetDefFree(def->data.network.actual);
1403 1404 1405 1406
        break;

    case VIR_DOMAIN_NET_TYPE_BRIDGE:
        VIR_FREE(def->data.bridge.brname);
1407
        VIR_FREE(def->data.bridge.ipaddr);
1408
        break;
D
Daniel Veillard 已提交
1409 1410 1411 1412

    case VIR_DOMAIN_NET_TYPE_INTERNAL:
        VIR_FREE(def->data.internal.name);
        break;
1413 1414 1415 1416

    case VIR_DOMAIN_NET_TYPE_DIRECT:
        VIR_FREE(def->data.direct.linkdev);
        break;
S
Stefan Berger 已提交
1417

1418 1419 1420 1421
    case VIR_DOMAIN_NET_TYPE_HOSTDEV:
        virDomainHostdevDefClear(&def->data.hostdev.def);
        break;

S
Stefan Berger 已提交
1422 1423 1424
    case VIR_DOMAIN_NET_TYPE_USER:
    case VIR_DOMAIN_NET_TYPE_LAST:
        break;
1425 1426
    }

1427 1428
    VIR_FREE(def->backend.tap);
    VIR_FREE(def->backend.vhost);
1429
    VIR_FREE(def->virtPortProfile);
1430
    VIR_FREE(def->script);
1431
    VIR_FREE(def->ifname);
1432 1433
    VIR_FREE(def->ifname_guest);
    VIR_FREE(def->ifname_guest_actual);
1434 1435 1436

    virDomainDeviceInfoClear(&def->info);

1437 1438 1439
    VIR_FREE(def->filter);
    virNWFilterHashTableFree(def->filterparams);

1440
    virNetDevBandwidthFree(def->bandwidth);
1441
    virNetDevVlanClear(&def->vlan);
1442

1443 1444 1445
    VIR_FREE(def);
}

1446
void ATTRIBUTE_NONNULL(1)
1447
virDomainChrSourceDefClear(virDomainChrSourceDefPtr def)
1448 1449 1450 1451 1452 1453 1454 1455 1456
{
    switch (def->type) {
    case VIR_DOMAIN_CHR_TYPE_PTY:
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
    case VIR_DOMAIN_CHR_TYPE_PIPE:
        VIR_FREE(def->data.file.path);
        break;

1457 1458 1459 1460 1461
    case VIR_DOMAIN_CHR_TYPE_NMDM:
        VIR_FREE(def->data.nmdm.master);
        VIR_FREE(def->data.nmdm.slave);
        break;

1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
    case VIR_DOMAIN_CHR_TYPE_UDP:
        VIR_FREE(def->data.udp.bindHost);
        VIR_FREE(def->data.udp.bindService);
        VIR_FREE(def->data.udp.connectHost);
        VIR_FREE(def->data.udp.connectService);
        break;

    case VIR_DOMAIN_CHR_TYPE_TCP:
        VIR_FREE(def->data.tcp.host);
        VIR_FREE(def->data.tcp.service);
        break;

    case VIR_DOMAIN_CHR_TYPE_UNIX:
        VIR_FREE(def->data.nix.path);
        break;
1477 1478 1479 1480

    case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
        VIR_FREE(def->data.spiceport.channel);
        break;
1481
    }
1482 1483
}

1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
/* Deep copies the contents of src into dest.  Return -1 and report
 * error on failure.  */
int
virDomainChrSourceDefCopy(virDomainChrSourceDefPtr dest,
                          virDomainChrSourceDefPtr src)
{
    if (!dest || !src)
        return -1;

    virDomainChrSourceDefClear(dest);

    switch (src->type) {
    case VIR_DOMAIN_CHR_TYPE_PTY:
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
    case VIR_DOMAIN_CHR_TYPE_PIPE:
1500
        if (VIR_STRDUP(dest->data.file.path, src->data.file.path) < 0)
1501 1502 1503 1504
            return -1;
        break;

    case VIR_DOMAIN_CHR_TYPE_UDP:
1505
        if (VIR_STRDUP(dest->data.udp.bindHost, src->data.udp.bindHost) < 0)
1506 1507
            return -1;

1508
        if (VIR_STRDUP(dest->data.udp.bindService, src->data.udp.bindService) < 0)
1509 1510
            return -1;

1511
        if (VIR_STRDUP(dest->data.udp.connectHost, src->data.udp.connectHost) < 0)
1512 1513
            return -1;

1514
        if (VIR_STRDUP(dest->data.udp.connectService, src->data.udp.connectService) < 0)
1515 1516 1517 1518
            return -1;
        break;

    case VIR_DOMAIN_CHR_TYPE_TCP:
1519
        if (VIR_STRDUP(dest->data.tcp.host, src->data.tcp.host) < 0)
1520 1521
            return -1;

1522
        if (VIR_STRDUP(dest->data.tcp.service, src->data.tcp.service) < 0)
1523 1524 1525 1526
            return -1;
        break;

    case VIR_DOMAIN_CHR_TYPE_UNIX:
1527
        if (VIR_STRDUP(dest->data.nix.path, src->data.nix.path) < 0)
1528 1529
            return -1;
        break;
1530 1531 1532 1533 1534 1535 1536 1537

    case VIR_DOMAIN_CHR_TYPE_NMDM:
        if (VIR_STRDUP(dest->data.nmdm.master, src->data.nmdm.master) < 0)
            return -1;
        if (VIR_STRDUP(dest->data.nmdm.slave, src->data.nmdm.slave) < 0)
            return -1;

        break;
1538 1539
    }

S
Stefan Berger 已提交
1540 1541
    dest->type = src->type;

1542 1543 1544
    return 0;
}

1545 1546 1547 1548 1549 1550 1551 1552 1553
void virDomainChrSourceDefFree(virDomainChrSourceDefPtr def)
{
    if (!def)
        return;

    virDomainChrSourceDefClear(def);

    VIR_FREE(def);
}
1554

1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
/* virDomainChrSourceDefIsEqual:
 * @src: Source
 * @tgt: Target
 *
 * Compares source and target if they contain
 * the same information.
 */
static bool
virDomainChrSourceDefIsEqual(const virDomainChrSourceDef *src,
                             const virDomainChrSourceDef *tgt)
{
    if (tgt->type != src->type)
        return false;

1569
    switch ((virDomainChrType)src->type) {
1570 1571 1572 1573 1574 1575
    case VIR_DOMAIN_CHR_TYPE_PTY:
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
    case VIR_DOMAIN_CHR_TYPE_PIPE:
        return STREQ_NULLABLE(src->data.file.path, tgt->data.file.path);
        break;
1576 1577 1578 1579
    case VIR_DOMAIN_CHR_TYPE_NMDM:
        return STREQ_NULLABLE(src->data.nmdm.master, tgt->data.nmdm.master) &&
            STREQ_NULLABLE(src->data.nmdm.slave, tgt->data.nmdm.slave);
        break;
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
    case VIR_DOMAIN_CHR_TYPE_UDP:
        return STREQ_NULLABLE(src->data.udp.bindHost, tgt->data.udp.bindHost) &&
            STREQ_NULLABLE(src->data.udp.bindService, tgt->data.udp.bindService) &&
            STREQ_NULLABLE(src->data.udp.connectHost, tgt->data.udp.connectHost) &&
            STREQ_NULLABLE(src->data.udp.connectService, tgt->data.udp.connectService);
        break;
    case VIR_DOMAIN_CHR_TYPE_TCP:
        return src->data.tcp.listen == tgt->data.tcp.listen &&
            src->data.tcp.protocol == tgt->data.tcp.protocol &&
            STREQ_NULLABLE(src->data.tcp.host, tgt->data.tcp.host) &&
            STREQ_NULLABLE(src->data.tcp.service, tgt->data.tcp.service);
        break;
    case VIR_DOMAIN_CHR_TYPE_UNIX:
        return src->data.nix.listen == tgt->data.nix.listen &&
            STREQ_NULLABLE(src->data.nix.path, tgt->data.nix.path);
        break;

1597 1598 1599 1600 1601
    case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
        return STREQ_NULLABLE(src->data.spiceport.channel,
                              tgt->data.spiceport.channel);
        break;

J
Ján Tomko 已提交
1602 1603 1604
    case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
        return src->data.spicevmc == tgt->data.spicevmc;

1605
    case VIR_DOMAIN_CHR_TYPE_NULL:
1606 1607
    case VIR_DOMAIN_CHR_TYPE_VC:
    case VIR_DOMAIN_CHR_TYPE_STDIO:
1608 1609
    case VIR_DOMAIN_CHR_TYPE_LAST:
        break;
1610 1611
    }

J
Ján Tomko 已提交
1612
    return true;
1613 1614
}

1615 1616
void virDomainChrDefFree(virDomainChrDefPtr def)
{
1617 1618
    size_t i;

1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
    if (!def)
        return;

    switch (def->deviceType) {
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
        switch (def->targetType) {
        case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_GUESTFWD:
            VIR_FREE(def->target.addr);
            break;

        case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO:
            VIR_FREE(def->target.name);
            break;
        }
        break;

    default:
        break;
    }

    virDomainChrSourceDefClear(&def->source);
1640 1641
    virDomainDeviceInfoClear(&def->info);

1642 1643 1644 1645 1646 1647
    if (def->seclabels) {
        for (i = 0; i < def->nseclabels; i++)
            virSecurityDeviceLabelDefFree(def->seclabels[i]);
        VIR_FREE(def->seclabels);
    }

1648 1649 1650
    VIR_FREE(def);
}

E
Eric Blake 已提交
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
void virDomainSmartcardDefFree(virDomainSmartcardDefPtr def)
{
    size_t i;
    if (!def)
        return;

    switch (def->type) {
    case VIR_DOMAIN_SMARTCARD_TYPE_HOST:
        break;

    case VIR_DOMAIN_SMARTCARD_TYPE_HOST_CERTIFICATES:
        for (i = 0; i < VIR_DOMAIN_SMARTCARD_NUM_CERTIFICATES; i++)
            VIR_FREE(def->data.cert.file[i]);
        VIR_FREE(def->data.cert.database);
        break;

    case VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH:
        virDomainChrSourceDefClear(&def->data.passthru);
        break;

    default:
        break;
    }

    virDomainDeviceInfoClear(&def->info);

    VIR_FREE(def);
}

1680 1681 1682 1683 1684 1685 1686 1687
void virDomainSoundCodecDefFree(virDomainSoundCodecDefPtr def)
{
    if (!def)
        return;

    VIR_FREE(def);
}

1688 1689 1690 1691 1692
void virDomainSoundDefFree(virDomainSoundDefPtr def)
{
    if (!def)
        return;

1693 1694
    virDomainDeviceInfoClear(&def->info);

1695
    size_t i;
1696
    for (i = 0; i < def->ncodecs; i++)
1697 1698 1699
        virDomainSoundCodecDefFree(def->codecs[i]);
    VIR_FREE(def->codecs);

1700 1701 1702
    VIR_FREE(def);
}

1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
void virDomainMemballoonDefFree(virDomainMemballoonDefPtr def)
{
    if (!def)
        return;

    virDomainDeviceInfoClear(&def->info);

    VIR_FREE(def);
}

L
Li Zhang 已提交
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
void virDomainNVRAMDefFree(virDomainNVRAMDefPtr def)
{
    if (!def)
        return;

    virDomainDeviceInfoClear(&def->info);

    VIR_FREE(def);
}

R
Richard Jones 已提交
1723 1724 1725 1726 1727
void virDomainWatchdogDefFree(virDomainWatchdogDefPtr def)
{
    if (!def)
        return;

1728 1729
    virDomainDeviceInfoClear(&def->info);

R
Richard Jones 已提交
1730 1731 1732
    VIR_FREE(def);
}

1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
void virDomainShmemDefFree(virDomainShmemDefPtr def)
{
    if (!def)
        return;

    virDomainDeviceInfoClear(&def->info);
    VIR_FREE(def->server.path);
    VIR_FREE(def->name);
    VIR_FREE(def);
}

1744 1745 1746 1747 1748
void virDomainVideoDefFree(virDomainVideoDefPtr def)
{
    if (!def)
        return;

1749 1750
    virDomainDeviceInfoClear(&def->info);

1751
    VIR_FREE(def->accel);
1752 1753 1754
    VIR_FREE(def);
}

1755 1756 1757 1758
virDomainHostdevDefPtr virDomainHostdevDefAlloc(void)
{
    virDomainHostdevDefPtr def = NULL;

1759 1760
    if (VIR_ALLOC(def) < 0 ||
        VIR_ALLOC(def->info) < 0)
1761 1762 1763 1764
        VIR_FREE(def);
    return def;
}

1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
static void
virDomainHostdevSubsysSCSIiSCSIClear(virDomainHostdevSubsysSCSIiSCSIPtr iscsisrc)
{
    if (!iscsisrc)
        return;
    VIR_FREE(iscsisrc->path);
    virStorageNetHostDefFree(iscsisrc->nhosts, iscsisrc->hosts);
    virStorageAuthDefFree(iscsisrc->auth);
    iscsisrc->auth = NULL;
}

1776 1777 1778 1779 1780 1781 1782 1783 1784
void virDomainHostdevDefClear(virDomainHostdevDefPtr def)
{
    if (!def)
        return;

    /* Free all resources in the hostdevdef. Currently the only
     * such resource is the virDomainDeviceInfo.
     */

1785 1786 1787 1788 1789
    /* If there is a parent device object, it will handle freeing
     * def->info.
     */
    if (def->parent.type == VIR_DOMAIN_DEVICE_NONE)
        virDomainDeviceInfoFree(def->info);
1790

H
Han Cheng 已提交
1791 1792
    switch (def->mode) {
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
1793 1794 1795 1796 1797 1798 1799
        switch (def->source.caps.type) {
        case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_STORAGE:
            VIR_FREE(def->source.caps.u.storage.block);
            break;
        case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_MISC:
            VIR_FREE(def->source.caps.u.misc.chardev);
            break;
1800 1801 1802
        case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_NET:
            VIR_FREE(def->source.caps.u.net.iface);
            break;
1803
        }
H
Han Cheng 已提交
1804 1805
        break;
    case VIR_DOMAIN_HOSTDEV_MODE_SUBSYS:
1806 1807 1808 1809 1810 1811 1812 1813 1814
        if (def->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI) {
            virDomainHostdevSubsysSCSIPtr scsisrc = &def->source.subsys.u.scsi;
            if (scsisrc->protocol ==
                VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
                virDomainHostdevSubsysSCSIiSCSIClear(&scsisrc->u.iscsi);
            } else {
                VIR_FREE(scsisrc->u.host.adapter);
            }
        }
H
Han Cheng 已提交
1815
        break;
1816
    }
1817 1818
}

1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
void virDomainTPMDefFree(virDomainTPMDefPtr def)
{
    if (!def)
        return;

    switch (def->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
        VIR_FREE(def->data.passthrough.source.data.file.path);
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

    virDomainDeviceInfoClear(&def->info);
    VIR_FREE(def);
}

1836 1837 1838 1839 1840
void virDomainHostdevDefFree(virDomainHostdevDefPtr def)
{
    if (!def)
        return;

1841 1842 1843
    /* free all subordinate objects */
    virDomainHostdevDefClear(def);

1844 1845 1846 1847 1848
    /* If there is a parent device object, it will handle freeing
     * the memory.
     */
    if (def->parent.type == VIR_DOMAIN_DEVICE_NONE)
        VIR_FREE(def);
1849 1850
}

M
Marc-André Lureau 已提交
1851 1852 1853 1854 1855 1856 1857 1858 1859
void virDomainHubDefFree(virDomainHubDefPtr def)
{
    if (!def)
        return;

    virDomainDeviceInfoClear(&def->info);
    VIR_FREE(def);
}

1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
void virDomainRedirdevDefFree(virDomainRedirdevDefPtr def)
{
    if (!def)
        return;

    virDomainChrSourceDefClear(&def->source.chr);
    virDomainDeviceInfoClear(&def->info);

    VIR_FREE(def);
}

1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
void virDomainRedirFilterDefFree(virDomainRedirFilterDefPtr def)
{
    size_t i;

    if (!def)
        return;

    for (i = 0; i < def->nusbdevs; i++)
        VIR_FREE(def->usbdevs[i]);

    VIR_FREE(def->usbdevs);
    VIR_FREE(def);
}

1885 1886 1887 1888 1889
void virDomainDeviceDefFree(virDomainDeviceDefPtr def)
{
    if (!def)
        return;

1890
    switch ((virDomainDeviceType) def->type) {
1891 1892 1893
    case VIR_DOMAIN_DEVICE_DISK:
        virDomainDiskDefFree(def->data.disk);
        break;
1894 1895 1896
    case VIR_DOMAIN_DEVICE_LEASE:
        virDomainLeaseDefFree(def->data.lease);
        break;
1897 1898 1899 1900 1901 1902 1903 1904 1905
    case VIR_DOMAIN_DEVICE_NET:
        virDomainNetDefFree(def->data.net);
        break;
    case VIR_DOMAIN_DEVICE_INPUT:
        virDomainInputDefFree(def->data.input);
        break;
    case VIR_DOMAIN_DEVICE_SOUND:
        virDomainSoundDefFree(def->data.sound);
        break;
1906 1907 1908
    case VIR_DOMAIN_DEVICE_VIDEO:
        virDomainVideoDefFree(def->data.video);
        break;
1909 1910 1911
    case VIR_DOMAIN_DEVICE_HOSTDEV:
        virDomainHostdevDefFree(def->data.hostdev);
        break;
R
Richard Jones 已提交
1912 1913 1914
    case VIR_DOMAIN_DEVICE_WATCHDOG:
        virDomainWatchdogDefFree(def->data.watchdog);
        break;
1915 1916 1917
    case VIR_DOMAIN_DEVICE_CONTROLLER:
        virDomainControllerDefFree(def->data.controller);
        break;
1918 1919 1920
    case VIR_DOMAIN_DEVICE_GRAPHICS:
        virDomainGraphicsDefFree(def->data.graphics);
        break;
M
Marc-André Lureau 已提交
1921 1922 1923
    case VIR_DOMAIN_DEVICE_HUB:
        virDomainHubDefFree(def->data.hub);
        break;
1924 1925 1926
    case VIR_DOMAIN_DEVICE_REDIRDEV:
        virDomainRedirdevDefFree(def->data.redirdev);
        break;
1927 1928 1929
    case VIR_DOMAIN_DEVICE_RNG:
        virDomainRNGDefFree(def->data.rng);
        break;
1930 1931 1932
    case VIR_DOMAIN_DEVICE_CHR:
        virDomainChrDefFree(def->data.chr);
        break;
1933
    case VIR_DOMAIN_DEVICE_FS:
1934 1935
        virDomainFSDefFree(def->data.fs);
        break;
1936
    case VIR_DOMAIN_DEVICE_SMARTCARD:
1937 1938
        virDomainSmartcardDefFree(def->data.smartcard);
        break;
1939
    case VIR_DOMAIN_DEVICE_MEMBALLOON:
1940 1941
        virDomainMemballoonDefFree(def->data.memballoon);
        break;
L
Li Zhang 已提交
1942
    case VIR_DOMAIN_DEVICE_NVRAM:
1943 1944
        virDomainNVRAMDefFree(def->data.nvram);
        break;
1945 1946 1947
    case VIR_DOMAIN_DEVICE_SHMEM:
        virDomainShmemDefFree(def->data.shmem);
        break;
1948 1949 1950
    case VIR_DOMAIN_DEVICE_TPM:
        virDomainTPMDefFree(def->data.tpm);
        break;
1951 1952 1953
    case VIR_DOMAIN_DEVICE_PANIC:
        virDomainPanicDefFree(def->data.panic);
        break;
1954
    case VIR_DOMAIN_DEVICE_LAST:
1955
    case VIR_DOMAIN_DEVICE_NONE:
1956
        break;
1957 1958 1959 1960 1961
    }

    VIR_FREE(def);
}

1962 1963 1964 1965 1966 1967
static void
virDomainClockDefClear(virDomainClockDefPtr def)
{
    if (def->offset == VIR_DOMAIN_CLOCK_OFFSET_TIMEZONE)
        VIR_FREE(def->data.timezone);

1968
    size_t i;
1969 1970 1971 1972 1973
    for (i = 0; i < def->ntimers; i++)
        VIR_FREE(def->timers[i]);
    VIR_FREE(def->timers);
}

1974 1975 1976
virDomainVcpuPinDefPtr *
virDomainVcpuPinDefCopy(virDomainVcpuPinDefPtr *src, int nvcpupin)
{
1977
    size_t i;
1978
    virDomainVcpuPinDefPtr *ret = NULL;
1979

1980 1981
    if (VIR_ALLOC_N(ret, nvcpupin) < 0)
        goto error;
1982 1983 1984

    for (i = 0; i < nvcpupin; i++) {
        if (VIR_ALLOC(ret[i]) < 0)
1985
            goto error;
1986
        ret[i]->vcpuid = src[i]->vcpuid;
H
Hu Tao 已提交
1987
        if ((ret[i]->cpumask = virBitmapNewCopy(src[i]->cpumask)) == NULL)
1988
            goto error;
1989 1990 1991 1992
    }

    return ret;

1993
 error:
1994
    if (ret) {
1995
        for (i = 0; i < nvcpupin; i++) {
1996
            if (ret[i]) {
H
Hu Tao 已提交
1997
                virBitmapFree(ret[i]->cpumask);
1998 1999 2000 2001
                VIR_FREE(ret[i]);
            }
        }
        VIR_FREE(ret);
2002 2003 2004 2005 2006 2007
    }

    return NULL;
}

void
H
Hu Tao 已提交
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
virDomainVcpuPinDefFree(virDomainVcpuPinDefPtr def)
{
    if (def) {
        virBitmapFree(def->cpumask);
        VIR_FREE(def);
    }
}

void
virDomainVcpuPinDefArrayFree(virDomainVcpuPinDefPtr *def,
                             int nvcpupin)
2019
{
2020
    size_t i;
2021

2022
    if (!def)
2023 2024
        return;

2025
    for (i = 0; i < nvcpupin; i++)
H
Hu Tao 已提交
2026
        virDomainVcpuPinDefFree(def[i]);
2027 2028 2029 2030

    VIR_FREE(def);
}

2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041

void
virDomainResourceDefFree(virDomainResourceDefPtr resource)
{
    if (!resource)
        return;

    VIR_FREE(resource->partition);
    VIR_FREE(resource);
}

H
Hu Tao 已提交
2042 2043 2044 2045 2046 2047 2048 2049 2050
void
virDomainPanicDefFree(virDomainPanicDefPtr panic)
{
    if (!panic)
        return;

    virDomainDeviceInfoClear(&panic->info);
    VIR_FREE(panic);
}
2051

2052 2053 2054 2055 2056 2057 2058 2059
void
virDomainLoaderDefFree(virDomainLoaderDefPtr loader)
{
    if (!loader)
        return;

    VIR_FREE(loader->path);
    VIR_FREE(loader->nvram);
2060
    VIR_FREE(loader->templt);
2061 2062 2063
    VIR_FREE(loader);
}

2064 2065
void virDomainDefFree(virDomainDefPtr def)
{
2066
    size_t i;
2067

2068 2069 2070
    if (!def)
        return;

2071 2072
    virDomainResourceDefFree(def->resource);

2073 2074 2075 2076 2077 2078
    /* hostdevs must be freed before nets (or any future "intelligent
     * hostdevs") because the pointer to the hostdev is really
     * pointing into the middle of the higher level device's object,
     * so the original object must still be available during the call
     * to virDomainHostdevDefFree().
     */
2079
    for (i = 0; i < def->nhostdevs; i++)
2080 2081 2082
        virDomainHostdevDefFree(def->hostdevs[i]);
    VIR_FREE(def->hostdevs);

2083
    for (i = 0; i < def->nleases; i++)
2084 2085 2086
        virDomainLeaseDefFree(def->leases[i]);
    VIR_FREE(def->leases);

2087
    for (i = 0; i < def->ngraphics; i++)
2088 2089
        virDomainGraphicsDefFree(def->graphics[i]);
    VIR_FREE(def->graphics);
2090

2091
    for (i = 0; i < def->ninputs; i++)
2092 2093 2094
        virDomainInputDefFree(def->inputs[i]);
    VIR_FREE(def->inputs);

2095
    for (i = 0; i < def->ndisks; i++)
2096 2097 2098
        virDomainDiskDefFree(def->disks[i]);
    VIR_FREE(def->disks);

2099
    for (i = 0; i < def->ncontrollers; i++)
2100 2101 2102
        virDomainControllerDefFree(def->controllers[i]);
    VIR_FREE(def->controllers);

2103
    for (i = 0; i < def->nfss; i++)
2104 2105 2106
        virDomainFSDefFree(def->fss[i]);
    VIR_FREE(def->fss);

2107
    for (i = 0; i < def->nnets; i++)
2108 2109
        virDomainNetDefFree(def->nets[i]);
    VIR_FREE(def->nets);
2110

2111
    for (i = 0; i < def->nsmartcards; i++)
E
Eric Blake 已提交
2112 2113 2114
        virDomainSmartcardDefFree(def->smartcards[i]);
    VIR_FREE(def->smartcards);

2115
    for (i = 0; i < def->nserials; i++)
2116 2117 2118
        virDomainChrDefFree(def->serials[i]);
    VIR_FREE(def->serials);

2119
    for (i = 0; i < def->nparallels; i++)
2120 2121 2122
        virDomainChrDefFree(def->parallels[i]);
    VIR_FREE(def->parallels);

2123
    for (i = 0; i < def->nchannels; i++)
2124 2125 2126
        virDomainChrDefFree(def->channels[i]);
    VIR_FREE(def->channels);

2127
    for (i = 0; i < def->nconsoles; i++)
2128 2129
        virDomainChrDefFree(def->consoles[i]);
    VIR_FREE(def->consoles);
2130

2131
    for (i = 0; i < def->nsounds; i++)
2132 2133 2134
        virDomainSoundDefFree(def->sounds[i]);
    VIR_FREE(def->sounds);

2135
    for (i = 0; i < def->nvideos; i++)
2136 2137 2138
        virDomainVideoDefFree(def->videos[i]);
    VIR_FREE(def->videos);

2139
    for (i = 0; i < def->nhubs; i++)
M
Marc-André Lureau 已提交
2140 2141 2142
        virDomainHubDefFree(def->hubs[i]);
    VIR_FREE(def->hubs);

2143
    for (i = 0; i < def->nredirdevs; i++)
2144 2145 2146
        virDomainRedirdevDefFree(def->redirdevs[i]);
    VIR_FREE(def->redirdevs);

2147 2148 2149
    for (i = 0; i < def->nrngs; i++)
        virDomainRNGDefFree(def->rngs[i]);
    VIR_FREE(def->rngs);
2150

2151 2152
    virDomainTPMDefFree(def->tpm);

H
Hu Tao 已提交
2153 2154
    virDomainPanicDefFree(def->panic);

2155 2156 2157
    VIR_FREE(def->idmap.uidmap);
    VIR_FREE(def->idmap.gidmap);

2158 2159
    VIR_FREE(def->os.type);
    VIR_FREE(def->os.machine);
2160
    VIR_FREE(def->os.init);
2161
    for (i = 0; def->os.initargv && def->os.initargv[i]; i++)
2162 2163
        VIR_FREE(def->os.initargv[i]);
    VIR_FREE(def->os.initargv);
2164 2165 2166
    VIR_FREE(def->os.kernel);
    VIR_FREE(def->os.initrd);
    VIR_FREE(def->os.cmdline);
2167
    VIR_FREE(def->os.dtb);
2168
    VIR_FREE(def->os.root);
2169
    virDomainLoaderDefFree(def->os.loader);
2170 2171 2172
    VIR_FREE(def->os.bootloader);
    VIR_FREE(def->os.bootloaderArgs);

2173
    virDomainClockDefClear(&def->clock);
2174

2175
    VIR_FREE(def->name);
2176
    virBitmapFree(def->cpumask);
2177
    VIR_FREE(def->emulator);
2178
    VIR_FREE(def->description);
2179
    VIR_FREE(def->title);
2180

2181 2182
    virBlkioDeviceArrayClear(def->blkio.devices,
                             def->blkio.ndevices);
2183 2184
    VIR_FREE(def->blkio.devices);

R
Richard Jones 已提交
2185 2186
    virDomainWatchdogDefFree(def->watchdog);

C
Chris Lalancette 已提交
2187
    virDomainMemballoonDefFree(def->memballoon);
L
Li Zhang 已提交
2188
    virDomainNVRAMDefFree(def->nvram);
C
Chris Lalancette 已提交
2189

2190 2191 2192 2193
    for (i = 0; i < def->mem.nhugepages; i++)
        virBitmapFree(def->mem.hugepages[i].nodemask);
    VIR_FREE(def->mem.hugepages);

2194 2195 2196
    for (i = 0; i < def->nseclabels; i++)
        virSecurityLabelDefFree(def->seclabels[i]);
    VIR_FREE(def->seclabels);
2197

2198 2199
    virCPUDefFree(def->cpu);

H
Hu Tao 已提交
2200 2201 2202
    virDomainVcpuPinDefArrayFree(def->cputune.vcpupin, def->cputune.nvcpupin);

    virDomainVcpuPinDefFree(def->cputune.emulatorpin);
2203

2204 2205 2206
    virDomainVcpuPinDefArrayFree(def->cputune.iothreadspin,
                                 def->cputune.niothreadspin);

2207
    virDomainNumatuneFree(def->numatune);
O
Osier Yang 已提交
2208

2209 2210
    virSysinfoDefFree(def->sysinfo);

2211 2212
    virDomainRedirFilterDefFree(def->redirfilter);

2213 2214 2215 2216
    for (i = 0; i < def->nshmems; i++)
        virDomainShmemDefFree(def->shmems[i]);
    VIR_FREE(def->shmems);

2217 2218 2219
    if (def->namespaceData && def->ns.free)
        (def->ns.free)(def->namespaceData);

2220 2221
    xmlFreeNode(def->metadata);

2222 2223 2224
    VIR_FREE(def);
}

2225
static void virDomainObjDispose(void *obj)
2226
{
2227
    virDomainObjPtr dom = obj;
2228

2229
    VIR_DEBUG("obj=%p", dom);
2230 2231 2232
    virDomainDefFree(dom->def);
    virDomainDefFree(dom->newDef);

2233 2234 2235
    if (dom->privateDataFreeFunc)
        (dom->privateDataFreeFunc)(dom->privateData);

2236
    virDomainSnapshotObjListFree(dom->snapshots);
2237 2238
}

2239
virDomainObjPtr
2240
virDomainObjNew(virDomainXMLOptionPtr xmlopt)
2241 2242 2243
{
    virDomainObjPtr domain;

2244 2245 2246
    if (virDomainObjInitialize() < 0)
        return NULL;

2247
    if (!(domain = virObjectLockableNew(virDomainObjClass)))
2248 2249
        return NULL;

2250
    if (xmlopt->privateData.alloc) {
2251
        if (!(domain->privateData = (xmlopt->privateData.alloc)()))
2252
            goto error;
2253
        domain->privateDataFreeFunc = xmlopt->privateData.free;
2254 2255 2256 2257 2258
    }

    if (!(domain->snapshots = virDomainSnapshotObjListNew()))
        goto error;

2259
    virObjectLock(domain);
J
Jiri Denemark 已提交
2260 2261
    virDomainObjSetState(domain, VIR_DOMAIN_SHUTOFF,
                                 VIR_DOMAIN_SHUTOFF_UNKNOWN);
2262

2263
    VIR_DEBUG("obj=%p", domain);
2264
    return domain;
2265

2266
 error:
2267 2268
    virObjectUnref(domain);
    return NULL;
2269 2270
}

2271 2272 2273 2274 2275 2276 2277

virDomainDefPtr virDomainDefNew(const char *name,
                                const unsigned char *uuid,
                                int id)
{
    virDomainDefPtr def;

2278
    if (VIR_ALLOC(def) < 0)
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
        return NULL;

    if (VIR_STRDUP(def->name, name) < 0) {
        VIR_FREE(def);
        return NULL;
    }

    memcpy(def->uuid, uuid, VIR_UUID_BUFLEN);
    def->id = id;

    return def;
}


2293
void virDomainObjAssignDef(virDomainObjPtr domain,
2294
                           virDomainDefPtr def,
2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306
                           bool live,
                           virDomainDefPtr *oldDef)
{
    if (oldDef)
        *oldDef = NULL;
    if (virDomainObjIsActive(domain)) {
        if (oldDef)
            *oldDef = domain->newDef;
        else
            virDomainDefFree(domain->newDef);
        domain->newDef = def;
    } else {
2307
        if (live) {
2308 2309 2310 2311 2312
            /* save current configuration to be restored on domain shutdown */
            if (!domain->newDef)
                domain->newDef = domain->def;
            else
                virDomainDefFree(domain->def);
2313 2314
            domain->def = def;
        } else {
2315 2316 2317 2318
            if (oldDef)
                *oldDef = domain->def;
            else
                virDomainDefFree(domain->def);
2319 2320 2321 2322 2323
            domain->def = def;
        }
    }
}

2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336


/*
 *
 * If flags & VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE then
 * this will refuse updating an existing def if the
 * current def is Live
 *
 * If flags & VIR_DOMAIN_OBJ_LIST_ADD_LIVE then
 * the @def being added is assumed to represent a
 * live config, not a future inactive config
 *
 */
2337 2338
static virDomainObjPtr
virDomainObjListAddLocked(virDomainObjListPtr doms,
2339
                          virDomainDefPtr def,
2340
                          virDomainXMLOptionPtr xmlopt,
2341 2342
                          unsigned int flags,
                          virDomainDefPtr *oldDef)
2343
{
2344
    virDomainObjPtr vm;
2345
    char uuidstr[VIR_UUID_STRING_BUFLEN];
2346

2347 2348
    if (oldDef)
        *oldDef = false;
2349

2350 2351
    virUUIDFormat(def->uuid, uuidstr);

2352
    /* See if a VM with matching UUID already exists */
2353 2354
    if ((vm = virHashLookup(doms->objs, uuidstr))) {
        virObjectLock(vm);
2355 2356 2357 2358 2359 2360 2361 2362
        /* UUID matches, but if names don't match, refuse it */
        if (STRNEQ(vm->def->name, def->name)) {
            virUUIDFormat(vm->def->uuid, uuidstr);
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("domain '%s' is already defined with uuid %s"),
                           vm->def->name, uuidstr);
            goto error;
        }
2363

2364 2365 2366 2367
        if (flags & VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE) {
            /* UUID & name match, but if VM is already active, refuse it */
            if (virDomainObjIsActive(vm)) {
                virReportError(VIR_ERR_OPERATION_INVALID,
2368 2369 2370 2371 2372 2373 2374
                               _("domain '%s' is already active"),
                               vm->def->name);
                goto error;
            }
            if (!vm->persistent) {
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("domain '%s' is already being started"),
2375 2376 2377 2378
                               vm->def->name);
                goto error;
            }
        }
2379

2380 2381 2382 2383 2384 2385
        virDomainObjAssignDef(vm,
                              def,
                              !!(flags & VIR_DOMAIN_OBJ_LIST_ADD_LIVE),
                              oldDef);
    } else {
        /* UUID does not match, but if a name matches, refuse it */
2386 2387
        if ((vm = virHashSearch(doms->objs, virDomainObjListSearchName, def->name))) {
            virObjectLock(vm);
2388 2389 2390 2391 2392 2393 2394
            virUUIDFormat(vm->def->uuid, uuidstr);
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("domain '%s' already exists with uuid %s"),
                           def->name, uuidstr);
            goto error;
        }

2395
        if (!(vm = virDomainObjNew(xmlopt)))
2396 2397 2398 2399 2400 2401 2402 2403
            goto cleanup;
        vm->def = def;

        virUUIDFormat(def->uuid, uuidstr);
        if (virHashAddEntry(doms->objs, uuidstr, vm) < 0) {
            virObjectUnref(vm);
            return NULL;
        }
2404
    }
2405
 cleanup:
2406
    return vm;
2407

2408
 error:
2409 2410 2411
    virObjectUnlock(vm);
    vm = NULL;
    goto cleanup;
2412 2413
}

2414 2415

virDomainObjPtr virDomainObjListAdd(virDomainObjListPtr doms,
2416
                                    virDomainDefPtr def,
2417
                                    virDomainXMLOptionPtr xmlopt,
2418 2419 2420 2421 2422 2423
                                    unsigned int flags,
                                    virDomainDefPtr *oldDef)
{
    virDomainObjPtr ret;

    virObjectLock(doms);
2424
    ret = virDomainObjListAddLocked(doms, def, xmlopt, flags, oldDef);
2425 2426 2427 2428
    virObjectUnlock(doms);
    return ret;
}

2429 2430 2431 2432 2433
/*
 * Mark the running VM config as transient. Ensures transient hotplug
 * operations do not persist past shutdown.
 *
 * @param caps pointer to capabilities info
W
Wang Rui 已提交
2434
 * @param xmlopt pointer to XML parser configuration object
2435
 * @param domain domain object pointer
2436 2437 2438 2439
 * @param live if true, run this operation even for an inactive domain.
 *   this allows freely updated domain->def with runtime defaults before
 *   starting the VM, which will be discarded on VM shutdown. Any cleanup
 *   paths need to be sure to handle newDef if the domain is never started.
2440 2441 2442 2443
 * @return 0 on success, -1 on failure
 */
int
virDomainObjSetDefTransient(virCapsPtr caps,
2444
                            virDomainXMLOptionPtr xmlopt,
2445 2446
                            virDomainObjPtr domain,
                            bool live)
2447 2448 2449
{
    int ret = -1;

2450
    if (!virDomainObjIsActive(domain) && !live)
2451 2452 2453 2454 2455 2456 2457 2458
        return 0;

    if (!domain->persistent)
        return 0;

    if (domain->newDef)
        return 0;

2459
    if (!(domain->newDef = virDomainDefCopy(domain->def, caps, xmlopt, false)))
2460 2461 2462
        goto out;

    ret = 0;
2463
 out:
2464 2465 2466
    return ret;
}

2467 2468 2469 2470 2471
/*
 * Return the persistent domain configuration. If domain is transient,
 * return the running config.
 *
 * @param caps pointer to capabilities info
W
Wang Rui 已提交
2472
 * @param xmlopt pointer to XML parser configuration object
2473 2474 2475 2476 2477
 * @param domain domain object pointer
 * @return NULL on error, virDOmainDefPtr on success
 */
virDomainDefPtr
virDomainObjGetPersistentDef(virCapsPtr caps,
2478
                             virDomainXMLOptionPtr xmlopt,
2479 2480
                             virDomainObjPtr domain)
{
2481
    if (virDomainObjSetDefTransient(caps, xmlopt, domain, false) < 0)
2482 2483 2484 2485 2486 2487 2488 2489
        return NULL;

    if (domain->newDef)
        return domain->newDef;
    else
        return domain->def;
}

2490 2491 2492 2493 2494 2495 2496 2497 2498
/*
 * Helper method for --current, --live, and --config options, and check
 * whether domain is active or can get persistent domain configuration.
 *
 * Return 0 if success, also change the flags and get the persistent
 * domain configuration if needed. Return -1 on error.
 */
int
virDomainLiveConfigHelperMethod(virCapsPtr caps,
2499
                                virDomainXMLOptionPtr xmlopt,
2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
                                virDomainObjPtr dom,
                                unsigned int *flags,
                                virDomainDefPtr *persistentDef)
{
    bool isActive;
    int ret = -1;

    isActive = virDomainObjIsActive(dom);

    if ((*flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)) ==
        VIR_DOMAIN_AFFECT_CURRENT) {
        if (isActive)
            *flags |= VIR_DOMAIN_AFFECT_LIVE;
        else
            *flags |= VIR_DOMAIN_AFFECT_CONFIG;
    }

    if (!isActive && (*flags & VIR_DOMAIN_AFFECT_LIVE)) {
2518 2519
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain is not running"));
2520 2521 2522 2523 2524
        goto cleanup;
    }

    if (*flags & VIR_DOMAIN_AFFECT_CONFIG) {
        if (!dom->persistent) {
2525
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
2526 2527
                           _("transient domains do not have any "
                             "persistent config"));
2528 2529
            goto cleanup;
        }
2530
        if (!(*persistentDef = virDomainObjGetPersistentDef(caps, xmlopt, dom))) {
2531 2532
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Get persistent config failed"));
2533 2534 2535 2536 2537 2538
            goto cleanup;
        }
    }

    ret = 0;

2539
 cleanup:
2540 2541 2542
    return ret;
}

2543
/*
2544
 * The caller must hold a lock on the driver owning 'doms',
2545
 * and must also have locked 'dom', to ensure no one else
2546
 * is either waiting for 'dom' or still using it
2547
 */
2548 2549
void virDomainObjListRemove(virDomainObjListPtr doms,
                            virDomainObjPtr dom)
2550
{
2551
    char uuidstr[VIR_UUID_STRING_BUFLEN];
2552

2553
    virUUIDFormat(dom->def->uuid, uuidstr);
2554
    virObjectRef(dom);
2555
    virObjectUnlock(dom);
2556

2557
    virObjectLock(doms);
2558
    virObjectLock(dom);
2559
    virHashRemoveEntry(doms->objs, uuidstr);
2560 2561
    virObjectUnlock(dom);
    virObjectUnref(dom);
2562
    virObjectUnlock(doms);
2563
}
D
Daniel P. Berrange 已提交
2564

2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581
/* The caller must hold lock on 'doms' in addition to 'virDomainObjListRemove'
 * requirements
 *
 * Can be used to remove current element while iterating with
 * virDomainObjListForEach
 */
void virDomainObjListRemoveLocked(virDomainObjListPtr doms,
                                  virDomainObjPtr dom)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    virUUIDFormat(dom->def->uuid, uuidstr);
    virObjectUnlock(dom);

    virHashRemoveEntry(doms->objs, uuidstr);
}

2582 2583 2584 2585 2586 2587 2588
static int
virDomainDeviceCCWAddressIsValid(virDomainDeviceCCWAddressPtr addr)
{
    return addr->cssid <= VIR_DOMAIN_DEVICE_CCW_MAX_CSSID &&
        addr->ssid <= VIR_DOMAIN_DEVICE_CCW_MAX_SSID &&
        addr->devno <= VIR_DOMAIN_DEVICE_CCW_MAX_DEVNO;
}
2589

2590 2591 2592 2593 2594 2595 2596 2597
int virDomainDeviceAddressIsValid(virDomainDeviceInfoPtr info,
                                  int type)
{
    if (info->type != type)
        return 0;

    switch (info->type) {
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI:
2598
        return virDevicePCIAddressIsValid(&info->addr.pci);
2599 2600

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE:
2601
        return 1;
2602

2603
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390:
2604
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO:
2605 2606 2607 2608 2609
        return 1;

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW:
        return virDomainDeviceCCWAddressIsValid(&info->addr.ccw);

2610
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB:
2611
        return 1;
2612 2613 2614 2615 2616
    }

    return 0;
}

2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650
virDomainDeviceInfoPtr
virDomainDeviceGetInfo(virDomainDeviceDefPtr device)
{
    switch ((virDomainDeviceType) device->type) {
    case VIR_DOMAIN_DEVICE_DISK:
        return &device->data.disk->info;
    case VIR_DOMAIN_DEVICE_FS:
        return &device->data.fs->info;
    case VIR_DOMAIN_DEVICE_NET:
        return &device->data.net->info;
    case VIR_DOMAIN_DEVICE_INPUT:
        return &device->data.input->info;
    case VIR_DOMAIN_DEVICE_SOUND:
        return &device->data.sound->info;
    case VIR_DOMAIN_DEVICE_VIDEO:
        return &device->data.video->info;
    case VIR_DOMAIN_DEVICE_HOSTDEV:
        return device->data.hostdev->info;
    case VIR_DOMAIN_DEVICE_WATCHDOG:
        return &device->data.watchdog->info;
    case VIR_DOMAIN_DEVICE_CONTROLLER:
        return &device->data.controller->info;
    case VIR_DOMAIN_DEVICE_HUB:
        return &device->data.hub->info;
    case VIR_DOMAIN_DEVICE_REDIRDEV:
        return &device->data.redirdev->info;
    case VIR_DOMAIN_DEVICE_SMARTCARD:
        return &device->data.smartcard->info;
    case VIR_DOMAIN_DEVICE_CHR:
        return &device->data.chr->info;
    case VIR_DOMAIN_DEVICE_MEMBALLOON:
        return &device->data.memballoon->info;
    case VIR_DOMAIN_DEVICE_NVRAM:
        return &device->data.nvram->info;
2651 2652
    case VIR_DOMAIN_DEVICE_SHMEM:
        return &device->data.shmem->info;
2653 2654
    case VIR_DOMAIN_DEVICE_RNG:
        return &device->data.rng->info;
2655 2656
    case VIR_DOMAIN_DEVICE_TPM:
        return &device->data.tpm->info;
2657 2658
    case VIR_DOMAIN_DEVICE_PANIC:
        return &device->data.panic->info;
2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669

    /* The following devices do not contain virDomainDeviceInfo */
    case VIR_DOMAIN_DEVICE_LEASE:
    case VIR_DOMAIN_DEVICE_GRAPHICS:
    case VIR_DOMAIN_DEVICE_LAST:
    case VIR_DOMAIN_DEVICE_NONE:
        break;
    }
    return NULL;
}

2670
static bool
2671
virDomainDeviceInfoIsSet(virDomainDeviceInfoPtr info, unsigned int flags)
2672 2673
{
    if (info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
2674
        return true;
2675
    if (info->alias && !(flags & VIR_DOMAIN_XML_INACTIVE))
2676 2677 2678
        return true;
    if (info->mastertype != VIR_DOMAIN_CONTROLLER_MASTER_NONE)
        return true;
J
Ján Tomko 已提交
2679
    if ((info->rombar != VIR_TRISTATE_SWITCH_ABSENT) ||
2680 2681 2682 2683 2684
        info->romfile)
        return true;
    if (info->bootIndex)
        return true;
    return false;
2685 2686
}

2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699
int
virDomainDeviceInfoCopy(virDomainDeviceInfoPtr dst,
                        virDomainDeviceInfoPtr src)
{
    /* Assume that dst is already cleared */

    /* first a shallow copy of *everything* */
    *dst = *src;

    /* then redo the two fields that are pointers */
    dst->alias = NULL;
    dst->romfile = NULL;

2700 2701
    if (VIR_STRDUP(dst->alias, src->alias) < 0 ||
        VIR_STRDUP(dst->romfile, src->romfile) < 0)
2702 2703 2704 2705
        return -1;
    return 0;
}

2706 2707
void virDomainDeviceInfoClear(virDomainDeviceInfoPtr info)
{
2708
    VIR_FREE(info->alias);
2709
    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB)
2710
        VIR_FREE(info->addr.usb.port);
2711 2712
    memset(&info->addr, 0, sizeof(info->addr));
    info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE;
2713
    VIR_FREE(info->romfile);
2714 2715 2716
}


2717
static int virDomainDeviceInfoClearAlias(virDomainDefPtr def ATTRIBUTE_UNUSED,
2718
                                         virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
2719 2720
                                         virDomainDeviceInfoPtr info,
                                         void *opaque ATTRIBUTE_UNUSED)
2721
{
2722 2723 2724 2725 2726
    VIR_FREE(info->alias);
    return 0;
}

static int virDomainDeviceInfoClearPCIAddress(virDomainDefPtr def ATTRIBUTE_UNUSED,
2727
                                              virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
2728 2729 2730 2731
                                              virDomainDeviceInfoPtr info,
                                              void *opaque ATTRIBUTE_UNUSED)
{
    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
2732 2733 2734
        memset(&info->addr, 0, sizeof(info->addr));
        info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE;
    }
2735
    return 0;
2736 2737
}

2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
static int
virDomainDeviceInfoClearCCWAddress(virDomainDefPtr def ATTRIBUTE_UNUSED,
                                   virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
                                   virDomainDeviceInfoPtr info,
                                   void *opaque ATTRIBUTE_UNUSED)
{
    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW) {
        memset(&info->addr, 0, sizeof(info->addr));
        info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE;
    }
    return 0;
}

2751 2752 2753 2754 2755
static int
virDomainDeviceInfoIterateInternal(virDomainDefPtr def,
                                   virDomainDeviceInfoCallback cb,
                                   bool all,
                                   void *opaque)
2756
{
2757
    size_t i;
2758
    virDomainDeviceDef device;
2759

2760
    device.type = VIR_DOMAIN_DEVICE_DISK;
2761
    for (i = 0; i < def->ndisks; i++) {
2762 2763
        device.data.disk = def->disks[i];
        if (cb(def, &device, &def->disks[i]->info, opaque) < 0)
2764
            return -1;
2765 2766
    }
    device.type = VIR_DOMAIN_DEVICE_NET;
2767
    for (i = 0; i < def->nnets; i++) {
2768 2769
        device.data.net = def->nets[i];
        if (cb(def, &device, &def->nets[i]->info, opaque) < 0)
2770
            return -1;
2771 2772
    }
    device.type = VIR_DOMAIN_DEVICE_SOUND;
2773
    for (i = 0; i < def->nsounds; i++) {
2774 2775
        device.data.sound = def->sounds[i];
        if (cb(def, &device, &def->sounds[i]->info, opaque) < 0)
2776
            return -1;
2777 2778
    }
    device.type = VIR_DOMAIN_DEVICE_HOSTDEV;
2779
    for (i = 0; i < def->nhostdevs; i++) {
2780
        device.data.hostdev = def->hostdevs[i];
2781
        if (cb(def, &device, def->hostdevs[i]->info, opaque) < 0)
2782
            return -1;
2783 2784
    }
    device.type = VIR_DOMAIN_DEVICE_VIDEO;
2785
    for (i = 0; i < def->nvideos; i++) {
2786 2787
        device.data.video = def->videos[i];
        if (cb(def, &device, &def->videos[i]->info, opaque) < 0)
2788
            return -1;
2789 2790
    }
    device.type = VIR_DOMAIN_DEVICE_CONTROLLER;
2791
    for (i = 0; i < def->ncontrollers; i++) {
2792 2793
        device.data.controller = def->controllers[i];
        if (cb(def, &device, &def->controllers[i]->info, opaque) < 0)
2794
            return -1;
2795 2796
    }
    device.type = VIR_DOMAIN_DEVICE_SMARTCARD;
2797
    for (i = 0; i < def->nsmartcards; i++) {
2798 2799
        device.data.smartcard = def->smartcards[i];
        if (cb(def, &device, &def->smartcards[i]->info, opaque) < 0)
E
Eric Blake 已提交
2800
            return -1;
2801 2802
    }
    device.type = VIR_DOMAIN_DEVICE_CHR;
2803
    for (i = 0; i < def->nserials; i++) {
2804 2805
        device.data.chr = def->serials[i];
        if (cb(def, &device, &def->serials[i]->info, opaque) < 0)
2806
            return -1;
2807
    }
2808
    for (i = 0; i < def->nparallels; i++) {
2809 2810
        device.data.chr = def->parallels[i];
        if (cb(def, &device, &def->parallels[i]->info, opaque) < 0)
2811
            return -1;
2812
    }
2813
    for (i = 0; i < def->nchannels; i++) {
2814 2815
        device.data.chr = def->channels[i];
        if (cb(def, &device, &def->channels[i]->info, opaque) < 0)
2816
            return -1;
2817
    }
2818
    for (i = 0; i < def->nconsoles; i++) {
2819 2820 2821 2822 2823
        if (!all &&
            i == 0 &&
            (def->consoles[i]->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL ||
             def->consoles[i]->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_NONE) &&
             STREQ_NULLABLE(def->os.type, "hvm"))
2824
            continue;
2825 2826
        device.data.chr = def->consoles[i];
        if (cb(def, &device, &def->consoles[i]->info, opaque) < 0)
2827
            return -1;
2828 2829
    }
    device.type = VIR_DOMAIN_DEVICE_INPUT;
2830
    for (i = 0; i < def->ninputs; i++) {
2831 2832
        device.data.input = def->inputs[i];
        if (cb(def, &device, &def->inputs[i]->info, opaque) < 0)
2833
            return -1;
2834 2835
    }
    device.type = VIR_DOMAIN_DEVICE_FS;
2836
    for (i = 0; i < def->nfss; i++) {
2837 2838
        device.data.fs = def->fss[i];
        if (cb(def, &device, &def->fss[i]->info, opaque) < 0)
2839
            return -1;
2840 2841 2842 2843 2844
    }
    if (def->watchdog) {
        device.type = VIR_DOMAIN_DEVICE_WATCHDOG;
        device.data.watchdog = def->watchdog;
        if (cb(def, &device, &def->watchdog->info, opaque) < 0)
2845
            return -1;
2846 2847 2848 2849 2850
    }
    if (def->memballoon) {
        device.type = VIR_DOMAIN_DEVICE_MEMBALLOON;
        device.data.memballoon = def->memballoon;
        if (cb(def, &device, &def->memballoon->info, opaque) < 0)
2851
            return -1;
2852
    }
2853 2854 2855 2856
    device.type = VIR_DOMAIN_DEVICE_RNG;
    for (i = 0; i < def->nrngs; i++) {
        device.data.rng = def->rngs[i];
        if (cb(def, &device, &def->rngs[i]->info, opaque) < 0)
2857 2858
            return -1;
    }
L
Li Zhang 已提交
2859 2860 2861 2862 2863 2864
    if (def->nvram) {
        device.type = VIR_DOMAIN_DEVICE_NVRAM;
        device.data.nvram = def->nvram;
        if (cb(def, &device, &def->nvram->info, opaque) < 0)
            return -1;
    }
2865
    device.type = VIR_DOMAIN_DEVICE_HUB;
2866
    for (i = 0; i < def->nhubs; i++) {
2867 2868
        device.data.hub = def->hubs[i];
        if (cb(def, &device, &def->hubs[i]->info, opaque) < 0)
M
Marc-André Lureau 已提交
2869
            return -1;
2870
    }
2871 2872 2873 2874 2875 2876
    device.type = VIR_DOMAIN_DEVICE_SHMEM;
    for (i = 0; i < def->nshmems; i++) {
        device.data.shmem = def->shmems[i];
        if (cb(def, &device, &def->shmems[i]->info, opaque) < 0)
            return -1;
    }
2877 2878 2879 2880 2881 2882
    if (def->tpm) {
        device.type = VIR_DOMAIN_DEVICE_TPM;
        device.data.tpm = def->tpm;
        if (cb(def, &device, &def->tpm->info, opaque) < 0)
            return -1;
    }
2883 2884 2885 2886 2887 2888
    if (def->panic) {
        device.type = VIR_DOMAIN_DEVICE_PANIC;
        device.data.panic = def->panic;
        if (cb(def, &device, &def->panic->info, opaque) < 0)
            return -1;
    }
2889

2890 2891
    /* Coverity is not very happy with this - all dead_error_condition */
#if !STATIC_ANALYSIS
2892
    /* This switch statement is here to trigger compiler warning when adding
E
Eric Blake 已提交
2893
     * a new device type. When you are adding a new field to the switch you
M
Martin Kletzander 已提交
2894
     * also have to add an iteration statement above. Otherwise the switch
2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915
     * statement has no real function here and should be optimized out by the
     * compiler. */
    i = VIR_DOMAIN_DEVICE_LAST;
    switch ((virDomainDeviceType) i) {
    case VIR_DOMAIN_DEVICE_DISK:
    case VIR_DOMAIN_DEVICE_LEASE:
    case VIR_DOMAIN_DEVICE_FS:
    case VIR_DOMAIN_DEVICE_NET:
    case VIR_DOMAIN_DEVICE_INPUT:
    case VIR_DOMAIN_DEVICE_SOUND:
    case VIR_DOMAIN_DEVICE_VIDEO:
    case VIR_DOMAIN_DEVICE_HOSTDEV:
    case VIR_DOMAIN_DEVICE_WATCHDOG:
    case VIR_DOMAIN_DEVICE_CONTROLLER:
    case VIR_DOMAIN_DEVICE_GRAPHICS:
    case VIR_DOMAIN_DEVICE_HUB:
    case VIR_DOMAIN_DEVICE_REDIRDEV:
    case VIR_DOMAIN_DEVICE_NONE:
    case VIR_DOMAIN_DEVICE_SMARTCARD:
    case VIR_DOMAIN_DEVICE_CHR:
    case VIR_DOMAIN_DEVICE_MEMBALLOON:
L
Li Zhang 已提交
2916
    case VIR_DOMAIN_DEVICE_NVRAM:
2917
    case VIR_DOMAIN_DEVICE_SHMEM:
2918
    case VIR_DOMAIN_DEVICE_TPM:
2919
    case VIR_DOMAIN_DEVICE_PANIC:
2920
    case VIR_DOMAIN_DEVICE_LAST:
2921
    case VIR_DOMAIN_DEVICE_RNG:
2922 2923
        break;
    }
2924
#endif
2925

2926
    return 0;
2927 2928 2929
}


2930 2931 2932 2933 2934 2935 2936 2937 2938
int
virDomainDeviceInfoIterate(virDomainDefPtr def,
                           virDomainDeviceInfoCallback cb,
                           void *opaque)
{
    return virDomainDeviceInfoIterateInternal(def, cb, false, opaque);
}


2939 2940 2941 2942 2943 2944 2945 2946 2947
static int
virDomainDefRejectDuplicateControllers(virDomainDefPtr def)
{
    int max_idx[VIR_DOMAIN_CONTROLLER_TYPE_LAST];
    virBitmapPtr bitmaps[VIR_DOMAIN_CONTROLLER_TYPE_LAST] = { NULL };
    virDomainControllerDefPtr cont;
    size_t nbitmaps = 0;
    int ret = -1;
    bool b;
2948
    size_t i;
2949 2950 2951 2952 2953

    memset(max_idx, -1, sizeof(max_idx));

    for (i = 0; i < def->ncontrollers; i++) {
        cont = def->controllers[i];
2954
        if ((int) cont->idx > max_idx[cont->type])
2955 2956 2957 2958 2959 2960 2961 2962
            max_idx[cont->type] = cont->idx;
    }

    /* multiple USB controllers with the same index are allowed */
    max_idx[VIR_DOMAIN_CONTROLLER_TYPE_USB] = -1;

    for (i = 0; i < VIR_DOMAIN_CONTROLLER_TYPE_LAST; i++) {
        if (max_idx[i] >= 0 && !(bitmaps[i] = virBitmapNew(max_idx[i] + 1)))
2963
            goto cleanup;
2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984
        nbitmaps++;
    }

    for (i = 0; i < def->ncontrollers; i++) {
        cont = def->controllers[i];

        if (max_idx[cont->type] == -1)
            continue;

        ignore_value(virBitmapGetBit(bitmaps[cont->type], cont->idx, &b));
        if (b) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("Multiple '%s' controllers with index '%d'"),
                           virDomainControllerTypeToString(cont->type),
                           cont->idx);
            goto cleanup;
        }
        ignore_value(virBitmapSetBit(bitmaps[cont->type], cont->idx));
    }

    ret = 0;
2985
 cleanup:
2986 2987 2988 2989 2990 2991
    for (i = 0; i < nbitmaps; i++)
        virBitmapFree(bitmaps[i]);
    return ret;
}


2992 2993 2994 2995
static int
virDomainDefPostParseInternal(virDomainDefPtr def,
                              virCapsPtr caps ATTRIBUTE_UNUSED)
{
2996
    size_t i;
2997

2998 2999 3000 3001 3002 3003
    if (!def->os.type) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("hypervisor type must be specified"));
        return -1;
    }

3004 3005 3006 3007 3008 3009 3010
    /* verify init path for container based domains */
    if (STREQ(def->os.type, "exe") && !def->os.init) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("init binary must be specified"));
        return -1;
    }

3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
    /*
     * Some really crazy backcompat stuff for consoles
     *
     * Historically the first (and only) '<console>' element in an HVM guest
     * was treated as being an alias for a <serial> device.
     *
     * So if we see that this console device should be a serial device, then we
     * move the config over to def->serials[0] (or discard it if that already
     * exists). However, given console can already be filled with aliased data
     * of def->serials[0]. Keep it then.
     *
     * We then fill def->consoles[0] with a stub just so we get sequencing
     * correct for consoles > 0
     */
    if (def->nconsoles > 0 && STREQ(def->os.type, "hvm") &&
        (def->consoles[0]->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL ||
         def->consoles[0]->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_NONE)) {
        /* First verify that only the first console is of type serial */
        for (i = 1; i < def->nconsoles; i++) {
            virDomainChrDefPtr cons = def->consoles[i];

            if (cons->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("Only the first console can be a serial port"));
                return -1;
            }
        }

        /* If there isn't a corresponding serial port:
         *  - create one and set, the console to be an alias for it
         *
         * If there is a corresponding serial port:
         * - Check if the source definition is equal:
         *    - if yes: leave it as-is
         *    - if no: change the console to be alias of the serial port
         */

        /* create the serial port definition from the console definition */
        if (def->nserials == 0) {
3050 3051 3052 3053
            if (VIR_APPEND_ELEMENT(def->serials,
                                   def->nserials,
                                   def->consoles[0]) < 0)
                return -1;
3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070

            /* modify it to be a serial port */
            def->serials[0]->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL;
            def->serials[0]->targetType = VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_ISA;
            def->serials[0]->target.port = 0;
        } else {
            /* if the console source doesn't match */
            if (!virDomainChrSourceDefIsEqual(&def->serials[0]->source,
                                              &def->consoles[0]->source)) {
                virDomainChrDefFree(def->consoles[0]);
                def->consoles[0] = NULL;
            }
        }

        if (!def->consoles[0]) {
            /* allocate a new console type for the stolen one */
            if (VIR_ALLOC(def->consoles[0]) < 0)
3071
                return -1;
3072 3073 3074 3075 3076 3077 3078

            /* Create an console alias for the serial port */
            def->consoles[0]->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE;
            def->consoles[0]->targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL;
        }
    }

3079 3080
    if (virDomainDefRejectDuplicateControllers(def) < 0)
        return -1;
3081 3082 3083 3084 3085

    /* verify settings of guest timers */
    for (i = 0; i < def->clock.ntimers; i++) {
        virDomainTimerDefPtr timer = def->clock.timers[i];

3086 3087
        if (timer->name == VIR_DOMAIN_TIMER_NAME_KVMCLOCK ||
            timer->name == VIR_DOMAIN_TIMER_NAME_HYPERVCLOCK) {
3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136
            if (timer->tickpolicy != -1) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("timer %s doesn't support setting of "
                                 "timer tickpolicy"),
                               virDomainTimerNameTypeToString(timer->name));
                return -1;
            }
        }

        if (timer->tickpolicy != VIR_DOMAIN_TIMER_TICKPOLICY_CATCHUP &&
            (timer->catchup.threshold != 0 ||
             timer->catchup.limit != 0 ||
             timer->catchup.slew != 0)) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("setting of timer catchup policies is only "
                             "supported with tickpolicy='catchup'"));
            return -1;
        }

        if (timer->name != VIR_DOMAIN_TIMER_NAME_TSC) {
            if (timer->frequency != 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("timer %s doesn't support setting of "
                                 "timer frequency"),
                               virDomainTimerNameTypeToString(timer->name));
                return -1;
             }

            if (timer->mode != -1) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("timer %s doesn't support setting of "
                                 "timer mode"),
                               virDomainTimerNameTypeToString(timer->name));
                return -1;
             }
        }

        if (timer->name != VIR_DOMAIN_TIMER_NAME_PLATFORM &&
            timer->name != VIR_DOMAIN_TIMER_NAME_RTC) {
            if (timer->track != -1) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("timer %s doesn't support setting of "
                                 "timer track"),
                               virDomainTimerNameTypeToString(timer->name));
                return -1;
            }
        }
    }

3137 3138 3139 3140 3141 3142
    return 0;
}


static int
virDomainDeviceDefPostParseInternal(virDomainDeviceDefPtr dev,
3143
                                    const virDomainDef *def,
3144 3145
                                    virCapsPtr caps ATTRIBUTE_UNUSED)
{
3146 3147
    if (dev->type == VIR_DOMAIN_DEVICE_CHR) {
        virDomainChrDefPtr chr = dev->data.chr;
3148 3149
        const virDomainChrDef **arrPtr;
        size_t i, cnt;
3150

3151
        virDomainChrGetDomainPtrs(def, chr->deviceType, &arrPtr, &cnt);
3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162

        if (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE &&
            chr->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_NONE)
            chr->targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL;

        if (chr->target.port == -1 &&
            (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL ||
             chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL ||
             chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE)) {
            int maxport = -1;

3163 3164 3165
            for (i = 0; i < cnt; i++) {
                if (arrPtr[i]->target.port > maxport)
                    maxport = arrPtr[i]->target.port;
3166 3167 3168 3169 3170 3171 3172 3173 3174
            }

            chr->target.port = maxport + 1;
        }

        if (chr->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL &&
            chr->info.addr.vioserial.port == 0) {
            int maxport = 0;

3175 3176
            for (i = 0; i < cnt; i++) {
                const virDomainChrDef *thischr = arrPtr[i];
3177 3178 3179 3180 3181 3182 3183 3184 3185
                if (thischr->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL &&
                    thischr->info.addr.vioserial.controller == chr->info.addr.vioserial.controller &&
                    thischr->info.addr.vioserial.bus == chr->info.addr.vioserial.bus &&
                    (int)thischr->info.addr.vioserial.port > maxport)
                    maxport = thischr->info.addr.vioserial.port;
            }
            chr->info.addr.vioserial.port = maxport + 1;
        }
    }
3186

3187 3188 3189 3190 3191 3192 3193 3194
    /* set default path for virtio-rng "random" backend to /dev/random */
    if (dev->type == VIR_DOMAIN_DEVICE_RNG &&
        dev->data.rng->backend == VIR_DOMAIN_RNG_BACKEND_RANDOM &&
        !dev->data.rng->source.file) {
        if (VIR_STRDUP(dev->data.rng->source.file, "/dev/random") < 0)
            return -1;
    }

3195 3196 3197 3198
    /* verify disk source */
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        virDomainDiskDefPtr disk = dev->data.disk;

3199 3200
        /* internal snapshots and config files are currently supported
         * only with rbd: */
3201 3202 3203 3204 3205 3206 3207 3208
        if (virStorageSourceGetActualType(disk->src) != VIR_STORAGE_TYPE_NETWORK &&
            disk->src->protocol != VIR_STORAGE_NET_PROTOCOL_RBD) {
            if (disk->src->snapshot) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("<snapshot> element is currently supported "
                                 "only with 'rbd' disks"));
                return -1;
            }
3209 3210 3211 3212 3213 3214 3215

            if (disk->src->configFile) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("<config> element is currently supported "
                                 "only with 'rbd' disks"));
                return -1;
            }
3216 3217 3218
        }
    }

3219 3220 3221 3222 3223 3224
    if (dev->type == VIR_DOMAIN_DEVICE_VIDEO) {
        virDomainVideoDefPtr video = dev->data.video;
        video->ram = VIR_ROUND_UP_POWER_OF_TWO(video->ram);
        video->vram = VIR_ROUND_UP_POWER_OF_TWO(video->vram);
    }

3225 3226 3227 3228
    return 0;
}


3229 3230
static int
virDomainDeviceDefPostParse(virDomainDeviceDefPtr dev,
3231
                            const virDomainDef *def,
3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243
                            virCapsPtr caps,
                            virDomainXMLOptionPtr xmlopt)
{
    int ret;

    if (xmlopt && xmlopt->config.devicesPostParseCallback) {
        ret = xmlopt->config.devicesPostParseCallback(dev, def, caps,
                                                      xmlopt->config.priv);
        if (ret < 0)
            return ret;
    }

3244 3245 3246
    if ((ret = virDomainDeviceDefPostParseInternal(dev, def, caps)) < 0)
        return ret;

3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268
    return 0;
}


struct virDomainDefPostParseDeviceIteratorData {
    virDomainDefPtr def;
    virCapsPtr caps;
    virDomainXMLOptionPtr xmlopt;
};


static int
virDomainDefPostParseDeviceIterator(virDomainDefPtr def ATTRIBUTE_UNUSED,
                                    virDomainDeviceDefPtr dev,
                                    virDomainDeviceInfoPtr info ATTRIBUTE_UNUSED,
                                    void *opaque)
{
    struct virDomainDefPostParseDeviceIteratorData *data = opaque;
    return virDomainDeviceDefPostParse(dev, data->def, data->caps, data->xmlopt);
}


3269
int
3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289
virDomainDefPostParse(virDomainDefPtr def,
                      virCapsPtr caps,
                      virDomainXMLOptionPtr xmlopt)
{
    int ret;
    struct virDomainDefPostParseDeviceIteratorData data = {
        .def = def,
        .caps = caps,
        .xmlopt = xmlopt,
    };

    /* call the domain config callback */
    if (xmlopt && xmlopt->config.domainPostParseCallback) {
        ret = xmlopt->config.domainPostParseCallback(def, caps,
                                                     xmlopt->config.priv);
        if (ret < 0)
            return ret;
    }

    /* iterate the devices */
3290 3291 3292 3293
    if ((ret = virDomainDeviceInfoIterateInternal(def,
                                                  virDomainDefPostParseDeviceIterator,
                                                  true,
                                                  &data)) < 0)
3294 3295
        return ret;

3296 3297 3298 3299

    if ((ret = virDomainDefPostParseInternal(def, caps)) < 0)
        return ret;

3300 3301 3302 3303
    return 0;
}


3304 3305
void virDomainDefClearPCIAddresses(virDomainDefPtr def)
{
3306
    virDomainDeviceInfoIterate(def, virDomainDeviceInfoClearPCIAddress, NULL);
D
Daniel P. Berrange 已提交
3307 3308
}

3309 3310 3311 3312 3313
void virDomainDefClearCCWAddresses(virDomainDefPtr def)
{
    virDomainDeviceInfoIterate(def, virDomainDeviceInfoClearCCWAddress, NULL);
}

D
Daniel P. Berrange 已提交
3314 3315
void virDomainDefClearDeviceAliases(virDomainDefPtr def)
{
3316
    virDomainDeviceInfoIterate(def, virDomainDeviceInfoClearAlias, NULL);
3317 3318 3319
}


3320
/* Generate a string representation of a device address
3321
 * @info address Device address to stringify
3322
 */
E
Eric Blake 已提交
3323 3324 3325
static int ATTRIBUTE_NONNULL(2)
virDomainDeviceInfoFormat(virBufferPtr buf,
                          virDomainDeviceInfoPtr info,
E
Eric Blake 已提交
3326
                          unsigned int flags)
3327
{
3328
    if ((flags & VIR_DOMAIN_XML_INTERNAL_ALLOW_BOOT) && info->bootIndex)
3329
        virBufferAsprintf(buf, "<boot order='%d'/>\n", info->bootIndex);
3330

D
Daniel P. Berrange 已提交
3331 3332
    if (info->alias &&
        !(flags & VIR_DOMAIN_XML_INACTIVE)) {
3333
        virBufferAsprintf(buf, "<alias name='%s'/>\n", info->alias);
D
Daniel P. Berrange 已提交
3334 3335
    }

3336
    if (info->mastertype == VIR_DOMAIN_CONTROLLER_MASTER_USB) {
3337
        virBufferAsprintf(buf, "<master startport='%d'/>\n",
3338 3339 3340
                          info->master.usb.startport);
    }

3341 3342 3343
    if ((flags & VIR_DOMAIN_XML_INTERNAL_ALLOW_ROM) &&
        (info->rombar || info->romfile)) {

3344
        virBufferAddLit(buf, "<rom");
3345 3346
        if (info->rombar) {

J
Ján Tomko 已提交
3347
            const char *rombar = virTristateSwitchTypeToString(info->rombar);
3348 3349

            if (!rombar) {
3350 3351 3352
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected rom bar value %d"),
                               info->rombar);
3353 3354 3355
                return -1;
            }
            virBufferAsprintf(buf, " bar='%s'", rombar);
3356
        }
3357 3358 3359
        if (info->romfile)
            virBufferAsprintf(buf, " file='%s'", info->romfile);
        virBufferAddLit(buf, "/>\n");
3360 3361
    }

3362 3363
    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE ||
        info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390)
3364 3365 3366
        return 0;

    /* We'll be in domain/devices/[device type]/ so 3 level indent */
3367
    virBufferAsprintf(buf, "<address type='%s'",
3368 3369
                      virDomainDeviceAddressTypeToString(info->type));

3370
    switch ((virDomainDeviceAddressType) info->type) {
3371
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI:
3372
        virBufferAsprintf(buf, " domain='0x%.4x' bus='0x%.2x' slot='0x%.2x' function='0x%.1x'",
3373 3374 3375 3376
                          info->addr.pci.domain,
                          info->addr.pci.bus,
                          info->addr.pci.slot,
                          info->addr.pci.function);
3377 3378
        if (info->addr.pci.multi) {
           virBufferAsprintf(buf, " multifunction='%s'",
J
Ján Tomko 已提交
3379
                             virTristateSwitchTypeToString(info->addr.pci.multi));
3380
        }
3381 3382
        break;

3383
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE:
3384
        virBufferAsprintf(buf, " controller='%d' bus='%d' target='%d' unit='%d'",
3385 3386
                          info->addr.drive.controller,
                          info->addr.drive.bus,
3387
                          info->addr.drive.target,
3388 3389 3390
                          info->addr.drive.unit);
        break;

3391
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL:
3392
        virBufferAsprintf(buf, " controller='%d' bus='%d' port='%d'",
3393
                          info->addr.vioserial.controller,
3394 3395
                          info->addr.vioserial.bus,
                          info->addr.vioserial.port);
3396 3397
        break;

E
Eric Blake 已提交
3398
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID:
3399
        virBufferAsprintf(buf, " controller='%d' slot='%d'",
E
Eric Blake 已提交
3400 3401 3402 3403
                          info->addr.ccid.controller,
                          info->addr.ccid.slot);
        break;

M
Marc-André Lureau 已提交
3404
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB:
3405
        virBufferAsprintf(buf, " bus='%d' port='%s'",
M
Marc-André Lureau 已提交
3406 3407 3408 3409
                          info->addr.usb.bus,
                          info->addr.usb.port);
        break;

3410 3411 3412 3413 3414
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO:
        if (info->addr.spaprvio.has_reg)
            virBufferAsprintf(buf, " reg='0x%llx'", info->addr.spaprvio.reg);
        break;

3415 3416 3417 3418 3419 3420 3421
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW:
        virBufferAsprintf(buf, " cssid='0x%x' ssid='0x%x' devno='0x%04x'",
                          info->addr.ccw.cssid,
                          info->addr.ccw.ssid,
                          info->addr.ccw.devno);
        break;

3422 3423 3424
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO:
        break;

H
Hu Tao 已提交
3425 3426 3427 3428 3429 3430 3431
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_ISA:
        if (info->addr.isa.iobase > 0)
            virBufferAsprintf(buf, " iobase='0x%x'", info->addr.isa.iobase);
        if (info->addr.isa.irq > 0)
            virBufferAsprintf(buf, " irq='0x%x'", info->addr.isa.irq);
        break;

3432 3433 3434 3435
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390:
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE:
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_LAST:
        break;
3436 3437 3438 3439 3440 3441
    }

    virBufferAddLit(buf, "/>\n");
    return 0;
}

3442
static int
3443
virDomainDeviceDriveAddressParseXML(xmlNodePtr node,
3444 3445
                                    virDomainDeviceDriveAddressPtr addr)
{
3446
    char *bus, *unit, *controller, *target;
3447 3448 3449 3450 3451 3452
    int ret = -1;

    memset(addr, 0, sizeof(*addr));

    controller = virXMLPropString(node, "controller");
    bus = virXMLPropString(node, "bus");
3453
    target = virXMLPropString(node, "target");
3454 3455 3456 3457
    unit = virXMLPropString(node, "unit");

    if (controller &&
        virStrToLong_ui(controller, NULL, 10, &addr->controller) < 0) {
3458 3459
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'controller' attribute"));
3460 3461 3462 3463 3464
        goto cleanup;
    }

    if (bus &&
        virStrToLong_ui(bus, NULL, 10, &addr->bus) < 0) {
3465 3466
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'bus' attribute"));
3467 3468 3469
        goto cleanup;
    }

3470 3471
    if (target &&
        virStrToLong_ui(target, NULL, 10, &addr->target) < 0) {
3472 3473
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'target' attribute"));
3474 3475 3476
        goto cleanup;
    }

3477 3478
    if (unit &&
        virStrToLong_ui(unit, NULL, 10, &addr->unit) < 0) {
3479 3480
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'unit' attribute"));
3481 3482 3483 3484 3485
        goto cleanup;
    }

    ret = 0;

3486
 cleanup:
3487 3488
    VIR_FREE(controller);
    VIR_FREE(bus);
3489
    VIR_FREE(target);
3490 3491 3492 3493
    VIR_FREE(unit);
    return ret;
}

3494 3495 3496 3497 3498 3499 3500

static int
virDomainDeviceVirtioSerialAddressParseXML(
    xmlNodePtr node,
    virDomainDeviceVirtioSerialAddressPtr addr
)
{
3501
    char *controller, *bus, *port;
3502 3503 3504 3505 3506 3507
    int ret = -1;

    memset(addr, 0, sizeof(*addr));

    controller = virXMLPropString(node, "controller");
    bus = virXMLPropString(node, "bus");
3508
    port = virXMLPropString(node, "port");
3509 3510 3511

    if (controller &&
        virStrToLong_ui(controller, NULL, 10, &addr->controller) < 0) {
3512 3513
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'controller' attribute"));
3514 3515 3516 3517 3518
        goto cleanup;
    }

    if (bus &&
        virStrToLong_ui(bus, NULL, 10, &addr->bus) < 0) {
3519 3520
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'bus' attribute"));
3521 3522 3523
        goto cleanup;
    }

3524 3525
    if (port &&
        virStrToLong_ui(port, NULL, 10, &addr->port) < 0) {
3526 3527
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'port' attribute"));
3528 3529 3530
        goto cleanup;
    }

3531 3532
    ret = 0;

3533
 cleanup:
3534 3535
    VIR_FREE(controller);
    VIR_FREE(bus);
E
Eric Blake 已提交
3536
    VIR_FREE(port);
3537 3538 3539
    return ret;
}

3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590
static int
virDomainDeviceCCWAddressParseXML(xmlNodePtr node,
                                  virDomainDeviceCCWAddressPtr addr)
{
    int   ret = -1;
    char *cssid;
    char *ssid;
    char *devno;

    memset(addr, 0, sizeof(*addr));

    cssid = virXMLPropString(node, "cssid");
    ssid = virXMLPropString(node, "ssid");
    devno = virXMLPropString(node, "devno");

    if (cssid && ssid && devno) {
        if (cssid &&
            virStrToLong_ui(cssid, NULL, 0, &addr->cssid) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot parse <address> 'cssid' attribute"));
            goto cleanup;
        }
        if (ssid &&
            virStrToLong_ui(ssid, NULL, 0, &addr->ssid) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot parse <address> 'ssid' attribute"));
            goto cleanup;
        }
        if (devno &&
            virStrToLong_ui(devno, NULL, 0, &addr->devno) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot parse <address> 'devno' attribute"));
            goto cleanup;
        }
        if (!virDomainDeviceCCWAddressIsValid(addr)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid specification for virtio ccw"
                             " address: cssid='%s' ssid='%s' devno='%s'"),
                           cssid, ssid, devno);
            goto cleanup;
        }
        addr->assigned = true;
    } else if (cssid || ssid || devno) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Invalid partial specification for virtio ccw"
                         " address"));
        goto cleanup;
    }

    ret = 0;

3591
 cleanup:
3592 3593 3594 3595 3596 3597
    VIR_FREE(cssid);
    VIR_FREE(ssid);
    VIR_FREE(devno);
    return ret;
}

E
Eric Blake 已提交
3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611
static int
virDomainDeviceCcidAddressParseXML(xmlNodePtr node,
                                   virDomainDeviceCcidAddressPtr addr)
{
    char *controller, *slot;
    int ret = -1;

    memset(addr, 0, sizeof(*addr));

    controller = virXMLPropString(node, "controller");
    slot = virXMLPropString(node, "slot");

    if (controller &&
        virStrToLong_ui(controller, NULL, 10, &addr->controller) < 0) {
3612 3613
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'controller' attribute"));
E
Eric Blake 已提交
3614 3615 3616 3617 3618
        goto cleanup;
    }

    if (slot &&
        virStrToLong_ui(slot, NULL, 10, &addr->slot) < 0) {
3619 3620
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'slot' attribute"));
E
Eric Blake 已提交
3621 3622 3623 3624 3625
        goto cleanup;
    }

    ret = 0;

3626
 cleanup:
E
Eric Blake 已提交
3627 3628 3629 3630 3631
    VIR_FREE(controller);
    VIR_FREE(slot);
    return ret;
}

3632 3633 3634 3635
static int
virDomainDeviceUSBAddressParseXML(xmlNodePtr node,
                                  virDomainDeviceUSBAddressPtr addr)
{
3636 3637
    char *port, *bus, *tmp;
    unsigned int p;
3638 3639 3640 3641 3642 3643 3644 3645
    int ret = -1;

    memset(addr, 0, sizeof(*addr));

    port = virXMLPropString(node, "port");
    bus = virXMLPropString(node, "bus");

    if (port &&
3646 3647 3648 3649
        ((virStrToLong_ui(port, &tmp, 10, &p) < 0 || (*tmp != '\0' && *tmp != '.')) ||
         (*tmp == '.' && (virStrToLong_ui(tmp + 1, &tmp, 10, &p) < 0 || (*tmp != '\0' && *tmp != '.'))) ||
         (*tmp == '.' && (virStrToLong_ui(tmp + 1, &tmp, 10, &p) < 0 || (*tmp != '\0' && *tmp != '.'))) ||
         (*tmp == '.' && (virStrToLong_ui(tmp + 1, &tmp, 10, &p) < 0 || (*tmp != '\0'))))) {
3650 3651
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'port' attribute"));
3652 3653 3654
        goto cleanup;
    }

3655 3656 3657
    addr->port = port;
    port = NULL;

3658 3659
    if (bus &&
        virStrToLong_ui(bus, NULL, 10, &addr->bus) < 0) {
3660 3661
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'bus' attribute"));
3662 3663 3664 3665 3666
        goto cleanup;
    }

    ret = 0;

3667
 cleanup:
3668 3669 3670 3671 3672
    VIR_FREE(bus);
    VIR_FREE(port);
    return ret;
}

3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684
static int
virDomainDeviceSpaprVioAddressParseXML(xmlNodePtr node,
                                      virDomainDeviceSpaprVioAddressPtr addr)
{
    char *reg;
    int ret;

    memset(addr, 0, sizeof(*addr));

    reg = virXMLPropString(node, "reg");
    if (reg) {
        if (virStrToLong_ull(reg, NULL, 16, &addr->reg) < 0) {
3685 3686
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot parse <address> 'reg' attribute"));
3687 3688 3689 3690 3691 3692 3693 3694
            ret = -1;
            goto cleanup;
        }

        addr->has_reg = true;
    }

    ret = 0;
3695
 cleanup:
3696 3697 3698 3699
    VIR_FREE(reg);
    return ret;
}

3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712
static int
virDomainDeviceUSBMasterParseXML(xmlNodePtr node,
                                 virDomainDeviceUSBMasterPtr master)
{
    char *startport;
    int ret = -1;

    memset(master, 0, sizeof(*master));

    startport = virXMLPropString(node, "startport");

    if (startport &&
        virStrToLong_ui(startport, NULL, 10, &master->startport) < 0) {
3713 3714
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <master> 'startport' attribute"));
3715 3716 3717 3718 3719
        goto cleanup;
    }

    ret = 0;

3720
 cleanup:
3721 3722 3723 3724
    VIR_FREE(startport);
    return ret;
}

3725 3726 3727
static int
virDomainDeviceBootParseXML(xmlNodePtr node,
                            int *bootIndex,
3728
                            virHashTablePtr bootHash)
3729 3730 3731 3732 3733 3734 3735
{
    char *order;
    int boot;
    int ret = -1;

    order = virXMLPropString(node, "order");
    if (!order) {
3736 3737
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing boot order attribute"));
3738 3739 3740
        goto cleanup;
    } else if (virStrToLong_i(order, NULL, 10, &boot) < 0 ||
               boot <= 0) {
3741 3742 3743
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("incorrect boot order '%s', expecting positive integer"),
                       order);
3744 3745 3746
        goto cleanup;
    }

3747 3748 3749 3750 3751
    if (bootHash) {
        if (virHashLookup(bootHash, order)) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("boot order '%s' used for more than one device"),
                           order);
3752 3753
            goto cleanup;
        }
3754 3755 3756

        if (virHashAddEntry(bootHash, order, (void *) 1) < 0)
            goto cleanup;
3757 3758 3759 3760 3761
    }

    *bootIndex = boot;
    ret = 0;

3762
 cleanup:
3763 3764 3765 3766
    VIR_FREE(order);
    return ret;
}

H
Hu Tao 已提交
3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794
static int
virDomainDeviceISAAddressParseXML(xmlNodePtr node,
                                  virDomainDeviceISAAddressPtr addr)
{
    int ret = -1;
    char *iobase;
    char *irq;

    memset(addr, 0, sizeof(*addr));

    iobase = virXMLPropString(node, "iobase");
    irq = virXMLPropString(node, "irq");

    if (iobase &&
        virStrToLong_ui(iobase, NULL, 16, &addr->iobase) < 0) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Cannot parse <address> 'iobase' attribute"));
        goto cleanup;
    }

    if (irq &&
        virStrToLong_ui(irq, NULL, 16, &addr->irq) < 0) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Cannot parse <address> 'irq' attribute"));
        goto cleanup;
    }

    ret = 0;
3795
 cleanup:
H
Hu Tao 已提交
3796 3797 3798 3799 3800
    VIR_FREE(iobase);
    VIR_FREE(irq);
    return ret;
}

3801 3802 3803 3804
/* Parse the XML definition for a device address
 * @param node XML nodeset to parse for device address definition
 */
static int
3805
virDomainDeviceInfoParseXML(xmlNodePtr node,
3806
                            virHashTablePtr bootHash,
3807
                            virDomainDeviceInfoPtr info,
E
Eric Blake 已提交
3808
                            unsigned int flags)
3809 3810 3811
{
    xmlNodePtr cur;
    xmlNodePtr address = NULL;
3812
    xmlNodePtr master = NULL;
D
Daniel P. Berrange 已提交
3813
    xmlNodePtr alias = NULL;
3814 3815
    xmlNodePtr boot = NULL;
    xmlNodePtr rom = NULL;
3816 3817 3818 3819 3820 3821 3822 3823
    char *type = NULL;
    int ret = -1;

    virDomainDeviceInfoClear(info);

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
D
Daniel P. Berrange 已提交
3824 3825 3826 3827 3828 3829
            if (alias == NULL &&
                !(flags & VIR_DOMAIN_XML_INACTIVE) &&
                xmlStrEqual(cur->name, BAD_CAST "alias")) {
                alias = cur;
            } else if (address == NULL &&
                       xmlStrEqual(cur->name, BAD_CAST "address")) {
3830
                address = cur;
3831 3832 3833
            } else if (master == NULL &&
                       xmlStrEqual(cur->name, BAD_CAST "master")) {
                master = cur;
3834
            } else if (boot == NULL &&
3835 3836 3837 3838 3839 3840 3841
                       (flags & VIR_DOMAIN_XML_INTERNAL_ALLOW_BOOT) &&
                       xmlStrEqual(cur->name, BAD_CAST "boot")) {
                boot = cur;
            } else if (rom == NULL &&
                       (flags & VIR_DOMAIN_XML_INTERNAL_ALLOW_ROM) &&
                       xmlStrEqual(cur->name, BAD_CAST "rom")) {
                rom = cur;
3842 3843 3844 3845 3846
            }
        }
        cur = cur->next;
    }

D
Daniel P. Berrange 已提交
3847 3848 3849
    if (alias)
        info->alias = virXMLPropString(alias, "name");

3850 3851 3852 3853 3854 3855
    if (master) {
        info->mastertype = VIR_DOMAIN_CONTROLLER_MASTER_USB;
        if (virDomainDeviceUSBMasterParseXML(master, &info->master.usb) < 0)
            goto cleanup;
    }

3856
    if (boot) {
3857
        if (virDomainDeviceBootParseXML(boot, &info->bootIndex, bootHash))
3858 3859 3860 3861 3862
            goto cleanup;
    }

    if (rom) {
        char *rombar = virXMLPropString(rom, "bar");
3863
        if (rombar &&
J
Ján Tomko 已提交
3864
            ((info->rombar = virTristateSwitchTypeFromString(rombar)) <= 0)) {
3865 3866
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown rom bar value '%s'"), rombar);
3867 3868 3869 3870
            VIR_FREE(rombar);
            goto cleanup;
        }
        VIR_FREE(rombar);
3871
        info->romfile = virXMLPropString(rom, "file");
3872 3873
    }

3874 3875 3876 3877 3878 3879
    if (!address)
        return 0;

    type = virXMLPropString(address, "type");

    if (type) {
3880
        if ((info->type = virDomainDeviceAddressTypeFromString(type)) <= 0) {
3881
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
3882
                           _("unknown address type '%s'"), type);
3883 3884 3885
            goto cleanup;
        }
    } else {
3886 3887
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("No type specified for device address"));
3888 3889 3890
        goto cleanup;
    }

3891
    switch ((virDomainDeviceAddressType) info->type) {
3892
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI:
3893
        if (virDevicePCIAddressParseXML(address, &info->addr.pci) < 0)
3894 3895 3896
            goto cleanup;
        break;

3897
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE:
3898
        if (virDomainDeviceDriveAddressParseXML(address, &info->addr.drive) < 0)
3899 3900 3901
            goto cleanup;
        break;

3902 3903 3904 3905 3906 3907
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL:
        if (virDomainDeviceVirtioSerialAddressParseXML
                (address, &info->addr.vioserial) < 0)
            goto cleanup;
        break;

E
Eric Blake 已提交
3908 3909 3910 3911 3912
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID:
        if (virDomainDeviceCcidAddressParseXML(address, &info->addr.ccid) < 0)
            goto cleanup;
        break;

3913 3914 3915 3916 3917
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB:
        if (virDomainDeviceUSBAddressParseXML(address, &info->addr.usb) < 0)
            goto cleanup;
        break;

3918 3919 3920 3921 3922
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO:
        if (virDomainDeviceSpaprVioAddressParseXML(address, &info->addr.spaprvio) < 0)
            goto cleanup;
        break;

3923 3924 3925 3926 3927 3928
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW:
        if (virDomainDeviceCCWAddressParseXML
                (address, &info->addr.ccw) < 0)
            goto cleanup;
        break;

3929 3930 3931
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO:
        break;

H
Hu Tao 已提交
3932 3933 3934 3935 3936
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_ISA:
        if (virDomainDeviceISAAddressParseXML(address, &info->addr.isa) < 0)
            goto cleanup;
        break;

3937 3938 3939
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390:
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("virtio-s390 bus doesn't have an address"));
3940
        goto cleanup;
3941 3942 3943 3944

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE:
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_LAST:
        break;
3945 3946 3947 3948
    }

    ret = 0;

3949
 cleanup:
D
Daniel P. Berrange 已提交
3950 3951
    if (ret == -1)
        VIR_FREE(info->alias);
3952 3953 3954 3955
    VIR_FREE(type);
    return ret;
}

3956 3957
static int
virDomainParseLegacyDeviceAddress(char *devaddr,
3958
                                  virDevicePCIAddressPtr pci)
3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972
{
    char *tmp;

    /* expected format: <domain>:<bus>:<slot> */
    if (/* domain */
        virStrToLong_ui(devaddr, &tmp, 16, &pci->domain) < 0 || *tmp != ':' ||
        /* bus */
        virStrToLong_ui(tmp + 1, &tmp, 16, &pci->bus) < 0 || *tmp != ':' ||
        /* slot */
        virStrToLong_ui(tmp + 1, NULL, 16, &pci->slot) < 0)
        return -1;

    return 0;
}
3973

3974
static int
3975
virDomainHostdevSubsysUSBDefParseXML(xmlNodePtr node,
3976 3977 3978 3979
                                     virDomainHostdevDefPtr def)
{

    int ret = -1;
3980
    bool got_product, got_vendor;
3981
    xmlNodePtr cur;
3982
    char *startupPolicy = NULL;
3983
    char *autoAddress;
3984
    virDomainHostdevSubsysUSBPtr usbsrc = &def->source.subsys.u.usb;
3985 3986 3987 3988 3989

    if ((startupPolicy = virXMLPropString(node, "startupPolicy"))) {
        def->startupPolicy =
            virDomainStartupPolicyTypeFromString(startupPolicy);
        if (def->startupPolicy <= 0) {
3990
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
3991 3992 3993 3994 3995 3996 3997
                           _("Unknown startup policy '%s'"),
                           startupPolicy);
            VIR_FREE(startupPolicy);
            goto out;
        }
        VIR_FREE(startupPolicy);
    }
3998

3999 4000
    if ((autoAddress = virXMLPropString(node, "autoAddress"))) {
        if (STREQ(autoAddress, "yes"))
4001
            usbsrc->autoAddress = true;
4002 4003 4004
        VIR_FREE(autoAddress);
    }

4005 4006
    /* Product can validly be 0, so we need some extra help to determine
     * if it is uninitialized*/
4007 4008
    got_product = false;
    got_vendor = false;
4009 4010 4011 4012 4013 4014 4015 4016

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if (xmlStrEqual(cur->name, BAD_CAST "vendor")) {
                char *vendor = virXMLPropString(cur, "id");

                if (vendor) {
4017
                    got_vendor = true;
4018
                    if (virStrToLong_ui(vendor, NULL, 0, &usbsrc->vendor) < 0) {
4019 4020
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("cannot parse vendor id %s"), vendor);
4021 4022 4023 4024 4025
                        VIR_FREE(vendor);
                        goto out;
                    }
                    VIR_FREE(vendor);
                } else {
4026 4027
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("usb vendor needs id"));
4028 4029 4030 4031 4032 4033
                    goto out;
                }
            } else if (xmlStrEqual(cur->name, BAD_CAST "product")) {
                char* product = virXMLPropString(cur, "id");

                if (product) {
4034
                    got_product = true;
4035
                    if (virStrToLong_ui(product, NULL, 0,
4036
                                        &usbsrc->product) < 0) {
4037 4038 4039
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("cannot parse product %s"),
                                       product);
4040 4041 4042 4043 4044
                        VIR_FREE(product);
                        goto out;
                    }
                    VIR_FREE(product);
                } else {
4045 4046
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("usb product needs id"));
4047 4048 4049 4050 4051 4052 4053
                    goto out;
                }
            } else if (xmlStrEqual(cur->name, BAD_CAST "address")) {
                char *bus, *device;

                bus = virXMLPropString(cur, "bus");
                if (bus) {
4054
                    if (virStrToLong_ui(bus, NULL, 0, &usbsrc->bus) < 0) {
4055 4056
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("cannot parse bus %s"), bus);
4057 4058 4059 4060 4061
                        VIR_FREE(bus);
                        goto out;
                    }
                    VIR_FREE(bus);
                } else {
4062 4063
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("usb address needs bus id"));
4064 4065 4066 4067 4068
                    goto out;
                }

                device = virXMLPropString(cur, "device");
                if (device) {
4069
                    if (virStrToLong_ui(device, NULL, 0, &usbsrc->device) < 0) {
4070 4071 4072
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("cannot parse device %s"),
                                       device);
4073 4074 4075 4076 4077
                        VIR_FREE(device);
                        goto out;
                    }
                    VIR_FREE(device);
                } else {
4078 4079
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("usb address needs device id"));
4080 4081 4082
                    goto out;
                }
            } else {
4083 4084 4085
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unknown usb source type '%s'"),
                               cur->name);
4086 4087 4088 4089 4090 4091
                goto out;
            }
        }
        cur = cur->next;
    }

4092
    if (got_vendor && usbsrc->vendor == 0) {
4093 4094
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("vendor cannot be 0."));
4095 4096 4097 4098
        goto out;
    }

    if (!got_vendor && got_product) {
4099 4100
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing vendor"));
4101 4102 4103
        goto out;
    }
    if (got_vendor && !got_product) {
4104 4105
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing product"));
4106 4107 4108 4109
        goto out;
    }

    ret = 0;
4110
 out:
4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122
    return ret;
}

/* The internal XML for host PCI device's original states:
 *
 * <origstates>
 *   <unbind/>
 *   <removeslot/>
 *   <reprobe/>
 * </origstates>
 */
static int
4123
virDomainHostdevSubsysPCIOrigStatesDefParseXML(xmlNodePtr node,
4124 4125 4126 4127 4128 4129 4130 4131
                                               virDomainHostdevOrigStatesPtr def)
{
    xmlNodePtr cur;
    cur = node->children;

    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if (xmlStrEqual(cur->name, BAD_CAST "unbind")) {
4132
                def->states.pci.unbind_from_stub = true;
4133
            } else if (xmlStrEqual(cur->name, BAD_CAST "removeslot")) {
4134
                def->states.pci.remove_slot = true;
4135
            } else if (xmlStrEqual(cur->name, BAD_CAST "reprobe")) {
4136
                def->states.pci.reprobe = true;
4137
            } else {
4138 4139 4140
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unsupported element '%s' of 'origstates'"),
                               cur->name);
4141 4142 4143 4144 4145 4146 4147 4148 4149 4150
                return -1;
            }
        }
        cur = cur->next;
    }

    return 0;
}

static int
4151
virDomainHostdevSubsysPCIDefParseXML(xmlNodePtr node,
4152 4153 4154 4155 4156 4157 4158 4159 4160 4161
                                     virDomainHostdevDefPtr def,
                                     unsigned int flags)
{
    int ret = -1;
    xmlNodePtr cur;

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if (xmlStrEqual(cur->name, BAD_CAST "address")) {
4162
                virDevicePCIAddressPtr addr =
4163
                    &def->source.subsys.u.pci.addr;
4164

4165
                if (virDevicePCIAddressParseXML(cur, addr) < 0)
4166 4167 4168 4169 4170 4171 4172
                    goto out;
            } else if ((flags & VIR_DOMAIN_XML_INTERNAL_STATUS) &&
                       xmlStrEqual(cur->name, BAD_CAST "state")) {
                /* Legacy back-compat. Don't add any more attributes here */
                char *devaddr = virXMLPropString(cur, "devaddr");
                if (devaddr &&
                    virDomainParseLegacyDeviceAddress(devaddr,
4173
                                                      &def->info->addr.pci) < 0) {
4174 4175 4176
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to parse devaddr parameter '%s'"),
                                   devaddr);
4177 4178 4179
                    VIR_FREE(devaddr);
                    goto out;
                }
4180
                def->info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
4181 4182 4183
            } else if ((flags & VIR_DOMAIN_XML_INTERNAL_PCI_ORIG_STATES) &&
                       xmlStrEqual(cur->name, BAD_CAST "origstates")) {
                virDomainHostdevOrigStatesPtr states = &def->origstates;
4184
                if (virDomainHostdevSubsysPCIOrigStatesDefParseXML(cur, states) < 0)
4185 4186
                    goto out;
            } else {
4187 4188 4189
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unknown pci source type '%s'"),
                               cur->name);
4190 4191 4192 4193 4194 4195 4196
                goto out;
            }
        }
        cur = cur->next;
    }

    ret = 0;
4197
 out:
4198 4199 4200
    return ret;
}

4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273
static int
virDomainStorageHostParse(xmlNodePtr node,
                          virStorageNetHostDefPtr *hosts,
                          size_t *nhosts)
{
    int ret = -1;
    xmlNodePtr child;
    char *transport = NULL;
    virStorageNetHostDef host;

    memset(&host, 0, sizeof(host));

    child = node->children;
    while (child != NULL) {
        if (child->type == XML_ELEMENT_NODE &&
            xmlStrEqual(child->name, BAD_CAST "host")) {

            host.transport = VIR_STORAGE_NET_HOST_TRANS_TCP;

            /* transport can be tcp (default), unix or rdma.  */
            if ((transport = virXMLPropString(child, "transport"))) {
                host.transport = virStorageNetHostTransportTypeFromString(transport);
                if (host.transport < 0) {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("unknown protocol transport type '%s'"),
                                   transport);
                    goto cleanup;
                }
            }

            host.socket = virXMLPropString(child, "socket");

            if (host.transport == VIR_STORAGE_NET_HOST_TRANS_UNIX &&
                host.socket == NULL) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing socket for unix transport"));
                goto cleanup;
            }

            if (host.transport != VIR_STORAGE_NET_HOST_TRANS_UNIX &&
                host.socket != NULL) {
                virReportError(VIR_ERR_XML_ERROR,
                               _("transport '%s' does not support "
                                 "socket attribute"),
                               transport);
                goto cleanup;
            }

            VIR_FREE(transport);

            if (host.transport != VIR_STORAGE_NET_HOST_TRANS_UNIX) {
                if (!(host.name = virXMLPropString(child, "name"))) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("missing name for host"));
                    goto cleanup;
                }

                host.port = virXMLPropString(child, "port");
            }

            if (VIR_APPEND_ELEMENT(*hosts, *nhosts, host) < 0)
                goto cleanup;
        }
        child = child->next;
    }
    ret = 0;

 cleanup:
    virStorageNetHostDefClear(&host);
    VIR_FREE(transport);
    return ret;
}

H
Han Cheng 已提交
4274
static int
4275 4276
virDomainHostdevSubsysSCSIHostDefParseXML(xmlNodePtr sourcenode,
                                          virDomainHostdevSubsysSCSIPtr scsisrc)
H
Han Cheng 已提交
4277 4278 4279 4280 4281
{
    int ret = -1;
    bool got_address = false, got_adapter = false;
    xmlNodePtr cur;
    char *bus = NULL, *target = NULL, *unit = NULL;
4282
    virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
H
Han Cheng 已提交
4283

4284
    cur = sourcenode->children;
H
Han Cheng 已提交
4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if (xmlStrEqual(cur->name, BAD_CAST "address")) {
                if (got_address) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("more than one source addresses is "
                                     "specified for scsi hostdev"));
                    goto cleanup;
                }

                if (!(bus = virXMLPropString(cur, "bus")) ||
                    !(target = virXMLPropString(cur, "target")) ||
                    !(unit = virXMLPropString(cur, "unit"))) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("'bus', 'target', and 'unit' must be specified "
                                     "for scsi hostdev source address"));
                    goto cleanup;
                }

4304
                if (virStrToLong_ui(bus, NULL, 0, &scsihostsrc->bus) < 0) {
H
Han Cheng 已提交
4305 4306 4307 4308 4309
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("cannot parse bus '%s'"), bus);
                    goto cleanup;
                }

4310 4311
                if (virStrToLong_ui(target, NULL, 0,
                                    &scsihostsrc->target) < 0) {
H
Han Cheng 已提交
4312 4313 4314 4315 4316
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("cannot parse target '%s'"), target);
                    goto cleanup;
                }

4317
                if (virStrToLong_ui(unit, NULL, 0, &scsihostsrc->unit) < 0) {
H
Han Cheng 已提交
4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("cannot parse unit '%s'"), unit);
                    goto cleanup;
                }

                got_address = true;
            } else if (xmlStrEqual(cur->name, BAD_CAST "adapter")) {
                if (got_adapter) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("more than one adapters is specified "
                                     "for scsi hostdev source"));
                    goto cleanup;
                }
4331
                if (!(scsihostsrc->adapter = virXMLPropString(cur, "name"))) {
H
Han Cheng 已提交
4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("'adapter' must be specified for scsi hostdev source"));
                    goto cleanup;
                }

                got_adapter = true;
            } else {
                virReportError(VIR_ERR_XML_ERROR,
                               _("unsupported element '%s' of scsi hostdev source"),
                               cur->name);
                goto cleanup;
            }
        }
        cur = cur->next;
    }

    if (!got_address || !got_adapter) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("'adapter' and 'address' must be specified for scsi "
                         "hostdev source"));
        goto cleanup;
    }

    ret = 0;
4356
 cleanup:
H
Han Cheng 已提交
4357 4358 4359 4360 4361 4362
    VIR_FREE(bus);
    VIR_FREE(target);
    VIR_FREE(unit);
    return ret;
}

J
John Ferlan 已提交
4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427
static int
virDomainHostdevSubsysSCSIiSCSIDefParseXML(xmlNodePtr sourcenode,
                                           virDomainHostdevSubsysSCSIPtr def)
{
    int ret = -1;
    int auth_secret_usage = -1;
    xmlNodePtr cur;
    virStorageAuthDefPtr authdef = NULL;
    virDomainHostdevSubsysSCSIiSCSIPtr iscsisrc = &def->u.iscsi;

    /* Similar to virDomainDiskSourceParse for a VIR_STORAGE_TYPE_NETWORK */

    if (!(iscsisrc->path = virXMLPropString(sourcenode, "name"))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing iSCSI hostdev source path name"));
        goto cleanup;
    }

    if (virDomainStorageHostParse(sourcenode, &iscsisrc->hosts,
                                  &iscsisrc->nhosts) < 0)
        goto cleanup;

    if (iscsisrc->nhosts < 1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing the host address for the iSCSI hostdev"));
        goto cleanup;
    }
    if (iscsisrc->nhosts > 1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("only one source host address may be specified "
                         "for the iSCSI hostdev"));
        goto cleanup;
    }

    cur = sourcenode->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "auth")) {
            if (!(authdef = virStorageAuthDefParse(sourcenode->doc, cur)))
                goto cleanup;
            if ((auth_secret_usage =
                 virSecretUsageTypeFromString(authdef->secrettype)) < 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("invalid secret type %s"),
                               authdef->secrettype);
                goto cleanup;
            }
            if (auth_secret_usage != VIR_SECRET_USAGE_TYPE_ISCSI) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("hostdev invalid secret type '%s'"),
                               authdef->secrettype);
                goto cleanup;
            }
            iscsisrc->auth = authdef;
            authdef = NULL;
        }
        cur = cur->next;
    }
    ret = 0;

 cleanup:
    virStorageAuthDefFree(authdef);
    return ret;
}

4428 4429 4430 4431
static int
virDomainHostdevSubsysSCSIDefParseXML(xmlNodePtr sourcenode,
                                      virDomainHostdevSubsysSCSIPtr scsisrc)
{
J
John Ferlan 已提交
4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453
    char *protocol = NULL;
    int ret = -1;

    if ((protocol = virXMLPropString(sourcenode, "protocol"))) {
        scsisrc->protocol =
            virDomainHostdevSubsysSCSIProtocolTypeFromString(protocol);
        if (scsisrc->protocol < 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Unknown SCSI subsystem protocol '%s'"),
                           protocol);
            goto cleanup;
        }
    }

    if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI)
        ret = virDomainHostdevSubsysSCSIiSCSIDefParseXML(sourcenode, scsisrc);
    else
        ret = virDomainHostdevSubsysSCSIHostDefParseXML(sourcenode, scsisrc);

 cleanup:
    VIR_FREE(protocol);
    return ret;
4454 4455
}

4456 4457 4458 4459
/* Check if a drive type address $controller:0:0:$unit is already
 * taken by a disk or not.
 */
static bool
4460
virDomainDriveAddressIsUsedByDisk(const virDomainDef *def,
4461
                                  virDomainDiskBus type,
4462 4463 4464 4465
                                  unsigned int controller,
                                  unsigned int unit)
{
    virDomainDiskDefPtr disk;
4466
    size_t i;
4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488

    for (i = 0; i < def->ndisks; i++) {
        disk = def->disks[i];

        if (disk->bus != type ||
            disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE)
            continue;

        if (disk->info.addr.drive.controller == controller &&
            disk->info.addr.drive.unit == unit &&
            disk->info.addr.drive.bus == 0 &&
            disk->info.addr.drive.target == 0)
            return true;
    }

    return false;
}

/* Check if a drive type address $controller:0:0:$unit is already
 * taken by a host device or not.
 */
static bool
4489
virDomainDriveAddressIsUsedByHostdev(const virDomainDef *def,
4490
                                     virDomainHostdevSubsysType type,
4491 4492 4493 4494
                                     unsigned int controller,
                                     unsigned int unit)
{
    virDomainHostdevDefPtr hostdev;
4495
    size_t i;
4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513

    for (i = 0; i < def->nhostdevs; i++) {
        hostdev = def->hostdevs[i];

        if (hostdev->source.subsys.type != type)
            continue;

        if (hostdev->info->addr.drive.controller == controller &&
            hostdev->info->addr.drive.unit == unit &&
            hostdev->info->addr.drive.bus == 0 &&
            hostdev->info->addr.drive.target == 0)
            return true;
    }

    return false;
}

static bool
4514
virDomainSCSIDriveAddressIsUsed(const virDomainDef *def,
4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534
                                unsigned int controller,
                                unsigned int unit)
{
    /* In current implementation, the maximum unit number of a controller
     * is either 16 or 7 (narrow SCSI bus), and if the maximum unit number
     * is 16, the controller itself is on unit 7 */
    if (unit == 7)
        return true;

    if (virDomainDriveAddressIsUsedByDisk(def, VIR_DOMAIN_DISK_BUS_SCSI,
                                          controller, unit) ||
        virDomainDriveAddressIsUsedByHostdev(def, VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI,
                                             controller, unit))
        return true;

    return false;
}

/* Find out the next usable "unit" of a specific controller */
static int
4535
virDomainControllerSCSINextUnit(const virDomainDef *def,
4536 4537 4538
                                unsigned int max_unit,
                                unsigned int controller)
{
4539
    size_t i;
4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553

    for (i = 0; i < max_unit; i++) {
        if (!virDomainSCSIDriveAddressIsUsed(def, controller, i))
            return i;
    }

    return -1;
}

#define SCSI_WIDE_BUS_MAX_CONT_UNIT 16
#define SCSI_NARROW_BUS_MAX_CONT_UNIT 7

static int
virDomainHostdevAssignAddress(virDomainXMLOptionPtr xmlopt,
4554
                              const virDomainDef *def,
4555 4556
                              virDomainHostdevDefPtr hostdev)
{
4557 4558
    int next_unit = 0;
    unsigned controller = 0;
4559
    size_t i;
4560
    int ret;
4561 4562 4563 4564

    if (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI)
        return -1;

4565
    for (i = 0; i < def->ncontrollers; i++) {
4566 4567 4568
        if (def->controllers[i]->type != VIR_DOMAIN_CONTROLLER_TYPE_SCSI)
            continue;

4569 4570
        controller++;
        ret = virDomainControllerSCSINextUnit(def,
4571
                                              xmlopt->config.hasWideSCSIBus ?
4572 4573 4574 4575 4576 4577 4578 4579
                                              SCSI_WIDE_BUS_MAX_CONT_UNIT :
                                              SCSI_NARROW_BUS_MAX_CONT_UNIT,
                                              def->controllers[i]->idx);
        if (ret >= 0) {
            next_unit = ret;
            controller = def->controllers[i]->idx;
            break;
        }
4580 4581 4582
    }

    hostdev->info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE;
4583
    hostdev->info->addr.drive.controller = controller;
4584 4585
    hostdev->info->addr.drive.bus = 0;
    hostdev->info->addr.drive.target = 0;
4586
    hostdev->info->addr.drive.unit = next_unit;
4587 4588 4589 4590

    return 0;
}

4591
static int
4592 4593 4594 4595 4596
virDomainHostdevDefParseXMLSubsys(xmlNodePtr node,
                                  xmlXPathContextPtr ctxt,
                                  const char *type,
                                  virDomainHostdevDefPtr def,
                                  unsigned int flags)
4597 4598 4599
{
    xmlNodePtr sourcenode;
    char *managed = NULL;
O
Osier Yang 已提交
4600
    char *sgio = NULL;
4601
    char *rawio = NULL;
4602 4603
    char *backendStr = NULL;
    int backend;
4604
    int ret = -1;
4605
    virDomainHostdevSubsysPCIPtr pcisrc = &def->source.subsys.u.pci;
4606
    virDomainHostdevSubsysSCSIPtr scsisrc = &def->source.subsys.u.scsi;
4607 4608 4609 4610 4611 4612

    /* @managed can be read from the xml document - it is always an
     * attribute of the toplevel element, no matter what type of
     * element that might be (pure hostdev, or higher level device
     * (e.g. <interface>) with type='hostdev')
     */
C
Chen Fan 已提交
4613
    if ((managed = virXMLPropString(node, "managed")) != NULL) {
4614
        if (STREQ(managed, "yes"))
4615
            def->managed = true;
4616 4617
    }

O
Osier Yang 已提交
4618
    sgio = virXMLPropString(node, "sgio");
4619
    rawio = virXMLPropString(node, "rawio");
O
Osier Yang 已提交
4620

4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631
    /* @type is passed in from the caller rather than read from the
     * xml document, because it is specified in different places for
     * different kinds of defs - it is an attribute of
     * <source>/<address> for an intelligent hostdev (<interface>),
     * but an attribute of the toplevel element for a standard
     * <hostdev>.  (the functions we're going to call expect address
     * type to already be known).
     */
    if (type) {
        if ((def->source.subsys.type
             = virDomainHostdevSubsysTypeFromString(type)) < 0) {
4632
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4633 4634
                           _("unknown host device source address type '%s'"),
                           type);
4635 4636 4637
            goto error;
        }
    } else {
4638 4639
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("missing source address type"));
4640 4641 4642 4643
        goto error;
    }

    if (!(sourcenode = virXPathNode("./source", ctxt))) {
4644 4645
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Missing <source> element in hostdev device"));
4646 4647
        goto error;
    }
4648 4649 4650 4651 4652 4653 4654 4655 4656

    if (def->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB &&
        virXPathBoolean("boolean(./source/@startupPolicy)", ctxt)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Setting startupPolicy is only allowed for USB"
                         " devices"));
        goto error;
    }

O
Osier Yang 已提交
4657
    if (sgio) {
4658
        if (def->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI) {
O
Osier Yang 已提交
4659 4660 4661 4662 4663
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("sgio is only supported for scsi host device"));
            goto error;
        }

4664
        if ((scsisrc->sgio = virDomainDeviceSGIOTypeFromString(sgio)) <= 0) {
4665
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
O
Osier Yang 已提交
4666 4667 4668 4669 4670
                           _("unknown sgio mode '%s'"), sgio);
            goto error;
        }
    }

4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685
    if (rawio) {
        if (def->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("rawio is only supported for scsi host device"));
            goto error;
        }

        if ((scsisrc->rawio = virTristateBoolTypeFromString(rawio)) <= 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown hostdev rawio setting '%s'"),
                           rawio);
            goto error;
        }
    }

4686 4687
    switch (def->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
4688
        if (virDomainHostdevSubsysPCIDefParseXML(sourcenode, def, flags) < 0)
4689
            goto error;
4690

4691
        backend = VIR_DOMAIN_HOSTDEV_PCI_BACKEND_DEFAULT;
4692
        if ((backendStr = virXPathString("string(./driver/@name)", ctxt)) &&
4693
            (((backend = virDomainHostdevSubsysPCIBackendTypeFromString(backendStr)) < 0) ||
4694
             backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_DEFAULT)) {
4695
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4696 4697 4698 4699
                           _("Unknown PCI device <driver name='%s'/> "
                             "has been specified"), backendStr);
            goto error;
        }
4700
        pcisrc->backend = backend;
4701

4702
        break;
4703

4704
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
4705
        if (virDomainHostdevSubsysUSBDefParseXML(sourcenode, def) < 0)
4706 4707
            goto error;
        break;
H
Han Cheng 已提交
4708 4709

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
4710
        if (virDomainHostdevSubsysSCSIDefParseXML(sourcenode, scsisrc) < 0)
H
Han Cheng 已提交
4711 4712 4713
            goto error;
        break;

4714
    default:
4715 4716 4717
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("address type='%s' not supported in hostdev interfaces"),
                       virDomainHostdevSubsysTypeToString(def->source.subsys.type));
4718 4719
        goto error;
    }
4720

4721
    ret = 0;
4722
 error:
4723
    VIR_FREE(managed);
O
Osier Yang 已提交
4724
    VIR_FREE(sgio);
4725
    VIR_FREE(rawio);
4726
    VIR_FREE(backendStr);
4727 4728 4729
    return ret;
}

4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749
static int
virDomainHostdevDefParseXMLCaps(xmlNodePtr node ATTRIBUTE_UNUSED,
                                xmlXPathContextPtr ctxt,
                                const char *type,
                                virDomainHostdevDefPtr def)
{
    xmlNodePtr sourcenode;
    int ret = -1;

    /* @type is passed in from the caller rather than read from the
     * xml document, because it is specified in different places for
     * different kinds of defs - it is an attribute of
     * <source>/<address> for an intelligent hostdev (<interface>),
     * but an attribute of the toplevel element for a standard
     * <hostdev>.  (the functions we're going to call expect address
     * type to already be known).
     */
    if (type) {
        if ((def->source.caps.type
             = virDomainHostdevCapsTypeFromString(type)) < 0) {
4750
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783
                           _("unknown host device source address type '%s'"),
                           type);
            goto error;
        }
    } else {
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("missing source address type"));
        goto error;
    }

    if (!(sourcenode = virXPathNode("./source", ctxt))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Missing <source> element in hostdev device"));
        goto error;
    }

    switch (def->source.caps.type) {
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_STORAGE:
        if (!(def->source.caps.u.storage.block =
              virXPathString("string(./source/block[1])", ctxt))) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("Missing <block> element in hostdev storage device"));
            goto error;
        }
        break;
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_MISC:
        if (!(def->source.caps.u.misc.chardev =
              virXPathString("string(./source/char[1])", ctxt))) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("Missing <char> element in hostdev character device"));
            goto error;
        }
        break;
4784 4785 4786 4787 4788 4789 4790 4791
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_NET:
        if (!(def->source.caps.u.net.iface =
              virXPathString("string(./source/interface[1])", ctxt))) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("Missing <interface> element in hostdev net device"));
            goto error;
        }
        break;
4792 4793 4794 4795 4796 4797 4798
    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("address type='%s' not supported in hostdev interfaces"),
                       virDomainHostdevCapsTypeToString(def->source.caps.type));
        goto error;
    }
    ret = 0;
4799
 error:
4800 4801 4802
    return ret;
}

4803
int
H
Han Cheng 已提交
4804 4805 4806
virDomainDeviceFindControllerModel(virDomainDefPtr def,
                                   virDomainDeviceInfoPtr info,
                                   int controllerType)
4807 4808
{
    int model = -1;
4809
    size_t i;
4810 4811 4812

    for (i = 0; i < def->ncontrollers; i++) {
        if (def->controllers[i]->type == controllerType &&
H
Han Cheng 已提交
4813
            def->controllers[i]->idx == info->addr.drive.controller)
4814 4815 4816 4817 4818 4819
            model = def->controllers[i]->model;
    }

    return model;
}

4820 4821 4822 4823 4824
virDomainDiskDefPtr
virDomainDiskFindByBusAndDst(virDomainDefPtr def,
                             int bus,
                             char *dst)
{
4825
    size_t i;
4826 4827 4828 4829

    if (!dst)
        return NULL;

4830
    for (i = 0; i < def->ndisks; i++) {
4831 4832 4833 4834 4835 4836 4837 4838 4839
        if (def->disks[i]->bus == bus &&
            STREQ(def->disks[i]->dst, dst)) {
            return def->disks[i];
        }
    }

    return NULL;
}

4840
int
4841 4842
virDomainDiskDefAssignAddress(virDomainXMLOptionPtr xmlopt,
                              virDomainDiskDefPtr def)
4843 4844
{
    int idx = virDiskNameToIndex(def->dst);
4845 4846 4847 4848
    if (idx < 0) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("Unknown disk name '%s' and no address specified"),
                       def->dst);
4849
        return -1;
4850
    }
4851 4852 4853 4854

    switch (def->bus) {
    case VIR_DOMAIN_DISK_BUS_SCSI:
        def->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE;
4855

4856
        if (xmlopt->config.hasWideSCSIBus) {
4857 4858 4859 4860 4861 4862 4863 4864 4865 4866
            /* For a wide SCSI bus we define the default mapping to be
             * 16 units per bus, 1 bus per controller, many controllers.
             * Unit 7 is the SCSI controller itself. Therefore unit 7
             * cannot be assigned to disks and is skipped.
             */
            def->info.addr.drive.controller = idx / 15;
            def->info.addr.drive.bus = 0;
            def->info.addr.drive.unit = idx % 15;

            /* Skip the SCSI controller at unit 7 */
4867
            if (def->info.addr.drive.unit >= 7)
4868 4869 4870 4871 4872 4873 4874 4875 4876
                ++def->info.addr.drive.unit;
        } else {
            /* For a narrow SCSI bus we define the default mapping to be
             * 7 units per bus, 1 bus per controller, many controllers */
            def->info.addr.drive.controller = idx / 7;
            def->info.addr.drive.bus = 0;
            def->info.addr.drive.unit = idx % 7;
        }

4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887
        break;

    case VIR_DOMAIN_DISK_BUS_IDE:
        /* For IDE we define the default mapping to be 2 units
         * per bus, 2 bus per controller, many controllers */
        def->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE;
        def->info.addr.drive.controller = idx / 4;
        def->info.addr.drive.bus = (idx % 4) / 2;
        def->info.addr.drive.unit = (idx % 2);
        break;

J
Jim Fehlig 已提交
4888 4889 4890 4891 4892 4893 4894 4895 4896
    case VIR_DOMAIN_DISK_BUS_SATA:
        /* For SATA we define the default mapping to be 6 units
         * per bus, 1 bus per controller, many controllers */
        def->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE;
        def->info.addr.drive.controller = idx / 6;
        def->info.addr.drive.bus = 0;
        def->info.addr.drive.unit = idx % 6;
        break;

4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909
    case VIR_DOMAIN_DISK_BUS_FDC:
        /* For FDC we define the default mapping to be 2 units
         * per bus, 1 bus per controller, many controllers */
        def->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE;
        def->info.addr.drive.controller = idx / 2;
        def->info.addr.drive.bus = 0;
        def->info.addr.drive.unit = idx % 2;
        break;

    default:
        /* Other disk bus's aren't controller based */
        break;
    }
4910 4911

    return 0;
4912 4913
}

4914 4915
static virSecurityLabelDefPtr
virSecurityLabelDefParseXML(xmlXPathContextPtr ctxt,
4916
                            unsigned int flags)
E
Eric Blake 已提交
4917 4918
{
    char *p;
4919
    virSecurityLabelDefPtr seclabel = NULL;
E
Eric Blake 已提交
4920

4921 4922 4923 4924
    p = virXPathStringLimit("string(./@model)",
                            VIR_SECURITY_MODEL_BUFLEN - 1, ctxt);

    if (!(seclabel = virSecurityLabelDefNew(p)))
4925
        goto error;
4926
    VIR_FREE(p);
E
Eric Blake 已提交
4927

4928 4929 4930
    /* set default value */
    seclabel->type = VIR_DOMAIN_SECLABEL_DYNAMIC;

4931
    p = virXPathStringLimit("string(./@type)",
4932 4933 4934 4935
                            VIR_SECURITY_LABEL_BUFLEN - 1, ctxt);
    if (p) {
        seclabel->type = virDomainSeclabelTypeFromString(p);
        if (seclabel->type <= 0) {
4936
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4937
                           _("invalid security type '%s'"), p);
E
Eric Blake 已提交
4938 4939
            goto error;
        }
4940
    }
4941

4942 4943 4944 4945 4946
    if (seclabel->type == VIR_DOMAIN_SECLABEL_STATIC ||
        seclabel->type == VIR_DOMAIN_SECLABEL_NONE)
        seclabel->relabel = false;

    VIR_FREE(p);
4947
    p = virXPathStringLimit("string(./@relabel)",
E
Eric Blake 已提交
4948
                            VIR_SECURITY_LABEL_BUFLEN-1, ctxt);
4949
    if (p) {
E
Eric Blake 已提交
4950
        if (STREQ(p, "yes")) {
4951
            seclabel->relabel = true;
E
Eric Blake 已提交
4952
        } else if (STREQ(p, "no")) {
4953
            seclabel->relabel = false;
E
Eric Blake 已提交
4954
        } else {
4955 4956
            virReportError(VIR_ERR_XML_ERROR,
                           _("invalid security relabel value %s"), p);
4957
            goto error;
E
Eric Blake 已提交
4958 4959
        }
    }
4960
    VIR_FREE(p);
E
Eric Blake 已提交
4961

4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973
    if (seclabel->type == VIR_DOMAIN_SECLABEL_DYNAMIC &&
        !seclabel->relabel) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       "%s", _("dynamic label type must use resource relabeling"));
        goto error;
    }
    if (seclabel->type == VIR_DOMAIN_SECLABEL_NONE &&
        seclabel->relabel) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       "%s", _("resource relabeling is not compatible with 'none' label type"));
        goto error;
    }
4974 4975 4976 4977

    /* For the model 'none' none of the following labels is going to be
     * present. Hence, return now. */

4978
    if (STREQ_NULLABLE(seclabel->model, "none")) {
4979 4980
        if (flags & VIR_DOMAIN_XML_INACTIVE) {
            /* Fix older configurations */
4981 4982
            seclabel->type = VIR_DOMAIN_SECLABEL_NONE;
            seclabel->relabel = false;
4983
        } else {
4984
            if (seclabel->type != VIR_DOMAIN_SECLABEL_NONE) {
4985 4986
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unsupported type='%s' to model 'none'"),
4987
                               virDomainSeclabelTypeToString(seclabel->type));
4988 4989 4990 4991 4992
                goto error;
            }
            /* combination of relabel='yes' and type='static'
             * is checked a few lines above. */
        }
4993
        return seclabel;
4994
    }
4995

E
Eric Blake 已提交
4996
    /* Only parse label, if using static labels, or
4997
     * if the 'live' VM XML is requested
E
Eric Blake 已提交
4998
     */
4999
    if (seclabel->type == VIR_DOMAIN_SECLABEL_STATIC ||
E
Eric Blake 已提交
5000
        (!(flags & VIR_DOMAIN_XML_INACTIVE) &&
5001
         seclabel->type != VIR_DOMAIN_SECLABEL_NONE)) {
5002
        p = virXPathStringLimit("string(./label[1])",
E
Eric Blake 已提交
5003
                                VIR_SECURITY_LABEL_BUFLEN-1, ctxt);
5004
        if (p == NULL) {
5005 5006
            virReportError(VIR_ERR_XML_ERROR,
                           "%s", _("security label is missing"));
5007
            goto error;
E
Eric Blake 已提交
5008 5009
        }

5010
        seclabel->label = p;
5011
        p = NULL;
E
Eric Blake 已提交
5012 5013 5014
    }

    /* Only parse imagelabel, if requested live XML with relabeling */
5015
    if (seclabel->relabel &&
E
Eric Blake 已提交
5016
        (!(flags & VIR_DOMAIN_XML_INACTIVE) &&
5017
         seclabel->type != VIR_DOMAIN_SECLABEL_NONE)) {
5018
        p = virXPathStringLimit("string(./imagelabel[1])",
E
Eric Blake 已提交
5019 5020
                                VIR_SECURITY_LABEL_BUFLEN-1, ctxt);
        if (p == NULL) {
5021 5022
            virReportError(VIR_ERR_XML_ERROR,
                           "%s", _("security imagelabel is missing"));
E
Eric Blake 已提交
5023 5024
            goto error;
        }
5025
        seclabel->imagelabel = p;
5026
        p = NULL;
E
Eric Blake 已提交
5027 5028
    }

E
Eric Blake 已提交
5029
    /* Only parse baselabel for dynamic label type */
5030
    if (seclabel->type == VIR_DOMAIN_SECLABEL_DYNAMIC) {
5031
        p = virXPathStringLimit("string(./baselabel[1])",
E
Eric Blake 已提交
5032
                                VIR_SECURITY_LABEL_BUFLEN-1, ctxt);
5033
        seclabel->baselabel = p;
5034
        p = NULL;
E
Eric Blake 已提交
5035 5036
    }

5037
    return seclabel;
E
Eric Blake 已提交
5038

5039
 error:
5040 5041
    VIR_FREE(p);
    virSecurityLabelDefFree(seclabel);
5042
    return NULL;
E
Eric Blake 已提交
5043 5044
}

5045
static int
5046
virSecurityLabelDefsParseXML(virDomainDefPtr def,
5047 5048 5049
                             xmlXPathContextPtr ctxt,
                             virCapsPtr caps,
                             unsigned int flags)
5050
{
5051
    size_t i = 0, j;
5052
    int n;
5053
    xmlNodePtr *list = NULL, saved_node;
5054
    virCapsHostPtr host = &caps->host;
5055

5056 5057 5058 5059
    /* Check args and save context */
    if (def == NULL || ctxt == NULL)
        return 0;
    saved_node = ctxt->node;
5060

5061
    /* Allocate a security labels based on XML */
5062 5063 5064
    if ((n = virXPathNodeSet("./seclabel", ctxt, &list)) < 0)
        goto error;
    if (n == 0)
5065 5066
        return 0;

5067
    if (VIR_ALLOC_N(def->seclabels, n) < 0)
5068
        goto error;
5069

5070 5071
    /* Parse each "seclabel" tag */
    for (i = 0; i < n; i++) {
5072 5073
        virSecurityLabelDefPtr seclabel;

5074
        ctxt->node = list[i];
5075
        if (!(seclabel = virSecurityLabelDefParseXML(ctxt, flags)))
5076
            goto error;
5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088

        for (j = 0; j < i; j++) {
            if (STREQ_NULLABLE(seclabel->model, def->seclabels[j]->model)) {
                virReportError(VIR_ERR_XML_DETAIL,
                               _("seclablel for model %s is already provided"),
                               seclabel->model);
                virSecurityLabelDefFree(seclabel);
                goto error;
            }
        }

        def->seclabels[i] = seclabel;
5089
    }
5090 5091 5092
    def->nseclabels = n;
    ctxt->node = saved_node;
    VIR_FREE(list);
5093

5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110
    /* libvirt versions prior to 0.10.0 support just a single seclabel element
     * in guest's XML and model attribute can be suppressed if type is none or
     * type is dynamic, baselabel is not defined and INACTIVE flag is set.
     *
     * To avoid compatibility issues, for this specific case the first model
     * defined in host's capabilities is used as model for the seclabel.
     */
    if (def->nseclabels == 1 &&
        !def->seclabels[0]->model &&
        host->nsecModels > 0) {
        if (def->seclabels[0]->type == VIR_DOMAIN_SECLABEL_NONE ||
            (def->seclabels[0]->type == VIR_DOMAIN_SECLABEL_DYNAMIC &&
             !def->seclabels[0]->baselabel &&
             (flags & VIR_DOMAIN_XML_INACTIVE))) {
            /* Copy model from host. */
            VIR_DEBUG("Found seclabel without a model, using '%s'",
                      host->secModels[0].model);
5111
            if (VIR_STRDUP(def->seclabels[0]->model, host->secModels[0].model) < 0)
5112
                goto error;
5113 5114 5115 5116 5117 5118 5119

            if (STREQ(def->seclabels[0]->model, "none") &&
                flags & VIR_DOMAIN_XML_INACTIVE) {
                /* Fix older configurations */
                def->seclabels[0]->type = VIR_DOMAIN_SECLABEL_NONE;
                def->seclabels[0]->relabel = false;
            }
5120 5121 5122 5123 5124 5125 5126 5127 5128
        } else {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing security model in domain seclabel"));
            goto error;
        }
    }

    /* Checking missing model information */
    if (def->nseclabels > 1) {
5129
        for (; n; n--) {
5130 5131
            if (def->seclabels[n - 1]->model == NULL) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
5132 5133
                               _("missing security model "
                                 "when using multiple labels"));
5134 5135
                goto error;
            }
5136 5137
        }
    }
5138

5139
    return 0;
5140

5141
 error:
5142
    ctxt->node = saved_node;
5143
    for (; i > 0; i--)
5144 5145
        virSecurityLabelDefFree(def->seclabels[i - 1]);
    VIR_FREE(def->seclabels);
5146
    def->nseclabels = 0;
5147 5148 5149
    VIR_FREE(list);
    return -1;
}
5150

5151
/* Parse the <seclabel> from a disk or character device. */
5152
static int
5153 5154
virSecurityDeviceLabelDefParseXML(virSecurityDeviceLabelDefPtr **seclabels_rtn,
                                  size_t *nseclabels_rtn,
5155
                                  virSecurityLabelDefPtr *vmSeclabels,
5156 5157
                                  int nvmSeclabels, xmlXPathContextPtr ctxt,
                                  unsigned int flags)
5158
{
5159
    virSecurityDeviceLabelDefPtr *seclabels = NULL;
5160
    size_t nseclabels = 0;
5161 5162
    int n;
    size_t i, j;
5163 5164
    xmlNodePtr *list = NULL;
    virSecurityLabelDefPtr vmDef = NULL;
5165
    char *model, *relabel, *label, *labelskip;
5166

5167 5168 5169
    if ((n = virXPathNodeSet("./seclabel", ctxt, &list)) < 0)
        goto error;
    if (n == 0)
5170 5171
        return 0;

5172
    if (VIR_ALLOC_N(seclabels, n) < 0)
5173
        goto error;
5174
    nseclabels = n;
5175
    for (i = 0; i < n; i++) {
5176
        if (VIR_ALLOC(seclabels[i]) < 0)
5177
            goto error;
5178 5179
    }

5180 5181 5182
    for (i = 0; i < n; i++) {
        /* get model associated to this override */
        model = virXMLPropString(list[i], "model");
5183 5184
        if (model) {
            /* find the security label that it's being overridden */
5185 5186 5187 5188 5189 5190
            for (j = 0; j < nvmSeclabels; j++) {
                if (STREQ(vmSeclabels[j]->model, model)) {
                    vmDef = vmSeclabels[j];
                    break;
                }
            }
5191
            seclabels[i]->model = model;
5192 5193 5194
        }

        /* Can't use overrides if top-level doesn't allow relabeling.  */
5195
        if (vmDef && !vmDef->relabel) {
5196 5197 5198 5199 5200 5201 5202 5203 5204
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("label overrides require relabeling to be "
                             "enabled at the domain level"));
            goto error;
        }

        relabel = virXMLPropString(list[i], "relabel");
        if (relabel != NULL) {
            if (STREQ(relabel, "yes")) {
5205
                seclabels[i]->relabel = true;
5206
            } else if (STREQ(relabel, "no")) {
5207
                seclabels[i]->relabel = false;
5208 5209 5210 5211 5212 5213 5214 5215 5216
            } else {
                virReportError(VIR_ERR_XML_ERROR,
                               _("invalid security relabel value %s"),
                               relabel);
                VIR_FREE(relabel);
                goto error;
            }
            VIR_FREE(relabel);
        } else {
5217
            seclabels[i]->relabel = true;
5218 5219
        }

5220 5221 5222 5223 5224 5225 5226
        /* labelskip is only parsed on live images */
        labelskip = virXMLPropString(list[i], "labelskip");
        seclabels[i]->labelskip = false;
        if (labelskip && !(flags & VIR_DOMAIN_XML_INACTIVE))
            seclabels[i]->labelskip = STREQ(labelskip, "yes");
        VIR_FREE(labelskip);

5227 5228 5229
        ctxt->node = list[i];
        label = virXPathStringLimit("string(./label)",
                                    VIR_SECURITY_LABEL_BUFLEN-1, ctxt);
5230
        seclabels[i]->label = label;
5231

5232
        if (label && !seclabels[i]->relabel) {
5233 5234 5235
            virReportError(VIR_ERR_XML_ERROR,
                           _("Cannot specify a label if relabelling is "
                             "turned off. model=%s"),
5236
                             NULLSTR(seclabels[i]->model));
5237 5238 5239 5240
            goto error;
        }
    }
    VIR_FREE(list);
5241 5242 5243 5244

    *nseclabels_rtn = nseclabels;
    *seclabels_rtn = seclabels;

5245
    return 0;
5246

5247
 error:
5248
    for (i = 0; i < nseclabels; i++)
5249 5250
        virSecurityDeviceLabelDefFree(seclabels[i]);
    VIR_FREE(seclabels);
5251 5252
    VIR_FREE(list);
    return -1;
5253 5254 5255
}


5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267
/* Parse the XML definition for a lease
 */
static virDomainLeaseDefPtr
virDomainLeaseDefParseXML(xmlNodePtr node)
{
    virDomainLeaseDefPtr def;
    xmlNodePtr cur;
    char *lockspace = NULL;
    char *key = NULL;
    char *path = NULL;
    char *offset = NULL;

5268
    if (VIR_ALLOC(def) < 0)
5269 5270 5271 5272 5273
        return NULL;

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
E
Eric Blake 已提交
5274
            if (!key && xmlStrEqual(cur->name, BAD_CAST "key")) {
5275
                key = (char *)xmlNodeGetContent(cur);
E
Eric Blake 已提交
5276 5277
            } else if (!lockspace &&
                       xmlStrEqual(cur->name, BAD_CAST "lockspace")) {
5278
                lockspace = (char *)xmlNodeGetContent(cur);
E
Eric Blake 已提交
5279 5280
            } else if (!path &&
                       xmlStrEqual(cur->name, BAD_CAST "target")) {
5281 5282 5283 5284 5285 5286 5287 5288
                path = virXMLPropString(cur, "path");
                offset = virXMLPropString(cur, "offset");
            }
        }
        cur = cur->next;
    }

    if (!key) {
5289 5290
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Missing 'key' element for lease"));
5291 5292 5293
        goto error;
    }
    if (!path) {
5294 5295
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Missing 'target' element for lease"));
5296 5297 5298 5299 5300
        goto error;
    }

    if (offset &&
        virStrToLong_ull(offset, NULL, 10, &def->offset) < 0) {
5301 5302
        virReportError(VIR_ERR_XML_ERROR,
                       _("Malformed lease target offset %s"), offset);
5303 5304 5305 5306 5307 5308 5309 5310
        goto error;
    }

    def->key = key;
    def->lockspace = lockspace;
    def->path = path;
    path = key = lockspace = NULL;

5311
 cleanup:
5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324
    VIR_FREE(lockspace);
    VIR_FREE(key);
    VIR_FREE(path);
    VIR_FREE(offset);

    return def;

 error:
    virDomainLeaseDefFree(def);
    def = NULL;
    goto cleanup;
}

5325 5326
static int
virDomainDiskSourcePoolDefParse(xmlNodePtr node,
5327
                                virStorageSourcePoolDefPtr *srcpool)
5328
{
5329
    char *mode = NULL;
5330
    virStorageSourcePoolDefPtr source;
5331 5332
    int ret = -1;

5333 5334 5335 5336 5337 5338 5339
    *srcpool = NULL;

    if (VIR_ALLOC(source) < 0)
        return -1;

    source->pool = virXMLPropString(node, "pool");
    source->volume = virXMLPropString(node, "volume");
5340
    mode = virXMLPropString(node, "mode");
5341 5342

    /* CD-ROM and Floppy allows no source */
5343 5344 5345 5346
    if (!source->pool && !source->volume) {
        ret = 0;
        goto cleanup;
    }
5347

5348
    if (!source->pool || !source->volume) {
5349 5350 5351 5352 5353 5354
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("'pool' and 'volume' must be specified together "
                         "for 'pool' type source"));
        goto cleanup;
    }

5355
    if (mode &&
5356
        (source->mode = virStorageSourcePoolModeTypeFromString(mode)) <= 0) {
5357
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5358 5359 5360 5361 5362
                       _("unknown source mode '%s' for volume type disk"),
                       mode);
        goto cleanup;
    }

5363 5364
    *srcpool = source;
    source = NULL;
5365 5366
    ret = 0;

5367
 cleanup:
5368
    virStorageSourcePoolDefFree(source);
5369
    VIR_FREE(mode);
5370 5371 5372
    return ret;
}

5373

5374
int
5375
virDomainDiskSourceParse(xmlNodePtr node,
5376
                         xmlXPathContextPtr ctxt,
5377
                         virStorageSourcePtr src)
5378 5379
{
    int ret = -1;
5380
    char *protocol = NULL;
5381 5382 5383
    xmlNodePtr saveNode = ctxt->node;

    ctxt->node = node;
5384

5385
    switch ((virStorageType)src->type) {
E
Eric Blake 已提交
5386
    case VIR_STORAGE_TYPE_FILE:
5387
        src->path = virXMLPropString(node, "file");
5388
        break;
E
Eric Blake 已提交
5389
    case VIR_STORAGE_TYPE_BLOCK:
5390
        src->path = virXMLPropString(node, "dev");
5391
        break;
E
Eric Blake 已提交
5392
    case VIR_STORAGE_TYPE_DIR:
5393
        src->path = virXMLPropString(node, "dir");
5394
        break;
E
Eric Blake 已提交
5395
    case VIR_STORAGE_TYPE_NETWORK:
5396 5397 5398 5399
        if (!(protocol = virXMLPropString(node, "protocol"))) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing network source protocol type"));
            goto cleanup;
5400
        }
5401

5402
        if ((src->protocol = virStorageNetProtocolTypeFromString(protocol)) <= 0) {
5403
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5404 5405
                           _("unknown protocol type '%s'"), protocol);
            goto cleanup;
5406 5407
        }

5408 5409
        if (!(src->path = virXMLPropString(node, "name")) &&
            src->protocol != VIR_STORAGE_NET_PROTOCOL_NBD) {
5410
            virReportError(VIR_ERR_XML_ERROR, "%s",
5411
                           _("missing name for disk source"));
5412
            goto cleanup;
5413
        }
5414

5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435
        /* for historical reasons the volume name for gluster volume is stored
         * as a part of the path. This is hard to work with when dealing with
         * relative names. Split out the volume into a separate variable */
        if (src->path && src->protocol == VIR_STORAGE_NET_PROTOCOL_GLUSTER) {
            char *tmp;
            if (!(tmp = strchr(src->path, '/')) ||
                tmp == src->path) {
                virReportError(VIR_ERR_XML_ERROR,
                               _("missing volume name or file name in "
                                 "gluster source path '%s'"), src->path);
                goto cleanup;
            }

            src->volume = src->path;

            if (VIR_STRDUP(src->path, tmp) < 0)
                goto cleanup;

            tmp[0] = '\0';
        }

5436 5437 5438
        /* snapshot currently works only for remote disks */
        src->snapshot = virXPathString("string(./snapshot/@name)", ctxt);

5439 5440 5441
        /* config file currently only works with remote disks */
        src->configFile = virXPathString("string(./config/@file)", ctxt);

5442 5443
        if (virDomainStorageHostParse(node, &src->hosts, &src->nhosts) < 0)
            goto cleanup;
5444
        break;
E
Eric Blake 已提交
5445
    case VIR_STORAGE_TYPE_VOLUME:
5446
        if (virDomainDiskSourcePoolDefParse(node, &src->srcpool) < 0)
5447
            goto cleanup;
5448
        break;
5449 5450
    case VIR_STORAGE_TYPE_NONE:
    case VIR_STORAGE_TYPE_LAST:
5451 5452
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected disk type %s"),
5453
                       virStorageTypeToString(src->type));
5454
        goto cleanup;
5455 5456
    }

5457 5458 5459
    /* People sometimes pass a bogus '' source path when they mean to omit the
     * source element completely (e.g. CDROM without media). This is just a
     * little compatibility check to help those broken apps */
5460 5461
    if (src->path && !*src->path)
        VIR_FREE(src->path);
5462 5463 5464

    ret = 0;

5465
 cleanup:
5466
    VIR_FREE(protocol);
5467
    ctxt->node = saveNode;
5468 5469 5470 5471
    return ret;
}


5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497
static int
virDomainDiskBackingStoreParse(xmlXPathContextPtr ctxt,
                               virStorageSourcePtr src)
{
    virStorageSourcePtr backingStore = NULL;
    xmlNodePtr save_ctxt = ctxt->node;
    xmlNodePtr source;
    char *type = NULL;
    char *format = NULL;
    int ret = -1;

    if (!(ctxt->node = virXPathNode("./backingStore[*]", ctxt))) {
        ret = 0;
        goto cleanup;
    }

    if (VIR_ALLOC(backingStore) < 0)
        goto cleanup;

    if (!(type = virXMLPropString(ctxt->node, "type"))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing disk backing store type"));
        goto cleanup;
    }

    backingStore->type = virStorageTypeFromString(type);
5498
    if (backingStore->type <= 0) {
5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("unknown disk backing store type '%s'"), type);
        goto cleanup;
    }

    if (!(format = virXPathString("string(./format/@type)", ctxt))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing disk backing store format"));
        goto cleanup;
    }

    backingStore->format = virStorageFileFormatTypeFromString(format);
5511
    if (backingStore->format <= 0) {
5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("unknown disk backing store format '%s'"), format);
        goto cleanup;
    }

    if (!(source = virXPathNode("./source", ctxt))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing disk backing store source"));
        goto cleanup;
    }

5523
    if (virDomainDiskSourceParse(source, ctxt, backingStore) < 0 ||
5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539
        virDomainDiskBackingStoreParse(ctxt, backingStore) < 0)
        goto cleanup;

    src->backingStore = backingStore;
    ret = 0;

 cleanup:
    if (ret < 0)
        virStorageSourceFree(backingStore);
    VIR_FREE(type);
    VIR_FREE(format);
    ctxt->node = save_ctxt;
    return ret;
}


5540 5541
#define VENDOR_LEN  8
#define PRODUCT_LEN 16
5542

5543 5544 5545 5546
/* Parse the XML definition for a disk
 * @param node XML nodeset to parse for disk definition
 */
static virDomainDiskDefPtr
5547
virDomainDiskDefParseXML(virDomainXMLOptionPtr xmlopt,
5548
                         xmlNodePtr node,
L
Lei Li 已提交
5549
                         xmlXPathContextPtr ctxt,
5550
                         virHashTablePtr bootHash,
5551 5552
                         virSecurityLabelDefPtr* vmSeclabels,
                         int nvmSeclabels,
E
Eric Blake 已提交
5553
                         unsigned int flags)
5554
{
5555
    virDomainDiskDefPtr def;
5556
    xmlNodePtr sourceNode = NULL;
5557
    xmlNodePtr cur;
L
Lei Li 已提交
5558
    xmlNodePtr save_ctxt = ctxt->node;
5559 5560
    char *type = NULL;
    char *device = NULL;
5561
    char *snapshot = NULL;
5562
    char *rawio = NULL;
O
Osier Yang 已提交
5563
    char *sgio = NULL;
5564 5565
    char *driverName = NULL;
    char *driverType = NULL;
5566
    const char *source = NULL;
5567
    char *target = NULL;
J
J.B. Joret 已提交
5568
    char *trans = NULL;
5569
    char *bus = NULL;
5570
    char *cachetag = NULL;
5571
    char *error_policy = NULL;
5572
    char *rerror_policy = NULL;
M
Matthias Dahl 已提交
5573
    char *iotag = NULL;
5574
    char *ioeventfd = NULL;
5575
    char *event_idx = NULL;
O
Osier Yang 已提交
5576
    char *copy_on_read = NULL;
5577
    char *driverIOThread = NULL;
5578
    char *devaddr = NULL;
5579
    virStorageEncryptionPtr encryption = NULL;
5580
    char *serial = NULL;
5581
    char *startupPolicy = NULL;
5582
    virStorageAuthDefPtr authdef = NULL;
5583
    char *tray = NULL;
5584
    char *removable = NULL;
5585 5586
    char *logical_block_size = NULL;
    char *physical_block_size = NULL;
O
Osier Yang 已提交
5587
    char *wwn = NULL;
5588 5589
    char *vendor = NULL;
    char *product = NULL;
O
Osier Yang 已提交
5590
    char *discard = NULL;
E
Eric Blake 已提交
5591 5592
    char *mirrorFormat = NULL;
    char *mirrorType = NULL;
5593 5594
    int expected_secret_usage = -1;
    int auth_secret_usage = -1;
5595
    int ret = 0;
5596

5597
    if (!(def = virDomainDiskDefNew()))
5598 5599
        return NULL;

J
J.B. Joret 已提交
5600 5601 5602 5603 5604
    def->geometry.cylinders = 0;
    def->geometry.heads = 0;
    def->geometry.sectors = 0;
    def->geometry.trans = VIR_DOMAIN_DISK_TRANS_DEFAULT;

V
Viktor Mihajlovski 已提交
5605 5606
    def->blockio.logical_block_size = 0;
    def->blockio.physical_block_size = 0;
5607

L
Lei Li 已提交
5608 5609
    ctxt->node = node;

5610 5611
    type = virXMLPropString(node, "type");
    if (type) {
5612
        if ((def->src->type = virStorageTypeFromString(type)) <= 0) {
5613
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5614
                           _("unknown disk type '%s'"), type);
5615 5616 5617
            goto error;
        }
    } else {
5618
        def->src->type = VIR_STORAGE_TYPE_FILE;
5619 5620
    }

5621 5622
    snapshot = virXMLPropString(node, "snapshot");

5623
    rawio = virXMLPropString(node, "rawio");
O
Osier Yang 已提交
5624
    sgio = virXMLPropString(node, "sgio");
5625

5626 5627 5628
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
5629
            if (!source && !def->src->hosts && !def->src->srcpool &&
E
Eric Blake 已提交
5630
                xmlStrEqual(cur->name, BAD_CAST "source")) {
5631 5632
                sourceNode = cur;

5633
                if (virDomainDiskSourceParse(cur, ctxt, def->src) < 0)
5634
                    goto error;
5635
                source = def->src->path;
5636

5637 5638
                if (def->src->type == VIR_STORAGE_TYPE_NETWORK) {
                    if (def->src->protocol == VIR_STORAGE_NET_PROTOCOL_ISCSI)
5639
                        expected_secret_usage = VIR_SECRET_USAGE_TYPE_ISCSI;
5640
                    else if (def->src->protocol == VIR_STORAGE_NET_PROTOCOL_RBD)
5641
                        expected_secret_usage = VIR_SECRET_USAGE_TYPE_CEPH;
5642
                }
5643

5644 5645
                startupPolicy = virXMLPropString(cur, "startupPolicy");

E
Eric Blake 已提交
5646 5647
            } else if (!target &&
                       xmlStrEqual(cur->name, BAD_CAST "target")) {
5648 5649
                target = virXMLPropString(cur, "dev");
                bus = virXMLPropString(cur, "bus");
5650
                tray = virXMLPropString(cur, "tray");
5651
                removable = virXMLPropString(cur, "removable");
5652 5653 5654 5655 5656 5657

                /* HACK: Work around for compat with Xen
                 * driver in previous libvirt releases */
                if (target &&
                    STRPREFIX(target, "ioemu:"))
                    memmove(target, target+6, strlen(target)-5);
J
J.B. Joret 已提交
5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680
            } else if (xmlStrEqual(cur->name, BAD_CAST "geometry")) {
                if (virXPathUInt("string(./geometry/@cyls)",
                                 ctxt, &def->geometry.cylinders) < 0) {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("invalid geometry settings (cyls)"));
                    goto error;
                }
                if (virXPathUInt("string(./geometry/@heads)",
                                 ctxt, &def->geometry.heads) < 0) {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("invalid geometry settings (heads)"));
                    goto error;
                }
                if (virXPathUInt("string(./geometry/@secs)",
                                 ctxt, &def->geometry.sectors) < 0) {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("invalid geometry settings (secs)"));
                    goto error;
                }
                trans = virXMLPropString(cur, "trans");
                if (trans) {
                    def->geometry.trans = virDomainDiskGeometryTransTypeFromString(trans);
                    if (def->geometry.trans <= 0) {
5681
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
J
J.B. Joret 已提交
5682 5683 5684 5685 5686
                                       _("invalid translation value '%s'"),
                                       trans);
                        goto error;
                    }
                }
V
Viktor Mihajlovski 已提交
5687
            } else if (xmlStrEqual(cur->name, BAD_CAST "blockio")) {
5688 5689 5690 5691
                logical_block_size =
                    virXMLPropString(cur, "logical_block_size");
                if (logical_block_size &&
                    virStrToLong_ui(logical_block_size, NULL, 0,
V
Viktor Mihajlovski 已提交
5692
                                    &def->blockio.logical_block_size) < 0) {
5693 5694 5695 5696 5697 5698 5699 5700 5701
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("invalid logical block size '%s'"),
                                   logical_block_size);
                    goto error;
                }
                physical_block_size =
                    virXMLPropString(cur, "physical_block_size");
                if (physical_block_size &&
                    virStrToLong_ui(physical_block_size, NULL, 0,
V
Viktor Mihajlovski 已提交
5702
                                    &def->blockio.physical_block_size) < 0) {
5703 5704 5705 5706 5707
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("invalid physical block size '%s'"),
                                   physical_block_size);
                    goto error;
                }
E
Eric Blake 已提交
5708 5709
            } else if (!driverName &&
                       xmlStrEqual(cur->name, BAD_CAST "driver")) {
5710 5711
                driverName = virXMLPropString(cur, "name");
                driverType = virXMLPropString(cur, "type");
5712 5713 5714 5715 5716 5717
                if (STREQ_NULLABLE(driverType, "aio")) {
                    /* In-place conversion to "raw", for Xen back-compat */
                    driverType[0] = 'r';
                    driverType[1] = 'a';
                    driverType[2] = 'w';
                }
5718
                cachetag = virXMLPropString(cur, "cache");
5719
                error_policy = virXMLPropString(cur, "error_policy");
5720
                rerror_policy = virXMLPropString(cur, "rerror_policy");
M
Matthias Dahl 已提交
5721
                iotag = virXMLPropString(cur, "io");
5722
                ioeventfd = virXMLPropString(cur, "ioeventfd");
5723
                event_idx = virXMLPropString(cur, "event_idx");
O
Osier Yang 已提交
5724
                copy_on_read = virXMLPropString(cur, "copy_on_read");
O
Osier Yang 已提交
5725
                discard = virXMLPropString(cur, "discard");
5726
                driverIOThread = virXMLPropString(cur, "iothread");
5727 5728
            } else if (!def->mirror &&
                       xmlStrEqual(cur->name, BAD_CAST "mirror") &&
5729 5730
                       !(flags & VIR_DOMAIN_XML_INACTIVE)) {
                char *ready;
E
Eric Blake 已提交
5731
                char *blockJob;
5732 5733 5734

                if (VIR_ALLOC(def->mirror) < 0)
                    goto error;
E
Eric Blake 已提交
5735

E
Eric Blake 已提交
5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750
                blockJob = virXMLPropString(cur, "job");
                if (blockJob) {
                    def->mirrorJob = virDomainBlockJobTypeFromString(blockJob);
                    if (def->mirrorJob <= 0) {
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                       _("unknown mirror job type '%s'"),
                                       blockJob);
                        VIR_FREE(blockJob);
                        goto error;
                    }
                    VIR_FREE(blockJob);
                } else {
                    def->mirrorJob = VIR_DOMAIN_BLOCK_JOB_TYPE_COPY;
                }

E
Eric Blake 已提交
5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772
                mirrorType = virXMLPropString(cur, "type");
                if (mirrorType) {
                    def->mirror->type = virStorageTypeFromString(mirrorType);
                    if (def->mirror->type <= 0) {
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                       _("unknown mirror backing store "
                                         "type '%s'"), mirrorType);
                        goto error;
                    }
                    mirrorFormat = virXPathString("string(./mirror/format/@type)",
                                                  ctxt);
                } else {
                    /* For back-compat reasons, we handle a file name
                     * encoded as attributes, even though we prefer
                     * modern output in the style of backingStore */
                    def->mirror->type = VIR_STORAGE_TYPE_FILE;
                    def->mirror->path = virXMLPropString(cur, "file");
                    if (!def->mirror->path) {
                        virReportError(VIR_ERR_XML_ERROR, "%s",
                                       _("mirror requires file name"));
                        goto error;
                    }
E
Eric Blake 已提交
5773 5774 5775 5776 5777 5778
                    if (def->mirrorJob != VIR_DOMAIN_BLOCK_JOB_TYPE_COPY) {
                        virReportError(VIR_ERR_XML_ERROR, "%s",
                                       _("mirror without type only supported "
                                         "by copy job"));
                        goto error;
                    }
E
Eric Blake 已提交
5779
                    mirrorFormat = virXMLPropString(cur, "format");
5780
                }
5781 5782 5783 5784 5785 5786 5787 5788 5789
                if (mirrorFormat) {
                    def->mirror->format =
                        virStorageFileFormatTypeFromString(mirrorFormat);
                    if (def->mirror->format <= 0) {
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                       _("unknown mirror format value '%s'"),
                                       mirrorFormat);
                        goto error;
                    }
E
Eric Blake 已提交
5790 5791 5792 5793 5794 5795 5796 5797 5798
                }
                if (mirrorType) {
                    xmlNodePtr mirrorNode;

                    if (!(mirrorNode = virXPathNode("./mirror/source", ctxt))) {
                        virReportError(VIR_ERR_XML_ERROR, "%s",
                                       _("mirror requires source element"));
                        goto error;
                    }
5799 5800
                    if (virDomainDiskSourceParse(mirrorNode, ctxt,
                                                 def->mirror) < 0)
E
Eric Blake 已提交
5801
                        goto error;
5802
                }
5803 5804
                ready = virXMLPropString(cur, "ready");
                if (ready) {
5805 5806 5807 5808 5809 5810 5811 5812
                    if ((def->mirrorState =
                         virDomainDiskMirrorStateTypeFromString(ready)) < 0) {
                        virReportError(VIR_ERR_XML_ERROR,
                                       _("unknown mirror ready state %s"),
                                       ready);
                        VIR_FREE(ready);
                        goto error;
                    }
5813 5814
                    VIR_FREE(ready);
                }
5815 5816
            } else if (!authdef &&
                       xmlStrEqual(cur->name, BAD_CAST "auth")) {
5817 5818 5819 5820 5821 5822 5823
                if (!(authdef = virStorageAuthDefParse(node->doc, cur)))
                    goto error;
                if ((auth_secret_usage =
                     virSecretUsageTypeFromString(authdef->secrettype)) < 0) {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("invalid secret type %s"),
                                   authdef->secrettype);
5824 5825
                    goto error;
                }
L
Lei Li 已提交
5826
            } else if (xmlStrEqual(cur->name, BAD_CAST "iotune")) {
5827 5828 5829 5830 5831 5832 5833 5834
                ret = virXPathULongLong("string(./iotune/total_bytes_sec)",
                                        ctxt,
                                        &def->blkdeviotune.total_bytes_sec);
                if (ret == -2) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("total throughput limit must be an integer"));
                    goto error;
                } else if (ret < 0) {
L
Lei Li 已提交
5835 5836 5837
                    def->blkdeviotune.total_bytes_sec = 0;
                }

5838 5839 5840 5841 5842 5843 5844 5845
                ret = virXPathULongLong("string(./iotune/read_bytes_sec)",
                                        ctxt,
                                        &def->blkdeviotune.read_bytes_sec);
                if (ret == -2) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("read throughput limit must be an integer"));
                    goto error;
                } else if (ret < 0) {
L
Lei Li 已提交
5846 5847 5848
                    def->blkdeviotune.read_bytes_sec = 0;
                }

5849 5850 5851 5852 5853 5854 5855 5856
                ret = virXPathULongLong("string(./iotune/write_bytes_sec)",
                                        ctxt,
                                        &def->blkdeviotune.write_bytes_sec);
                if (ret == -2) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("write throughput limit must be an integer"));
                    goto error;
                } else if (ret < 0) {
L
Lei Li 已提交
5857 5858 5859
                    def->blkdeviotune.write_bytes_sec = 0;
                }

5860 5861 5862 5863 5864 5865 5866 5867
                ret = virXPathULongLong("string(./iotune/total_iops_sec)",
                                        ctxt,
                                        &def->blkdeviotune.total_iops_sec);
                if (ret == -2) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("total I/O operations limit must be an integer"));
                    goto error;
                } else if (ret < 0) {
L
Lei Li 已提交
5868 5869 5870
                    def->blkdeviotune.total_iops_sec = 0;
                }

5871 5872 5873 5874 5875 5876 5877 5878
                ret = virXPathULongLong("string(./iotune/read_iops_sec)",
                                        ctxt,
                                        &def->blkdeviotune.read_iops_sec);
                if (ret == -2) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("read I/O operations limit must be an integer"));
                    goto error;
                } else if (ret < 0) {
L
Lei Li 已提交
5879 5880 5881
                    def->blkdeviotune.read_iops_sec = 0;
                }

5882 5883 5884 5885 5886 5887 5888 5889
                ret = virXPathULongLong("string(./iotune/write_iops_sec)",
                                        ctxt,
                                        &def->blkdeviotune.write_iops_sec);
                if (ret == -2) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("write I/O operations limit must be an integer"));
                    goto error;
                } else if (ret < 0) {
L
Lei Li 已提交
5890 5891 5892
                    def->blkdeviotune.write_iops_sec = 0;
                }

5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935
                if (virXPathULongLong("string(./iotune/total_bytes_sec_max)",
                                      ctxt,
                                      &def->blkdeviotune.total_bytes_sec_max) < 0) {
                    def->blkdeviotune.total_bytes_sec_max = 0;
                }

                if (virXPathULongLong("string(./iotune/read_bytes_sec_max)",
                                      ctxt,
                                      &def->blkdeviotune.read_bytes_sec_max) < 0) {
                    def->blkdeviotune.read_bytes_sec_max = 0;
                }

                if (virXPathULongLong("string(./iotune/write_bytes_sec_max)",
                                      ctxt,
                                      &def->blkdeviotune.write_bytes_sec_max) < 0) {
                    def->blkdeviotune.write_bytes_sec_max = 0;
                }

                if (virXPathULongLong("string(./iotune/total_iops_sec_max)",
                                      ctxt,
                                      &def->blkdeviotune.total_iops_sec_max) < 0) {
                    def->blkdeviotune.total_iops_sec_max = 0;
                }

                if (virXPathULongLong("string(./iotune/read_iops_sec_max)",
                                      ctxt,
                                      &def->blkdeviotune.read_iops_sec_max) < 0) {
                    def->blkdeviotune.read_iops_sec_max = 0;
                }

                if (virXPathULongLong("string(./iotune/write_iops_sec_max)",
                                      ctxt,
                                      &def->blkdeviotune.write_iops_sec_max) < 0) {
                    def->blkdeviotune.write_iops_sec_max = 0;
                }

                if (virXPathULongLong("string(./iotune/size_iops_sec)",
                                      ctxt,
                                      &def->blkdeviotune.size_iops_sec) < 0) {
                    def->blkdeviotune.size_iops_sec = 0;
                }


L
Lei Li 已提交
5936 5937 5938 5939
                if ((def->blkdeviotune.total_bytes_sec &&
                     def->blkdeviotune.read_bytes_sec) ||
                    (def->blkdeviotune.total_bytes_sec &&
                     def->blkdeviotune.write_bytes_sec)) {
5940
                    virReportError(VIR_ERR_XML_ERROR, "%s",
5941 5942
                                   _("total and read/write bytes_sec "
                                     "cannot be set at the same time"));
L
Lei Li 已提交
5943 5944 5945 5946 5947 5948 5949
                    goto error;
                }

                if ((def->blkdeviotune.total_iops_sec &&
                     def->blkdeviotune.read_iops_sec) ||
                    (def->blkdeviotune.total_iops_sec &&
                     def->blkdeviotune.write_iops_sec)) {
5950
                    virReportError(VIR_ERR_XML_ERROR, "%s",
5951 5952
                                   _("total and read/write iops_sec "
                                     "cannot be set at the same time"));
L
Lei Li 已提交
5953 5954
                    goto error;
                }
5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975

                if ((def->blkdeviotune.total_bytes_sec_max &&
                     def->blkdeviotune.read_bytes_sec_max) ||
                    (def->blkdeviotune.total_bytes_sec_max &&
                     def->blkdeviotune.write_bytes_sec_max)) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("total and read/write bytes_sec_max "
                                     "cannot be set at the same time"));
                    goto error;
                }

                if ((def->blkdeviotune.total_iops_sec_max &&
                     def->blkdeviotune.read_iops_sec_max) ||
                    (def->blkdeviotune.total_iops_sec_max &&
                     def->blkdeviotune.write_iops_sec_max)) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("total and read/write iops_sec_max "
                                     "cannot be set at the same time"));
                    goto error;
                }

5976
            } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
5977
                def->src->readonly = true;
5978
            } else if (xmlStrEqual(cur->name, BAD_CAST "shareable")) {
5979
                def->src->shared = true;
5980
            } else if (xmlStrEqual(cur->name, BAD_CAST "transient")) {
5981
                def->transient = true;
5982 5983
            } else if ((flags & VIR_DOMAIN_XML_INTERNAL_STATUS) &&
                       xmlStrEqual(cur->name, BAD_CAST "state")) {
5984
                /* Legacy back-compat. Don't add any more attributes here */
5985
                devaddr = virXMLPropString(cur, "devaddr");
5986 5987
            } else if (encryption == NULL &&
                       xmlStrEqual(cur->name, BAD_CAST "encryption")) {
5988
                encryption = virStorageEncryptionParseNode(node->doc,
5989 5990 5991
                                                           cur);
                if (encryption == NULL)
                    goto error;
E
Eric Blake 已提交
5992 5993
            } else if (!serial &&
                       xmlStrEqual(cur->name, BAD_CAST "serial")) {
5994
                serial = (char *)xmlNodeGetContent(cur);
O
Osier Yang 已提交
5995 5996 5997 5998 5999 6000
            } else if (!wwn &&
                       xmlStrEqual(cur->name, BAD_CAST "wwn")) {
                wwn = (char *)xmlNodeGetContent(cur);

                if (!virValidateWWN(wwn))
                    goto error;
6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019
            } else if (!vendor &&
                       xmlStrEqual(cur->name, BAD_CAST "vendor")) {
                vendor = (char *)xmlNodeGetContent(cur);

                if (strlen(vendor) > VENDOR_LEN) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("disk vendor is more than 8 characters"));
                    goto error;
                }

                if (!virStrIsPrint(vendor)) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("disk vendor is not printable string"));
                    goto error;
                }
            } else if (!product &&
                       xmlStrEqual(cur->name, BAD_CAST "product")) {
                product = (char *)xmlNodeGetContent(cur);

A
Alex Jia 已提交
6020
                if (strlen(product) > PRODUCT_LEN) {
6021 6022 6023 6024 6025 6026 6027 6028 6029 6030
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("disk product is more than 16 characters"));
                    goto error;
                }

                if (!virStrIsPrint(product)) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("disk product is not printable string"));
                    goto error;
                }
6031
            } else if (xmlStrEqual(cur->name, BAD_CAST "boot")) {
6032
                /* boot is parsed as part of virDomainDeviceInfoParseXML */
6033 6034 6035 6036 6037
            }
        }
        cur = cur->next;
    }

6038 6039 6040
    if (auth_secret_usage != -1 && auth_secret_usage != expected_secret_usage) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid secret type '%s'"),
6041
                       virSecretUsageTypeToString(auth_secret_usage));
6042 6043 6044
        goto error;
    }

6045 6046 6047
    device = virXMLPropString(node, "device");
    if (device) {
        if ((def->device = virDomainDiskDeviceTypeFromString(device)) < 0) {
6048
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6049
                           _("unknown disk device '%s'"), device);
6050 6051 6052 6053 6054 6055 6056
            goto error;
        }
    } else {
        def->device = VIR_DOMAIN_DISK_DEVICE_DISK;
    }

    /* Only CDROM and Floppy devices are allowed missing source path
6057 6058
     * to indicate no media present. LUN is for raw access CD-ROMs
     * that are not attached to a physical device presently */
6059
    if (source == NULL && def->src->hosts == NULL && !def->src->srcpool &&
6060 6061
        (def->device == VIR_DOMAIN_DISK_DEVICE_DISK ||
         (flags & VIR_DOMAIN_XML_INTERNAL_DISK_SOURCE))) {
6062 6063
        virReportError(VIR_ERR_NO_SOURCE,
                       target ? "%s" : NULL, target);
6064 6065 6066
        goto error;
    }

6067 6068 6069 6070
    /* If source is present, check for an optional seclabel override.  */
    if (sourceNode) {
        xmlNodePtr saved_node = ctxt->node;
        ctxt->node = sourceNode;
6071 6072
        if (virSecurityDeviceLabelDefParseXML(&def->src->seclabels,
                                              &def->src->nseclabels,
6073
                                              vmSeclabels,
6074
                                              nvmSeclabels,
6075 6076
                                              ctxt,
                                              flags) < 0)
6077 6078 6079 6080
            goto error;
        ctxt->node = saved_node;
    }

6081
    if (!target && !(flags & VIR_DOMAIN_XML_INTERNAL_DISK_SOURCE)) {
6082
        if (def->src->srcpool) {
6083 6084
            char *tmp;
            if (virAsprintf(&tmp, "pool = '%s', volume = '%s'",
6085
                def->src->srcpool->pool, def->src->srcpool->volume) < 0)
6086 6087 6088 6089 6090 6091 6092
                goto error;

            virReportError(VIR_ERR_NO_TARGET, "%s", tmp);
            VIR_FREE(tmp);
        } else {
            virReportError(VIR_ERR_NO_TARGET, source ? "%s" : NULL, source);
        }
6093 6094 6095
        goto error;
    }

6096 6097 6098 6099 6100 6101 6102
    if (!(flags & VIR_DOMAIN_XML_INTERNAL_DISK_SOURCE)) {
        if (def->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
            !STRPREFIX(target, "fd")) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid floppy device name: %s"), target);
            goto error;
        }
6103

6104 6105 6106
        /* Force CDROM to be listed as read only */
        if (def->device == VIR_DOMAIN_DISK_DEVICE_CDROM)
            def->src->readonly = true;
6107

6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118
        if ((def->device == VIR_DOMAIN_DISK_DEVICE_DISK ||
             def->device == VIR_DOMAIN_DISK_DEVICE_LUN) &&
            !STRPREFIX((const char *)target, "hd") &&
            !STRPREFIX((const char *)target, "sd") &&
            !STRPREFIX((const char *)target, "vd") &&
            !STRPREFIX((const char *)target, "xvd") &&
            !STRPREFIX((const char *)target, "ubd")) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid harddisk device name: %s"), target);
            goto error;
        }
6119 6120
    }

6121
    if (snapshot) {
E
Eric Blake 已提交
6122
        def->snapshot = virDomainSnapshotLocationTypeFromString(snapshot);
6123
        if (def->snapshot <= 0) {
6124
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6125 6126
                           _("unknown disk snapshot setting '%s'"),
                           snapshot);
6127 6128
            goto error;
        }
6129
    } else if (def->src->readonly) {
E
Eric Blake 已提交
6130
        def->snapshot = VIR_DOMAIN_SNAPSHOT_LOCATION_NONE;
6131 6132
    }

O
Osier Yang 已提交
6133 6134 6135 6136 6137 6138 6139 6140
    if ((rawio || sgio) &&
        (def->device != VIR_DOMAIN_DISK_DEVICE_LUN)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("rawio or sgio can be used only with "
                         "device='lun'"));
        goto error;
    }

6141
    if (rawio) {
6142
        if ((def->rawio = virTristateBoolTypeFromString(rawio)) <= 0) {
O
Osier Yang 已提交
6143 6144 6145 6146 6147 6148 6149 6150
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown disk rawio setting '%s'"),
                           rawio);
            goto error;
        }
    }

    if (sgio) {
6151
        if ((def->sgio = virDomainDeviceSGIOTypeFromString(sgio)) <= 0) {
6152
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
O
Osier Yang 已提交
6153
                           _("unknown disk sgio mode '%s'"), sgio);
6154 6155 6156 6157
            goto error;
        }
    }

6158 6159
    if (bus) {
        if ((def->bus = virDomainDiskBusTypeFromString(bus)) < 0) {
6160
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6161
                           _("unknown disk bus type '%s'"), bus);
6162 6163 6164 6165 6166
            goto error;
        }
    } else {
        if (def->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
            def->bus = VIR_DOMAIN_DISK_BUS_FDC;
6167
        } else if (!(flags & VIR_DOMAIN_XML_INTERNAL_DISK_SOURCE)) {
6168 6169 6170 6171 6172 6173 6174 6175
            if (STRPREFIX(target, "hd"))
                def->bus = VIR_DOMAIN_DISK_BUS_IDE;
            else if (STRPREFIX(target, "sd"))
                def->bus = VIR_DOMAIN_DISK_BUS_SCSI;
            else if (STRPREFIX(target, "vd"))
                def->bus = VIR_DOMAIN_DISK_BUS_VIRTIO;
            else if (STRPREFIX(target, "xvd"))
                def->bus = VIR_DOMAIN_DISK_BUS_XEN;
6176 6177
            else if (STRPREFIX(target, "ubd"))
                def->bus = VIR_DOMAIN_DISK_BUS_UML;
6178 6179 6180 6181 6182
            else
                def->bus = VIR_DOMAIN_DISK_BUS_IDE;
        }
    }

6183 6184
    if (tray) {
        if ((def->tray_status = virDomainDiskTrayTypeFromString(tray)) < 0) {
6185
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6186
                           _("unknown disk tray status '%s'"), tray);
6187 6188 6189 6190 6191
            goto error;
        }

        if (def->device != VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
            def->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
6192 6193
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("tray is only valid for cdrom and floppy"));
6194 6195 6196 6197 6198 6199 6200 6201
            goto error;
        }
    } else {
        if (def->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY ||
            def->device == VIR_DOMAIN_DISK_DEVICE_CDROM)
            def->tray_status = VIR_DOMAIN_DISK_TRAY_CLOSED;
    }

6202
    if (removable) {
J
Ján Tomko 已提交
6203
        if ((def->removable = virTristateSwitchTypeFromString(removable)) < 0) {
6204
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6205 6206 6207 6208 6209 6210 6211 6212 6213 6214
                           _("unknown disk removable status '%s'"), removable);
            goto error;
        }

        if (def->bus != VIR_DOMAIN_DISK_BUS_USB) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("removable is only valid for usb disks"));
            goto error;
        }
    } else {
6215
        if (def->bus == VIR_DOMAIN_DISK_BUS_USB)
J
Ján Tomko 已提交
6216
            def->removable = VIR_TRISTATE_SWITCH_ABSENT;
6217 6218
    }

6219 6220
    if (def->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
        def->bus != VIR_DOMAIN_DISK_BUS_FDC) {
6221 6222
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid bus type '%s' for floppy disk"), bus);
6223 6224 6225 6226
        goto error;
    }
    if (def->device != VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
        def->bus == VIR_DOMAIN_DISK_BUS_FDC) {
6227 6228
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid bus type '%s' for disk"), bus);
6229 6230 6231
        goto error;
    }

6232 6233
    if (cachetag &&
        (def->cachemode = virDomainDiskCacheTypeFromString(cachetag)) < 0) {
6234
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6235
                       _("unknown disk cache mode '%s'"), cachetag);
6236 6237 6238
        goto error;
    }

6239
    if (error_policy &&
6240
        (def->error_policy = virDomainDiskErrorPolicyTypeFromString(error_policy)) <= 0) {
6241
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6242
                       _("unknown disk error policy '%s'"), error_policy);
6243 6244 6245
        goto error;
    }

6246 6247 6248 6249
    if (rerror_policy &&
        (((def->rerror_policy
           = virDomainDiskErrorPolicyTypeFromString(rerror_policy)) <= 0) ||
         (def->rerror_policy == VIR_DOMAIN_DISK_ERROR_POLICY_ENOSPACE))) {
6250
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6251 6252
                       _("unknown disk read error policy '%s'"),
                       rerror_policy);
6253 6254 6255
        goto error;
    }

M
Matthias Dahl 已提交
6256 6257 6258
    if (iotag) {
        if ((def->iomode = virDomainDiskIoTypeFromString(iotag)) < 0 ||
            def->iomode == VIR_DOMAIN_DISK_IO_DEFAULT) {
6259
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6260
                           _("unknown disk io mode '%s'"), iotag);
M
Matthias Dahl 已提交
6261 6262 6263 6264
            goto error;
        }
    }

6265
    if (ioeventfd) {
6266 6267
        int val;

6268
        if (def->bus != VIR_DOMAIN_DISK_BUS_VIRTIO) {
6269
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6270 6271
                           _("disk ioeventfd mode supported "
                             "only for virtio bus"));
6272 6273 6274
            goto error;
        }

J
Ján Tomko 已提交
6275
        if ((val = virTristateSwitchTypeFromString(ioeventfd)) <= 0) {
6276 6277 6278
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown disk ioeventfd mode '%s'"),
                           ioeventfd);
6279 6280
            goto error;
        }
6281
        def->ioeventfd = val;
6282 6283
    }

6284 6285
    if (event_idx) {
        if (def->bus != VIR_DOMAIN_DISK_BUS_VIRTIO) {
6286
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6287 6288
                           _("disk event_idx mode supported "
                             "only for virtio bus"));
6289 6290 6291 6292
            goto error;
        }

        int idx;
J
Ján Tomko 已提交
6293
        if ((idx = virTristateSwitchTypeFromString(event_idx)) <= 0) {
6294 6295 6296
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown disk event_idx mode '%s'"),
                           event_idx);
6297 6298 6299 6300 6301
            goto error;
        }
        def->event_idx = idx;
    }

O
Osier Yang 已提交
6302 6303
    if (copy_on_read) {
        int cor;
J
Ján Tomko 已提交
6304
        if ((cor = virTristateSwitchTypeFromString(copy_on_read)) <= 0) {
6305 6306 6307
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown disk copy_on_read mode '%s'"),
                           copy_on_read);
O
Osier Yang 已提交
6308 6309 6310 6311 6312
            goto error;
        }
        def->copy_on_read = cor;
    }

O
Osier Yang 已提交
6313 6314 6315 6316 6317 6318 6319 6320
    if (discard) {
        if ((def->discard = virDomainDiskDiscardTypeFromString(discard)) <= 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown disk discard mode '%s'"), discard);
            goto error;
        }
    }

6321 6322 6323 6324 6325 6326 6327 6328 6329
    if (driverIOThread) {
        if (virStrToLong_uip(driverIOThread, NULL, 10, &def->iothread) < 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid iothread attribute in disk driver "
                             "element: %s"), driverIOThread);
            goto error;
        }
    }

6330
    if (devaddr) {
6331 6332
        if (virDomainParseLegacyDeviceAddress(devaddr,
                                              &def->info.addr.pci) < 0) {
6333 6334 6335
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to parse devaddr parameter '%s'"),
                           devaddr);
6336 6337 6338 6339
            goto error;
        }
        def->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
    } else {
6340
        if (virDomainDeviceInfoParseXML(node, bootHash, &def->info,
6341
                                        flags | VIR_DOMAIN_XML_INTERNAL_ALLOW_BOOT) < 0)
6342
            goto error;
6343 6344
    }

6345
    if (startupPolicy) {
6346
        int val;
6347

6348
        if ((val = virDomainStartupPolicyTypeFromString(startupPolicy)) <= 0) {
6349 6350 6351
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown startupPolicy value '%s'"),
                           startupPolicy);
6352 6353 6354
            goto error;
        }

6355
        if (def->src->type == VIR_STORAGE_TYPE_NETWORK) {
6356 6357 6358
            virReportError(VIR_ERR_XML_ERROR,
                           _("Setting disk %s is not allowed for "
                             "disk of network type"),
6359
                           startupPolicy);
6360 6361
            goto error;
        }
6362 6363 6364 6365 6366 6367 6368 6369 6370

        if (def->device != VIR_DOMAIN_DISK_DEVICE_CDROM &&
            def->device != VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
            val == VIR_DOMAIN_STARTUP_POLICY_REQUISITE) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("Setting disk 'requisite' is allowed only for "
                             "cdrom or floppy"));
            goto error;
        }
6371
        def->startupPolicy = val;
6372 6373
    }

6374 6375
    def->dst = target;
    target = NULL;
6376 6377
    def->src->auth = authdef;
    authdef = NULL;
6378
    def->src->driverName = driverName;
6379
    driverName = NULL;
6380
    def->src->encryption = encryption;
6381
    encryption = NULL;
6382 6383
    def->serial = serial;
    serial = NULL;
O
Osier Yang 已提交
6384 6385
    def->wwn = wwn;
    wwn = NULL;
6386 6387 6388 6389
    def->vendor = vendor;
    vendor = NULL;
    def->product = product;
    product = NULL;
6390

6391
    if (driverType) {
6392 6393
        def->src->format = virStorageFileFormatTypeFromString(driverType);
        if (def->src->format <= 0) {
6394 6395 6396 6397 6398 6399
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown driver format value '%s'"),
                           driverType);
            goto error;
        }
    }
6400

6401 6402 6403 6404
    if (!(flags & VIR_DOMAIN_XML_INTERNAL_DISK_SOURCE)) {
        if (def->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE
            && virDomainDiskDefAssignAddress(xmlopt, def) < 0)
            goto error;
6405

6406 6407 6408
        if (virDomainDiskBackingStoreParse(ctxt, def->src) < 0)
            goto error;
    }
6409

6410
 cleanup:
6411 6412
    VIR_FREE(bus);
    VIR_FREE(type);
6413
    VIR_FREE(snapshot);
6414
    VIR_FREE(rawio);
O
Osier Yang 已提交
6415
    VIR_FREE(sgio);
6416
    VIR_FREE(target);
6417
    VIR_FREE(tray);
6418
    VIR_FREE(removable);
J
J.B. Joret 已提交
6419
    VIR_FREE(trans);
6420
    VIR_FREE(device);
6421
    virStorageAuthDefFree(authdef);
6422 6423
    VIR_FREE(driverType);
    VIR_FREE(driverName);
6424
    VIR_FREE(cachetag);
6425
    VIR_FREE(error_policy);
6426
    VIR_FREE(rerror_policy);
M
Matthias Dahl 已提交
6427
    VIR_FREE(iotag);
6428
    VIR_FREE(ioeventfd);
6429
    VIR_FREE(event_idx);
O
Osier Yang 已提交
6430
    VIR_FREE(copy_on_read);
O
Osier Yang 已提交
6431
    VIR_FREE(discard);
6432
    VIR_FREE(driverIOThread);
6433
    VIR_FREE(devaddr);
6434
    VIR_FREE(serial);
6435
    virStorageEncryptionFree(encryption);
6436
    VIR_FREE(startupPolicy);
6437 6438
    VIR_FREE(logical_block_size);
    VIR_FREE(physical_block_size);
O
Osier Yang 已提交
6439
    VIR_FREE(wwn);
6440 6441
    VIR_FREE(vendor);
    VIR_FREE(product);
E
Eric Blake 已提交
6442 6443
    VIR_FREE(mirrorType);
    VIR_FREE(mirrorFormat);
6444

L
Lei Li 已提交
6445
    ctxt->node = save_ctxt;
6446 6447
    return def;

6448
 error:
6449 6450 6451 6452 6453
    virDomainDiskDefFree(def);
    def = NULL;
    goto cleanup;
}

6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475
/**
 * virDomainParseScaledValue:
 * @xpath: XPath to memory amount
 * @units_xpath: XPath to units attribute
 * @ctxt: XPath context
 * @val: scaled value is stored here
 * @scale: default scale for @val
 * @max: maximal @val allowed
 * @required: is the value required?
 *
 * Parse a value located at @xpath within @ctxt, and store the
 * result into @val. The value is scaled by units located at
 * @units_xpath (or the 'unit' attribute under @xpath if
 * @units_xpath is NULL). If units are not present, the default
 * @scale is used. If @required is set, then the value must
 * exist; otherwise, the value is optional. The resulting value
 * is in bytes.
 *
 * Returns 1 on success,
 *         0 if the value was not present and !@required,
 *         -1 on failure after issuing error.
 */
6476 6477
static int
virDomainParseScaledValue(const char *xpath,
6478
                          const char *units_xpath,
6479 6480 6481 6482 6483 6484 6485 6486
                          xmlXPathContextPtr ctxt,
                          unsigned long long *val,
                          unsigned long long scale,
                          unsigned long long max,
                          bool required)
{
    char *xpath_full = NULL;
    char *unit = NULL;
6487
    char *bytes_str = NULL;
6488 6489 6490 6491 6492 6493
    int ret = -1;
    unsigned long long bytes;

    *val = 0;
    if (virAsprintf(&xpath_full, "string(%s)", xpath) < 0)
        goto cleanup;
6494 6495 6496 6497 6498 6499

    bytes_str = virXPathString(xpath_full, ctxt);
    if (!bytes_str) {
        if (!required) {
            ret = 0;
        } else {
6500
            virReportError(VIR_ERR_XML_ERROR,
6501
                           _("missing element or attribute '%s'"),
6502
                           xpath);
6503
        }
6504 6505 6506 6507
        goto cleanup;
    }
    VIR_FREE(xpath_full);

6508 6509
    if (virStrToLong_ullp(bytes_str, NULL, 10, &bytes) < 0) {
        virReportError(VIR_ERR_XML_ERROR,
6510
                       _("Invalid value '%s' for element or attribute '%s'"),
6511 6512 6513 6514
                       bytes_str, xpath);
        goto cleanup;
    }

6515 6516 6517 6518
    if ((units_xpath &&
         virAsprintf(&xpath_full, "string(%s)", units_xpath) < 0) ||
        (!units_xpath &&
         virAsprintf(&xpath_full, "string(%s/@unit)", xpath) < 0))
6519 6520 6521 6522 6523 6524 6525 6526
        goto cleanup;
    unit = virXPathString(xpath_full, ctxt);

    if (virScaleInteger(&bytes, unit, scale, max) < 0)
        goto cleanup;

    *val = bytes;
    ret = 1;
6527
 cleanup:
6528
    VIR_FREE(bytes_str);
6529 6530 6531 6532 6533 6534
    VIR_FREE(xpath_full);
    VIR_FREE(unit);
    return ret;
}


6535 6536 6537 6538 6539 6540 6541 6542
/**
 * virDomainParseMemory:
 * @xpath: XPath to memory amount
 * @units_xpath: XPath to units attribute
 * @ctxt: XPath context
 * @mem: scaled memory amount is stored here
 * @required: whether value is required
 * @capped: whether scaled value must fit within unsigned long
6543
 *
6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556
 * Parse a memory element or attribute located at @xpath within
 * @ctxt, and store the result into @mem, in blocks of 1024. The
 * value is scaled by units located at @units_xpath (or the
 * 'unit' attribute under @xpath if @units_xpath is NULL). If
 * units are not present, he default scale of 1024 is used. If
 * @required is set, then the value must exist; otherwise, the
 * value is optional.  The value must not exceed
 * VIR_DOMAIN_MEMORY_PARAM_UNLIMITED once scaled; additionally,
 * if @capped is true, the value must fit within an unsigned long
 * (only matters on 32-bit platforms).
 *
 * Return 0 on success, -1 on failure after issuing error.
 */
6557
int
6558 6559 6560 6561 6562 6563
virDomainParseMemory(const char *xpath,
                     const char *units_xpath,
                     xmlXPathContextPtr ctxt,
                     unsigned long long *mem,
                     bool required,
                     bool capped)
6564 6565 6566 6567 6568 6569
{
    int ret = -1;
    unsigned long long bytes, max;

    /* On 32-bit machines, our bound is 0xffffffff * KiB. On 64-bit
     * machines, our bound is off_t (2^63).  */
6570
    if (capped && sizeof(unsigned long) < sizeof(long long))
6571 6572 6573 6574
        max = 1024ull * ULONG_MAX;
    else
        max = LLONG_MAX;

6575 6576
    ret = virDomainParseScaledValue(xpath, units_xpath, ctxt,
                                    &bytes, 1024, max, required);
6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587
    if (ret < 0)
        goto cleanup;

    /* Yes, we really do use kibibytes for our internal sizing.  */
    *mem = VIR_DIV_UP(bytes, 1024);
    ret = 0;
 cleanup:
    return ret;
}


6588
static int
6589
virDomainControllerModelTypeFromString(const virDomainControllerDef *def,
6590 6591 6592 6593
                                       const char *model)
{
    if (def->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI)
        return virDomainControllerModelSCSITypeFromString(model);
6594 6595
    else if (def->type == VIR_DOMAIN_CONTROLLER_TYPE_USB)
        return virDomainControllerModelUSBTypeFromString(model);
J
Ján Tomko 已提交
6596 6597
    else if (def->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI)
        return virDomainControllerModelPCITypeFromString(model);
6598 6599 6600 6601

    return -1;
}

6602 6603 6604 6605
/* Parse the XML definition for a controller
 * @param node XML nodeset to parse for controller definition
 */
static virDomainControllerDefPtr
6606
virDomainControllerDefParseXML(xmlNodePtr node,
6607
                               xmlXPathContextPtr ctxt,
E
Eric Blake 已提交
6608
                               unsigned int flags)
6609 6610
{
    virDomainControllerDefPtr def;
6611
    xmlNodePtr cur = NULL;
6612 6613
    char *type = NULL;
    char *idx = NULL;
6614
    char *model = NULL;
6615
    char *queues = NULL;
6616 6617
    char *cmd_per_lun = NULL;
    char *max_sectors = NULL;
6618
    xmlNodePtr saved = ctxt->node;
6619
    int rc;
6620 6621

    ctxt->node = node;
6622

6623
    if (VIR_ALLOC(def) < 0)
6624 6625 6626 6627
        return NULL;

    type = virXMLPropString(node, "type");
    if (type) {
6628
        if ((def->type = virDomainControllerTypeFromString(type)) < 0) {
6629
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6630
                           _("Unknown controller type '%s'"), type);
6631 6632 6633 6634 6635 6636
            goto error;
        }
    }

    idx = virXMLPropString(node, "index");
    if (idx) {
6637 6638
        if (virStrToLong_ui(idx, NULL, 10, &def->idx) < 0 ||
            def->idx > INT_MAX) {
6639 6640
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Cannot parse controller index %s"), idx);
6641 6642 6643 6644
            goto error;
        }
    }

6645 6646
    model = virXMLPropString(node, "model");
    if (model) {
6647
        if ((def->model = virDomainControllerModelTypeFromString(def, model)) < 0) {
6648
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6649
                           _("Unknown model type '%s'"), model);
6650 6651 6652 6653 6654 6655
            goto error;
        }
    } else {
        def->model = -1;
    }

6656 6657 6658
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
6659
            if (xmlStrEqual(cur->name, BAD_CAST "driver")) {
6660
                queues = virXMLPropString(cur, "queues");
6661 6662
                cmd_per_lun = virXMLPropString(cur, "cmd_per_lun");
                max_sectors = virXMLPropString(cur, "max_sectors");
6663
            }
6664
        }
6665 6666 6667 6668 6669 6670 6671
        cur = cur->next;
    }

    if (queues && virStrToLong_ui(queues, NULL, 10, &def->queues) < 0) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("Malformed 'queues' value '%s'"), queues);
        goto error;
6672 6673
    }

6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684
    if (cmd_per_lun && virStrToLong_ui(cmd_per_lun, NULL, 10, &def->cmd_per_lun) < 0) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("Malformed 'cmd_per_lun' value '%s'"), cmd_per_lun);
        goto error;
    }

    if (max_sectors && virStrToLong_ui(max_sectors, NULL, 10, &def->max_sectors) < 0) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("Malformed 'max_sectors' value %s'"), max_sectors);
    }

6685
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
6686 6687
        goto error;

6688 6689 6690 6691 6692 6693 6694
    switch (def->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL: {
        char *ports = virXMLPropString(node, "ports");
        if (ports) {
            int r = virStrToLong_i(ports, NULL, 10,
                                   &def->opts.vioserial.ports);
            if (r != 0 || def->opts.vioserial.ports < 0) {
6695 6696
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid ports: %s"), ports);
6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709
                VIR_FREE(ports);
                goto error;
            }
        } else {
            def->opts.vioserial.ports = -1;
        }
        VIR_FREE(ports);

        char *vectors = virXMLPropString(node, "vectors");
        if (vectors) {
            int r = virStrToLong_i(vectors, NULL, 10,
                                   &def->opts.vioserial.vectors);
            if (r != 0 || def->opts.vioserial.vectors < 0) {
6710 6711
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid vectors: %s"), vectors);
6712 6713 6714 6715 6716 6717 6718 6719 6720
                VIR_FREE(vectors);
                goto error;
            }
        } else {
            def->opts.vioserial.vectors = -1;
        }
        VIR_FREE(vectors);
        break;
    }
6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742
    case VIR_DOMAIN_CONTROLLER_TYPE_USB: {
        /* If the XML has a uhci1, uhci2, uhci3 controller and no
         * master port was given, we should set a sensible one */
        int masterPort = -1;
        switch (def->model) {
        case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI1:
            masterPort = 0;
            break;
        case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI2:
            masterPort = 2;
            break;
        case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI3:
            masterPort = 4;
            break;
        }
        if (masterPort != -1 &&
            def->info.mastertype == VIR_DOMAIN_CONTROLLER_MASTER_NONE) {
            def->info.mastertype = VIR_DOMAIN_CONTROLLER_MASTER_USB;
            def->info.master.usb.startport = masterPort;
        }
        break;
    }
J
Ján Tomko 已提交
6743 6744 6745
    case VIR_DOMAIN_CONTROLLER_TYPE_PCI:
        switch (def->model) {
        case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
6746 6747
        case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT: {
            unsigned long long bytes;
J
Ján Tomko 已提交
6748 6749
            if (def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
L
Laine Stump 已提交
6750
                               _("pci-root and pcie-root controllers should not "
J
Ján Tomko 已提交
6751 6752 6753
                                 "have an address"));
                goto error;
            }
6754 6755
            if (def->idx != 0) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
L
Laine Stump 已提交
6756 6757
                               _("pci-root and pcie-root controllers "
                                 "should have index 0"));
6758 6759
                goto error;
            }
6760 6761
            if ((rc = virDomainParseScaledValue("./pcihole64", NULL,
                                                ctxt, &bytes, 1024,
6762 6763
                                                1024ULL * ULONG_MAX, false)) < 0)
                goto error;
6764

6765 6766 6767 6768
            if (rc == 1)
                def->opts.pciopts.pcihole64 = true;
            def->opts.pciopts.pcihole64size = VIR_DIV_UP(bytes, 1024);
        }
J
Ján Tomko 已提交
6769
        }
6770 6771 6772 6773 6774

    default:
        break;
    }

6775
    if (def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
6776
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO &&
6777
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW &&
6778
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390 &&
6779
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO &&
6780
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
6781 6782
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Controllers must use the 'pci' address type"));
6783 6784 6785
        goto error;
    }

6786
 cleanup:
6787
    ctxt->node = saved;
6788 6789
    VIR_FREE(type);
    VIR_FREE(idx);
6790
    VIR_FREE(model);
6791
    VIR_FREE(queues);
6792 6793
    VIR_FREE(cmd_per_lun);
    VIR_FREE(max_sectors);
6794 6795 6796 6797 6798 6799 6800 6801 6802

    return def;

 error:
    virDomainControllerDefFree(def);
    def = NULL;
    goto cleanup;
}

6803

6804 6805 6806 6807 6808 6809 6810 6811
void
virDomainNetGenerateMAC(virDomainXMLOptionPtr xmlopt,
                        virMacAddrPtr mac)
{
    virMacAddrGenerate(xmlopt->config.macPrefix, mac);
}


6812 6813 6814 6815
/* Parse the XML definition for a disk
 * @param node XML nodeset to parse for disk definition
 */
static virDomainFSDefPtr
6816
virDomainFSDefParseXML(xmlNodePtr node,
6817
                       xmlXPathContextPtr ctxt,
6818 6819
                       unsigned int flags)
{
6820
    virDomainFSDefPtr def;
6821
    xmlNodePtr cur, save_node = ctxt->node;
6822
    char *type = NULL;
6823
    char *fsdriver = NULL;
6824 6825
    char *source = NULL;
    char *target = NULL;
6826
    char *format = NULL;
6827
    char *accessmode = NULL;
6828
    char *wrpolicy = NULL;
6829
    char *usage = NULL;
6830
    char *units = NULL;
6831

6832 6833
    ctxt->node = node;

6834
    if (VIR_ALLOC(def) < 0)
6835 6836 6837 6838 6839
        return NULL;

    type = virXMLPropString(node, "type");
    if (type) {
        if ((def->type = virDomainFSTypeFromString(type)) < 0) {
6840
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6841
                           _("unknown filesystem type '%s'"), type);
6842 6843 6844 6845 6846 6847
            goto error;
        }
    } else {
        def->type = VIR_DOMAIN_FS_TYPE_MOUNT;
    }

6848 6849 6850
    accessmode = virXMLPropString(node, "accessmode");
    if (accessmode) {
        if ((def->accessmode = virDomainFSAccessModeTypeFromString(accessmode)) < 0) {
6851
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6852
                           _("unknown accessmode '%s'"), accessmode);
6853 6854 6855 6856 6857 6858
            goto error;
        }
    } else {
        def->accessmode = VIR_DOMAIN_FS_ACCESSMODE_PASSTHROUGH;
    }

6859 6860 6861
    if (virDomainParseScaledValue("./space_hard_limit[1]",
                                  NULL, ctxt, &def->space_hard_limit,
                                  1, ULLONG_MAX, false) < 0)
6862 6863
        goto error;

6864 6865 6866
    if (virDomainParseScaledValue("./space_soft_limit[1]",
                                  NULL, ctxt, &def->space_soft_limit,
                                  1, ULLONG_MAX, false) < 0)
6867 6868
        goto error;

6869 6870 6871
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
E
Eric Blake 已提交
6872 6873
            if (!source &&
                xmlStrEqual(cur->name, BAD_CAST "source")) {
6874

6875
                if (def->type == VIR_DOMAIN_FS_TYPE_MOUNT ||
6876
                    def->type == VIR_DOMAIN_FS_TYPE_BIND) {
6877
                    source = virXMLPropString(cur, "dir");
6878
                } else if (def->type == VIR_DOMAIN_FS_TYPE_FILE) {
6879
                    source = virXMLPropString(cur, "file");
6880
                } else if (def->type == VIR_DOMAIN_FS_TYPE_BLOCK) {
6881
                    source = virXMLPropString(cur, "dev");
6882
                } else if (def->type == VIR_DOMAIN_FS_TYPE_TEMPLATE) {
6883
                    source = virXMLPropString(cur, "name");
6884
                } else if (def->type == VIR_DOMAIN_FS_TYPE_RAM) {
6885
                    usage = virXMLPropString(cur, "usage");
6886
                    units = virXMLPropString(cur, "units");
6887
                }
E
Eric Blake 已提交
6888 6889
            } else if (!target &&
                       xmlStrEqual(cur->name, BAD_CAST "target")) {
6890 6891
                target = virXMLPropString(cur, "dir");
            } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
6892
                def->readonly = true;
6893 6894 6895 6896 6897 6898 6899
            } else if (xmlStrEqual(cur->name, BAD_CAST "driver")) {
                if (!fsdriver)
                    fsdriver = virXMLPropString(cur, "type");
                if (!wrpolicy)
                    wrpolicy = virXMLPropString(cur, "wrpolicy");
                if (!format)
                    format = virXMLPropString(cur, "format");
6900 6901 6902 6903 6904
            }
        }
        cur = cur->next;
    }

6905
    if (fsdriver) {
6906
        if ((def->fsdriver = virDomainFSDriverTypeFromString(fsdriver)) <= 0) {
6907
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6908
                           _("unknown fs driver type '%s'"), fsdriver);
6909 6910 6911 6912
            goto error;
        }
    }

6913 6914 6915 6916 6917 6918 6919 6920
    if (format) {
        if ((def->format = virStorageFileFormatTypeFromString(format)) <= 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown driver format value '%s'"), format);
            goto error;
        }
    }

6921 6922
    if (wrpolicy) {
        if ((def->wrpolicy = virDomainFSWrpolicyTypeFromString(wrpolicy)) <= 0) {
6923 6924
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown filesystem write policy '%s'"), wrpolicy);
6925 6926 6927 6928 6929 6930
            goto error;
        }
    } else {
        def->wrpolicy = VIR_DOMAIN_FS_WRPOLICY_DEFAULT;
    }

6931 6932
    if (source == NULL &&
        def->type != VIR_DOMAIN_FS_TYPE_RAM) {
6933 6934
        virReportError(VIR_ERR_NO_SOURCE,
                       target ? "%s" : NULL, target);
6935 6936 6937 6938
        goto error;
    }

    if (target == NULL) {
6939 6940
        virReportError(VIR_ERR_NO_TARGET,
                       source ? "%s" : NULL, source);
6941 6942 6943
        goto error;
    }

6944 6945
    if (def->type == VIR_DOMAIN_FS_TYPE_RAM) {
        if (!usage) {
6946 6947
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing 'usage' attribute for RAM filesystem"));
6948 6949 6950
            goto error;
        }
        if (virStrToLong_ull(usage, NULL, 10, &def->usage) < 0) {
6951 6952 6953
            virReportError(VIR_ERR_XML_ERROR,
                           _("cannot parse usage '%s' for RAM filesystem"),
                           usage);
6954 6955
            goto error;
        }
6956
        if (virScaleInteger(&def->usage, units,
6957
                            1024, ULLONG_MAX) < 0)
6958 6959 6960
            goto error;
    }

6961 6962 6963 6964 6965
    def->src = source;
    source = NULL;
    def->dst = target;
    target = NULL;

6966
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
6967 6968
        goto error;

6969
 cleanup:
6970
    ctxt->node = save_node;
6971
    VIR_FREE(type);
6972
    VIR_FREE(fsdriver);
6973 6974
    VIR_FREE(target);
    VIR_FREE(source);
6975
    VIR_FREE(accessmode);
6976
    VIR_FREE(wrpolicy);
6977
    VIR_FREE(usage);
6978
    VIR_FREE(units);
6979
    VIR_FREE(format);
6980 6981 6982 6983 6984 6985 6986 6987 6988

    return def;

 error:
    virDomainFSDefFree(def);
    def = NULL;
    goto cleanup;
}

6989 6990 6991
static int
virDomainActualNetDefParseXML(xmlNodePtr node,
                              xmlXPathContextPtr ctxt,
6992 6993 6994
                              virDomainNetDefPtr parent,
                              virDomainActualNetDefPtr *def,
                              unsigned int flags)
6995 6996 6997 6998
{
    virDomainActualNetDefPtr actual = NULL;
    int ret = -1;
    xmlNodePtr save_ctxt = ctxt->node;
6999
    xmlNodePtr bandwidth_node = NULL;
7000
    xmlNodePtr vlanNode;
7001
    xmlNodePtr virtPortNode;
7002 7003
    char *type = NULL;
    char *mode = NULL;
7004
    char *addrtype = NULL;
7005
    char *trustGuestRxFilters = NULL;
7006

7007
    if (VIR_ALLOC(actual) < 0)
7008 7009 7010 7011 7012 7013
        return -1;

    ctxt->node = node;

    type = virXMLPropString(node, "type");
    if (!type) {
7014 7015
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("missing type attribute in interface's <actual> element"));
7016 7017 7018
        goto error;
    }
    if ((actual->type = virDomainNetTypeFromString(type)) < 0) {
7019
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7020
                       _("unknown type '%s' in interface's <actual> element"), type);
7021 7022 7023
        goto error;
    }
    if (actual->type != VIR_DOMAIN_NET_TYPE_BRIDGE &&
7024
        actual->type != VIR_DOMAIN_NET_TYPE_DIRECT &&
7025
        actual->type != VIR_DOMAIN_NET_TYPE_HOSTDEV &&
7026
        actual->type != VIR_DOMAIN_NET_TYPE_NETWORK) {
7027 7028 7029
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unsupported type '%s' in interface's <actual> element"),
                       type);
7030 7031 7032
        goto error;
    }

7033 7034 7035 7036 7037 7038 7039 7040 7041 7042
    trustGuestRxFilters = virXMLPropString(node, "trustGuestRxFilters");
    if (trustGuestRxFilters &&
        ((actual->trustGuestRxFilters
          = virTristateBoolTypeFromString(trustGuestRxFilters)) <= 0)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("unknown trustGuestRxFilters value '%s'"),
                       trustGuestRxFilters);
        goto error;
    }

7043 7044 7045 7046 7047
    virtPortNode = virXPathNode("./virtualport", ctxt);
    if (virtPortNode) {
        if (actual->type == VIR_DOMAIN_NET_TYPE_BRIDGE ||
            actual->type == VIR_DOMAIN_NET_TYPE_DIRECT ||
            actual->type == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
7048 7049 7050
            /* the virtualport in <actual> should always already
             * have an instanceid/interfaceid if its required,
             * so don't let the parser generate one */
7051
            if (!(actual->virtPortProfile
7052 7053 7054
                  = virNetDevVPortProfileParse(virtPortNode,
                                               VIR_VPORT_XML_REQUIRE_ALL_ATTRIBUTES |
                                               VIR_VPORT_XML_REQUIRE_TYPE))) {
7055 7056 7057 7058 7059 7060
                goto error;
            }
        } else {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("<virtualport> element unsupported for type='%s'"
                             " in interface's <actual> element"), type);
A
Ansis Atteka 已提交
7061
            goto error;
7062 7063
        }
    }
7064

7065
    if (actual->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
7066 7067 7068 7069 7070
        actual->data.direct.linkdev = virXPathString("string(./source[1]/@dev)", ctxt);

        mode = virXPathString("string(./source[1]/@mode)", ctxt);
        if (mode) {
            int m;
7071
            if ((m = virNetDevMacVLanModeTypeFromString(mode)) < 0) {
7072
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
J
Ján Tomko 已提交
7073
                               _("Unknown mode '%s' in interface <actual> element"),
7074
                               mode);
7075 7076 7077 7078
                goto error;
            }
            actual->data.direct.mode = m;
        }
7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090
    } else if (actual->type == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
        virDomainHostdevDefPtr hostdev = &actual->data.hostdev.def;

        hostdev->parent.type = VIR_DOMAIN_DEVICE_NET;
        hostdev->parent.data.net = parent;
        hostdev->info = &parent->info;
        /* The helper function expects type to already be found and
         * passed in as a string, since it is in a different place in
         * NetDef vs HostdevDef.
         */
        addrtype = virXPathString("string(./source/address/@type)", ctxt);
        /* if not explicitly stated, source/vendor implies usb device */
E
Eric Blake 已提交
7091
        if (!addrtype && virXPathNode("./source/vendor", ctxt) &&
7092
            VIR_STRDUP(addrtype, "usb") < 0)
7093
            goto error;
7094 7095 7096
        hostdev->mode = VIR_DOMAIN_HOSTDEV_MODE_SUBSYS;
        if (virDomainHostdevDefParseXMLSubsys(node, ctxt, addrtype,
                                              hostdev, flags) < 0) {
7097 7098
            goto error;
        }
7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109
    } else if (actual->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
        char *class_id = virXPathString("string(./class/@id)", ctxt);
        if (class_id &&
            virStrToLong_ui(class_id, NULL, 10, &actual->class_id) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to parse class id '%s'"),
                           class_id);
            VIR_FREE(class_id);
            goto error;
        }
        VIR_FREE(class_id);
7110 7111 7112
    }
    if (actual->type == VIR_DOMAIN_NET_TYPE_BRIDGE ||
        actual->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
7113
        char *brname = virXPathString("string(./source/@bridge)", ctxt);
7114 7115

        if (!brname && actual->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
7116 7117 7118 7119 7120 7121
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing <source> element with bridge name in "
                             "interface's <actual> element"));
            goto error;
        }
        actual->data.bridge.brname = brname;
7122 7123
    }

7124 7125
    bandwidth_node = virXPathNode("./bandwidth", ctxt);
    if (bandwidth_node &&
7126 7127
        !(actual->bandwidth = virNetDevBandwidthParse(bandwidth_node,
                                                      actual->type)))
7128 7129
        goto error;

7130 7131 7132 7133
    vlanNode = virXPathNode("./vlan", ctxt);
    if (vlanNode && virNetDevVlanParse(vlanNode, ctxt, &actual->vlan) < 0)
       goto error;

7134 7135 7136
    *def = actual;
    actual = NULL;
    ret = 0;
7137
 error:
7138 7139
    VIR_FREE(type);
    VIR_FREE(mode);
7140
    VIR_FREE(addrtype);
7141
    VIR_FREE(trustGuestRxFilters);
7142 7143 7144 7145 7146
    virDomainActualNetDefFree(actual);

    ctxt->node = save_ctxt;
    return ret;
}
7147

E
Eric Blake 已提交
7148
#define NET_MODEL_CHARS \
7149
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"
E
Eric Blake 已提交
7150

7151 7152 7153 7154
/* Parse the XML definition for a network interface
 * @param node XML nodeset to parse for net definition
 * @return 0 on success, -1 on failure
 */
7155
static virDomainNetDefPtr
7156
virDomainNetDefParseXML(virDomainXMLOptionPtr xmlopt,
7157
                        xmlNodePtr node,
7158
                        xmlXPathContextPtr ctxt,
7159
                        virHashTablePtr bootHash,
E
Eric Blake 已提交
7160
                        unsigned int flags)
7161
{
7162
    virDomainNetDefPtr def;
7163
    virDomainHostdevDefPtr hostdev;
7164 7165 7166 7167
    xmlNodePtr cur;
    char *macaddr = NULL;
    char *type = NULL;
    char *network = NULL;
7168
    char *portgroup = NULL;
7169 7170 7171
    char *bridge = NULL;
    char *dev = NULL;
    char *ifname = NULL;
7172 7173
    char *ifname_guest = NULL;
    char *ifname_guest_actual = NULL;
7174 7175 7176 7177
    char *script = NULL;
    char *address = NULL;
    char *port = NULL;
    char *model = NULL;
7178
    char *backend = NULL;
7179
    char *txmode = NULL;
7180
    char *ioeventfd = NULL;
7181
    char *event_idx = NULL;
7182
    char *queues = NULL;
7183
    char *str = NULL;
7184
    char *filter = NULL;
D
Daniel Veillard 已提交
7185
    char *internal = NULL;
7186
    char *devaddr = NULL;
7187
    char *mode = NULL;
7188
    char *linkstate = NULL;
7189
    char *addrtype = NULL;
M
Michele Paolino 已提交
7190 7191 7192
    char *vhostuser_mode = NULL;
    char *vhostuser_path = NULL;
    char *vhostuser_type = NULL;
7193
    char *trustGuestRxFilters = NULL;
7194
    virNWFilterHashTablePtr filterparams = NULL;
7195
    virDomainActualNetDefPtr actual = NULL;
7196
    xmlNodePtr oldnode = ctxt->node;
7197
    int ret, val;
7198

7199
    if (VIR_ALLOC(def) < 0)
7200 7201
        return NULL;

7202 7203
    ctxt->node = node;

7204 7205
    type = virXMLPropString(node, "type");
    if (type != NULL) {
S
Stefan Berger 已提交
7206
        if ((int)(def->type = virDomainNetTypeFromString(type)) < 0) {
7207
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7208
                           _("unknown interface type '%s'"), type);
7209 7210 7211 7212 7213 7214
            goto error;
        }
    } else {
        def->type = VIR_DOMAIN_NET_TYPE_USER;
    }

7215 7216 7217 7218 7219 7220 7221 7222 7223 7224
    trustGuestRxFilters = virXMLPropString(node, "trustGuestRxFilters");
    if (trustGuestRxFilters &&
        ((def->trustGuestRxFilters
          = virTristateBoolTypeFromString(trustGuestRxFilters)) <= 0)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("unknown trustGuestRxFilters value '%s'"),
                       trustGuestRxFilters);
        goto error;
    }

7225 7226 7227
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
E
Eric Blake 已提交
7228
            if (!macaddr && xmlStrEqual(cur->name, BAD_CAST "mac")) {
7229
                macaddr = virXMLPropString(cur, "address");
E
Eric Blake 已提交
7230 7231 7232
            } else if (!network &&
                       def->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
                       xmlStrEqual(cur->name, BAD_CAST "source")) {
7233
                network = virXMLPropString(cur, "network");
7234
                portgroup = virXMLPropString(cur, "portgroup");
E
Eric Blake 已提交
7235 7236 7237
            } else if (!internal &&
                       def->type == VIR_DOMAIN_NET_TYPE_INTERNAL &&
                       xmlStrEqual(cur->name, BAD_CAST "source")) {
D
Daniel Veillard 已提交
7238
                internal = virXMLPropString(cur, "name");
G
Guannan Ren 已提交
7239
            } else if (!bridge &&
E
Eric Blake 已提交
7240 7241
                       def->type == VIR_DOMAIN_NET_TYPE_BRIDGE &&
                       xmlStrEqual(cur->name, BAD_CAST "source")) {
7242
                bridge = virXMLPropString(cur, "bridge");
E
Eric Blake 已提交
7243
            } else if (!dev &&
7244 7245
                       (def->type == VIR_DOMAIN_NET_TYPE_ETHERNET ||
                        def->type == VIR_DOMAIN_NET_TYPE_DIRECT) &&
7246
                       xmlStrEqual(cur->name, BAD_CAST "source")) {
7247 7248
                dev  = virXMLPropString(cur, "dev");
                mode = virXMLPropString(cur, "mode");
M
Michele Paolino 已提交
7249 7250 7251 7252 7253 7254
            } else if (!vhostuser_path && !vhostuser_mode && !vhostuser_type
                       && def->type == VIR_DOMAIN_NET_TYPE_VHOSTUSER &&
                       xmlStrEqual(cur->name, BAD_CAST "source")) {
                vhostuser_type = virXMLPropString(cur, "type");
                vhostuser_path = virXMLPropString(cur, "path");
                vhostuser_mode = virXMLPropString(cur, "mode");
7255 7256
            } else if (!def->virtPortProfile
                       && xmlStrEqual(cur->name, BAD_CAST "virtualport")) {
7257
                if (def->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
7258
                    if (!(def->virtPortProfile
7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270
                          = virNetDevVPortProfileParse(cur,
                                                       VIR_VPORT_XML_GENERATE_MISSING_DEFAULTS))) {
                        goto error;
                    }
                } else if (def->type == VIR_DOMAIN_NET_TYPE_BRIDGE ||
                           def->type == VIR_DOMAIN_NET_TYPE_DIRECT ||
                           def->type == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
                    if (!(def->virtPortProfile
                          = virNetDevVPortProfileParse(cur,
                                                       VIR_VPORT_XML_GENERATE_MISSING_DEFAULTS|
                                                       VIR_VPORT_XML_REQUIRE_ALL_ATTRIBUTES|
                                                       VIR_VPORT_XML_REQUIRE_TYPE))) {
7271 7272 7273 7274 7275 7276
                        goto error;
                    }
                } else {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("<virtualport> element unsupported for"
                                     " <interface type='%s'>"), type);
7277
                    goto error;
7278
                }
G
Guannan Ren 已提交
7279
            } else if (!address &&
E
Eric Blake 已提交
7280 7281 7282 7283
                       (def->type == VIR_DOMAIN_NET_TYPE_SERVER ||
                        def->type == VIR_DOMAIN_NET_TYPE_CLIENT ||
                        def->type == VIR_DOMAIN_NET_TYPE_MCAST) &&
                       xmlStrEqual(cur->name, BAD_CAST "source")) {
7284 7285
                address = virXMLPropString(cur, "address");
                port = virXMLPropString(cur, "port");
E
Eric Blake 已提交
7286
            } else if (!address &&
7287 7288
                       (def->type == VIR_DOMAIN_NET_TYPE_ETHERNET ||
                        def->type == VIR_DOMAIN_NET_TYPE_BRIDGE) &&
E
Eric Blake 已提交
7289
                       xmlStrEqual(cur->name, BAD_CAST "ip")) {
7290
                address = virXMLPropString(cur, "address");
E
Eric Blake 已提交
7291
            } else if (!ifname &&
7292 7293
                       xmlStrEqual(cur->name, BAD_CAST "target")) {
                ifname = virXMLPropString(cur, "dev");
E
Eric Blake 已提交
7294 7295 7296
                if (ifname &&
                    (flags & VIR_DOMAIN_XML_INACTIVE) &&
                    STRPREFIX(ifname, VIR_NET_GENERATED_PREFIX)) {
7297 7298 7299
                    /* An auto-generated target name, blank it out */
                    VIR_FREE(ifname);
                }
7300 7301 7302 7303
            } else if ((!ifname_guest || !ifname_guest_actual) &&
                       xmlStrEqual(cur->name, BAD_CAST "guest")) {
                ifname_guest = virXMLPropString(cur, "dev");
                ifname_guest_actual = virXMLPropString(cur, "actual");
E
Eric Blake 已提交
7304
            } else if (!linkstate &&
7305 7306
                       xmlStrEqual(cur->name, BAD_CAST "link")) {
                linkstate = virXMLPropString(cur, "state");
E
Eric Blake 已提交
7307
            } else if (!script &&
7308 7309
                       xmlStrEqual(cur->name, BAD_CAST "script")) {
                script = virXMLPropString(cur, "path");
7310
            } else if (xmlStrEqual(cur->name, BAD_CAST "model")) {
7311
                model = virXMLPropString(cur, "type");
7312
            } else if (xmlStrEqual(cur->name, BAD_CAST "driver")) {
7313
                backend = virXMLPropString(cur, "name");
7314
                txmode = virXMLPropString(cur, "txmode");
7315
                ioeventfd = virXMLPropString(cur, "ioeventfd");
7316
                event_idx = virXMLPropString(cur, "event_idx");
7317
                queues = virXMLPropString(cur, "queues");
7318
            } else if (xmlStrEqual(cur->name, BAD_CAST "filterref")) {
7319 7320 7321 7322 7323 7324
                if (filter) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("Invalid specification of multiple <filterref>s "
                                     "in a single <interface>"));
                    goto error;
                }
7325
                filter = virXMLPropString(cur, "filter");
7326
                virNWFilterHashTableFree(filterparams);
7327
                filterparams = virNWFilterParseParamAttributes(cur);
7328 7329
            } else if ((flags & VIR_DOMAIN_XML_INTERNAL_STATUS) &&
                       xmlStrEqual(cur->name, BAD_CAST "state")) {
7330
                /* Legacy back-compat. Don't add any more attributes here */
7331
                devaddr = virXMLPropString(cur, "devaddr");
7332
            } else if (xmlStrEqual(cur->name, BAD_CAST "boot")) {
7333
                /* boot is parsed as part of virDomainDeviceInfoParseXML */
E
Eric Blake 已提交
7334
            } else if (!actual &&
7335
                       (flags & VIR_DOMAIN_XML_INTERNAL_ACTUAL_NET) &&
E
Eric Blake 已提交
7336
                       def->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
7337
                       xmlStrEqual(cur->name, BAD_CAST "actual")) {
7338 7339
                if (virDomainActualNetDefParseXML(cur, ctxt, def,
                                                  &actual, flags) < 0) {
7340
                    goto error;
7341
                }
7342
            } else if (xmlStrEqual(cur->name, BAD_CAST "bandwidth")) {
7343 7344
                if (!(def->bandwidth = virNetDevBandwidthParse(cur,
                                                               def->type)))
7345
                    goto error;
7346 7347 7348
            } else if (xmlStrEqual(cur->name, BAD_CAST "vlan")) {
                if (virNetDevVlanParse(cur, ctxt, &def->vlan) < 0)
                    goto error;
7349
            } else if (xmlStrEqual(cur->name, BAD_CAST "backend")) {
7350 7351 7352 7353 7354 7355 7356 7357 7358
                char *tmp = NULL;

                if ((tmp = virXMLPropString(cur, "tap")))
                    def->backend.tap = virFileSanitizePath(tmp);
                VIR_FREE(tmp);

                if ((tmp = virXMLPropString(cur, "vhost")))
                    def->backend.vhost = virFileSanitizePath(tmp);
                VIR_FREE(tmp);
7359 7360 7361 7362 7363 7364
            }
        }
        cur = cur->next;
    }

    if (macaddr) {
7365
        if (virMacAddrParse((const char *)macaddr, &def->mac) < 0) {
7366 7367 7368
            virReportError(VIR_ERR_XML_ERROR,
                           _("unable to parse mac address '%s'"),
                           (const char *)macaddr);
7369 7370
            goto error;
        }
7371
        if (virMacAddrIsMulticast(&def->mac)) {
7372 7373 7374
            virReportError(VIR_ERR_XML_ERROR,
                           _("expected unicast mac address, found multicast '%s'"),
                           (const char *)macaddr);
7375 7376
            goto error;
        }
7377
    } else {
7378
        virDomainNetGenerateMAC(xmlopt, &def->mac);
7379 7380
    }

7381
    if (devaddr) {
7382 7383
        if (virDomainParseLegacyDeviceAddress(devaddr,
                                              &def->info.addr.pci) < 0) {
7384 7385 7386
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to parse devaddr parameter '%s'"),
                           devaddr);
7387 7388 7389 7390
            goto error;
        }
        def->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
    } else {
7391
        if (virDomainDeviceInfoParseXML(node, bootHash, &def->info,
7392 7393
                                        flags | VIR_DOMAIN_XML_INTERNAL_ALLOW_BOOT
                                        | VIR_DOMAIN_XML_INTERNAL_ALLOW_ROM) < 0)
7394 7395 7396 7397 7398 7399
            goto error;
    }

    /* XXX what about ISA/USB based NIC models - once we support
     * them we should make sure address type is correct */
    if (def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
7400
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO &&
7401
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW &&
7402
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390 &&
7403
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO &&
7404
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
7405 7406
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Network interfaces must use 'pci' address type"));
7407 7408 7409
        goto error;
    }

7410 7411 7412
    switch (def->type) {
    case VIR_DOMAIN_NET_TYPE_NETWORK:
        if (network == NULL) {
7413 7414 7415
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No <source> 'network' attribute "
                             "specified with <interface type='network'/>"));
7416 7417 7418 7419
            goto error;
        }
        def->data.network.name = network;
        network = NULL;
7420 7421 7422 7423
        def->data.network.portgroup = portgroup;
        portgroup = NULL;
        def->data.network.actual = actual;
        actual = NULL;
7424 7425
        break;

M
Michele Paolino 已提交
7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471
    case VIR_DOMAIN_NET_TYPE_VHOSTUSER:
        if (STRNEQ_NULLABLE(model, "virtio")) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Wrong or no <model> 'type' attribute "
                             "specified with <interface type='vhostuser'/>. "
                             "vhostuser requires the virtio-net* frontend"));
            goto error;
        }

        if (STRNEQ_NULLABLE(vhostuser_type, "unix")) {
            if (vhostuser_type)
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("Type='%s' unsupported for"
                                 " <interface type='vhostuser'>"),
                               vhostuser_type);
            else
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("No <source> 'type' attribute "
                                 "specified for <interface "
                                 "type='vhostuser'>"));
            goto error;
        }

        if (vhostuser_path == NULL) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No <source> 'path' attribute "
                             "specified with <interface "
                             "type='vhostuser'/>"));
            goto error;
        }

        if (vhostuser_mode == NULL) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No <source> 'mode' attribute "
                             "specified with <interface "
                             "type='vhostuser'/>"));
            goto error;
        }

        if (VIR_ALLOC(def->data.vhostuser) < 0)
            goto error;

        def->data.vhostuser->type = VIR_DOMAIN_CHR_TYPE_UNIX;
        def->data.vhostuser->data.nix.path = vhostuser_path;
        vhostuser_path = NULL;

7472
        if (STREQ(vhostuser_mode, "server")) {
M
Michele Paolino 已提交
7473
            def->data.vhostuser->data.nix.listen = true;
7474
        } else if (STREQ(vhostuser_mode, "client")) {
M
Michele Paolino 已提交
7475
            def->data.vhostuser->data.nix.listen = false;
7476
        } else {
M
Michele Paolino 已提交
7477 7478 7479 7480 7481 7482 7483 7484
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Wrong <source> 'mode' attribute "
                             "specified with <interface "
                             "type='vhostuser'/>"));
            goto error;
        }
        break;

7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497
    case VIR_DOMAIN_NET_TYPE_ETHERNET:
        if (dev != NULL) {
            def->data.ethernet.dev = dev;
            dev = NULL;
        }
        if (address != NULL) {
            def->data.ethernet.ipaddr = address;
            address = NULL;
        }
        break;

    case VIR_DOMAIN_NET_TYPE_BRIDGE:
        if (bridge == NULL) {
7498 7499 7500
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No <source> 'bridge' attribute "
                             "specified with <interface type='bridge'/>"));
7501 7502 7503 7504
            goto error;
        }
        def->data.bridge.brname = bridge;
        bridge = NULL;
7505 7506 7507 7508
        if (address != NULL) {
            def->data.bridge.ipaddr = address;
            address = NULL;
        }
7509 7510 7511 7512 7513 7514
        break;

    case VIR_DOMAIN_NET_TYPE_CLIENT:
    case VIR_DOMAIN_NET_TYPE_SERVER:
    case VIR_DOMAIN_NET_TYPE_MCAST:
        if (port == NULL) {
7515 7516 7517
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No <source> 'port' attribute "
                             "specified with socket interface"));
7518 7519 7520
            goto error;
        }
        if (virStrToLong_i(port, NULL, 10, &def->data.socket.port) < 0) {
7521 7522 7523
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot parse <source> 'port' attribute "
                             "with socket interface"));
7524 7525 7526 7527 7528 7529
            goto error;
        }

        if (address == NULL) {
            if (def->type == VIR_DOMAIN_NET_TYPE_CLIENT ||
                def->type == VIR_DOMAIN_NET_TYPE_MCAST) {
7530 7531 7532
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("No <source> 'address' attribute "
                                 "specified with socket interface"));
7533 7534 7535 7536 7537 7538
                goto error;
            }
        } else {
            def->data.socket.address = address;
            address = NULL;
        }
7539 7540
        break;

D
Daniel Veillard 已提交
7541 7542
    case VIR_DOMAIN_NET_TYPE_INTERNAL:
        if (internal == NULL) {
7543 7544 7545
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No <source> 'name' attribute specified "
                             "with <interface type='internal'/>"));
D
Daniel Veillard 已提交
7546 7547 7548 7549 7550
            goto error;
        }
        def->data.internal.name = internal;
        internal = NULL;
        break;
7551 7552 7553

    case VIR_DOMAIN_NET_TYPE_DIRECT:
        if (dev == NULL) {
7554 7555 7556
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No <source> 'dev' attribute specified "
                             "with <interface type='direct'/>"));
7557 7558 7559 7560
            goto error;
        }

        if (mode != NULL) {
7561
            if ((val = virNetDevMacVLanModeTypeFromString(mode)) < 0) {
7562
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
J
Ján Tomko 已提交
7563
                               _("Unknown mode has been specified"));
7564 7565
                goto error;
            }
7566
            def->data.direct.mode = val;
E
Eric Blake 已提交
7567
        } else {
7568
            def->data.direct.mode = VIR_NETDEV_MACVLAN_MODE_VEPA;
E
Eric Blake 已提交
7569
        }
7570 7571 7572 7573

        def->data.direct.linkdev = dev;
        dev = NULL;

E
Eric Blake 已提交
7574
        if (flags & VIR_DOMAIN_XML_INACTIVE)
7575
            VIR_FREE(ifname);
7576

7577
        break;
S
Stefan Berger 已提交
7578

7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589
    case VIR_DOMAIN_NET_TYPE_HOSTDEV:
        hostdev = &def->data.hostdev.def;
        hostdev->parent.type = VIR_DOMAIN_DEVICE_NET;
        hostdev->parent.data.net = def;
        hostdev->info = &def->info;
        /* The helper function expects type to already be found and
         * passed in as a string, since it is in a different place in
         * NetDef vs HostdevDef.
         */
        addrtype = virXPathString("string(./source/address/@type)", ctxt);
        /* if not explicitly stated, source/vendor implies usb device */
E
Eric Blake 已提交
7590
        if (!addrtype && virXPathNode("./source/vendor", ctxt) &&
7591
            VIR_STRDUP(addrtype, "usb") < 0)
7592
            goto error;
7593 7594 7595
        hostdev->mode = VIR_DOMAIN_HOSTDEV_MODE_SUBSYS;
        if (virDomainHostdevDefParseXMLSubsys(node, ctxt, addrtype,
                                              hostdev, flags) < 0) {
7596 7597 7598 7599
            goto error;
        }
        break;

S
Stefan Berger 已提交
7600 7601 7602
    case VIR_DOMAIN_NET_TYPE_USER:
    case VIR_DOMAIN_NET_TYPE_LAST:
        break;
7603 7604
    }

7605 7606 7607 7608
    if (script != NULL) {
        def->script = script;
        script = NULL;
    }
7609 7610 7611 7612
    if (ifname != NULL) {
        def->ifname = ifname;
        ifname = NULL;
    }
7613 7614 7615 7616 7617 7618 7619 7620
    if (ifname_guest != NULL) {
        def->ifname_guest = ifname_guest;
        ifname_guest = NULL;
    }
    if (ifname_guest_actual != NULL) {
        def->ifname_guest_actual = ifname_guest_actual;
        ifname_guest_actual = NULL;
    }
7621 7622 7623 7624 7625

    /* NIC model (see -net nic,model=?).  We only check that it looks
     * reasonable, not that it is a supported NIC type.  FWIW kvm
     * supports these types as of April 2008:
     * i82551 i82557b i82559er ne2k_pci pcnet rtl8139 e1000 virtio
E
Eric Blake 已提交
7626
     * QEMU PPC64 supports spapr-vlan
7627 7628
     */
    if (model != NULL) {
E
Eric Blake 已提交
7629
        if (strspn(model, NET_MODEL_CHARS) < strlen(model)) {
7630 7631
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("Model name contains invalid characters"));
E
Eric Blake 已提交
7632
            goto error;
7633 7634 7635 7636 7637
        }
        def->model = model;
        model = NULL;
    }

7638 7639
    if (def->type != VIR_DOMAIN_NET_TYPE_HOSTDEV &&
        STREQ_NULLABLE(def->model, "virtio")) {
7640
        if (backend != NULL) {
7641 7642
            if ((val = virDomainNetBackendTypeFromString(backend)) < 0 ||
                val == VIR_DOMAIN_NET_BACKEND_TYPE_DEFAULT) {
7643
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7644 7645 7646
                               _("Unknown interface <driver name='%s'> "
                                 "has been specified"),
                               backend);
7647 7648
                goto error;
            }
7649
            def->driver.virtio.name = val;
7650
        }
7651
        if (txmode != NULL) {
7652 7653
            if ((val = virDomainNetVirtioTxModeTypeFromString(txmode)) < 0 ||
                val == VIR_DOMAIN_NET_VIRTIO_TX_MODE_DEFAULT) {
7654
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7655 7656 7657
                               _("Unknown interface <driver txmode='%s'> "
                                 "has been specified"),
                               txmode);
7658 7659
                goto error;
            }
7660
            def->driver.virtio.txmode = val;
7661
        }
7662
        if (ioeventfd) {
J
Ján Tomko 已提交
7663
            if ((val = virTristateSwitchTypeFromString(ioeventfd)) <= 0) {
7664 7665 7666
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown interface ioeventfd mode '%s'"),
                               ioeventfd);
7667 7668
                goto error;
            }
7669
            def->driver.virtio.ioeventfd = val;
7670
        }
7671
        if (event_idx) {
7672
            if ((val = virTristateSwitchTypeFromString(event_idx)) <= 0) {
7673 7674 7675
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown interface event_idx mode '%s'"),
                               event_idx);
7676 7677
                goto error;
            }
7678
            def->driver.virtio.event_idx = val;
7679
        }
7680 7681
        if (queues) {
            unsigned int q;
7682
            if (virStrToLong_uip(queues, NULL, 10, &q) < 0) {
7683 7684 7685 7686 7687 7688 7689
                virReportError(VIR_ERR_XML_DETAIL,
                               _("'queues' attribute must be positive number: %s"),
                               queues);
                goto error;
            }
            def->driver.virtio.queues = q;
        }
7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798
        if ((str = virXPathString("string(./driver/host/@csum)", ctxt))) {
            if ((val = virTristateSwitchTypeFromString(str)) <= 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown host csum mode '%s'"),
                               str);
                goto error;
            }
            def->driver.virtio.host.csum = val;
        }
        VIR_FREE(str);
        if ((str = virXPathString("string(./driver/host/@gso)", ctxt))) {
            if ((val = virTristateSwitchTypeFromString(str)) <= 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown host gso mode '%s'"),
                               str);
                goto error;
            }
            def->driver.virtio.host.gso = val;
        }
        VIR_FREE(str);
        if ((str = virXPathString("string(./driver/host/@tso4)", ctxt))) {
            if ((val = virTristateSwitchTypeFromString(str)) <= 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown host tso4 mode '%s'"),
                               str);
                goto error;
            }
            def->driver.virtio.host.tso4 = val;
        }
        VIR_FREE(str);
        if ((str = virXPathString("string(./driver/host/@tso6)", ctxt))) {
            if ((val = virTristateSwitchTypeFromString(str)) <= 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown host tso6 mode '%s'"),
                               str);
                goto error;
            }
            def->driver.virtio.host.tso6 = val;
        }
        VIR_FREE(str);
        if ((str = virXPathString("string(./driver/host/@ecn)", ctxt))) {
            if ((val = virTristateSwitchTypeFromString(str)) <= 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown host ecn mode '%s'"),
                               str);
                goto error;
            }
            def->driver.virtio.host.ecn = val;
        }
        VIR_FREE(str);
        if ((str = virXPathString("string(./driver/host/@ufo)", ctxt))) {
            if ((val = virTristateSwitchTypeFromString(str)) <= 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown host ufo mode '%s'"),
                               str);
                goto error;
            }
            def->driver.virtio.host.ufo = val;
        }
        VIR_FREE(str);
        if ((str = virXPathString("string(./driver/guest/@csum)", ctxt))) {
            if ((val = virTristateSwitchTypeFromString(str)) <= 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown guest csum mode '%s'"),
                               str);
                goto error;
            }
            def->driver.virtio.guest.csum = val;
        }
        VIR_FREE(str);
        if ((str = virXPathString("string(./driver/guest/@tso4)", ctxt))) {
            if ((val = virTristateSwitchTypeFromString(str)) <= 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown guest tso4 mode '%s'"),
                               str);
                goto error;
            }
            def->driver.virtio.guest.tso4 = val;
        }
        VIR_FREE(str);
        if ((str = virXPathString("string(./driver/guest/@tso6)", ctxt))) {
            if ((val = virTristateSwitchTypeFromString(str)) <= 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown guest tso6 mode '%s'"),
                               str);
                goto error;
            }
            def->driver.virtio.guest.tso6 = val;
        }
        VIR_FREE(str);
        if ((str = virXPathString("string(./driver/guest/@ecn)", ctxt))) {
            if ((val = virTristateSwitchTypeFromString(str)) <= 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown guest ecn mode '%s'"),
                               str);
                goto error;
            }
            def->driver.virtio.guest.ecn = val;
        }
        VIR_FREE(str);
        if ((str = virXPathString("string(./driver/guest/@ufo)", ctxt))) {
            if ((val = virTristateSwitchTypeFromString(str)) <= 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown guest ufo mode '%s'"),
                               str);
                goto error;
            }
            def->driver.virtio.guest.ufo = val;
        }
7799
    }
7800

7801 7802 7803
    def->linkstate = VIR_DOMAIN_NET_INTERFACE_LINK_STATE_DEFAULT;
    if (linkstate != NULL) {
        if ((def->linkstate = virDomainNetInterfaceLinkStateTypeFromString(linkstate)) <= 0) {
7804 7805 7806
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown interface link state '%s'"),
                           linkstate);
7807 7808 7809 7810
            goto error;
        }
    }

7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825
    if (filter != NULL) {
        switch (def->type) {
        case VIR_DOMAIN_NET_TYPE_ETHERNET:
        case VIR_DOMAIN_NET_TYPE_NETWORK:
        case VIR_DOMAIN_NET_TYPE_BRIDGE:
            def->filter = filter;
            filter = NULL;
            def->filterparams = filterparams;
            filterparams = NULL;
        break;
        default:
        break;
        }
    }

7826 7827 7828 7829
    ret = virXPathULong("string(./tune/sndbuf)", ctxt, &def->tune.sndbuf);
    if (ret >= 0) {
        def->tune.sndbuf_specified = true;
    } else if (ret == -2) {
7830 7831
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("sndbuf must be a positive integer"));
7832 7833 7834
        goto error;
    }

7835
 cleanup:
7836
    ctxt->node = oldnode;
7837 7838
    VIR_FREE(macaddr);
    VIR_FREE(network);
7839
    VIR_FREE(portgroup);
7840 7841
    VIR_FREE(address);
    VIR_FREE(port);
M
Michele Paolino 已提交
7842 7843 7844
    VIR_FREE(vhostuser_type);
    VIR_FREE(vhostuser_path);
    VIR_FREE(vhostuser_mode);
7845 7846
    VIR_FREE(ifname);
    VIR_FREE(dev);
7847
    virDomainActualNetDefFree(actual);
7848 7849 7850
    VIR_FREE(script);
    VIR_FREE(bridge);
    VIR_FREE(model);
7851
    VIR_FREE(backend);
7852
    VIR_FREE(txmode);
7853
    VIR_FREE(ioeventfd);
7854
    VIR_FREE(event_idx);
7855
    VIR_FREE(queues);
7856
    VIR_FREE(str);
7857
    VIR_FREE(filter);
7858
    VIR_FREE(type);
D
Daniel Veillard 已提交
7859
    VIR_FREE(internal);
7860
    VIR_FREE(devaddr);
S
Stefan Berger 已提交
7861
    VIR_FREE(mode);
7862
    VIR_FREE(linkstate);
7863
    VIR_FREE(addrtype);
7864
    VIR_FREE(trustGuestRxFilters);
7865
    virNWFilterHashTableFree(filterparams);
7866 7867 7868

    return def;

7869
 error:
7870 7871 7872 7873 7874
    virDomainNetDefFree(def);
    def = NULL;
    goto cleanup;
}

7875
static int
7876 7877
virDomainChrDefaultTargetType(int devtype)
{
7878
    switch ((virDomainChrDeviceType) devtype) {
7879
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
7880 7881 7882
        virReportError(VIR_ERR_XML_ERROR,
                       _("target type must be specified for %s device"),
                       virDomainChrDeviceTypeToString(devtype));
7883
        return -1;
7884 7885

    case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
7886
        return VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_NONE;
7887

7888
    case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
7889
        return VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_ISA;
G
Guannan Ren 已提交
7890

7891
    case VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL:
7892
    case VIR_DOMAIN_CHR_DEVICE_TYPE_LAST:
7893 7894 7895 7896
        /* No target type yet*/
        break;
    }

7897
    return 0;
7898 7899 7900
}

static int
7901
virDomainChrTargetTypeFromString(virDomainChrDefPtr def,
7902
                                 int devtype,
7903 7904 7905 7906
                                 const char *targetType)
{
    int ret = -1;

7907 7908
    if (!targetType)
        return virDomainChrDefaultTargetType(devtype);
7909

7910
    switch ((virDomainChrDeviceType) devtype) {
7911
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
7912
        ret = virDomainChrChannelTargetTypeFromString(targetType);
7913 7914
        break;

7915
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
7916
        ret = virDomainChrConsoleTargetTypeFromString(targetType);
C
Cole Robinson 已提交
7917
        break;
7918

7919
    case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
7920
        ret = virDomainChrSerialTargetTypeFromString(targetType);
G
Guannan Ren 已提交
7921 7922
        break;

7923
    case VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL:
7924
    case VIR_DOMAIN_CHR_DEVICE_TYPE_LAST:
7925
        /* No target type yet*/
7926
        ret = 0;
7927 7928 7929
        break;
    }

G
Guannan Ren 已提交
7930 7931
    def->targetTypeAttr = true;

7932 7933 7934 7935
    return ret;
}

static int
7936
virDomainChrDefParseTargetXML(virDomainChrDefPtr def,
7937 7938
                              xmlNodePtr cur,
                              unsigned int flags)
7939 7940 7941
{
    int ret = -1;
    unsigned int port;
7942 7943 7944
    char *targetType = virXMLPropString(cur, "type");
    char *addrStr = NULL;
    char *portStr = NULL;
7945
    char *stateStr = NULL;
7946 7947

    if ((def->targetType =
7948 7949
         virDomainChrTargetTypeFromString(def, def->deviceType,
                                          targetType)) < 0) {
7950
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7951 7952
                       _("unknown target type '%s' specified for character device"),
                       targetType);
7953 7954 7955 7956 7957 7958 7959 7960 7961 7962
        goto error;
    }

    switch (def->deviceType) {
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
        switch (def->targetType) {
        case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_GUESTFWD:
            addrStr = virXMLPropString(cur, "address");
            portStr = virXMLPropString(cur, "port");

7963
            if (VIR_ALLOC(def->target.addr) < 0)
7964 7965
                goto error;

7966
            if (addrStr == NULL) {
7967 7968 7969
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("guestfwd channel does not "
                                 "define a target address"));
7970 7971 7972
                goto error;
            }

7973
            if (virSocketAddrParse(def->target.addr, addrStr, AF_UNSPEC) < 0)
7974 7975
                goto error;

7976
            if (def->target.addr->data.stor.ss_family != AF_INET) {
7977 7978 7979
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               "%s", _("guestfwd channel only supports "
                                       "IPv4 addresses"));
7980 7981 7982 7983
                goto error;
            }

            if (portStr == NULL) {
7984 7985 7986
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("guestfwd channel does "
                                 "not define a target port"));
7987 7988 7989 7990
                goto error;
            }

            if (virStrToLong_ui(portStr, NULL, 10, &port) < 0) {
7991 7992 7993
                virReportError(VIR_ERR_XML_ERROR,
                               _("Invalid port number: %s"),
                               portStr);
7994 7995 7996
                goto error;
            }

7997
            virSocketAddrSetPort(def->target.addr, port);
7998 7999 8000 8001
            break;

        case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO:
            def->target.name = virXMLPropString(cur, "name");
8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015

            if (!(flags & VIR_DOMAIN_XML_INACTIVE) &&
                (stateStr = virXMLPropString(cur, "state"))) {
                int tmp;

                if ((tmp = virDomainChrDeviceStateTypeFromString(stateStr)) <= 0) {
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("invalid channel state value '%s'"),
                                   stateStr);
                    goto error;
                }

                def->state = tmp;
            }
8016 8017 8018 8019 8020 8021 8022
            break;
        }
        break;

    default:
        portStr = virXMLPropString(cur, "port");
        if (portStr == NULL) {
8023 8024
            /* Set to negative value to indicate we should set it later */
            def->target.port = -1;
8025 8026 8027 8028
            break;
        }

        if (virStrToLong_ui(portStr, NULL, 10, &port) < 0) {
8029 8030 8031
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid port number: %s"),
                           portStr);
8032 8033
            goto error;
        }
8034
        def->target.port = port;
8035 8036 8037 8038 8039
        break;
    }


    ret = 0;
8040
 error:
8041 8042 8043
    VIR_FREE(targetType);
    VIR_FREE(addrStr);
    VIR_FREE(portStr);
8044
    VIR_FREE(stateStr);
8045 8046 8047 8048

    return ret;
}

8049 8050 8051
#define SERIAL_CHANNEL_NAME_CHARS \
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-."

8052 8053 8054 8055 8056 8057 8058
/* Parse the source half of the XML definition for a character device,
 * where node is the first element of node->children of the parent
 * element.  def->type must already be valid.  Return -1 on failure,
 * otherwise the number of ignored children (this intentionally skips
 * <target>, which is used by <serial> but not <smartcard>). */
static int
virDomainChrSourceDefParseXML(virDomainChrSourceDefPtr def,
8059 8060 8061 8062 8063
                              xmlNodePtr cur, unsigned int flags,
                              virDomainChrDefPtr chr_def,
                              xmlXPathContextPtr ctxt,
                              virSecurityLabelDefPtr* vmSeclabels,
                              int nvmSeclabels)
8064
{
8065 8066 8067 8068 8069 8070 8071
    char *bindHost = NULL;
    char *bindService = NULL;
    char *connectHost = NULL;
    char *connectService = NULL;
    char *path = NULL;
    char *mode = NULL;
    char *protocol = NULL;
8072
    char *channel = NULL;
8073 8074
    char *master = NULL;
    char *slave = NULL;
8075
    int remaining = 0;
8076 8077 8078 8079

    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if (xmlStrEqual(cur->name, BAD_CAST "source")) {
8080
                if (!mode)
8081 8082
                    mode = virXMLPropString(cur, "mode");

8083
                switch ((virDomainChrType) def->type) {
8084 8085 8086 8087 8088
                case VIR_DOMAIN_CHR_TYPE_PTY:
                case VIR_DOMAIN_CHR_TYPE_DEV:
                case VIR_DOMAIN_CHR_TYPE_FILE:
                case VIR_DOMAIN_CHR_TYPE_PIPE:
                case VIR_DOMAIN_CHR_TYPE_UNIX:
8089
                    /* PTY path is only parsed from live xml.  */
8090
                    if (!path  &&
8091 8092
                        (def->type != VIR_DOMAIN_CHR_TYPE_PTY ||
                         !(flags & VIR_DOMAIN_XML_INACTIVE)))
8093 8094 8095 8096 8097 8098
                        path = virXMLPropString(cur, "path");

                    break;

                case VIR_DOMAIN_CHR_TYPE_UDP:
                case VIR_DOMAIN_CHR_TYPE_TCP:
8099 8100
                    if (!mode || STREQ(mode, "connect")) {
                        if (!connectHost)
8101
                            connectHost = virXMLPropString(cur, "host");
8102
                        if (!connectService)
8103
                            connectService = virXMLPropString(cur, "service");
8104 8105
                    } else if (STREQ(mode, "bind")) {
                        if (!bindHost)
8106
                            bindHost = virXMLPropString(cur, "host");
8107
                        if (!bindService)
8108
                            bindService = virXMLPropString(cur, "service");
8109
                    } else {
8110
                        virReportError(VIR_ERR_INTERNAL_ERROR,
8111
                                       _("Unknown source mode '%s'"), mode);
8112
                        goto error;
8113 8114
                    }

8115
                    if (def->type == VIR_DOMAIN_CHR_TYPE_UDP)
8116
                        VIR_FREE(mode);
8117 8118
                    break;

8119 8120 8121 8122 8123
                case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
                    if (!channel)
                        channel = virXMLPropString(cur, "channel");
                    break;

8124 8125 8126 8127 8128 8129 8130
                case VIR_DOMAIN_CHR_TYPE_NMDM:
                    if (!master)
                        master = virXMLPropString(cur, "master");
                    if (!slave)
                        slave = virXMLPropString(cur, "slave");
                    break;

8131 8132 8133 8134 8135 8136
                case VIR_DOMAIN_CHR_TYPE_LAST:
                case VIR_DOMAIN_CHR_TYPE_NULL:
                case VIR_DOMAIN_CHR_TYPE_VC:
                case VIR_DOMAIN_CHR_TYPE_STDIO:
                case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
                    break;
8137
                }
8138 8139 8140 8141 8142 8143 8144 8145 8146

                /* Check for an optional seclabel override in <source/>. */
                if (chr_def) {
                    xmlNodePtr saved_node = ctxt->node;
                    ctxt->node = cur;
                    if (virSecurityDeviceLabelDefParseXML(&chr_def->seclabels,
                                                          &chr_def->nseclabels,
                                                          vmSeclabels,
                                                          nvmSeclabels,
8147 8148
                                                          ctxt,
                                                          flags) < 0) {
8149 8150 8151 8152 8153
                        ctxt->node = saved_node;
                        goto error;
                    }
                    ctxt->node = saved_node;
                }
8154
            } else if (xmlStrEqual(cur->name, BAD_CAST "protocol")) {
8155
                if (!protocol)
8156
                    protocol = virXMLPropString(cur, "type");
8157 8158
            } else {
                remaining++;
8159 8160 8161 8162 8163
            }
        }
        cur = cur->next;
    }

8164
    switch ((virDomainChrType) def->type) {
8165
    case VIR_DOMAIN_CHR_TYPE_NULL:
8166
    case VIR_DOMAIN_CHR_TYPE_VC:
8167 8168
    case VIR_DOMAIN_CHR_TYPE_STDIO:
    case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
8169
    case VIR_DOMAIN_CHR_TYPE_LAST:
8170 8171 8172 8173 8174 8175
        break;

    case VIR_DOMAIN_CHR_TYPE_PTY:
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
    case VIR_DOMAIN_CHR_TYPE_PIPE:
8176
        if (!path &&
8177
            def->type != VIR_DOMAIN_CHR_TYPE_PTY) {
8178 8179
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing source path attribute for char device"));
8180 8181 8182 8183 8184 8185 8186
            goto error;
        }

        def->data.file.path = path;
        path = NULL;
        break;

8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205
    case VIR_DOMAIN_CHR_TYPE_NMDM:
        if (!master) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing master path attribute for nmdm device"));
            goto error;
        }

        if (!slave) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing slave path attribute for nmdm device"));
            goto error;
        }

        def->data.nmdm.master = master;
        def->data.nmdm.slave = slave;
        master = NULL;
        slave = NULL;
        break;

8206
    case VIR_DOMAIN_CHR_TYPE_TCP:
8207 8208
        if (!mode || STREQ(mode, "connect")) {
            if (!connectHost) {
8209 8210
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Missing source host attribute for char device"));
8211 8212
                goto error;
            }
8213 8214

            if (!connectService) {
8215 8216
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Missing source service attribute for char device"));
8217 8218 8219 8220 8221 8222 8223
                goto error;
            }

            def->data.tcp.host = connectHost;
            connectHost = NULL;
            def->data.tcp.service = connectService;
            connectService = NULL;
8224
            def->data.tcp.listen = false;
8225
        } else {
8226
            if (!bindHost) {
8227 8228
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Missing source host attribute for char device"));
8229 8230
                goto error;
            }
8231 8232

            if (!bindService) {
8233 8234
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Missing source service attribute for char device"));
8235 8236 8237 8238 8239 8240 8241
                goto error;
            }

            def->data.tcp.host = bindHost;
            bindHost = NULL;
            def->data.tcp.service = bindService;
            bindService = NULL;
8242
            def->data.tcp.listen = true;
8243
        }
8244

8245
        if (!protocol)
8246
            def->data.tcp.protocol = VIR_DOMAIN_CHR_TCP_PROTOCOL_RAW;
8247 8248
        else if ((def->data.tcp.protocol =
                  virDomainChrTcpProtocolTypeFromString(protocol)) < 0) {
8249
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8250
                           _("Unknown protocol '%s'"), protocol);
8251 8252 8253
            goto error;
        }

8254 8255 8256
        break;

    case VIR_DOMAIN_CHR_TYPE_UDP:
8257
        if (!connectService) {
8258 8259
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing source service attribute for char device"));
8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274
            goto error;
        }

        def->data.udp.connectHost = connectHost;
        connectHost = NULL;
        def->data.udp.connectService = connectService;
        connectService = NULL;

        def->data.udp.bindHost = bindHost;
        bindHost = NULL;
        def->data.udp.bindService = bindService;
        bindService = NULL;
        break;

    case VIR_DOMAIN_CHR_TYPE_UNIX:
8275 8276
        /* path can be auto generated */
        if (!path &&
8277 8278
            (!chr_def ||
             chr_def->targetType != VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO)) {
8279 8280
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing source path attribute for char device"));
8281 8282 8283
            goto error;
        }

8284
        def->data.nix.listen = mode != NULL && STRNEQ(mode, "connect");
8285 8286 8287 8288

        def->data.nix.path = path;
        path = NULL;
        break;
8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303

    case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
        if (!channel) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("Missing source channel attribute for char device"));
            goto error;
        }
        if (strspn(channel, SERIAL_CHANNEL_NAME_CHARS) < strlen(channel)) {
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("Invalid character in source channel for char device"));
            goto error;
        }
        def->data.spiceport.channel = channel;
        channel = NULL;
        break;
8304 8305
    }

8306
 cleanup:
8307 8308 8309 8310 8311 8312 8313
    VIR_FREE(mode);
    VIR_FREE(protocol);
    VIR_FREE(bindHost);
    VIR_FREE(bindService);
    VIR_FREE(connectHost);
    VIR_FREE(connectService);
    VIR_FREE(path);
8314
    VIR_FREE(channel);
8315

8316 8317
    return remaining;

8318
 error:
8319 8320 8321 8322 8323
    virDomainChrSourceDefClear(def);
    remaining = -1;
    goto cleanup;
}

M
Michal Novotny 已提交
8324 8325 8326 8327
/* Create a new character device definition and set
 * default port.
 */
virDomainChrDefPtr
8328 8329
virDomainChrDefNew(void)
{
M
Michal Novotny 已提交
8330 8331
    virDomainChrDefPtr def = NULL;

8332
    if (VIR_ALLOC(def) < 0)
M
Michal Novotny 已提交
8333 8334 8335 8336 8337 8338
        return NULL;

    def->target.port = -1;
    return def;
}

8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375
/* Parse the XML definition for a character device
 * @param node XML nodeset to parse for net definition
 *
 * The XML we're dealing with looks like
 *
 * <serial type="pty">
 *   <source path="/dev/pts/3"/>
 *   <target port="1"/>
 * </serial>
 *
 * <serial type="dev">
 *   <source path="/dev/ttyS0"/>
 *   <target port="1"/>
 * </serial>
 *
 * <serial type="tcp">
 *   <source mode="connect" host="0.0.0.0" service="2445"/>
 *   <target port="1"/>
 * </serial>
 *
 * <serial type="tcp">
 *   <source mode="bind" host="0.0.0.0" service="2445"/>
 *   <target port="1"/>
 *   <protocol type='raw'/>
 * </serial>
 *
 * <serial type="udp">
 *   <source mode="bind" host="0.0.0.0" service="2445"/>
 *   <source mode="connect" host="0.0.0.0" service="2445"/>
 *   <target port="1"/>
 * </serial>
 *
 * <serial type="unix">
 *   <source mode="bind" path="/tmp/foo"/>
 *   <target port="1"/>
 * </serial>
 *
8376 8377 8378 8379 8380
 * <serial type="nmdm">
 *   <source master="/dev/nmdm0A" slave="/dev/nmdm0B"/>
 *   <target port="1">
 * </serial>
 *
8381 8382
 */
static virDomainChrDefPtr
8383
virDomainChrDefParseXML(xmlXPathContextPtr ctxt,
8384
                        xmlNodePtr node,
8385 8386
                        virSecurityLabelDefPtr* vmSeclabels,
                        int nvmSeclabels,
E
Eric Blake 已提交
8387 8388
                        unsigned int flags)
{
8389 8390 8391 8392
    xmlNodePtr cur;
    char *type = NULL;
    const char *nodeName;
    virDomainChrDefPtr def;
8393
    bool seenTarget = false;
8394

M
Michal Novotny 已提交
8395
    if (!(def = virDomainChrDefNew()))
8396 8397 8398 8399 8400 8401
        return NULL;

    type = virXMLPropString(node, "type");
    if (type == NULL) {
        def->source.type = VIR_DOMAIN_CHR_TYPE_PTY;
    } else if ((def->source.type = virDomainChrTypeFromString(type)) < 0) {
8402
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8403 8404
                       _("unknown type presented to host for character device: %s"),
                       type);
8405 8406 8407 8408 8409
        goto error;
    }

    nodeName = (const char *) node->name;
    if ((def->deviceType = virDomainChrDeviceTypeFromString(nodeName)) < 0) {
8410
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8411 8412
                       _("unknown character device type: %s"),
                       nodeName);
8413 8414 8415
    }

    cur = node->children;
8416 8417 8418 8419
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if (xmlStrEqual(cur->name, BAD_CAST "target")) {
                seenTarget = true;
8420
                if (virDomainChrDefParseTargetXML(def, cur, flags) < 0)
8421
                    goto error;
8422 8423
            }
        }
8424
        cur = cur->next;
8425 8426
    }

8427
    if (!seenTarget &&
8428
        ((def->targetType = virDomainChrDefaultTargetType(def->deviceType)) < 0))
8429 8430
        goto cleanup;

8431 8432 8433 8434
    if (virDomainChrSourceDefParseXML(&def->source, node->children, flags, def,
                                      ctxt, vmSeclabels, nvmSeclabels) < 0)
        goto error;

E
Eric Blake 已提交
8435 8436
    if (def->source.type == VIR_DOMAIN_CHR_TYPE_SPICEVMC) {
        if (def->targetType != VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO) {
8437 8438 8439
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("spicevmc device type only supports "
                             "virtio"));
E
Eric Blake 已提交
8440 8441 8442 8443
            goto error;
        } else {
            def->source.data.spicevmc = VIR_DOMAIN_CHR_SPICEVMC_VDAGENT;
        }
8444 8445
    }

8446
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
8447 8448
        goto error;

G
Guannan Ren 已提交
8449 8450 8451 8452 8453 8454 8455 8456 8457
    if (def->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL &&
        def->targetType == VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_USB &&
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("usb-serial requires address of usb type"));
        goto error;
    }

8458
 cleanup:
8459 8460
    VIR_FREE(type);

8461 8462
    return def;

8463
 error:
8464 8465 8466 8467 8468
    virDomainChrDefFree(def);
    def = NULL;
    goto cleanup;
}

E
Eric Blake 已提交
8469 8470
static virDomainSmartcardDefPtr
virDomainSmartcardDefParseXML(xmlNodePtr node,
E
Eric Blake 已提交
8471
                              unsigned int flags)
E
Eric Blake 已提交
8472 8473 8474 8475 8476
{
    xmlNodePtr cur;
    char *mode = NULL;
    char *type = NULL;
    virDomainSmartcardDefPtr def;
8477
    size_t i;
E
Eric Blake 已提交
8478

8479
    if (VIR_ALLOC(def) < 0)
E
Eric Blake 已提交
8480 8481 8482 8483
        return NULL;

    mode = virXMLPropString(node, "mode");
    if (mode == NULL) {
8484 8485
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing smartcard device mode"));
E
Eric Blake 已提交
8486 8487 8488
        goto error;
    }
    if ((def->type = virDomainSmartcardTypeFromString(mode)) < 0) {
8489
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8490 8491
                       _("unknown smartcard device mode: %s"),
                       mode);
E
Eric Blake 已提交
8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505
        goto error;
    }

    switch (def->type) {
    case VIR_DOMAIN_SMARTCARD_TYPE_HOST:
        break;

    case VIR_DOMAIN_SMARTCARD_TYPE_HOST_CERTIFICATES:
        i = 0;
        cur = node->children;
        while (cur) {
            if (cur->type == XML_ELEMENT_NODE &&
                xmlStrEqual(cur->name, BAD_CAST "certificate")) {
                if (i == 3) {
8506 8507 8508
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("host-certificates mode needs "
                                     "exactly three certificates"));
E
Eric Blake 已提交
8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525
                    goto error;
                }
                def->data.cert.file[i] = (char *)xmlNodeGetContent(cur);
                if (!def->data.cert.file[i]) {
                    virReportOOMError();
                    goto error;
                }
                i++;
            } else if (cur->type == XML_ELEMENT_NODE &&
                       xmlStrEqual(cur->name, BAD_CAST "database") &&
                       !def->data.cert.database) {
                def->data.cert.database = (char *)xmlNodeGetContent(cur);
                if (!def->data.cert.database) {
                    virReportOOMError();
                    goto error;
                }
                if (*def->data.cert.database != '/') {
8526 8527 8528
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("expecting absolute path: %s"),
                                   def->data.cert.database);
E
Eric Blake 已提交
8529 8530 8531 8532 8533 8534
                    goto error;
                }
            }
            cur = cur->next;
        }
        if (i < 3) {
8535 8536 8537
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("host-certificates mode needs "
                             "exactly three certificates"));
E
Eric Blake 已提交
8538 8539 8540 8541 8542 8543 8544
            goto error;
        }
        break;

    case VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH:
        type = virXMLPropString(node, "type");
        if (type == NULL) {
8545 8546 8547
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("passthrough mode requires a character "
                             "device type attribute"));
E
Eric Blake 已提交
8548 8549 8550
            goto error;
        }
        if ((def->data.passthru.type = virDomainChrTypeFromString(type)) < 0) {
8551
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8552 8553
                           _("unknown type presented to host for "
                             "character device: %s"), type);
E
Eric Blake 已提交
8554 8555 8556 8557
            goto error;
        }

        cur = node->children;
8558 8559
        if (virDomainChrSourceDefParseXML(&def->data.passthru, cur, flags,
                                          NULL, NULL, NULL, 0) < 0)
E
Eric Blake 已提交
8560
            goto error;
8561 8562

        if (def->data.passthru.type == VIR_DOMAIN_CHR_TYPE_SPICEVMC) {
E
Eric Blake 已提交
8563 8564
            def->data.passthru.data.spicevmc
                = VIR_DOMAIN_CHR_SPICEVMC_SMARTCARD;
8565
        }
E
Eric Blake 已提交
8566

E
Eric Blake 已提交
8567 8568 8569
        break;

    default:
8570 8571
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unknown smartcard mode"));
E
Eric Blake 已提交
8572 8573 8574
        goto error;
    }

8575
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
E
Eric Blake 已提交
8576 8577 8578
        goto error;
    if (def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID) {
8579 8580
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Controllers must use the 'ccid' address type"));
E
Eric Blake 已提交
8581 8582 8583
        goto error;
    }

8584
 cleanup:
E
Eric Blake 已提交
8585 8586 8587 8588 8589
    VIR_FREE(mode);
    VIR_FREE(type);

    return def;

8590
 error:
E
Eric Blake 已提交
8591 8592 8593 8594 8595
    virDomainSmartcardDefFree(def);
    def = NULL;
    goto cleanup;
}

8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607
/* Parse the XML definition for a TPM device
 *
 * The XML looks like this:
 *
 * <tpm model='tpm-tis'>
 *   <backend type='passthrough'>
 *     <device path='/dev/tpm0'/>
 *   </backend>
 * </tpm>
 *
 */
static virDomainTPMDefPtr
8608
virDomainTPMDefParseXML(xmlNodePtr node,
8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620
                        xmlXPathContextPtr ctxt,
                        unsigned int flags)
{
    char *type = NULL;
    char *path = NULL;
    char *model = NULL;
    char *backend = NULL;
    virDomainTPMDefPtr def;
    xmlNodePtr save = ctxt->node;
    xmlNodePtr *backends = NULL;
    int nbackends;

8621
    if (VIR_ALLOC(def) < 0)
8622 8623 8624 8625 8626
        return NULL;

    model = virXMLPropString(node, "model");
    if (model != NULL &&
        (int)(def->model = virDomainTPMModelTypeFromString(model)) < 0) {
8627
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644
                       _("Unknown TPM frontend model '%s'"), model);
        goto error;
    } else {
        def->model = VIR_DOMAIN_TPM_MODEL_TIS;
    }

    ctxt->node = node;

    if ((nbackends = virXPathNodeSet("./backend", ctxt, &backends)) < 0)
        goto error;

    if (nbackends > 1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("only one TPM backend is supported"));
        goto error;
    }

8645 8646 8647 8648 8649 8650
    if (nbackends == 0) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing TPM device backend"));
        goto error;
    }

8651 8652 8653 8654 8655 8656 8657
    if (!(backend = virXMLPropString(backends[0], "type"))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing TPM device backend type"));
        goto error;
    }

    if ((int)(def->type = virDomainTPMBackendTypeFromString(backend)) < 0) {
8658
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8659 8660 8661 8662 8663 8664 8665 8666
                       _("Unknown TPM backend type '%s'"),
                       backend);
        goto error;
    }

    switch (def->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
        path = virXPathString("string(./backend/device/@path)", ctxt);
8667
        if (!path && VIR_STRDUP(path, VIR_DOMAIN_TPM_DEFAULT_DEVICE) < 0)
8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679
            goto error;
        def->data.passthrough.source.data.file.path = path;
        def->data.passthrough.source.type = VIR_DOMAIN_CHR_TYPE_DEV;
        path = NULL;
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        goto error;
    }

    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
        goto error;

8680
 cleanup:
8681 8682 8683 8684 8685 8686 8687 8688
    VIR_FREE(type);
    VIR_FREE(path);
    VIR_FREE(model);
    VIR_FREE(backend);
    VIR_FREE(backends);
    ctxt->node = save;
    return def;

8689
 error:
8690 8691 8692 8693 8694
    virDomainTPMDefFree(def);
    def = NULL;
    goto cleanup;
}

8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711
static virDomainPanicDefPtr
virDomainPanicDefParseXML(xmlNodePtr node)
{
    virDomainPanicDefPtr panic;

    if (VIR_ALLOC(panic) < 0)
        return NULL;

    if (virDomainDeviceInfoParseXML(node, NULL, &panic->info, 0) < 0)
        goto error;

    return panic;
 error:
    virDomainPanicDefFree(panic);
    return NULL;
}

8712
/* Parse the XML definition for an input device */
8713
static virDomainInputDefPtr
L
Li Zhang 已提交
8714
virDomainInputDefParseXML(const virDomainDef *dom,
8715
                          xmlNodePtr node,
E
Eric Blake 已提交
8716 8717
                          unsigned int flags)
{
8718 8719 8720 8721
    virDomainInputDefPtr def;
    char *type = NULL;
    char *bus = NULL;

8722
    if (VIR_ALLOC(def) < 0)
8723 8724 8725 8726 8727 8728
        return NULL;

    type = virXMLPropString(node, "type");
    bus = virXMLPropString(node, "bus");

    if (!type) {
8729 8730
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing input device type"));
8731 8732 8733 8734
        goto error;
    }

    if ((def->type = virDomainInputTypeFromString(type)) < 0) {
8735
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8736
                       _("unknown input device type '%s'"), type);
8737 8738 8739 8740 8741
        goto error;
    }

    if (bus) {
        if ((def->bus = virDomainInputBusTypeFromString(bus)) < 0) {
8742
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8743
                           _("unknown input bus type '%s'"), bus);
8744 8745 8746
            goto error;
        }

L
Li Zhang 已提交
8747 8748 8749 8750
        if (STREQ(dom->os.type, "hvm")) {
            if (def->bus == VIR_DOMAIN_INPUT_BUS_PS2 &&
                def->type != VIR_DOMAIN_INPUT_TYPE_MOUSE &&
                def->type != VIR_DOMAIN_INPUT_TYPE_KBD) {
8751 8752 8753
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("ps2 bus does not support %s input device"),
                               type);
8754 8755 8756
                goto error;
            }
            if (def->bus == VIR_DOMAIN_INPUT_BUS_XEN) {
8757 8758 8759
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unsupported input bus %s"),
                               bus);
8760 8761 8762 8763
                goto error;
            }
        } else {
            if (def->bus != VIR_DOMAIN_INPUT_BUS_XEN) {
8764 8765 8766
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unsupported input bus %s"),
                               bus);
8767
            }
L
Li Zhang 已提交
8768 8769
            if (def->type != VIR_DOMAIN_INPUT_TYPE_MOUSE &&
                def->type != VIR_DOMAIN_INPUT_TYPE_KBD) {
8770 8771 8772
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("xen bus does not support %s input device"),
                               type);
8773 8774 8775 8776
                goto error;
            }
        }
    } else {
L
Li Zhang 已提交
8777 8778
        if (STREQ(dom->os.type, "hvm")) {
            if ((def->type == VIR_DOMAIN_INPUT_TYPE_MOUSE ||
8779 8780
                def->type == VIR_DOMAIN_INPUT_TYPE_KBD) &&
                (ARCH_IS_X86(dom->os.arch) || dom->os.arch == VIR_ARCH_NONE)) {
8781
                def->bus = VIR_DOMAIN_INPUT_BUS_PS2;
8782
            } else {
8783
                def->bus = VIR_DOMAIN_INPUT_BUS_USB;
8784
            }
8785 8786 8787 8788 8789
        } else {
            def->bus = VIR_DOMAIN_INPUT_BUS_XEN;
        }
    }

8790
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
8791 8792
        goto error;

8793 8794 8795
    if (def->bus == VIR_DOMAIN_INPUT_BUS_USB &&
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB) {
8796 8797
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Invalid address for a USB device"));
8798 8799 8800
        goto error;
    }

8801
 cleanup:
8802 8803 8804 8805 8806
    VIR_FREE(type);
    VIR_FREE(bus);

    return def;

8807
 error:
8808 8809 8810 8811 8812 8813
    virDomainInputDefFree(def);
    def = NULL;
    goto cleanup;
}


E
Eric Blake 已提交
8814
/* Parse the XML definition for a hub device */
M
Marc-André Lureau 已提交
8815 8816 8817 8818 8819 8820
static virDomainHubDefPtr
virDomainHubDefParseXML(xmlNodePtr node, unsigned int flags)
{
    virDomainHubDefPtr def;
    char *type = NULL;

8821
    if (VIR_ALLOC(def) < 0)
M
Marc-André Lureau 已提交
8822 8823 8824 8825 8826
        return NULL;

    type = virXMLPropString(node, "type");

    if (!type) {
8827 8828
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing hub device type"));
M
Marc-André Lureau 已提交
8829 8830 8831 8832
        goto error;
    }

    if ((def->type = virDomainHubTypeFromString(type)) < 0) {
8833
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8834
                       _("unknown hub device type '%s'"), type);
M
Marc-André Lureau 已提交
8835 8836 8837
        goto error;
    }

8838
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
M
Marc-André Lureau 已提交
8839 8840
        goto error;

8841
 cleanup:
M
Marc-André Lureau 已提交
8842 8843 8844 8845
    VIR_FREE(type);

    return def;

8846
 error:
M
Marc-André Lureau 已提交
8847 8848 8849 8850 8851 8852
    virDomainHubDefFree(def);
    def = NULL;
    goto cleanup;
}


8853 8854
/* Parse the XML definition for a clock timer */
static virDomainTimerDefPtr
8855
virDomainTimerDefParseXML(xmlNodePtr node,
E
Eric Blake 已提交
8856
                          xmlXPathContextPtr ctxt)
8857 8858 8859 8860
{
    char *name = NULL;
    char *present = NULL;
    char *tickpolicy = NULL;
8861
    char *track = NULL;
8862 8863 8864 8865
    char *mode = NULL;

    virDomainTimerDefPtr def;
    xmlNodePtr oldnode = ctxt->node;
8866 8867
    xmlNodePtr catchup;
    int ret;
8868

8869
    if (VIR_ALLOC(def) < 0)
8870 8871 8872 8873 8874 8875
        return NULL;

    ctxt->node = node;

    name = virXMLPropString(node, "name");
    if (name == NULL) {
8876 8877
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing timer name"));
8878 8879 8880
        goto error;
    }
    if ((def->name = virDomainTimerNameTypeFromString(name)) < 0) {
8881
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8882
                       _("unknown timer name '%s'"), name);
8883 8884 8885 8886 8887 8888 8889 8890 8891 8892
        goto error;
    }

    def->present = -1; /* unspecified */
    if ((present = virXMLPropString(node, "present")) != NULL) {
        if (STREQ(present, "yes")) {
            def->present = 1;
        } else if (STREQ(present, "no")) {
            def->present = 0;
        } else {
8893 8894
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown timer present value '%s'"), present);
8895 8896 8897 8898 8899 8900 8901 8902
            goto error;
        }
    }

    def->tickpolicy = -1;
    tickpolicy = virXMLPropString(node, "tickpolicy");
    if (tickpolicy != NULL) {
        if ((def->tickpolicy = virDomainTimerTickpolicyTypeFromString(tickpolicy)) < 0) {
8903
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8904
                           _("unknown timer tickpolicy '%s'"), tickpolicy);
8905 8906 8907 8908
            goto error;
        }
    }

8909 8910 8911 8912
    def->track = -1;
    track = virXMLPropString(node, "track");
    if (track != NULL) {
        if ((def->track = virDomainTimerTrackTypeFromString(track)) < 0) {
8913
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8914
                           _("unknown timer track '%s'"), track);
8915 8916 8917 8918
            goto error;
        }
    }

8919
    ret = virXPathULong("string(./frequency)", ctxt, &def->frequency);
8920 8921
    if (ret == -1) {
        def->frequency = 0;
8922
    } else if (ret < 0) {
8923 8924
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("invalid timer frequency"));
8925 8926 8927 8928 8929 8930 8931
        goto error;
    }

    def->mode = -1;
    mode = virXMLPropString(node, "mode");
    if (mode != NULL) {
        if ((def->mode = virDomainTimerModeTypeFromString(mode)) < 0) {
8932
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8933
                           _("unknown timer mode '%s'"), mode);
8934 8935 8936 8937
            goto error;
        }
    }

8938
    catchup = virXPathNode("./catchup", ctxt);
8939 8940 8941 8942 8943 8944
    if (catchup != NULL) {
        ret = virXPathULong("string(./catchup/@threshold)", ctxt,
                            &def->catchup.threshold);
        if (ret == -1) {
            def->catchup.threshold = 0;
        } else if (ret < 0) {
8945 8946
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("invalid catchup threshold"));
8947 8948 8949 8950 8951 8952 8953
            goto error;
        }

        ret = virXPathULong("string(./catchup/@slew)", ctxt, &def->catchup.slew);
        if (ret == -1) {
            def->catchup.slew = 0;
        } else if (ret < 0) {
8954 8955
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("invalid catchup slew"));
8956 8957 8958 8959 8960 8961 8962
            goto error;
        }

        ret = virXPathULong("string(./catchup/@limit)", ctxt, &def->catchup.limit);
        if (ret == -1) {
            def->catchup.limit = 0;
        } else if (ret < 0) {
8963 8964
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("invalid catchup limit"));
8965 8966 8967 8968
            goto error;
        }
    }

8969
 cleanup:
8970 8971 8972
    VIR_FREE(name);
    VIR_FREE(present);
    VIR_FREE(tickpolicy);
8973
    VIR_FREE(track);
8974 8975 8976 8977 8978
    VIR_FREE(mode);
    ctxt->node = oldnode;

    return def;

8979
 error:
8980 8981 8982 8983
    VIR_FREE(def);
    goto cleanup;
}

8984 8985

static int
8986 8987 8988
virDomainGraphicsAuthDefParseXML(xmlNodePtr node,
                                 virDomainGraphicsAuthDefPtr def,
                                 int type)
8989 8990
{
    char *validTo = NULL;
8991
    char *connected = virXMLPropString(node, "connected");
8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015

    def->passwd = virXMLPropString(node, "passwd");

    if (!def->passwd)
        return 0;

    validTo = virXMLPropString(node, "passwdValidTo");
    if (validTo) {
        char *tmp;
        struct tm tm;
        memset(&tm, 0, sizeof(tm));
        /* Expect: YYYY-MM-DDTHH:MM:SS (%d-%d-%dT%d:%d:%d)  eg 2010-11-28T14:29:01 */
        if (/* year */
            virStrToLong_i(validTo, &tmp, 10, &tm.tm_year) < 0 || *tmp != '-' ||
            /* month */
            virStrToLong_i(tmp+1, &tmp, 10, &tm.tm_mon) < 0 || *tmp != '-' ||
            /* day */
            virStrToLong_i(tmp+1, &tmp, 10, &tm.tm_mday) < 0 || *tmp != 'T' ||
            /* hour */
            virStrToLong_i(tmp+1, &tmp, 10, &tm.tm_hour) < 0 || *tmp != ':' ||
            /* minute */
            virStrToLong_i(tmp+1, &tmp, 10, &tm.tm_min) < 0 || *tmp != ':' ||
            /* second */
            virStrToLong_i(tmp+1, &tmp, 10, &tm.tm_sec) < 0 || *tmp != '\0') {
9016 9017 9018
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot parse password validity time '%s', expect YYYY-MM-DDTHH:MM:SS"),
                           validTo);
9019 9020 9021 9022 9023 9024 9025 9026 9027 9028
            VIR_FREE(validTo);
            VIR_FREE(def->passwd);
            return -1;
        }
        VIR_FREE(validTo);

        tm.tm_year -= 1900; /* Human epoch starts at 0 BC, not 1900BC */
        tm.tm_mon--; /* Humans start months at 1, computers at 0 */

        def->validTo = timegm(&tm);
9029
        def->expires = true;
9030 9031
    }

9032 9033 9034
    if (connected) {
        int action = virDomainGraphicsAuthConnectedTypeFromString(connected);
        if (action <= 0) {
9035 9036 9037
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown connected value %s"),
                           connected);
9038 9039 9040 9041 9042 9043 9044 9045
            VIR_FREE(connected);
            return -1;
        }
        VIR_FREE(connected);

        /* VNC supports connected='keep' only */
        if (type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
            action != VIR_DOMAIN_GRAPHICS_AUTH_CONNECTED_KEEP) {
9046 9047
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("VNC supports connected='keep' only"));
9048 9049 9050 9051 9052 9053
            return -1;
        }

        def->connected = action;
    }

9054 9055 9056
    return 0;
}

9057 9058 9059 9060 9061 9062 9063 9064 9065
static int
virDomainGraphicsListenDefParseXML(virDomainGraphicsListenDefPtr def,
                                   xmlNodePtr node,
                                   unsigned int flags)
{
    int ret = -1;
    char *type     = virXMLPropString(node, "type");
    char *address  = virXMLPropString(node, "address");
    char *network  = virXMLPropString(node, "network");
9066 9067
    char *fromConfig = virXMLPropString(node, "fromConfig");
    int tmp;
9068 9069

    if (!type) {
9070 9071
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("graphics listen type must be specified"));
9072 9073 9074 9075
        goto error;
    }

    if ((def->type = virDomainGraphicsListenTypeFromString(type)) < 0) {
9076
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9077
                       _("unknown graphics listen type '%s'"), type);
9078 9079 9080 9081 9082 9083 9084
        goto error;
    }

    /* address is recognized if either type='address', or if
     * type='network' and we're looking at live XML (i.e. *not*
     * inactive). It is otherwise ignored. */
    if (address && address[0] &&
E
Eric Blake 已提交
9085 9086
        (def->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS ||
         (def->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK &&
9087 9088 9089 9090 9091 9092 9093 9094
          !(flags & VIR_DOMAIN_XML_INACTIVE)))) {
        def->address = address;
        address = NULL;
    }

    if (network && network[0]) {
        if (def->type != VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK) {
            /* network='xxx' never makes sense with anything except
9095
             * type='network' */
9096 9097
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("network attribute not allowed when listen type is not network"));
9098 9099 9100 9101 9102 9103
            goto error;
        }
        def->network = network;
        network = NULL;
    }

9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114
    if (fromConfig &&
        flags & VIR_DOMAIN_XML_INTERNAL_STATUS) {
        if (virStrToLong_i(fromConfig, NULL, 10, &tmp) < 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid fromConfig value: %s"),
                           fromConfig);
            goto error;
        }
        def->fromConfig = tmp != 0;
    }

9115
    ret = 0;
9116
 error:
9117 9118 9119 9120 9121
    if (ret < 0)
        virDomainGraphicsListenDefClear(def);
    VIR_FREE(type);
    VIR_FREE(address);
    VIR_FREE(network);
9122
    VIR_FREE(fromConfig);
9123 9124 9125
    return ret;
}

9126

9127 9128
/* Parse the XML definition for a graphics device */
static virDomainGraphicsDefPtr
9129 9130 9131
virDomainGraphicsDefParseXML(xmlNodePtr node,
                             xmlXPathContextPtr ctxt,
                             unsigned int flags)
E
Eric Blake 已提交
9132
{
9133 9134
    virDomainGraphicsDefPtr def;
    char *type = NULL;
9135 9136 9137 9138
    int nListens;
    xmlNodePtr *listenNodes = NULL;
    char *listenAddr = NULL;
    xmlNodePtr save = ctxt->node;
9139

9140
    if (VIR_ALLOC(def) < 0)
9141 9142
        return NULL;

9143 9144
    ctxt->node = node;

9145 9146 9147
    type = virXMLPropString(node, "type");

    if (!type) {
9148 9149
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing graphics device type"));
9150 9151 9152 9153
        goto error;
    }

    if ((def->type = virDomainGraphicsTypeFromString(type)) < 0) {
9154
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9155
                       _("unknown graphics device type '%s'"), type);
9156 9157 9158
        goto error;
    }

E
Eric Blake 已提交
9159 9160 9161
    if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC ||
        def->type == VIR_DOMAIN_GRAPHICS_TYPE_RDP ||
        def->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE) {
9162 9163 9164 9165 9166 9167 9168

        /* parse the <listen> subelements for graphics types that support it */
        nListens = virXPathNodeSet("./listen", ctxt, &listenNodes);
        if (nListens < 0)
            goto error;

        if (nListens > 0) {
9169
            size_t i;
9170

9171
            if (VIR_ALLOC_N(def->listens, nListens) < 0)
9172 9173
                goto error;

9174 9175 9176
            for (i = 0; i < nListens; i++) {
                int ret = virDomainGraphicsListenDefParseXML(&def->listens[i],
                                                             listenNodes[i],
9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205
                                                             flags);
                if (ret < 0)
                    goto error;
                def->nListens++;
            }
            VIR_FREE(listenNodes);
        }

        /* listen attribute of <graphics> is also supported by these,
         * but must match the 'address' attribute of the first listen
         * that is type='address' (if present) */
        listenAddr = virXMLPropString(node, "listen");
        if (listenAddr && !listenAddr[0])
            VIR_FREE(listenAddr);

        if (listenAddr) {
            if (def->nListens == 0) {
                /* There were no <listen> elements, so we can just
                 * directly set listenAddr as listens[0]->address */
                if (virDomainGraphicsListenSetAddress(def, 0, listenAddr,
                                                      -1, true) < 0)
                    goto error;
            } else {
                /* There is at least 1 listen element, so we look for
                 * the first listen of type='address', and make sure
                 * its address matches the listen attribute from
                 * graphics. */
                bool matched = false;
                const char *found = NULL;
9206
                size_t i;
9207

9208 9209
                for (i = 0; i < nListens; i++) {
                    if (virDomainGraphicsListenGetType(def, i)
9210
                        == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS) {
9211
                        found = virDomainGraphicsListenGetAddress(def, i);
9212
                        if (STREQ_NULLABLE(found, listenAddr))
9213 9214 9215 9216 9217
                            matched = true;
                        break;
                    }
                }
                if (!matched) {
9218 9219 9220 9221
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("graphics listen attribute %s must match address "
                                     "attribute of first listen element (found %s)"),
                                   listenAddr, found ? found : "none");
9222 9223 9224 9225 9226 9227
                    goto error;
                }
            }
        }
    }

9228 9229
    if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC) {
        char *port = virXMLPropString(node, "port");
M
Martin Kletzander 已提交
9230
        char *websocket = virXMLPropString(node, "websocket");
9231
        char *sharePolicy = virXMLPropString(node, "sharePolicy");
9232 9233 9234 9235
        char *autoport;

        if (port) {
            if (virStrToLong_i(port, NULL, 10, &def->data.vnc.port) < 0) {
9236 9237
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("cannot parse vnc port %s"), port);
9238 9239 9240 9241 9242 9243
                VIR_FREE(port);
                goto error;
            }
            VIR_FREE(port);
            /* Legacy compat syntax, used -1 for auto-port */
            if (def->data.vnc.port == -1) {
9244 9245
                if (flags & VIR_DOMAIN_XML_INACTIVE)
                    def->data.vnc.port = 0;
9246
                def->data.vnc.autoport = true;
9247 9248 9249
            }
        } else {
            def->data.vnc.port = 0;
9250
            def->data.vnc.autoport = true;
9251 9252 9253 9254
        }

        if ((autoport = virXMLPropString(node, "autoport")) != NULL) {
            if (STREQ(autoport, "yes")) {
9255 9256
                if (flags & VIR_DOMAIN_XML_INACTIVE)
                    def->data.vnc.port = 0;
9257
                def->data.vnc.autoport = true;
9258 9259 9260 9261
            }
            VIR_FREE(autoport);
        }

M
Martin Kletzander 已提交
9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273
        if (websocket) {
            if (virStrToLong_i(websocket,
                               NULL, 10,
                               &def->data.vnc.websocket) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("cannot parse vnc WebSocket port %s"), websocket);
                VIR_FREE(websocket);
                goto error;
            }
            VIR_FREE(websocket);
        }

9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288
        if (sharePolicy) {
            int policy =
               virDomainGraphicsVNCSharePolicyTypeFromString(sharePolicy);

            if (policy < 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown vnc display sharing policy '%s'"), sharePolicy);
                VIR_FREE(sharePolicy);
                goto error;
            } else {
                def->data.vnc.sharePolicy = policy;
            }
            VIR_FREE(sharePolicy);
        }

9289
        def->data.vnc.socket = virXMLPropString(node, "socket");
9290
        def->data.vnc.keymap = virXMLPropString(node, "keymap");
9291

9292 9293
        if (virDomainGraphicsAuthDefParseXML(node, &def->data.vnc.auth,
                                             def->type) < 0)
9294
            goto error;
9295
    } else if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL) {
9296 9297 9298 9299
        char *fullscreen = virXMLPropString(node, "fullscreen");

        if (fullscreen != NULL) {
            if (STREQ(fullscreen, "yes")) {
9300
                def->data.sdl.fullscreen = true;
9301
            } else if (STREQ(fullscreen, "no")) {
9302
                def->data.sdl.fullscreen = false;
9303
            } else {
9304 9305
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unknown fullscreen value '%s'"), fullscreen);
9306 9307 9308 9309
                VIR_FREE(fullscreen);
                goto error;
            }
            VIR_FREE(fullscreen);
E
Eric Blake 已提交
9310
        } else {
9311
            def->data.sdl.fullscreen = false;
E
Eric Blake 已提交
9312
        }
9313 9314
        def->data.sdl.xauth = virXMLPropString(node, "xauth");
        def->data.sdl.display = virXMLPropString(node, "display");
9315 9316 9317 9318 9319 9320 9321 9322
    } else if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_RDP) {
        char *port = virXMLPropString(node, "port");
        char *autoport;
        char *replaceUser;
        char *multiUser;

        if (port) {
            if (virStrToLong_i(port, NULL, 10, &def->data.rdp.port) < 0) {
9323 9324
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("cannot parse rdp port %s"), port);
9325 9326 9327
                VIR_FREE(port);
                goto error;
            }
M
Michal Privoznik 已提交
9328 9329
            /* Legacy compat syntax, used -1 for auto-port */
            if (def->data.rdp.port == -1)
9330
                def->data.rdp.autoport = true;
M
Michal Privoznik 已提交
9331

9332 9333 9334
            VIR_FREE(port);
        } else {
            def->data.rdp.port = 0;
9335
            def->data.rdp.autoport = true;
9336 9337 9338
        }

        if ((autoport = virXMLPropString(node, "autoport")) != NULL) {
M
Michal Privoznik 已提交
9339
            if (STREQ(autoport, "yes"))
9340
                def->data.rdp.autoport = true;
M
Michal Privoznik 已提交
9341

9342 9343 9344
            VIR_FREE(autoport);
        }

M
Michal Privoznik 已提交
9345 9346 9347
        if (def->data.rdp.autoport && (flags & VIR_DOMAIN_XML_INACTIVE))
            def->data.rdp.port = 0;

9348
        if ((replaceUser = virXMLPropString(node, "replaceUser")) != NULL) {
9349
            if (STREQ(replaceUser, "yes"))
9350
                def->data.rdp.replaceUser = true;
9351 9352 9353 9354
            VIR_FREE(replaceUser);
        }

        if ((multiUser = virXMLPropString(node, "multiUser")) != NULL) {
9355
            if (STREQ(multiUser, "yes"))
9356
                def->data.rdp.multiUser = true;
9357 9358 9359 9360 9361 9362 9363 9364
            VIR_FREE(multiUser);
        }

    } else if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP) {
        char *fullscreen = virXMLPropString(node, "fullscreen");

        if (fullscreen != NULL) {
            if (STREQ(fullscreen, "yes")) {
9365
                def->data.desktop.fullscreen = true;
9366
            } else if (STREQ(fullscreen, "no")) {
9367
                def->data.desktop.fullscreen = false;
9368
            } else {
9369 9370
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unknown fullscreen value '%s'"), fullscreen);
9371 9372 9373 9374
                VIR_FREE(fullscreen);
                goto error;
            }
            VIR_FREE(fullscreen);
E
Eric Blake 已提交
9375
        } else {
9376
            def->data.desktop.fullscreen = false;
E
Eric Blake 已提交
9377
        }
9378 9379

        def->data.desktop.display = virXMLPropString(node, "display");
9380
    } else if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE) {
9381
        xmlNodePtr cur;
9382 9383 9384
        char *port = virXMLPropString(node, "port");
        char *tlsPort;
        char *autoport;
9385 9386
        char *defaultMode;
        int defaultModeVal;
9387 9388 9389

        if (port) {
            if (virStrToLong_i(port, NULL, 10, &def->data.spice.port) < 0) {
9390 9391
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("cannot parse spice port %s"), port);
9392 9393 9394 9395 9396
                VIR_FREE(port);
                goto error;
            }
            VIR_FREE(port);
        } else {
9397
            def->data.spice.port = 0;
9398 9399 9400 9401 9402
        }

        tlsPort = virXMLPropString(node, "tlsPort");
        if (tlsPort) {
            if (virStrToLong_i(tlsPort, NULL, 10, &def->data.spice.tlsPort) < 0) {
9403 9404
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("cannot parse spice tlsPort %s"), tlsPort);
9405 9406 9407 9408 9409 9410 9411 9412 9413
                VIR_FREE(tlsPort);
                goto error;
            }
            VIR_FREE(tlsPort);
        } else {
            def->data.spice.tlsPort = 0;
        }

        if ((autoport = virXMLPropString(node, "autoport")) != NULL) {
M
Michal Privoznik 已提交
9414
            if (STREQ(autoport, "yes"))
9415
                def->data.spice.autoport = true;
9416 9417 9418
            VIR_FREE(autoport);
        }

9419 9420 9421 9422
        def->data.spice.defaultMode = VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_ANY;

        if ((defaultMode = virXMLPropString(node, "defaultMode")) != NULL) {
            if ((defaultModeVal = virDomainGraphicsSpiceChannelModeTypeFromString(defaultMode)) < 0) {
9423
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9424 9425
                               _("unknown default spice channel mode %s"),
                               defaultMode);
9426 9427 9428 9429 9430 9431 9432
                VIR_FREE(defaultMode);
                goto error;
            }
            def->data.spice.defaultMode = defaultModeVal;
            VIR_FREE(defaultMode);
        }

M
Michal Privoznik 已提交
9433 9434
        if (def->data.spice.port == -1 && def->data.spice.tlsPort == -1) {
            /* Legacy compat syntax, used -1 for auto-port */
9435
            def->data.spice.autoport = true;
M
Michal Privoznik 已提交
9436 9437 9438 9439 9440 9441 9442
        }

        if (def->data.spice.autoport && (flags & VIR_DOMAIN_XML_INACTIVE)) {
            def->data.spice.port = 0;
            def->data.spice.tlsPort = 0;
        }

9443
        def->data.spice.keymap = virXMLPropString(node, "keymap");
9444

9445 9446
        if (virDomainGraphicsAuthDefParseXML(node, &def->data.spice.auth,
                                             def->type) < 0)
9447
            goto error;
9448 9449 9450 9451 9452

        cur = node->children;
        while (cur != NULL) {
            if (cur->type == XML_ELEMENT_NODE) {
                if (xmlStrEqual(cur->name, BAD_CAST "channel")) {
9453
                    char *name, *mode;
9454 9455 9456 9457 9458
                    int nameval, modeval;
                    name = virXMLPropString(cur, "name");
                    mode = virXMLPropString(cur, "mode");

                    if (!name || !mode) {
9459 9460
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("spice channel missing name/mode"));
E
Eric Blake 已提交
9461 9462
                        VIR_FREE(name);
                        VIR_FREE(mode);
9463 9464 9465 9466
                        goto error;
                    }

                    if ((nameval = virDomainGraphicsSpiceChannelNameTypeFromString(name)) < 0) {
9467
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9468 9469
                                       _("unknown spice channel name %s"),
                                       name);
E
Eric Blake 已提交
9470 9471
                        VIR_FREE(name);
                        VIR_FREE(mode);
9472 9473 9474
                        goto error;
                    }
                    if ((modeval = virDomainGraphicsSpiceChannelModeTypeFromString(mode)) < 0) {
9475
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9476 9477
                                       _("unknown spice channel mode %s"),
                                       mode);
E
Eric Blake 已提交
9478 9479
                        VIR_FREE(name);
                        VIR_FREE(mode);
9480 9481
                        goto error;
                    }
E
Eric Blake 已提交
9482 9483
                    VIR_FREE(name);
                    VIR_FREE(mode);
9484 9485

                    def->data.spice.channels[nameval] = modeval;
9486
                } else if (xmlStrEqual(cur->name, BAD_CAST "image")) {
9487
                    char *compression = virXMLPropString(cur, "compression");
9488 9489 9490
                    int compressionVal;

                    if (!compression) {
9491 9492
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("spice image missing compression"));
9493 9494 9495 9496 9497
                        goto error;
                    }

                    if ((compressionVal =
                         virDomainGraphicsSpiceImageCompressionTypeFromString(compression)) <= 0) {
9498 9499 9500
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                       _("unknown spice image compression %s"),
                                       compression);
9501 9502 9503 9504 9505 9506 9507
                        VIR_FREE(compression);
                        goto error;
                    }
                    VIR_FREE(compression);

                    def->data.spice.image = compressionVal;
                } else if (xmlStrEqual(cur->name, BAD_CAST "jpeg")) {
9508
                    char *compression = virXMLPropString(cur, "compression");
9509 9510 9511
                    int compressionVal;

                    if (!compression) {
9512 9513
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("spice jpeg missing compression"));
9514 9515 9516 9517 9518
                        goto error;
                    }

                    if ((compressionVal =
                         virDomainGraphicsSpiceJpegCompressionTypeFromString(compression)) <= 0) {
9519 9520 9521
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                       _("unknown spice jpeg compression %s"),
                                       compression);
9522 9523 9524 9525 9526 9527 9528
                        VIR_FREE(compression);
                        goto error;
                    }
                    VIR_FREE(compression);

                    def->data.spice.jpeg = compressionVal;
                } else if (xmlStrEqual(cur->name, BAD_CAST "zlib")) {
9529
                    char *compression = virXMLPropString(cur, "compression");
9530 9531 9532
                    int compressionVal;

                    if (!compression) {
9533 9534
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("spice zlib missing compression"));
9535 9536 9537 9538 9539
                        goto error;
                    }

                    if ((compressionVal =
                         virDomainGraphicsSpiceZlibCompressionTypeFromString(compression)) <= 0) {
9540 9541 9542
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                       _("unknown spice zlib compression %s"),
                                       compression);
9543 9544 9545
                        VIR_FREE(compression);
                        goto error;
                    }
9546
                    VIR_FREE(compression);
9547 9548 9549

                    def->data.spice.zlib = compressionVal;
                } else if (xmlStrEqual(cur->name, BAD_CAST "playback")) {
9550
                    char *compression = virXMLPropString(cur, "compression");
9551 9552 9553
                    int compressionVal;

                    if (!compression) {
9554 9555
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("spice playback missing compression"));
9556 9557 9558 9559
                        goto error;
                    }

                    if ((compressionVal =
J
Ján Tomko 已提交
9560
                         virTristateSwitchTypeFromString(compression)) <= 0) {
9561
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9562
                                       _("unknown spice playback compression"));
9563 9564 9565 9566 9567 9568 9569
                        VIR_FREE(compression);
                        goto error;

                    }
                    VIR_FREE(compression);

                    def->data.spice.playback = compressionVal;
9570
                } else if (xmlStrEqual(cur->name, BAD_CAST "streaming")) {
9571
                    char *mode = virXMLPropString(cur, "mode");
9572 9573 9574
                    int modeVal;

                    if (!mode) {
9575 9576
                        virReportError(VIR_ERR_XML_ERROR, "%s",
                                       _("spice streaming missing mode"));
9577 9578 9579 9580
                        goto error;
                    }
                    if ((modeVal =
                         virDomainGraphicsSpiceStreamingModeTypeFromString(mode)) <= 0) {
9581
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9582
                                       _("unknown spice streaming mode"));
9583 9584 9585 9586 9587 9588 9589
                        VIR_FREE(mode);
                        goto error;

                    }
                    VIR_FREE(mode);

                    def->data.spice.streaming = modeVal;
9590
                } else if (xmlStrEqual(cur->name, BAD_CAST "clipboard")) {
9591
                    char *copypaste = virXMLPropString(cur, "copypaste");
9592 9593 9594
                    int copypasteVal;

                    if (!copypaste) {
9595 9596
                        virReportError(VIR_ERR_XML_ERROR, "%s",
                                       _("spice clipboard missing copypaste"));
9597 9598 9599 9600
                        goto error;
                    }

                    if ((copypasteVal =
J
Ján Tomko 已提交
9601
                         virTristateBoolTypeFromString(copypaste)) <= 0) {
9602
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9603
                                       _("unknown copypaste value '%s'"), copypaste);
9604 9605 9606 9607 9608 9609
                        VIR_FREE(copypaste);
                        goto error;
                    }
                    VIR_FREE(copypaste);

                    def->data.spice.copypaste = copypasteVal;
9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620
                } else if (xmlStrEqual(cur->name, BAD_CAST "filetransfer")) {
                    char *enable = virXMLPropString(cur, "enable");
                    int enableVal;

                    if (!enable) {
                        virReportError(VIR_ERR_XML_ERROR, "%s",
                                       _("spice filetransfer missing enable"));
                        goto error;
                    }

                    if ((enableVal =
J
Ján Tomko 已提交
9621
                         virTristateBoolTypeFromString(enable)) <= 0) {
9622 9623 9624 9625 9626 9627 9628 9629
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                       _("unknown enable value '%s'"), enable);
                        VIR_FREE(enable);
                        goto error;
                    }
                    VIR_FREE(enable);

                    def->data.spice.filetransfer = enableVal;
P
Peng Zhou 已提交
9630
                } else if (xmlStrEqual(cur->name, BAD_CAST "mouse")) {
9631
                    char *mode = virXMLPropString(cur, "mode");
P
Peng Zhou 已提交
9632 9633 9634
                    int modeVal;

                    if (!mode) {
9635 9636
                        virReportError(VIR_ERR_XML_ERROR, "%s",
                                       _("spice mouse missing mode"));
P
Peng Zhou 已提交
9637 9638 9639 9640
                        goto error;
                    }

                    if ((modeVal = virDomainGraphicsSpiceMouseModeTypeFromString(mode)) <= 0) {
9641
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9642 9643
                                       _("unknown mouse mode value '%s'"),
                                       mode);
P
Peng Zhou 已提交
9644 9645 9646 9647 9648 9649
                        VIR_FREE(mode);
                        goto error;
                    }
                    VIR_FREE(mode);

                    def->data.spice.mousemode = modeVal;
9650 9651 9652 9653
                }
            }
            cur = cur->next;
        }
9654 9655
    }

9656
 cleanup:
9657
    VIR_FREE(type);
9658 9659
    VIR_FREE(listenNodes);
    VIR_FREE(listenAddr);
9660

9661
    ctxt->node = save;
9662 9663
    return def;

9664
 error:
9665 9666 9667 9668 9669 9670
    virDomainGraphicsDefFree(def);
    def = NULL;
    goto cleanup;
}


9671
static virDomainSoundCodecDefPtr
9672
virDomainSoundCodecDefParseXML(xmlNodePtr node)
9673 9674 9675 9676
{
    char *type;
    virDomainSoundCodecDefPtr def;

9677
    if (VIR_ALLOC(def) < 0)
9678 9679 9680 9681
        return NULL;

    type = virXMLPropString(node, "type");
    if ((def->type = virDomainSoundCodecTypeFromString(type)) < 0) {
9682
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9683
                       _("unknown codec type '%s'"), type);
9684 9685 9686
        goto error;
    }

9687
 cleanup:
9688 9689 9690 9691
    VIR_FREE(type);

    return def;

9692
 error:
9693 9694 9695 9696 9697 9698
    virDomainSoundCodecDefFree(def);
    def = NULL;
    goto cleanup;
}


9699
static virDomainSoundDefPtr
9700
virDomainSoundDefParseXML(xmlNodePtr node,
9701
                          xmlXPathContextPtr ctxt,
E
Eric Blake 已提交
9702
                          unsigned int flags)
9703
{
9704 9705
    char *model;
    virDomainSoundDefPtr def;
9706
    xmlNodePtr save = ctxt->node;
9707

9708
    if (VIR_ALLOC(def) < 0)
9709 9710
        return NULL;

9711 9712
    ctxt->node = node;

9713 9714
    model = virXMLPropString(node, "model");
    if ((def->model = virDomainSoundModelTypeFromString(model)) < 0) {
9715
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9716
                       _("unknown sound model '%s'"), model);
9717 9718 9719
        goto error;
    }

9720 9721
    if (def->model == VIR_DOMAIN_SOUND_MODEL_ICH6 ||
        def->model == VIR_DOMAIN_SOUND_MODEL_ICH9) {
9722 9723 9724 9725 9726 9727 9728 9729 9730
        int ncodecs;
        xmlNodePtr *codecNodes = NULL;

        /* parse the <codec> subelements for sound models that support it */
        ncodecs = virXPathNodeSet("./codec", ctxt, &codecNodes);
        if (ncodecs < 0)
            goto error;

        if (ncodecs > 0) {
9731
            size_t i;
9732 9733 9734 9735 9736 9737

            if (VIR_ALLOC_N(def->codecs, ncodecs) < 0) {
                VIR_FREE(codecNodes);
                goto error;
            }

9738 9739
            for (i = 0; i < ncodecs; i++) {
                virDomainSoundCodecDefPtr codec = virDomainSoundCodecDefParseXML(codecNodes[i]);
9740 9741
                if (codec == NULL) {
                    VIR_FREE(codecNodes);
9742
                    goto error;
9743
                }
9744 9745 9746 9747 9748 9749 9750 9751

                codec->cad = def->ncodecs; /* that will do for now */
                def->codecs[def->ncodecs++] = codec;
            }
            VIR_FREE(codecNodes);
        }
    }

9752
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
9753 9754
        goto error;

9755
 cleanup:
9756 9757
    VIR_FREE(model);

9758
    ctxt->node = save;
9759 9760
    return def;

9761
 error:
9762 9763 9764 9765 9766
    virDomainSoundDefFree(def);
    def = NULL;
    goto cleanup;
}

9767

R
Richard Jones 已提交
9768
static virDomainWatchdogDefPtr
9769
virDomainWatchdogDefParseXML(xmlNodePtr node,
E
Eric Blake 已提交
9770
                             unsigned int flags)
9771
{
R
Richard Jones 已提交
9772 9773 9774 9775 9776

    char *model = NULL;
    char *action = NULL;
    virDomainWatchdogDefPtr def;

9777
    if (VIR_ALLOC(def) < 0)
R
Richard Jones 已提交
9778 9779
        return NULL;

9780
    model = virXMLPropString(node, "model");
R
Richard Jones 已提交
9781
    if (model == NULL) {
9782 9783
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("watchdog must contain model name"));
R
Richard Jones 已提交
9784 9785
        goto error;
    }
9786
    def->model = virDomainWatchdogModelTypeFromString(model);
R
Richard Jones 已提交
9787
    if (def->model < 0) {
9788
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9789
                       _("unknown watchdog model '%s'"), model);
R
Richard Jones 已提交
9790 9791 9792
        goto error;
    }

9793
    action = virXMLPropString(node, "action");
9794
    if (action == NULL) {
R
Richard Jones 已提交
9795
        def->action = VIR_DOMAIN_WATCHDOG_ACTION_RESET;
9796
    } else {
9797
        def->action = virDomainWatchdogActionTypeFromString(action);
R
Richard Jones 已提交
9798
        if (def->action < 0) {
9799
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9800
                           _("unknown watchdog action '%s'"), action);
R
Richard Jones 已提交
9801 9802 9803 9804
            goto error;
        }
    }

9805
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
9806 9807
        goto error;

9808
 cleanup:
9809 9810
    VIR_FREE(action);
    VIR_FREE(model);
R
Richard Jones 已提交
9811 9812 9813

    return def;

9814
 error:
9815
    virDomainWatchdogDefFree(def);
R
Richard Jones 已提交
9816 9817 9818 9819 9820
    def = NULL;
    goto cleanup;
}


9821
static virDomainRNGDefPtr
9822
virDomainRNGDefParseXML(xmlNodePtr node,
9823 9824 9825
                        xmlXPathContextPtr ctxt,
                        unsigned int flags)
{
9826 9827 9828
    char *model = NULL;
    char *backend = NULL;
    char *type = NULL;
9829 9830 9831 9832 9833
    virDomainRNGDefPtr def;
    xmlNodePtr save = ctxt->node;
    xmlNodePtr *backends = NULL;
    int nbackends;

9834
    if (VIR_ALLOC(def) < 0)
9835 9836 9837 9838 9839 9840 9841 9842
        return NULL;

    if (!(model = virXMLPropString(node, "model"))) {
        virReportError(VIR_ERR_XML_ERROR, "%s", _("missing RNG device model"));
        goto error;
    }

    if ((def->model = virDomainRNGModelTypeFromString(model)) < 0) {
9843
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, _("unknown RNG model '%s'"), model);
9844 9845 9846 9847 9848
        goto error;
    }

    ctxt->node = node;

9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861
    if (virXPathUInt("string(./rate/@bytes)", ctxt, &def->rate) < -1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("invalid RNG rate bytes value"));
        goto error;
    }

    if (def->rate > 0 &&
        virXPathUInt("string(./rate/@period)", ctxt, &def->period) < -1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("invalid RNG rate period value"));
        goto error;
    }

9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877
    if ((nbackends = virXPathNodeSet("./backend", ctxt, &backends)) < 0)
        goto error;

    if (nbackends != 1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("only one RNG backend is supported"));
        goto error;
    }

    if (!(backend = virXMLPropString(backends[0], "model"))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing RNG device backend model"));
        goto error;
    }

    if ((def->backend = virDomainRNGBackendTypeFromString(backend)) < 0) {
9878
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9879 9880 9881 9882
                       _("unknown RNG backend model '%s'"), backend);
        goto error;
    }

9883
    switch ((virDomainRNGBackend) def->backend) {
9884 9885
    case VIR_DOMAIN_RNG_BACKEND_RANDOM:
        def->source.file = virXPathString("string(./backend)", ctxt);
9886 9887
        if (def->source.file &&
            STRNEQ(def->source.file, "/dev/random") &&
9888 9889 9890 9891 9892 9893
            STRNEQ(def->source.file, "/dev/hwrng")) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("file '%s' is not a supported random source"),
                           def->source.file);
            goto error;
        }
9894 9895 9896 9897 9898 9899 9900 9901 9902
        break;

    case VIR_DOMAIN_RNG_BACKEND_EGD:
        if (!(type = virXMLPropString(backends[0], "type"))) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing EGD backend type"));
            goto error;
        }

9903
        if (VIR_ALLOC(def->source.chardev) < 0)
9904 9905 9906 9907
            goto error;

        def->source.chardev->type = virDomainChrTypeFromString(type);
        if (def->source.chardev->type < 0) {
9908
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926
                           _("unknown backend type '%s' for egd"),
                           type);
            goto error;
        }

        if (virDomainChrSourceDefParseXML(def->source.chardev,
                                          backends[0]->children, flags,
                                          NULL, ctxt, NULL, 0) < 0)
            goto error;
        break;

    case VIR_DOMAIN_RNG_BACKEND_LAST:
        break;
    }

    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
        goto error;

9927
 cleanup:
9928 9929 9930 9931 9932 9933 9934
    VIR_FREE(model);
    VIR_FREE(backend);
    VIR_FREE(type);
    VIR_FREE(backends);
    ctxt->node = save;
    return def;

9935
 error:
9936 9937 9938 9939 9940 9941
    virDomainRNGDefFree(def);
    def = NULL;
    goto cleanup;
}


9942
static virDomainMemballoonDefPtr
9943
virDomainMemballoonDefParseXML(xmlNodePtr node,
9944
                               xmlXPathContextPtr ctxt,
E
Eric Blake 已提交
9945
                               unsigned int flags)
9946 9947 9948
{
    char *model;
    virDomainMemballoonDefPtr def;
9949
    xmlNodePtr save = ctxt->node;
9950

9951
    if (VIR_ALLOC(def) < 0)
9952 9953 9954
        return NULL;

    model = virXMLPropString(node, "model");
9955
    if (model == NULL) {
9956
        virReportError(VIR_ERR_XML_ERROR, "%s",
9957
                       _("balloon memory must contain model name"));
9958 9959
        goto error;
    }
9960

9961
    if ((def->model = virDomainMemballoonModelTypeFromString(model)) < 0) {
9962
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9963
                       _("unknown memory balloon model '%s'"), model);
9964 9965 9966
        goto error;
    }

9967 9968 9969 9970 9971 9972 9973
    ctxt->node = node;
    if (virXPathUInt("string(./stats/@period)", ctxt, &def->period) < -1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("invalid statistics collection period"));
        goto error;
    }

9974
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
9975 9976
        goto error;

9977
 cleanup:
9978 9979
    VIR_FREE(model);

9980
    ctxt->node = save;
9981 9982
    return def;

9983
 error:
9984 9985 9986 9987 9988
    virDomainMemballoonDefFree(def);
    def = NULL;
    goto cleanup;
}

L
Li Zhang 已提交
9989
static virDomainNVRAMDefPtr
9990
virDomainNVRAMDefParseXML(xmlNodePtr node,
L
Li Zhang 已提交
9991 9992 9993 9994
                          unsigned int flags)
{
   virDomainNVRAMDefPtr def;

9995
    if (VIR_ALLOC(def) < 0)
L
Li Zhang 已提交
9996 9997 9998 9999 10000 10001 10002
        return NULL;

    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
        goto error;

    return def;

10003
 error:
L
Li Zhang 已提交
10004 10005 10006 10007
    virDomainNVRAMDefFree(def);
    return NULL;
}

10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031
static virDomainShmemDefPtr
virDomainShmemDefParseXML(xmlNodePtr node,
                          xmlXPathContextPtr ctxt,
                          unsigned int flags)
{
    char *tmp = NULL;
    virDomainShmemDefPtr def = NULL;
    virDomainShmemDefPtr ret = NULL;
    xmlNodePtr msi = NULL;
    xmlNodePtr save = ctxt->node;
    xmlNodePtr server = NULL;


    if (VIR_ALLOC(def) < 0)
        return NULL;

    ctxt->node = node;

    if (!(def->name = virXMLPropString(node, "name"))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("shmem element must contain 'name' attribute"));
        goto cleanup;
    }

10032 10033
    if (virDomainParseScaledValue("./size[1]", NULL, ctxt,
                                  &def->size, 1, ULLONG_MAX, false) < 0)
10034 10035
        goto cleanup;

10036
    if ((server = virXPathNode("./server[1]", ctxt))) {
10037 10038 10039 10040 10041 10042 10043
        def->server.enabled = true;

        if ((tmp = virXMLPropString(server, "path")))
            def->server.path = virFileSanitizePath(tmp);
        VIR_FREE(tmp);
    }

10044
    if ((msi = virXPathNode("./msi[1]", ctxt))) {
10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085
        def->msi.enabled = true;

        if ((tmp = virXMLPropString(msi, "vectors")) &&
            virStrToLong_uip(tmp, NULL, 0, &def->msi.vectors) < 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("invalid number of vectors for shmem: '%s'"),
                           tmp);
            goto cleanup;
        }
        VIR_FREE(tmp);

        if ((tmp = virXMLPropString(msi, "ioeventfd")) &&
            (def->msi.ioeventfd = virTristateSwitchTypeFromString(tmp)) <= 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("invalid msi ioeventfd setting for shmem: '%s'"),
                           tmp);
            goto cleanup;
        }
        VIR_FREE(tmp);
    }

    /* msi option is only relevant with a server */
    if (def->msi.enabled && !def->server.enabled) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("msi option is only supported with a server"));
        goto cleanup;
    }

    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
        goto cleanup;


    ret = def;
    def = NULL;
 cleanup:
    ctxt->node = save;
    VIR_FREE(tmp);
    virDomainShmemDefFree(def);
    return ret;
}

10086
static virSysinfoDefPtr
10087
virSysinfoParseXML(xmlNodePtr node,
10088 10089 10090
                  xmlXPathContextPtr ctxt,
                  unsigned char *domUUID,
                  bool uuid_generated)
10091 10092 10093
{
    virSysinfoDefPtr def;
    char *type;
10094
    char *tmpUUID = NULL;
10095 10096

    if (!xmlStrEqual(node->name, BAD_CAST "sysinfo")) {
10097 10098
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("XML does not contain expected 'sysinfo' element"));
10099
        return NULL;
10100 10101
    }

10102
    if (VIR_ALLOC(def) < 0)
10103
        return NULL;
10104 10105 10106

    type = virXMLPropString(node, "type");
    if (type == NULL) {
10107 10108
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("sysinfo must contain a type attribute"));
10109 10110
        goto error;
    }
10111
    if ((def->type = virSysinfoTypeFromString(type)) < 0) {
10112
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10113
                       _("unknown sysinfo type '%s'"), type);
10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124
        goto error;
    }


    /* Extract BIOS related metadata */
    def->bios_vendor =
        virXPathString("string(bios/entry[@name='vendor'])", ctxt);
    def->bios_version =
        virXPathString("string(bios/entry[@name='version'])", ctxt);
    def->bios_date =
        virXPathString("string(bios/entry[@name='date'])", ctxt);
10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147
    if (def->bios_date != NULL) {
        char *ptr;
        int month, day, year;

        /* Validate just the format of the date
         * Expect mm/dd/yyyy or mm/dd/yy,
         * where yy must be 00->99 and would be assumed to be 19xx
         * a yyyy date should be 1900 and beyond
         */
        if (virStrToLong_i(def->bios_date, &ptr, 10, &month) < 0 ||
            *ptr != '/' ||
            virStrToLong_i(ptr + 1, &ptr, 10, &day) < 0 ||
            *ptr != '/' ||
            virStrToLong_i(ptr + 1, &ptr, 10, &year) < 0 ||
            *ptr != '\0' ||
            (month < 1 || month > 12) ||
            (day < 1 || day > 31) ||
            (year < 0 || (year >= 100 && year < 1900))) {
            virReportError(VIR_ERR_XML_DETAIL, "%s",
                           _("Invalid BIOS 'date' format"));
            goto error;
        }
    }
10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159
    def->bios_release =
        virXPathString("string(bios/entry[@name='release'])", ctxt);

    /* Extract system related metadata */
    def->system_manufacturer =
        virXPathString("string(system/entry[@name='manufacturer'])", ctxt);
    def->system_product =
        virXPathString("string(system/entry[@name='product'])", ctxt);
    def->system_version =
        virXPathString("string(system/entry[@name='version'])", ctxt);
    def->system_serial =
        virXPathString("string(system/entry[@name='serial'])", ctxt);
10160 10161 10162 10163 10164 10165 10166 10167 10168
    tmpUUID = virXPathString("string(system/entry[@name='uuid'])", ctxt);
    if (tmpUUID) {
        unsigned char uuidbuf[VIR_UUID_BUFLEN];
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        if (virUUIDParse(tmpUUID, uuidbuf) < 0) {
            virReportError(VIR_ERR_XML_DETAIL,
                           "%s", _("malformed <sysinfo> uuid element"));
            goto error;
        }
10169
        if (uuid_generated) {
10170
            memcpy(domUUID, uuidbuf, VIR_UUID_BUFLEN);
10171
        } else if (memcmp(domUUID, uuidbuf, VIR_UUID_BUFLEN) != 0) {
10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186
            virReportError(VIR_ERR_XML_DETAIL, "%s",
                           _("UUID mismatch between <uuid> and "
                             "<sysinfo>"));
            goto error;
        }
        /* Although we've validated the UUID as good, virUUIDParse() is
         * lax with respect to allowing extraneous "-" and " ", but the
         * underlying hypervisor may be less forgiving. Use virUUIDFormat()
         * to validate format in xml is right. If not, then format it
         * properly so that it's used correctly later.
         */
        virUUIDFormat(uuidbuf, uuidstr);
        if (VIR_STRDUP(def->system_uuid, uuidstr) < 0)
            goto error;
    }
10187 10188
    def->system_sku =
        virXPathString("string(system/entry[@name='sku'])", ctxt);
E
Eric Blake 已提交
10189 10190
    def->system_family =
        virXPathString("string(system/entry[@name='family'])", ctxt);
10191

10192
 cleanup:
10193
    VIR_FREE(type);
10194
    VIR_FREE(tmpUUID);
10195
    return def;
10196

10197
 error:
10198 10199 10200 10201
    virSysinfoDefFree(def);
    def = NULL;
    goto cleanup;
}
10202

10203
unsigned int
10204
virDomainVideoDefaultRAM(const virDomainDef *def,
10205
                         const virDomainVideoType type)
10206
{
10207 10208 10209 10210
    /* Defer setting default vram to the Xen drivers */
    if (def->virtType == VIR_DOMAIN_VIRT_XEN)
        return 0;

10211 10212 10213 10214 10215 10216
    switch (type) {
    case VIR_DOMAIN_VIDEO_TYPE_VGA:
    case VIR_DOMAIN_VIDEO_TYPE_CIRRUS:
    case VIR_DOMAIN_VIDEO_TYPE_VMVGA:
        if (def->virtType == VIR_DOMAIN_VIRT_VBOX)
            return 8 * 1024;
M
Matthias Bolte 已提交
10217 10218
        else if (def->virtType == VIR_DOMAIN_VIRT_VMWARE)
            return 4 * 1024;
10219
        else
10220
            return 16 * 1024;
10221 10222 10223 10224 10225 10226
        break;

    case VIR_DOMAIN_VIDEO_TYPE_XEN:
        /* Original Xen PVFB hardcoded to 4 MB */
        return 4 * 1024;

10227
    case VIR_DOMAIN_VIDEO_TYPE_QXL:
10228
        /* QEMU use 64M as the minimal video memory for qxl device */
10229 10230
        return 64 * 1024;

10231 10232 10233 10234 10235 10236 10237
    default:
        return 0;
    }
}


int
10238
virDomainVideoDefaultType(const virDomainDef *def)
10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249
{
    switch (def->virtType) {
    case VIR_DOMAIN_VIRT_TEST:
    case VIR_DOMAIN_VIRT_QEMU:
    case VIR_DOMAIN_VIRT_KQEMU:
    case VIR_DOMAIN_VIRT_KVM:
    case VIR_DOMAIN_VIRT_XEN:
        if (def->os.type &&
            (STREQ(def->os.type, "xen") ||
             STREQ(def->os.type, "linux")))
            return VIR_DOMAIN_VIDEO_TYPE_XEN;
10250
        else if ARCH_IS_PPC64(def->os.arch)
10251
            return VIR_DOMAIN_VIDEO_TYPE_VGA;
10252 10253 10254 10255 10256 10257
        else
            return VIR_DOMAIN_VIDEO_TYPE_CIRRUS;

    case VIR_DOMAIN_VIRT_VBOX:
        return VIR_DOMAIN_VIDEO_TYPE_VBOX;

M
Matthias Bolte 已提交
10258 10259 10260
    case VIR_DOMAIN_VIRT_VMWARE:
        return VIR_DOMAIN_VIDEO_TYPE_VMVGA;

10261 10262 10263 10264 10265
    default:
        return -1;
    }
}

10266
static virDomainVideoAccelDefPtr
10267 10268
virDomainVideoAccelDefParseXML(xmlNodePtr node)
{
10269 10270 10271 10272 10273 10274 10275 10276
    xmlNodePtr cur;
    virDomainVideoAccelDefPtr def;
    char *support3d = NULL;
    char *support2d = NULL;

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
E
Eric Blake 已提交
10277
            if (!support3d && !support2d &&
10278 10279 10280 10281 10282 10283 10284 10285
                xmlStrEqual(cur->name, BAD_CAST "acceleration")) {
                support3d = virXMLPropString(cur, "accel3d");
                support2d = virXMLPropString(cur, "accel2d");
            }
        }
        cur = cur->next;
    }

E
Eric Blake 已提交
10286
    if (!support3d && !support2d)
10287
        return NULL;
10288

10289
    if (VIR_ALLOC(def) < 0)
10290 10291 10292 10293
        return NULL;

    if (support3d) {
        if (STREQ(support3d, "yes"))
10294
            def->support3d = true;
10295
        else
10296
            def->support3d = false;
10297 10298 10299 10300 10301
        VIR_FREE(support3d);
    }

    if (support2d) {
        if (STREQ(support2d, "yes"))
10302
            def->support2d = true;
10303
        else
10304
            def->support2d = false;
10305 10306 10307 10308 10309 10310
        VIR_FREE(support2d);
    }

    return def;
}

10311
static virDomainVideoDefPtr
10312 10313
virDomainVideoDefParseXML(xmlNodePtr node,
                          const virDomainDef *dom,
E
Eric Blake 已提交
10314 10315
                          unsigned int flags)
{
10316 10317 10318 10319 10320
    virDomainVideoDefPtr def;
    xmlNodePtr cur;
    char *type = NULL;
    char *heads = NULL;
    char *vram = NULL;
10321
    char *ram = NULL;
10322
    char *vgamem = NULL;
10323
    char *primary = NULL;
10324

10325
    if (VIR_ALLOC(def) < 0)
10326 10327 10328 10329 10330
        return NULL;

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
10331
            if (!type && !vram && !ram && !heads &&
10332 10333
                xmlStrEqual(cur->name, BAD_CAST "model")) {
                type = virXMLPropString(cur, "type");
10334
                ram = virXMLPropString(cur, "ram");
10335
                vram = virXMLPropString(cur, "vram");
10336
                vgamem = virXMLPropString(cur, "vgamem");
10337
                heads = virXMLPropString(cur, "heads");
10338

10339
                if ((primary = virXMLPropString(cur, "primary")) != NULL) {
10340 10341
                    if (STREQ(primary, "yes"))
                        def->primary = 1;
10342 10343
                    VIR_FREE(primary);
                }
10344

10345
                def->accel = virDomainVideoAccelDefParseXML(cur);
10346 10347 10348 10349 10350 10351 10352
            }
        }
        cur = cur->next;
    }

    if (type) {
        if ((def->type = virDomainVideoTypeFromString(type)) < 0) {
10353
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10354
                           _("unknown video model '%s'"), type);
10355 10356 10357 10358
            goto error;
        }
    } else {
        if ((def->type = virDomainVideoDefaultType(dom)) < 0) {
10359 10360
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("missing video model and cannot determine default"));
10361 10362 10363 10364
            goto error;
        }
    }

10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379
    if (ram) {
        if (def->type != VIR_DOMAIN_VIDEO_TYPE_QXL) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("ram attribute only supported for type of qxl"));
            goto error;
        }
        if (virStrToLong_ui(ram, NULL, 10, &def->ram) < 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("cannot parse video ram '%s'"), ram);
            goto error;
        }
    } else if (def->type == VIR_DOMAIN_VIDEO_TYPE_QXL) {
        def->ram = virDomainVideoDefaultRAM(dom, def->type);
    }

10380 10381
    if (vram) {
        if (virStrToLong_ui(vram, NULL, 10, &def->vram) < 0) {
10382
            virReportError(VIR_ERR_XML_ERROR,
10383
                           _("cannot parse video vram '%s'"), vram);
10384 10385 10386 10387 10388 10389
            goto error;
        }
    } else {
        def->vram = virDomainVideoDefaultRAM(dom, def->type);
    }

10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402
    if (vgamem) {
        if (def->type != VIR_DOMAIN_VIDEO_TYPE_QXL) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("vgamem attribute only supported for type of qxl"));
            goto error;
        }
        if (virStrToLong_ui(vgamem, NULL, 10, &def->vgamem) < 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("cannot parse video vgamem '%s'"), vgamem);
            goto error;
        }
    }

10403 10404
    if (heads) {
        if (virStrToLong_ui(heads, NULL, 10, &def->heads) < 0) {
10405 10406
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot parse video heads '%s'"), heads);
10407 10408 10409 10410 10411 10412
            goto error;
        }
    } else {
        def->heads = 1;
    }

10413
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
10414 10415
        goto error;

10416
    VIR_FREE(type);
10417
    VIR_FREE(ram);
10418
    VIR_FREE(vram);
10419
    VIR_FREE(vgamem);
10420 10421 10422 10423
    VIR_FREE(heads);

    return def;

10424
 error:
10425 10426
    virDomainVideoDefFree(def);
    VIR_FREE(type);
10427
    VIR_FREE(ram);
10428
    VIR_FREE(vram);
10429
    VIR_FREE(vgamem);
10430 10431 10432 10433
    VIR_FREE(heads);
    return NULL;
}

10434
static virDomainHostdevDefPtr
10435
virDomainHostdevDefParseXML(virDomainXMLOptionPtr xmlopt,
10436 10437
                            const virDomainDef *vmdef,
                            xmlNodePtr node,
10438
                            xmlXPathContextPtr ctxt,
10439
                            virHashTablePtr bootHash,
E
Eric Blake 已提交
10440
                            unsigned int flags)
10441
{
10442
    virDomainHostdevDefPtr def;
10443 10444 10445
    xmlNodePtr save = ctxt->node;
    char *mode = virXMLPropString(node, "mode");
    char *type = virXMLPropString(node, "type");
10446

10447
    ctxt->node = node;
10448

10449
    if (!(def = virDomainHostdevDefAlloc()))
10450 10451
        goto error;

10452 10453
    if (mode) {
        if ((def->mode = virDomainHostdevModeTypeFromString(mode)) < 0) {
10454
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467
                           _("unknown hostdev mode '%s'"), mode);
            goto error;
        }
    } else {
        def->mode = VIR_DOMAIN_HOSTDEV_MODE_SUBSYS;
    }

    switch (def->mode) {
    case VIR_DOMAIN_HOSTDEV_MODE_SUBSYS:
        /* parse managed/mode/type, and the <source> element */
        if (virDomainHostdevDefParseXMLSubsys(node, ctxt, type, def, flags) < 0)
            goto error;
        break;
10468 10469 10470 10471 10472
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
        /* parse managed/mode/type, and the <source> element */
        if (virDomainHostdevDefParseXMLCaps(node, ctxt, type, def) < 0)
            goto error;
        break;
10473 10474 10475
    default:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unexpected hostdev mode %d"), def->mode);
10476
        goto error;
10477
    }
10478

10479
    if (def->info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
10480
        if (virDomainDeviceInfoParseXML(node, bootHash, def->info,
10481 10482
                                        flags  | VIR_DOMAIN_XML_INTERNAL_ALLOW_BOOT
                                        | VIR_DOMAIN_XML_INTERNAL_ALLOW_ROM) < 0)
10483 10484 10485 10486 10487 10488
            goto error;
    }

    if (def->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
        switch (def->source.subsys.type) {
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
10489 10490
            if (def->info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
                def->info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
10491 10492
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("PCI host devices must use 'pci' address type"));
10493 10494 10495
                goto error;
            }
            break;
H
Han Cheng 已提交
10496
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
10497 10498 10499
            if (def->info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
                virDomainHostdevAssignAddress(xmlopt, vmdef, def) < 0) {

H
Han Cheng 已提交
10500 10501 10502 10503
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("SCSI host devices must have address specified"));
                goto error;
            }
O
Osier Yang 已提交
10504 10505 10506

            if (virXPathBoolean("boolean(./readonly)", ctxt))
                def->readonly = true;
10507 10508
            if (virXPathBoolean("boolean(./shareable)", ctxt))
                def->shareable = true;
H
Han Cheng 已提交
10509
            break;
10510 10511 10512
        }
    }

10513
 cleanup:
10514 10515
    VIR_FREE(type);
    VIR_FREE(mode);
10516
    ctxt->node = save;
10517 10518
    return def;

10519
 error:
10520 10521 10522 10523 10524
    virDomainHostdevDefFree(def);
    def = NULL;
    goto cleanup;
}

10525

10526
static virDomainRedirdevDefPtr
10527
virDomainRedirdevDefParseXML(xmlNodePtr node,
10528
                             virHashTablePtr bootHash,
10529 10530 10531 10532 10533
                             unsigned int flags)
{
    xmlNodePtr cur;
    virDomainRedirdevDefPtr def;
    char *bus, *type = NULL;
10534
    int remaining;
10535

10536
    if (VIR_ALLOC(def) < 0)
10537 10538 10539 10540 10541
        return NULL;

    bus = virXMLPropString(node, "bus");
    if (bus) {
        if ((def->bus = virDomainRedirdevBusTypeFromString(bus)) < 0) {
10542
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10543
                           _("unknown redirdev bus '%s'"), bus);
10544 10545 10546 10547 10548 10549 10550 10551 10552
            goto error;
        }
    } else {
        def->bus = VIR_DOMAIN_REDIRDEV_BUS_USB;
    }

    type = virXMLPropString(node, "type");
    if (type) {
        if ((def->source.chr.type = virDomainChrTypeFromString(type)) < 0) {
10553
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10554
                           _("unknown redirdev character device type '%s'"), type);
10555 10556 10557
            goto error;
        }
    } else {
10558 10559
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing type in redirdev"));
10560 10561 10562 10563
        goto error;
    }

    cur = node->children;
10564 10565 10566 10567 10568 10569 10570
    /* boot gets parsed in virDomainDeviceInfoParseXML
     * source gets parsed in virDomainChrSourceDefParseXML
     * we don't know any of the elements that might remain */
    remaining = virDomainChrSourceDefParseXML(&def->source.chr, cur, flags,
                                              NULL, NULL, NULL, 0);
    if (remaining < 0)
        goto error;
10571

10572
    if (def->source.chr.type == VIR_DOMAIN_CHR_TYPE_SPICEVMC)
10573 10574
        def->source.chr.data.spicevmc = VIR_DOMAIN_CHR_SPICEVMC_USBREDIR;

10575
    if (virDomainDeviceInfoParseXML(node, bootHash, &def->info,
10576
                                    flags | VIR_DOMAIN_XML_INTERNAL_ALLOW_BOOT) < 0)
10577 10578 10579 10580 10581
        goto error;

    if (def->bus == VIR_DOMAIN_REDIRDEV_BUS_USB &&
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB) {
10582 10583
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Invalid address for a USB device"));
10584 10585 10586 10587
        goto error;
    }


10588
 cleanup:
10589 10590 10591 10592
    VIR_FREE(bus);
    VIR_FREE(type);
    return def;

10593
 error:
10594 10595 10596 10597 10598
    virDomainRedirdevDefFree(def);
    def = NULL;
    goto cleanup;
}

10599 10600 10601 10602 10603 10604 10605 10606 10607
/*
 * This is the helper function to convert USB version from a
 * format of JJ.MN to a format of 0xJJMN where JJ is the major
 * version number, M is the minor version number and N is the
 * sub minor version number.
 * e.g. USB 2.0 is reported as 0x0200,
 *      USB 1.1 as 0x0110 and USB 1.0 as 0x0100.
 */
static int
10608 10609
virDomainRedirFilterUSBVersionHelper(const char *version,
                                     virDomainRedirFilterUSBDevDefPtr def)
10610 10611 10612 10613 10614 10615 10616 10617 10618 10619
{
    char *version_copy = NULL;
    char *temp = NULL;
    int ret = -1;
    size_t len;
    size_t fraction_len;
    unsigned int major;
    unsigned int minor;
    unsigned int hex;

10620
    if (VIR_STRDUP(version_copy, version) < 0)
10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656
        return -1;

    len = strlen(version_copy);
    /*
     * The valid format of version is like 01.10, 1.10, 1.1, etc.
     */
    if (len > 5 ||
        !(temp = strchr(version_copy, '.')) ||
        temp - version_copy < 1 ||
        temp - version_copy > 2 ||
        !(fraction_len = strlen(temp + 1)) ||
        fraction_len > 2) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Incorrect USB version format %s"), version);
        goto cleanup;
    }

    *temp = '\0';
    temp++;

    if ((virStrToLong_ui(version_copy, NULL, 0, &major)) < 0 ||
        (virStrToLong_ui(temp, NULL, 0, &minor)) < 0) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("Cannot parse USB version %s"), version);
        goto cleanup;
    }

    hex = (major / 10) << 12 | (major % 10) << 8;
    if (fraction_len == 1)
        hex |= (minor % 10) << 4;
    else
        hex |= (minor / 10) << 4 | (minor % 10) << 0;

    def->version = hex;
    ret = 0;

10657
 cleanup:
10658 10659 10660 10661
    VIR_FREE(version_copy);
    return ret;
}

10662 10663
static virDomainRedirFilterUSBDevDefPtr
virDomainRedirFilterUSBDevDefParseXML(xmlNodePtr node)
10664 10665 10666 10667
{
    char *class;
    char *vendor = NULL, *product = NULL;
    char *version = NULL, *allow = NULL;
10668
    virDomainRedirFilterUSBDevDefPtr def;
10669

10670
    if (VIR_ALLOC(def) < 0)
10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715
        return NULL;

    class = virXMLPropString(node, "class");
    if (class) {
        if ((virStrToLong_i(class, NULL, 0, &def->usbClass)) < 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("Cannot parse USB Class code %s"), class);
            goto error;
        }

        if (def->usbClass != -1 && def->usbClass &~ 0xFF) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid USB Class code %s"), class);
            goto error;
        }
    } else {
        def->usbClass = -1;
    }

    vendor = virXMLPropString(node, "vendor");
    if (vendor) {
        if ((virStrToLong_i(vendor, NULL, 0, &def->vendor)) < 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("Cannot parse USB vendor ID %s"), vendor);
            goto error;
        }
    } else {
        def->vendor = -1;
    }

    product = virXMLPropString(node, "product");
    if (product) {
        if ((virStrToLong_i(product, NULL, 0, &def->product)) < 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("Cannot parse USB product ID %s"), product);
            goto error;
        }
    } else {
        def->product = -1;
    }

    version = virXMLPropString(node, "version");
    if (version) {
        if (STREQ(version, "-1"))
            def->version = -1;
10716
        else if ((virDomainRedirFilterUSBVersionHelper(version, def)) < 0)
10717 10718 10719 10720 10721 10722 10723
            goto error;
    } else {
        def->version = -1;
    }

    allow = virXMLPropString(node, "allow");
    if (allow) {
10724
        if (STREQ(allow, "yes")) {
10725
            def->allow = true;
10726
        } else if (STREQ(allow, "no")) {
10727
            def->allow = false;
10728
        } else {
10729 10730 10731 10732 10733 10734 10735 10736 10737 10738
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Invalid allow value, either 'yes' or 'no'"));
            goto error;
        }
    } else {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Missing allow attribute for USB redirection filter"));
        goto error;
    }

10739
 cleanup:
10740 10741 10742 10743 10744 10745 10746
    VIR_FREE(class);
    VIR_FREE(vendor);
    VIR_FREE(product);
    VIR_FREE(version);
    VIR_FREE(allow);
    return def;

10747
 error:
10748 10749 10750 10751 10752 10753
    VIR_FREE(def);
    def = NULL;
    goto cleanup;
}

static virDomainRedirFilterDefPtr
10754
virDomainRedirFilterDefParseXML(xmlNodePtr node,
10755 10756 10757 10758 10759 10760 10761 10762 10763
                                xmlXPathContextPtr ctxt)
{
    int n;
    size_t i;
    xmlNodePtr *nodes = NULL;
    xmlNodePtr save = ctxt->node;
    virDomainRedirFilterDefPtr def = NULL;

    if (VIR_ALLOC(def) < 0)
10764
        goto error;
10765 10766

    ctxt->node = node;
10767
    if ((n = virXPathNodeSet("./usbdev", ctxt, &nodes)) < 0)
10768 10769 10770
        goto error;

    if (n && VIR_ALLOC_N(def->usbdevs, n) < 0)
10771
        goto error;
10772 10773

    for (i = 0; i < n; i++) {
10774 10775
        virDomainRedirFilterUSBDevDefPtr usbdev =
            virDomainRedirFilterUSBDevDefParseXML(nodes[i]);
10776 10777 10778 10779 10780 10781 10782 10783 10784 10785

        if (!usbdev)
            goto error;
        def->usbdevs[def->nusbdevs++] = usbdev;
    }
    VIR_FREE(nodes);

    ctxt->node = save;
    return def;

10786
 error:
10787 10788 10789 10790 10791
    VIR_FREE(nodes);
    virDomainRedirFilterDefFree(def);
    return NULL;
}

10792 10793 10794 10795 10796 10797 10798
static int
virDomainEventActionParseXML(xmlXPathContextPtr ctxt,
                             const char *name,
                             const char *xpath,
                             int *val,
                             int defaultVal,
                             virEventActionFromStringFunc convFunc)
10799
{
10800
    char *tmp = virXPathString(xpath, ctxt);
10801 10802 10803
    if (tmp == NULL) {
        *val = defaultVal;
    } else {
10804
        *val = convFunc(tmp);
10805
        if (*val < 0) {
10806
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10807
                           _("unknown %s action: %s"), name, tmp);
10808 10809 10810 10811 10812 10813 10814 10815
            VIR_FREE(tmp);
            return -1;
        }
        VIR_FREE(tmp);
    }
    return 0;
}

10816 10817 10818 10819 10820 10821 10822 10823
static int
virDomainPMStateParseXML(xmlXPathContextPtr ctxt,
                         const char *xpath,
                         int *val)
{
    int ret = -1;
    char *tmp = virXPathString(xpath, ctxt);
    if (tmp) {
J
Ján Tomko 已提交
10824
        *val = virTristateBoolTypeFromString(tmp);
10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837
        if (*val < 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown PM state value %s"), tmp);
            goto cleanup;
        }
    }

    ret = 0;
 cleanup:
    VIR_FREE(tmp);
    return ret;
}

10838
virDomainDeviceDefPtr
10839
virDomainDeviceDefParse(const char *xmlStr,
10840
                        const virDomainDef *def,
10841 10842
                        virCapsPtr caps,
                        virDomainXMLOptionPtr xmlopt,
10843
                        unsigned int flags)
10844 10845 10846
{
    xmlDocPtr xml;
    xmlNodePtr node;
10847
    xmlXPathContextPtr ctxt = NULL;
10848 10849
    virDomainDeviceDefPtr dev = NULL;

10850
    if (!(xml = virXMLParseStringCtxt(xmlStr, _("(device_definition)"), &ctxt)))
10851
        goto error;
10852

10853
    node = ctxt->node;
10854

10855
    if (VIR_ALLOC(dev) < 0)
10856 10857
        goto error;

10858 10859 10860 10861 10862 10863 10864 10865 10866
    if ((dev->type = virDomainDeviceTypeFromString((const char *) node->name)) < 0) {
        /* Some crazy mapping of serial, parallel, console and channel to
         * VIR_DOMAIN_DEVICE_CHR. */
        if (xmlStrEqual(node->name, BAD_CAST "channel") ||
            xmlStrEqual(node->name, BAD_CAST "console") ||
            xmlStrEqual(node->name, BAD_CAST "parallel") ||
            xmlStrEqual(node->name, BAD_CAST "serial")) {
            dev->type = VIR_DOMAIN_DEVICE_CHR;
        } else {
10867
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10868 10869 10870 10871 10872 10873 10874 10875
                           _("unknown device type '%s'"),
                           node->name);
            goto error;
        }
    }

    switch ((virDomainDeviceType) dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
10876
        if (!(dev->data.disk = virDomainDiskDefParseXML(xmlopt, node, ctxt,
10877 10878
                                                        NULL, def->seclabels,
                                                        def->nseclabels,
10879
                                                        flags)))
10880
            goto error;
10881 10882
        break;
    case VIR_DOMAIN_DEVICE_LEASE:
10883 10884
        if (!(dev->data.lease = virDomainLeaseDefParseXML(node)))
            goto error;
10885 10886
        break;
    case VIR_DOMAIN_DEVICE_FS:
10887
        if (!(dev->data.fs = virDomainFSDefParseXML(node, ctxt, flags)))
10888
            goto error;
10889 10890
        break;
    case VIR_DOMAIN_DEVICE_NET:
10891
        if (!(dev->data.net = virDomainNetDefParseXML(xmlopt, node, ctxt,
10892
                                                      NULL, flags)))
10893
            goto error;
10894 10895
        break;
    case VIR_DOMAIN_DEVICE_INPUT:
L
Li Zhang 已提交
10896
        if (!(dev->data.input = virDomainInputDefParseXML(def,
10897
                                                          node, flags)))
10898
            goto error;
10899 10900
        break;
    case VIR_DOMAIN_DEVICE_SOUND:
10901
        if (!(dev->data.sound = virDomainSoundDefParseXML(node, ctxt, flags)))
10902
            goto error;
10903 10904
        break;
    case VIR_DOMAIN_DEVICE_WATCHDOG:
10905
        if (!(dev->data.watchdog = virDomainWatchdogDefParseXML(node, flags)))
R
Richard Jones 已提交
10906
            goto error;
10907 10908
        break;
    case VIR_DOMAIN_DEVICE_VIDEO:
10909
        if (!(dev->data.video = virDomainVideoDefParseXML(node, def, flags)))
10910
            goto error;
10911 10912
        break;
    case VIR_DOMAIN_DEVICE_HOSTDEV:
10913 10914
        if (!(dev->data.hostdev = virDomainHostdevDefParseXML(xmlopt, def, node,
                                                              ctxt, NULL, flags)))
10915
            goto error;
10916 10917
        break;
    case VIR_DOMAIN_DEVICE_CONTROLLER:
10918 10919
        if (!(dev->data.controller = virDomainControllerDefParseXML(node, ctxt,
                                                                    flags)))
10920
            goto error;
10921 10922
        break;
    case VIR_DOMAIN_DEVICE_GRAPHICS:
10923
        if (!(dev->data.graphics = virDomainGraphicsDefParseXML(node, ctxt, flags)))
10924
            goto error;
10925 10926
        break;
    case VIR_DOMAIN_DEVICE_HUB:
M
Marc-André Lureau 已提交
10927 10928
        if (!(dev->data.hub = virDomainHubDefParseXML(node, flags)))
            goto error;
10929 10930
        break;
    case VIR_DOMAIN_DEVICE_REDIRDEV:
10931
        if (!(dev->data.redirdev = virDomainRedirdevDefParseXML(node, NULL, flags)))
10932
            goto error;
10933 10934
        break;
    case VIR_DOMAIN_DEVICE_RNG:
10935 10936
        if (!(dev->data.rng = virDomainRNGDefParseXML(node, ctxt, flags)))
            goto error;
10937 10938
        break;
    case VIR_DOMAIN_DEVICE_CHR:
10939 10940 10941 10942 10943 10944
        if (!(dev->data.chr = virDomainChrDefParseXML(ctxt,
                                                      node,
                                                      def->seclabels,
                                                      def->nseclabels,
                                                      flags)))
            goto error;
10945 10946
        break;
    case VIR_DOMAIN_DEVICE_SMARTCARD:
10947 10948
        if (!(dev->data.smartcard = virDomainSmartcardDefParseXML(node, flags)))
            goto error;
10949 10950
        break;
    case VIR_DOMAIN_DEVICE_MEMBALLOON:
10951 10952 10953
        if (!(dev->data.memballoon = virDomainMemballoonDefParseXML(node,
                                                                    ctxt,
                                                                    flags)))
10954
            goto error;
10955 10956
        break;
    case VIR_DOMAIN_DEVICE_NVRAM:
10957 10958
        if (!(dev->data.nvram = virDomainNVRAMDefParseXML(node, flags)))
            goto error;
10959
        break;
10960 10961 10962 10963
    case VIR_DOMAIN_DEVICE_SHMEM:
        if (!(dev->data.shmem = virDomainShmemDefParseXML(node, ctxt, flags)))
            goto error;
        break;
10964 10965 10966 10967
    case VIR_DOMAIN_DEVICE_TPM:
        if (!(dev->data.tpm = virDomainTPMDefParseXML(node, ctxt, flags)))
            goto error;
        break;
10968 10969 10970 10971
    case VIR_DOMAIN_DEVICE_PANIC:
        if (!(dev->data.panic = virDomainPanicDefParseXML(node)))
            goto error;
        break;
10972 10973 10974
    case VIR_DOMAIN_DEVICE_NONE:
    case VIR_DOMAIN_DEVICE_LAST:
        break;
10975 10976
    }

10977
    /* callback to fill driver specific device aspects */
10978
    if (virDomainDeviceDefPostParse(dev, def, caps, xmlopt) < 0)
10979 10980
        goto error;

10981
 cleanup:
10982
    xmlFreeDoc(xml);
10983
    xmlXPathFreeContext(ctxt);
10984 10985
    return dev;

10986
 error:
10987
    VIR_FREE(dev);
10988
    goto cleanup;
10989
}
M
Matthias Bolte 已提交
10990 10991


10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032
virStorageSourcePtr
virDomainDiskDefSourceParse(const char *xmlStr,
                            const virDomainDef *def,
                            virDomainXMLOptionPtr xmlopt,
                            unsigned int flags)
{
    xmlDocPtr xml;
    xmlNodePtr node;
    xmlXPathContextPtr ctxt = NULL;
    virDomainDiskDefPtr disk = NULL;
    virStorageSourcePtr ret = NULL;

    if (!(xml = virXMLParseStringCtxt(xmlStr, _("(disk_definition)"), &ctxt)))
        goto cleanup;
    node = ctxt->node;

    if (!xmlStrEqual(node->name, BAD_CAST "disk")) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("expecting root element of 'disk', not '%s'"),
                       node->name);
        goto cleanup;
    }

    flags |= VIR_DOMAIN_XML_INTERNAL_DISK_SOURCE;
    if (!(disk = virDomainDiskDefParseXML(xmlopt, node, ctxt,
                                          NULL, def->seclabels,
                                          def->nseclabels,
                                          flags)))
        goto cleanup;

    ret = disk->src;
    disk->src = NULL;

 cleanup:
    virDomainDiskDefFree(disk);
    xmlFreeDoc(xml);
    xmlXPathFreeContext(ctxt);
    return ret;
}


11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045
static const char *
virDomainChrTargetTypeToString(int deviceType,
                               int targetType)
{
    const char *type = NULL;

    switch (deviceType) {
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
        type = virDomainChrChannelTargetTypeToString(targetType);
        break;
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
        type = virDomainChrConsoleTargetTypeToString(targetType);
        break;
G
Guannan Ren 已提交
11046 11047 11048
    case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
        type = virDomainChrSerialTargetTypeToString(targetType);
        break;
11049 11050 11051 11052 11053 11054 11055
    default:
        break;
    }

    return type;
}

L
Laine Stump 已提交
11056 11057 11058
int
virDomainHostdevInsert(virDomainDefPtr def, virDomainHostdevDefPtr hostdev)
{
11059 11060

    return VIR_APPEND_ELEMENT(def->hostdevs, def->nhostdevs, hostdev);
L
Laine Stump 已提交
11061 11062
}

11063
virDomainHostdevDefPtr
L
Laine Stump 已提交
11064 11065
virDomainHostdevRemove(virDomainDefPtr def, size_t i)
{
11066 11067
    virDomainHostdevDefPtr hostdev = def->hostdevs[i];

11068
    VIR_DELETE_ELEMENT(def->hostdevs, i, def->nhostdevs);
11069
    return hostdev;
L
Laine Stump 已提交
11070 11071
}

11072 11073

static int
11074 11075
virDomainHostdevMatchSubsysUSB(virDomainHostdevDefPtr first,
                               virDomainHostdevDefPtr second)
11076
{
11077 11078 11079 11080
    virDomainHostdevSubsysUSBPtr first_usbsrc = &first->source.subsys.u.usb;
    virDomainHostdevSubsysUSBPtr second_usbsrc = &second->source.subsys.u.usb;

    if (first_usbsrc->bus && first_usbsrc->device) {
11081
        /* specified by bus location on host */
11082 11083
        if (first_usbsrc->bus == second_usbsrc->bus &&
            first_usbsrc->device == second_usbsrc->device)
11084 11085 11086
            return 1;
    } else {
        /* specified by product & vendor id */
11087 11088
        if (first_usbsrc->product == second_usbsrc->product &&
            first_usbsrc->vendor == second_usbsrc->vendor)
11089 11090 11091 11092 11093 11094
            return 1;
    }
    return 0;
}

static int
11095 11096
virDomainHostdevMatchSubsysPCI(virDomainHostdevDefPtr first,
                               virDomainHostdevDefPtr second)
11097
{
11098 11099 11100 11101 11102 11103 11104
    virDomainHostdevSubsysPCIPtr first_pcisrc = &first->source.subsys.u.pci;
    virDomainHostdevSubsysPCIPtr second_pcisrc = &second->source.subsys.u.pci;

    if (first_pcisrc->addr.domain == second_pcisrc->addr.domain &&
        first_pcisrc->addr.bus == second_pcisrc->addr.bus &&
        first_pcisrc->addr.slot == second_pcisrc->addr.slot &&
        first_pcisrc->addr.function == second_pcisrc->addr.function)
11105 11106 11107 11108
        return 1;
    return 0;
}

H
Han Cheng 已提交
11109
static int
11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121
virDomainHostdevMatchSubsysSCSIHost(virDomainHostdevDefPtr first,
                                    virDomainHostdevDefPtr second)
{
    virDomainHostdevSubsysSCSIHostPtr first_scsihostsrc =
        &first->source.subsys.u.scsi.u.host;
    virDomainHostdevSubsysSCSIHostPtr second_scsihostsrc =
        &second->source.subsys.u.scsi.u.host;

    if (STREQ(first_scsihostsrc->adapter, second_scsihostsrc->adapter) &&
        first_scsihostsrc->bus == second_scsihostsrc->bus &&
        first_scsihostsrc->target == second_scsihostsrc->target &&
        first_scsihostsrc->unit == second_scsihostsrc->unit)
H
Han Cheng 已提交
11122 11123 11124
        return 1;
    return 0;
}
11125

11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141
static int
virDomainHostdevMatchSubsysSCSIiSCSI(virDomainHostdevDefPtr first,
                                     virDomainHostdevDefPtr second)
{
    virDomainHostdevSubsysSCSIiSCSIPtr first_iscsisrc =
        &first->source.subsys.u.scsi.u.iscsi;
    virDomainHostdevSubsysSCSIiSCSIPtr second_iscsisrc =
        &second->source.subsys.u.scsi.u.iscsi;

    if (STREQ(first_iscsisrc->hosts[0].name, second_iscsisrc->hosts[0].name) &&
        STREQ(first_iscsisrc->hosts[0].port, second_iscsisrc->hosts[0].port) &&
        STREQ(first_iscsisrc->path, second_iscsisrc->path))
        return 1;
    return 0;
}

11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153
static int
virDomainHostdevMatchSubsys(virDomainHostdevDefPtr a,
                            virDomainHostdevDefPtr b)
{
    if (a->source.subsys.type != b->source.subsys.type)
        return 0;

    switch (a->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
        return virDomainHostdevMatchSubsysPCI(a, b);
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
        return virDomainHostdevMatchSubsysUSB(a, b);
H
Han Cheng 已提交
11154
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
11155 11156 11157 11158 11159
        if (a->source.subsys.u.scsi.protocol ==
            VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI)
            return virDomainHostdevMatchSubsysSCSIiSCSI(a, b);
        else
            return virDomainHostdevMatchSubsysSCSIHost(a, b);
11160 11161 11162 11163 11164
    }
    return 0;
}


11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181
static int
virDomainHostdevMatchCapsStorage(virDomainHostdevDefPtr a,
                                 virDomainHostdevDefPtr b)
{
    return STREQ_NULLABLE(a->source.caps.u.storage.block,
                          b->source.caps.u.storage.block);
}


static int
virDomainHostdevMatchCapsMisc(virDomainHostdevDefPtr a,
                              virDomainHostdevDefPtr b)
{
    return STREQ_NULLABLE(a->source.caps.u.misc.chardev,
                          b->source.caps.u.misc.chardev);
}

11182 11183 11184 11185 11186 11187 11188 11189
static int
virDomainHostdevMatchCapsNet(virDomainHostdevDefPtr a,
                              virDomainHostdevDefPtr b)
{
    return STREQ_NULLABLE(a->source.caps.u.net.iface,
                          b->source.caps.u.net.iface);
}

11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202

static int
virDomainHostdevMatchCaps(virDomainHostdevDefPtr a,
                          virDomainHostdevDefPtr b)
{
    if (a->source.caps.type != b->source.caps.type)
        return 0;

    switch (a->source.caps.type) {
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_STORAGE:
        return virDomainHostdevMatchCapsStorage(a, b);
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_MISC:
        return virDomainHostdevMatchCapsMisc(a, b);
11203 11204
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_NET:
        return virDomainHostdevMatchCapsNet(a, b);
11205 11206 11207 11208 11209
    }
    return 0;
}


11210 11211 11212 11213 11214 11215 11216 11217 11218 11219
static int
virDomainHostdevMatch(virDomainHostdevDefPtr a,
                      virDomainHostdevDefPtr b)
{
    if (a->mode != b->mode)
        return 0;

    switch (a->mode) {
    case VIR_DOMAIN_HOSTDEV_MODE_SUBSYS:
        return virDomainHostdevMatchSubsys(a, b);
11220 11221
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
        return virDomainHostdevMatchCaps(a, b);
11222 11223 11224 11225
    }
    return 0;
}

L
Laine Stump 已提交
11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236
/* Find an entry in hostdevs that matches the source spec in
 * @match. return pointer to the entry in @found (if found is
 * non-NULL). Returns index (within hostdevs) of matched entry, or -1
 * if no match was found.
 */
int
virDomainHostdevFind(virDomainDefPtr def,
                     virDomainHostdevDefPtr match,
                     virDomainHostdevDefPtr *found)
{
    virDomainHostdevDefPtr local_found;
11237
    size_t i;
L
Laine Stump 已提交
11238 11239 11240 11241 11242

    if (!found)
        found = &local_found;
    *found = NULL;

11243
    for (i = 0; i < def->nhostdevs; i++) {
11244 11245
        if (virDomainHostdevMatch(match, def->hostdevs[i])) {
            *found = def->hostdevs[i];
L
Laine Stump 已提交
11246 11247 11248 11249 11250 11251
            break;
        }
    }
    return *found ? i : -1;
}

11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305
static bool
virDomainDiskControllerMatch(int controller_type, int disk_bus)
{
    if (controller_type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI &&
        disk_bus == VIR_DOMAIN_DISK_BUS_SCSI)
        return true;

    if (controller_type == VIR_DOMAIN_CONTROLLER_TYPE_FDC &&
        disk_bus == VIR_DOMAIN_DISK_BUS_FDC)
        return true;

    if (controller_type == VIR_DOMAIN_CONTROLLER_TYPE_IDE &&
        disk_bus == VIR_DOMAIN_DISK_BUS_IDE)
        return true;

    if (controller_type == VIR_DOMAIN_CONTROLLER_TYPE_SATA &&
        disk_bus == VIR_DOMAIN_DISK_BUS_SATA)
        return true;

    return false;
}

int
virDomainDiskIndexByAddress(virDomainDefPtr def,
                            virDevicePCIAddressPtr pci_address,
                            unsigned int bus, unsigned int target,
                            unsigned int unit)
{
    virDomainDiskDefPtr vdisk;
    virDomainControllerDefPtr controller = NULL;
    size_t i;
    int cidx;

    if ((cidx = virDomainControllerFindByPCIAddress(def, pci_address)) >= 0)
        controller = def->controllers[cidx];

    for (i = 0; i < def->ndisks; i++) {
        vdisk = def->disks[i];
        if (vdisk->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI &&
            virDevicePCIAddressEqual(&vdisk->info.addr.pci, pci_address))
            return i;
        if (vdisk->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE) {
            virDomainDeviceDriveAddressPtr drive = &vdisk->info.addr.drive;
            if (controller &&
                virDomainDiskControllerMatch(controller->type, vdisk->bus) &&
                drive->controller == controller->idx &&
                drive->bus == bus && drive->target == target &&
                drive->unit == unit)
                return i;
        }
    }
    return -1;
}

11306 11307 11308
int
virDomainDiskIndexByName(virDomainDefPtr def, const char *name,
                         bool allow_ambiguous)
11309 11310
{
    virDomainDiskDefPtr vdisk;
11311
    size_t i;
11312
    int candidate = -1;
11313

11314 11315 11316 11317
    /* We prefer the <target dev='name'/> name (it's shorter, required
     * for all disks, and should be unambiguous), but also support
     * <source file='name'/> (if unambiguous).  Assume dst if there is
     * no leading slash, source name otherwise.  */
11318 11319
    for (i = 0; i < def->ndisks; i++) {
        vdisk = def->disks[i];
11320 11321 11322
        if (*name != '/') {
            if (STREQ(vdisk->dst, name))
                return i;
11323
        } else if (STREQ_NULLABLE(virDomainDiskGetSource(vdisk), name)) {
11324 11325 11326 11327 11328 11329
            if (allow_ambiguous)
                return i;
            if (candidate >= 0)
                return -1;
            candidate = i;
        }
11330
    }
11331 11332 11333 11334 11335 11336 11337 11338 11339
    return candidate;
}

/* Return the path to a disk image if a string identifies at least one
 * disk belonging to the domain (both device strings 'vda' and paths
 * '/path/to/file' are converted into '/path/to/file').  */
const char *
virDomainDiskPathByName(virDomainDefPtr def, const char *name)
{
11340
    int idx = virDomainDiskIndexByName(def, name, true);
11341

11342
    return idx < 0 ? NULL : virDomainDiskGetSource(def->disks[idx]);
11343 11344
}

11345 11346
int virDomainDiskInsert(virDomainDefPtr def,
                        virDomainDiskDefPtr disk)
11347 11348
{

11349 11350 11351 11352 11353 11354
    if (VIR_REALLOC_N(def->disks, def->ndisks+1) < 0)
        return -1;

    virDomainDiskInsertPreAlloced(def, disk);

    return 0;
11355 11356
}

11357 11358 11359
void virDomainDiskInsertPreAlloced(virDomainDefPtr def,
                                   virDomainDiskDefPtr disk)
{
11360
    int idx;
11361 11362 11363 11364 11365 11366 11367 11368
    /* Tenatively plan to insert disk at the end. */
    int insertAt = -1;

    /* Then work backwards looking for disks on
     * the same bus. If we find a disk with a drive
     * index greater than the new one, insert at
     * that position
     */
11369
    for (idx = (def->ndisks - 1); idx >= 0; idx--) {
11370 11371
        /* If bus matches and current disk is after
         * new disk, then new disk should go here */
11372 11373
        if (def->disks[idx]->bus == disk->bus &&
            (virDiskNameToIndex(def->disks[idx]->dst) >
11374
             virDiskNameToIndex(disk->dst))) {
11375 11376
            insertAt = idx;
        } else if (def->disks[idx]->bus == disk->bus &&
11377 11378 11379 11380
                   insertAt == -1) {
            /* Last disk with match bus is before the
             * new disk, then put new disk just after
             */
11381
            insertAt = idx + 1;
11382 11383 11384
        }
    }

11385 11386 11387
    /* VIR_INSERT_ELEMENT_INPLACE will never return an error here. */
    ignore_value(VIR_INSERT_ELEMENT_INPLACE(def->disks, insertAt,
                                            def->ndisks, disk));
11388 11389 11390
}


11391 11392
virDomainDiskDefPtr
virDomainDiskRemove(virDomainDefPtr def, size_t i)
11393
{
11394
    virDomainDiskDefPtr disk = def->disks[i];
11395

11396
    VIR_DELETE_ELEMENT(def->disks, i, def->ndisks);
11397
    return disk;
11398 11399
}

11400 11401
virDomainDiskDefPtr
virDomainDiskRemoveByName(virDomainDefPtr def, const char *name)
11402
{
11403 11404
    int idx = virDomainDiskIndexByName(def, name, false);
    if (idx < 0)
11405
        return NULL;
11406
    return virDomainDiskRemove(def, idx);
11407 11408
}

E
Eric Blake 已提交
11409
/* Return true if VM has at least one disk involved in a current block
11410
 * copy/commit job (that is, with a <mirror> element in the disk xml).  */
E
Eric Blake 已提交
11411 11412 11413
bool
virDomainHasDiskMirror(virDomainObjPtr vm)
{
11414
    size_t i;
E
Eric Blake 已提交
11415 11416 11417 11418 11419 11420
    for (i = 0; i < vm->def->ndisks; i++)
        if (vm->def->disks[i]->mirror)
            return true;
    return false;
}

11421 11422
int virDomainNetInsert(virDomainDefPtr def, virDomainNetDefPtr net)
{
11423 11424 11425 11426 11427 11428 11429 11430 11431 11432
    /* hostdev net devices must also exist in the hostdevs array */
    if (net->type == VIR_DOMAIN_NET_TYPE_HOSTDEV &&
        virDomainHostdevInsert(def, &net->data.hostdev.def) < 0)
        return -1;

    if (VIR_APPEND_ELEMENT(def->nets, def->nnets, net) < 0) {
        /* virDomainHostdevInsert just appends new hostdevs, so we are sure
         * that the hostdev we've added a few lines above is at the end of
         * array. Although, devices are indexed from zero ... */
        virDomainHostdevRemove(def, def->nhostdevs - 1);
11433
        return -1;
11434
    }
11435 11436 11437
    return 0;
}

11438 11439 11440 11441
/* virDomainNetFindIdx: search according to mac address and guest side
 *                      PCI address (if specified)
 *
 * Return: index of match if unique match found
11442
 *         -1 otherwise and an error is logged
11443 11444 11445
 */
int
virDomainNetFindIdx(virDomainDefPtr def, virDomainNetDefPtr net)
11446
{
11447 11448
    size_t i;
    int matchidx = -1;
11449
    char mac[VIR_MAC_STRING_BUFLEN];
11450 11451
    bool PCIAddrSpecified = virDomainDeviceAddressIsValid(&net->info,
                                                          VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI);
11452

11453 11454
    for (i = 0; i < def->nnets; i++) {
        if (virMacAddrCmp(&def->nets[i]->mac, &net->mac))
11455 11456 11457 11458 11459 11460 11461 11462 11463
            continue;

        if ((matchidx >= 0) && !PCIAddrSpecified) {
            /* there were multiple matches on mac address, and no
             * qualifying guest-side PCI address was given, so we must
             * fail (NB: a USB address isn't adequate, since it may
             * specify only vendor and product ID, and there may be
             * multiples of those.
             */
11464 11465 11466 11467
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("multiple devices matching mac address %s found"),
                           virMacAddrFormat(&net->mac, mac));
            return -1;
11468 11469
        }
        if (PCIAddrSpecified) {
11470
            if (virDevicePCIAddressEqual(&def->nets[i]->info.addr.pci,
11471 11472 11473 11474
                                         &net->info.addr.pci)) {
                /* exit early if the pci address was specified and
                 * it matches, as this guarantees no duplicates.
                 */
11475
                matchidx = i;
11476 11477 11478 11479
                break;
            }
        } else {
            /* no PCI address given, so there may be multiple matches */
11480
            matchidx = i;
11481 11482
        }
    }
11483
    if (matchidx < 0) {
11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497
        if (PCIAddrSpecified) {
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("no device matching mac address %s found on "
                             "%.4x:%.2x:%.2x.%.1x"),
                           virMacAddrFormat(&net->mac, mac),
                           net->info.addr.pci.domain,
                           net->info.addr.pci.bus,
                           net->info.addr.pci.slot,
                           net->info.addr.pci.function);
        } else {
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("no device matching mac address %s found"),
                           virMacAddrFormat(&net->mac, mac));
        }
11498
    }
11499
    return matchidx;
11500 11501
}

11502

11503 11504 11505 11506
void
virDomainNetRemoveHostdev(virDomainDefPtr def,
                          virDomainNetDefPtr net)
{
11507 11508 11509 11510 11511 11512
    /* hostdev net devices are normally also be in the hostdevs
     * array, but might have already been removed by the time we
     * get here.
     */
    virDomainHostdevDefPtr hostdev = virDomainNetGetActualHostdev(net);
    size_t i;
11513

11514
    if (hostdev) {
11515 11516 11517
        for (i = 0; i < def->nhostdevs; i++) {
            if (def->hostdevs[i] == hostdev) {
                virDomainHostdevRemove(def, i);
11518 11519 11520 11521
                break;
            }
        }
    }
11522 11523 11524 11525 11526 11527 11528 11529 11530
}


virDomainNetDefPtr
virDomainNetRemove(virDomainDefPtr def, size_t i)
{
    virDomainNetDefPtr net = def->nets[i];

    virDomainNetRemoveHostdev(def, net);
11531
    VIR_DELETE_ELEMENT(def->nets, i, def->nnets);
11532
    return net;
11533 11534
}

11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549
int virDomainControllerInsert(virDomainDefPtr def,
                              virDomainControllerDefPtr controller)
{

    if (VIR_REALLOC_N(def->controllers, def->ncontrollers+1) < 0)
        return -1;

    virDomainControllerInsertPreAlloced(def, controller);

    return 0;
}

void virDomainControllerInsertPreAlloced(virDomainDefPtr def,
                                         virDomainControllerDefPtr controller)
{
11550
    int idx;
11551 11552 11553 11554 11555 11556 11557 11558
    /* Tenatively plan to insert controller at the end. */
    int insertAt = -1;

    /* Then work backwards looking for controllers of
     * the same type. If we find a controller with a
     * index greater than the new one, insert at
     * that position
     */
11559
    for (idx = (def->ncontrollers - 1); idx >= 0; idx--) {
11560 11561
        /* If bus matches and current controller is after
         * new controller, then new controller should go here */
11562 11563 11564 11565
        if (def->controllers[idx]->type == controller->type &&
            def->controllers[idx]->idx > controller->idx) {
            insertAt = idx;
        } else if (def->controllers[idx]->type == controller->type &&
11566 11567 11568 11569
                   insertAt == -1) {
            /* Last controller with match bus is before the
             * new controller, then put new controller just after
             */
11570
            insertAt = idx + 1;
11571 11572 11573
        }
    }

11574 11575 11576
    /* VIR_INSERT_ELEMENT_INPLACE will never return an error here. */
    ignore_value(VIR_INSERT_ELEMENT_INPLACE(def->controllers, insertAt,
                                            def->ncontrollers, controller));
11577 11578
}

11579 11580 11581 11582
int
virDomainControllerFind(virDomainDefPtr def,
                        int type, int idx)
{
11583
    size_t i;
11584

11585
    for (i = 0; i < def->ncontrollers; i++) {
11586 11587 11588 11589 11590 11591 11592 11593 11594
        if ((def->controllers[i]->type == type) &&
            (def->controllers[i]->idx == idx)) {
            return i;
        }
    }

    return -1;
}

11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611
int
virDomainControllerFindByPCIAddress(virDomainDefPtr def,
                                    virDevicePCIAddressPtr addr)
{
    size_t i;

    for (i = 0; i < def->ncontrollers; i++) {
        virDomainDeviceInfoPtr info = &def->controllers[i]->info;

        if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI &&
            virDevicePCIAddressEqual(&info->addr.pci, addr))
            return i;
    }

    return -1;
}

11612 11613 11614 11615 11616
virDomainControllerDefPtr
virDomainControllerRemove(virDomainDefPtr def, size_t i)
{
    virDomainControllerDefPtr controller = def->controllers[i];

11617
    VIR_DELETE_ELEMENT(def->controllers, i, def->ncontrollers);
11618 11619
    return controller;
}
11620

11621 11622 11623 11624
int virDomainLeaseIndex(virDomainDefPtr def,
                        virDomainLeaseDefPtr lease)
{
    virDomainLeaseDefPtr vlease;
11625
    size_t i;
11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644

    for (i = 0; i < def->nleases; i++) {
        vlease = def->leases[i];
        /* Either both must have lockspaces present which  match.. */
        if (vlease->lockspace && lease->lockspace &&
            STRNEQ(vlease->lockspace, lease->lockspace))
            continue;
        /* ...or neither must have a lockspace present */
        if (vlease->lockspace || lease->lockspace)
            continue;
        if (STREQ(vlease->key, lease->key))
            return i;
    }
    return -1;
}


int virDomainLeaseInsertPreAlloc(virDomainDefPtr def)
{
11645
    return VIR_EXPAND_N(def->leases, def->nleases, 1);
11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668
}

int virDomainLeaseInsert(virDomainDefPtr def,
                         virDomainLeaseDefPtr lease)
{
    if (virDomainLeaseInsertPreAlloc(def) < 0)
        return -1;

    virDomainLeaseInsertPreAlloced(def, lease);
    return 0;
}


void virDomainLeaseInsertPreAlloced(virDomainDefPtr def,
                                    virDomainLeaseDefPtr lease)
{
    if (lease == NULL)
        VIR_SHRINK_N(def->leases, def->nleases, 1);
    else
        def->leases[def->nleases-1] = lease;
}


11669 11670
virDomainLeaseDefPtr
virDomainLeaseRemoveAt(virDomainDefPtr def, size_t i)
11671
{
11672 11673 11674

    virDomainLeaseDefPtr lease = def->leases[i];

11675
    VIR_DELETE_ELEMENT(def->leases, i, def->nleases);
11676
    return lease;
11677 11678 11679
}


11680 11681 11682
virDomainLeaseDefPtr
virDomainLeaseRemove(virDomainDefPtr def,
                     virDomainLeaseDefPtr lease)
11683
{
11684 11685
    int idx = virDomainLeaseIndex(def, lease);
    if (idx < 0)
11686
        return NULL;
11687
    return virDomainLeaseRemoveAt(def, idx);
11688 11689
}

11690
bool
11691 11692 11693 11694 11695 11696 11697 11698 11699 11700
virDomainChrEquals(virDomainChrDefPtr src,
                   virDomainChrDefPtr tgt)
{
    if (!src || !tgt)
        return src == tgt;

    if (src->deviceType != tgt->deviceType ||
        !virDomainChrSourceDefIsEqual(&src->source, &tgt->source))
        return false;

11701
    switch ((virDomainChrDeviceType) src->deviceType) {
11702 11703 11704
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
        if (src->targetType != tgt->targetType)
            return false;
11705
        switch ((virDomainChrChannelTargetType) src->targetType) {
11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740
        case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO:
            return STREQ_NULLABLE(src->target.name, tgt->target.name);
            break;
        case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_GUESTFWD:
            if (!src->target.addr || !tgt->target.addr)
                return src->target.addr == tgt->target.addr;
            return memcmp(src->target.addr, tgt->target.addr,
                          sizeof(*src->target.addr)) == 0;
            break;

        case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_NONE:
        case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_LAST:
            /* shouldn't happen */
            break;
        }
        break;

    case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
        if (src->targetTypeAttr != tgt->targetTypeAttr)
            return false;
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
    case VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL:
        return src->target.port == tgt->target.port;
        break;
    case VIR_DOMAIN_CHR_DEVICE_TYPE_LAST:
        /* shouldn't happen */
        break;
    }
    return false;
}

virDomainChrDefPtr
virDomainChrFind(virDomainDefPtr def,
                 virDomainChrDefPtr target)
{
11741 11742 11743
    virDomainChrDefPtr chr;
    const virDomainChrDef **arrPtr;
    size_t i, cnt;
11744

11745
    virDomainChrGetDomainPtrs(def, target->deviceType, &arrPtr, &cnt);
11746

11747 11748 11749
    for (i = 0; i < cnt; i++) {
        /* Cast away const */
        chr = (virDomainChrDefPtr) arrPtr[i];
11750 11751 11752 11753 11754 11755
        if (virDomainChrEquals(chr, target))
            return chr;
    }
    return NULL;
}

11756 11757 11758 11759 11760

/* Return the address within vmdef to be modified when working with a
 * chrdefptr of the given type.  */
static void
virDomainChrGetDomainPtrsInternal(virDomainDefPtr vmdef,
11761
                                  virDomainChrDeviceType type,
11762 11763
                                  virDomainChrDefPtr ***arrPtr,
                                  size_t **cntPtr)
11764
{
11765
    switch (type) {
11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786
    case VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL:
        *arrPtr = &vmdef->parallels;
        *cntPtr = &vmdef->nparallels;
        break;

    case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
        *arrPtr = &vmdef->serials;
        *cntPtr = &vmdef->nserials;
        break;

    case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
        *arrPtr = &vmdef->consoles;
        *cntPtr = &vmdef->nconsoles;
        break;

    case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
        *arrPtr = &vmdef->channels;
        *cntPtr = &vmdef->nchannels;
        break;

    case VIR_DOMAIN_CHR_DEVICE_TYPE_LAST:
11787 11788
        *arrPtr = NULL;
        *cntPtr = NULL;
11789 11790 11791 11792
        break;
    }
}

11793

11794 11795 11796 11797
/* Return the array within vmdef that can contain a chrdefptr of the
 * given type.  */
void
virDomainChrGetDomainPtrs(const virDomainDef *vmdef,
11798
                          virDomainChrDeviceType type,
11799 11800 11801
                          const virDomainChrDef ***arrPtr,
                          size_t *cntPtr)
{
11802 11803
    virDomainChrDef ***arrVar = NULL;
    size_t *cntVar = NULL;
11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816

    /* Cast away const; we add it back in the final assignment.  */
    virDomainChrGetDomainPtrsInternal((virDomainDefPtr) vmdef, type,
                                      &arrVar, &cntVar);
    if (arrVar) {
        *arrPtr = (const virDomainChrDef **) *arrVar;
        *cntPtr = *cntVar;
    } else {
        *arrPtr = NULL;
        *cntPtr = 0;
    }
}

11817

11818 11819 11820 11821
int
virDomainChrInsert(virDomainDefPtr vmdef,
                   virDomainChrDefPtr chr)
{
11822 11823
    virDomainChrDefPtr **arrPtr = NULL;
    size_t *cntPtr = NULL;
11824

11825
    virDomainChrGetDomainPtrsInternal(vmdef, chr->deviceType, &arrPtr, &cntPtr);
11826 11827 11828 11829 11830 11831 11832 11833

    return VIR_APPEND_ELEMENT(*arrPtr, *cntPtr, chr);
}

virDomainChrDefPtr
virDomainChrRemove(virDomainDefPtr vmdef,
                   virDomainChrDefPtr chr)
{
11834 11835
    virDomainChrDefPtr ret, **arrPtr = NULL;
    size_t i, *cntPtr = NULL;
11836

11837
    virDomainChrGetDomainPtrsInternal(vmdef, chr->deviceType, &arrPtr, &cntPtr);
11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851

    for (i = 0; i < *cntPtr; i++) {
        ret = (*arrPtr)[i];

        if (virDomainChrEquals(ret, chr))
            break;
    }

    if (i == *cntPtr)
        return NULL;

    VIR_DELETE_ELEMENT(*arrPtr, i, *cntPtr);
    return ret;
}
11852

11853 11854 11855 11856
char *
virDomainDefGetDefaultEmulator(virDomainDefPtr def,
                               virCapsPtr caps)
{
11857 11858 11859 11860 11861 11862
    const char *type;
    const char *emulator;
    char *retemu;

    type = virDomainVirtTypeToString(def->virtType);
    if (!type) {
11863 11864
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("unknown virt type"));
11865 11866 11867 11868 11869 11870 11871 11872 11873
        return NULL;
    }

    emulator = virCapabilitiesDefaultGuestEmulator(caps,
                                                   def->os.type,
                                                   def->os.arch,
                                                   type);

    if (!emulator) {
11874
        virReportError(VIR_ERR_INTERNAL_ERROR,
11875 11876
                       _("no emulator for domain %s os type %s "
                         "on architecture %s"),
11877
                       type, def->os.type, virArchToString(def->os.arch));
11878 11879 11880
        return NULL;
    }

11881
    ignore_value(VIR_STRDUP(retemu, emulator));
11882 11883 11884
    return retemu;
}

11885 11886
static int
virDomainDefParseBootXML(xmlXPathContextPtr ctxt,
11887
                         virDomainDefPtr def)
11888 11889
{
    xmlNodePtr *nodes = NULL;
11890 11891
    size_t i;
    int n;
M
Martin Kletzander 已提交
11892
    char *tmp = NULL;
11893
    int ret = -1;
M
Michal Privoznik 已提交
11894
    unsigned long deviceBoot, serialPorts;
11895 11896

    if (virXPathULong("count(./devices/disk[boot]"
11897
                      "|./devices/interface[boot]"
11898 11899
                      "|./devices/hostdev[boot]"
                      "|./devices/redirdev[boot])", ctxt, &deviceBoot) < 0) {
11900 11901
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot count boot devices"));
11902 11903
        goto cleanup;
    }
11904 11905

    /* analysis of the boot devices */
11906
    if ((n = virXPathNodeSet("./os/boot", ctxt, &nodes)) < 0)
11907 11908
        goto cleanup;

11909
    if (n > 0 && deviceBoot) {
11910 11911 11912
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("per-device boot elements cannot be used"
                         " together with os/boot elements"));
11913 11914 11915
        goto cleanup;
    }

11916
    for (i = 0; i < n && i < VIR_DOMAIN_BOOT_LAST; i++) {
11917 11918 11919
        int val;
        char *dev = virXMLPropString(nodes[i], "dev");
        if (!dev) {
11920 11921
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("missing boot device"));
11922 11923 11924
            goto cleanup;
        }
        if ((val = virDomainBootTypeFromString(dev)) < 0) {
11925
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11926 11927
                           _("unknown boot device '%s'"),
                           dev);
11928 11929 11930 11931 11932 11933
            VIR_FREE(dev);
            goto cleanup;
        }
        VIR_FREE(dev);
        def->os.bootDevs[def->os.nBootDevs++] = val;
    }
11934
    if (def->os.nBootDevs == 0 && !deviceBoot) {
11935 11936 11937 11938
        def->os.nBootDevs = 1;
        def->os.bootDevs[0] = VIR_DOMAIN_BOOT_DISK;
    }

M
Martin Kletzander 已提交
11939 11940
    tmp = virXPathString("string(./os/bootmenu[1]/@enable)", ctxt);
    if (tmp) {
J
Ján Tomko 已提交
11941
        def->os.bootmenu = virTristateBoolTypeFromString(tmp);
11942 11943 11944 11945 11946
        if (def->os.bootmenu <= 0) {
            /* In order not to break misconfigured machines, this
             * should not emit an error, but rather set the bootmenu
             * to disabled */
            VIR_WARN("disabling bootmenu due to unknown option '%s'",
M
Martin Kletzander 已提交
11947
                     tmp);
J
Ján Tomko 已提交
11948
            def->os.bootmenu = VIR_TRISTATE_BOOL_NO;
11949
        }
M
Martin Kletzander 已提交
11950
        VIR_FREE(tmp);
11951 11952
    }

11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965
    tmp = virXPathString("string(./os/bootmenu[1]/@timeout)", ctxt);
    if (tmp && def->os.bootmenu == VIR_TRISTATE_BOOL_YES) {
        if (virStrToLong_uip(tmp, NULL, 0, &def->os.bm_timeout) < 0 ||
            def->os.bm_timeout > 65535) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("invalid value for boot menu timeout, "
                             "must be in range [0,65535]"));
            goto cleanup;
        }
        def->os.bm_timeout_set = true;
    }
    VIR_FREE(tmp);

M
Martin Kletzander 已提交
11966 11967 11968
    tmp = virXPathString("string(./os/bios[1]/@useserial)", ctxt);
    if (tmp) {
        if (STREQ(tmp, "yes")) {
M
Michal Privoznik 已提交
11969 11970
            if (virXPathULong("count(./devices/serial)",
                              ctxt, &serialPorts) < 0) {
11971 11972 11973
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("need at least one serial port "
                                 "for useserial"));
M
Michal Privoznik 已提交
11974 11975
                goto cleanup;
            }
J
Ján Tomko 已提交
11976
            def->os.bios.useserial = VIR_TRISTATE_BOOL_YES;
M
Michal Privoznik 已提交
11977
        } else {
J
Ján Tomko 已提交
11978
            def->os.bios.useserial = VIR_TRISTATE_BOOL_NO;
M
Michal Privoznik 已提交
11979
        }
M
Martin Kletzander 已提交
11980
        VIR_FREE(tmp);
M
Michal Privoznik 已提交
11981 11982
    }

11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996
    tmp = virXPathString("string(./os/bios[1]/@rebootTimeout)", ctxt);
    if (tmp) {
        /* that was really just for the check if it is there */

        if (virStrToLong_i(tmp, NULL, 0, &def->os.bios.rt_delay) < 0 ||
            def->os.bios.rt_delay < -1 || def->os.bios.rt_delay > 65535) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("invalid value for rebootTimeout, "
                             "must be in range [-1,65535]"));
            goto cleanup;
        }
        def->os.bios.rt_set = true;
    }

11997 11998
    ret = 0;

11999
 cleanup:
12000
    VIR_FREE(tmp);
12001 12002 12003 12004
    VIR_FREE(nodes);
    return ret;
}

12005

G
Gao feng 已提交
12006 12007
static int virDomainIdMapEntrySort(const void *a, const void *b)
{
12008 12009
    const virDomainIdMapEntry *entrya = a;
    const virDomainIdMapEntry *entryb = b;
G
Gao feng 已提交
12010 12011 12012 12013 12014 12015 12016 12017 12018

    if (entrya->start > entryb->start)
        return 1;
    else if (entrya->start < entryb->start)
        return -1;
    else
        return 0;
}

12019 12020 12021 12022 12023 12024 12025 12026 12027
/* Parse the XML definition for user namespace id map.
 *
 * idmap has the form of
 *
 *   <uid start='0' target='1000' count='10'/>
 *   <gid start='0' target='1000' count='10'/>
 */
static virDomainIdMapEntryPtr
virDomainIdmapDefParseXML(xmlXPathContextPtr ctxt,
12028
                          xmlNodePtr *node,
12029 12030 12031 12032 12033 12034
                          size_t num)
{
    size_t i;
    virDomainIdMapEntryPtr idmap = NULL;
    xmlNodePtr save_ctxt = ctxt->node;

12035
    if (VIR_ALLOC_N(idmap, num) < 0)
12036 12037 12038 12039 12040 12041 12042
        goto cleanup;

    for (i = 0; i < num; i++) {
        ctxt->node = node[i];
        if (virXPathUInt("string(./@start)", ctxt, &idmap[i].start) < 0 ||
            virXPathUInt("string(./@target)", ctxt, &idmap[i].target) < 0 ||
            virXPathUInt("string(./@count)", ctxt, &idmap[i].count) < 0) {
12043 12044
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("invalid idmap start/target/count settings"));
12045 12046 12047 12048 12049
            VIR_FREE(idmap);
            goto cleanup;
        }
    }

G
Gao feng 已提交
12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060
    qsort(idmap, num, sizeof(idmap[0]), virDomainIdMapEntrySort);

    if (idmap[0].start != 0) {
        /* Root user of container hasn't been mapped to any user of host,
         * return error. */
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("You must map the root user of container"));
        VIR_FREE(idmap);
        goto cleanup;
    }

12061
 cleanup:
12062 12063 12064 12065
    ctxt->node = save_ctxt;
    return idmap;
}

12066 12067 12068 12069 12070 12071 12072 12073
/* Parse the XML definition for a vcpupin or emulatorpin.
 *
 * vcpupin has the form of
 *   <vcpupin vcpu='0' cpuset='0'/>
 *
 * and emulatorpin has the form of
 *   <emulatorpin cpuset='0'/>
 *
12074 12075 12076
 * and an iothreadspin has the form
 *   <iothreadpin iothread='1' cpuset='2'/>
 *
12077 12078 12079
 * A vcpuid of -1 is valid and only valid for emulatorpin. So callers
 * have to check the returned cpuid for validity.
 */
E
Eric Blake 已提交
12080
static virDomainVcpuPinDefPtr
12081
virDomainVcpuPinDefParseXML(xmlNodePtr node,
12082
                            xmlXPathContextPtr ctxt,
12083
                            int maxvcpus,
12084 12085
                            bool emulator,
                            bool iothreads)
12086
{
E
Eric Blake 已提交
12087
    virDomainVcpuPinDefPtr def;
12088
    xmlNodePtr oldnode = ctxt->node;
12089
    int vcpuid = -1;
12090
    unsigned int iothreadid;
12091 12092 12093
    char *tmp = NULL;
    int ret;

12094
    if (VIR_ALLOC(def) < 0)
12095 12096 12097 12098
        return NULL;

    ctxt->node = node;

12099
    if (!emulator && !iothreads) {
12100 12101
        ret = virXPathInt("string(./@vcpu)", ctxt, &vcpuid);
        if ((ret == -2) || (vcpuid < -1)) {
12102 12103
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("vcpu id must be an unsigned integer or -1"));
12104 12105
            goto error;
        } else if (vcpuid == -1) {
12106 12107
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("vcpu id value -1 is not allowed for vcpupin"));
12108 12109
            goto error;
        }
12110

12111 12112 12113 12114 12115
        if (vcpuid >= maxvcpus) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("vcpu id must be less than maxvcpus"));
            goto error;
        }
12116

12117 12118
        def->vcpuid = vcpuid;
    }
12119

12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147
    if (iothreads && (tmp = virXPathString("string(./@iothread)", ctxt))) {
        if (virStrToLong_uip(tmp, NULL, 10, &iothreadid) < 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("invalid setting for iothread '%s'"), tmp);
            goto error;
        }
        VIR_FREE(tmp);

        if (iothreadid == 0) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("zero is an invalid iothread id value"));
            goto error;
        }

        /* NB: maxvcpus is actually def->iothreads
         * IOThreads are numbered "iothread1...iothread<n>", where
         * "n" is the iothreads value
         */
        if (iothreadid > maxvcpus) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("iothread id must not exceed iothreads"));
            goto error;
        }

        /* Rather than creating our own structure we are reusing the vCPU */
        def->vcpuid = iothreadid;
    }

12148 12149 12150 12151
    if (!(tmp = virXMLPropString(node, "cpuset"))) {
        if (emulator)
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("missing cpuset for emulatorpin"));
12152 12153 12154
        else if (iothreads)
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("missing cpuset for iothreadpin"));
12155 12156 12157
        else
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("missing cpuset for vcpupin"));
12158 12159 12160 12161

        goto error;
    }

12162 12163 12164
    if (virBitmapParse(tmp, 0, &def->cpumask, VIR_DOMAIN_CPUMASK_LEN) < 0)
        goto error;

12165
 cleanup:
12166
    VIR_FREE(tmp);
12167 12168 12169
    ctxt->node = oldnode;
    return def;

12170
 error:
12171 12172 12173 12174
    VIR_FREE(def);
    goto cleanup;
}

12175

12176
int
12177 12178 12179 12180
virDomainDefMaybeAddController(virDomainDefPtr def,
                               int type,
                               int idx,
                               int model)
12181
{
12182
    size_t i;
12183 12184
    virDomainControllerDefPtr cont;

12185
    for (i = 0; i < def->ncontrollers; i++) {
12186 12187
        if (def->controllers[i]->type == type &&
            def->controllers[i]->idx == idx)
12188
            return 0;
12189 12190
    }

12191
    if (VIR_ALLOC(cont) < 0)
12192 12193 12194 12195
        return -1;

    cont->type = type;
    cont->idx = idx;
12196
    cont->model = model;
12197 12198 12199 12200 12201 12202

    if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL) {
        cont->opts.vioserial.ports = -1;
        cont->opts.vioserial.vectors = -1;
    }

12203
    if (VIR_APPEND_ELEMENT(def->controllers, def->ncontrollers, cont) < 0) {
12204 12205 12206 12207 12208 12209 12210
        VIR_FREE(cont);
        return -1;
    }

    return 0;
}

E
Eric Blake 已提交
12211

12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240
int
virDomainDefMaybeAddInput(virDomainDefPtr def,
                          int type,
                          int bus)
{
    size_t i;
    virDomainInputDefPtr input;

    for (i = 0; i < def->ninputs; i++) {
        if (def->inputs[i]->type == type &&
            def->inputs[i]->bus == bus)
            return 0;
    }

    if (VIR_ALLOC(input) < 0)
        return -1;

    input->type = type;
    input->bus = bus;

    if (VIR_APPEND_ELEMENT(def->inputs, def->ninputs, input) < 0) {
        VIR_FREE(input);
        return -1;
    }

    return 0;
}


12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251
static int
virDomainHugepagesParseXML(xmlNodePtr node,
                           xmlXPathContextPtr ctxt,
                           virDomainHugePagePtr hugepage)
{
    int ret = -1;
    xmlNodePtr oldnode = ctxt->node;
    char *unit = NULL, *nodeset = NULL;

    ctxt->node = node;

12252 12253
    if (virDomainParseMemory("./@size", "./@unit", ctxt,
                             &hugepage->size, true, false) < 0)
12254 12255
        goto cleanup;

12256
    if (!hugepage->size) {
12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276
        virReportError(VIR_ERR_XML_DETAIL, "%s",
                       _("hugepage size can't be zero"));
        goto cleanup;
    }

    if ((nodeset = virXMLPropString(node, "nodeset"))) {
        if (virBitmapParse(nodeset, 0, &hugepage->nodemask,
                           VIR_DOMAIN_CPUMASK_LEN) < 0)
            goto cleanup;
    }

    ret = 0;
 cleanup:
    VIR_FREE(unit);
    VIR_FREE(nodeset);
    ctxt->node = oldnode;
    return ret;
}


12277 12278 12279 12280 12281 12282 12283 12284 12285
static virDomainResourceDefPtr
virDomainResourceDefParse(xmlNodePtr node,
                          xmlXPathContextPtr ctxt)
{
    virDomainResourceDefPtr def = NULL;
    xmlNodePtr tmp = ctxt->node;

    ctxt->node = node;

12286
    if (VIR_ALLOC(def) < 0)
12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298
        goto error;

    /* Find out what type of virtualization to use */
    if (!(def->partition = virXPathString("string(./partition)", ctxt))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing resource partition attribute"));
        goto error;
    }

    ctxt->node = tmp;
    return def;

12299
 error:
12300 12301 12302 12303 12304
    ctxt->node = tmp;
    virDomainResourceDefFree(def);
    return NULL;
}

12305 12306 12307 12308
static int
virDomainDefMaybeAddHostdevSCSIcontroller(virDomainDefPtr def)
{
    /* Look for any hostdev scsi dev */
12309
    size_t i;
12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321
    int maxController = -1;
    virDomainHostdevDefPtr hostdev;

    for (i = 0; i < def->nhostdevs; i++) {
        hostdev = def->hostdevs[i];
        if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
            hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
            (int)hostdev->info->addr.drive.controller > maxController) {
            maxController = hostdev->info->addr.drive.controller;
        }
    }

12322 12323 12324
    if (maxController == -1)
        return 0;

12325 12326 12327 12328 12329 12330 12331
    for (i = 0; i <= maxController; i++) {
        if (virDomainDefMaybeAddController(def, VIR_DOMAIN_CONTROLLER_TYPE_SCSI, i, -1) < 0)
            return -1;
    }

    return 0;
}
12332

12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368
static int
virDomainLoaderDefParseXML(xmlNodePtr node,
                           virDomainLoaderDefPtr loader)
{
    int ret = -1;
    char *readonly_str = NULL;
    char *type_str = NULL;

    readonly_str = virXMLPropString(node, "readonly");
    type_str = virXMLPropString(node, "type");
    loader->path = (char *) xmlNodeGetContent(node);

    if (readonly_str &&
        (loader->readonly = virTristateBoolTypeFromString(readonly_str)) <= 0) {
        virReportError(VIR_ERR_XML_DETAIL,
                       _("unknown readonly value: %s"), readonly_str);
        goto cleanup;
    }

    if (type_str) {
        int type;
        if ((type = virDomainLoaderTypeFromString(type_str)) < 0) {
            virReportError(VIR_ERR_XML_DETAIL,
                           _("unknown type value: %s"), type_str);
            goto cleanup;
        }
        loader->type = type;
    }

    ret = 0;
 cleanup:
    VIR_FREE(readonly_str);
    VIR_FREE(type_str);
    return ret;
}

12369
static virDomainDefPtr
12370
virDomainDefParseXML(xmlDocPtr xml,
12371 12372
                     xmlNodePtr root,
                     xmlXPathContextPtr ctxt,
12373 12374
                     virCapsPtr caps,
                     virDomainXMLOptionPtr xmlopt,
12375 12376
                     unsigned int expectedVirtTypes,
                     unsigned int flags)
12377 12378 12379
{
    xmlNodePtr *nodes = NULL, node = NULL;
    char *tmp = NULL;
12380
    size_t i, j;
12381
    int n;
12382
    long id = -1;
12383
    virDomainDefPtr def;
E
Eric Blake 已提交
12384
    unsigned long count;
12385
    bool uuid_generated = false;
12386
    virHashTablePtr bootHash = NULL;
12387 12388
    bool usb_none = false;
    bool usb_other = false;
12389
    bool usb_master = false;
12390
    bool primaryVideo = false;
12391

12392
    if (VIR_ALLOC(def) < 0)
12393
        return NULL;
12394 12395

    if (!(flags & VIR_DOMAIN_XML_INACTIVE))
E
Eric Blake 已提交
12396
        if (virXPathLong("string(./@id)", ctxt, &id) < 0)
12397 12398
            id = -1;
    def->id = (int)id;
12399

12400
    /* Find out what type of virtualization to use */
12401
    if (!(tmp = virXPathString("string(./@type)", ctxt))) {
12402 12403
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing domain type attribute"));
12404 12405 12406 12407
        goto error;
    }

    if ((def->virtType = virDomainVirtTypeFromString(tmp)) < 0) {
12408
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
12409
                       _("invalid domain type %s"), tmp);
12410 12411 12412 12413
        goto error;
    }
    VIR_FREE(tmp);

M
Matthias Bolte 已提交
12414 12415
    if ((expectedVirtTypes & (1 << def->virtType)) == 0) {
        if (count_one_bits(expectedVirtTypes) == 1) {
12416 12417 12418 12419
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected domain type %s, expecting %s"),
                           virDomainVirtTypeToString(def->virtType),
                           virDomainVirtTypeToString(ffs(expectedVirtTypes) - 1));
M
Matthias Bolte 已提交
12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432
        } else {
            virBuffer buffer = VIR_BUFFER_INITIALIZER;
            char *string;

            for (i = 0; i < VIR_DOMAIN_VIRT_LAST; ++i) {
                if ((expectedVirtTypes & (1 << i)) != 0) {
                    if (virBufferUse(&buffer) > 0)
                        virBufferAddLit(&buffer, ", ");

                    virBufferAdd(&buffer, virDomainVirtTypeToString(i), -1);
                }
            }

12433
            if (virBufferCheckError(&buffer) < 0)
M
Matthias Bolte 已提交
12434 12435 12436 12437
                goto error;

            string = virBufferContentAndReset(&buffer);

12438 12439 12440 12441 12442
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected domain type %s, "
                             "expecting one of these: %s"),
                           virDomainVirtTypeToString(def->virtType),
                           string);
M
Matthias Bolte 已提交
12443 12444 12445 12446 12447 12448 12449

            VIR_FREE(string);
        }

        goto error;
    }

12450
    /* Extract domain name */
12451
    if (!(def->name = virXPathString("string(./name[1])", ctxt))) {
12452
        virReportError(VIR_ERR_NO_NAME, NULL);
12453 12454 12455
        goto error;
    }

12456 12457 12458
    /* Extract domain uuid. If both uuid and sysinfo/system/entry/uuid
     * exist, they must match; and if only the latter exists, it can
     * also serve as the uuid. */
12459
    tmp = virXPathString("string(./uuid[1])", ctxt);
12460
    if (!tmp) {
12461
        if (virUUIDGenerate(def->uuid)) {
12462 12463
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Failed to generate UUID"));
12464 12465
            goto error;
        }
12466
        uuid_generated = true;
12467 12468
    } else {
        if (virUUIDParse(tmp, def->uuid) < 0) {
12469 12470
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("malformed uuid element"));
12471 12472 12473 12474 12475
            goto error;
        }
        VIR_FREE(tmp);
    }

12476 12477 12478
    /* Extract short description of domain (title) */
    def->title = virXPathString("string(./title[1])", ctxt);
    if (def->title && strchr(def->title, '\n')) {
12479 12480
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Domain title can't contain newlines"));
12481 12482 12483
        goto error;
    }

12484
    /* Extract documentation if present */
12485
    def->description = virXPathString("string(./description[1])", ctxt);
12486

E
Eric Blake 已提交
12487 12488
    /* analysis of security label, done early even though we format it
     * late, so devices can refer to this for defaults */
12489
    if (virSecurityLabelDefsParseXML(def, ctxt, caps, flags) == -1)
E
Eric Blake 已提交
12490 12491
        goto error;

12492
    /* Extract domain memory */
12493
    if (virDomainParseMemory("./memory[1]", NULL, ctxt,
12494
                             &def->mem.max_balloon, true, true) < 0)
12495 12496
        goto error;

12497
    if (virDomainParseMemory("./currentMemory[1]", NULL, ctxt,
12498
                             &def->mem.cur_balloon, false, true) < 0)
E
Eric Blake 已提交
12499
        goto error;
12500

12501
    /* and info about it */
12502
    if ((tmp = virXPathString("string(./memory[1]/@dumpCore)", ctxt)) &&
J
Ján Tomko 已提交
12503
        (def->mem.dump_core = virTristateSwitchTypeFromString(tmp)) <= 0) {
12504
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
12505 12506
                       _("Invalid memory core dump attribute value '%s'"), tmp);
        goto error;
12507
    }
12508
    VIR_FREE(tmp);
12509

12510
    if (def->mem.cur_balloon > def->mem.max_balloon) {
12511
        /* Older libvirt could get into this situation due to
12512
         * rounding; if the discrepancy is less than 4MiB, we silently
12513
         * round down, otherwise we flag the issue.  */
12514 12515
        if (VIR_DIV_UP(def->mem.cur_balloon, 4096) >
            VIR_DIV_UP(def->mem.max_balloon, 4096)) {
12516 12517 12518 12519
            virReportError(VIR_ERR_XML_ERROR,
                           _("current memory '%lluk' exceeds "
                             "maximum '%lluk'"),
                           def->mem.cur_balloon, def->mem.max_balloon);
12520 12521 12522 12523 12524 12525
            goto error;
        } else {
            VIR_DEBUG("Truncating current %lluk to maximum %lluk",
                      def->mem.cur_balloon, def->mem.max_balloon);
            def->mem.cur_balloon = def->mem.max_balloon;
        }
E
Eric Blake 已提交
12526 12527
    } else if (def->mem.cur_balloon == 0) {
        def->mem.cur_balloon = def->mem.max_balloon;
12528 12529
    }

12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578

    if ((n = virXPathNodeSet("./memoryBacking/hugepages/page", ctxt, &nodes)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot extract hugepages nodes"));
        goto error;
    }

    if (n) {
        if (VIR_ALLOC_N(def->mem.hugepages, n) < 0)
            goto error;

        for (i = 0; i < n; i++) {
            if (virDomainHugepagesParseXML(nodes[i], ctxt,
                                           &def->mem.hugepages[i]) < 0)
                goto error;
            def->mem.nhugepages++;

            for (j = 0; j < i; j++) {
                if (def->mem.hugepages[i].nodemask &&
                    def->mem.hugepages[j].nodemask &&
                    virBitmapOverlaps(def->mem.hugepages[i].nodemask,
                                      def->mem.hugepages[j].nodemask)) {
                    virReportError(VIR_ERR_XML_DETAIL,
                                   _("nodeset attribute of hugepages "
                                     "of sizes %llu and %llu intersect"),
                                   def->mem.hugepages[i].size,
                                   def->mem.hugepages[j].size);
                    goto error;
                } else if (!def->mem.hugepages[i].nodemask &&
                           !def->mem.hugepages[j].nodemask) {
                    virReportError(VIR_ERR_XML_DETAIL,
                                   _("two master hugepages detected: "
                                     "%llu and %llu"),
                                   def->mem.hugepages[i].size,
                                   def->mem.hugepages[j].size);
                    goto error;
                }
            }
        }

        VIR_FREE(nodes);
    } else {
        if ((node = virXPathNode("./memoryBacking/hugepages", ctxt))) {
            if (VIR_ALLOC(def->mem.hugepages) < 0)
                goto error;

            def->mem.nhugepages = 1;
        }
    }
12579

12580 12581 12582
    if ((node = virXPathNode("./memoryBacking/nosharepages", ctxt)))
        def->mem.nosharepages = true;

12583 12584 12585
    if (virXPathBoolean("boolean(./memoryBacking/locked)", ctxt))
        def->mem.locked = true;

12586 12587 12588 12589 12590
    /* Extract blkio cgroup tunables */
    if (virXPathUInt("string(./blkiotune/weight)", ctxt,
                     &def->blkio.weight) < 0)
        def->blkio.weight = 0;

12591
    if ((n = virXPathNodeSet("./blkiotune/device", ctxt, &nodes)) < 0) {
12592 12593
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot extract blkiotune nodes"));
12594 12595 12596
        goto error;
    }
    if (n && VIR_ALLOC_N(def->blkio.devices, n) < 0)
12597
        goto error;
12598 12599

    for (i = 0; i < n; i++) {
12600 12601
        if (virDomainBlkioDeviceParseXML(nodes[i],
                                         &def->blkio.devices[i]) < 0)
12602 12603
            goto error;
        def->blkio.ndevices++;
12604 12605 12606
        for (j = 0; j < i; j++) {
            if (STREQ(def->blkio.devices[j].path,
                      def->blkio.devices[i].path)) {
12607
                virReportError(VIR_ERR_XML_ERROR,
12608
                               _("duplicate blkio device path '%s'"),
12609
                               def->blkio.devices[i].path);
12610 12611 12612
                goto error;
            }
        }
12613 12614 12615
    }
    VIR_FREE(nodes);

12616
    /* Extract other memory tunables */
12617
    if (virDomainParseMemory("./memtune/hard_limit[1]", NULL, ctxt,
12618
                             &def->mem.hard_limit, false, false) < 0)
E
Eric Blake 已提交
12619
        goto error;
12620

12621
    if (virDomainParseMemory("./memtune/soft_limit[1]", NULL, ctxt,
12622
                             &def->mem.soft_limit, false, false) < 0)
E
Eric Blake 已提交
12623
        goto error;
12624

12625
    if (virDomainParseMemory("./memtune/min_guarantee[1]", NULL, ctxt,
12626
                             &def->mem.min_guarantee, false, false) < 0)
E
Eric Blake 已提交
12627
        goto error;
12628

12629
    if (virDomainParseMemory("./memtune/swap_hard_limit[1]", NULL, ctxt,
12630
                             &def->mem.swap_hard_limit, false, false) < 0)
E
Eric Blake 已提交
12631
        goto error;
12632

E
Eric Blake 已提交
12633 12634
    n = virXPathULong("string(./vcpu[1])", ctxt, &count);
    if (n == -2) {
12635 12636
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("maximum vcpus must be an integer"));
E
Eric Blake 已提交
12637 12638 12639 12640 12641
        goto error;
    } else if (n < 0) {
        def->maxvcpus = 1;
    } else {
        def->maxvcpus = count;
12642
        if (count == 0 || (unsigned short) count != count) {
12643
            virReportError(VIR_ERR_XML_ERROR,
12644
                           _("invalid maximum number of vCPUs '%lu'"), count);
E
Eric Blake 已提交
12645 12646 12647 12648 12649 12650
            goto error;
        }
    }

    n = virXPathULong("string(./vcpu[1]/@current)", ctxt, &count);
    if (n == -2) {
12651 12652
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("current vcpus must be an integer"));
E
Eric Blake 已提交
12653 12654 12655 12656 12657
        goto error;
    } else if (n < 0) {
        def->vcpus = def->maxvcpus;
    } else {
        def->vcpus = count;
12658
        if (count == 0 || (unsigned short) count != count) {
12659
            virReportError(VIR_ERR_XML_ERROR,
12660
                           _("invalid current number of vCPUs '%lu'"), count);
E
Eric Blake 已提交
12661 12662
            goto error;
        }
12663 12664

        if (def->maxvcpus < count) {
12665
            virReportError(VIR_ERR_INTERNAL_ERROR,
12666 12667
                           _("maxvcpus must not be less than current vcpus "
                             "(%d < %lu)"),
12668
                           def->maxvcpus, count);
12669 12670
            goto error;
        }
E
Eric Blake 已提交
12671
    }
12672

O
Osier Yang 已提交
12673 12674 12675 12676
    tmp = virXPathString("string(./vcpu[1]/@placement)", ctxt);
    if (tmp) {
        if ((def->placement_mode =
             virDomainCpuPlacementModeTypeFromString(tmp)) < 0) {
12677
             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
12678 12679
                            _("Unsupported CPU placement mode '%s'"),
                            tmp);
O
Osier Yang 已提交
12680 12681 12682 12683
             goto error;
        }
        VIR_FREE(tmp);
    } else {
12684
        def->placement_mode = VIR_DOMAIN_CPU_PLACEMENT_MODE_STATIC;
O
Osier Yang 已提交
12685 12686
    }

12687
    if (def->placement_mode != VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO) {
12688 12689
        tmp = virXPathString("string(./vcpu[1]/@cpuset)", ctxt);
        if (tmp) {
H
Hu Tao 已提交
12690
            if (virBitmapParse(tmp, 0, &def->cpumask,
12691
                               VIR_DOMAIN_CPUMASK_LEN) < 0)
12692
                goto error;
12693
            VIR_FREE(tmp);
12694 12695 12696
        }
    }

12697 12698 12699 12700 12701 12702 12703 12704 12705
    /* Optional - iothreads */
    tmp = virXPathString("string(./iothreads[1])", ctxt);
    if (tmp && virStrToLong_uip(tmp, NULL, 10, &def->iothreads) < 0) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("invalid iothreads count '%s'"), tmp);
        goto error;
    }
    VIR_FREE(tmp);

12706
    /* Extract cpu tunables. */
12707 12708
    if ((n = virXPathULong("string(./cputune/shares[1])", ctxt,
                           &def->cputune.shares)) < -1) {
12709 12710 12711
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("can't parse cputune shares value"));
        goto error;
12712 12713
    } else if (n == 0) {
        def->cputune.sharesSpecified = true;
12714
    }
12715

12716
    if (virXPathULongLong("string(./cputune/period[1])", ctxt,
12717 12718 12719 12720 12721
                          &def->cputune.period) < -1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("can't parse cputune period value"));
        goto error;
    }
12722

12723 12724 12725 12726 12727 12728 12729 12730
    if (def->cputune.period > 0 &&
        (def->cputune.period < 1000 || def->cputune.period > 1000000)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Value of cputune period must be in range "
                         "[1000, 1000000]"));
        goto error;
    }

12731
    if (virXPathLongLong("string(./cputune/quota[1])", ctxt,
12732 12733 12734 12735 12736
                         &def->cputune.quota) < -1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("can't parse cputune quota value"));
        goto error;
    }
12737

12738 12739
    if (def->cputune.quota > 0 &&
        (def->cputune.quota < 1000 ||
E
Eric Blake 已提交
12740
         def->cputune.quota > 18446744073709551LL)) {
12741 12742 12743 12744 12745 12746
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Value of cputune quota must be in range "
                         "[1000, 18446744073709551]"));
        goto error;
    }

12747
    if (virXPathULongLong("string(./cputune/emulator_period[1])", ctxt,
12748 12749 12750 12751 12752
                          &def->cputune.emulator_period) < -1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("can't parse cputune emulator period value"));
        goto error;
    }
12753

12754 12755 12756 12757 12758 12759 12760 12761 12762
    if (def->cputune.emulator_period > 0 &&
        (def->cputune.emulator_period < 1000 ||
         def->cputune.emulator_period > 1000000)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Value of cputune emulator_period must be in range "
                         "[1000, 1000000]"));
        goto error;
    }

12763
    if (virXPathLongLong("string(./cputune/emulator_quota[1])", ctxt,
12764 12765 12766
                         &def->cputune.emulator_quota) < -1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("can't parse cputune emulator quota value"));
12767 12768 12769
        goto error;
    }

12770 12771
    if (def->cputune.emulator_quota > 0 &&
        (def->cputune.emulator_quota < 1000 ||
E
Eric Blake 已提交
12772
         def->cputune.emulator_quota > 18446744073709551LL)) {
12773 12774 12775 12776 12777 12778
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Value of cputune emulator_quota must be in range "
                         "[1000, 18446744073709551]"));
        goto error;
    }

12779 12780 12781
    if ((n = virXPathNodeSet("./cputune/vcpupin", ctxt, &nodes)) < 0)
        goto error;

12782
    if (n && VIR_ALLOC_N(def->cputune.vcpupin, n) < 0)
12783
        goto error;
12784

12785
    for (i = 0; i < n; i++) {
E
Eric Blake 已提交
12786
        virDomainVcpuPinDefPtr vcpupin = NULL;
12787
        vcpupin = virDomainVcpuPinDefParseXML(nodes[i], ctxt,
12788
                                              def->maxvcpus, false, false);
12789 12790 12791 12792

        if (!vcpupin)
            goto error;

E
Eric Blake 已提交
12793
        if (virDomainVcpuPinIsDuplicate(def->cputune.vcpupin,
12794 12795
                                        def->cputune.nvcpupin,
                                        vcpupin->vcpuid)) {
12796 12797
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("duplicate vcpupin for same vcpu"));
12798
            virDomainVcpuPinDefFree(vcpupin);
12799 12800 12801
            goto error;
        }

12802
        if (vcpupin->vcpuid >= def->vcpus) {
12803 12804 12805 12806 12807 12808
            /* To avoid the regression when daemon loading
             * domain confs, we can't simply error out if
             * <vcpupin> nodes greater than current vcpus,
             * ignoring them instead.
             */
            VIR_WARN("Ignore vcpupin for not onlined vcpus");
12809 12810
            virDomainVcpuPinDefFree(vcpupin);
        } else {
12811
            def->cputune.vcpupin[def->cputune.nvcpupin++] = vcpupin;
12812
        }
12813 12814 12815
    }
    VIR_FREE(nodes);

12816 12817 12818 12819
    /* Initialize the pinning policy for vcpus which doesn't has
     * the policy specified explicitly as def->cpuset.
     */
    if (def->cpumask) {
12820
        if (VIR_REALLOC_N(def->cputune.vcpupin, def->vcpus) < 0)
12821
            goto error;
12822 12823

        for (i = 0; i < def->vcpus; i++) {
12824 12825 12826 12827
            if (virDomainVcpuPinIsDuplicate(def->cputune.vcpupin,
                                            def->cputune.nvcpupin,
                                            i))
                continue;
12828

12829
            virDomainVcpuPinDefPtr vcpupin = NULL;
12830

12831
            if (VIR_ALLOC(vcpupin) < 0)
12832 12833
                goto error;

12834 12835
            if (!(vcpupin->cpumask = virBitmapNew(VIR_DOMAIN_CPUMASK_LEN))) {
                VIR_FREE(vcpupin);
12836
                goto error;
12837
            }
12838 12839 12840
            virBitmapCopy(vcpupin->cpumask, def->cpumask);
            vcpupin->vcpuid = i;
            def->cputune.vcpupin[def->cputune.nvcpupin++] = vcpupin;
12841 12842 12843
        }
    }

T
Tang Chen 已提交
12844 12845 12846 12847 12848 12849
    if ((n = virXPathNodeSet("./cputune/emulatorpin", ctxt, &nodes)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot extract emulatorpin nodes"));
        goto error;
    }

12850 12851 12852 12853
    /* Ignore emulatorpin if <vcpu> placement is "auto", they
     * conflicts with each other, and <vcpu> placement can't be
     * simply ignored, as <numatune>'s placement defaults to it.
     */
T
Tang Chen 已提交
12854
    if (n) {
12855 12856 12857 12858 12859 12860 12861
        if (def->placement_mode != VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO) {
            if (n > 1) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("only one emulatorpin is supported"));
                VIR_FREE(nodes);
                goto error;
            }
T
Tang Chen 已提交
12862

12863 12864 12865
            def->cputune.emulatorpin = virDomainVcpuPinDefParseXML(nodes[0],
                                                                   ctxt, 0,
                                                                   true, false);
T
Tang Chen 已提交
12866

12867 12868 12869 12870 12871
            if (!def->cputune.emulatorpin)
                goto error;
        } else {
            VIR_WARN("Ignore emulatorpin for <vcpu> placement is 'auto'");
        }
T
Tang Chen 已提交
12872 12873 12874
    }
    VIR_FREE(nodes);

12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917

    if ((n = virXPathNodeSet("./cputune/iothreadpin", ctxt, &nodes)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot extract iothreadpin nodes"));
        goto error;
    }

    /* Ignore iothreadpin if <vcpu> placement is "auto", they
     * conflict with each other, and <vcpu> placement can't be
     * simply ignored, as <numatune>'s placement defaults to it.
     */
    if (n) {
        if (def->placement_mode != VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO) {
            if (VIR_ALLOC_N(def->cputune.iothreadspin, n) < 0)
                goto error;

            for (i = 0; i < n; i++) {
                virDomainVcpuPinDefPtr iothreadpin = NULL;
                iothreadpin = virDomainVcpuPinDefParseXML(nodes[i], ctxt,
                                                          def->iothreads,
                                                          false, true);
                if (!iothreadpin)
                    goto error;

                if (virDomainVcpuPinIsDuplicate(def->cputune.iothreadspin,
                                                def->cputune.niothreadspin,
                                                iothreadpin->vcpuid)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("duplicate iothreadpin for same iothread"));
                    virDomainVcpuPinDefFree(iothreadpin);
                    goto error;
                }

                def->cputune.iothreadspin[def->cputune.niothreadspin++] =
                    iothreadpin;
            }
        } else {
            VIR_WARN("Ignore iothreadpin for <vcpu> placement is 'auto'");
        }
    }
    VIR_FREE(nodes);


M
Martin Kletzander 已提交
12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943
    /* analysis of cpu handling */
    if ((node = virXPathNode("./cpu[1]", ctxt)) != NULL) {
        xmlNodePtr oldnode = ctxt->node;
        ctxt->node = node;
        def->cpu = virCPUDefParseXML(node, ctxt, VIR_CPU_TYPE_GUEST);
        ctxt->node = oldnode;

        if (def->cpu == NULL)
            goto error;

        if (def->cpu->sockets &&
            def->maxvcpus >
            def->cpu->sockets * def->cpu->cores * def->cpu->threads) {
            virReportError(VIR_ERR_XML_DETAIL, "%s",
                           _("Maximum CPUs greater than topology limit"));
            goto error;
        }

        if (def->cpu->cells_cpus > def->maxvcpus) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Number of CPUs in <numa> exceeds the"
                             " <vcpu> count"));
            goto error;
        }
    }

12944 12945 12946 12947 12948
    if (virDomainNumatuneParseXML(&def->numatune,
                                  def->placement_mode ==
                                  VIR_DOMAIN_CPU_PLACEMENT_MODE_STATIC,
                                  def->cpu ? def->cpu->ncells : 0,
                                  ctxt) < 0)
12949 12950
        goto error;

12951 12952 12953
    if (virDomainNumatuneHasPlacementAuto(def->numatune) && !def->cpumask)
        def->placement_mode = VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO;

12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970
    if ((n = virXPathNodeSet("./resource", ctxt, &nodes)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot extract resource nodes"));
        goto error;
    }

    if (n > 1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("only one resource element is supported"));
        goto error;
    }

    if (n &&
        !(def->resource = virDomainResourceDefParse(nodes[0], ctxt)))
        goto error;
    VIR_FREE(nodes);

12971
    if ((n = virXPathNodeSet("./features/*", ctxt, &nodes)) < 0)
12972
        goto error;
12973

12974
    for (i = 0; i < n; i++) {
12975 12976
        int val = virDomainFeatureTypeFromString((const char *)nodes[i]->name);
        if (val < 0) {
12977
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
12978
                           _("unexpected feature '%s'"), nodes[i]->name);
12979 12980
            goto error;
        }
12981

12982
        switch ((virDomainFeature) val) {
12983 12984
        case VIR_DOMAIN_FEATURE_APIC:
            if ((tmp = virXPathString("string(./features/apic/@eoi)", ctxt))) {
12985
                int eoi;
J
Ján Tomko 已提交
12986
                if ((eoi = virTristateSwitchTypeFromString(tmp)) <= 0) {
12987
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
12988
                                   _("unknown value for attribute eoi: '%s'"),
12989 12990
                                   tmp);
                    goto error;
12991
                }
12992 12993
                def->apic_eoi = eoi;
                VIR_FREE(tmp);
12994
            }
12995 12996 12997 12998 12999 13000 13001
            /* fallthrough */
        case VIR_DOMAIN_FEATURE_ACPI:
        case VIR_DOMAIN_FEATURE_PAE:
        case VIR_DOMAIN_FEATURE_HAP:
        case VIR_DOMAIN_FEATURE_VIRIDIAN:
        case VIR_DOMAIN_FEATURE_PRIVNET:
        case VIR_DOMAIN_FEATURE_HYPERV:
13002
        case VIR_DOMAIN_FEATURE_KVM:
J
Ján Tomko 已提交
13003
            def->features[val] = VIR_TRISTATE_SWITCH_ON;
13004 13005
            break;

13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017
        case VIR_DOMAIN_FEATURE_CAPABILITIES:
            node = ctxt->node;
            ctxt->node = nodes[i];
            if ((tmp = virXPathString("string(./@policy)", ctxt))) {
                if ((def->features[val] = virDomainCapabilitiesPolicyTypeFromString(tmp)) == -1) {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("unknown state attribute '%s' of feature '%s'"),
                                   tmp, virDomainFeatureTypeToString(val));
                    goto error;
                }
                VIR_FREE(tmp);
            } else {
J
Ján Tomko 已提交
13018
                def->features[val] = VIR_TRISTATE_SWITCH_ABSENT;
13019 13020 13021
            }
            ctxt->node = node;
            break;
13022 13023 13024 13025
        case VIR_DOMAIN_FEATURE_PVSPINLOCK:
            node = ctxt->node;
            ctxt->node = nodes[i];
            if ((tmp = virXPathString("string(./@state)", ctxt))) {
J
Ján Tomko 已提交
13026
                if ((def->features[val] = virTristateSwitchTypeFromString(tmp)) == -1) {
13027
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
Y
Yuri Chornoivan 已提交
13028
                                   _("unknown state attribute '%s' of feature '%s'"),
13029 13030 13031
                                   tmp, virDomainFeatureTypeToString(val));
                    goto error;
                }
13032
                VIR_FREE(tmp);
13033
            } else {
J
Ján Tomko 已提交
13034
                def->features[val] = VIR_TRISTATE_SWITCH_ON;
13035 13036 13037 13038
            }
            ctxt->node = node;
            break;

13039
        /* coverity[dead_error_begin] */
13040 13041
        case VIR_DOMAIN_FEATURE_LAST:
            break;
13042 13043
        }
    }
13044
    VIR_FREE(nodes);
13045

J
Ján Tomko 已提交
13046
    if (def->features[VIR_DOMAIN_FEATURE_HYPERV] == VIR_TRISTATE_SWITCH_ON) {
13047 13048 13049 13050 13051 13052 13053 13054 13055
        int feature;
        int value;
        node = ctxt->node;
        if ((n = virXPathNodeSet("./features/hyperv/*", ctxt, &nodes)) < 0)
            goto error;

        for (i = 0; i < n; i++) {
            feature = virDomainHypervTypeFromString((const char *)nodes[i]->name);
            if (feature < 0) {
13056
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
13057 13058 13059 13060 13061 13062 13063
                               _("unsupported HyperV Enlightenment feature: %s"),
                               nodes[i]->name);
                goto error;
            }

            ctxt->node = nodes[i];

13064
            switch ((virDomainHyperv) feature) {
13065
                case VIR_DOMAIN_HYPERV_RELAXED:
13066
                case VIR_DOMAIN_HYPERV_VAPIC:
13067 13068 13069 13070 13071 13072 13073 13074
                    if (!(tmp = virXPathString("string(./@state)", ctxt))) {
                        virReportError(VIR_ERR_XML_ERROR,
                                       _("missing 'state' attribute for "
                                         "HyperV Enlightenment feature '%s'"),
                                       nodes[i]->name);
                        goto error;
                    }

J
Ján Tomko 已提交
13075
                    if ((value = virTristateSwitchTypeFromString(tmp)) < 0) {
13076
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
13077 13078 13079 13080 13081 13082
                                       _("invalid value of state argument "
                                         "for HyperV Enlightenment feature '%s'"),
                                       nodes[i]->name);
                        goto error;
                    }

13083
                    VIR_FREE(tmp);
13084 13085 13086
                    def->hyperv_features[feature] = value;
                    break;

13087 13088 13089 13090 13091 13092 13093 13094 13095
                case VIR_DOMAIN_HYPERV_SPINLOCKS:
                    if (!(tmp = virXPathString("string(./@state)", ctxt))) {
                        virReportError(VIR_ERR_XML_ERROR,
                                       _("missing 'state' attribute for "
                                         "HyperV Enlightenment feature '%s'"),
                                       nodes[i]->name);
                        goto error;
                    }

J
Ján Tomko 已提交
13096
                    if ((value = virTristateSwitchTypeFromString(tmp)) < 0) {
13097
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
13098 13099 13100 13101 13102 13103 13104
                                       _("invalid value of state argument "
                                         "for HyperV Enlightenment feature '%s'"),
                                       nodes[i]->name);
                        goto error;
                    }

                    VIR_FREE(tmp);
J
Ján Tomko 已提交
13105
                    if (value == VIR_TRISTATE_SWITCH_ON) {
13106 13107 13108 13109 13110 13111
                        if (virXPathUInt("string(./@retries)", ctxt,
                                     &def->hyperv_spinlocks) < 0) {
                            virReportError(VIR_ERR_XML_ERROR, "%s",
                                           _("invalid HyperV spinlock retry count"));
                            goto error;
                        }
13112

13113 13114 13115 13116 13117 13118
                        if (def->hyperv_spinlocks < 0xFFF) {
                            virReportError(VIR_ERR_XML_ERROR, "%s",
                                           _("HyperV spinlock retry count must be "
                                             "at least 4095"));
                            goto error;
                        }
13119 13120 13121 13122
                    }
                    def->hyperv_features[feature] = value;
                    break;

13123
                /* coverity[dead_error_begin] */
13124 13125 13126 13127 13128 13129 13130 13131
                case VIR_DOMAIN_HYPERV_LAST:
                    break;
            }
        }
        VIR_FREE(nodes);
        ctxt->node = node;
    }

13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171
    if (def->features[VIR_DOMAIN_FEATURE_KVM] == VIR_TRISTATE_SWITCH_ON) {
        int feature;
        int value;
        node = ctxt->node;
        if ((n = virXPathNodeSet("./features/kvm/*", ctxt, &nodes)) < 0)
            goto error;

        for (i = 0; i < n; i++) {
            feature = virDomainKVMTypeFromString((const char *)nodes[i]->name);
            if (feature < 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unsupported KVM feature: %s"),
                               nodes[i]->name);
                goto error;
            }

            ctxt->node = nodes[i];

            switch ((virDomainKVM) feature) {
                case VIR_DOMAIN_KVM_HIDDEN:
                    if (!(tmp = virXPathString("string(./@state)", ctxt))) {
                        virReportError(VIR_ERR_XML_ERROR,
                                       _("missing 'state' attribute for "
                                         "KVM feature '%s'"),
                                       nodes[i]->name);
                        goto error;
                    }

                    if ((value = virTristateSwitchTypeFromString(tmp)) < 0) {
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                       _("invalid value of state argument "
                                         "for KVM feature '%s'"),
                                       nodes[i]->name);
                        goto error;
                    }

                    VIR_FREE(tmp);
                    def->kvm_features[feature] = value;
                    break;

13172
                /* coverity[dead_error_begin] */
13173 13174 13175 13176 13177 13178 13179 13180
                case VIR_DOMAIN_KVM_LAST:
                    break;
            }
        }
        VIR_FREE(nodes);
        ctxt->node = node;
    }

13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196
    if ((n = virXPathNodeSet("./features/capabilities/*", ctxt, &nodes)) < 0)
        goto error;

    for (i = 0; i < n; i++) {
        int val = virDomainCapsFeatureTypeFromString((const char *)nodes[i]->name);
        if (val < 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unexpected capability feature '%s'"), nodes[i]->name);
            goto error;
        }

        if (val >= 0 && val < VIR_DOMAIN_CAPS_FEATURE_LAST) {
            node = ctxt->node;
            ctxt->node = nodes[i];

            if ((tmp = virXPathString("string(./@state)", ctxt))) {
J
Ján Tomko 已提交
13197
                if ((def->caps_features[val] = virTristateSwitchTypeFromString(tmp)) == -1) {
13198 13199 13200 13201 13202 13203 13204
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("unknown state attribute '%s' of feature capability '%s'"),
                                   tmp, virDomainFeatureTypeToString(val));
                    goto error;
                }
                VIR_FREE(tmp);
            } else {
J
Ján Tomko 已提交
13205
                def->caps_features[val] = VIR_TRISTATE_SWITCH_ON;
13206 13207 13208 13209 13210 13211
            }
            ctxt->node = node;
        }
    }
    VIR_FREE(nodes);

13212 13213 13214 13215 13216
    if (virDomainEventActionParseXML(ctxt, "on_reboot",
                                     "string(./on_reboot[1])",
                                     &def->onReboot,
                                     VIR_DOMAIN_LIFECYCLE_RESTART,
                                     virDomainLifecycleTypeFromString) < 0)
13217 13218
        goto error;

13219 13220 13221 13222 13223
    if (virDomainEventActionParseXML(ctxt, "on_poweroff",
                                     "string(./on_poweroff[1])",
                                     &def->onPoweroff,
                                     VIR_DOMAIN_LIFECYCLE_DESTROY,
                                     virDomainLifecycleTypeFromString) < 0)
13224 13225
        goto error;

13226 13227 13228 13229 13230
    if (virDomainEventActionParseXML(ctxt, "on_crash",
                                     "string(./on_crash[1])",
                                     &def->onCrash,
                                     VIR_DOMAIN_LIFECYCLE_CRASH_DESTROY,
                                     virDomainLifecycleCrashTypeFromString) < 0)
13231 13232
        goto error;

13233 13234 13235 13236 13237 13238 13239
    if (virDomainEventActionParseXML(ctxt, "on_lockfailure",
                                     "string(./on_lockfailure[1])",
                                     &def->onLockFailure,
                                     VIR_DOMAIN_LOCK_FAILURE_DEFAULT,
                                     virDomainLockFailureTypeFromString) < 0)
        goto error;

13240 13241 13242 13243 13244 13245 13246 13247 13248 13249
    if (virDomainPMStateParseXML(ctxt,
                                 "string(./pm/suspend-to-mem/@enabled)",
                                 &def->pm.s3) < 0)
        goto error;

    if (virDomainPMStateParseXML(ctxt,
                                 "string(./pm/suspend-to-disk/@enabled)",
                                 &def->pm.s4) < 0)
        goto error;

13250 13251
    if ((tmp = virXPathString("string(./clock/@offset)", ctxt)) &&
        (def->clock.offset = virDomainClockOffsetTypeFromString(tmp)) < 0) {
13252
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
13253 13254
                       _("unknown clock offset '%s'"), tmp);
        goto error;
13255
    }
13256 13257
    VIR_FREE(tmp);

13258
    switch (def->clock.offset) {
13259 13260 13261 13262 13263 13264 13265
    case VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME:
    case VIR_DOMAIN_CLOCK_OFFSET_UTC:
        tmp = virXPathString("string(./clock/@adjustment)", ctxt);
        if (tmp) {
            if (STREQ(tmp, "reset")) {
                def->clock.data.utc_reset = true;
            } else {
13266 13267
                if (virStrToLong_ll(tmp, NULL, 10,
                                    &def->clock.data.variable.adjustment) < 0) {
13268 13269 13270
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("unknown clock adjustment '%s'"),
                                   tmp);
13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288
                    goto error;
                }
                switch (def->clock.offset) {
                case VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME:
                    def->clock.data.variable.basis = VIR_DOMAIN_CLOCK_BASIS_LOCALTIME;
                    break;
                case VIR_DOMAIN_CLOCK_OFFSET_UTC:
                    def->clock.data.variable.basis = VIR_DOMAIN_CLOCK_BASIS_UTC;
                    break;
                }
                def->clock.offset = VIR_DOMAIN_CLOCK_OFFSET_VARIABLE;
            }
            VIR_FREE(tmp);
        } else {
            def->clock.data.utc_reset = false;
        }
        break;

13289 13290
    case VIR_DOMAIN_CLOCK_OFFSET_VARIABLE:
        if (virXPathLongLong("number(./clock/@adjustment)", ctxt,
13291 13292
                             &def->clock.data.variable.adjustment) < 0)
            def->clock.data.variable.adjustment = 0;
13293 13294 13295
        if (virXPathLongLong("number(./clock/@adjustment0)", ctxt,
                             &def->clock.data.variable.adjustment0) < 0)
            def->clock.data.variable.adjustment0 = 0;
13296 13297 13298
        tmp = virXPathString("string(./clock/@basis)", ctxt);
        if (tmp) {
            if ((def->clock.data.variable.basis = virDomainClockBasisTypeFromString(tmp)) < 0) {
13299
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
13300
                               _("unknown clock basis '%s'"), tmp);
13301 13302 13303 13304 13305 13306
                goto error;
            }
            VIR_FREE(tmp);
        } else {
            def->clock.data.variable.basis = VIR_DOMAIN_CLOCK_BASIS_UTC;
        }
13307 13308 13309 13310 13311
        break;

    case VIR_DOMAIN_CLOCK_OFFSET_TIMEZONE:
        def->clock.data.timezone = virXPathString("string(./clock/@timezone)", ctxt);
        if (!def->clock.data.timezone) {
13312 13313
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("missing 'timezone' attribute for clock with offset='timezone'"));
13314 13315
            goto error;
        }
13316 13317
        break;
    }
13318

13319
    if ((n = virXPathNodeSet("./clock/timer", ctxt, &nodes)) < 0)
13320
        goto error;
13321

13322
    if (n && VIR_ALLOC_N(def->clock.timers, n) < 0)
13323
        goto error;
13324

13325
    for (i = 0; i < n; i++) {
13326
        virDomainTimerDefPtr timer = virDomainTimerDefParseXML(nodes[i],
E
Eric Blake 已提交
13327
                                                               ctxt);
13328 13329 13330 13331 13332 13333 13334
        if (!timer)
            goto error;

        def->clock.timers[def->clock.ntimers++] = timer;
    }
    VIR_FREE(nodes);

13335 13336
    def->os.bootloader = virXPathString("string(./bootloader)", ctxt);
    def->os.bootloaderArgs = virXPathString("string(./bootloader_args)", ctxt);
13337

13338
    def->os.type = virXPathString("string(./os/type[1])", ctxt);
13339 13340
    if (!def->os.type) {
        if (def->os.bootloader) {
13341 13342
            if (VIR_STRDUP(def->os.type, "xen") < 0)
                goto error;
13343
        } else {
13344 13345
            virReportError(VIR_ERR_OS_TYPE,
                           "%s", _("no OS type"));
13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356
            goto error;
        }
    }
    /*
     * HACK: For xen driver we previously used bogus 'linux' as the
     * os type for paravirt, whereas capabilities declare it to
     * be 'xen'. So we accept the former and convert
     */
    if (STREQ(def->os.type, "linux") &&
        def->virtType == VIR_DOMAIN_VIRT_XEN) {
        VIR_FREE(def->os.type);
13357 13358
        if (VIR_STRDUP(def->os.type, "xen") < 0)
            goto error;
13359 13360 13361
    }

    if (!virCapabilitiesSupportsGuestOSType(caps, def->os.type)) {
13362 13363
        virReportError(VIR_ERR_OS_TYPE,
                       "%s", def->os.type);
13364 13365 13366
        goto error;
    }

13367 13368
    tmp = virXPathString("string(./os/type[1]/@arch)", ctxt);
    if (tmp) {
13369 13370
        def->os.arch = virArchFromString(tmp);
        if (!def->os.arch) {
13371 13372 13373 13374 13375 13376 13377
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Unknown architecture %s"),
                           tmp);
            goto error;
        }
        VIR_FREE(tmp);

13378
        if (!virCapabilitiesSupportsGuestArch(caps, def->os.arch)) {
13379 13380
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("No guest options available for arch '%s'"),
13381
                           virArchToString(def->os.arch));
13382 13383 13384 13385 13386 13387
            goto error;
        }

        if (!virCapabilitiesSupportsGuestOSTypeArch(caps,
                                                    def->os.type,
                                                    def->os.arch)) {
13388 13389
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("No os type '%s' available for arch '%s'"),
13390
                           def->os.type, virArchToString(def->os.arch));
13391 13392 13393
            goto error;
        }
    } else {
13394 13395 13396 13397 13398
        def->os.arch =
            virCapabilitiesDefaultGuestArch(caps,
                                            def->os.type,
                                            virDomainVirtTypeToString(def->virtType));
        if (!def->os.arch) {
13399 13400 13401
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("no supported architecture for os type '%s'"),
                           def->os.type);
13402 13403 13404 13405
            goto error;
        }
    }

13406
    def->os.machine = virXPathString("string(./os/type[1]/@machine)", ctxt);
13407 13408 13409
    if (!def->os.machine) {
        const char *defaultMachine = virCapabilitiesDefaultGuestMachine(caps,
                                                                        def->os.type,
13410 13411
                                                                        def->os.arch,
                                                                        virDomainVirtTypeToString(def->virtType));
13412 13413
        if (VIR_STRDUP(def->os.machine, defaultMachine) < 0)
            goto error;
13414 13415
    }

13416 13417 13418 13419 13420 13421 13422 13423 13424 13425
    /*
     * Booting options for different OS types....
     *
     *   - A bootloader (and optional kernel+initrd)  (xen)
     *   - A kernel + initrd                          (xen)
     *   - A boot device (and optional kernel+initrd) (hvm)
     *   - An init script                             (exe)
     */

    if (STREQ(def->os.type, "exe")) {
13426
        def->os.init = virXPathString("string(./os/init[1])", ctxt);
13427
        def->os.cmdline = virXPathString("string(./os/cmdline[1])", ctxt);
13428

13429
        if ((n = virXPathNodeSet("./os/initarg", ctxt, &nodes)) < 0)
13430 13431 13432
            goto error;

        if (VIR_ALLOC_N(def->os.initargv, n+1) < 0)
13433
            goto error;
13434
        for (i = 0; i < n; i++) {
13435 13436
            if (!nodes[i]->children ||
                !nodes[i]->children->content) {
13437 13438
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("No data supplied for <initarg> element"));
13439 13440
                goto error;
            }
13441 13442 13443
            if (VIR_STRDUP(def->os.initargv[i],
                           (const char*) nodes[i]->children->content) < 0)
                goto error;
13444 13445 13446
        }
        def->os.initargv[n] = NULL;
        VIR_FREE(nodes);
13447 13448 13449
    }

    if (STREQ(def->os.type, "xen") ||
13450 13451
        STREQ(def->os.type, "hvm") ||
        STREQ(def->os.type, "uml")) {
13452 13453
        xmlNodePtr loader_node;

13454 13455 13456
        def->os.kernel = virXPathString("string(./os/kernel[1])", ctxt);
        def->os.initrd = virXPathString("string(./os/initrd[1])", ctxt);
        def->os.cmdline = virXPathString("string(./os/cmdline[1])", ctxt);
13457
        def->os.dtb = virXPathString("string(./os/dtb[1])", ctxt);
13458
        def->os.root = virXPathString("string(./os/root[1])", ctxt);
13459 13460 13461 13462 13463 13464 13465 13466
        if ((loader_node = virXPathNode("./os/loader[1]", ctxt))) {
            if (VIR_ALLOC(def->os.loader) < 0)
                goto error;

            if (virDomainLoaderDefParseXML(loader_node, def->os.loader) < 0)
                goto error;

            def->os.loader->nvram = virXPathString("string(./os/nvram[1])", ctxt);
13467
            def->os.loader->templt = virXPathString("string(./os/nvram[1]/@template)", ctxt);
13468
        }
13469
    }
13470

13471
    if (STREQ(def->os.type, "hvm")) {
13472 13473 13474
        if (virDomainDefParseBootXML(ctxt, def) < 0)
            goto error;
        if (!(bootHash = virHashCreate(5, NULL)))
13475
            goto error;
13476 13477
    }

13478
    def->emulator = virXPathString("string(./devices/emulator[1])", ctxt);
13479 13480

    /* analysis of the disk devices */
13481
    if ((n = virXPathNodeSet("./devices/disk", ctxt, &nodes)) < 0)
13482
        goto error;
13483

13484
    if (n && VIR_ALLOC_N(def->disks, n) < 0)
13485
        goto error;
13486

13487
    for (i = 0; i < n; i++) {
13488
        virDomainDiskDefPtr disk = virDomainDiskDefParseXML(xmlopt,
13489
                                                            nodes[i],
L
Lei Li 已提交
13490
                                                            ctxt,
13491
                                                            bootHash,
13492 13493
                                                            def->seclabels,
                                                            def->nseclabels,
13494
                                                            flags);
13495 13496 13497
        if (!disk)
            goto error;

13498
        virDomainDiskInsertPreAlloced(def, disk);
13499 13500 13501
    }
    VIR_FREE(nodes);

13502
    /* analysis of the controller devices */
13503
    if ((n = virXPathNodeSet("./devices/controller", ctxt, &nodes)) < 0)
13504
        goto error;
13505

13506
    if (n && VIR_ALLOC_N(def->controllers, n) < 0)
13507
        goto error;
13508

13509
    for (i = 0; i < n; i++) {
13510
        virDomainControllerDefPtr controller = virDomainControllerDefParseXML(nodes[i],
13511
                                                                              ctxt,
13512 13513 13514 13515
                                                                              flags);
        if (!controller)
            goto error;

13516 13517 13518 13519
        /* sanitize handling of "none" usb controller */
        if (controller->type == VIR_DOMAIN_CONTROLLER_TYPE_USB) {
            if (controller->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE) {
                if (usb_other || usb_none) {
13520
                    virDomainControllerDefFree(controller);
13521 13522 13523 13524 13525 13526 13527 13528
                    virReportError(VIR_ERR_XML_DETAIL, "%s",
                                   _("Can't add another USB controller: "
                                     "USB is disabled for this domain"));
                    goto error;
                }
                usb_none = true;
            } else {
                if (usb_none) {
13529
                    virDomainControllerDefFree(controller);
13530 13531 13532 13533 13534 13535 13536
                    virReportError(VIR_ERR_XML_DETAIL, "%s",
                                   _("Can't add another USB controller: "
                                     "USB is disabled for this domain"));
                    goto error;
                }
                usb_other = true;
            }
13537 13538 13539

            if (controller->info.mastertype == VIR_DOMAIN_CONTROLLER_MASTER_NONE)
                usb_master = true;
13540 13541
        }

13542
        virDomainControllerInsertPreAlloced(def, controller);
13543 13544 13545
    }
    VIR_FREE(nodes);

13546 13547 13548 13549 13550 13551
    if (usb_other && !usb_master) {
        virReportError(VIR_ERR_XML_DETAIL, "%s",
                       _("No master USB controller specified"));
        goto error;
    }

13552 13553
    /* analysis of the resource leases */
    if ((n = virXPathNodeSet("./devices/lease", ctxt, &nodes)) < 0) {
13554 13555
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot extract device leases"));
13556 13557 13558
        goto error;
    }
    if (n && VIR_ALLOC_N(def->leases, n) < 0)
13559
        goto error;
13560
    for (i = 0; i < n; i++) {
13561 13562 13563 13564 13565 13566 13567 13568
        virDomainLeaseDefPtr lease = virDomainLeaseDefParseXML(nodes[i]);
        if (!lease)
            goto error;

        def->leases[def->nleases++] = lease;
    }
    VIR_FREE(nodes);

13569
    /* analysis of the filesystems */
13570
    if ((n = virXPathNodeSet("./devices/filesystem", ctxt, &nodes)) < 0)
13571
        goto error;
13572
    if (n && VIR_ALLOC_N(def->fss, n) < 0)
13573
        goto error;
13574
    for (i = 0; i < n; i++) {
13575
        virDomainFSDefPtr fs = virDomainFSDefParseXML(nodes[i], ctxt,
13576
                                                      flags);
13577 13578 13579
        if (!fs)
            goto error;

13580
        def->fss[def->nfss++] = fs;
13581 13582 13583
    }
    VIR_FREE(nodes);

13584
    /* analysis of the network devices */
13585
    if ((n = virXPathNodeSet("./devices/interface", ctxt, &nodes)) < 0)
13586
        goto error;
13587
    if (n && VIR_ALLOC_N(def->nets, n) < 0)
13588
        goto error;
13589
    for (i = 0; i < n; i++) {
13590
        virDomainNetDefPtr net = virDomainNetDefParseXML(xmlopt,
13591
                                                         nodes[i],
13592
                                                         ctxt,
13593
                                                         bootHash,
13594
                                                         flags);
13595 13596 13597
        if (!net)
            goto error;

13598
        def->nets[def->nnets++] = net;
13599

13600 13601 13602 13603 13604 13605
        /* <interface type='hostdev'> (and <interface type='net'>
         * where the actual network type is already known to be
         * hostdev) must also be in the hostdevs array.
         */
        if (virDomainNetGetActualType(net) == VIR_DOMAIN_NET_TYPE_HOSTDEV &&
            virDomainHostdevInsert(def, virDomainNetGetActualHostdev(net)) < 0) {
13606
            goto error;
13607
        }
13608 13609 13610 13611
    }
    VIR_FREE(nodes);


E
Eric Blake 已提交
13612
    /* analysis of the smartcard devices */
13613
    if ((n = virXPathNodeSet("./devices/smartcard", ctxt, &nodes)) < 0)
E
Eric Blake 已提交
13614 13615
        goto error;
    if (n && VIR_ALLOC_N(def->smartcards, n) < 0)
13616
        goto error;
E
Eric Blake 已提交
13617

13618
    for (i = 0; i < n; i++) {
E
Eric Blake 已提交
13619 13620 13621 13622 13623 13624 13625 13626 13627 13628
        virDomainSmartcardDefPtr card = virDomainSmartcardDefParseXML(nodes[i],
                                                                      flags);
        if (!card)
            goto error;

        def->smartcards[def->nsmartcards++] = card;
    }
    VIR_FREE(nodes);


13629
    /* analysis of the character devices */
13630
    if ((n = virXPathNodeSet("./devices/parallel", ctxt, &nodes)) < 0)
13631
        goto error;
13632
    if (n && VIR_ALLOC_N(def->parallels, n) < 0)
13633
        goto error;
13634

13635
    for (i = 0; i < n; i++) {
13636
        virDomainChrDefPtr chr = virDomainChrDefParseXML(ctxt,
13637
                                                         nodes[i],
13638 13639
                                                         def->seclabels,
                                                         def->nseclabels,
13640
                                                         flags);
13641 13642 13643
        if (!chr)
            goto error;

13644 13645
        if (chr->target.port == -1) {
            int maxport = -1;
13646
            for (j = 0; j < i; j++) {
13647 13648 13649 13650 13651
                if (def->parallels[j]->target.port > maxport)
                    maxport = def->parallels[j]->target.port;
            }
            chr->target.port = maxport + 1;
        }
13652
        def->parallels[def->nparallels++] = chr;
13653 13654 13655
    }
    VIR_FREE(nodes);

13656
    if ((n = virXPathNodeSet("./devices/serial", ctxt, &nodes)) < 0)
13657
        goto error;
13658

13659
    if (n && VIR_ALLOC_N(def->serials, n) < 0)
13660
        goto error;
13661

13662
    for (i = 0; i < n; i++) {
13663
        virDomainChrDefPtr chr = virDomainChrDefParseXML(ctxt,
13664
                                                         nodes[i],
13665 13666
                                                         def->seclabels,
                                                         def->nseclabels,
13667
                                                         flags);
13668 13669 13670
        if (!chr)
            goto error;

13671 13672
        if (chr->target.port == -1) {
            int maxport = -1;
13673
            for (j = 0; j < i; j++) {
13674 13675 13676 13677 13678
                if (def->serials[j]->target.port > maxport)
                    maxport = def->serials[j]->target.port;
            }
            chr->target.port = maxport + 1;
        }
13679
        def->serials[def->nserials++] = chr;
13680 13681 13682
    }
    VIR_FREE(nodes);

13683
    if ((n = virXPathNodeSet("./devices/console", ctxt, &nodes)) < 0) {
13684 13685
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot extract console devices"));
13686 13687 13688
        goto error;
    }
    if (n && VIR_ALLOC_N(def->consoles, n) < 0)
13689
        goto error;
13690

13691
    for (i = 0; i < n; i++) {
13692
        virDomainChrDefPtr chr = virDomainChrDefParseXML(ctxt,
13693
                                                         nodes[i],
13694 13695
                                                         def->seclabels,
                                                         def->nseclabels,
13696
                                                         flags);
13697 13698
        if (!chr)
            goto error;
13699

13700 13701
        chr->target.port = i;
        def->consoles[def->nconsoles++] = chr;
13702
    }
13703
    VIR_FREE(nodes);
13704

13705
    if ((n = virXPathNodeSet("./devices/channel", ctxt, &nodes)) < 0)
13706 13707
        goto error;
    if (n && VIR_ALLOC_N(def->channels, n) < 0)
13708
        goto error;
13709

13710
    for (i = 0; i < n; i++) {
13711
        virDomainChrDefPtr chr = virDomainChrDefParseXML(ctxt,
13712
                                                         nodes[i],
13713 13714
                                                         def->seclabels,
                                                         def->nseclabels,
13715 13716 13717 13718 13719
                                                         flags);
        if (!chr)
            goto error;

        def->channels[def->nchannels++] = chr;
13720

13721 13722
        if (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL &&
            chr->targetType == VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO &&
13723 13724 13725
            chr->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
            chr->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL;

13726 13727
        if (chr->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL &&
            chr->info.addr.vioserial.port == 0) {
13728
            int maxport = 0;
13729
            for (j = 0; j < i; j++) {
13730 13731 13732 13733 13734 13735 13736 13737 13738
                virDomainChrDefPtr thischr = def->channels[j];
                if (thischr->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL &&
                    thischr->info.addr.vioserial.controller == chr->info.addr.vioserial.controller &&
                    thischr->info.addr.vioserial.bus == chr->info.addr.vioserial.bus &&
                    (int)thischr->info.addr.vioserial.port > maxport)
                    maxport = thischr->info.addr.vioserial.port;
            }
            chr->info.addr.vioserial.port = maxport + 1;
        }
13739 13740 13741
    }
    VIR_FREE(nodes);

13742 13743

    /* analysis of the input devices */
13744
    if ((n = virXPathNodeSet("./devices/input", ctxt, &nodes)) < 0)
13745
        goto error;
13746
    if (n && VIR_ALLOC_N(def->inputs, n) < 0)
13747
        goto error;
13748

13749
    for (i = 0; i < n; i++) {
L
Li Zhang 已提交
13750
        virDomainInputDefPtr input = virDomainInputDefParseXML(def,
13751 13752
                                                               nodes[i],
                                                               flags);
13753 13754 13755
        if (!input)
            goto error;

13756 13757
        /* Check if USB bus is required */
        if (input->bus == VIR_DOMAIN_INPUT_BUS_USB && usb_none) {
13758
            virDomainInputDefFree(input);
13759 13760 13761 13762 13763
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Can't add USB input device. "
                             "USB bus is disabled"));
            goto error;
        }
13764 13765 13766 13767 13768 13769

        /* With QEMU / KVM / Xen graphics, mouse + PS/2 is implicit
         * with graphics, so don't store it.
         * XXX will this be true for other virt types ? */
        if ((STREQ(def->os.type, "hvm") &&
             input->bus == VIR_DOMAIN_INPUT_BUS_PS2 &&
L
Li Zhang 已提交
13770 13771
             (input->type == VIR_DOMAIN_INPUT_TYPE_MOUSE ||
              input->type == VIR_DOMAIN_INPUT_TYPE_KBD)) ||
13772 13773
            (STRNEQ(def->os.type, "hvm") &&
             input->bus == VIR_DOMAIN_INPUT_BUS_XEN &&
L
Li Zhang 已提交
13774 13775
             (input->type == VIR_DOMAIN_INPUT_TYPE_MOUSE ||
              input->type == VIR_DOMAIN_INPUT_TYPE_KBD))) {
13776 13777 13778 13779
            virDomainInputDefFree(input);
            continue;
        }

13780
        def->inputs[def->ninputs++] = input;
13781 13782 13783
    }
    VIR_FREE(nodes);

13784
    /* analysis of the graphics devices */
13785
    if ((n = virXPathNodeSet("./devices/graphics", ctxt, &nodes)) < 0)
13786
        goto error;
13787
    if (n && VIR_ALLOC_N(def->graphics, n) < 0)
13788
        goto error;
13789
    for (i = 0; i < n; i++) {
13790
        virDomainGraphicsDefPtr graphics = virDomainGraphicsDefParseXML(nodes[i],
13791
                                                                        ctxt,
13792
                                                                        flags);
13793 13794 13795
        if (!graphics)
            goto error;

13796
        def->graphics[def->ngraphics++] = graphics;
13797 13798 13799 13800
    }
    VIR_FREE(nodes);

    /* If graphics are enabled, there's an implicit PS2 mouse */
13801 13802
    if (def->ngraphics > 0 &&
        (ARCH_IS_X86(def->os.arch) || def->os.arch == VIR_ARCH_NONE)) {
13803
        int input_bus = VIR_DOMAIN_INPUT_BUS_XEN;
13804

13805 13806
        if (STREQ(def->os.type, "hvm"))
            input_bus = VIR_DOMAIN_INPUT_BUS_PS2;
13807

13808 13809 13810
        if (virDomainDefMaybeAddInput(def,
                                      VIR_DOMAIN_INPUT_TYPE_MOUSE,
                                      input_bus) < 0)
13811
            goto error;
13812

L
Li Zhang 已提交
13813 13814 13815 13816 13817
        if (virDomainDefMaybeAddInput(def,
                                      VIR_DOMAIN_INPUT_TYPE_KBD,
                                      input_bus) < 0)
            goto error;
    }
13818 13819

    /* analysis of the sound devices */
13820
    if ((n = virXPathNodeSet("./devices/sound", ctxt, &nodes)) < 0)
13821
        goto error;
13822
    if (n && VIR_ALLOC_N(def->sounds, n) < 0)
13823
        goto error;
13824
    for (i = 0; i < n; i++) {
13825
        virDomainSoundDefPtr sound = virDomainSoundDefParseXML(nodes[i],
13826
                                                               ctxt,
13827
                                                               flags);
13828 13829 13830
        if (!sound)
            goto error;

13831
        def->sounds[def->nsounds++] = sound;
13832 13833 13834
    }
    VIR_FREE(nodes);

13835
    /* analysis of the video devices */
13836
    if ((n = virXPathNodeSet("./devices/video", ctxt, &nodes)) < 0)
13837 13838
        goto error;
    if (n && VIR_ALLOC_N(def->videos, n) < 0)
13839
        goto error;
13840
    for (i = 0; i < n; i++) {
13841
        j = def->nvideos;
13842
        virDomainVideoDefPtr video = virDomainVideoDefParseXML(nodes[j],
13843 13844 13845 13846
                                                               def,
                                                               flags);
        if (!video)
            goto error;
13847 13848 13849

        if (video->primary) {
            if (primaryVideo) {
13850
                virDomainVideoDefFree(video);
13851 13852 13853 13854 13855
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("Only one primary video device is supported"));
                goto error;
            }

13856
            j = 0;
13857 13858
            primaryVideo = true;
        }
13859
        if (VIR_INSERT_ELEMENT_INPLACE(def->videos,
13860
                                       j,
13861 13862
                                       def->nvideos,
                                       video) < 0) {
13863
            virDomainVideoDefFree(video);
13864
            goto error;
13865
        }
13866 13867 13868
    }
    VIR_FREE(nodes);

13869
    /* For backwards compatibility, if no <video> tag is set but there
13870 13871 13872 13873
     * is a <graphics> tag, then we add a single video tag */
    if (def->ngraphics && !def->nvideos) {
        virDomainVideoDefPtr video;
        if (VIR_ALLOC(video) < 0)
13874
            goto error;
13875 13876
        video->type = virDomainVideoDefaultType(def);
        if (video->type < 0) {
13877 13878
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot determine default video type"));
13879 13880 13881 13882 13883 13884 13885
            VIR_FREE(video);
            goto error;
        }
        video->vram = virDomainVideoDefaultRAM(def, video->type);
        video->heads = 1;
        if (VIR_ALLOC_N(def->videos, 1) < 0) {
            virDomainVideoDefFree(video);
13886
            goto error;
13887 13888 13889 13890
        }
        def->videos[def->nvideos++] = video;
    }

13891
    /* analysis of the host devices */
13892
    if ((n = virXPathNodeSet("./devices/hostdev", ctxt, &nodes)) < 0)
13893
        goto error;
13894
    if (n && VIR_REALLOC_N(def->hostdevs, def->nhostdevs + n) < 0)
13895
        goto error;
13896
    for (i = 0; i < n; i++) {
13897 13898
        virDomainHostdevDefPtr hostdev;

13899 13900
        hostdev = virDomainHostdevDefParseXML(xmlopt, def, nodes[i],
                                              ctxt, bootHash, flags);
13901 13902 13903
        if (!hostdev)
            goto error;

13904 13905 13906 13907 13908
        if (hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB &&
            usb_none) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Can't add host USB device: "
                             "USB is disabled in this host"));
13909
            virDomainHostdevDefFree(hostdev);
13910 13911 13912
            goto error;
        }

13913
        def->hostdevs[def->nhostdevs++] = hostdev;
13914 13915 13916

        if (virDomainDefMaybeAddHostdevSCSIcontroller(def) < 0)
            goto error;
13917 13918 13919
    }
    VIR_FREE(nodes);

R
Richard Jones 已提交
13920 13921
    /* analysis of the watchdog devices */
    def->watchdog = NULL;
13922
    if ((n = virXPathNodeSet("./devices/watchdog", ctxt, &nodes)) < 0)
R
Richard Jones 已提交
13923 13924
        goto error;
    if (n > 1) {
13925 13926
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("only a single watchdog device is supported"));
R
Richard Jones 已提交
13927 13928 13929 13930
        goto error;
    }
    if (n > 0) {
        virDomainWatchdogDefPtr watchdog =
13931
            virDomainWatchdogDefParseXML(nodes[0], flags);
R
Richard Jones 已提交
13932 13933 13934 13935 13936 13937 13938
        if (!watchdog)
            goto error;

        def->watchdog = watchdog;
        VIR_FREE(nodes);
    }

13939 13940
    /* analysis of the memballoon devices */
    def->memballoon = NULL;
13941
    if ((n = virXPathNodeSet("./devices/memballoon", ctxt, &nodes)) < 0)
13942 13943
        goto error;
    if (n > 1) {
13944 13945
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("only a single memory balloon device is supported"));
13946 13947 13948 13949
        goto error;
    }
    if (n > 0) {
        virDomainMemballoonDefPtr memballoon =
13950
            virDomainMemballoonDefParseXML(nodes[0], ctxt, flags);
13951 13952 13953 13954 13955 13956 13957
        if (!memballoon)
            goto error;

        def->memballoon = memballoon;
        VIR_FREE(nodes);
    }

13958
    /* Parse the RNG devices */
13959 13960
    if ((n = virXPathNodeSet("./devices/rng", ctxt, &nodes)) < 0)
        goto error;
13961
    if (n && VIR_ALLOC_N(def->rngs, n) < 0)
13962
        goto error;
13963 13964 13965 13966 13967
    for (i = 0; i < n; i++) {
        virDomainRNGDefPtr rng = virDomainRNGDefParseXML(nodes[i],
                                                         ctxt,
                                                         flags);
        if (!rng)
13968
            goto error;
13969 13970

        def->rngs[def->nrngs++] = rng;
13971
    }
13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988
    VIR_FREE(nodes);

    /* Parse the TPM devices */
    if ((n = virXPathNodeSet("./devices/tpm", ctxt, &nodes)) < 0)
        goto error;

    if (n > 1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("only a single TPM device is supported"));
        goto error;
    }

    if (n > 0) {
        if (!(def->tpm = virDomainTPMDefParseXML(nodes[0], ctxt, flags)))
            goto error;
    }
    VIR_FREE(nodes);
13989

13990
    if ((n = virXPathNodeSet("./devices/nvram", ctxt, &nodes)) < 0)
L
Li Zhang 已提交
13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005
        goto error;

    if (n > 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("only a single nvram device is supported"));
        goto error;
    } else if (n == 1) {
        virDomainNVRAMDefPtr nvram =
            virDomainNVRAMDefParseXML(nodes[0], flags);
        if (!nvram)
            goto error;
        def->nvram = nvram;
        VIR_FREE(nodes);
    }

M
Marc-André Lureau 已提交
14006
    /* analysis of the hub devices */
14007
    if ((n = virXPathNodeSet("./devices/hub", ctxt, &nodes)) < 0)
M
Marc-André Lureau 已提交
14008 14009
        goto error;
    if (n && VIR_ALLOC_N(def->hubs, n) < 0)
14010
        goto error;
14011
    for (i = 0; i < n; i++) {
M
Marc-André Lureau 已提交
14012 14013 14014 14015
        virDomainHubDefPtr hub = virDomainHubDefParseXML(nodes[i], flags);
        if (!hub)
            goto error;

14016
        if (hub->type == VIR_DOMAIN_HUB_TYPE_USB && usb_none) {
14017
            virDomainHubDefFree(hub);
14018 14019 14020 14021 14022 14023
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Can't add USB hub: "
                             "USB is disabled for this domain"));
            goto error;
        }

M
Marc-André Lureau 已提交
14024 14025 14026 14027
        def->hubs[def->nhubs++] = hub;
    }
    VIR_FREE(nodes);

14028
    /* analysis of the redirected devices */
14029
    if ((n = virXPathNodeSet("./devices/redirdev", ctxt, &nodes)) < 0)
14030 14031
        goto error;
    if (n && VIR_ALLOC_N(def->redirdevs, n) < 0)
14032
        goto error;
14033
    for (i = 0; i < n; i++) {
14034
        virDomainRedirdevDefPtr redirdev = virDomainRedirdevDefParseXML(nodes[i],
14035
                                                                        bootHash,
14036 14037 14038 14039
                                                                        flags);
        if (!redirdev)
            goto error;

14040 14041 14042 14043
        if (redirdev->bus == VIR_DOMAIN_REDIRDEV_BUS_USB && usb_none) {
             virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                            _("Can't add redirected USB device: "
                              "USB is disabled for this domain"));
14044
            virDomainRedirdevDefFree(redirdev);
14045 14046 14047
            goto error;
        }

14048 14049 14050 14051
        def->redirdevs[def->nredirdevs++] = redirdev;
    }
    VIR_FREE(nodes);

14052
    /* analysis of the redirection filter rules */
14053
    if ((n = virXPathNodeSet("./devices/redirfilter", ctxt, &nodes)) < 0)
14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070
        goto error;
    if (n > 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("only one set of redirection filter rule is supported"));
        goto error;
    }

    if (n) {
        virDomainRedirFilterDefPtr redirfilter =
            virDomainRedirFilterDefParseXML(nodes[0], ctxt);
        if (!redirfilter)
            goto error;

        def->redirfilter = redirfilter;
    }
    VIR_FREE(nodes);

H
Hu Tao 已提交
14071 14072
    /* analysis of the panic devices */
    def->panic = NULL;
14073
    if ((n = virXPathNodeSet("./devices/panic", ctxt, &nodes)) < 0)
H
Hu Tao 已提交
14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089
        goto error;
    if (n > 1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("only a single panic device is supported"));
        goto error;
    }
    if (n > 0) {
        virDomainPanicDefPtr panic =
            virDomainPanicDefParseXML(nodes[0]);
        if (!panic)
            goto error;

        def->panic = panic;
        VIR_FREE(nodes);
    }

14090
    /* analysis of the shmem devices */
14091
    if ((n = virXPathNodeSet("./devices/shmem", ctxt, &nodes)) < 0)
14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107
        goto error;
    if (n && VIR_ALLOC_N(def->shmems, n) < 0)
        goto error;

    node = ctxt->node;
    for (i = 0; i < n; i++) {
        virDomainShmemDefPtr shmem;
        ctxt->node = nodes[i];
        shmem = virDomainShmemDefParseXML(nodes[i], ctxt, flags);
        if (!shmem)
            goto error;

        def->shmems[def->nshmems++] = shmem;
    }
    ctxt->node = node;
    VIR_FREE(nodes);
H
Hu Tao 已提交
14108

14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140
    /* analysis of the user namespace mapping */
    if ((n = virXPathNodeSet("./idmap/uid", ctxt, &nodes)) < 0)
        goto error;

    if (n) {
        def->idmap.uidmap = virDomainIdmapDefParseXML(ctxt, nodes, n);
        if (!def->idmap.uidmap)
            goto error;

        def->idmap.nuidmap = n;
    }
    VIR_FREE(nodes);

    if  ((n = virXPathNodeSet("./idmap/gid", ctxt, &nodes)) < 0)
        goto error;

    if (n) {
        def->idmap.gidmap =  virDomainIdmapDefParseXML(ctxt, nodes, n);
        if (!def->idmap.gidmap)
            goto error;

        def->idmap.ngidmap = n;
    }
    VIR_FREE(nodes);

    if ((def->idmap.uidmap && !def->idmap.gidmap) ||
        (!def->idmap.uidmap && def->idmap.gidmap)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("uid and gid should be mapped both"));
            goto error;
    }

14141 14142 14143
    if ((node = virXPathNode("./sysinfo[1]", ctxt)) != NULL) {
        xmlNodePtr oldnode = ctxt->node;
        ctxt->node = node;
14144 14145
        def->sysinfo = virSysinfoParseXML(node, ctxt,
                                          def->uuid, uuid_generated);
14146 14147 14148 14149 14150
        ctxt->node = oldnode;

        if (def->sysinfo == NULL)
            goto error;
    }
14151 14152

    if ((tmp = virXPathString("string(./os/smbios/@mode)", ctxt))) {
14153 14154 14155
        int mode;

        if ((mode = virDomainSmbiosModeTypeFromString(tmp)) < 0) {
14156
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
14157
                           _("unknown smbios mode '%s'"), tmp);
14158 14159 14160 14161 14162
            goto error;
        }
        def->os.smbios_mode = mode;
        VIR_FREE(tmp);
    }
14163

14164
    /* Extract custom metadata */
14165
    if ((node = virXPathNode("./metadata[1]", ctxt)) != NULL)
14166 14167
        def->metadata = xmlCopyNode(node, 1);

14168 14169 14170
    /* we have to make a copy of all of the callback pointers here since
     * we won't have the virCaps structure available during free
     */
14171
    def->ns = xmlopt->ns;
14172

14173 14174 14175
    if (def->ns.parse &&
        (def->ns.parse)(xml, root, ctxt, &def->namespaceData) < 0)
        goto error;
14176

14177 14178 14179 14180
    /* callback to fill driver specific domain aspects */
    if (virDomainDefPostParse(def, caps, xmlopt) < 0)
        goto error;

14181 14182 14183 14184
    /* Auto-add any implied controllers which aren't present */
    if (virDomainDefAddImplicitControllers(def) < 0)
        goto error;

14185
    virHashFree(bootHash);
14186

14187 14188
    return def;

14189
 error:
14190 14191
    VIR_FREE(tmp);
    VIR_FREE(nodes);
14192
    virHashFree(bootHash);
14193 14194 14195 14196
    virDomainDefFree(def);
    return NULL;
}

14197

14198
static virDomainObjPtr
14199
virDomainObjParseXML(xmlDocPtr xml,
14200
                     xmlXPathContextPtr ctxt,
14201 14202
                     virCapsPtr caps,
                     virDomainXMLOptionPtr xmlopt,
14203 14204
                     unsigned int expectedVirtTypes,
                     unsigned int flags)
14205 14206 14207 14208 14209 14210
{
    char *tmp = NULL;
    long val;
    xmlNodePtr config;
    xmlNodePtr oldnode;
    virDomainObjPtr obj;
14211
    xmlNodePtr *nodes = NULL;
14212 14213
    size_t i;
    int n;
J
Jiri Denemark 已提交
14214 14215
    int state;
    int reason = 0;
14216

14217
    if (!(obj = virDomainObjNew(xmlopt)))
14218 14219
        return NULL;

14220
    if (!(config = virXPathNode("./domain", ctxt))) {
14221 14222
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("no domain config"));
14223 14224 14225 14226 14227
        goto error;
    }

    oldnode = ctxt->node;
    ctxt->node = config;
14228 14229
    obj->def = virDomainDefParseXML(xml, config, ctxt, caps, xmlopt,
                                    expectedVirtTypes, flags);
14230 14231 14232 14233
    ctxt->node = oldnode;
    if (!obj->def)
        goto error;

14234
    if (!(tmp = virXPathString("string(./@state)", ctxt))) {
14235 14236
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing domain state"));
14237 14238
        goto error;
    }
J
Jiri Denemark 已提交
14239
    if ((state = virDomainStateTypeFromString(tmp)) < 0) {
14240
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
14241
                       _("invalid domain state '%s'"), tmp);
14242 14243 14244 14245 14246
        VIR_FREE(tmp);
        goto error;
    }
    VIR_FREE(tmp);

J
Jiri Denemark 已提交
14247 14248
    if ((tmp = virXPathString("string(./@reason)", ctxt))) {
        if ((reason = virDomainStateReasonFromString(state, tmp)) < 0) {
14249
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
14250
                           _("invalid domain state reason '%s'"), tmp);
J
Jiri Denemark 已提交
14251 14252 14253 14254 14255 14256 14257 14258
            VIR_FREE(tmp);
            goto error;
        }
        VIR_FREE(tmp);
    }

    virDomainObjSetState(obj, state, reason);

E
Eric Blake 已提交
14259
    if (virXPathLong("string(./@pid)", ctxt, &val) < 0) {
14260 14261
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("invalid pid"));
14262 14263 14264 14265
        goto error;
    }
    obj->pid = (pid_t)val;

14266
    if ((n = virXPathNodeSet("./taint", ctxt, &nodes)) < 0)
14267
        goto error;
14268
    for (i = 0; i < n; i++) {
14269 14270 14271 14272
        char *str = virXMLPropString(nodes[i], "flag");
        if (str) {
            int flag = virDomainTaintTypeFromString(str);
            if (flag < 0) {
14273
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
14274
                               _("Unknown taint flag %s"), str);
14275
                VIR_FREE(str);
14276 14277
                goto error;
            }
14278
            VIR_FREE(str);
14279 14280 14281 14282 14283
            virDomainObjTaint(obj, flag);
        }
    }
    VIR_FREE(nodes);

14284 14285
    if (xmlopt->privateData.parse &&
        ((xmlopt->privateData.parse)(ctxt, obj->privateData)) < 0)
14286
        goto error;
14287

14288 14289
    return obj;

14290
 error:
14291
    virObjectUnref(obj);
14292
    VIR_FREE(nodes);
14293 14294 14295 14296
    return NULL;
}


J
Jiri Denemark 已提交
14297 14298 14299 14300
static virDomainDefPtr
virDomainDefParse(const char *xmlStr,
                  const char *filename,
                  virCapsPtr caps,
14301
                  virDomainXMLOptionPtr xmlopt,
M
Matthias Bolte 已提交
14302
                  unsigned int expectedVirtTypes,
E
Eric Blake 已提交
14303
                  unsigned int flags)
14304
{
J
Jiri Denemark 已提交
14305 14306
    xmlDocPtr xml;
    virDomainDefPtr def = NULL;
14307
    int keepBlanksDefault = xmlKeepBlanksDefault(0);
J
Jiri Denemark 已提交
14308

14309
    if ((xml = virXMLParse(filename, xmlStr, _("(domain_definition)")))) {
14310 14311
        def = virDomainDefParseNode(xml, xmlDocGetRootElement(xml), caps,
                                    xmlopt, expectedVirtTypes, flags);
J
Jiri Denemark 已提交
14312
        xmlFreeDoc(xml);
14313
    }
J
Jiri Denemark 已提交
14314

14315
    xmlKeepBlanksDefault(keepBlanksDefault);
J
Jiri Denemark 已提交
14316
    return def;
14317
}
14318

14319
virDomainDefPtr
14320 14321
virDomainDefParseString(const char *xmlStr,
                        virCapsPtr caps,
14322
                        virDomainXMLOptionPtr xmlopt,
14323 14324
                        unsigned int expectedVirtTypes,
                        unsigned int flags)
14325
{
14326
    return virDomainDefParse(xmlStr, NULL, caps, xmlopt,
14327
                             expectedVirtTypes, flags);
14328 14329
}

14330
virDomainDefPtr
14331 14332
virDomainDefParseFile(const char *filename,
                      virCapsPtr caps,
14333
                      virDomainXMLOptionPtr xmlopt,
14334 14335
                      unsigned int expectedVirtTypes,
                      unsigned int flags)
14336
{
14337
    return virDomainDefParse(NULL, filename, caps, xmlopt,
14338
                             expectedVirtTypes, flags);
14339 14340 14341
}


14342
virDomainDefPtr
14343
virDomainDefParseNode(xmlDocPtr xml,
14344
                      xmlNodePtr root,
14345 14346
                      virCapsPtr caps,
                      virDomainXMLOptionPtr xmlopt,
14347 14348
                      unsigned int expectedVirtTypes,
                      unsigned int flags)
14349 14350 14351 14352 14353
{
    xmlXPathContextPtr ctxt = NULL;
    virDomainDefPtr def = NULL;

    if (!xmlStrEqual(root->name, BAD_CAST "domain")) {
14354 14355 14356 14357
        virReportError(VIR_ERR_XML_ERROR,
                       _("unexpected root element <%s>, "
                         "expecting <domain>"),
                       root->name);
14358 14359 14360 14361 14362
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
14363
        virReportOOMError();
14364 14365 14366 14367
        goto cleanup;
    }

    ctxt->node = root;
14368
    def = virDomainDefParseXML(xml, root, ctxt, caps, xmlopt,
14369
                               expectedVirtTypes, flags);
14370

14371
 cleanup:
14372 14373 14374
    xmlXPathFreeContext(ctxt);
    return def;
}
14375 14376


H
Hu Tao 已提交
14377
static virDomainObjPtr
14378
virDomainObjParseNode(xmlDocPtr xml,
L
Laine Stump 已提交
14379
                      xmlNodePtr root,
14380 14381
                      virCapsPtr caps,
                      virDomainXMLOptionPtr xmlopt,
M
Matthias Bolte 已提交
14382
                      unsigned int expectedVirtTypes,
L
Laine Stump 已提交
14383
                      unsigned int flags)
14384 14385 14386 14387 14388
{
    xmlXPathContextPtr ctxt = NULL;
    virDomainObjPtr obj = NULL;

    if (!xmlStrEqual(root->name, BAD_CAST "domstatus")) {
14389 14390 14391 14392
        virReportError(VIR_ERR_XML_ERROR,
                       _("unexpected root element <%s>, "
                         "expecting <domstatus>"),
                       root->name);
14393 14394 14395
        goto cleanup;
    }

14396
    if (!(ctxt = xmlXPathNewContext(xml))) {
14397
        virReportOOMError();
14398 14399 14400 14401
        goto cleanup;
    }

    ctxt->node = root;
14402
    obj = virDomainObjParseXML(xml, ctxt, caps, xmlopt, expectedVirtTypes, flags);
14403

14404
 cleanup:
14405 14406 14407 14408
    xmlXPathFreeContext(ctxt);
    return obj;
}

H
Hu Tao 已提交
14409

14410
static virDomainObjPtr
14411 14412
virDomainObjParseFile(const char *filename,
                      virCapsPtr caps,
14413
                      virDomainXMLOptionPtr xmlopt,
14414 14415
                      unsigned int expectedVirtTypes,
                      unsigned int flags)
H
Hu Tao 已提交
14416 14417 14418
{
    xmlDocPtr xml;
    virDomainObjPtr obj = NULL;
14419
    int keepBlanksDefault = xmlKeepBlanksDefault(0);
H
Hu Tao 已提交
14420 14421

    if ((xml = virXMLParseFile(filename))) {
14422 14423
        obj = virDomainObjParseNode(xml, xmlDocGetRootElement(xml),
                                    caps, xmlopt,
M
Matthias Bolte 已提交
14424
                                    expectedVirtTypes, flags);
H
Hu Tao 已提交
14425 14426 14427
        xmlFreeDoc(xml);
    }

14428
    xmlKeepBlanksDefault(keepBlanksDefault);
H
Hu Tao 已提交
14429 14430 14431 14432
    return obj;
}


14433 14434 14435
static bool
virDomainTimerDefCheckABIStability(virDomainTimerDefPtr src,
                                   virDomainTimerDefPtr dst)
14436 14437
{
    if (src->name != dst->name) {
14438 14439 14440 14441
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target timer %s does not match source %s"),
                       virDomainTimerNameTypeToString(dst->name),
                       virDomainTimerNameTypeToString(src->name));
14442
        return false;
14443 14444 14445
    }

    if (src->present != dst->present) {
14446 14447 14448
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target timer presence %d does not match source %d"),
                       dst->present, src->present);
14449
        return false;
14450 14451 14452 14453
    }

    if (src->name == VIR_DOMAIN_TIMER_NAME_TSC) {
        if (src->frequency != dst->frequency) {
14454 14455 14456
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target TSC frequency %lu does not match source %lu"),
                           dst->frequency, src->frequency);
14457
            return false;
14458 14459 14460
        }

        if (src->mode != dst->mode) {
14461 14462 14463 14464
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target TSC mode %s does not match source %s"),
                           virDomainTimerModeTypeToString(dst->mode),
                           virDomainTimerModeTypeToString(src->mode));
14465
            return false;
14466 14467 14468
        }
    }

14469
    return true;
14470 14471 14472
}


14473 14474 14475
static bool
virDomainDeviceInfoCheckABIStability(virDomainDeviceInfoPtr src,
                                     virDomainDeviceInfoPtr dst)
14476 14477
{
    if (src->type != dst->type) {
14478 14479 14480 14481
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target device address type %s does not match source %s"),
                       virDomainDeviceAddressTypeToString(dst->type),
                       virDomainDeviceAddressTypeToString(src->type));
14482
        return false;
14483 14484
    }

14485
    switch ((virDomainDeviceAddressType) src->type) {
14486 14487 14488 14489 14490
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI:
        if (src->addr.pci.domain != dst->addr.pci.domain ||
            src->addr.pci.bus != dst->addr.pci.bus ||
            src->addr.pci.slot != dst->addr.pci.slot ||
            src->addr.pci.function != dst->addr.pci.function) {
14491
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
14492 14493
                           _("Target device PCI address %04x:%02x:%02x.%02x "
                             "does not match source %04x:%02x:%02x.%02x"),
14494 14495 14496 14497
                           dst->addr.pci.domain, dst->addr.pci.bus,
                           dst->addr.pci.slot, dst->addr.pci.function,
                           src->addr.pci.domain, src->addr.pci.bus,
                           src->addr.pci.slot, src->addr.pci.function);
14498
            return false;
14499 14500 14501 14502 14503 14504 14505
        }
        break;

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE:
        if (src->addr.drive.controller != dst->addr.drive.controller ||
            src->addr.drive.bus != dst->addr.drive.bus ||
            src->addr.drive.unit != dst->addr.drive.unit) {
14506
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
14507 14508
                           _("Target device drive address %d:%d:%d "
                             "does not match source %d:%d:%d"),
14509 14510 14511 14512
                           dst->addr.drive.controller, dst->addr.drive.bus,
                           dst->addr.drive.unit,
                           src->addr.drive.controller, src->addr.drive.bus,
                           src->addr.drive.unit);
14513
            return false;
14514 14515 14516 14517 14518 14519 14520
        }
        break;

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL:
        if (src->addr.vioserial.controller != dst->addr.vioserial.controller ||
            src->addr.vioserial.bus != dst->addr.vioserial.bus ||
            src->addr.vioserial.port != dst->addr.vioserial.port) {
14521
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
14522 14523
                           _("Target device virtio serial address %d:%d:%d "
                             "does not match source %d:%d:%d"),
14524 14525 14526 14527
                           dst->addr.vioserial.controller, dst->addr.vioserial.bus,
                           dst->addr.vioserial.port,
                           src->addr.vioserial.controller, src->addr.vioserial.bus,
                           src->addr.vioserial.port);
14528
            return false;
14529 14530 14531 14532 14533 14534
        }
        break;

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID:
        if (src->addr.ccid.controller != dst->addr.ccid.controller ||
            src->addr.ccid.slot != dst->addr.ccid.slot) {
14535
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
14536 14537
                           _("Target device ccid address %d:%d "
                             "does not match source %d:%d"),
14538 14539 14540 14541
                           dst->addr.ccid.controller,
                           dst->addr.ccid.slot,
                           src->addr.ccid.controller,
                           src->addr.ccid.slot);
14542
            return false;
14543 14544
        }
        break;
H
Hu Tao 已提交
14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_ISA:
        if (src->addr.isa.iobase != dst->addr.isa.iobase ||
            src->addr.isa.irq != dst->addr.isa.irq) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target device isa address %d:%d "
                             "does not match source %d:%d"),
                           dst->addr.isa.iobase,
                           dst->addr.isa.irq,
                           src->addr.isa.iobase,
                           src->addr.isa.irq);
            return false;
        }
        break;
14559 14560 14561 14562 14563 14564 14565 14566 14567

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB:
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO:
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390:
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW:
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO:
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE:
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_LAST:
        break;
14568 14569
    }

14570
    return true;
14571 14572 14573
}


14574 14575 14576
static bool
virDomainDiskDefCheckABIStability(virDomainDiskDefPtr src,
                                  virDomainDiskDefPtr dst)
14577 14578
{
    if (src->device != dst->device) {
14579 14580 14581 14582
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target disk device %s does not match source %s"),
                       virDomainDiskDeviceTypeToString(dst->device),
                       virDomainDiskDeviceTypeToString(src->device));
14583
        return false;
14584 14585 14586
    }

    if (src->bus != dst->bus) {
14587 14588 14589 14590
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target disk bus %s does not match source %s"),
                       virDomainDiskBusTypeToString(dst->bus),
                       virDomainDiskBusTypeToString(src->bus));
14591
        return false;
14592 14593 14594
    }

    if (STRNEQ(src->dst, dst->dst)) {
14595 14596 14597
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target disk %s does not match source %s"),
                       dst->dst, src->dst);
14598
        return false;
14599 14600 14601
    }

    if (STRNEQ_NULLABLE(src->serial, dst->serial)) {
14602 14603 14604
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target disk serial %s does not match source %s"),
                       NULLSTR(dst->serial), NULLSTR(src->serial));
14605
        return false;
14606 14607
    }

14608 14609
    if (src->src->readonly != dst->src->readonly ||
        src->src->shared != dst->src->shared) {
14610 14611
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Target disk access mode does not match source"));
14612
        return false;
14613 14614 14615
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
14616
        return false;
14617

14618
    return true;
14619 14620 14621
}


14622 14623 14624
static bool
virDomainControllerDefCheckABIStability(virDomainControllerDefPtr src,
                                        virDomainControllerDefPtr dst)
14625 14626
{
    if (src->type != dst->type) {
14627 14628 14629 14630
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target controller type %s does not match source %s"),
                       virDomainControllerTypeToString(dst->type),
                       virDomainControllerTypeToString(src->type));
14631
        return false;
14632 14633 14634
    }

    if (src->idx != dst->idx) {
14635 14636 14637
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target controller index %d does not match source %d"),
                       dst->idx, src->idx);
14638
        return false;
14639 14640 14641
    }

    if (src->model != dst->model) {
14642 14643 14644
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target controller model %d does not match source %d"),
                       dst->model, src->model);
14645
        return false;
14646 14647 14648 14649
    }

    if (src->type == VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL) {
        if (src->opts.vioserial.ports != dst->opts.vioserial.ports) {
14650 14651 14652
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target controller ports %d does not match source %d"),
                           dst->opts.vioserial.ports, src->opts.vioserial.ports);
14653
            return false;
14654 14655 14656
        }

        if (src->opts.vioserial.vectors != dst->opts.vioserial.vectors) {
14657 14658 14659
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target controller vectors %d does not match source %d"),
                           dst->opts.vioserial.vectors, src->opts.vioserial.vectors);
14660
            return false;
14661 14662 14663 14664
        }
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
14665
        return false;
14666

14667
    return true;
14668 14669 14670
}


14671 14672 14673
static bool
virDomainFsDefCheckABIStability(virDomainFSDefPtr src,
                                virDomainFSDefPtr dst)
14674 14675
{
    if (STRNEQ(src->dst, dst->dst)) {
14676 14677 14678
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target filesystem guest target %s does not match source %s"),
                       dst->dst, src->dst);
14679
        return false;
14680 14681 14682
    }

    if (src->readonly != dst->readonly) {
14683 14684
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Target filesystem access mode does not match source"));
14685
        return false;
14686 14687 14688
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
14689
        return false;
14690

14691
    return true;
14692 14693 14694
}


14695 14696 14697
static bool
virDomainNetDefCheckABIStability(virDomainNetDefPtr src,
                                 virDomainNetDefPtr dst)
14698
{
14699 14700 14701
    char srcmac[VIR_MAC_STRING_BUFLEN];
    char dstmac[VIR_MAC_STRING_BUFLEN];

14702
    if (virMacAddrCmp(&src->mac, &dst->mac) != 0) {
14703
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
14704 14705 14706 14707
                       _("Target network card mac %s"
                         " does not match source %s"),
                       virMacAddrFormat(&dst->mac, dstmac),
                       virMacAddrFormat(&src->mac, srcmac));
14708
        return false;
14709 14710 14711
    }

    if (STRNEQ_NULLABLE(src->model, dst->model)) {
14712 14713 14714
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target network card model %s does not match source %s"),
                       NULLSTR(dst->model), NULLSTR(src->model));
14715
        return false;
14716 14717 14718
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
14719
        return false;
14720

14721
    return true;
14722 14723 14724
}


14725 14726 14727
static bool
virDomainInputDefCheckABIStability(virDomainInputDefPtr src,
                                   virDomainInputDefPtr dst)
14728 14729
{
    if (src->type != dst->type) {
14730 14731 14732 14733
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target input device type %s does not match source %s"),
                       virDomainInputTypeToString(dst->type),
                       virDomainInputTypeToString(src->type));
14734
        return false;
14735 14736 14737
    }

    if (src->bus != dst->bus) {
14738 14739 14740 14741
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target input device bus %s does not match source %s"),
                       virDomainInputBusTypeToString(dst->bus),
                       virDomainInputBusTypeToString(src->bus));
14742
        return false;
14743 14744 14745
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
14746
        return false;
14747

14748
    return true;
14749 14750 14751
}


14752 14753 14754
static bool
virDomainSoundDefCheckABIStability(virDomainSoundDefPtr src,
                                   virDomainSoundDefPtr dst)
14755 14756
{
    if (src->model != dst->model) {
14757 14758 14759 14760
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target sound card model %s does not match source %s"),
                       virDomainSoundModelTypeToString(dst->model),
                       virDomainSoundModelTypeToString(src->model));
14761
        return false;
14762 14763 14764
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
14765
        return false;
14766

14767
    return true;
14768 14769 14770
}


14771 14772 14773
static bool
virDomainVideoDefCheckABIStability(virDomainVideoDefPtr src,
                                   virDomainVideoDefPtr dst)
14774 14775
{
    if (src->type != dst->type) {
14776 14777 14778 14779
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target video card model %s does not match source %s"),
                       virDomainVideoTypeToString(dst->type),
                       virDomainVideoTypeToString(src->type));
14780
        return false;
14781 14782
    }

14783 14784 14785 14786 14787 14788 14789
    if (src->ram != dst->ram) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target video card ram %u does not match source %u"),
                       dst->ram, src->ram);
        return false;
    }

14790
    if (src->vram != dst->vram) {
14791 14792 14793
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target video card vram %u does not match source %u"),
                       dst->vram, src->vram);
14794
        return false;
14795 14796
    }

14797 14798 14799 14800 14801 14802 14803
    if (src->vgamem != dst->vgamem) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target video card vgamem %u does not match source %u"),
                       dst->vgamem, src->vgamem);
        return false;
    }

14804
    if (src->heads != dst->heads) {
14805 14806 14807
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target video card heads %u does not match source %u"),
                       dst->heads, src->heads);
14808
        return false;
14809 14810 14811 14812
    }

    if ((src->accel && !dst->accel) ||
        (!src->accel && dst->accel)) {
14813 14814
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Target video card acceleration does not match source"));
14815
        return false;
14816 14817 14818 14819
    }

    if (src->accel) {
        if (src->accel->support2d != dst->accel->support2d) {
14820 14821 14822
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target video card 2d accel %u does not match source %u"),
                           dst->accel->support2d, src->accel->support2d);
14823
            return false;
14824 14825 14826
        }

        if (src->accel->support3d != dst->accel->support3d) {
14827 14828 14829
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target video card 3d accel %u does not match source %u"),
                           dst->accel->support3d, src->accel->support3d);
14830
            return false;
14831 14832 14833 14834
        }
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
14835
        return false;
14836

14837
    return true;
14838 14839 14840
}


14841 14842 14843
static bool
virDomainHostdevDefCheckABIStability(virDomainHostdevDefPtr src,
                                     virDomainHostdevDefPtr dst)
14844 14845
{
    if (src->mode != dst->mode) {
14846 14847 14848 14849
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target host device mode %s does not match source %s"),
                       virDomainHostdevModeTypeToString(dst->mode),
                       virDomainHostdevModeTypeToString(src->mode));
14850
        return false;
14851 14852
    }

14853 14854 14855 14856 14857 14858 14859
    if (src->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
        src->source.subsys.type != dst->source.subsys.type) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target host device subsystem %s does not match source %s"),
                       virDomainHostdevSubsysTypeToString(dst->source.subsys.type),
                       virDomainHostdevSubsysTypeToString(src->source.subsys.type));
        return false;
14860 14861
    }

14862
    if (!virDomainDeviceInfoCheckABIStability(src->info, dst->info))
14863
        return false;
14864

14865
    return true;
14866 14867 14868
}


14869 14870 14871
static bool
virDomainSmartcardDefCheckABIStability(virDomainSmartcardDefPtr src,
                                       virDomainSmartcardDefPtr dst)
14872 14873
{
    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
14874
        return false;
14875

14876
    return true;
14877 14878 14879
}


14880 14881 14882
static bool
virDomainSerialDefCheckABIStability(virDomainChrDefPtr src,
                                    virDomainChrDefPtr dst)
14883 14884
{
    if (src->target.port != dst->target.port) {
14885 14886 14887
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target serial port %d does not match source %d"),
                       dst->target.port, src->target.port);
14888
        return false;
14889 14890 14891
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
14892
        return false;
14893

14894
    return true;
14895 14896 14897
}


14898 14899 14900
static bool
virDomainParallelDefCheckABIStability(virDomainChrDefPtr src,
                                      virDomainChrDefPtr dst)
14901 14902
{
    if (src->target.port != dst->target.port) {
14903
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
14904
                       _("Target parallel port %d does not match source %d"),
14905
                       dst->target.port, src->target.port);
14906
        return false;
14907 14908 14909
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
14910
        return false;
14911

14912
    return true;
14913 14914 14915
}


14916 14917 14918
static bool
virDomainChannelDefCheckABIStability(virDomainChrDefPtr src,
                                     virDomainChrDefPtr dst)
14919 14920
{
    if (src->targetType != dst->targetType) {
14921 14922 14923 14924
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target channel type %s does not match source %s"),
                       virDomainChrChannelTargetTypeToString(dst->targetType),
                       virDomainChrChannelTargetTypeToString(src->targetType));
14925
        return false;
14926 14927 14928 14929
    }

    switch (src->targetType) {
    case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO:
14930
        if (STRNEQ_NULLABLE(src->target.name, dst->target.name)) {
14931 14932 14933
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target channel name %s does not match source %s"),
                           NULLSTR(dst->target.name), NULLSTR(src->target.name));
14934
            return false;
14935
        }
14936 14937 14938 14939 14940 14941 14942
        if (src->source.type != dst->source.type &&
            (src->source.type == VIR_DOMAIN_CHR_TYPE_SPICEVMC ||
             dst->source.type == VIR_DOMAIN_CHR_TYPE_SPICEVMC) &&
            !src->target.name) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Changing device type to/from spicevmc would"
                             " change default target channel name"));
14943
            return false;
14944
        }
14945 14946
        break;
    case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_GUESTFWD:
E
Eric Blake 已提交
14947 14948
        if (memcmp(src->target.addr, dst->target.addr,
                   sizeof(*src->target.addr)) != 0) {
14949 14950
            char *saddr = virSocketAddrFormatFull(src->target.addr, true, ":");
            char *daddr = virSocketAddrFormatFull(dst->target.addr, true, ":");
14951 14952 14953
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target channel addr %s does not match source %s"),
                           NULLSTR(daddr), NULLSTR(saddr));
14954 14955
            VIR_FREE(saddr);
            VIR_FREE(daddr);
14956
            return false;
14957 14958 14959 14960 14961
        }
        break;
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
14962
        return false;
14963

14964
    return true;
14965 14966 14967
}


14968 14969 14970
static bool
virDomainConsoleDefCheckABIStability(virDomainChrDefPtr src,
                                     virDomainChrDefPtr dst)
14971 14972
{
    if (src->targetType != dst->targetType) {
14973 14974 14975 14976
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target console type %s does not match source %s"),
                       virDomainChrConsoleTargetTypeToString(dst->targetType),
                       virDomainChrConsoleTargetTypeToString(src->targetType));
14977
        return false;
14978 14979 14980
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
14981
        return false;
14982

14983
    return true;
14984 14985 14986
}


14987 14988 14989
static bool
virDomainWatchdogDefCheckABIStability(virDomainWatchdogDefPtr src,
                                      virDomainWatchdogDefPtr dst)
14990 14991
{
    if (src->model != dst->model) {
14992 14993 14994 14995
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target watchdog model %s does not match source %s"),
                       virDomainWatchdogModelTypeToString(dst->model),
                       virDomainWatchdogModelTypeToString(src->model));
14996
        return false;
14997 14998 14999
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
15000
        return false;
15001

15002
    return true;
15003 15004 15005
}


15006 15007 15008
static bool
virDomainMemballoonDefCheckABIStability(virDomainMemballoonDefPtr src,
                                        virDomainMemballoonDefPtr dst)
15009 15010
{
    if (src->model != dst->model) {
15011 15012 15013 15014
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target balloon model %s does not match source %s"),
                       virDomainMemballoonModelTypeToString(dst->model),
                       virDomainMemballoonModelTypeToString(src->model));
15015
        return false;
15016 15017 15018
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
15019
        return false;
15020

15021
    return true;
15022 15023 15024
}


15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043
static bool
virDomainRNGDefCheckABIStability(virDomainRNGDefPtr src,
                                 virDomainRNGDefPtr dst)
{
    if (src->model != dst->model) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target RNG model '%s' does not match source '%s'"),
                       virDomainRNGModelTypeToString(dst->model),
                       virDomainRNGModelTypeToString(src->model));
        return false;
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
        return false;

    return true;
}


15044 15045 15046
static bool
virDomainHubDefCheckABIStability(virDomainHubDefPtr src,
                                 virDomainHubDefPtr dst)
M
Marc-André Lureau 已提交
15047 15048
{
    if (src->type != dst->type) {
15049 15050 15051 15052
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target hub device type %s does not match source %s"),
                       virDomainHubTypeToString(dst->type),
                       virDomainHubTypeToString(src->type));
15053
        return false;
M
Marc-André Lureau 已提交
15054 15055 15056
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
15057
        return false;
M
Marc-André Lureau 已提交
15058

15059
    return true;
M
Marc-André Lureau 已提交
15060 15061
}

15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075

static bool
virDomainRedirdevDefCheckABIStability(virDomainRedirdevDefPtr src,
                                      virDomainRedirdevDefPtr dst)
{
    if (src->bus != dst->bus) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target redirected device bus %s does not match "
                         "source %s"),
                       virDomainRedirdevBusTypeToString(dst->bus),
                       virDomainRedirdevBusTypeToString(src->bus));
        return false;
    }

15076
    switch ((virDomainRedirdevBus) src->bus) {
15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097
    case VIR_DOMAIN_REDIRDEV_BUS_USB:
        if (src->source.chr.type != dst->source.chr.type) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target redirected device source type %s does "
                             "not match source device source type %s"),
                           virDomainChrTypeToString(dst->source.chr.type),
                           virDomainChrTypeToString(src->source.chr.type));
            return false;
        }
        break;
    case VIR_DOMAIN_REDIRDEV_BUS_LAST:
        break;
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
        return false;

    return true;
}


15098 15099 15100 15101
static bool
virDomainRedirFilterDefCheckABIStability(virDomainRedirFilterDefPtr src,
                                         virDomainRedirFilterDefPtr dst)
{
15102
    size_t i;
15103 15104 15105 15106 15107 15108

    if (src->nusbdevs != dst->nusbdevs) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target USB redirection filter rule "
                         "count %zu does not match source %zu"),
                         dst->nusbdevs, src->nusbdevs);
15109
        return false;
15110 15111 15112
    }

    for (i = 0; i < src->nusbdevs; i++) {
15113 15114 15115
        virDomainRedirFilterUSBDevDefPtr srcUSBDev = src->usbdevs[i];
        virDomainRedirFilterUSBDevDefPtr dstUSBDev = dst->usbdevs[i];
        if (srcUSBDev->usbClass != dstUSBDev->usbClass) {
15116 15117
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           "%s", _("Target USB Class code does not match source"));
15118
            return false;
15119 15120
        }

15121
        if (srcUSBDev->vendor != dstUSBDev->vendor) {
15122 15123
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           "%s", _("Target USB vendor ID does not match source"));
15124
            return false;
15125 15126
        }

15127
        if (srcUSBDev->product != dstUSBDev->product) {
15128 15129
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           "%s", _("Target USB product ID does not match source"));
15130
            return false;
15131 15132
        }

15133
        if (srcUSBDev->version != dstUSBDev->version) {
15134 15135
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           "%s", _("Target USB version does not match source"));
15136
            return false;
15137 15138
        }

15139
        if (srcUSBDev->allow != dstUSBDev->allow) {
15140 15141
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target USB allow '%s' does not match source '%s'"),
15142 15143
                             dstUSBDev->allow ? "yes" : "no",
                             srcUSBDev->allow ? "yes" : "no");
15144
            return false;
15145 15146 15147
        }
    }

15148
    return true;
15149
}
M
Marc-André Lureau 已提交
15150

15151 15152 15153 15154 15155 15156 15157

static bool
virDomainDefFeaturesCheckABIStability(virDomainDefPtr src,
                                      virDomainDefPtr dst)
{
    size_t i;

15158 15159 15160 15161 15162 15163
    for (i = 0; i < VIR_DOMAIN_FEATURE_LAST; i++) {
        if (src->features[i] != dst->features[i]) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("State of feature '%s' differs: "
                             "source: '%s', destination: '%s'"),
                           virDomainFeatureTypeToString(i),
J
Ján Tomko 已提交
15164 15165
                           virTristateSwitchTypeToString(src->features[i]),
                           virTristateSwitchTypeToString(dst->features[i]));
15166 15167
            return false;
        }
15168 15169 15170 15171 15172 15173 15174
    }

    /* APIC EOI */
    if (src->apic_eoi != dst->apic_eoi) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("State of APIC EOI differs: "
                         "source: '%s', destination: '%s'"),
J
Ján Tomko 已提交
15175 15176
                       virTristateSwitchTypeToString(src->apic_eoi),
                       virTristateSwitchTypeToString(dst->apic_eoi));
15177 15178 15179 15180
        return false;
    }

    /* hyperv */
J
Ján Tomko 已提交
15181
    if (src->features[VIR_DOMAIN_FEATURE_HYPERV] == VIR_TRISTATE_SWITCH_ON) {
15182
        for (i = 0; i < VIR_DOMAIN_HYPERV_LAST; i++) {
15183
            switch ((virDomainHyperv) i) {
15184 15185 15186 15187 15188 15189 15190 15191
            case VIR_DOMAIN_HYPERV_RELAXED:
            case VIR_DOMAIN_HYPERV_VAPIC:
                if (src->hyperv_features[i] != dst->hyperv_features[i]) {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("State of HyperV enlightenment "
                                     "feature '%s' differs: "
                                     "source: '%s', destination: '%s'"),
                                   virDomainHypervTypeToString(i),
J
Ján Tomko 已提交
15192 15193
                                   virTristateSwitchTypeToString(src->hyperv_features[i]),
                                   virTristateSwitchTypeToString(dst->hyperv_features[i]));
15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210
                    return false;
                }

                break;

            case VIR_DOMAIN_HYPERV_SPINLOCKS:
                /* spinlock count matters! */
                if (src->hyperv_spinlocks != dst->hyperv_spinlocks) {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("HyperV spinlock retry count differs: "
                                     "source: '%u', destination: '%u'"),
                                   src->hyperv_spinlocks,
                                   dst->hyperv_spinlocks);
                    return false;
                }
                break;

15211
            /* coverity[dead_error_begin] */
15212 15213 15214 15215 15216 15217
            case VIR_DOMAIN_HYPERV_LAST:
                break;
            }
        }
    }

15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234
    /* kvm */
    if (src->features[VIR_DOMAIN_FEATURE_KVM] == VIR_TRISTATE_SWITCH_ON) {
        for (i = 0; i < VIR_DOMAIN_KVM_LAST; i++) {
            switch ((virDomainKVM) i) {
            case VIR_DOMAIN_KVM_HIDDEN:
                if (src->kvm_features[i] != dst->kvm_features[i]) {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("State of KVM feature '%s' differs: "
                                     "source: '%s', destination: '%s'"),
                                   virDomainKVMTypeToString(i),
                                   virTristateSwitchTypeToString(src->kvm_features[i]),
                                   virTristateSwitchTypeToString(dst->kvm_features[i]));
                    return false;
                }

                break;

15235
            /* coverity[dead_error_begin] */
15236 15237 15238 15239 15240 15241
            case VIR_DOMAIN_KVM_LAST:
                break;
            }
        }
    }

15242 15243 15244
    return true;
}

H
Hu Tao 已提交
15245 15246 15247 15248
static bool
virDomainPanicCheckABIStability(virDomainPanicDefPtr src,
                                virDomainPanicDefPtr dst)
{
15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259
    if (!src && !dst)
        return true;

    if (!src || !dst) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain panic device count '%d' "
                         "does not match source count '%d'"),
                       src ? 1 : 0, dst ? 1 : 0);
        return false;
    }

H
Hu Tao 已提交
15260 15261 15262
    return virDomainDeviceInfoCheckABIStability(&src->info, &dst->info);
}

15263

15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301
static bool
virDomainShmemDefCheckABIStability(virDomainShmemDefPtr src,
                                   virDomainShmemDefPtr dst)
{
    if (STRNEQ_NULLABLE(src->name, dst->name)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target shared memory name '%s' does not match source "
                         "'%s'"), dst->name, src->name);
        return false;
    }

    if (src->size != dst->size) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target shared memory size '%llu' does not match "
                         "source size '%llu'"), dst->size, src->size);
        return false;
    }

    if (src->server.enabled != dst->server.enabled) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Target shared memory server usage doesn't match "
                         "source"));
        return false;
    }

    if (src->msi.vectors != dst->msi.vectors ||
        src->msi.enabled != dst->msi.enabled ||
        src->msi.ioeventfd != dst->msi.ioeventfd) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Target shared memory MSI configuration doesn't match "
                         "source"));
        return false;
    }

    return virDomainDeviceInfoCheckABIStability(&src->info, &dst->info);
}


15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320
static bool
virDomainTPMDefCheckABIStability(virDomainTPMDefPtr src,
                                 virDomainTPMDefPtr dst)
{
    if (src->type != dst->type) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Target TPM device type doesn't match source"));
        return false;
    }

    if (src->model != dst->model) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Target TPM device model doesn't match source"));
        return false;
    }

    return virDomainDeviceInfoCheckABIStability(&src->info, &dst->info);
}

15321 15322 15323 15324 15325 15326 15327
static bool
virDomainPanicDefCheckABIStability(virDomainPanicDefPtr src,
                                   virDomainPanicDefPtr dst)
{
    return virDomainDeviceInfoCheckABIStability(&src->info, &dst->info);
}

15328 15329 15330 15331
/* This compares two configurations and looks for any differences
 * which will affect the guest ABI. This is primarily to allow
 * validation of custom XML config passed in during migration
 */
15332 15333 15334
bool
virDomainDefCheckABIStability(virDomainDefPtr src,
                              virDomainDefPtr dst)
15335
{
15336
    size_t i;
15337 15338 15339
    virErrorPtr err;
    char *strSrc;
    char *strDst;
15340 15341

    if (src->virtType != dst->virtType) {
15342 15343 15344 15345
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain virt type %s does not match source %s"),
                       virDomainVirtTypeToString(dst->virtType),
                       virDomainVirtTypeToString(src->virtType));
15346
        goto error;
15347 15348 15349 15350 15351 15352 15353
    }

    if (memcmp(src->uuid, dst->uuid, VIR_UUID_BUFLEN) != 0) {
        char uuidsrc[VIR_UUID_STRING_BUFLEN];
        char uuiddst[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(src->uuid, uuidsrc);
        virUUIDFormat(dst->uuid, uuiddst);
15354 15355 15356
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain uuid %s does not match source %s"),
                       uuiddst, uuidsrc);
15357
        goto error;
15358 15359
    }

15360 15361 15362 15363
    /* Not strictly ABI related, but we want to make sure domains
     * don't get silently re-named through the backdoor when passing
     * custom XML into various APIs, since this would create havoc
     */
15364
    if (STRNEQ_NULLABLE(src->name, dst->name)) {
15365 15366 15367
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain name '%s' does not match source '%s'"),
                       dst->name, src->name);
15368
        goto error;
15369 15370
    }

15371
    if (src->mem.max_balloon != dst->mem.max_balloon) {
15372 15373 15374
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain max memory %lld does not match source %lld"),
                       dst->mem.max_balloon, src->mem.max_balloon);
15375
        goto error;
15376 15377
    }
    if (src->mem.cur_balloon != dst->mem.cur_balloon) {
15378 15379 15380
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain current memory %lld does not match source %lld"),
                       dst->mem.cur_balloon, src->mem.cur_balloon);
15381
        goto error;
15382
    }
15383
    if (src->mem.nhugepages != dst->mem.nhugepages) {
15384
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15385 15386
                       _("Target domain huge pages count %zu does not match source %zu"),
                       dst->mem.nhugepages, src->mem.nhugepages);
15387
        goto error;
15388
    }
15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414
    for (i = 0; i < src->mem.nhugepages; i++) {
        virDomainHugePagePtr src_huge = &src->mem.hugepages[i];
        virDomainHugePagePtr dst_huge = &dst->mem.hugepages[i];

        if (src_huge->size != dst_huge->size) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target domain huge page size %llu "
                             "does not match source %llu"),
                           dst_huge->size, src_huge->size);
            goto error;
        }

        if (src_huge->nodemask && dst_huge->nodemask) {
            if (!virBitmapEqual(src_huge->nodemask, dst_huge->nodemask)) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("Target huge page nodemask does not match source"));
                goto error;
            }
        } else {
            if (src_huge->nodemask || dst_huge->nodemask) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("Target huge page nodemask does not match source"));
                goto error;
            }
        }
    }
15415

15416
    if (src->vcpus != dst->vcpus) {
15417
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15418
                       _("Target domain vCPU count %d does not match source %d"),
15419
                       dst->vcpus, src->vcpus);
15420
        goto error;
15421 15422
    }
    if (src->maxvcpus != dst->maxvcpus) {
15423
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15424
                       _("Target domain vCPU max %d does not match source %d"),
15425
                       dst->maxvcpus, src->maxvcpus);
15426
        goto error;
15427 15428
    }

15429 15430 15431 15432 15433 15434 15435 15436
    if (src->iothreads != dst->iothreads) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain iothreads count %u does not "
                         "match source %u"),
                       dst->iothreads, src->iothreads);
        goto error;
    }

15437
    if (STRNEQ(src->os.type, dst->os.type)) {
15438 15439 15440
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain OS type %s does not match source %s"),
                       dst->os.type, src->os.type);
15441
        goto error;
15442
    }
15443
    if (src->os.arch != dst->os.arch) {
15444 15445
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain architecture %s does not match source %s"),
15446 15447
                       virArchToString(dst->os.arch),
                       virArchToString(src->os.arch));
15448
        goto error;
15449
    }
15450
    if (STRNEQ_NULLABLE(src->os.machine, dst->os.machine)) {
15451 15452 15453
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain OS type %s does not match source %s"),
                       dst->os.machine, src->os.machine);
15454
        goto error;
15455 15456 15457
    }

    if (src->os.smbios_mode != dst->os.smbios_mode) {
15458 15459 15460 15461
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain SMBIOS mode %s does not match source %s"),
                       virDomainSmbiosModeTypeToString(dst->os.smbios_mode),
                       virDomainSmbiosModeTypeToString(src->os.smbios_mode));
15462
        goto error;
15463 15464
    }

15465
    if (!virDomainDefFeaturesCheckABIStability(src, dst))
15466
        goto error;
15467 15468

    if (src->clock.ntimers != dst->clock.ntimers) {
15469 15470
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Target domain timers do not match source"));
15471
        goto error;
15472 15473
    }

15474
    for (i = 0; i < src->clock.ntimers; i++) {
15475 15476
        if (!virDomainTimerDefCheckABIStability(src->clock.timers[i],
                                                dst->clock.timers[i]))
15477
            goto error;
15478 15479 15480
    }

    if (!virCPUDefIsEqual(src->cpu, dst->cpu))
15481
        goto error;
15482 15483

    if (!virSysinfoIsEqual(src->sysinfo, dst->sysinfo))
15484
        goto error;
15485 15486

    if (src->ndisks != dst->ndisks) {
15487
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15488
                       _("Target domain disk count %zu does not match source %zu"),
15489
                       dst->ndisks, src->ndisks);
15490
        goto error;
15491 15492
    }

15493
    for (i = 0; i < src->ndisks; i++)
15494
        if (!virDomainDiskDefCheckABIStability(src->disks[i], dst->disks[i]))
15495
            goto error;
15496 15497

    if (src->ncontrollers != dst->ncontrollers) {
15498
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15499
                       _("Target domain controller count %zu "
15500
                         "does not match source %zu"),
15501
                       dst->ncontrollers, src->ncontrollers);
15502
        goto error;
15503 15504
    }

15505
    for (i = 0; i < src->ncontrollers; i++)
15506 15507
        if (!virDomainControllerDefCheckABIStability(src->controllers[i],
                                                     dst->controllers[i]))
15508
            goto error;
15509 15510

    if (src->nfss != dst->nfss) {
15511
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15512 15513
                       _("Target domain filesystem count %zu "
                         "does not match source %zu"),
15514
                       dst->nfss, src->nfss);
15515
        goto error;
15516 15517
    }

15518
    for (i = 0; i < src->nfss; i++)
15519
        if (!virDomainFsDefCheckABIStability(src->fss[i], dst->fss[i]))
15520
            goto error;
15521 15522

    if (src->nnets != dst->nnets) {
15523
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15524 15525
                       _("Target domain net card count %zu "
                         "does not match source %zu"),
15526
                       dst->nnets, src->nnets);
15527
        goto error;
15528 15529
    }

15530
    for (i = 0; i < src->nnets; i++)
15531
        if (!virDomainNetDefCheckABIStability(src->nets[i], dst->nets[i]))
15532
            goto error;
15533 15534

    if (src->ninputs != dst->ninputs) {
15535
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15536 15537
                       _("Target domain input device count %zu "
                         "does not match source %zu"),
15538
                       dst->ninputs, src->ninputs);
15539
        goto error;
15540 15541
    }

15542
    for (i = 0; i < src->ninputs; i++)
15543
        if (!virDomainInputDefCheckABIStability(src->inputs[i], dst->inputs[i]))
15544
            goto error;
15545 15546

    if (src->nsounds != dst->nsounds) {
15547
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15548 15549
                       _("Target domain sound card count %zu "
                         "does not match source %zu"),
15550
                       dst->nsounds, src->nsounds);
15551
        goto error;
15552 15553
    }

15554
    for (i = 0; i < src->nsounds; i++)
15555
        if (!virDomainSoundDefCheckABIStability(src->sounds[i], dst->sounds[i]))
15556
            goto error;
15557 15558

    if (src->nvideos != dst->nvideos) {
15559
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15560 15561
                       _("Target domain video card count %zu "
                         "does not match source %zu"),
15562
                       dst->nvideos, src->nvideos);
15563
        goto error;
15564 15565
    }

15566
    for (i = 0; i < src->nvideos; i++)
15567
        if (!virDomainVideoDefCheckABIStability(src->videos[i], dst->videos[i]))
15568
            goto error;
15569 15570

    if (src->nhostdevs != dst->nhostdevs) {
15571
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15572 15573
                       _("Target domain host device count %zu "
                         "does not match source %zu"),
15574
                       dst->nhostdevs, src->nhostdevs);
15575
        goto error;
15576 15577
    }

15578
    for (i = 0; i < src->nhostdevs; i++)
15579 15580
        if (!virDomainHostdevDefCheckABIStability(src->hostdevs[i],
                                                  dst->hostdevs[i]))
15581
            goto error;
15582 15583

    if (src->nsmartcards != dst->nsmartcards) {
15584
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15585 15586
                       _("Target domain smartcard count %zu "
                         "does not match source %zu"),
15587
                       dst->nsmartcards, src->nsmartcards);
15588
        goto error;
15589 15590
    }

15591
    for (i = 0; i < src->nsmartcards; i++)
15592 15593
        if (!virDomainSmartcardDefCheckABIStability(src->smartcards[i],
                                                    dst->smartcards[i]))
15594
            goto error;
15595 15596

    if (src->nserials != dst->nserials) {
15597
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15598 15599
                       _("Target domain serial port count %zu "
                         "does not match source %zu"),
15600
                       dst->nserials, src->nserials);
15601
        goto error;
15602 15603
    }

15604
    for (i = 0; i < src->nserials; i++)
15605 15606
        if (!virDomainSerialDefCheckABIStability(src->serials[i],
                                                 dst->serials[i]))
15607
            goto error;
15608 15609

    if (src->nparallels != dst->nparallels) {
15610
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15611 15612
                       _("Target domain parallel port count %zu "
                         "does not match source %zu"),
15613
                       dst->nparallels, src->nparallels);
15614
        goto error;
15615 15616
    }

15617
    for (i = 0; i < src->nparallels; i++)
15618 15619
        if (!virDomainParallelDefCheckABIStability(src->parallels[i],
                                                   dst->parallels[i]))
15620
            goto error;
15621 15622

    if (src->nchannels != dst->nchannels) {
15623
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15624 15625
                       _("Target domain channel count %zu "
                         "does not match source %zu"),
15626
                       dst->nchannels, src->nchannels);
15627
        goto error;
15628 15629
    }

15630
    for (i = 0; i < src->nchannels; i++)
15631 15632
        if (!virDomainChannelDefCheckABIStability(src->channels[i],
                                                  dst->channels[i]))
15633
            goto error;
15634

15635
    if (src->nconsoles != dst->nconsoles) {
15636
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15637 15638
                       _("Target domain console count %zu "
                         "does not match source %zu"),
15639
                       dst->nconsoles, src->nconsoles);
15640
        goto error;
15641 15642
    }

15643
    for (i = 0; i < src->nconsoles; i++)
15644 15645
        if (!virDomainConsoleDefCheckABIStability(src->consoles[i],
                                                  dst->consoles[i]))
15646
            goto error;
15647

M
Marc-André Lureau 已提交
15648
    if (src->nhubs != dst->nhubs) {
15649
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15650 15651
                       _("Target domain hub device count %zu "
                         "does not match source %zu"),
15652
                       dst->nhubs, src->nhubs);
15653
        goto error;
M
Marc-André Lureau 已提交
15654 15655
    }

15656
    for (i = 0; i < src->nhubs; i++)
M
Marc-André Lureau 已提交
15657
        if (!virDomainHubDefCheckABIStability(src->hubs[i], dst->hubs[i]))
15658
            goto error;
M
Marc-André Lureau 已提交
15659

15660 15661 15662 15663
    if (src->nredirdevs != dst->nredirdevs) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain redirected devices count %zu "
                         "does not match source %zu"),
15664
                       dst->nredirdevs, src->nredirdevs);
15665 15666 15667 15668 15669 15670 15671 15672 15673
        goto error;
    }

    for (i = 0; i < src->nredirdevs; i++) {
        if (!virDomainRedirdevDefCheckABIStability(src->redirdevs[i],
                                                   dst->redirdevs[i]))
            goto error;
    }

15674 15675 15676
    if ((!src->redirfilter && dst->redirfilter) ||
        (src->redirfilter && !dst->redirfilter)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15677 15678
                       _("Target domain USB redirection filter count %d "
                         "does not match source %d"),
15679
                       dst->redirfilter ? 1 : 0, src->redirfilter ? 1 : 0);
15680
        goto error;
15681 15682 15683
    }

    if (src->redirfilter &&
15684 15685
        !virDomainRedirFilterDefCheckABIStability(src->redirfilter,
                                                  dst->redirfilter))
15686
        goto error;
15687 15688 15689

    if ((!src->watchdog && dst->watchdog) ||
        (src->watchdog && !dst->watchdog)) {
15690
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15691 15692
                       _("Target domain watchdog count %d "
                         "does not match source %d"),
15693
                       dst->watchdog ? 1 : 0, src->watchdog ? 1 : 0);
15694
        goto error;
15695 15696 15697 15698
    }

    if (src->watchdog &&
        !virDomainWatchdogDefCheckABIStability(src->watchdog, dst->watchdog))
15699
        goto error;
15700 15701 15702

    if ((!src->memballoon && dst->memballoon) ||
        (src->memballoon && !dst->memballoon)) {
15703
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15704 15705
                       _("Target domain memory balloon count %d "
                         "does not match source %d"),
15706
                       dst->memballoon ? 1 : 0, src->memballoon ? 1 : 0);
15707
        goto error;
15708 15709 15710
    }

    if (src->memballoon &&
15711 15712
        !virDomainMemballoonDefCheckABIStability(src->memballoon,
                                                 dst->memballoon))
15713
        goto error;
15714

15715 15716 15717 15718
    if (src->nrngs != dst->nrngs) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain RNG device count %zu "
                         "does not match source %zu"), dst->nrngs, src->nrngs);
15719
        goto error;
15720 15721 15722 15723 15724
    }

    for (i = 0; i < src->nrngs; i++)
        if (!virDomainRNGDefCheckABIStability(src->rngs[i], dst->rngs[i]))
            goto error;
15725

H
Hu Tao 已提交
15726
    if (!virDomainPanicCheckABIStability(src->panic, dst->panic))
15727
        goto error;
H
Hu Tao 已提交
15728

15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740
    if (src->nshmems != dst->nshmems) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain shared memory device count %zu "
                         "does not match source %zu"), dst->nshmems, src->nshmems);
        goto error;
    }

    for (i = 0; i < src->nshmems; i++) {
        if (!virDomainShmemDefCheckABIStability(src->shmems[i], dst->shmems[i]))
            goto error;
    }

15741 15742 15743 15744 15745 15746 15747 15748 15749 15750
    if (src->tpm && dst->tpm) {
        if (!virDomainTPMDefCheckABIStability(src->tpm, dst->tpm))
            goto error;
    } else if (src->tpm || dst->tpm) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Either both target and source domains or none of "
                         "them must have TPM device present"));
        goto error;
    }

15751 15752 15753 15754 15755 15756 15757 15758 15759 15760
    if (src->panic && dst->panic) {
        if (!virDomainPanicDefCheckABIStability(src->panic, dst->panic))
            goto error;
    } else if (src->panic || dst->panic) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Either both target and source domains or none of "
                         "them must have PANIC device present"));
        goto error;
    }

15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788
    /* Coverity is not very happy with this - all dead_error_condition */
#if !STATIC_ANALYSIS
    /* This switch statement is here to trigger compiler warning when adding
     * a new device type. When you are adding a new field to the switch you
     * also have to add an check above. Otherwise the switch statement has no
     * real function here and should be optimized out by the compiler. */
    i = VIR_DOMAIN_DEVICE_LAST;
    switch ((virDomainDeviceType) i) {
    case VIR_DOMAIN_DEVICE_DISK:
    case VIR_DOMAIN_DEVICE_LEASE:
    case VIR_DOMAIN_DEVICE_FS:
    case VIR_DOMAIN_DEVICE_NET:
    case VIR_DOMAIN_DEVICE_INPUT:
    case VIR_DOMAIN_DEVICE_SOUND:
    case VIR_DOMAIN_DEVICE_VIDEO:
    case VIR_DOMAIN_DEVICE_HOSTDEV:
    case VIR_DOMAIN_DEVICE_WATCHDOG:
    case VIR_DOMAIN_DEVICE_CONTROLLER:
    case VIR_DOMAIN_DEVICE_GRAPHICS:
    case VIR_DOMAIN_DEVICE_HUB:
    case VIR_DOMAIN_DEVICE_REDIRDEV:
    case VIR_DOMAIN_DEVICE_NONE:
    case VIR_DOMAIN_DEVICE_SMARTCARD:
    case VIR_DOMAIN_DEVICE_CHR:
    case VIR_DOMAIN_DEVICE_MEMBALLOON:
    case VIR_DOMAIN_DEVICE_NVRAM:
    case VIR_DOMAIN_DEVICE_LAST:
    case VIR_DOMAIN_DEVICE_RNG:
15789
    case VIR_DOMAIN_DEVICE_TPM:
15790
    case VIR_DOMAIN_DEVICE_PANIC:
15791 15792 15793 15794 15795
    case VIR_DOMAIN_DEVICE_SHMEM:
        break;
    }
#endif

15796
    return true;
15797

15798
 error:
15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812
    err = virSaveLastError();

    strSrc = virDomainDefFormat(src, 0);
    strDst = virDomainDefFormat(dst, 0);
    VIR_DEBUG("XMLs that failed stability check were: src=\"%s\", dst=\"%s\"",
              NULLSTR(strSrc), NULLSTR(strDst));
    VIR_FREE(strSrc);
    VIR_FREE(strDst);

    if (err) {
        virSetError(err);
        virFreeError(err);
    }
    return false;
15813 15814 15815
}


15816 15817 15818 15819
static int
virDomainDefAddDiskControllersForType(virDomainDefPtr def,
                                      int controllerType,
                                      int diskBus)
15820
{
15821
    size_t i;
15822 15823
    int maxController = -1;

15824
    for (i = 0; i < def->ndisks; i++) {
15825 15826 15827 15828 15829 15830 15831 15832 15833 15834
        if (def->disks[i]->bus != diskBus)
            continue;

        if (def->disks[i]->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE)
            continue;

        if ((int)def->disks[i]->info.addr.drive.controller > maxController)
            maxController = def->disks[i]->info.addr.drive.controller;
    }

15835 15836 15837
    if (maxController == -1)
        return 0;

15838
    for (i = 0; i <= maxController; i++) {
15839
        if (virDomainDefMaybeAddController(def, controllerType, i, -1) < 0)
15840 15841 15842 15843 15844 15845 15846
            return -1;
    }

    return 0;
}


15847 15848
static int
virDomainDefMaybeAddVirtioSerialController(virDomainDefPtr def)
15849
{
C
Cole Robinson 已提交
15850
    /* Look for any virtio serial or virtio console devs */
15851
    size_t i;
15852

15853
    for (i = 0; i < def->nchannels; i++) {
15854 15855
        virDomainChrDefPtr channel = def->channels[i];

15856
        if (channel->targetType == VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO) {
15857 15858 15859 15860
            int idx = 0;
            if (channel->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL)
                idx = channel->info.addr.vioserial.controller;

15861
            if (virDomainDefMaybeAddController(def,
15862
                VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL, idx, -1) < 0)
15863 15864 15865 15866
                return -1;
        }
    }

15867
    for (i = 0; i < def->nconsoles; i++) {
15868
        virDomainChrDefPtr console = def->consoles[i];
C
Cole Robinson 已提交
15869 15870 15871 15872 15873 15874 15875 15876

        if (console->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_VIRTIO) {
            int idx = 0;
            if (console->info.type ==
                VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL)
                idx = console->info.addr.vioserial.controller;

            if (virDomainDefMaybeAddController(def,
15877
                VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL, idx, -1) < 0)
C
Cole Robinson 已提交
15878 15879 15880 15881
                return -1;
        }
    }

15882 15883 15884 15885
    return 0;
}


E
Eric Blake 已提交
15886 15887 15888 15889
static int
virDomainDefMaybeAddSmartcardController(virDomainDefPtr def)
{
    /* Look for any smartcard devs */
15890
    size_t i;
E
Eric Blake 已提交
15891

15892
    for (i = 0; i < def->nsmartcards; i++) {
E
Eric Blake 已提交
15893 15894 15895 15896 15897 15898 15899
        virDomainSmartcardDefPtr smartcard = def->smartcards[i];
        int idx = 0;

        if (smartcard->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID) {
            idx = smartcard->info.addr.ccid.controller;
        } else if (smartcard->info.type
                   == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
15900
            size_t j;
E
Eric Blake 已提交
15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916
            int max = -1;

            for (j = 0; j < def->nsmartcards; j++) {
                virDomainDeviceInfoPtr info = &def->smartcards[j]->info;
                if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID &&
                    info->addr.ccid.controller == 0 &&
                    (int) info->addr.ccid.slot > max)
                    max = info->addr.ccid.slot;
            }
            smartcard->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID;
            smartcard->info.addr.ccid.controller = 0;
            smartcard->info.addr.ccid.slot = max + 1;
        }

        if (virDomainDefMaybeAddController(def,
                                           VIR_DOMAIN_CONTROLLER_TYPE_CCID,
15917
                                           idx, -1) < 0)
E
Eric Blake 已提交
15918 15919 15920 15921 15922 15923
            return -1;
    }

    return 0;
}

15924
/*
15925
 * Based on the declared <address/> info for any devices,
15926
 * add necessary drive controllers which are not already present
15927 15928 15929
 * in the XML. This is for compat with existing apps which will
 * not know/care about <controller> info in the XML
 */
15930 15931
int
virDomainDefAddImplicitControllers(virDomainDefPtr def)
15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947
{
    if (virDomainDefAddDiskControllersForType(def,
                                              VIR_DOMAIN_CONTROLLER_TYPE_SCSI,
                                              VIR_DOMAIN_DISK_BUS_SCSI) < 0)
        return -1;

    if (virDomainDefAddDiskControllersForType(def,
                                              VIR_DOMAIN_CONTROLLER_TYPE_FDC,
                                              VIR_DOMAIN_DISK_BUS_FDC) < 0)
        return -1;

    if (virDomainDefAddDiskControllersForType(def,
                                              VIR_DOMAIN_CONTROLLER_TYPE_IDE,
                                              VIR_DOMAIN_DISK_BUS_IDE) < 0)
        return -1;

J
Jim Fehlig 已提交
15948 15949 15950 15951 15952
    if (virDomainDefAddDiskControllersForType(def,
                                              VIR_DOMAIN_CONTROLLER_TYPE_SATA,
                                              VIR_DOMAIN_DISK_BUS_SATA) < 0)
        return -1;

15953 15954 15955
    if (virDomainDefMaybeAddVirtioSerialController(def) < 0)
        return -1;

E
Eric Blake 已提交
15956 15957 15958
    if (virDomainDefMaybeAddSmartcardController(def) < 0)
        return -1;

H
Han Cheng 已提交
15959 15960 15961
    if (virDomainDefMaybeAddHostdevSCSIcontroller(def) < 0)
        return -1;

15962 15963 15964
    return 0;
}

15965 15966 15967
/* Check if vcpupin with same vcpuid already exists.
 * Return 1 if exists, 0 if not. */
int
E
Eric Blake 已提交
15968
virDomainVcpuPinIsDuplicate(virDomainVcpuPinDefPtr *def,
15969 15970 15971
                            int nvcpupin,
                            int vcpu)
{
15972
    size_t i;
15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984

    if (!def || !nvcpupin)
        return 0;

    for (i = 0; i < nvcpupin; i++) {
        if (def[i]->vcpuid == vcpu)
            return 1;
    }

    return 0;
}

E
Eric Blake 已提交
15985 15986
virDomainVcpuPinDefPtr
virDomainVcpuPinFindByVcpu(virDomainVcpuPinDefPtr *def,
15987 15988 15989
                           int nvcpupin,
                           int vcpu)
{
15990
    size_t i;
15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002

    if (!def || !nvcpupin)
        return NULL;

    for (i = 0; i < nvcpupin; i++) {
        if (def[i]->vcpuid == vcpu)
            return def[i];
    }

    return NULL;
}

16003 16004
int
virDomainVcpuPinAdd(virDomainVcpuPinDefPtr **vcpupin_list,
16005
                    size_t *nvcpupin,
16006 16007 16008
                    unsigned char *cpumap,
                    int maplen,
                    int vcpu)
16009 16010 16011
{
    virDomainVcpuPinDefPtr vcpupin = NULL;

H
Hu Tao 已提交
16012 16013
    if (!vcpupin_list)
        return -1;
16014

16015
    vcpupin = virDomainVcpuPinFindByVcpu(*vcpupin_list,
H
Hu Tao 已提交
16016 16017 16018
                                         *nvcpupin,
                                         vcpu);
    if (vcpupin) {
16019
        vcpupin->vcpuid = vcpu;
H
Hu Tao 已提交
16020 16021
        virBitmapFree(vcpupin->cpumask);
        vcpupin->cpumask = virBitmapNewData(cpumap, maplen);
16022
        if (!vcpupin->cpumask)
H
Hu Tao 已提交
16023
            return -1;
16024

H
Hu Tao 已提交
16025 16026
        return 0;
    }
16027

H
Hu Tao 已提交
16028
    /* No existing vcpupin matches vcpu, adding a new one */
16029

16030
    if (VIR_ALLOC(vcpupin) < 0)
16031
        goto error;
16032

H
Hu Tao 已提交
16033
    vcpupin->vcpuid = vcpu;
H
Hu Tao 已提交
16034
    vcpupin->cpumask = virBitmapNewData(cpumap, maplen);
16035
    if (!vcpupin->cpumask)
16036
        goto error;
16037

16038
    if (VIR_APPEND_ELEMENT(*vcpupin_list, *nvcpupin, vcpupin) < 0)
16039
        goto error;
H
Hu Tao 已提交
16040 16041

    return 0;
16042

16043
 error:
G
Guido Günther 已提交
16044
    virDomainVcpuPinDefFree(vcpupin);
16045
    return -1;
16046 16047
}

16048
void
E
Eric Blake 已提交
16049
virDomainVcpuPinDel(virDomainDefPtr def, int vcpu)
16050 16051
{
    int n;
E
Eric Blake 已提交
16052
    virDomainVcpuPinDefPtr *vcpupin_list = def->cputune.vcpupin;
16053 16054 16055

    for (n = 0; n < def->cputune.nvcpupin; n++) {
        if (vcpupin_list[n]->vcpuid == vcpu) {
16056
            virBitmapFree(vcpupin_list[n]->cpumask);
16057
            VIR_FREE(vcpupin_list[n]);
16058
            VIR_DELETE_ELEMENT(vcpupin_list, n, def->cputune.nvcpupin);
16059
            return;
16060 16061 16062 16063
        }
    }
}

16064 16065 16066 16067 16068 16069 16070 16071 16072
int
virDomainEmulatorPinAdd(virDomainDefPtr def,
                        unsigned char *cpumap,
                        int maplen)
{
    virDomainVcpuPinDefPtr emulatorpin = NULL;

    if (!def->cputune.emulatorpin) {
        /* No emulatorpin exists yet. */
16073
        if (VIR_ALLOC(emulatorpin) < 0)
H
Hu Tao 已提交
16074
            return -1;
16075 16076

        emulatorpin->vcpuid = -1;
H
Hu Tao 已提交
16077
        emulatorpin->cpumask = virBitmapNewData(cpumap, maplen);
16078 16079
        if (!emulatorpin->cpumask) {
            virDomainVcpuPinDefFree(emulatorpin);
H
Hu Tao 已提交
16080
            return -1;
16081
        }
H
Hu Tao 已提交
16082

16083 16084 16085 16086 16087
        def->cputune.emulatorpin = emulatorpin;
    } else {
        /* Since there is only 1 emulatorpin for each vm,
         * juest replace the old one.
         */
H
Hu Tao 已提交
16088 16089 16090 16091
        virBitmapFree(def->cputune.emulatorpin->cpumask);
        def->cputune.emulatorpin->cpumask = virBitmapNewData(cpumap, maplen);
        if (!def->cputune.emulatorpin->cpumask)
            return -1;
16092 16093 16094 16095 16096 16097 16098 16099
    }

    return 0;
}

int
virDomainEmulatorPinDel(virDomainDefPtr def)
{
16100
    if (!def->cputune.emulatorpin)
16101 16102
        return 0;

H
Hu Tao 已提交
16103
    virDomainVcpuPinDefFree(def->cputune.emulatorpin);
16104 16105 16106 16107 16108
    def->cputune.emulatorpin = NULL;

    return 0;
}

16109
static int
16110 16111 16112 16113
virDomainEventActionDefFormat(virBufferPtr buf,
                              int type,
                              const char *name,
                              virEventActionToStringFunc convFunc)
16114
{
16115
    const char *typeStr = convFunc(type);
16116
    if (!typeStr) {
16117
        virReportError(VIR_ERR_INTERNAL_ERROR,
16118
                       _("unexpected %s action: %d"), name, type);
16119 16120 16121
        return -1;
    }

16122
    virBufferAsprintf(buf, "<%s>%s</%s>\n", name, typeStr, name);
16123 16124 16125 16126 16127

    return 0;
}


16128
static void
16129
virSecurityLabelDefFormat(virBufferPtr buf,
16130
                          virSecurityLabelDefPtr def)
16131 16132 16133 16134
{
    const char *sectype = virDomainSeclabelTypeToString(def->type);

    if (!sectype)
16135 16136 16137 16138 16139
        return;

    if (def->type == VIR_DOMAIN_SECLABEL_DEFAULT)
        return;

16140 16141
    /* To avoid backward compatibility issues, suppress DAC and 'none' labels
     * that are automatically generated.
16142
     */
16143 16144
    if ((STREQ_NULLABLE(def->model, "dac") ||
         STREQ_NULLABLE(def->model, "none")) && def->implicit)
16145 16146
        return;

16147 16148 16149
    virBufferAsprintf(buf, "<seclabel type='%s'",
                      sectype);

16150
    virBufferEscapeString(buf, " model='%s'", def->model);
16151

16152 16153 16154 16155 16156
    if (def->type == VIR_DOMAIN_SECLABEL_NONE) {
        virBufferAddLit(buf, "/>\n");
        return;
    }

16157
    virBufferAsprintf(buf, " relabel='%s'",
16158
                      def->relabel ? "yes" : "no");
16159

16160 16161
    if (def->label || def->imagelabel || def->baselabel) {
        virBufferAddLit(buf, ">\n");
16162 16163
        virBufferAdjustIndent(buf, 2);
        virBufferEscapeString(buf, "<label>%s</label>\n",
16164
                              def->label);
16165
        if (def->relabel)
16166
            virBufferEscapeString(buf, "<imagelabel>%s</imagelabel>\n",
16167 16168
                                  def->imagelabel);
        if (def->type == VIR_DOMAIN_SECLABEL_DYNAMIC)
16169
            virBufferEscapeString(buf, "<baselabel>%s</baselabel>\n",
16170
                                  def->baselabel);
16171
        virBufferAdjustIndent(buf, -2);
16172
        virBufferAddLit(buf, "</seclabel>\n");
16173 16174
    } else {
        virBufferAddLit(buf, "/>\n");
16175 16176 16177 16178
    }
}


16179 16180
static void
virSecurityDeviceLabelDefFormat(virBufferPtr buf,
16181 16182
                                virSecurityDeviceLabelDefPtr def,
                                unsigned int flags)
16183
{
16184 16185
    /* For offline output, skip elements that allow labels but have no
     * label specified (possible if labelskip was ignored on input).  */
16186
    if ((flags & VIR_DOMAIN_XML_INACTIVE) && !def->label && def->relabel)
16187 16188
        return;

16189
    virBufferAddLit(buf, "<seclabel");
16190 16191 16192 16193

    if (def->model)
        virBufferAsprintf(buf, " model='%s'", def->model);

16194 16195 16196
    if (def->labelskip)
        virBufferAddLit(buf, " labelskip='yes'");
    else
16197
        virBufferAsprintf(buf, " relabel='%s'", def->relabel ? "yes" : "no");
16198

16199 16200
    if (def->label) {
        virBufferAddLit(buf, ">\n");
16201 16202
        virBufferAdjustIndent(buf, 2);
        virBufferEscapeString(buf, "<label>%s</label>\n",
16203
                              def->label);
16204
        virBufferAdjustIndent(buf, -2);
16205 16206 16207 16208 16209 16210 16211
        virBufferAddLit(buf, "</seclabel>\n");
    } else {
        virBufferAddLit(buf, "/>\n");
    }
}


16212 16213 16214 16215
static int
virDomainLeaseDefFormat(virBufferPtr buf,
                        virDomainLeaseDefPtr def)
{
16216 16217 16218 16219 16220
    virBufferAddLit(buf, "<lease>\n");
    virBufferAdjustIndent(buf, 2);
    virBufferEscapeString(buf, "<lockspace>%s</lockspace>\n", def->lockspace);
    virBufferEscapeString(buf, "<key>%s</key>\n", def->key);
    virBufferEscapeString(buf, "<target path='%s'", def->path);
16221 16222 16223
    if (def->offset)
        virBufferAsprintf(buf, " offset='%llu'", def->offset);
    virBufferAddLit(buf, "/>\n");
16224 16225
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</lease>\n");
16226 16227 16228 16229

    return 0;
}

16230 16231 16232
static void
virDomainDiskGeometryDefFormat(virBufferPtr buf,
                               virDomainDiskDefPtr def)
J
J.B. Joret 已提交
16233 16234 16235 16236 16237 16238 16239 16240
{
    const char *trans =
        virDomainDiskGeometryTransTypeToString(def->geometry.trans);

    if (def->geometry.cylinders > 0 &&
        def->geometry.heads > 0 &&
        def->geometry.sectors > 0) {
        virBufferAsprintf(buf,
16241
                          "<geometry cyls='%u' heads='%u' secs='%u'",
J
J.B. Joret 已提交
16242 16243 16244 16245 16246 16247 16248 16249 16250 16251
                          def->geometry.cylinders,
                          def->geometry.heads,
                          def->geometry.sectors);

        if (def->geometry.trans != VIR_DOMAIN_DISK_TRANS_DEFAULT)
            virBufferEscapeString(buf, " trans='%s'", trans);

        virBufferAddLit(buf, "/>\n");
    }
}
16252

16253 16254 16255
static void
virDomainDiskBlockIoDefFormat(virBufferPtr buf,
                              virDomainDiskDefPtr def)
16256
{
V
Viktor Mihajlovski 已提交
16257 16258
    if (def->blockio.logical_block_size > 0 ||
        def->blockio.physical_block_size > 0) {
16259
        virBufferAddLit(buf, "<blockio");
V
Viktor Mihajlovski 已提交
16260
        if (def->blockio.logical_block_size > 0) {
16261 16262
            virBufferAsprintf(buf,
                              " logical_block_size='%u'",
V
Viktor Mihajlovski 已提交
16263
                              def->blockio.logical_block_size);
16264
        }
V
Viktor Mihajlovski 已提交
16265
        if (def->blockio.physical_block_size > 0) {
16266 16267
            virBufferAsprintf(buf,
                              " physical_block_size='%u'",
V
Viktor Mihajlovski 已提交
16268
                              def->blockio.physical_block_size);
16269 16270 16271 16272 16273
        }
        virBufferAddLit(buf, "/>\n");
    }
}

16274

16275
/* virDomainSourceDefFormatSeclabel:
16276 16277 16278 16279 16280
 *
 * This function automaticaly closes the <source> element and formats any
 * possible seclabels.
 */
static void
16281 16282 16283 16284 16285
virDomainDiskSourceDefFormatSeclabel(virBufferPtr buf,
                                     size_t nseclabels,
                                     virSecurityDeviceLabelDefPtr *seclabels,
                                     unsigned int flags,
                                     bool skipSeclables)
16286 16287 16288
{
    size_t n;

16289
    if (nseclabels && !skipSeclables) {
16290
        virBufferAddLit(buf, ">\n");
16291
        virBufferAdjustIndent(buf, 2);
16292 16293
        for (n = 0; n < nseclabels; n++)
            virSecurityDeviceLabelDefFormat(buf, seclabels[n], flags);
16294 16295
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</source>\n");
16296 16297 16298 16299 16300
    } else {
        virBufferAddLit(buf, "/>\n");
    }
}

16301 16302 16303 16304 16305 16306 16307 16308 16309 16310 16311 16312 16313 16314 16315
static void
virDomainSourceDefFormatSeclabel(virBufferPtr buf,
                                 size_t nseclabels,
                                 virSecurityDeviceLabelDefPtr *seclabels,
                                 unsigned int flags)
{
    virDomainDiskSourceDefFormatSeclabel(buf, nseclabels, seclabels, flags, false);
}

static int
virDomainDiskSourceFormatInternal(virBufferPtr buf,
                                  virStorageSourcePtr src,
                                  int policy,
                                  unsigned int flags,
                                  bool skipSeclabels)
16316
{
16317
    size_t n;
16318
    char *path = NULL;
16319
    const char *startupPolicy = NULL;
16320

16321 16322 16323
    if (policy)
        startupPolicy = virDomainStartupPolicyTypeToString(policy);

16324
    if (src->path || src->nhosts > 0 || src->srcpool || startupPolicy) {
16325
        switch ((virStorageType)src->type) {
E
Eric Blake 已提交
16326
        case VIR_STORAGE_TYPE_FILE:
16327
            virBufferAddLit(buf, "<source");
16328
            virBufferEscapeString(buf, " file='%s'", src->path);
16329 16330
            virBufferEscapeString(buf, " startupPolicy='%s'", startupPolicy);

16331 16332 16333
            virDomainDiskSourceDefFormatSeclabel(buf, src->nseclabels,
                                                 src->seclabels, flags,
                                                 skipSeclabels);
16334
            break;
16335

E
Eric Blake 已提交
16336
        case VIR_STORAGE_TYPE_BLOCK:
16337
            virBufferAddLit(buf, "<source");
16338
            virBufferEscapeString(buf, " dev='%s'", src->path);
16339 16340
            virBufferEscapeString(buf, " startupPolicy='%s'", startupPolicy);

16341 16342 16343
            virDomainDiskSourceDefFormatSeclabel(buf, src->nseclabels,
                                                 src->seclabels, flags,
                                                 skipSeclabels);
16344
            break;
16345

E
Eric Blake 已提交
16346
        case VIR_STORAGE_TYPE_DIR:
16347
            virBufferAddLit(buf, "<source");
16348
            virBufferEscapeString(buf, " dir='%s'", src->path);
16349
            virBufferEscapeString(buf, " startupPolicy='%s'", startupPolicy);
16350
            virBufferAddLit(buf, "/>\n");
16351
            break;
16352

E
Eric Blake 已提交
16353
        case VIR_STORAGE_TYPE_NETWORK:
16354
            virBufferAsprintf(buf, "<source protocol='%s'",
16355
                              virStorageNetProtocolTypeToString(src->protocol));
16356 16357 16358 16359 16360 16361 16362 16363 16364 16365


            if (src->volume) {
                if (virAsprintf(&path, "%s%s", src->volume, src->path) < 0)
                    return -1;
            }

            virBufferEscapeString(buf, " name='%s'", path ? path : src->path);

            VIR_FREE(path);
16366

16367
            if (src->nhosts == 0 && !src->snapshot && !src->configFile) {
16368 16369 16370
                virBufferAddLit(buf, "/>\n");
            } else {
                virBufferAddLit(buf, ">\n");
16371
                virBufferAdjustIndent(buf, 2);
16372

16373
                for (n = 0; n < src->nhosts; n++) {
16374
                    virBufferAddLit(buf, "<host");
16375 16376 16377 16378
                    virBufferEscapeString(buf, " name='%s'",
                                          src->hosts[n].name);
                    virBufferEscapeString(buf, " port='%s'",
                                          src->hosts[n].port);
16379

16380
                    if (src->hosts[n].transport)
16381
                        virBufferAsprintf(buf, " transport='%s'",
16382
                                          virStorageNetHostTransportTypeToString(src->hosts[n].transport));
16383

16384 16385
                    virBufferEscapeString(buf, " socket='%s'",
                                          src->hosts[n].socket);
16386

16387 16388
                    virBufferAddLit(buf, "/>\n");
                }
16389 16390 16391 16392

                virBufferEscapeString(buf, "<snapshot name='%s'/>\n",
                                      src->snapshot);

16393 16394 16395
                virBufferEscapeString(buf, "<config file='%s'/>\n",
                                      src->configFile);

16396 16397
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</source>\n");
16398 16399
            }
            break;
16400

E
Eric Blake 已提交
16401
        case VIR_STORAGE_TYPE_VOLUME:
16402
            virBufferAddLit(buf, "<source");
16403

16404 16405 16406 16407 16408
            if (src->srcpool) {
                virBufferEscapeString(buf, " pool='%s'", src->srcpool->pool);
                virBufferEscapeString(buf, " volume='%s'",
                                      src->srcpool->volume);
                if (src->srcpool->mode)
16409
                    virBufferAsprintf(buf, " mode='%s'",
16410
                                      virStorageSourcePoolModeTypeToString(src->srcpool->mode));
16411
            }
16412
            virBufferEscapeString(buf, " startupPolicy='%s'", startupPolicy);
16413

16414 16415 16416
            virDomainDiskSourceDefFormatSeclabel(buf, src->nseclabels,
                                                 src->seclabels, flags,
                                                 skipSeclabels);
16417
            break;
16418

16419
        case VIR_STORAGE_TYPE_NONE:
16420
        case VIR_STORAGE_TYPE_LAST:
16421
            virReportError(VIR_ERR_INTERNAL_ERROR,
16422
                           _("unexpected disk type %d"), src->type);
16423 16424 16425 16426 16427 16428
            return -1;
        }
    }

    return 0;
}
J
J.B. Joret 已提交
16429

16430

16431 16432 16433 16434 16435 16436 16437 16438 16439 16440
int
virDomainDiskSourceFormat(virBufferPtr buf,
                          virStorageSourcePtr src,
                          int policy,
                          unsigned int flags)
{
    return virDomainDiskSourceFormatInternal(buf, src, policy, flags, false);
}


16441 16442 16443 16444
static int
virDomainDiskBackingStoreFormat(virBufferPtr buf,
                                virStorageSourcePtr backingStore,
                                const char *backingStoreRaw,
16445
                                unsigned int idx)
16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465 16466 16467 16468 16469 16470 16471 16472
{
    const char *type;
    const char *format;

    if (!backingStore) {
        if (!backingStoreRaw)
            virBufferAddLit(buf, "<backingStore/>\n");
        return 0;
    }

    if (!backingStore->type ||
        !(type = virStorageTypeToString(backingStore->type))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected disk backing store type %d"),
                       backingStore->type);
        return -1;
    }

    if (backingStore->format <= 0 ||
        !(format = virStorageFileFormatTypeToString(backingStore->format))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected disk backing store format %d"),
                       backingStore->format);
        return -1;
    }

    virBufferAsprintf(buf, "<backingStore type='%s' index='%u'>\n",
16473
                      type, idx);
16474 16475 16476
    virBufferAdjustIndent(buf, 2);

    virBufferAsprintf(buf, "<format type='%s'/>\n", format);
16477 16478
    /* We currently don't output seclabels for backing chain element */
    if (virDomainDiskSourceFormatInternal(buf, backingStore, 0, 0, true) < 0 ||
16479 16480 16481
        virDomainDiskBackingStoreFormat(buf,
                                        backingStore->backingStore,
                                        backingStore->backingStoreRaw,
16482
                                        idx + 1) < 0)
16483 16484 16485 16486 16487 16488 16489 16490
        return -1;

    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</backingStore>\n");
    return 0;
}


16491
static int
16492
virDomainDiskDefFormat(virBufferPtr buf,
D
Daniel P. Berrange 已提交
16493
                       virDomainDiskDefPtr def,
E
Eric Blake 已提交
16494
                       unsigned int flags)
16495
{
16496
    const char *type = virStorageTypeToString(def->src->type);
16497 16498
    const char *device = virDomainDiskDeviceTypeToString(def->device);
    const char *bus = virDomainDiskBusTypeToString(def->bus);
16499
    const char *cachemode = virDomainDiskCacheTypeToString(def->cachemode);
16500
    const char *error_policy = virDomainDiskErrorPolicyTypeToString(def->error_policy);
16501
    const char *rerror_policy = virDomainDiskErrorPolicyTypeToString(def->rerror_policy);
M
Matthias Dahl 已提交
16502
    const char *iomode = virDomainDiskIoTypeToString(def->iomode);
J
Ján Tomko 已提交
16503 16504 16505
    const char *ioeventfd = virTristateSwitchTypeToString(def->ioeventfd);
    const char *event_idx = virTristateSwitchTypeToString(def->event_idx);
    const char *copy_on_read = virTristateSwitchTypeToString(def->copy_on_read);
16506
    const char *sgio = virDomainDeviceSGIOTypeToString(def->sgio);
O
Osier Yang 已提交
16507
    const char *discard = virDomainDiskDiscardTypeToString(def->discard);
16508

16509
    if (!type || !def->src->type) {
16510
        virReportError(VIR_ERR_INTERNAL_ERROR,
16511
                       _("unexpected disk type %d"), def->src->type);
16512 16513 16514
        return -1;
    }
    if (!device) {
16515 16516
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected disk device %d"), def->device);
16517 16518 16519
        return -1;
    }
    if (!bus) {
16520 16521
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected disk bus %d"), def->bus);
16522 16523
        return -1;
    }
16524
    if (!cachemode) {
16525 16526
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected disk cache mode %d"), def->cachemode);
16527 16528
        return -1;
    }
M
Matthias Dahl 已提交
16529
    if (!iomode) {
16530 16531
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected disk io mode %d"), def->iomode);
M
Matthias Dahl 已提交
16532 16533
        return -1;
    }
O
Osier Yang 已提交
16534 16535 16536 16537 16538
    if (!sgio) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unexpected disk sgio mode '%d'"), def->sgio);
        return -1;
    }
16539

16540
    virBufferAsprintf(buf,
16541
                      "<disk type='%s' device='%s'",
16542
                      type, device);
16543 16544 16545
    if (def->rawio) {
        virBufferAsprintf(buf, " rawio='%s'",
                          virTristateBoolTypeToString(def->rawio));
16546
    }
O
Osier Yang 已提交
16547 16548 16549 16550

    if (def->sgio)
        virBufferAsprintf(buf, " sgio='%s'", sgio);

16551
    if (def->snapshot &&
16552 16553
        !(def->snapshot == VIR_DOMAIN_SNAPSHOT_LOCATION_NONE &&
          def->src->readonly))
16554
        virBufferAsprintf(buf, " snapshot='%s'",
E
Eric Blake 已提交
16555
                          virDomainSnapshotLocationTypeToString(def->snapshot));
16556
    virBufferAddLit(buf, ">\n");
16557
    virBufferAdjustIndent(buf, 2);
16558

16559
    if (def->src->driverName || def->src->format > 0 || def->cachemode ||
16560 16561
        def->error_policy || def->rerror_policy || def->iomode ||
        def->ioeventfd || def->event_idx || def->copy_on_read ||
16562
        def->discard || def->iothread) {
16563
        virBufferAddLit(buf, "<driver");
16564 16565 16566
        if (def->src->driverName)
            virBufferAsprintf(buf, " name='%s'", def->src->driverName);
        if (def->src->format > 0)
16567
            virBufferAsprintf(buf, " type='%s'",
16568
                              virStorageFileFormatTypeToString(def->src->format));
16569
        if (def->cachemode)
16570
            virBufferAsprintf(buf, " cache='%s'", cachemode);
16571
        if (def->error_policy)
16572
            virBufferAsprintf(buf, " error_policy='%s'", error_policy);
16573 16574
        if (def->rerror_policy)
            virBufferAsprintf(buf, " rerror_policy='%s'", rerror_policy);
M
Matthias Dahl 已提交
16575
        if (def->iomode)
16576
            virBufferAsprintf(buf, " io='%s'", iomode);
16577 16578
        if (def->ioeventfd)
            virBufferAsprintf(buf, " ioeventfd='%s'", ioeventfd);
16579 16580
        if (def->event_idx)
            virBufferAsprintf(buf, " event_idx='%s'", event_idx);
O
Osier Yang 已提交
16581 16582
        if (def->copy_on_read)
            virBufferAsprintf(buf, " copy_on_read='%s'", copy_on_read);
O
Osier Yang 已提交
16583 16584
        if (def->discard)
            virBufferAsprintf(buf, " discard='%s'", discard);
16585 16586
        if (def->iothread)
            virBufferAsprintf(buf, " iothread='%u'", def->iothread);
16587
        virBufferAddLit(buf, "/>\n");
16588 16589
    }

16590 16591 16592
    if (def->src->auth) {
        if (virStorageAuthDefFormat(buf, def->src->auth) < 0)
            return -1;
16593 16594
    }

16595
    if (virDomainDiskSourceFormat(buf, def->src, def->startupPolicy,
16596
                                  flags) < 0)
16597
        return -1;
16598 16599 16600 16601

    /* Don't format backingStore to inactive XMLs until the code for
     * persistent storage of backing chains is ready. */
    if (!(flags & VIR_DOMAIN_XML_INACTIVE) &&
16602 16603
        virDomainDiskBackingStoreFormat(buf, def->src->backingStore,
                                        def->src->backingStoreRaw, 1) < 0)
16604 16605
        return -1;

J
J.B. Joret 已提交
16606
    virDomainDiskGeometryDefFormat(buf, def);
V
Viktor Mihajlovski 已提交
16607
    virDomainDiskBlockIoDefFormat(buf, def);
J
J.B. Joret 已提交
16608

16609 16610
    /* For now, mirroring is currently output-only: we only output it
     * for live domains, therefore we ignore it on input except for
16611 16612 16613 16614
     * the internal parse on libvirtd restart.  We prefer to output
     * the new style similar to backingStore, but for back-compat on
     * blockcopy files we also have to output old style attributes.
     * The parser accepts either style across libvirtd upgrades. */
16615
    if (def->mirror && !(flags & VIR_DOMAIN_XML_INACTIVE)) {
16616 16617 16618 16619
        const char *formatStr = NULL;

        if (def->mirror->format)
            formatStr = virStorageFileFormatTypeToString(def->mirror->format);
E
Eric Blake 已提交
16620 16621
        virBufferAsprintf(buf, "<mirror type='%s'",
                          virStorageTypeToString(def->mirror->type));
E
Eric Blake 已提交
16622 16623
        if (def->mirror->type == VIR_STORAGE_TYPE_FILE &&
            def->mirrorJob == VIR_DOMAIN_BLOCK_JOB_TYPE_COPY) {
16624 16625 16626
            virBufferEscapeString(buf, " file='%s'", def->mirror->path);
            virBufferEscapeString(buf, " format='%s'", formatStr);
        }
E
Eric Blake 已提交
16627 16628
        virBufferEscapeString(buf, " job='%s'",
                              virDomainBlockJobTypeToString(def->mirrorJob));
16629 16630 16631 16632 16633 16634
        if (def->mirrorState) {
            const char *mirror;

            mirror = virDomainDiskMirrorStateTypeToString(def->mirrorState);
            virBufferEscapeString(buf, " ready='%s'", mirror);
        }
E
Eric Blake 已提交
16635 16636
        virBufferAddLit(buf, ">\n");
        virBufferAdjustIndent(buf, 2);
16637
        virBufferEscapeString(buf, "<format type='%s'/>\n", formatStr);
E
Eric Blake 已提交
16638 16639 16640 16641
        if (virDomainDiskSourceFormat(buf, def->mirror, 0, 0) < 0)
            return -1;
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</mirror>\n");
16642 16643
    }

16644
    virBufferAsprintf(buf, "<target dev='%s' bus='%s'",
16645
                      def->dst, bus);
16646 16647
    if ((def->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY ||
         def->device == VIR_DOMAIN_DISK_DEVICE_CDROM) &&
E
Eric Blake 已提交
16648
        def->tray_status != VIR_DOMAIN_DISK_TRAY_CLOSED)
16649
        virBufferAsprintf(buf, " tray='%s'",
16650
                          virDomainDiskTrayTypeToString(def->tray_status));
16651
    if (def->bus == VIR_DOMAIN_DISK_BUS_USB &&
J
Ján Tomko 已提交
16652
        def->removable != VIR_TRISTATE_SWITCH_ABSENT) {
16653
        virBufferAsprintf(buf, " removable='%s'",
J
Ján Tomko 已提交
16654
                          virTristateSwitchTypeToString(def->removable));
16655 16656
    }
    virBufferAddLit(buf, "/>\n");
16657

L
Lei Li 已提交
16658 16659 16660 16661 16662 16663
    /*disk I/O throttling*/
    if (def->blkdeviotune.total_bytes_sec ||
        def->blkdeviotune.read_bytes_sec ||
        def->blkdeviotune.write_bytes_sec ||
        def->blkdeviotune.total_iops_sec ||
        def->blkdeviotune.read_iops_sec ||
16664 16665 16666 16667 16668 16669 16670 16671
        def->blkdeviotune.write_iops_sec ||
        def->blkdeviotune.total_bytes_sec_max ||
        def->blkdeviotune.read_bytes_sec_max ||
        def->blkdeviotune.write_bytes_sec_max ||
        def->blkdeviotune.total_iops_sec_max ||
        def->blkdeviotune.read_iops_sec_max ||
        def->blkdeviotune.write_iops_sec_max ||
        def->blkdeviotune.size_iops_sec) {
16672 16673
        virBufferAddLit(buf, "<iotune>\n");
        virBufferAdjustIndent(buf, 2);
L
Lei Li 已提交
16674
        if (def->blkdeviotune.total_bytes_sec) {
16675
            virBufferAsprintf(buf, "<total_bytes_sec>%llu</total_bytes_sec>\n",
L
Lei Li 已提交
16676 16677 16678 16679
                              def->blkdeviotune.total_bytes_sec);
        }

        if (def->blkdeviotune.read_bytes_sec) {
16680
            virBufferAsprintf(buf, "<read_bytes_sec>%llu</read_bytes_sec>\n",
L
Lei Li 已提交
16681 16682 16683 16684 16685
                              def->blkdeviotune.read_bytes_sec);

        }

        if (def->blkdeviotune.write_bytes_sec) {
16686
            virBufferAsprintf(buf, "<write_bytes_sec>%llu</write_bytes_sec>\n",
L
Lei Li 已提交
16687 16688 16689 16690
                              def->blkdeviotune.write_bytes_sec);
        }

        if (def->blkdeviotune.total_iops_sec) {
16691
            virBufferAsprintf(buf, "<total_iops_sec>%llu</total_iops_sec>\n",
L
Lei Li 已提交
16692 16693 16694 16695
                              def->blkdeviotune.total_iops_sec);
        }

        if (def->blkdeviotune.read_iops_sec) {
16696
            virBufferAsprintf(buf, "<read_iops_sec>%llu</read_iops_sec>\n",
L
Lei Li 已提交
16697 16698 16699 16700
                              def->blkdeviotune.read_iops_sec);
        }

        if (def->blkdeviotune.write_iops_sec) {
16701
            virBufferAsprintf(buf, "<write_iops_sec>%llu</write_iops_sec>\n",
L
Lei Li 已提交
16702 16703
                              def->blkdeviotune.write_iops_sec);
        }
16704 16705 16706 16707 16708 16709 16710 16711 16712 16713 16714 16715 16716 16717 16718 16719 16720 16721 16722 16723 16724 16725 16726 16727 16728 16729 16730 16731 16732 16733 16734 16735 16736 16737 16738 16739

        if (def->blkdeviotune.total_bytes_sec_max) {
            virBufferAsprintf(buf, "<total_bytes_sec_max>%llu</total_bytes_sec_max>\n",
                              def->blkdeviotune.total_bytes_sec_max);
        }

        if (def->blkdeviotune.read_bytes_sec_max) {
            virBufferAsprintf(buf, "<read_bytes_sec_max>%llu</read_bytes_sec_max>\n",
                              def->blkdeviotune.read_bytes_sec_max);
        }

        if (def->blkdeviotune.write_bytes_sec_max) {
            virBufferAsprintf(buf, "<write_bytes_sec_max>%llu</write_bytes_sec_max>\n",
                              def->blkdeviotune.write_bytes_sec_max);
        }

        if (def->blkdeviotune.total_iops_sec_max) {
            virBufferAsprintf(buf, "<total_iops_sec_max>%llu</total_iops_sec_max>\n",
                              def->blkdeviotune.total_iops_sec_max);
        }

        if (def->blkdeviotune.read_iops_sec_max) {
            virBufferAsprintf(buf, "<read_iops_sec_max>%llu</read_iops_sec_max>\n",
                              def->blkdeviotune.read_iops_sec_max);
        }

        if (def->blkdeviotune.write_iops_sec_max) {
            virBufferAsprintf(buf, "<write_iops_sec_max>%llu</write_iops_sec_max>\n",
                              def->blkdeviotune.write_iops_sec_max);
        }

        if (def->blkdeviotune.size_iops_sec) {
            virBufferAsprintf(buf, "<size_iops_sec>%llu</size_iops_sec>\n",
                              def->blkdeviotune.size_iops_sec);
        }

16740 16741
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</iotune>\n");
L
Lei Li 已提交
16742 16743
    }

16744
    if (def->src->readonly)
16745
        virBufferAddLit(buf, "<readonly/>\n");
16746
    if (def->src->shared)
16747
        virBufferAddLit(buf, "<shareable/>\n");
16748
    if (def->transient)
16749 16750 16751 16752 16753
        virBufferAddLit(buf, "<transient/>\n");
    virBufferEscapeString(buf, "<serial>%s</serial>\n", def->serial);
    virBufferEscapeString(buf, "<wwn>%s</wwn>\n", def->wwn);
    virBufferEscapeString(buf, "<vendor>%s</vendor>\n", def->vendor);
    virBufferEscapeString(buf, "<product>%s</product>\n", def->product);
16754 16755
    if (def->src->encryption &&
        virStorageEncryptionFormat(buf, def->src->encryption) < 0)
16756
        return -1;
16757 16758
    if (virDomainDeviceInfoFormat(buf, &def->info,
                                  flags | VIR_DOMAIN_XML_INTERNAL_ALLOW_BOOT) < 0)
16759
        return -1;
16760

16761 16762
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</disk>\n");
16763 16764 16765
    return 0;
}

16766 16767 16768 16769 16770 16771
static const char *
virDomainControllerModelTypeToString(virDomainControllerDefPtr def,
                                     int model)
{
    if (def->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI)
        return virDomainControllerModelSCSITypeToString(model);
16772 16773
    else if (def->type == VIR_DOMAIN_CONTROLLER_TYPE_USB)
        return virDomainControllerModelUSBTypeToString(model);
J
Ján Tomko 已提交
16774 16775
    else if (def->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI)
        return virDomainControllerModelPCITypeToString(model);
16776 16777 16778 16779

    return NULL;
}

16780
static int
16781
virDomainControllerDefFormat(virBufferPtr buf,
D
Daniel P. Berrange 已提交
16782
                             virDomainControllerDefPtr def,
E
Eric Blake 已提交
16783
                             unsigned int flags)
16784 16785
{
    const char *type = virDomainControllerTypeToString(def->type);
16786
    const char *model = NULL;
16787
    bool pcihole64 = false;
16788 16789

    if (!type) {
16790 16791
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected controller type %d"), def->type);
16792 16793 16794
        return -1;
    }

16795
    if (def->model != -1) {
16796
        model = virDomainControllerModelTypeToString(def, def->model);
16797 16798

        if (!model) {
16799 16800
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected model type %d"), def->model);
16801 16802 16803 16804
            return -1;
        }
    }

16805
    virBufferAsprintf(buf,
16806
                      "<controller type='%s' index='%u'",
16807 16808
                      type, def->idx);

16809
    if (model)
16810 16811
        virBufferEscapeString(buf, " model='%s'", model);

16812 16813 16814
    switch (def->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL:
        if (def->opts.vioserial.ports != -1) {
16815
            virBufferAsprintf(buf, " ports='%d'",
16816 16817 16818
                              def->opts.vioserial.ports);
        }
        if (def->opts.vioserial.vectors != -1) {
16819
            virBufferAsprintf(buf, " vectors='%d'",
16820 16821 16822 16823
                              def->opts.vioserial.vectors);
        }
        break;

16824 16825 16826 16827 16828
    case VIR_DOMAIN_CONTROLLER_TYPE_PCI:
        if (def->opts.pciopts.pcihole64)
            pcihole64 = true;
        break;

16829 16830 16831 16832
    default:
        break;
    }

16833 16834
    if (def->queues || def->cmd_per_lun || def->max_sectors ||
        virDomainDeviceInfoIsSet(&def->info, flags) || pcihole64) {
16835
        virBufferAddLit(buf, ">\n");
16836
        virBufferAdjustIndent(buf, 2);
16837
        if (def->queues)
16838
            virBufferAsprintf(buf, "<driver queues='%u'/>\n", def->queues);
16839

16840 16841 16842 16843 16844 16845
        if (def->cmd_per_lun)
            virBufferAsprintf(buf, "<driver cmd_per_lun='%u'/>\n", def->cmd_per_lun);

        if (def->max_sectors)
            virBufferAsprintf(buf, "<driver max_sectors='%u'/>\n", def->max_sectors);

16846 16847
        if (virDomainDeviceInfoIsSet(&def->info, flags) &&
            virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
16848
            return -1;
16849

16850
        if (pcihole64) {
16851
            virBufferAsprintf(buf, "<pcihole64 unit='KiB'>%lu</"
16852 16853 16854
                              "pcihole64>\n", def->opts.pciopts.pcihole64size);
        }

16855 16856
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</controller>\n");
16857 16858 16859 16860 16861 16862 16863
    } else {
        virBufferAddLit(buf, "/>\n");
    }

    return 0;
}

16864 16865 16866 16867 16868

int
virDomainFSIndexByName(virDomainDefPtr def, const char *name)
{
    virDomainFSDefPtr fs;
16869
    size_t i;
16870 16871 16872 16873 16874 16875 16876 16877 16878 16879

    for (i = 0; i < def->nfss; i++) {
        fs = def->fss[i];
        if (STREQ(fs->dst, name))
            return i;
    }
    return -1;
}


16880
static int
16881
virDomainFSDefFormat(virBufferPtr buf,
16882
                     virDomainFSDefPtr def,
E
Eric Blake 已提交
16883
                     unsigned int flags)
16884 16885
{
    const char *type = virDomainFSTypeToString(def->type);
16886
    const char *accessmode = virDomainFSAccessModeTypeToString(def->accessmode);
16887
    const char *fsdriver = virDomainFSDriverTypeToString(def->fsdriver);
16888
    const char *wrpolicy = virDomainFSWrpolicyTypeToString(def->wrpolicy);
16889 16890

    if (!type) {
16891 16892
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected filesystem type %d"), def->type);
16893 16894 16895
        return -1;
    }

16896
   if (!accessmode) {
16897 16898
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected accessmode %d"), def->accessmode);
16899 16900 16901 16902
        return -1;
    }


16903
    virBufferAsprintf(buf,
16904
                      "<filesystem type='%s' accessmode='%s'>\n",
16905
                      type, accessmode);
16906
    virBufferAdjustIndent(buf, 2);
16907
    if (def->fsdriver) {
16908
        virBufferAsprintf(buf, "<driver type='%s'", fsdriver);
16909

16910 16911 16912 16913
        if (def->format)
            virBufferAsprintf(buf, " format='%s'",
                              virStorageFileFormatTypeToString(def->format));

16914
        /* Don't generate anything if wrpolicy is set to default */
16915
        if (def->wrpolicy)
16916 16917 16918
            virBufferAsprintf(buf, " wrpolicy='%s'", wrpolicy);

        virBufferAddLit(buf, "/>\n");
16919 16920
    }

16921 16922
    switch (def->type) {
    case VIR_DOMAIN_FS_TYPE_MOUNT:
16923
    case VIR_DOMAIN_FS_TYPE_BIND:
16924
        virBufferEscapeString(buf, "<source dir='%s'/>\n",
16925 16926
                              def->src);
        break;
16927

16928
    case VIR_DOMAIN_FS_TYPE_BLOCK:
16929
        virBufferEscapeString(buf, "<source dev='%s'/>\n",
16930 16931
                              def->src);
        break;
16932

16933
    case VIR_DOMAIN_FS_TYPE_FILE:
16934
        virBufferEscapeString(buf, "<source file='%s'/>\n",
16935 16936
                              def->src);
        break;
16937

16938
    case VIR_DOMAIN_FS_TYPE_TEMPLATE:
16939
        virBufferEscapeString(buf, "<source name='%s'/>\n",
16940 16941 16942 16943
                              def->src);
        break;

    case VIR_DOMAIN_FS_TYPE_RAM:
16944
        virBufferAsprintf(buf, "<source usage='%lld' units='KiB'/>\n",
16945 16946
                          def->usage / 1024);
        break;
16947 16948
    }

16949
    virBufferEscapeString(buf, "<target dir='%s'/>\n",
16950
                          def->dst);
16951 16952

    if (def->readonly)
16953
        virBufferAddLit(buf, "<readonly/>\n");
16954

16955 16956 16957
    if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
        return -1;

16958 16959

    if (def->space_hard_limit)
16960
        virBufferAsprintf(buf, "<space_hard_limit unit='bytes'>"
16961 16962
                          "%llu</space_hard_limit>\n", def->space_hard_limit);
    if (def->space_soft_limit) {
16963
        virBufferAsprintf(buf, "<space_soft_limit unit='bytes'>"
16964 16965
                          "%llu</space_soft_limit>\n", def->space_soft_limit);
    }
16966 16967
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</filesystem>\n");
16968 16969 16970
    return 0;
}

16971
static int
16972 16973 16974 16975
virDomainHostdevDefFormatSubsys(virBufferPtr buf,
                                virDomainHostdevDefPtr def,
                                unsigned int flags,
                                bool includeTypeInAddr)
16976
{
16977
    virDomainHostdevSubsysUSBPtr usbsrc = &def->source.subsys.u.usb;
16978
    virDomainHostdevSubsysPCIPtr pcisrc = &def->source.subsys.u.pci;
16979
    virDomainHostdevSubsysSCSIPtr scsisrc = &def->source.subsys.u.scsi;
16980
    virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
J
John Ferlan 已提交
16981
    virDomainHostdevSubsysSCSIiSCSIPtr iscsisrc = &scsisrc->u.iscsi;
16982

16983
    if (def->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
16984 16985 16986
        pcisrc->backend != VIR_DOMAIN_HOSTDEV_PCI_BACKEND_DEFAULT) {
        const char *backend =
            virDomainHostdevSubsysPCIBackendTypeToString(pcisrc->backend);
16987 16988 16989 16990

        if (!backend) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected pci hostdev driver name type %d"),
16991
                           pcisrc->backend);
16992 16993 16994 16995 16996
            return -1;
        }
        virBufferAsprintf(buf, "<driver name='%s'/>\n", backend);
    }

16997
    virBufferAddLit(buf, "<source");
J
John Ferlan 已提交
16998 16999 17000 17001 17002 17003 17004 17005 17006 17007 17008
    if (def->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
        if (def->startupPolicy) {
            const char *policy;
            policy = virDomainStartupPolicyTypeToString(def->startupPolicy);
            virBufferAsprintf(buf, " startupPolicy='%s'", policy);
        }
        if (usbsrc->autoAddress && (flags & VIR_DOMAIN_XML_MIGRATABLE))
            virBufferAddLit(buf, " autoAddress='yes'");

        if (def->missing && !(flags & VIR_DOMAIN_XML_INACTIVE))
            virBufferAddLit(buf, " missing='yes'");
17009
    }
17010

J
John Ferlan 已提交
17011 17012 17013 17014 17015 17016 17017 17018
    if (def->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
        scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
        const char *protocol =
            virDomainHostdevSubsysSCSIProtocolTypeToString(scsisrc->protocol);

        virBufferAsprintf(buf, " protocol='%s' name='%s'",
                          protocol, iscsisrc->path);
    }
17019

17020 17021
    virBufferAddLit(buf, ">\n");

17022
    virBufferAdjustIndent(buf, 2);
E
Eric Blake 已提交
17023
    switch (def->source.subsys.type) {
17024
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
17025 17026 17027 17028 17029
        if (usbsrc->vendor) {
            virBufferAsprintf(buf, "<vendor id='0x%.4x'/>\n", usbsrc->vendor);
            virBufferAsprintf(buf, "<product id='0x%.4x'/>\n", usbsrc->product);
        }
        if (usbsrc->bus || usbsrc->device) {
17030
            virBufferAsprintf(buf, "<address %sbus='%d' device='%d'/>\n",
17031
                              includeTypeInAddr ? "type='usb' " : "",
17032
                              usbsrc->bus, usbsrc->device);
17033 17034 17035
        }
        break;
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
17036
        if (virDevicePCIAddressFormat(buf, pcisrc->addr,
17037 17038 17039
                                      includeTypeInAddr) != 0)
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("PCI address Formatting failed"));
17040 17041 17042 17043 17044

        if ((flags & VIR_DOMAIN_XML_INTERNAL_PCI_ORIG_STATES) &&
            (def->origstates.states.pci.unbind_from_stub ||
             def->origstates.states.pci.remove_slot ||
             def->origstates.states.pci.reprobe)) {
17045
            virBufferAddLit(buf, "<origstates>\n");
17046
            virBufferAdjustIndent(buf, 2);
17047
            if (def->origstates.states.pci.unbind_from_stub)
17048
                virBufferAddLit(buf, "<unbind/>\n");
17049
            if (def->origstates.states.pci.remove_slot)
17050
                virBufferAddLit(buf, "<removeslot/>\n");
17051
            if (def->origstates.states.pci.reprobe)
17052 17053
                virBufferAddLit(buf, "<reprobe/>\n");
            virBufferAdjustIndent(buf, -2);
17054
            virBufferAddLit(buf, "</origstates>\n");
17055 17056
        }
        break;
H
Han Cheng 已提交
17057
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
J
John Ferlan 已提交
17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071
        if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
            virBufferAddLit(buf, "<host");
            virBufferEscapeString(buf, " name='%s'", iscsisrc->hosts[0].name);
            virBufferEscapeString(buf, " port='%s'", iscsisrc->hosts[0].port);
            virBufferAddLit(buf, "/>\n");
        } else {
            virBufferAsprintf(buf, "<adapter name='%s'/>\n",
                              scsihostsrc->adapter);
            virBufferAsprintf(buf,
                              "<address %sbus='%d' target='%d' unit='%d'/>\n",
                              includeTypeInAddr ? "type='scsi' " : "",
                              scsihostsrc->bus, scsihostsrc->target,
                              scsihostsrc->unit);
        }
H
Han Cheng 已提交
17072
        break;
17073
    default:
17074 17075 17076
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected hostdev type %d"),
                       def->source.subsys.type);
17077 17078 17079
        return -1;
    }

J
John Ferlan 已提交
17080 17081 17082 17083 17084 17085 17086
    if (def->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
        scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI &&
        iscsisrc->auth) {
        if (virStorageAuthDefFormat(buf, iscsisrc->auth) < 0)
            return -1;
    }

17087
    virBufferAdjustIndent(buf, -2);
17088
    virBufferAddLit(buf, "</source>\n");
J
John Ferlan 已提交
17089

17090 17091 17092
    return 0;
}

17093 17094 17095 17096 17097 17098 17099
static int
virDomainHostdevDefFormatCaps(virBufferPtr buf,
                              virDomainHostdevDefPtr def)
{
    virBufferAddLit(buf, "<source>\n");

    virBufferAdjustIndent(buf, 2);
E
Eric Blake 已提交
17100
    switch (def->source.caps.type) {
17101 17102 17103 17104 17105 17106 17107 17108
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_STORAGE:
        virBufferEscapeString(buf, "<block>%s</block>\n",
                              def->source.caps.u.storage.block);
        break;
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_MISC:
        virBufferEscapeString(buf, "<char>%s</char>\n",
                              def->source.caps.u.misc.chardev);
        break;
17109 17110 17111 17112
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_NET:
        virBufferEscapeString(buf, "<interface>%s</interface>\n",
                              def->source.caps.u.net.iface);
        break;
17113 17114 17115 17116 17117 17118 17119 17120 17121 17122 17123 17124
    default:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected hostdev type %d"),
                       def->source.caps.type);
        return -1;
    }

    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</source>\n");
    return 0;
}

17125 17126 17127 17128 17129
/* virDomainActualNetDefContentsFormat() - format just the subelements
 * of <interface> that may be overridden by what is in the
 * virDomainActualNetDef, but inside the current element, rather
 * than enclosed in an <actual> subelement.
 */
17130
static int
17131 17132 17133 17134
virDomainActualNetDefContentsFormat(virBufferPtr buf,
                                    virDomainNetDefPtr def,
                                    bool inSubelement,
                                    unsigned int flags)
17135
{
17136
    int actualType = virDomainNetGetActualType(def);
17137

17138
    if (actualType == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
17139
        if (virDomainHostdevDefFormatSubsys(buf, virDomainNetGetActualHostdev(def),
17140
                                            flags, true) < 0) {
17141 17142
            return -1;
        }
17143 17144 17145 17146 17147 17148 17149 17150 17151 17152 17153
    } else {
        virBufferAddLit(buf, "<source");
        if (def->type == VIR_DOMAIN_NET_TYPE_NETWORK && !inSubelement) {
            /* When we're putting our output into the <actual>
             * subelement rather than the main <interface>, the
             * network name isn't included in the <source> because the
             * main interface element's <source> has the same info
             * already. If we've been called to output directly into
             * the main element's <source> though (the case here -
             * "!inSubElement"), we *do* need to output the network
             * name, because the caller won't have done it).
17154
             */
17155
            virBufferEscapeString(buf, " network='%s'", def->data.network.name);
17156
        }
17157 17158 17159 17160 17161 17162 17163 17164 17165 17166 17167 17168 17169 17170 17171 17172 17173 17174 17175 17176 17177 17178 17179 17180 17181 17182 17183 17184 17185
        if (actualType == VIR_DOMAIN_NET_TYPE_BRIDGE ||
            actualType == VIR_DOMAIN_NET_TYPE_NETWORK) {
            /* actualType == NETWORK includes the name of the bridge
             * that is used by the network, whether we are
             * "inSubElement" or not.
             */
            virBufferEscapeString(buf, " bridge='%s'",
                                  virDomainNetGetActualBridgeName(def));
        } else if (actualType == VIR_DOMAIN_NET_TYPE_DIRECT) {
            const char *mode;

            virBufferEscapeString(buf, " dev='%s'",
                                  virDomainNetGetActualDirectDev(def));
            mode = virNetDevMacVLanModeTypeToString(virDomainNetGetActualDirectMode(def));
            if (!mode) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected source mode %d"),
                               virDomainNetGetActualDirectMode(def));
                return -1;
            }
            virBufferAsprintf(buf, " mode='%s'", mode);
        }

        virBufferAddLit(buf, "/>\n");
    }
    if (actualType == VIR_DOMAIN_NET_TYPE_DIRECT &&
        def->data.network.actual && def->data.network.actual->class_id) {
        virBufferAsprintf(buf, "<class id='%u'/>\n",
                          def->data.network.actual->class_id);
17186
    }
17187

17188
    if (virNetDevVlanFormat(virDomainNetGetActualVlan(def), buf) < 0)
17189
        return -1;
17190
    if (virNetDevVPortProfileFormat(virDomainNetGetActualVirtPortProfile(def), buf) < 0)
17191
        return -1;
17192
    if (virNetDevBandwidthFormat(virDomainNetGetActualBandwidth(def), buf) < 0)
17193
        return -1;
17194 17195 17196 17197 17198 17199 17200 17201 17202 17203 17204 17205 17206
    return 0;
}


/* virDomainActualNetDefFormat() - format the ActualNetDef
 * info inside an <actual> element, as required for internal storage
 * of domain status
 */
static int
virDomainActualNetDefFormat(virBufferPtr buf,
                            virDomainNetDefPtr def,
                            unsigned int flags)
{
17207 17208
    unsigned int type;
    const char *typeStr;
17209 17210 17211

    if (!def)
        return 0;
17212 17213
    type = virDomainNetGetActualType(def);
    typeStr = virDomainNetTypeToString(type);
17214

17215 17216 17217 17218 17219 17220 17221 17222 17223 17224 17225 17226
    if (!typeStr) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected net type %d"), def->type);
        return -1;
    }

    virBufferAsprintf(buf, "<actual type='%s'", typeStr);
    if (type == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
        virDomainHostdevDefPtr hostdef = virDomainNetGetActualHostdev(def);
        if  (hostdef && hostdef->managed)
            virBufferAddLit(buf, " managed='yes'");
    }
17227 17228 17229
    if (def->trustGuestRxFilters)
        virBufferAsprintf(buf, " trustGuestRxFilters='%s'",
                          virTristateBoolTypeToString(def->trustGuestRxFilters));
17230 17231 17232
    virBufferAddLit(buf, ">\n");

    virBufferAdjustIndent(buf, 2);
17233
    if (virDomainActualNetDefContentsFormat(buf, def, true, flags) < 0)
17234
       return -1;
17235 17236
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</actual>\n");
17237
    return 0;
17238 17239
}

17240

17241 17242 17243 17244 17245 17246 17247 17248 17249 17250 17251 17252 17253 17254 17255 17256 17257 17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276 17277 17278 17279 17280 17281 17282 17283 17284 17285 17286 17287 17288 17289 17290 17291 17292 17293 17294 17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312 17313 17314
static int
virDomainVirtioNetGuestOptsFormat(char **outstr,
                                  virDomainNetDefPtr def)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    if (def->driver.virtio.guest.csum) {
        virBufferAsprintf(&buf, "csum='%s' ",
                          virTristateSwitchTypeToString(def->driver.virtio.guest.csum));
    }
    if (def->driver.virtio.guest.tso4) {
        virBufferAsprintf(&buf, "tso4='%s' ",
                          virTristateSwitchTypeToString(def->driver.virtio.guest.tso4));
    }
    if (def->driver.virtio.guest.tso6) {
        virBufferAsprintf(&buf, "tso6='%s' ",
                          virTristateSwitchTypeToString(def->driver.virtio.guest.tso6));
    }
    if (def->driver.virtio.guest.ecn) {
        virBufferAsprintf(&buf, "ecn='%s' ",
                          virTristateSwitchTypeToString(def->driver.virtio.guest.ecn));
    }
    if (def->driver.virtio.guest.ufo) {
        virBufferAsprintf(&buf, "ufo='%s' ",
                          virTristateSwitchTypeToString(def->driver.virtio.guest.ufo));
    }
    virBufferTrim(&buf, " ", -1);

    if (virBufferCheckError(&buf) < 0)
        return -1;

    *outstr = virBufferContentAndReset(&buf);
    return 0;
}


static int
virDomainVirtioNetHostOptsFormat(char **outstr,
                                 virDomainNetDefPtr def)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    if (def->driver.virtio.host.csum) {
        virBufferAsprintf(&buf, "csum='%s' ",
                          virTristateSwitchTypeToString(def->driver.virtio.host.csum));
    }
    if (def->driver.virtio.host.gso) {
        virBufferAsprintf(&buf, "gso='%s' ",
                          virTristateSwitchTypeToString(def->driver.virtio.host.gso));
    }
    if (def->driver.virtio.host.tso4) {
        virBufferAsprintf(&buf, "tso4='%s' ",
                          virTristateSwitchTypeToString(def->driver.virtio.host.tso4));
    }
    if (def->driver.virtio.host.tso6) {
        virBufferAsprintf(&buf, "tso6='%s' ",
                          virTristateSwitchTypeToString(def->driver.virtio.host.tso6));
    }
    if (def->driver.virtio.host.ecn) {
        virBufferAsprintf(&buf, "ecn='%s' ",
                          virTristateSwitchTypeToString(def->driver.virtio.host.ecn));
    }
    if (def->driver.virtio.host.ufo) {
        virBufferAsprintf(&buf, "ufo='%s' ",
                          virTristateSwitchTypeToString(def->driver.virtio.host.ufo));
    }
    virBufferTrim(&buf, " ", -1);

    if (virBufferCheckError(&buf) < 0)
        return -1;

    *outstr = virBufferContentAndReset(&buf);
    return 0;
}


17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330 17331 17332 17333 17334 17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348
static int
virDomainVirtioNetDriverFormat(char **outstr,
                               virDomainNetDefPtr def)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    if (def->driver.virtio.name) {
        virBufferAsprintf(&buf, "name='%s' ",
                          virDomainNetBackendTypeToString(def->driver.virtio.name));
    }
    if (def->driver.virtio.txmode) {
        virBufferAsprintf(&buf, "txmode='%s' ",
                          virDomainNetVirtioTxModeTypeToString(def->driver.virtio.txmode));
    }
    if (def->driver.virtio.ioeventfd) {
        virBufferAsprintf(&buf, "ioeventfd='%s' ",
                          virTristateSwitchTypeToString(def->driver.virtio.ioeventfd));
    }
    if (def->driver.virtio.event_idx) {
        virBufferAsprintf(&buf, "event_idx='%s' ",
                          virTristateSwitchTypeToString(def->driver.virtio.event_idx));
    }
    if (def->driver.virtio.queues)
        virBufferAsprintf(&buf, "queues='%u' ", def->driver.virtio.queues);

    virBufferTrim(&buf, " ", -1);

    if (virBufferCheckError(&buf) < 0)
        return -1;

    *outstr = virBufferContentAndReset(&buf);
    return 0;
}


17349
int
17350
virDomainNetDefFormat(virBufferPtr buf,
17351
                      virDomainNetDefPtr def,
E
Eric Blake 已提交
17352
                      unsigned int flags)
17353
{
17354 17355 17356 17357 17358 17359 17360 17361 17362 17363
    /* publicActual is true if we should report the current state in
     * def->data.network.actual *instead of* the config (*not* in
     * addition to)
     */
    unsigned int actualType = virDomainNetGetActualType(def);
    bool publicActual
       = (def->type == VIR_DOMAIN_NET_TYPE_NETWORK && def->data.network.actual &&
          !(flags & (VIR_DOMAIN_XML_INACTIVE | VIR_DOMAIN_XML_INTERNAL_ACTUAL_NET)));
    const char *typeStr;
    virDomainHostdevDefPtr hostdef = NULL;
17364
    char macstr[VIR_MAC_STRING_BUFLEN];
17365

17366 17367 17368 17369 17370 17371 17372 17373 17374 17375 17376 17377 17378 17379 17380 17381
    if (publicActual) {
        if (!(typeStr = virDomainNetTypeToString(actualType))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected actual net type %d"), actualType);
            return -1;
        }
        if (actualType == VIR_DOMAIN_NET_TYPE_HOSTDEV)
            hostdef = virDomainNetGetActualHostdev(def);
    } else {
        if (!(typeStr = virDomainNetTypeToString(def->type))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected net type %d"), def->type);
            return -1;
        }
        if (def->type == VIR_DOMAIN_NET_TYPE_HOSTDEV)
            hostdef = &def->data.hostdev.def;
17382 17383
    }

17384
    virBufferAsprintf(buf, "<interface type='%s'", typeStr);
17385
    if (hostdef && hostdef->managed)
17386
        virBufferAddLit(buf, " managed='yes'");
17387 17388 17389
    if (def->trustGuestRxFilters)
        virBufferAsprintf(buf, " trustGuestRxFilters='%s'",
                          virTristateBoolTypeToString(def->trustGuestRxFilters));
17390
    virBufferAddLit(buf, ">\n");
17391

17392
    virBufferAdjustIndent(buf, 2);
17393 17394
    virBufferAsprintf(buf, "<mac address='%s'/>\n",
                      virMacAddrFormat(&def->mac, macstr));
17395

17396 17397 17398 17399 17400 17401 17402
    if (publicActual) {
        /* when there is a virDomainActualNetDef, and we haven't been
         * asked to 1) report the domain's inactive XML, or 2) give
         * the internal version of the ActualNetDef separately in an
         * <actual> subelement, we can just put the ActualDef data in
         * the standard place...  (this is for public reporting of
         * interface status)
17403
         */
17404
        if (virDomainActualNetDefContentsFormat(buf, def, false, flags) < 0)
17405
            return -1;
17406 17407 17408 17409 17410 17411 17412 17413 17414 17415 17416 17417 17418 17419 17420
    } else {
        /* ...but if we've asked for the inactive XML (rather than
         * status), or to report the ActualDef as a separate <actual>
         * subelement (this is how we privately store interface
         * status), or there simply *isn't* any ActualNetDef, then
         * format the NetDef's data here, and optionally format the
         * ActualNetDef as an <actual> subelement of this element.
         */
        switch (def->type) {
        case VIR_DOMAIN_NET_TYPE_NETWORK:
            virBufferEscapeString(buf, "<source network='%s'",
                                  def->data.network.name);
            virBufferEscapeString(buf, " portgroup='%s'",
                                  def->data.network.portgroup);
            virBufferAddLit(buf, "/>\n");
17421

17422 17423 17424 17425 17426 17427 17428 17429
            /* ONLY for internal status storage - format the ActualNetDef
             * as a subelement of <interface> so that no persistent config
             * data is overwritten.
             */
            if ((flags & VIR_DOMAIN_XML_INTERNAL_ACTUAL_NET) &&
                (virDomainActualNetDefFormat(buf, def, flags) < 0))
                return -1;
            break;
17430

17431 17432 17433 17434 17435 17436 17437
        case VIR_DOMAIN_NET_TYPE_ETHERNET:
            virBufferEscapeString(buf, "<source dev='%s'/>\n",
                                  def->data.ethernet.dev);
            if (def->data.ethernet.ipaddr)
                virBufferAsprintf(buf, "<ip address='%s'/>\n",
                                  def->data.ethernet.ipaddr);
            break;
17438

M
Michele Paolino 已提交
17439 17440 17441 17442 17443
        case VIR_DOMAIN_NET_TYPE_VHOSTUSER:
            if (def->data.vhostuser->type == VIR_DOMAIN_CHR_TYPE_UNIX) {
                virBufferAddLit(buf, "<source type='unix'");
                virBufferEscapeString(buf, " path='%s'",
                                      def->data.vhostuser->data.nix.path);
17444 17445 17446
                virBufferAsprintf(buf, " mode='%s'",
                                  def->data.vhostuser->data.nix.listen ?
                                  "server"  : "client");
M
Michele Paolino 已提交
17447 17448 17449 17450
                virBufferAddLit(buf, "/>\n");
            }
            break;

17451 17452 17453 17454 17455 17456 17457 17458
        case VIR_DOMAIN_NET_TYPE_BRIDGE:
            virBufferEscapeString(buf, "<source bridge='%s'/>\n",
                                  def->data.bridge.brname);
            if (def->data.bridge.ipaddr) {
                virBufferAsprintf(buf, "<ip address='%s'/>\n",
                                  def->data.bridge.ipaddr);
            }
            break;
D
Daniel Veillard 已提交
17459

17460 17461 17462 17463 17464 17465 17466 17467 17468 17469 17470
        case VIR_DOMAIN_NET_TYPE_SERVER:
        case VIR_DOMAIN_NET_TYPE_CLIENT:
        case VIR_DOMAIN_NET_TYPE_MCAST:
            if (def->data.socket.address) {
                virBufferAsprintf(buf, "<source address='%s' port='%d'/>\n",
                                  def->data.socket.address, def->data.socket.port);
            } else {
                virBufferAsprintf(buf, "<source port='%d'/>\n",
                                  def->data.socket.port);
            }
            break;
D
Daniel Veillard 已提交
17471

17472 17473 17474 17475
        case VIR_DOMAIN_NET_TYPE_INTERNAL:
            virBufferEscapeString(buf, "<source name='%s'/>\n",
                                  def->data.internal.name);
            break;
S
Stefan Berger 已提交
17476

17477 17478 17479 17480 17481 17482 17483 17484 17485 17486 17487 17488 17489 17490 17491 17492 17493 17494
        case VIR_DOMAIN_NET_TYPE_DIRECT:
            virBufferEscapeString(buf, "<source dev='%s'",
                                  def->data.direct.linkdev);
            virBufferAsprintf(buf, " mode='%s'",
                              virNetDevMacVLanModeTypeToString(def->data.direct.mode));
            virBufferAddLit(buf, "/>\n");
            break;

        case VIR_DOMAIN_NET_TYPE_HOSTDEV:
            if (virDomainHostdevDefFormatSubsys(buf, &def->data.hostdev.def,
                                                flags, true) < 0) {
                return -1;
            }
            break;

        case VIR_DOMAIN_NET_TYPE_USER:
        case VIR_DOMAIN_NET_TYPE_LAST:
            break;
17495 17496
        }

17497 17498 17499 17500 17501 17502
        if (virNetDevVlanFormat(&def->vlan, buf) < 0)
            return -1;
        if (virNetDevVPortProfileFormat(def->virtPortProfile, buf) < 0)
            return -1;
        if (virNetDevBandwidthFormat(def->bandwidth, buf) < 0)
            return -1;
17503 17504
    }

17505
    virBufferEscapeString(buf, "<script path='%s'/>\n",
17506
                          def->script);
17507 17508 17509 17510
    if (def->ifname &&
        !((flags & VIR_DOMAIN_XML_INACTIVE) &&
          (STRPREFIX(def->ifname, VIR_NET_GENERATED_PREFIX)))) {
        /* Skip auto-generated target names for inactive config. */
17511
        virBufferEscapeString(buf, "<target dev='%s'/>\n", def->ifname);
17512
    }
17513 17514 17515 17516 17517 17518 17519 17520 17521 17522 17523
    if (def->ifname_guest || def->ifname_guest_actual) {
        virBufferAddLit(buf, "<guest");
        /* Skip auto-generated target names for inactive config. */
        if (def->ifname_guest)
            virBufferEscapeString(buf, " dev='%s'", def->ifname_guest);

        /* Only set if the host is running, so shouldn't pollute output */
        if (def->ifname_guest_actual)
            virBufferEscapeString(buf, " actual='%s'", def->ifname_guest_actual);
        virBufferAddLit(buf, "/>\n");
    }
17524
    if (def->model) {
17525
        virBufferEscapeString(buf, "<model type='%s'/>\n",
17526
                              def->model);
17527
        if (STREQ(def->model, "virtio")) {
17528 17529
            char *str = NULL, *gueststr = NULL, *hoststr = NULL;
            int rc = 0;
17530

17531 17532 17533 17534
            if (virDomainVirtioNetDriverFormat(&str, def) < 0 ||
                virDomainVirtioNetGuestOptsFormat(&gueststr, def) < 0 ||
                virDomainVirtioNetHostOptsFormat(&hoststr, def) < 0)
                rc = -1;
17535

17536 17537 17538 17539 17540 17541 17542 17543 17544 17545 17546 17547 17548 17549 17550 17551
            if (!gueststr && !hoststr) {
                if (str)
                    virBufferAsprintf(buf, "<driver %s/>\n", str);
            } else {
                if (str)
                    virBufferAsprintf(buf, "<driver %s>\n", str);
                else
                    virBufferAddLit(buf, "<driver>\n");
                virBufferAdjustIndent(buf, 2);
                if (hoststr)
                    virBufferAsprintf(buf, "<host %s/>\n", hoststr);
                if (gueststr)
                    virBufferAsprintf(buf, "<guest %s/>\n", gueststr);
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</driver>\n");
            }
17552
            VIR_FREE(str);
17553 17554 17555 17556 17557
            VIR_FREE(hoststr);
            VIR_FREE(gueststr);

            if (rc < 0)
                return -1;
17558 17559
        }
    }
17560 17561 17562 17563 17564 17565
    if (def->backend.tap || def->backend.vhost) {
        virBufferAddLit(buf, "<backend");
        virBufferEscapeString(buf, " tap='%s'", def->backend.tap);
        virBufferEscapeString(buf, " vhost='%s'", def->backend.vhost);
        virBufferAddLit(buf, "/>\n");
    }
17566
    if (def->filter) {
17567 17568 17569
        if (virNWFilterFormatParamAttributes(buf, def->filterparams,
                                             def->filter) < 0)
            return -1;
17570
    }
17571

17572
    if (def->tune.sndbuf_specified) {
17573
        virBufferAddLit(buf,   "<tune>\n");
17574 17575 17576
        virBufferAdjustIndent(buf, 2);
        virBufferAsprintf(buf, "<sndbuf>%lu</sndbuf>\n", def->tune.sndbuf);
        virBufferAdjustIndent(buf, -2);
17577
        virBufferAddLit(buf,   "</tune>\n");
17578 17579
    }

17580 17581
    if (def->linkstate) {
        virBufferAsprintf(buf, "<link state='%s'/>\n",
17582
                          virDomainNetInterfaceLinkStateTypeToString(def->linkstate));
17583
    }
17584
    if (virDomainDeviceInfoFormat(buf, &def->info,
17585 17586
                                  flags | VIR_DOMAIN_XML_INTERNAL_ALLOW_BOOT
                                  | VIR_DOMAIN_XML_INTERNAL_ALLOW_ROM) < 0)
17587 17588
        return -1;

17589 17590
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</interface>\n");
17591 17592 17593 17594
    return 0;
}


17595 17596
/* Assumes that "<device" has already been generated, and starts
 * output at " type='type'>". */
17597
static int
17598
virDomainChrSourceDefFormat(virBufferPtr buf,
J
Ján Tomko 已提交
17599
                            virDomainChrDefPtr chr_def,
17600 17601
                            virDomainChrSourceDefPtr def,
                            bool tty_compat,
E
Eric Blake 已提交
17602
                            unsigned int flags)
17603 17604
{
    const char *type = virDomainChrTypeToString(def->type);
J
Ján Tomko 已提交
17605 17606 17607 17608 17609 17610 17611
    size_t nseclabels = 0;
    virSecurityDeviceLabelDefPtr *seclabels = NULL;

    if (chr_def) {
        nseclabels = chr_def->nseclabels;
        seclabels = chr_def->seclabels;
    }
17612

17613
    if (!type) {
17614 17615
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected char type %d"), def->type);
17616
        return -1;
17617 17618
    }

17619
    /* Compat with legacy <console tty='/dev/pts/5'/> syntax */
17620
    virBufferAsprintf(buf, " type='%s'", type);
17621
    if (tty_compat) {
C
Cole Robinson 已提交
17622
        virBufferEscapeString(buf, " tty='%s'",
17623 17624
                              def->data.file.path);
    }
C
Cole Robinson 已提交
17625
    virBufferAddLit(buf, ">\n");
17626

17627
    switch ((virDomainChrType)def->type) {
17628 17629 17630
    case VIR_DOMAIN_CHR_TYPE_NULL:
    case VIR_DOMAIN_CHR_TYPE_VC:
    case VIR_DOMAIN_CHR_TYPE_STDIO:
17631
    case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
17632
    case VIR_DOMAIN_CHR_TYPE_LAST:
17633 17634 17635 17636 17637 17638 17639 17640
        /* nada */
        break;

    case VIR_DOMAIN_CHR_TYPE_PTY:
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_FILE:
    case VIR_DOMAIN_CHR_TYPE_PIPE:
        if (def->type != VIR_DOMAIN_CHR_TYPE_PTY ||
17641 17642
            (def->data.file.path &&
             !(flags & VIR_DOMAIN_XML_INACTIVE))) {
J
Ján Tomko 已提交
17643
            virBufferEscapeString(buf, "<source path='%s'",
17644
                                  def->data.file.path);
J
Ján Tomko 已提交
17645
            virDomainSourceDefFormatSeclabel(buf, nseclabels, seclabels, flags);
17646 17647 17648
        }
        break;

17649 17650 17651 17652 17653 17654
    case VIR_DOMAIN_CHR_TYPE_NMDM:
        virBufferAsprintf(buf, "<source master='%s' slave='%s'/>\n",
                          def->data.nmdm.master,
                          def->data.nmdm.slave);
        break;

17655 17656 17657
    case VIR_DOMAIN_CHR_TYPE_UDP:
        if (def->data.udp.bindService &&
            def->data.udp.bindHost) {
17658
            virBufferAsprintf(buf,
17659
                              "<source mode='bind' host='%s' "
17660
                              "service='%s'/>\n",
17661 17662 17663
                              def->data.udp.bindHost,
                              def->data.udp.bindService);
        } else if (def->data.udp.bindHost) {
17664
            virBufferAsprintf(buf, "<source mode='bind' host='%s'/>\n",
17665 17666
                              def->data.udp.bindHost);
        } else if (def->data.udp.bindService) {
17667
            virBufferAsprintf(buf, "<source mode='bind' service='%s'/>\n",
17668 17669 17670 17671 17672
                              def->data.udp.bindService);
        }

        if (def->data.udp.connectService &&
            def->data.udp.connectHost) {
17673
            virBufferAsprintf(buf,
17674
                              "<source mode='connect' host='%s' "
17675
                              "service='%s'/>\n",
17676 17677 17678
                              def->data.udp.connectHost,
                              def->data.udp.connectService);
        } else if (def->data.udp.connectHost) {
17679
            virBufferAsprintf(buf, "<source mode='connect' host='%s'/>\n",
17680 17681
                              def->data.udp.connectHost);
        } else if (def->data.udp.connectService) {
17682
            virBufferAsprintf(buf,
17683
                              "<source mode='connect' service='%s'/>\n",
17684 17685 17686 17687 17688
                              def->data.udp.connectService);
        }
        break;

    case VIR_DOMAIN_CHR_TYPE_TCP:
17689
        virBufferAsprintf(buf,
17690
                          "<source mode='%s' host='%s' service='%s'/>\n",
17691 17692 17693
                          def->data.tcp.listen ? "bind" : "connect",
                          def->data.tcp.host,
                          def->data.tcp.service);
17694
        virBufferAsprintf(buf, "<protocol type='%s'/>\n",
17695 17696
                          virDomainChrTcpProtocolTypeToString(
                              def->data.tcp.protocol));
17697 17698 17699
        break;

    case VIR_DOMAIN_CHR_TYPE_UNIX:
17700
        virBufferAsprintf(buf, "<source mode='%s'",
17701
                          def->data.nix.listen ? "bind" : "connect");
17702
        virBufferEscapeString(buf, " path='%s'", def->data.nix.path);
J
Ján Tomko 已提交
17703
        virDomainSourceDefFormatSeclabel(buf, nseclabels, seclabels, flags);
17704
        break;
17705 17706

    case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
17707
        virBufferAsprintf(buf, "<source channel='%s'/>\n",
17708 17709 17710
                          def->data.spiceport.channel);
        break;

17711 17712
    }

17713 17714 17715 17716 17717 17718
    return 0;
}

static int
virDomainChrDefFormat(virBufferPtr buf,
                      virDomainChrDefPtr def,
E
Eric Blake 已提交
17719
                      unsigned int flags)
17720 17721 17722 17723 17724 17725 17726 17727 17728
{
    const char *elementName = virDomainChrDeviceTypeToString(def->deviceType);
    const char *targetType = virDomainChrTargetTypeToString(def->deviceType,
                                                            def->targetType);
    bool tty_compat;

    int ret = 0;

    if (!elementName) {
17729 17730 17731
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected char device type %d"),
                       def->deviceType);
17732 17733 17734
        return -1;
    }

17735 17736
    virBufferAsprintf(buf, "<%s", elementName);
    virBufferAdjustIndent(buf, 2);
17737 17738 17739 17740 17741
    tty_compat = (def->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE &&
                  def->target.port == 0 &&
                  def->source.type == VIR_DOMAIN_CHR_TYPE_PTY &&
                  !(flags & VIR_DOMAIN_XML_INACTIVE) &&
                  def->source.data.file.path);
J
Ján Tomko 已提交
17742
    if (virDomainChrSourceDefFormat(buf, def, &def->source, tty_compat, flags) < 0)
17743 17744
        return -1;

17745
    /* Format <target> block */
17746
    switch (def->deviceType) {
17747 17748
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL: {
        if (!targetType) {
17749 17750
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not format channel target type"));
17751 17752
            return -1;
        }
17753
        virBufferAsprintf(buf, "<target type='%s'", targetType);
17754 17755 17756

        switch (def->targetType) {
        case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_GUESTFWD: {
17757
            int port = virSocketAddrGetPort(def->target.addr);
17758
            if (port < 0) {
17759 17760
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to format guestfwd port"));
17761 17762
                return -1;
            }
17763

17764
            char *addr = virSocketAddrFormat(def->target.addr);
17765
            if (addr == NULL)
17766
                return -1;
17767

17768
            virBufferAsprintf(buf, " address='%s' port='%d'",
17769 17770 17771
                              addr, port);
            VIR_FREE(addr);
            break;
17772 17773
        }

17774
        case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO:
17775
            if (def->target.name)
17776
                virBufferEscapeString(buf, " name='%s'", def->target.name);
17777 17778 17779 17780 17781 17782

            if (def->state != VIR_DOMAIN_CHR_DEVICE_STATE_DEFAULT &&
                !(flags & VIR_DOMAIN_XML_INACTIVE)) {
                virBufferAsprintf(buf, " state='%s'",
                                  virDomainChrDeviceStateTypeToString(def->state));
            }
17783 17784 17785
            break;
        }

17786 17787
        virBufferAddLit(buf, "/>\n");
        break;
17788
    }
17789

17790
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
17791
        virBufferAsprintf(buf,
17792
                          "<target type='%s' port='%d'/>\n",
17793 17794 17795 17796 17797
                          virDomainChrTargetTypeToString(def->deviceType,
                                                         def->targetType),
                          def->target.port);
        break;

G
Guannan Ren 已提交
17798 17799 17800
    case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
        if (def->targetTypeAttr) {
            virBufferAsprintf(buf,
17801
                              "<target type='%s' port='%d'/>\n",
G
Guannan Ren 已提交
17802 17803 17804 17805 17806
                              virDomainChrTargetTypeToString(def->deviceType,
                                                             def->targetType),
                              def->target.port);
            break;
        }
17807
    default:
17808
        virBufferAsprintf(buf, "<target port='%d'/>\n",
17809
                          def->target.port);
17810
        break;
17811
    }
17812

17813
    if (virDomainDeviceInfoIsSet(&def->info, flags)) {
17814 17815 17816
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
            return -1;
    }
17817

17818 17819
    virBufferAdjustIndent(buf, -2);
    virBufferAsprintf(buf, "</%s>\n", elementName);
17820

17821
    return ret;
17822 17823
}

E
Eric Blake 已提交
17824 17825 17826
static int
virDomainSmartcardDefFormat(virBufferPtr buf,
                            virDomainSmartcardDefPtr def,
E
Eric Blake 已提交
17827
                            unsigned int flags)
E
Eric Blake 已提交
17828 17829 17830 17831 17832
{
    const char *mode = virDomainSmartcardTypeToString(def->type);
    size_t i;

    if (!mode) {
17833 17834
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected smartcard type %d"), def->type);
E
Eric Blake 已提交
17835 17836 17837
        return -1;
    }

17838 17839
    virBufferAsprintf(buf, "<smartcard mode='%s'", mode);
    virBufferAdjustIndent(buf, 2);
E
Eric Blake 已提交
17840 17841
    switch (def->type) {
    case VIR_DOMAIN_SMARTCARD_TYPE_HOST:
17842
        if (!virDomainDeviceInfoIsSet(&def->info, flags)) {
17843
            virBufferAdjustIndent(buf, -2);
E
Eric Blake 已提交
17844 17845 17846
            virBufferAddLit(buf, "/>\n");
            return 0;
        }
17847
        virBufferAddLit(buf, ">\n");
E
Eric Blake 已提交
17848 17849 17850 17851 17852
        break;

    case VIR_DOMAIN_SMARTCARD_TYPE_HOST_CERTIFICATES:
        virBufferAddLit(buf, ">\n");
        for (i = 0; i < VIR_DOMAIN_SMARTCARD_NUM_CERTIFICATES; i++)
17853
            virBufferEscapeString(buf, "<certificate>%s</certificate>\n",
E
Eric Blake 已提交
17854
                                  def->data.cert.file[i]);
17855
        virBufferEscapeString(buf, "<database>%s</database>\n",
17856
                              def->data.cert.database);
E
Eric Blake 已提交
17857 17858 17859
        break;

    case VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH:
J
Ján Tomko 已提交
17860
        if (virDomainChrSourceDefFormat(buf, NULL, &def->data.passthru, false,
E
Eric Blake 已提交
17861 17862 17863 17864 17865
                                        flags) < 0)
            return -1;
        break;

    default:
17866 17867
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected smartcard type %d"), def->type);
E
Eric Blake 已提交
17868 17869 17870 17871
        return -1;
    }
    if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
        return -1;
17872 17873
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</smartcard>\n");
E
Eric Blake 已提交
17874 17875 17876
    return 0;
}

17877 17878 17879 17880 17881 17882 17883
static int
virDomainSoundCodecDefFormat(virBufferPtr buf,
                             virDomainSoundCodecDefPtr def)
{
    const char *type = virDomainSoundCodecTypeToString(def->type);

    if (!type) {
17884 17885
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected codec type %d"), def->type);
17886 17887 17888
        return -1;
    }

17889
    virBufferAsprintf(buf, "<codec type='%s'/>\n",  type);
17890 17891 17892 17893

    return 0;
}

17894 17895 17896 17897 17898
static int
virDomainTPMDefFormat(virBufferPtr buf,
                      virDomainTPMDefPtr def,
                      unsigned int flags)
{
17899
    virBufferAsprintf(buf, "<tpm model='%s'>\n",
17900
                      virDomainTPMModelTypeToString(def->model));
17901 17902
    virBufferAdjustIndent(buf, 2);
    virBufferAsprintf(buf, "<backend type='%s'>\n",
17903
                      virDomainTPMBackendTypeToString(def->type));
17904
    virBufferAdjustIndent(buf, 2);
17905 17906 17907

    switch (def->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
17908
        virBufferEscapeString(buf, "<device path='%s'/>\n",
17909 17910 17911 17912 17913 17914
                              def->data.passthrough.source.data.file.path);
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

17915 17916
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</backend>\n");
17917 17918 17919 17920 17921 17922

    if (virDomainDeviceInfoIsSet(&def->info, flags)) {
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
            return -1;
    }

17923 17924
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</tpm>\n");
17925 17926 17927 17928 17929

    return 0;
}


17930
static int
17931
virDomainSoundDefFormat(virBufferPtr buf,
D
Daniel P. Berrange 已提交
17932
                        virDomainSoundDefPtr def,
E
Eric Blake 已提交
17933
                        unsigned int flags)
17934 17935
{
    const char *model = virDomainSoundModelTypeToString(def->model);
17936
    bool children = false;
17937
    size_t i;
17938 17939

    if (!model) {
17940 17941
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected sound model %d"), def->model);
17942 17943 17944
        return -1;
    }

17945
    virBufferAsprintf(buf, "<sound model='%s'",  model);
17946

17947 17948 17949
    for (i = 0; i < def->ncodecs; i++) {
        if (!children) {
            virBufferAddLit(buf, ">\n");
17950
            virBufferAdjustIndent(buf, 2);
17951 17952 17953 17954 17955
            children = true;
        }
        virDomainSoundCodecDefFormat(buf, def->codecs[i]);
    }

17956
    if (virDomainDeviceInfoIsSet(&def->info, flags)) {
17957 17958
        if (!children) {
            virBufferAddLit(buf, ">\n");
17959
            virBufferAdjustIndent(buf, 2);
17960 17961
            children = true;
        }
D
Daniel P. Berrange 已提交
17962
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
17963
            return -1;
17964 17965 17966
    }

    if (children) {
17967 17968
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</sound>\n");
17969 17970 17971 17972
    } else {
        virBufferAddLit(buf, "/>\n");
    }

17973 17974 17975
    return 0;
}

17976

17977 17978 17979
static int
virDomainMemballoonDefFormat(virBufferPtr buf,
                             virDomainMemballoonDefPtr def,
E
Eric Blake 已提交
17980
                             unsigned int flags)
17981 17982
{
    const char *model = virDomainMemballoonModelTypeToString(def->model);
17983
    bool noopts = true;
17984 17985

    if (!model) {
17986 17987
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected memballoon model %d"), def->model);
17988 17989 17990
        return -1;
    }

17991 17992
    virBufferAsprintf(buf, "<memballoon model='%s'", model);
    virBufferAdjustIndent(buf, 2);
17993

17994
    if (virDomainDeviceInfoIsSet(&def->info, flags)) {
17995 17996 17997
        virBufferAddLit(buf, ">\n");
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
            return -1;
17998
        noopts = false;
17999 18000
    }

18001 18002 18003
    if (def->period) {
        if (noopts)
            virBufferAddLit(buf, ">\n");
18004
        virBufferAsprintf(buf, "<stats period='%u'/>\n", def->period);
18005 18006 18007
        noopts = false;
    }

18008
    virBufferAdjustIndent(buf, -2);
18009 18010 18011
    if (noopts)
        virBufferAddLit(buf, "/>\n");
    else
18012
        virBufferAddLit(buf, "</memballoon>\n");
18013

18014 18015 18016
    return 0;
}

L
Li Zhang 已提交
18017 18018 18019 18020 18021
static int
virDomainNVRAMDefFormat(virBufferPtr buf,
                        virDomainNVRAMDefPtr def,
                        unsigned int flags)
{
18022 18023
    virBufferAddLit(buf, "<nvram>\n");
    virBufferAdjustIndent(buf, 2);
L
Li Zhang 已提交
18024 18025 18026 18027
    if (virDomainDeviceInfoIsSet(&def->info, flags) &&
        virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
        return -1;

18028 18029
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</nvram>\n");
L
Li Zhang 已提交
18030 18031 18032 18033

    return 0;
}

18034

R
Richard Jones 已提交
18035
static int
18036
virDomainWatchdogDefFormat(virBufferPtr buf,
D
Daniel P. Berrange 已提交
18037
                           virDomainWatchdogDefPtr def,
E
Eric Blake 已提交
18038
                           unsigned int flags)
R
Richard Jones 已提交
18039
{
18040 18041
    const char *model = virDomainWatchdogModelTypeToString(def->model);
    const char *action = virDomainWatchdogActionTypeToString(def->action);
R
Richard Jones 已提交
18042 18043

    if (!model) {
18044 18045
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected watchdog model %d"), def->model);
R
Richard Jones 已提交
18046 18047 18048 18049
        return -1;
    }

    if (!action) {
18050 18051
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected watchdog action %d"), def->action);
R
Richard Jones 已提交
18052 18053 18054
        return -1;
    }

18055
    virBufferAsprintf(buf, "<watchdog model='%s' action='%s'",
R
Richard Jones 已提交
18056 18057
                      model, action);

18058
    if (virDomainDeviceInfoIsSet(&def->info, flags)) {
18059
        virBufferAddLit(buf, ">\n");
18060
        virBufferAdjustIndent(buf, 2);
D
Daniel P. Berrange 已提交
18061
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
18062
            return -1;
18063 18064
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</watchdog>\n");
18065 18066 18067 18068
    } else {
        virBufferAddLit(buf, "/>\n");
    }

R
Richard Jones 已提交
18069 18070 18071
    return 0;
}

H
Hu Tao 已提交
18072
static int virDomainPanicDefFormat(virBufferPtr buf,
18073
                                   virDomainPanicDefPtr def)
H
Hu Tao 已提交
18074
{
18075 18076
    virBufferAddLit(buf, "<panic>\n");
    virBufferAdjustIndent(buf, 2);
H
Hu Tao 已提交
18077 18078
    if (virDomainDeviceInfoFormat(buf, &def->info, 0) < 0)
        return -1;
18079 18080
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</panic>\n");
H
Hu Tao 已提交
18081 18082 18083

    return 0;
}
R
Richard Jones 已提交
18084

18085 18086 18087 18088 18089
static int
virDomainShmemDefFormat(virBufferPtr buf,
                        virDomainShmemDefPtr def,
                        unsigned int flags)
{
M
Martin Kletzander 已提交
18090
    virBufferEscapeString(buf, "<shmem name='%s'", def->name);
18091 18092 18093 18094 18095 18096 18097 18098 18099 18100 18101 18102 18103 18104

    if (!def->size &&
        !def->server.enabled &&
        !def->msi.enabled &&
        !virDomainDeviceInfoIsSet(&def->info, flags)) {
        virBufferAddLit(buf, "/>\n");
        return 0;
    } else {
        virBufferAddLit(buf, ">\n");
    }

    virBufferAdjustIndent(buf, 2);

    if (def->size)
M
Martin Kletzander 已提交
18105
        virBufferAsprintf(buf, "<size unit='M'>%llu</size>\n", def->size >> 20);
18106 18107 18108 18109 18110 18111 18112 18113 18114 18115 18116 18117 18118 18119 18120 18121 18122 18123 18124 18125 18126 18127 18128 18129 18130 18131

    if (def->server.enabled) {
        virBufferAddLit(buf, "<server");
        virBufferEscapeString(buf, " path='%s'", def->server.path);
        virBufferAddLit(buf, "/>\n");
    }

    if (def->msi.enabled) {
        virBufferAddLit(buf, "<msi");
        if (def->msi.vectors)
            virBufferAsprintf(buf, " vectors='%u'", def->msi.vectors);
        if (def->msi.ioeventfd)
            virBufferAsprintf(buf, " ioeventfd='%s'",
                              virTristateSwitchTypeToString(def->msi.ioeventfd));
        virBufferAddLit(buf, "/>\n");
    }

    if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
        return -1;

    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</shmem>\n");

    return 0;
}

18132 18133 18134 18135 18136 18137 18138 18139
static int
virDomainRNGDefFormat(virBufferPtr buf,
                      virDomainRNGDefPtr def,
                      unsigned int flags)
{
    const char *model = virDomainRNGModelTypeToString(def->model);
    const char *backend = virDomainRNGBackendTypeToString(def->backend);

18140 18141
    virBufferAsprintf(buf, "<rng model='%s'>\n", model);
    virBufferAdjustIndent(buf, 2);
18142
    if (def->rate) {
18143
        virBufferAsprintf(buf, "<rate bytes='%u'", def->rate);
18144 18145 18146 18147
        if (def->period)
            virBufferAsprintf(buf, " period='%u'", def->period);
        virBufferAddLit(buf, "/>\n");
    }
18148
    virBufferAsprintf(buf, "<backend model='%s'", backend);
18149

18150
    switch ((virDomainRNGBackend) def->backend) {
18151
    case VIR_DOMAIN_RNG_BACKEND_RANDOM:
18152
        virBufferEscapeString(buf, ">%s</backend>\n", def->source.file);
18153 18154 18155 18156
        break;

    case VIR_DOMAIN_RNG_BACKEND_EGD:
        virBufferAdjustIndent(buf, 2);
J
Ján Tomko 已提交
18157
        if (virDomainChrSourceDefFormat(buf, NULL, def->source.chardev,
18158 18159 18160
                                        false, flags) < 0)
            return -1;
        virBufferAdjustIndent(buf, -2);
18161
        virBufferAddLit(buf, "</backend>\n");
18162 18163 18164 18165 18166

    case VIR_DOMAIN_RNG_BACKEND_LAST:
        break;
    }

18167 18168 18169 18170 18171
    if (virDomainDeviceInfoIsSet(&def->info, flags)) {
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
            return -1;
    }

18172 18173
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</rng>\n");
18174 18175 18176 18177 18178 18179 18180 18181 18182
    return 0;
}

void
virDomainRNGDefFree(virDomainRNGDefPtr def)
{
    if (!def)
        return;

18183
    switch ((virDomainRNGBackend) def->backend) {
18184 18185 18186 18187 18188 18189 18190 18191 18192 18193
    case VIR_DOMAIN_RNG_BACKEND_RANDOM:
        VIR_FREE(def->source.file);
        break;
    case VIR_DOMAIN_RNG_BACKEND_EGD:
        virDomainChrSourceDefFree(def->source.chardev);
        break;
    case VIR_DOMAIN_RNG_BACKEND_LAST:
        break;
    }

J
John Ferlan 已提交
18194
    virDomainDeviceInfoClear(&def->info);
18195 18196 18197
    VIR_FREE(def);
}

18198 18199 18200 18201
static void
virDomainVideoAccelDefFormat(virBufferPtr buf,
                             virDomainVideoAccelDefPtr def)
{
18202
    virBufferAsprintf(buf, "<acceleration accel3d='%s'",
18203
                      def->support3d ? "yes" : "no");
18204
    virBufferAsprintf(buf, " accel2d='%s'",
18205 18206 18207 18208 18209
                      def->support2d ? "yes" : "no");
    virBufferAddLit(buf, "/>\n");
}


18210
static int
18211
virDomainVideoDefFormat(virBufferPtr buf,
D
Daniel P. Berrange 已提交
18212
                        virDomainVideoDefPtr def,
E
Eric Blake 已提交
18213
                        unsigned int flags)
18214 18215 18216 18217
{
    const char *model = virDomainVideoTypeToString(def->type);

    if (!model) {
18218 18219
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected video model %d"), def->type);
18220 18221 18222
        return -1;
    }

18223 18224 18225
    virBufferAddLit(buf, "<video>\n");
    virBufferAdjustIndent(buf, 2);
    virBufferAsprintf(buf, "<model type='%s'",
18226
                      model);
18227 18228
    if (def->ram)
        virBufferAsprintf(buf, " ram='%u'", def->ram);
18229
    if (def->vram)
18230
        virBufferAsprintf(buf, " vram='%u'", def->vram);
18231 18232
    if (def->vgamem)
        virBufferAsprintf(buf, " vgamem='%u'", def->vgamem);
18233
    if (def->heads)
18234
        virBufferAsprintf(buf, " heads='%u'", def->heads);
18235 18236
    if (def->primary)
        virBufferAddLit(buf, " primary='yes'");
18237 18238
    if (def->accel) {
        virBufferAddLit(buf, ">\n");
18239
        virBufferAdjustIndent(buf, 2);
18240
        virDomainVideoAccelDefFormat(buf, def->accel);
18241 18242
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</model>\n");
18243 18244 18245 18246
    } else {
        virBufferAddLit(buf, "/>\n");
    }

D
Daniel P. Berrange 已提交
18247
    if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
18248 18249
        return -1;

18250 18251
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</video>\n");
18252 18253 18254
    return 0;
}

18255
static int
18256
virDomainInputDefFormat(virBufferPtr buf,
18257
                        virDomainInputDefPtr def,
E
Eric Blake 已提交
18258
                        unsigned int flags)
18259 18260 18261 18262 18263
{
    const char *type = virDomainInputTypeToString(def->type);
    const char *bus = virDomainInputBusTypeToString(def->bus);

    if (!type) {
18264 18265
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected input type %d"), def->type);
18266 18267 18268
        return -1;
    }
    if (!bus) {
18269 18270
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected input bus type %d"), def->bus);
18271 18272 18273
        return -1;
    }

18274
    virBufferAsprintf(buf, "<input type='%s' bus='%s'",
18275 18276
                      type, bus);

18277
    if (virDomainDeviceInfoIsSet(&def->info, flags)) {
18278
        virBufferAddLit(buf, ">\n");
18279
        virBufferAdjustIndent(buf, 2);
18280 18281
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
            return -1;
18282 18283
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</input>\n");
18284 18285 18286 18287
    } else {
        virBufferAddLit(buf, "/>\n");
    }

18288 18289 18290 18291
    return 0;
}


18292 18293 18294 18295 18296 18297 18298
static int
virDomainTimerDefFormat(virBufferPtr buf,
                        virDomainTimerDefPtr def)
{
    const char *name = virDomainTimerNameTypeToString(def->name);

    if (!name) {
18299 18300
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected timer name %d"), def->name);
18301 18302
        return -1;
    }
18303
    virBufferAsprintf(buf, "<timer name='%s'", name);
18304 18305 18306 18307 18308 18309 18310 18311 18312 18313 18314

    if (def->present == 0) {
        virBufferAddLit(buf, " present='no'");
    } else if (def->present == 1) {
        virBufferAddLit(buf, " present='yes'");
    }

    if (def->tickpolicy != -1) {
        const char *tickpolicy
            = virDomainTimerTickpolicyTypeToString(def->tickpolicy);
        if (!tickpolicy) {
18315 18316 18317
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected timer tickpolicy %d"),
                           def->tickpolicy);
18318 18319
            return -1;
        }
18320
        virBufferAsprintf(buf, " tickpolicy='%s'", tickpolicy);
18321 18322 18323 18324
    }

    if ((def->name == VIR_DOMAIN_TIMER_NAME_PLATFORM)
        || (def->name == VIR_DOMAIN_TIMER_NAME_RTC)) {
18325 18326 18327 18328
        if (def->track != -1) {
            const char *track
                = virDomainTimerTrackTypeToString(def->track);
            if (!track) {
18329 18330 18331
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected timer track %d"),
                               def->track);
18332 18333
                return -1;
            }
18334
            virBufferAsprintf(buf, " track='%s'", track);
18335 18336 18337 18338
        }
    }

    if (def->name == VIR_DOMAIN_TIMER_NAME_TSC) {
18339
        if (def->frequency > 0)
18340
            virBufferAsprintf(buf, " frequency='%lu'", def->frequency);
18341 18342 18343 18344 18345

        if (def->mode != -1) {
            const char *mode
                = virDomainTimerModeTypeToString(def->mode);
            if (!mode) {
18346 18347 18348
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected timer mode %d"),
                               def->mode);
18349 18350
                return -1;
            }
18351
            virBufferAsprintf(buf, " mode='%s'", mode);
18352 18353 18354
        }
    }

E
Eric Blake 已提交
18355 18356
    if (def->catchup.threshold == 0 && def->catchup.slew == 0 &&
        def->catchup.limit == 0) {
18357 18358
        virBufferAddLit(buf, "/>\n");
    } else {
18359
        virBufferAddLit(buf, ">\n");
18360 18361
        virBufferAdjustIndent(buf, 2);
        virBufferAddLit(buf, "<catchup");
18362
        if (def->catchup.threshold > 0)
18363
            virBufferAsprintf(buf, " threshold='%lu'", def->catchup.threshold);
18364
        if (def->catchup.slew > 0)
18365
            virBufferAsprintf(buf, " slew='%lu'", def->catchup.slew);
18366
        if (def->catchup.limit > 0)
18367
            virBufferAsprintf(buf, " limit='%lu'", def->catchup.limit);
18368
        virBufferAddLit(buf, "/>\n");
18369 18370
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</timer>\n");
18371
    }
18372 18373 18374 18375

    return 0;
}

18376 18377 18378 18379 18380 18381 18382 18383 18384 18385 18386 18387 18388 18389 18390 18391 18392
static void
virDomainGraphicsAuthDefFormatAttr(virBufferPtr buf,
                                   virDomainGraphicsAuthDefPtr def,
                                   unsigned int flags)
{
    if (!def->passwd)
        return;

    if (flags & VIR_DOMAIN_XML_SECURE)
        virBufferEscapeString(buf, " passwd='%s'",
                              def->passwd);

    if (def->expires) {
        char strbuf[100];
        struct tm tmbuf, *tm;
        tm = gmtime_r(&def->validTo, &tmbuf);
        strftime(strbuf, sizeof(strbuf), "%Y-%m-%dT%H:%M:%S", tm);
18393
        virBufferAsprintf(buf, " passwdValidTo='%s'", strbuf);
18394
    }
18395 18396 18397 18398

    if (def->connected)
        virBufferEscapeString(buf, " connected='%s'",
                              virDomainGraphicsAuthConnectedTypeToString(def->connected));
18399 18400
}

18401 18402 18403 18404 18405 18406

static void
virDomainGraphicsListenDefFormat(virBufferPtr buf,
                                 virDomainGraphicsListenDefPtr def,
                                 unsigned int flags)
{
18407 18408 18409 18410 18411
    /* If generating migratable XML, skip listen address
     * dragged in from config file */
    if ((flags & VIR_DOMAIN_XML_MIGRATABLE) && def->fromConfig)
        return;

18412
    virBufferAddLit(buf, "<listen");
18413 18414 18415 18416 18417 18418
    if (def->type) {
        virBufferAsprintf(buf, " type='%s'",
                          virDomainGraphicsListenTypeToString(def->type));
    }

    if (def->address &&
E
Eric Blake 已提交
18419 18420
        (def->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS ||
         (def->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK &&
18421 18422 18423 18424 18425 18426 18427 18428
          !(flags & VIR_DOMAIN_XML_INACTIVE)))) {
        /* address may also be set to show current status when type='network',
         * but we don't want to print that if INACTIVE data is requested. */
        virBufferAsprintf(buf, " address='%s'", def->address);
    }

    if (def->network &&
        (def->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK)) {
18429
        virBufferEscapeString(buf, " network='%s'", def->network);
18430 18431
    }

18432 18433 18434
    if (flags & VIR_DOMAIN_XML_INTERNAL_STATUS)
        virBufferAsprintf(buf, " fromConfig='%d'", def->fromConfig);

18435 18436 18437 18438
    virBufferAddLit(buf, "/>\n");
}


18439
static int
18440
virDomainGraphicsDefFormat(virBufferPtr buf,
18441
                           virDomainGraphicsDefPtr def,
E
Eric Blake 已提交
18442
                           unsigned int flags)
18443 18444
{
    const char *type = virDomainGraphicsTypeToString(def->type);
18445
    const char *listenAddr = NULL;
18446
    bool children = false;
18447
    size_t i;
18448 18449

    if (!type) {
18450 18451
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected net type %d"), def->type);
18452 18453 18454
        return -1;
    }

18455 18456 18457 18458 18459 18460
    /* find the first listen element of type='address' and duplicate
    * its address attribute as the listen attribute of
    * <graphics>. This is done to improve backward compatibility. */
    for (i = 0; i < def->nListens; i++) {
        if (virDomainGraphicsListenGetType(def, i)
            == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS) {
18461 18462 18463
            if (flags & VIR_DOMAIN_XML_MIGRATABLE &&
                def->listens[i].fromConfig)
                continue;
18464 18465 18466 18467 18468
            listenAddr = virDomainGraphicsListenGetAddress(def, i);
            break;
        }
    }

18469
    virBufferAsprintf(buf, "<graphics type='%s'", type);
18470 18471 18472

    switch (def->type) {
    case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
18473 18474
        if (def->data.vnc.socket) {
            if (def->data.vnc.socket)
18475
                virBufferAsprintf(buf, " socket='%s'",
18476 18477 18478 18479
                                  def->data.vnc.socket);
        } else {
            if (def->data.vnc.port &&
                (!def->data.vnc.autoport || !(flags & VIR_DOMAIN_XML_INACTIVE)))
18480
                virBufferAsprintf(buf, " port='%d'",
18481 18482 18483
                                  def->data.vnc.port);
            else if (def->data.vnc.autoport)
                virBufferAddLit(buf, " port='-1'");
18484

18485
            virBufferAsprintf(buf, " autoport='%s'",
18486
                              def->data.vnc.autoport ? "yes" : "no");
18487

M
Martin Kletzander 已提交
18488 18489 18490
            if (def->data.vnc.websocket)
                virBufferAsprintf(buf, " websocket='%d'", def->data.vnc.websocket);

18491 18492
            if (listenAddr)
                virBufferAsprintf(buf, " listen='%s'", listenAddr);
18493
        }
18494 18495 18496 18497 18498

        if (def->data.vnc.keymap)
            virBufferEscapeString(buf, " keymap='%s'",
                                  def->data.vnc.keymap);

18499 18500 18501 18502 18503
        if (def->data.vnc.sharePolicy)
            virBufferAsprintf(buf, " sharePolicy='%s'",
                              virDomainGraphicsVNCSharePolicyTypeToString(
                              def->data.vnc.sharePolicy));

18504
        virDomainGraphicsAuthDefFormatAttr(buf, &def->data.vnc.auth, flags);
18505 18506 18507 18508 18509 18510 18511 18512 18513 18514
        break;

    case VIR_DOMAIN_GRAPHICS_TYPE_SDL:
        if (def->data.sdl.display)
            virBufferEscapeString(buf, " display='%s'",
                                  def->data.sdl.display);

        if (def->data.sdl.xauth)
            virBufferEscapeString(buf, " xauth='%s'",
                                  def->data.sdl.xauth);
18515 18516 18517
        if (def->data.sdl.fullscreen)
            virBufferAddLit(buf, " fullscreen='yes'");

18518
        break;
18519 18520 18521

    case VIR_DOMAIN_GRAPHICS_TYPE_RDP:
        if (def->data.rdp.port)
18522
            virBufferAsprintf(buf, " port='%d'",
18523 18524 18525 18526 18527
                              def->data.rdp.port);
        else if (def->data.rdp.autoport)
            virBufferAddLit(buf, " port='0'");

        if (def->data.rdp.autoport)
18528
            virBufferAddLit(buf, " autoport='yes'");
18529 18530

        if (def->data.rdp.replaceUser)
18531
            virBufferAddLit(buf, " replaceUser='yes'");
18532 18533

        if (def->data.rdp.multiUser)
18534
            virBufferAddLit(buf, " multiUser='yes'");
18535

18536 18537
        if (listenAddr)
            virBufferAsprintf(buf, " listen='%s'", listenAddr);
18538 18539 18540 18541 18542 18543 18544 18545 18546 18547 18548 18549 18550

        break;

    case VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP:
        if (def->data.desktop.display)
            virBufferEscapeString(buf, " display='%s'",
                                  def->data.desktop.display);

        if (def->data.desktop.fullscreen)
            virBufferAddLit(buf, " fullscreen='yes'");

        break;

18551 18552
    case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
        if (def->data.spice.port)
18553
            virBufferAsprintf(buf, " port='%d'",
18554 18555 18556
                              def->data.spice.port);

        if (def->data.spice.tlsPort)
18557
            virBufferAsprintf(buf, " tlsPort='%d'",
18558 18559
                              def->data.spice.tlsPort);

18560
        virBufferAsprintf(buf, " autoport='%s'",
18561 18562
                          def->data.spice.autoport ? "yes" : "no");

18563 18564
        if (listenAddr)
            virBufferAsprintf(buf, " listen='%s'", listenAddr);
18565 18566 18567 18568 18569

        if (def->data.spice.keymap)
            virBufferEscapeString(buf, " keymap='%s'",
                                  def->data.spice.keymap);

18570 18571 18572 18573
        if (def->data.spice.defaultMode != VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_ANY)
            virBufferAsprintf(buf, " defaultMode='%s'",
              virDomainGraphicsSpiceChannelModeTypeToString(def->data.spice.defaultMode));

18574
        virDomainGraphicsAuthDefFormatAttr(buf, &def->data.spice.auth, flags);
18575 18576
        break;

18577 18578
    }

18579 18580 18581 18582
    for (i = 0; i < def->nListens; i++) {
        if (virDomainGraphicsListenGetType(def, i)
            == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NONE)
            continue;
18583 18584 18585
        if (flags & VIR_DOMAIN_XML_MIGRATABLE &&
            def->listens[i].fromConfig)
            continue;
18586 18587
        if (!children) {
            virBufferAddLit(buf, ">\n");
18588
            virBufferAdjustIndent(buf, 2);
18589
            children = true;
18590 18591 18592 18593
        }
        virDomainGraphicsListenDefFormat(buf, &def->listens[i], flags);
    }

18594
    if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE) {
18595
        for (i = 0; i < VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_LAST; i++) {
18596 18597 18598 18599 18600 18601
            int mode = def->data.spice.channels[i];
            if (mode == VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_ANY)
                continue;

            if (!children) {
                virBufferAddLit(buf, ">\n");
18602
                virBufferAdjustIndent(buf, 2);
18603
                children = true;
18604 18605
            }

18606
            virBufferAsprintf(buf, "<channel name='%s' mode='%s'/>\n",
18607 18608 18609
                              virDomainGraphicsSpiceChannelNameTypeToString(i),
                              virDomainGraphicsSpiceChannelModeTypeToString(mode));
        }
18610 18611
        if (!children && (def->data.spice.image || def->data.spice.jpeg ||
                          def->data.spice.zlib || def->data.spice.playback ||
P
Peng Zhou 已提交
18612
                          def->data.spice.streaming || def->data.spice.copypaste ||
18613
                          def->data.spice.mousemode || def->data.spice.filetransfer)) {
18614
            virBufferAddLit(buf, ">\n");
18615
            virBufferAdjustIndent(buf, 2);
18616
            children = true;
18617
        }
18618
        if (def->data.spice.image)
18619
            virBufferAsprintf(buf, "<image compression='%s'/>\n",
18620 18621
                              virDomainGraphicsSpiceImageCompressionTypeToString(def->data.spice.image));
        if (def->data.spice.jpeg)
18622
            virBufferAsprintf(buf, "<jpeg compression='%s'/>\n",
18623 18624
                              virDomainGraphicsSpiceJpegCompressionTypeToString(def->data.spice.jpeg));
        if (def->data.spice.zlib)
18625
            virBufferAsprintf(buf, "<zlib compression='%s'/>\n",
18626 18627
                              virDomainGraphicsSpiceZlibCompressionTypeToString(def->data.spice.zlib));
        if (def->data.spice.playback)
18628
            virBufferAsprintf(buf, "<playback compression='%s'/>\n",
J
Ján Tomko 已提交
18629
                              virTristateSwitchTypeToString(def->data.spice.playback));
18630
        if (def->data.spice.streaming)
18631
            virBufferAsprintf(buf, "<streaming mode='%s'/>\n",
18632
                              virDomainGraphicsSpiceStreamingModeTypeToString(def->data.spice.streaming));
P
Peng Zhou 已提交
18633
        if (def->data.spice.mousemode)
18634
            virBufferAsprintf(buf, "<mouse mode='%s'/>\n",
P
Peng Zhou 已提交
18635
                              virDomainGraphicsSpiceMouseModeTypeToString(def->data.spice.mousemode));
18636
        if (def->data.spice.copypaste)
18637
            virBufferAsprintf(buf, "<clipboard copypaste='%s'/>\n",
J
Ján Tomko 已提交
18638
                              virTristateBoolTypeToString(def->data.spice.copypaste));
18639
        if (def->data.spice.filetransfer)
18640
            virBufferAsprintf(buf, "<filetransfer enable='%s'/>\n",
J
Ján Tomko 已提交
18641
                              virTristateBoolTypeToString(def->data.spice.filetransfer));
18642 18643 18644
    }

    if (children) {
18645 18646
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</graphics>\n");
18647 18648 18649
    } else {
        virBufferAddLit(buf, "/>\n");
    }
18650 18651 18652 18653

    return 0;
}

18654 18655

static int
18656
virDomainHostdevDefFormat(virBufferPtr buf,
D
Daniel P. Berrange 已提交
18657
                          virDomainHostdevDefPtr def,
E
Eric Blake 已提交
18658
                          unsigned int flags)
18659 18660
{
    const char *mode = virDomainHostdevModeTypeToString(def->mode);
18661
    virDomainHostdevSubsysSCSIPtr scsisrc = &def->source.subsys.u.scsi;
18662 18663
    const char *type;

18664
    if (!mode) {
18665 18666
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected hostdev mode %d"), def->mode);
18667 18668 18669
        return -1;
    }

18670 18671 18672 18673 18674 18675 18676 18677 18678 18679
    switch (def->mode) {
    case VIR_DOMAIN_HOSTDEV_MODE_SUBSYS:
        type = virDomainHostdevSubsysTypeToString(def->source.subsys.type);
        if (!type) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected hostdev type %d"),
                           def->source.subsys.type);
            return -1;
        }
        break;
18680 18681 18682 18683 18684 18685 18686 18687 18688
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
        type = virDomainHostdevCapsTypeToString(def->source.caps.type);
        if (!type) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected hostdev type %d"),
                           def->source.caps.type);
            return -1;
        }
        break;
18689
    default:
18690
        virReportError(VIR_ERR_INTERNAL_ERROR,
18691
                       _("unexpected hostdev mode %d"), def->mode);
18692 18693 18694
        return -1;
    }

18695
    virBufferAsprintf(buf, "<hostdev mode='%s' type='%s'",
18696
                      mode, type);
O
Osier Yang 已提交
18697 18698
    if (def->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
        virBufferAsprintf(buf, " managed='%s'",
18699
                          def->managed ? "yes" : "no");
O
Osier Yang 已提交
18700

18701 18702
        if (def->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
            scsisrc->sgio)
O
Osier Yang 已提交
18703
            virBufferAsprintf(buf, " sgio='%s'",
18704
                              virDomainDeviceSGIOTypeToString(scsisrc->sgio));
18705 18706 18707 18708 18709 18710

        if (def->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
            scsisrc->rawio) {
            virBufferAsprintf(buf, " rawio='%s'",
                              virTristateBoolTypeToString(scsisrc->rawio));
        }
O
Osier Yang 已提交
18711 18712
    }
    virBufferAddLit(buf, ">\n");
18713
    virBufferAdjustIndent(buf, 2);
18714

18715 18716 18717 18718 18719
    switch (def->mode) {
    case VIR_DOMAIN_HOSTDEV_MODE_SUBSYS:
        if (virDomainHostdevDefFormatSubsys(buf, def, flags, false) < 0)
            return -1;
        break;
18720 18721 18722 18723
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
        if (virDomainHostdevDefFormatCaps(buf, def) < 0)
            return -1;
        break;
18724
    }
O
Osier Yang 已提交
18725 18726 18727

    if (def->readonly)
        virBufferAddLit(buf, "<readonly/>\n");
18728 18729
    if (def->shareable)
        virBufferAddLit(buf, "<shareable/>\n");
18730

18731
    if (virDomainDeviceInfoFormat(buf, def->info,
18732 18733
                                  flags | VIR_DOMAIN_XML_INTERNAL_ALLOW_BOOT
                                  | VIR_DOMAIN_XML_INTERNAL_ALLOW_ROM) < 0)
18734 18735
        return -1;

18736 18737
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</hostdev>\n");
18738 18739 18740 18741

    return 0;
}

18742 18743 18744 18745 18746 18747 18748 18749 18750
static int
virDomainRedirdevDefFormat(virBufferPtr buf,
                           virDomainRedirdevDefPtr def,
                           unsigned int flags)
{
    const char *bus;

    bus = virDomainRedirdevBusTypeToString(def->bus);

18751 18752
    virBufferAsprintf(buf, "<redirdev bus='%s'", bus);
    virBufferAdjustIndent(buf, 2);
J
Ján Tomko 已提交
18753
    if (virDomainChrSourceDefFormat(buf, NULL, &def->source.chr, false, flags) < 0)
18754
        return -1;
18755 18756
    if (virDomainDeviceInfoFormat(buf, &def->info,
                                  flags | VIR_DOMAIN_XML_INTERNAL_ALLOW_BOOT) < 0)
18757
        return -1;
18758 18759
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</redirdev>\n");
18760 18761
    return 0;
}
18762

18763 18764 18765 18766 18767 18768
static int
virDomainRedirFilterDefFormat(virBufferPtr buf,
                              virDomainRedirFilterDefPtr filter)
{
    size_t i;

18769 18770
    virBufferAddLit(buf, "<redirfilter>\n");
    virBufferAdjustIndent(buf, 2);
18771
    for (i = 0; i < filter->nusbdevs; i++) {
18772
        virDomainRedirFilterUSBDevDefPtr usbdev = filter->usbdevs[i];
18773
        virBufferAddLit(buf, "<usbdev");
18774 18775 18776 18777 18778 18779 18780 18781 18782 18783 18784 18785 18786 18787 18788 18789 18790 18791 18792
        if (usbdev->usbClass >= 0)
            virBufferAsprintf(buf, " class='0x%02X'", usbdev->usbClass);

        if (usbdev->vendor >= 0)
            virBufferAsprintf(buf, " vendor='0x%04X'", usbdev->vendor);

        if (usbdev->product >= 0)
            virBufferAsprintf(buf, " product='0x%04X'", usbdev->product);

        if (usbdev->version >= 0)
            virBufferAsprintf(buf, " version='%d.%d'",
                                 ((usbdev->version & 0xf000) >> 12) * 10 +
                                 ((usbdev->version & 0x0f00) >>  8),
                                 ((usbdev->version & 0x00f0) >>  4) * 10 +
                                 ((usbdev->version & 0x000f) >>  0));

        virBufferAsprintf(buf, " allow='%s'/>\n", usbdev->allow ? "yes" : "no");

    }
18793 18794
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</redirfilter>\n");
18795 18796 18797
    return 0;
}

M
Marc-André Lureau 已提交
18798 18799
static int
virDomainHubDefFormat(virBufferPtr buf,
18800 18801
                      virDomainHubDefPtr def,
                      unsigned int flags)
M
Marc-André Lureau 已提交
18802 18803 18804 18805
{
    const char *type = virDomainHubTypeToString(def->type);

    if (!type) {
18806 18807
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected hub type %d"), def->type);
M
Marc-André Lureau 已提交
18808 18809 18810
        return -1;
    }

18811
    virBufferAsprintf(buf, "<hub type='%s'", type);
M
Marc-André Lureau 已提交
18812 18813 18814

    if (virDomainDeviceInfoIsSet(&def->info, flags)) {
        virBufferAddLit(buf, ">\n");
18815
        virBufferAdjustIndent(buf, 2);
M
Marc-André Lureau 已提交
18816 18817
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
            return -1;
18818 18819
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</hub>\n");
M
Marc-André Lureau 已提交
18820 18821 18822 18823 18824 18825 18826
    } else {
        virBufferAddLit(buf, "/>\n");
    }

    return 0;
}

18827 18828 18829 18830 18831 18832 18833 18834
/*
 * Return true if no <vcpupin> specified in domain XML
 * (I.e. all vcpus inherit the cpuset from "cpuset" of
 * <vcpu>). Or false otherwise.
 */
static bool
virDomainIsAllVcpupinInherited(virDomainDefPtr def)
{
18835
    size_t i;
18836 18837

    if (!def->cpumask) {
18838
        if (def->cputune.nvcpupin)
18839
            return false;
18840 18841
        else
            return true;
18842 18843 18844 18845 18846 18847 18848 18849 18850 18851
    } else {
        for (i = 0; i < def->cputune.nvcpupin; i++) {
            if (!virBitmapEqual(def->cputune.vcpupin[i]->cpumask,
                                def->cpumask))
                return false;
        }

        return true;
   }
}
M
Marc-André Lureau 已提交
18852

18853 18854 18855 18856 18857

static void
virDomainResourceDefFormat(virBufferPtr buf,
                           virDomainResourceDefPtr def)
{
18858 18859 18860 18861 18862
    virBufferAddLit(buf, "<resource>\n");
    virBufferAdjustIndent(buf, 2);
    virBufferEscapeString(buf, "<partition>%s</partition>\n", def->partition);
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</resource>\n");
18863 18864 18865
}


18866 18867 18868 18869 18870 18871 18872 18873 18874 18875 18876 18877 18878 18879 18880 18881 18882 18883 18884 18885 18886 18887 18888 18889 18890 18891 18892 18893 18894 18895 18896 18897 18898 18899 18900 18901 18902 18903 18904 18905 18906 18907 18908 18909 18910 18911 18912
static int
virDomainHugepagesFormatBuf(virBufferPtr buf,
                            virDomainHugePagePtr hugepage)
{
    int ret = -1;

    virBufferAsprintf(buf, "<page size='%llu' unit='KiB'",
                      hugepage->size);

    if (hugepage->nodemask) {
        char *nodeset = NULL;
        if (!(nodeset = virBitmapFormat(hugepage->nodemask)))
            goto cleanup;
        virBufferAsprintf(buf, " nodeset='%s'", nodeset);
        VIR_FREE(nodeset);
    }

    virBufferAddLit(buf, "/>\n");

    ret = 0;
 cleanup:
    return ret;
}

static void
virDomainHugepagesFormat(virBufferPtr buf,
                         virDomainHugePagePtr hugepages,
                         size_t nhugepages)
{
    size_t i;

    if (nhugepages == 1 &&
        hugepages[0].size == 0) {
        virBufferAddLit(buf, "<hugepages/>\n");
        return;
    }

    virBufferAddLit(buf, "<hugepages>\n");
    virBufferAdjustIndent(buf, 2);

    for (i = 0; i < nhugepages; i++)
        virDomainHugepagesFormatBuf(buf, &hugepages[i]);

    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</hugepages>\n");
}

18913 18914 18915 18916 18917 18918 18919 18920 18921 18922 18923 18924 18925 18926 18927
static void
virDomainLoaderDefFormat(virBufferPtr buf,
                         virDomainLoaderDefPtr loader)
{
    const char *readonly = virTristateBoolTypeToString(loader->readonly);
    const char *type = virDomainLoaderTypeToString(loader->type);

    virBufferAddLit(buf, "<loader");

    if (loader->readonly)
        virBufferAsprintf(buf, " readonly='%s'", readonly);

    virBufferAsprintf(buf, " type='%s'>", type);

    virBufferEscapeString(buf, "%s</loader>\n", loader->path);
18928 18929 18930 18931 18932 18933 18934 18935
    if (loader->nvram || loader->templt) {
        virBufferAddLit(buf, "<nvram");
        virBufferEscapeString(buf, " template='%s'", loader->templt);
        if (loader->nvram)
            virBufferEscapeString(buf, ">%s</nvram>\n", loader->nvram);
        else
            virBufferAddLit(buf, "/>\n");
    }
18936
}
18937

18938 18939 18940 18941 18942 18943
static bool
virDomainDefHasCapabilitiesFeatures(virDomainDefPtr def)
{
    size_t i;

    for (i = 0; i < VIR_DOMAIN_CAPS_FEATURE_LAST; i++) {
J
Ján Tomko 已提交
18944
        if (def->caps_features[i] != VIR_TRISTATE_SWITCH_ABSENT)
18945 18946 18947 18948 18949 18950
            return true;
    }

    return false;
}

18951
/* This internal version can accept VIR_DOMAIN_XML_INTERNAL_*,
18952
 * whereas the public version cannot.  Also, it appends to an existing
18953 18954 18955
 * buffer (possibly with auto-indent), rather than flattening to string.
 * Return -1 on failure.  */
int
18956
virDomainDefFormatInternal(virDomainDefPtr def,
18957 18958
                           unsigned int flags,
                           virBufferPtr buf)
18959 18960 18961
{
    unsigned char *uuid;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
18962
    const char *type = NULL;
H
Hu Tao 已提交
18963
    int n;
18964
    size_t i;
18965
    bool blkio = false;
18966
    bool cputune = false;
18967

18968 18969
    virCheckFlags(DUMPXML_FLAGS |
                  VIR_DOMAIN_XML_INTERNAL_STATUS |
18970
                  VIR_DOMAIN_XML_INTERNAL_ACTUAL_NET |
18971 18972
                  VIR_DOMAIN_XML_INTERNAL_PCI_ORIG_STATES |
                  VIR_DOMAIN_XML_INTERNAL_CLOCK_ADJUST,
18973
                  -1);
18974

18975
    if (!(type = virDomainVirtTypeToString(def->virtType))) {
18976 18977
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected domain type %d"), def->virtType);
18978
        goto error;
18979 18980
    }

18981 18982 18983
    if (def->id == -1)
        flags |= VIR_DOMAIN_XML_INACTIVE;

18984
    virBufferAsprintf(buf, "<domain type='%s'", type);
18985
    if (!(flags & VIR_DOMAIN_XML_INACTIVE))
18986
        virBufferAsprintf(buf, " id='%d'", def->id);
18987
    if (def->namespaceData && def->ns.href)
18988 18989
        virBufferAsprintf(buf, " %s", (def->ns.href)());
    virBufferAddLit(buf, ">\n");
18990
    virBufferAdjustIndent(buf, 2);
18991

18992
    virBufferEscapeString(buf, "<name>%s</name>\n", def->name);
18993 18994 18995

    uuid = def->uuid;
    virUUIDFormat(uuid, uuidstr);
18996
    virBufferAsprintf(buf, "<uuid>%s</uuid>\n", uuidstr);
18997

18998
    virBufferEscapeString(buf, "<title>%s</title>\n", def->title);
18999

19000
    virBufferEscapeString(buf, "<description>%s</description>\n",
19001
                          def->description);
19002

19003 19004 19005 19006 19007 19008 19009 19010 19011 19012 19013 19014 19015
    if (def->metadata) {
        xmlBufferPtr xmlbuf;
        int oldIndentTreeOutput = xmlIndentTreeOutput;

        /* Indentation on output requires that we previously set
         * xmlKeepBlanksDefault to 0 when parsing; also, libxml does 2
         * spaces per level of indentation of intermediate elements,
         * but no leading indentation before the starting element.
         * Thankfully, libxml maps what looks like globals into
         * thread-local uses, so we are thread-safe.  */
        xmlIndentTreeOutput = 1;
        xmlbuf = xmlBufferCreate();
        if (xmlNodeDump(xmlbuf, def->metadata->doc, def->metadata,
19016
                        virBufferGetIndent(buf, false) / 2, 1) < 0) {
19017 19018
            xmlBufferFree(xmlbuf);
            xmlIndentTreeOutput = oldIndentTreeOutput;
19019
            goto error;
19020
        }
19021
        virBufferAsprintf(buf, "%s\n", (char *) xmlBufferContent(xmlbuf));
19022 19023 19024 19025
        xmlBufferFree(xmlbuf);
        xmlIndentTreeOutput = oldIndentTreeOutput;
    }

19026
    virBufferAddLit(buf, "<memory");
19027 19028
    if (def->mem.dump_core)
        virBufferAsprintf(buf, " dumpCore='%s'",
J
Ján Tomko 已提交
19029
                          virTristateSwitchTypeToString(def->mem.dump_core));
19030
    virBufferAsprintf(buf, " unit='KiB'>%llu</memory>\n",
E
Eric Blake 已提交
19031
                      def->mem.max_balloon);
19032

19033
    virBufferAsprintf(buf, "<currentMemory unit='KiB'>%llu</currentMemory>\n",
19034 19035
                      def->mem.cur_balloon);

19036 19037
    /* add blkiotune only if there are any */
    if (def->blkio.weight) {
19038 19039 19040
        blkio = true;
    } else {
        for (n = 0; n < def->blkio.ndevices; n++) {
19041 19042 19043 19044 19045
            if (def->blkio.devices[n].weight ||
                def->blkio.devices[n].riops ||
                def->blkio.devices[n].wiops ||
                def->blkio.devices[n].rbps ||
                def->blkio.devices[n].wbps) {
19046 19047 19048 19049 19050 19051 19052
                blkio = true;
                break;
            }
        }
    }

    if (blkio) {
19053 19054
        virBufferAddLit(buf, "<blkiotune>\n");
        virBufferAdjustIndent(buf, 2);
19055 19056

        if (def->blkio.weight)
19057
            virBufferAsprintf(buf, "<weight>%u</weight>\n",
19058 19059 19060
                              def->blkio.weight);

        for (n = 0; n < def->blkio.ndevices; n++) {
19061 19062 19063 19064
            virBlkioDevicePtr dev = &def->blkio.devices[n];

            if (!dev->weight && !dev->riops && !dev->wiops &&
                !dev->rbps && !dev->wbps)
19065
                continue;
19066 19067 19068
            virBufferAddLit(buf, "<device>\n");
            virBufferAdjustIndent(buf, 2);
            virBufferEscapeString(buf, "<path>%s</path>\n",
19069 19070
                                  dev->path);
            if (dev->weight)
19071
                virBufferAsprintf(buf, "<weight>%u</weight>\n",
19072 19073
                                  dev->weight);
            if (dev->riops)
19074
                virBufferAsprintf(buf, "<read_iops_sec>%u</read_iops_sec>\n",
19075 19076
                                  dev->riops);
            if (dev->wiops)
19077
                virBufferAsprintf(buf, "<write_iops_sec>%u</write_iops_sec>\n",
19078 19079
                                  dev->wiops);
            if (dev->rbps)
19080
                virBufferAsprintf(buf, "<read_bytes_sec>%llu</read_bytes_sec>\n",
19081 19082
                                  dev->rbps);
            if (dev->wbps)
19083
                virBufferAsprintf(buf, "<write_bytes_sec>%llu</write_bytes_sec>\n",
19084
                                  dev->wbps);
19085 19086
            virBufferAdjustIndent(buf, -2);
            virBufferAddLit(buf, "</device>\n");
19087 19088
        }

19089 19090
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</blkiotune>\n");
19091 19092
    }

19093
    /* add memtune only if there are any */
19094 19095 19096
    if ((def->mem.hard_limit &&
         def->mem.hard_limit != VIR_DOMAIN_MEMORY_PARAM_UNLIMITED) ||
        (def->mem.soft_limit &&
19097
         def->mem.soft_limit != VIR_DOMAIN_MEMORY_PARAM_UNLIMITED) ||
19098
        (def->mem.swap_hard_limit &&
19099
         def->mem.swap_hard_limit != VIR_DOMAIN_MEMORY_PARAM_UNLIMITED) ||
19100
        def->mem.min_guarantee) {
19101 19102
        virBufferAddLit(buf, "<memtune>\n");
        virBufferAdjustIndent(buf, 2);
19103
        if (def->mem.hard_limit) {
19104
            virBufferAsprintf(buf, "<hard_limit unit='KiB'>"
19105 19106 19107
                              "%llu</hard_limit>\n", def->mem.hard_limit);
        }
        if (def->mem.soft_limit) {
19108
            virBufferAsprintf(buf, "<soft_limit unit='KiB'>"
19109 19110 19111
                              "%llu</soft_limit>\n", def->mem.soft_limit);
        }
        if (def->mem.min_guarantee) {
19112
            virBufferAsprintf(buf, "<min_guarantee unit='KiB'>"
19113 19114 19115
                              "%llu</min_guarantee>\n", def->mem.min_guarantee);
        }
        if (def->mem.swap_hard_limit) {
19116
            virBufferAsprintf(buf, "<swap_hard_limit unit='KiB'>"
19117 19118
                              "%llu</swap_hard_limit>\n", def->mem.swap_hard_limit);
        }
19119 19120
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</memtune>\n");
19121
    }
19122

19123
    if (def->mem.nhugepages || def->mem.nosharepages || def->mem.locked) {
19124 19125
        virBufferAddLit(buf, "<memoryBacking>\n");
        virBufferAdjustIndent(buf, 2);
19126 19127
        if (def->mem.nhugepages)
            virDomainHugepagesFormat(buf, def->mem.hugepages, def->mem.nhugepages);
19128
        if (def->mem.nosharepages)
19129
            virBufferAddLit(buf, "<nosharepages/>\n");
19130
        if (def->mem.locked)
19131 19132 19133
            virBufferAddLit(buf, "<locked/>\n");
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</memoryBacking>\n");
19134
    }
19135

19136
    virBufferAddLit(buf, "<vcpu");
19137 19138
    virBufferAsprintf(buf, " placement='%s'",
                      virDomainCpuPlacementModeTypeToString(def->placement_mode));
H
Hu Tao 已提交
19139 19140

    if (def->cpumask && !virBitmapIsAllSet(def->cpumask)) {
19141
        char *cpumask = NULL;
H
Hu Tao 已提交
19142
        if ((cpumask = virBitmapFormat(def->cpumask)) == NULL)
19143
            goto error;
19144
        virBufferAsprintf(buf, " cpuset='%s'", cpumask);
19145 19146
        VIR_FREE(cpumask);
    }
E
Eric Blake 已提交
19147
    if (def->vcpus != def->maxvcpus)
19148 19149
        virBufferAsprintf(buf, " current='%u'", def->vcpus);
    virBufferAsprintf(buf, ">%u</vcpu>\n", def->maxvcpus);
19150

19151 19152 19153
    if (def->iothreads > 0)
        virBufferAsprintf(buf, "<iothreads>%u</iothreads>\n", def->iothreads);

19154
    if (def->cputune.sharesSpecified ||
19155
        (def->cputune.nvcpupin && !virDomainIsAllVcpupinInherited(def)) ||
T
Tang Chen 已提交
19156
        def->cputune.period || def->cputune.quota ||
19157
        def->cputune.emulatorpin ||
19158 19159
        def->cputune.emulator_period || def->cputune.emulator_quota ||
        def->cputune.niothreadspin) {
19160
        virBufferAddLit(buf, "<cputune>\n");
19161 19162
        cputune = true;
    }
19163

19164
    virBufferAdjustIndent(buf, 2);
19165
    if (def->cputune.sharesSpecified)
19166
        virBufferAsprintf(buf, "<shares>%lu</shares>\n",
19167
                          def->cputune.shares);
19168
    if (def->cputune.period)
19169
        virBufferAsprintf(buf, "<period>%llu</period>\n",
19170 19171
                          def->cputune.period);
    if (def->cputune.quota)
19172
        virBufferAsprintf(buf, "<quota>%lld</quota>\n",
19173
                          def->cputune.quota);
19174 19175

    if (def->cputune.emulator_period)
19176
        virBufferAsprintf(buf, "<emulator_period>%llu"
19177 19178 19179 19180
                          "</emulator_period>\n",
                          def->cputune.emulator_period);

    if (def->cputune.emulator_quota)
19181
        virBufferAsprintf(buf, "<emulator_quota>%lld"
19182 19183 19184
                          "</emulator_quota>\n",
                          def->cputune.emulator_quota);

19185
    for (i = 0; i < def->cputune.nvcpupin; i++) {
P
Peter Krempa 已提交
19186 19187
        char *cpumask;
        /* Ignore the vcpupin which inherit from "cpuset of "<vcpu>." */
19188 19189 19190 19191
        if (def->cpumask &&
            virBitmapEqual(def->cpumask,
                           def->cputune.vcpupin[i]->cpumask))
            continue;
19192

19193
        virBufferAsprintf(buf, "<vcpupin vcpu='%u' ",
19194
                          def->cputune.vcpupin[i]->vcpuid);
19195

19196
        if (!(cpumask = virBitmapFormat(def->cputune.vcpupin[i]->cpumask)))
19197
            goto error;
19198 19199 19200

        virBufferAsprintf(buf, "cpuset='%s'/>\n", cpumask);
        VIR_FREE(cpumask);
19201 19202
    }

T
Tang Chen 已提交
19203
    if (def->cputune.emulatorpin) {
P
Peter Krempa 已提交
19204
        char *cpumask;
19205
        virBufferAddLit(buf, "<emulatorpin ");
T
Tang Chen 已提交
19206

19207 19208
        if (!(cpumask = virBitmapFormat(def->cputune.emulatorpin->cpumask)))
            goto error;
T
Tang Chen 已提交
19209 19210 19211 19212

        virBufferAsprintf(buf, "cpuset='%s'/>\n", cpumask);
        VIR_FREE(cpumask);
    }
19213 19214 19215 19216 19217 19218 19219 19220 19221 19222 19223 19224 19225 19226 19227 19228 19229 19230 19231

    for (i = 0; i < def->cputune.niothreadspin; i++) {
        char *cpumask;
        /* Ignore the iothreadpin which inherit from "cpuset of "<vcpu>." */
        if (def->cpumask &&
            virBitmapEqual(def->cpumask,
                           def->cputune.iothreadspin[i]->cpumask))
            continue;

        virBufferAsprintf(buf, "<iothreadpin iothread='%u' ",
                          def->cputune.iothreadspin[i]->vcpuid);

        if (!(cpumask = virBitmapFormat(def->cputune.iothreadspin[i]->cpumask)))
            goto error;

        virBufferAsprintf(buf, "cpuset='%s'/>\n", cpumask);
        VIR_FREE(cpumask);
    }

19232
    virBufferAdjustIndent(buf, -2);
19233
    if (cputune)
19234
        virBufferAddLit(buf, "</cputune>\n");
19235

19236 19237
    if (virDomainNumatuneFormatXML(buf, def->numatune) < 0)
        goto error;
19238

19239 19240 19241
    if (def->resource)
        virDomainResourceDefFormat(buf, def->resource);

19242
    if (def->sysinfo)
19243
        ignore_value(virSysinfoFormat(buf, def->sysinfo));
19244

19245
    if (def->os.bootloader) {
19246
        virBufferEscapeString(buf, "<bootloader>%s</bootloader>\n",
19247
                              def->os.bootloader);
19248
        virBufferEscapeString(buf,
19249
                              "<bootloader_args>%s</bootloader_args>\n",
19250
                              def->os.bootloaderArgs);
19251 19252
    }

19253 19254 19255
    virBufferAddLit(buf, "<os>\n");
    virBufferAdjustIndent(buf, 2);
    virBufferAddLit(buf, "<type");
19256
    if (def->os.arch)
19257
        virBufferAsprintf(buf, " arch='%s'", virArchToString(def->os.arch));
19258
    if (def->os.machine)
19259
        virBufferAsprintf(buf, " machine='%s'", def->os.machine);
19260 19261 19262 19263 19264 19265 19266
    /*
     * HACK: For xen driver we previously used bogus 'linux' as the
     * os type for paravirt, whereas capabilities declare it to
     * be 'xen'. So we convert to the former for backcompat
     */
    if (def->virtType == VIR_DOMAIN_VIRT_XEN &&
        STREQ(def->os.type, "xen"))
19267
        virBufferAsprintf(buf, ">%s</type>\n", "linux");
19268
    else
19269
        virBufferAsprintf(buf, ">%s</type>\n", def->os.type);
19270

19271
    virBufferEscapeString(buf, "<init>%s</init>\n",
19272
                          def->os.init);
19273
    for (i = 0; def->os.initargv && def->os.initargv[i]; i++)
19274
        virBufferEscapeString(buf, "<initarg>%s</initarg>\n",
19275
                              def->os.initargv[i]);
19276 19277
    if (def->os.loader)
        virDomainLoaderDefFormat(buf, def->os.loader);
19278
    virBufferEscapeString(buf, "<kernel>%s</kernel>\n",
19279
                          def->os.kernel);
19280
    virBufferEscapeString(buf, "<initrd>%s</initrd>\n",
19281
                          def->os.initrd);
19282
    virBufferEscapeString(buf, "<cmdline>%s</cmdline>\n",
19283
                          def->os.cmdline);
19284
    virBufferEscapeString(buf, "<dtb>%s</dtb>\n",
19285
                          def->os.dtb);
19286
    virBufferEscapeString(buf, "<root>%s</root>\n",
19287
                          def->os.root);
19288 19289

    if (!def->os.bootloader) {
19290
        for (n = 0; n < def->os.nBootDevs; n++) {
19291 19292 19293
            const char *boottype =
                virDomainBootTypeToString(def->os.bootDevs[n]);
            if (!boottype) {
19294 19295 19296
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected boot device type %d"),
                               def->os.bootDevs[n]);
19297
                goto error;
19298
            }
19299
            virBufferAsprintf(buf, "<boot dev='%s'/>\n", boottype);
19300
        }
19301

19302 19303
        if (def->os.bootmenu) {
            virBufferAsprintf(buf, "<bootmenu enable='%s'",
J
Ján Tomko 已提交
19304
                              virTristateBoolTypeToString(def->os.bootmenu));
19305 19306 19307 19308
            if (def->os.bm_timeout_set)
                virBufferAsprintf(buf, " timeout='%u'", def->os.bm_timeout);
            virBufferAddLit(buf, "/>\n");
        }
M
Michal Privoznik 已提交
19309

19310
        if (def->os.bios.useserial || def->os.bios.rt_set) {
19311
            virBufferAddLit(buf, "<bios");
19312 19313
            if (def->os.bios.useserial)
                virBufferAsprintf(buf, " useserial='%s'",
J
Ján Tomko 已提交
19314
                                  virTristateBoolTypeToString(def->os.bios.useserial));
19315 19316 19317 19318
            if (def->os.bios.rt_set)
                virBufferAsprintf(buf, " rebootTimeout='%d'", def->os.bios.rt_delay);

            virBufferAddLit(buf, "/>\n");
M
Michal Privoznik 已提交
19319
        }
19320 19321
    }

19322 19323 19324 19325 19326
    if (def->os.smbios_mode) {
        const char *mode;

        mode = virDomainSmbiosModeTypeToString(def->os.smbios_mode);
        if (mode == NULL) {
19327 19328
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected smbios mode %d"), def->os.smbios_mode);
19329
            goto error;
19330
        }
19331
        virBufferAsprintf(buf, "<smbios mode='%s'/>\n", mode);
19332 19333
    }

19334 19335
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</os>\n");
19336

19337 19338

    if (def->idmap.uidmap) {
19339 19340
        virBufferAddLit(buf, "<idmap>\n");
        virBufferAdjustIndent(buf, 2);
19341 19342
        for (i = 0; i < def->idmap.nuidmap; i++) {
            virBufferAsprintf(buf,
19343
                              "<uid start='%u' target='%u' count='%u'/>\n",
19344 19345 19346 19347 19348 19349
                              def->idmap.uidmap[i].start,
                              def->idmap.uidmap[i].target,
                              def->idmap.uidmap[i].count);
        }
        for (i = 0; i < def->idmap.ngidmap; i++) {
            virBufferAsprintf(buf,
19350
                              "<gid start='%u' target='%u' count='%u'/>\n",
19351 19352 19353 19354
                              def->idmap.gidmap[i].start,
                              def->idmap.gidmap[i].target,
                              def->idmap.gidmap[i].count);
        }
19355 19356
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</idmap>\n");
19357 19358
    }

19359
    for (i = 0; i < VIR_DOMAIN_FEATURE_LAST; i++) {
J
Ján Tomko 已提交
19360
        if (def->features[i] != VIR_TRISTATE_SWITCH_ABSENT)
19361 19362
            break;
    }
19363

19364 19365
    if (i != VIR_DOMAIN_FEATURE_LAST ||
        virDomainDefHasCapabilitiesFeatures(def)) {
19366 19367
        virBufferAddLit(buf, "<features>\n");
        virBufferAdjustIndent(buf, 2);
19368

19369
        for (i = 0; i < VIR_DOMAIN_FEATURE_LAST; i++) {
19370 19371 19372 19373 19374 19375 19376
            const char *name = virDomainFeatureTypeToString(i);
            size_t j;

            if (!name) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected feature %zu"), i);
                goto error;
19377
            }
19378

19379
            switch ((virDomainFeature) i) {
19380 19381 19382 19383 19384
            case VIR_DOMAIN_FEATURE_ACPI:
            case VIR_DOMAIN_FEATURE_PAE:
            case VIR_DOMAIN_FEATURE_HAP:
            case VIR_DOMAIN_FEATURE_VIRIDIAN:
            case VIR_DOMAIN_FEATURE_PRIVNET:
J
Ján Tomko 已提交
19385 19386
                switch ((virTristateSwitch) def->features[i]) {
                case VIR_TRISTATE_SWITCH_ABSENT:
19387 19388
                    break;

J
Ján Tomko 已提交
19389
                case VIR_TRISTATE_SWITCH_ON:
19390
                   virBufferAsprintf(buf, "<%s/>\n", name);
19391 19392
                   break;

J
Ján Tomko 已提交
19393 19394
                case VIR_TRISTATE_SWITCH_LAST:
                case VIR_TRISTATE_SWITCH_OFF:
19395 19396 19397 19398 19399 19400 19401 19402
                   virReportError(VIR_ERR_INTERNAL_ERROR,
                                 _("Unexpected state of feature '%s'"), name);

                   goto error;
                   break;
                }

                break;
19403

19404
            case VIR_DOMAIN_FEATURE_PVSPINLOCK:
J
Ján Tomko 已提交
19405 19406 19407
                switch ((virTristateSwitch) def->features[i]) {
                case VIR_TRISTATE_SWITCH_LAST:
                case VIR_TRISTATE_SWITCH_ABSENT:
19408 19409
                    break;

J
Ján Tomko 已提交
19410
                case VIR_TRISTATE_SWITCH_ON:
19411
                   virBufferAsprintf(buf, "<%s state='on'/>\n", name);
19412 19413
                   break;

J
Ján Tomko 已提交
19414
                case VIR_TRISTATE_SWITCH_OFF:
19415
                   virBufferAsprintf(buf, "<%s state='off'/>\n", name);
19416 19417 19418 19419 19420
                   break;
                }

                break;

19421
            case VIR_DOMAIN_FEATURE_APIC:
J
Ján Tomko 已提交
19422
                if (def->features[i] == VIR_TRISTATE_SWITCH_ON) {
19423
                    virBufferAddLit(buf, "<apic");
19424 19425
                    if (def->apic_eoi) {
                        virBufferAsprintf(buf, " eoi='%s'",
J
Ján Tomko 已提交
19426
                                          virTristateSwitchTypeToString(def->apic_eoi));
19427
                    }
19428
                    virBufferAddLit(buf, "/>\n");
19429 19430
                }
                break;
19431

19432
            case VIR_DOMAIN_FEATURE_HYPERV:
J
Ján Tomko 已提交
19433
                if (def->features[i] != VIR_TRISTATE_SWITCH_ON)
19434
                    break;
19435

19436 19437
                virBufferAddLit(buf, "<hyperv>\n");
                virBufferAdjustIndent(buf, 2);
19438
                for (j = 0; j < VIR_DOMAIN_HYPERV_LAST; j++) {
19439
                    switch ((virDomainHyperv) j) {
19440 19441 19442
                    case VIR_DOMAIN_HYPERV_RELAXED:
                    case VIR_DOMAIN_HYPERV_VAPIC:
                        if (def->hyperv_features[j])
19443
                            virBufferAsprintf(buf, "<%s state='%s'/>\n",
19444
                                              virDomainHypervTypeToString(j),
J
Ján Tomko 已提交
19445
                                              virTristateSwitchTypeToString(
19446 19447 19448 19449 19450 19451 19452
                                                  def->hyperv_features[j]));
                        break;

                    case VIR_DOMAIN_HYPERV_SPINLOCKS:
                        if (def->hyperv_features[j] == 0)
                            break;

19453
                        virBufferAsprintf(buf, "<spinlocks state='%s'",
J
Ján Tomko 已提交
19454
                                          virTristateSwitchTypeToString(
19455
                                              def->hyperv_features[j]));
J
Ján Tomko 已提交
19456
                        if (def->hyperv_features[j] == VIR_TRISTATE_SWITCH_ON)
19457 19458 19459 19460 19461
                            virBufferAsprintf(buf, " retries='%d'",
                                              def->hyperv_spinlocks);
                        virBufferAddLit(buf, "/>\n");
                        break;

19462
                    /* coverity[dead_error_begin] */
19463 19464 19465
                    case VIR_DOMAIN_HYPERV_LAST:
                        break;
                    }
19466
                }
19467 19468
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</hyperv>\n");
19469 19470
                break;

19471 19472 19473 19474 19475 19476 19477 19478 19479 19480 19481 19482 19483 19484 19485 19486
            case VIR_DOMAIN_FEATURE_KVM:
                if (def->features[i] != VIR_TRISTATE_SWITCH_ON)
                    break;

                virBufferAddLit(buf, "<kvm>\n");
                virBufferAdjustIndent(buf, 2);
                for (j = 0; j < VIR_DOMAIN_KVM_LAST; j++) {
                    switch ((virDomainKVM) j) {
                    case VIR_DOMAIN_KVM_HIDDEN:
                        if (def->kvm_features[j])
                            virBufferAsprintf(buf, "<%s state='%s'/>\n",
                                              virDomainKVMTypeToString(j),
                                              virTristateSwitchTypeToString(
                                                  def->kvm_features[j]));
                        break;

19487
                    /* coverity[dead_error_begin] */
19488 19489 19490 19491 19492 19493 19494 19495
                    case VIR_DOMAIN_KVM_LAST:
                        break;
                    }
                }
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</kvm>\n");
                break;

19496 19497 19498 19499 19500 19501 19502 19503 19504
            case VIR_DOMAIN_FEATURE_CAPABILITIES:
                if (def->features[i] == VIR_DOMAIN_CAPABILITIES_POLICY_DEFAULT &&
                        !virDomainDefHasCapabilitiesFeatures(def))
                    break;

                virBufferAsprintf(buf, "<capabilities policy='%s'>\n",
                                  virDomainCapabilitiesPolicyTypeToString(def->features[i]));
                virBufferAdjustIndent(buf, 2);
                for (j = 0; j < VIR_DOMAIN_CAPS_FEATURE_LAST; j++) {
J
Ján Tomko 已提交
19505
                    if (def->caps_features[j] != VIR_TRISTATE_SWITCH_ABSENT)
19506 19507
                        virBufferAsprintf(buf, "<%s state='%s'/>\n",
                                          virDomainCapsFeatureTypeToString(j),
J
Ján Tomko 已提交
19508
                                          virTristateSwitchTypeToString(
19509 19510 19511 19512 19513 19514
                                              def->caps_features[j]));
                }
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</capabilities>\n");
                break;

19515
            /* coverity[dead_error_begin] */
19516 19517
            case VIR_DOMAIN_FEATURE_LAST:
                break;
19518 19519 19520
            }
        }

19521 19522
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</features>\n");
19523 19524
    }

19525
    if (virCPUDefFormatBufFull(buf, def->cpu, flags) < 0)
19526
        goto error;
19527

19528
    virBufferAsprintf(buf, "<clock offset='%s'",
19529
                      virDomainClockOffsetTypeToString(def->clock.offset));
19530
    switch (def->clock.offset) {
19531 19532 19533 19534 19535
    case VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME:
    case VIR_DOMAIN_CLOCK_OFFSET_UTC:
        if (def->clock.data.utc_reset)
            virBufferAddLit(buf, " adjustment='reset'");
        break;
19536
    case VIR_DOMAIN_CLOCK_OFFSET_VARIABLE:
19537 19538 19539
        virBufferAsprintf(buf, " adjustment='%lld' basis='%s'",
                          def->clock.data.variable.adjustment,
                          virDomainClockBasisTypeToString(def->clock.data.variable.basis));
19540 19541 19542 19543 19544
        if (flags & VIR_DOMAIN_XML_INTERNAL_CLOCK_ADJUST) {
            if (def->clock.data.variable.adjustment0)
                virBufferAsprintf(buf, " adjustment0='%lld'",
                                  def->clock.data.variable.adjustment0);
        }
19545 19546
        break;
    case VIR_DOMAIN_CLOCK_OFFSET_TIMEZONE:
19547
        virBufferEscapeString(buf, " timezone='%s'", def->clock.data.timezone);
19548 19549
        break;
    }
19550
    if (def->clock.ntimers == 0) {
19551
        virBufferAddLit(buf, "/>\n");
19552
    } else {
19553
        virBufferAddLit(buf, ">\n");
19554
        virBufferAdjustIndent(buf, 2);
19555
        for (n = 0; n < def->clock.ntimers; n++) {
19556
            if (virDomainTimerDefFormat(buf, def->clock.timers[n]) < 0)
19557
                goto error;
19558
        }
19559 19560
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</clock>\n");
19561
    }
19562

19563 19564 19565
    if (virDomainEventActionDefFormat(buf, def->onPoweroff,
                                      "on_poweroff",
                                      virDomainLifecycleTypeToString) < 0)
19566
        goto error;
19567 19568 19569
    if (virDomainEventActionDefFormat(buf, def->onReboot,
                                      "on_reboot",
                                      virDomainLifecycleTypeToString) < 0)
19570
        goto error;
19571 19572 19573
    if (virDomainEventActionDefFormat(buf, def->onCrash,
                                      "on_crash",
                                      virDomainLifecycleCrashTypeToString) < 0)
19574
        goto error;
19575 19576 19577 19578
    if (def->onLockFailure != VIR_DOMAIN_LOCK_FAILURE_DEFAULT &&
        virDomainEventActionDefFormat(buf, def->onLockFailure,
                                      "on_lockfailure",
                                      virDomainLockFailureTypeToString) < 0)
19579
        goto error;
19580

19581
    if (def->pm.s3 || def->pm.s4) {
19582 19583
        virBufferAddLit(buf, "<pm>\n");
        virBufferAdjustIndent(buf, 2);
19584
        if (def->pm.s3) {
19585
            virBufferAsprintf(buf, "<suspend-to-mem enabled='%s'/>\n",
J
Ján Tomko 已提交
19586
                              virTristateBoolTypeToString(def->pm.s3));
19587 19588
        }
        if (def->pm.s4) {
19589
            virBufferAsprintf(buf, "<suspend-to-disk enabled='%s'/>\n",
J
Ján Tomko 已提交
19590
                              virTristateBoolTypeToString(def->pm.s4));
19591
        }
19592 19593
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</pm>\n");
19594 19595
    }

19596 19597
    virBufferAddLit(buf, "<devices>\n");
    virBufferAdjustIndent(buf, 2);
19598

19599
    virBufferEscapeString(buf, "<emulator>%s</emulator>\n",
19600
                          def->emulator);
19601

19602
    for (n = 0; n < def->ndisks; n++)
19603
        if (virDomainDiskDefFormat(buf, def->disks[n], flags) < 0)
19604
            goto error;
19605

19606
    for (n = 0; n < def->ncontrollers; n++)
19607
        if (virDomainControllerDefFormat(buf, def->controllers[n], flags) < 0)
19608
            goto error;
19609

19610
    for (n = 0; n < def->nleases; n++)
19611
        if (virDomainLeaseDefFormat(buf, def->leases[n]) < 0)
19612
            goto error;
19613

19614
    for (n = 0; n < def->nfss; n++)
19615
        if (virDomainFSDefFormat(buf, def->fss[n], flags) < 0)
19616
            goto error;
19617

19618
    for (n = 0; n < def->nnets; n++)
19619
        if (virDomainNetDefFormat(buf, def->nets[n], flags) < 0)
19620
            goto error;
19621

19622
    for (n = 0; n < def->nsmartcards; n++)
19623
        if (virDomainSmartcardDefFormat(buf, def->smartcards[n], flags) < 0)
19624
            goto error;
E
Eric Blake 已提交
19625

19626
    for (n = 0; n < def->nserials; n++)
19627
        if (virDomainChrDefFormat(buf, def->serials[n], flags) < 0)
19628
            goto error;
19629

19630
    for (n = 0; n < def->nparallels; n++)
19631
        if (virDomainChrDefFormat(buf, def->parallels[n], flags) < 0)
19632
            goto error;
19633

19634
    for (n = 0; n < def->nconsoles; n++) {
19635 19636 19637 19638 19639
        virDomainChrDef console;
        /* Back compat, ignore the console element for hvm guests
         * if it is type == serial
         */
        if (STREQ(def->os.type, "hvm") &&
19640 19641
            (def->consoles[n]->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL ||
             def->consoles[n]->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_NONE) &&
19642 19643 19644
            (n < def->nserials)) {
            memcpy(&console, def->serials[n], sizeof(console));
            console.deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE;
G
Guannan Ren 已提交
19645
            console.targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL;
19646 19647 19648 19649
        } else {
            memcpy(&console, def->consoles[n], sizeof(console));
        }
        if (virDomainChrDefFormat(buf, &console, flags) < 0)
19650
            goto error;
19651 19652 19653 19654
    }
    if (STREQ(def->os.type, "hvm") &&
        def->nconsoles == 0 &&
        def->nserials > 0) {
19655
        virDomainChrDef console;
19656
        memcpy(&console, def->serials[n], sizeof(console));
19657
        console.deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE;
19658
        console.targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL;
19659
        if (virDomainChrDefFormat(buf, &console, flags) < 0)
19660
            goto error;
19661 19662
    }

19663
    for (n = 0; n < def->nchannels; n++)
19664
        if (virDomainChrDefFormat(buf, def->channels[n], flags) < 0)
19665
            goto error;
19666

19667
    for (n = 0; n < def->ninputs; n++)
19668
        if (def->inputs[n]->bus == VIR_DOMAIN_INPUT_BUS_USB &&
19669
            virDomainInputDefFormat(buf, def->inputs[n], flags) < 0)
19670
            goto error;
19671

19672 19673 19674 19675 19676
    if (def->tpm) {
        if (virDomainTPMDefFormat(buf, def->tpm, flags) < 0)
            goto error;
    }

19677
    if (def->ngraphics > 0) {
L
Li Zhang 已提交
19678
        /* If graphics is enabled, add the implicit mouse/keyboard */
19679 19680 19681 19682 19683 19684 19685
        if ((ARCH_IS_X86(def->os.arch)) || def->os.arch == VIR_ARCH_NONE) {
            virDomainInputDef autoInput = {
                VIR_DOMAIN_INPUT_TYPE_MOUSE,
                STREQ(def->os.type, "hvm") ?
                VIR_DOMAIN_INPUT_BUS_PS2 : VIR_DOMAIN_INPUT_BUS_XEN,
                { .alias = NULL },
            };
19686

L
Li Zhang 已提交
19687 19688
            if (virDomainInputDefFormat(buf, &autoInput, flags) < 0)
                goto error;
19689 19690 19691 19692 19693 19694

            if (!(flags & VIR_DOMAIN_XML_MIGRATABLE)) {
                autoInput.type = VIR_DOMAIN_INPUT_TYPE_KBD;
                if (virDomainInputDefFormat(buf, &autoInput, flags) < 0)
                    goto error;
            }
L
Li Zhang 已提交
19695 19696
        }

19697
        for (n = 0; n < def->ngraphics; n++)
19698
            if (virDomainGraphicsDefFormat(buf, def->graphics[n], flags) < 0)
19699
                goto error;
19700 19701
    }

19702
    for (n = 0; n < def->nsounds; n++)
19703
        if (virDomainSoundDefFormat(buf, def->sounds[n], flags) < 0)
19704
            goto error;
19705

19706
    for (n = 0; n < def->nvideos; n++)
19707
        if (virDomainVideoDefFormat(buf, def->videos[n], flags) < 0)
19708
            goto error;
19709

19710
    for (n = 0; n < def->nhostdevs; n++) {
19711 19712 19713 19714
        /* If parent.type != NONE, this is just a pointer to the
         * hostdev in a higher-level device (e.g. virDomainNetDef),
         * and will have already been formatted there.
         */
E
Eric Blake 已提交
19715 19716
        if (def->hostdevs[n]->parent.type == VIR_DOMAIN_DEVICE_NONE &&
            virDomainHostdevDefFormat(buf, def->hostdevs[n], flags) < 0) {
19717
            goto error;
19718 19719
        }
    }
19720

19721
    for (n = 0; n < def->nredirdevs; n++)
19722
        if (virDomainRedirdevDefFormat(buf, def->redirdevs[n], flags) < 0)
19723
            goto error;
19724

19725 19726 19727
    if (def->redirfilter)
        virDomainRedirFilterDefFormat(buf, def->redirfilter);

19728
    for (n = 0; n < def->nhubs; n++)
19729
        if (virDomainHubDefFormat(buf, def->hubs[n], flags) < 0)
19730
            goto error;
M
Marc-André Lureau 已提交
19731

R
Richard Jones 已提交
19732
    if (def->watchdog)
19733
        virDomainWatchdogDefFormat(buf, def->watchdog, flags);
R
Richard Jones 已提交
19734

19735
    if (def->memballoon)
19736
        virDomainMemballoonDefFormat(buf, def->memballoon, flags);
19737

19738 19739 19740 19741
    for (n = 0; n < def->nrngs; n++) {
        if (virDomainRNGDefFormat(buf, def->rngs[n], flags))
            goto error;
    }
19742

L
Li Zhang 已提交
19743 19744 19745
    if (def->nvram)
        virDomainNVRAMDefFormat(buf, def->nvram, flags);

H
Hu Tao 已提交
19746 19747 19748 19749
    if (def->panic &&
        virDomainPanicDefFormat(buf, def->panic) < 0)
        goto error;

19750 19751 19752 19753
    for (n = 0; n < def->nshmems; n++)
        if (virDomainShmemDefFormat(buf, def->shmems[n], flags) < 0)
            goto error;

19754 19755
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</devices>\n");
19756

19757
    for (n = 0; n < def->nseclabels; n++)
19758
        virSecurityLabelDefFormat(buf, def->seclabels[n]);
19759

19760
    if (def->namespaceData && def->ns.format) {
19761
        if ((def->ns.format)(buf, def->namespaceData) < 0)
19762
            goto error;
19763 19764
    }

19765
    virBufferAdjustIndent(buf, -2);
19766
    virBufferAddLit(buf, "</domain>\n");
19767

19768 19769
    if (virBufferCheckError(buf) < 0)
        goto error;
19770

19771
    return 0;
19772

19773
 error:
19774 19775
    virBufferFreeAndReset(buf);
    return -1;
19776 19777
}

19778 19779 19780
char *
virDomainDefFormat(virDomainDefPtr def, unsigned int flags)
{
19781 19782
    virBuffer buf = VIR_BUFFER_INITIALIZER;

19783
    virCheckFlags(DUMPXML_FLAGS, NULL);
19784 19785 19786 19787
    if (virDomainDefFormatInternal(def, flags, &buf) < 0)
        return NULL;

    return virBufferContentAndReset(&buf);
19788 19789
}

19790

19791
static char *
19792
virDomainObjFormat(virDomainXMLOptionPtr xmlopt,
19793 19794
                   virDomainObjPtr obj,
                   unsigned int flags)
19795 19796
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
J
Jiri Denemark 已提交
19797 19798
    int state;
    int reason;
19799
    size_t i;
19800

J
Jiri Denemark 已提交
19801
    state = virDomainObjGetState(obj, &reason);
19802
    virBufferAsprintf(&buf, "<domstatus state='%s' reason='%s' pid='%lld'>\n",
J
Jiri Denemark 已提交
19803 19804
                      virDomainStateTypeToString(state),
                      virDomainStateReasonToString(state, reason),
19805
                      (long long)obj->pid);
19806
    virBufferAdjustIndent(&buf, 2);
19807

19808
    for (i = 0; i < VIR_DOMAIN_TAINT_LAST; i++) {
19809
        if (obj->taint & (1 << i))
19810
            virBufferAsprintf(&buf, "<taint flag='%s'/>\n",
19811 19812 19813
                              virDomainTaintTypeToString(i));
    }

19814 19815
    if (xmlopt->privateData.format &&
        ((xmlopt->privateData.format)(&buf, obj->privateData)) < 0)
19816
        goto error;
19817

19818
    if (virDomainDefFormatInternal(obj->def, flags, &buf) < 0)
19819 19820
        goto error;

19821
    virBufferAdjustIndent(&buf, -2);
19822 19823
    virBufferAddLit(&buf, "</domstatus>\n");

19824 19825
    if (virBufferCheckError(&buf) < 0)
        goto error;
19826 19827 19828

    return virBufferContentAndReset(&buf);

19829
 error:
19830
    virBufferFreeAndReset(&buf);
19831 19832 19833
    return NULL;
}

19834 19835 19836
static bool
virDomainDefHasUSB(virDomainDefPtr def)
{
19837
    size_t i;
19838 19839 19840 19841 19842 19843 19844 19845 19846 19847 19848 19849 19850 19851 19852 19853 19854 19855 19856 19857 19858 19859 19860 19861 19862 19863 19864 19865 19866 19867 19868

    for (i = 0; i < def->ncontrollers; i++) {
        if (def->controllers[i]->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
            def->controllers[i]->model != VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE)
            return true;
    }

    return false;
}

static bool
virDomainDeviceIsUSB(virDomainDeviceDefPtr dev)
{
    int t = dev->type;
    if ((t == VIR_DOMAIN_DEVICE_DISK &&
         dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB) ||
        (t == VIR_DOMAIN_DEVICE_INPUT &&
         dev->data.input->type == VIR_DOMAIN_INPUT_BUS_USB) ||
        (t == VIR_DOMAIN_DEVICE_HOSTDEV &&
         dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
         dev->data.hostdev->source.subsys.type ==
         VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) ||
        (t == VIR_DOMAIN_DEVICE_HUB &&
         dev->data.hub->type == VIR_DOMAIN_HUB_TYPE_USB) ||
        (t == VIR_DOMAIN_DEVICE_REDIRDEV &&
         dev->data.redirdev->bus == VIR_DOMAIN_REDIRDEV_BUS_USB))
        return true;

    return false;
}

19869 19870 19871 19872 19873 19874 19875 19876 19877 19878 19879 19880 19881 19882 19883 19884 19885
static int
virDomainDeviceInfoCheckBootIndex(virDomainDefPtr def ATTRIBUTE_UNUSED,
                                  virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
                                  virDomainDeviceInfoPtr info,
                                  void *opaque)
{
    virDomainDeviceInfoPtr newinfo = opaque;

    if (info->bootIndex == newinfo->bootIndex) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("boot order %d is already used by another device"),
                       newinfo->bootIndex);
        return -1;
    }
    return 0;
}

19886 19887
int
virDomainDefCompatibleDevice(virDomainDefPtr def,
19888 19889
                             virDomainDeviceDefPtr dev,
                             virDomainDeviceAction action)
19890
{
19891 19892
    virDomainDeviceInfoPtr info = virDomainDeviceGetInfo(dev);

19893 19894 19895
    if (action != VIR_DOMAIN_DEVICE_ACTION_ATTACH)
        return 0;

19896
    if (!virDomainDefHasUSB(def) &&
19897
        STRNEQ(def->os.type, "exe") &&
19898 19899 19900 19901 19902 19903 19904
        virDomainDeviceIsUSB(dev)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Device configuration is not compatible: "
                         "Domain has no USB bus support"));
        return -1;
    }

19905 19906 19907 19908 19909 19910 19911 19912 19913 19914 19915 19916 19917
    if (info && info->bootIndex > 0) {
        if (def->os.nBootDevs > 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("per-device boot elements cannot be used"
                             " together with os/boot elements"));
            return -1;
        }
        if (virDomainDeviceInfoIterate(def,
                                       virDomainDeviceInfoCheckBootIndex,
                                       info) < 0)
            return -1;
    }

19918 19919 19920
    return 0;
}

19921 19922 19923 19924
int
virDomainSaveXML(const char *configDir,
                 virDomainDefPtr def,
                 const char *xml)
19925
{
J
Ján Tomko 已提交
19926
    char uuidstr[VIR_UUID_STRING_BUFLEN];
19927
    char *configFile = NULL;
19928
    int ret = -1;
19929

19930 19931 19932
    if (!configDir)
        return 0;

19933
    if ((configFile = virDomainConfigFile(configDir, def->name)) == NULL)
19934 19935
        goto cleanup;

19936
    if (virFileMakePath(configDir) < 0) {
19937
        virReportSystemError(errno,
19938 19939
                             _("cannot create config directory '%s'"),
                             configDir);
19940 19941 19942
        goto cleanup;
    }

J
Ján Tomko 已提交
19943 19944 19945 19946
    virUUIDFormat(def->uuid, uuidstr);
    ret = virXMLSaveFile(configFile,
                         virXMLPickShellSafeComment(def->name, uuidstr), "edit",
                         xml);
19947

19948
 cleanup:
R
Ryota Ozaki 已提交
19949
    VIR_FREE(configFile);
19950 19951 19952
    return ret;
}

19953 19954 19955
int
virDomainSaveConfig(const char *configDir,
                    virDomainDefPtr def)
19956 19957 19958
{
    int ret = -1;
    char *xml;
19959

19960
    if (!(xml = virDomainDefFormat(def, VIR_DOMAIN_XML_WRITE_FLAGS)))
19961 19962
        goto cleanup;

19963
    if (virDomainSaveXML(configDir, def, xml))
19964 19965 19966
        goto cleanup;

    ret = 0;
19967
 cleanup:
19968
    VIR_FREE(xml);
19969 19970 19971
    return ret;
}

19972
int
19973
virDomainSaveStatus(virDomainXMLOptionPtr xmlopt,
19974 19975
                    const char *statusDir,
                    virDomainObjPtr obj)
19976
{
19977 19978
    unsigned int flags = (VIR_DOMAIN_XML_SECURE |
                          VIR_DOMAIN_XML_INTERNAL_STATUS |
19979
                          VIR_DOMAIN_XML_INTERNAL_ACTUAL_NET |
19980 19981
                          VIR_DOMAIN_XML_INTERNAL_PCI_ORIG_STATES |
                          VIR_DOMAIN_XML_INTERNAL_CLOCK_ADJUST);
19982

19983 19984 19985
    int ret = -1;
    char *xml;

19986
    if (!(xml = virDomainObjFormat(xmlopt, obj, flags)))
19987 19988
        goto cleanup;

19989
    if (virDomainSaveXML(statusDir, obj->def, xml))
19990 19991 19992
        goto cleanup;

    ret = 0;
19993
 cleanup:
19994 19995 19996 19997
    VIR_FREE(xml);
    return ret;
}

19998

19999 20000 20001
static virDomainObjPtr
virDomainObjListLoadConfig(virDomainObjListPtr doms,
                           virCapsPtr caps,
20002
                           virDomainXMLOptionPtr xmlopt,
20003 20004 20005 20006 20007 20008
                           const char *configDir,
                           const char *autostartDir,
                           const char *name,
                           unsigned int expectedVirtTypes,
                           virDomainLoadConfigNotify notify,
                           void *opaque)
20009 20010 20011 20012 20013
{
    char *configFile = NULL, *autostartLink = NULL;
    virDomainDefPtr def = NULL;
    virDomainObjPtr dom;
    int autostart;
20014
    virDomainDefPtr oldDef = NULL;
20015

20016
    if ((configFile = virDomainConfigFile(configDir, name)) == NULL)
20017
        goto error;
20018
    if (!(def = virDomainDefParseFile(configFile, caps, xmlopt,
20019
                                      expectedVirtTypes,
20020
                                      VIR_DOMAIN_XML_INACTIVE)))
20021 20022
        goto error;

20023 20024 20025 20026 20027 20028
    if ((autostartLink = virDomainConfigFile(autostartDir, name)) == NULL)
        goto error;

    if ((autostart = virFileLinkPointsTo(autostartLink, configFile)) < 0)
        goto error;

20029
    if (!(dom = virDomainObjListAddLocked(doms, def, xmlopt, 0, &oldDef)))
20030 20031 20032 20033
        goto error;

    dom->autostart = autostart;

20034
    if (notify)
20035
        (*notify)(dom, oldDef == NULL, opaque);
20036

20037
    virDomainDefFree(oldDef);
20038 20039
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
20040 20041
    return dom;

20042
 error:
20043 20044 20045 20046 20047 20048
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
    virDomainDefFree(def);
    return NULL;
}

20049 20050 20051 20052
static virDomainObjPtr
virDomainObjListLoadStatus(virDomainObjListPtr doms,
                           const char *statusDir,
                           const char *name,
20053 20054
                           virCapsPtr caps,
                           virDomainXMLOptionPtr xmlopt,
20055 20056 20057
                           unsigned int expectedVirtTypes,
                           virDomainLoadConfigNotify notify,
                           void *opaque)
20058 20059 20060
{
    char *statusFile = NULL;
    virDomainObjPtr obj = NULL;
20061
    char uuidstr[VIR_UUID_STRING_BUFLEN];
20062

20063
    if ((statusFile = virDomainConfigFile(statusDir, name)) == NULL)
20064 20065
        goto error;

20066
    if (!(obj = virDomainObjParseFile(statusFile, caps, xmlopt, expectedVirtTypes,
20067
                                      VIR_DOMAIN_XML_INTERNAL_STATUS |
20068
                                      VIR_DOMAIN_XML_INTERNAL_ACTUAL_NET |
20069 20070
                                      VIR_DOMAIN_XML_INTERNAL_PCI_ORIG_STATES |
                                      VIR_DOMAIN_XML_INTERNAL_CLOCK_ADJUST)))
20071 20072
        goto error;

20073 20074 20075
    virUUIDFormat(obj->def->uuid, uuidstr);

    if (virHashLookup(doms->objs, uuidstr) != NULL) {
20076 20077 20078
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected domain %s already exists"),
                       obj->def->name);
20079 20080 20081
        goto error;
    }

20082
    if (virHashAddEntry(doms->objs, uuidstr, obj) < 0)
20083 20084 20085 20086 20087 20088 20089 20090
        goto error;

    if (notify)
        (*notify)(obj, 1, opaque);

    VIR_FREE(statusFile);
    return obj;

20091
 error:
20092
    virObjectUnref(obj);
20093 20094 20095 20096
    VIR_FREE(statusFile);
    return NULL;
}

20097 20098 20099 20100 20101
int
virDomainObjListLoadAllConfigs(virDomainObjListPtr doms,
                               const char *configDir,
                               const char *autostartDir,
                               int liveStatus,
20102 20103
                               virCapsPtr caps,
                               virDomainXMLOptionPtr xmlopt,
20104 20105 20106
                               unsigned int expectedVirtTypes,
                               virDomainLoadConfigNotify notify,
                               void *opaque)
20107 20108 20109
{
    DIR *dir;
    struct dirent *entry;
E
Eric Blake 已提交
20110
    int ret = -1;
20111

20112 20113
    VIR_INFO("Scanning for configs in %s", configDir);

20114 20115 20116
    if (!(dir = opendir(configDir))) {
        if (errno == ENOENT)
            return 0;
20117
        virReportSystemError(errno,
20118 20119
                             _("Failed to open dir '%s'"),
                             configDir);
20120 20121 20122
        return -1;
    }

20123 20124
    virObjectLock(doms);

E
Eric Blake 已提交
20125
    while ((ret = virDirRead(dir, &entry, configDir)) > 0) {
20126 20127
        virDomainObjPtr dom;

20128 20129 20130
        if (entry->d_name[0] == '.')
            continue;

20131
        if (!virFileStripSuffix(entry->d_name, ".xml"))
20132 20133 20134 20135
            continue;

        /* NB: ignoring errors, so one malformed config doesn't
           kill the whole process */
20136 20137
        VIR_INFO("Loading config file '%s.xml'", entry->d_name);
        if (liveStatus)
20138 20139 20140
            dom = virDomainObjListLoadStatus(doms,
                                             configDir,
                                             entry->d_name,
20141 20142
                                             caps,
                                             xmlopt,
20143 20144 20145
                                             expectedVirtTypes,
                                             notify,
                                             opaque);
20146
        else
20147 20148
            dom = virDomainObjListLoadConfig(doms,
                                             caps,
20149
                                             xmlopt,
20150 20151 20152 20153 20154 20155
                                             configDir,
                                             autostartDir,
                                             entry->d_name,
                                             expectedVirtTypes,
                                             notify,
                                             opaque);
20156
        if (dom) {
D
Daniel Veillard 已提交
20157 20158
            if (!liveStatus)
                dom->persistent = 1;
20159
            virObjectUnlock(dom);
20160
        }
20161 20162 20163
    }

    closedir(dir);
20164
    virObjectUnlock(doms);
E
Eric Blake 已提交
20165
    return ret;
20166 20167
}

20168 20169 20170 20171
int
virDomainDeleteConfig(const char *configDir,
                      const char *autostartDir,
                      virDomainObjPtr dom)
20172
{
20173 20174 20175
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

20176
    if ((configFile = virDomainConfigFile(configDir, dom->def->name)) == NULL)
20177
        goto cleanup;
20178 20179
    if ((autostartLink = virDomainConfigFile(autostartDir,
                                             dom->def->name)) == NULL)
20180
        goto cleanup;
20181 20182

    /* Not fatal if this doesn't work */
20183
    unlink(autostartLink);
20184

20185 20186
    if (unlink(configFile) < 0 &&
        errno != ENOENT) {
20187
        virReportSystemError(errno,
20188 20189
                             _("cannot remove config %s"),
                             configFile);
20190
        goto cleanup;
20191 20192
    }

20193 20194
    ret = 0;

20195
 cleanup:
20196 20197 20198
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
    return ret;
20199
}
20200

20201 20202 20203
char
*virDomainConfigFile(const char *dir,
                     const char *name)
20204
{
20205
    char *ret;
20206

20207
    ignore_value(virAsprintf(&ret, "%s/%s.xml", dir, name));
20208 20209 20210
    return ret;
}

20211 20212
/* Translates a device name of the form (regex) "[fhv]d[a-z]+" into
 * the corresponding bus,index combination (e.g. sda => (0,0), sdi (1,1),
D
Daniel Veillard 已提交
20213
 *                                               hdd => (1,1), vdaa => (0,26))
20214 20215 20216 20217 20218
 * @param disk The disk device
 * @param busIdx parsed bus number
 * @param devIdx parsed device number
 * @return 0 on success, -1 on failure
 */
20219
int
20220
virDiskNameToBusDeviceIndex(virDomainDiskDefPtr disk,
20221
                            int *busIdx,
20222 20223
                            int *devIdx)
{
20224 20225

    int idx = virDiskNameToIndex(disk->dst);
20226
    if (idx < 0)
20227 20228 20229 20230 20231 20232 20233 20234 20235 20236 20237 20238 20239 20240 20241
        return -1;

    switch (disk->bus) {
        case VIR_DOMAIN_DISK_BUS_IDE:
            *busIdx = idx / 2;
            *devIdx = idx % 2;
            break;
        case VIR_DOMAIN_DISK_BUS_SCSI:
            *busIdx = idx / 7;
            *devIdx = idx % 7;
            break;
        case VIR_DOMAIN_DISK_BUS_FDC:
        case VIR_DOMAIN_DISK_BUS_USB:
        case VIR_DOMAIN_DISK_BUS_VIRTIO:
        case VIR_DOMAIN_DISK_BUS_XEN:
20242
        case VIR_DOMAIN_DISK_BUS_SD:
20243 20244 20245 20246 20247 20248 20249 20250
        default:
            *busIdx = 0;
            *devIdx = idx;
            break;
    }

    return 0;
}
20251

20252 20253 20254 20255 20256 20257 20258 20259 20260 20261 20262 20263 20264 20265 20266 20267
int
virDomainFSInsert(virDomainDefPtr def, virDomainFSDefPtr fs)
{

    return VIR_APPEND_ELEMENT(def->fss, def->nfss, fs);
}

virDomainFSDefPtr
virDomainFSRemove(virDomainDefPtr def, size_t i)
{
    virDomainFSDefPtr fs = def->fss[i];

    VIR_DELETE_ELEMENT(def->fss, i, def->nfss);
    return fs;
}

20268
virDomainFSDefPtr
20269
virDomainGetFilesystemForTarget(virDomainDefPtr def,
20270
                                const char *target)
20271
{
20272
    size_t i;
20273

20274
    for (i = 0; i < def->nfss; i++) {
20275
        if (STREQ(def->fss[i]->dst, target))
20276 20277 20278 20279 20280 20281
            return def->fss[i];
    }

    return NULL;
}

20282

20283 20284 20285 20286 20287 20288
struct virDomainObjListData {
    virDomainObjListFilter filter;
    virConnectPtr conn;
    bool active;
    int count;
};
20289

20290
static void
20291 20292 20293
virDomainObjListCount(void *payload,
                      const void *name ATTRIBUTE_UNUSED,
                      void *opaque)
20294 20295
{
    virDomainObjPtr obj = payload;
20296
    struct virDomainObjListData *data = opaque;
20297
    virObjectLock(obj);
20298 20299 20300 20301 20302 20303 20304 20305 20306 20307
    if (data->filter &&
        !data->filter(data->conn, obj->def))
        goto cleanup;
    if (virDomainObjIsActive(obj)) {
        if (data->active)
            data->count++;
    } else {
        if (!data->active)
            data->count++;
    }
20308
 cleanup:
20309
    virObjectUnlock(obj);
20310 20311
}

20312 20313
int
virDomainObjListNumOfDomains(virDomainObjListPtr doms,
20314 20315 20316
                             bool active,
                             virDomainObjListFilter filter,
                             virConnectPtr conn)
20317
{
20318
    struct virDomainObjListData data = { filter, conn, active, 0 };
20319
    virObjectLock(doms);
20320
    virHashForEach(doms->objs, virDomainObjListCount, &data);
20321
    virObjectUnlock(doms);
20322
    return data.count;
20323 20324 20325
}

struct virDomainIDData {
20326 20327
    virDomainObjListFilter filter;
    virConnectPtr conn;
20328 20329 20330 20331 20332
    int numids;
    int maxids;
    int *ids;
};

20333 20334 20335 20336
static void
virDomainObjListCopyActiveIDs(void *payload,
                              const void *name ATTRIBUTE_UNUSED,
                              void *opaque)
20337 20338 20339
{
    virDomainObjPtr obj = payload;
    struct virDomainIDData *data = opaque;
20340
    virObjectLock(obj);
20341 20342 20343
    if (data->filter &&
        !data->filter(data->conn, obj->def))
        goto cleanup;
D
Daniel P. Berrange 已提交
20344
    if (virDomainObjIsActive(obj) && data->numids < data->maxids)
20345
        data->ids[data->numids++] = obj->def->id;
20346
 cleanup:
20347
    virObjectUnlock(obj);
20348 20349
}

20350 20351 20352
int
virDomainObjListGetActiveIDs(virDomainObjListPtr doms,
                             int *ids,
20353 20354 20355
                             int maxids,
                             virDomainObjListFilter filter,
                             virConnectPtr conn)
20356
{
20357 20358
    struct virDomainIDData data = { filter, conn,
                                    0, maxids, ids };
20359
    virObjectLock(doms);
20360
    virHashForEach(doms->objs, virDomainObjListCopyActiveIDs, &data);
20361
    virObjectUnlock(doms);
20362 20363 20364 20365
    return data.numids;
}

struct virDomainNameData {
20366 20367
    virDomainObjListFilter filter;
    virConnectPtr conn;
20368 20369 20370 20371 20372 20373
    int oom;
    int numnames;
    int maxnames;
    char **const names;
};

20374 20375 20376 20377
static void
virDomainObjListCopyInactiveNames(void *payload,
                                  const void *name ATTRIBUTE_UNUSED,
                                  void *opaque)
20378 20379 20380 20381 20382 20383 20384
{
    virDomainObjPtr obj = payload;
    struct virDomainNameData *data = opaque;

    if (data->oom)
        return;

20385
    virObjectLock(obj);
20386 20387 20388
    if (data->filter &&
        !data->filter(data->conn, obj->def))
        goto cleanup;
D
Daniel P. Berrange 已提交
20389
    if (!virDomainObjIsActive(obj) && data->numnames < data->maxnames) {
20390
        if (VIR_STRDUP(data->names[data->numnames], obj->def->name) < 0)
20391 20392 20393 20394
            data->oom = 1;
        else
            data->numnames++;
    }
20395
 cleanup:
20396
    virObjectUnlock(obj);
20397 20398 20399
}


20400 20401 20402
int
virDomainObjListGetInactiveNames(virDomainObjListPtr doms,
                                 char **const names,
20403 20404 20405
                                 int maxnames,
                                 virDomainObjListFilter filter,
                                 virConnectPtr conn)
20406
{
20407 20408
    struct virDomainNameData data = { filter, conn,
                                      0, 0, maxnames, names };
20409
    size_t i;
20410
    virObjectLock(doms);
20411
    virHashForEach(doms->objs, virDomainObjListCopyInactiveNames, &data);
20412
    virObjectUnlock(doms);
20413
    if (data.oom) {
20414
        for (i = 0; i < data.numnames; i++)
20415 20416
            VIR_FREE(data.names[i]);
        return -1;
20417 20418 20419 20420 20421
    }

    return data.numnames;
}

20422 20423 20424 20425 20426 20427 20428 20429 20430 20431 20432 20433 20434 20435 20436 20437 20438 20439

struct virDomainListIterData {
    virDomainObjListIterator callback;
    void *opaque;
    int ret;
};

static void
virDomainObjListHelper(void *payload,
                       const void *name ATTRIBUTE_UNUSED,
                       void *opaque)
{
    struct virDomainListIterData *data = opaque;

    if (data->callback(payload, data->opaque) < 0)
        data->ret = -1;
}

20440 20441 20442 20443
int
virDomainObjListForEach(virDomainObjListPtr doms,
                        virDomainObjListIterator callback,
                        void *opaque)
20444 20445 20446 20447
{
    struct virDomainListIterData data = {
        callback, opaque, 0,
    };
20448
    virObjectLock(doms);
20449
    virHashForEach(doms->objs, virDomainObjListHelper, &data);
20450
    virObjectUnlock(doms);
20451 20452 20453 20454
    return data.ret;
}


20455 20456 20457 20458 20459
int
virDomainChrDefForeach(virDomainDefPtr def,
                       bool abortOnError,
                       virDomainChrDefIterator iter,
                       void *opaque)
20460
{
20461
    size_t i;
20462 20463
    int rc = 0;

20464
    for (i = 0; i < def->nserials; i++) {
20465 20466 20467 20468 20469 20470 20471 20472 20473
        if ((iter)(def,
                   def->serials[i],
                   opaque) < 0)
            rc = -1;

        if (abortOnError && rc != 0)
            goto done;
    }

20474
    for (i = 0; i < def->nparallels; i++) {
20475 20476 20477 20478 20479 20480 20481 20482 20483
        if ((iter)(def,
                   def->parallels[i],
                   opaque) < 0)
            rc = -1;

        if (abortOnError && rc != 0)
            goto done;
    }

20484
    for (i = 0; i < def->nchannels; i++) {
20485 20486 20487 20488 20489 20490 20491 20492
        if ((iter)(def,
                   def->channels[i],
                   opaque) < 0)
            rc = -1;

        if (abortOnError && rc != 0)
            goto done;
    }
20493
    for (i = 0; i < def->nconsoles; i++) {
20494
        if ((iter)(def,
20495
                   def->consoles[i],
20496 20497 20498 20499 20500 20501 20502
                   opaque) < 0)
            rc = -1;

        if (abortOnError && rc != 0)
            goto done;
    }

20503
 done:
20504 20505 20506 20507
    return rc;
}


20508 20509 20510 20511 20512
int
virDomainSmartcardDefForeach(virDomainDefPtr def,
                             bool abortOnError,
                             virDomainSmartcardDefIterator iter,
                             void *opaque)
E
Eric Blake 已提交
20513
{
20514
    size_t i;
E
Eric Blake 已提交
20515 20516
    int rc = 0;

20517
    for (i = 0; i < def->nsmartcards; i++) {
E
Eric Blake 已提交
20518 20519 20520 20521 20522 20523 20524 20525 20526
        if ((iter)(def,
                   def->smartcards[i],
                   opaque) < 0)
            rc = -1;

        if (abortOnError && rc != 0)
            goto done;
    }

20527
 done:
E
Eric Blake 已提交
20528 20529 20530 20531
    return rc;
}


20532
/* Call iter(disk, name, depth, opaque) for each element of disk and
20533
 * its backing chain in the pre-populated disk->src.backingStore.
20534 20535 20536
 * ignoreOpenFailure determines whether to warn about a chain that
 * mentions a backing file without also having metadata on that
 * file.  */
20537 20538 20539 20540 20541
int
virDomainDiskDefForeachPath(virDomainDiskDefPtr disk,
                            bool ignoreOpenFailure,
                            virDomainDiskDefPathIterator iter,
                            void *opaque)
20542 20543 20544
{
    int ret = -1;
    size_t depth = 0;
20545
    virStorageSourcePtr tmp;
20546
    char *brokenRaw = NULL;
20547

20548
    if (!ignoreOpenFailure) {
20549
        if (virStorageFileChainGetBroken(disk->src, &brokenRaw) < 0)
20550
            goto cleanup;
20551

20552
        if (brokenRaw) {
20553
            virReportError(VIR_ERR_INTERNAL_ERROR,
20554
                           _("unable to visit backing chain file %s"),
20555
                           brokenRaw);
20556 20557
            goto cleanup;
        }
20558 20559
    }

20560
    for (tmp = disk->src; tmp; tmp = tmp->backingStore) {
20561 20562 20563 20564 20565 20566 20567 20568 20569 20570
        int actualType = virStorageSourceGetActualType(tmp);
        /* execute the callback only for local storage */
        if (actualType != VIR_STORAGE_TYPE_NETWORK &&
            actualType != VIR_STORAGE_TYPE_VOLUME &&
            tmp->path) {
            if (iter(disk, tmp->path, depth, opaque) < 0)
                goto cleanup;
        }

        depth++;
20571
    }
20572 20573 20574

    ret = 0;

20575
 cleanup:
20576
    VIR_FREE(brokenRaw);
20577 20578
    return ret;
}
20579 20580


20581 20582 20583 20584
/* Copy src into a new definition; with the quality of the copy
 * depending on the migratable flag (false for transitions between
 * persistent and active, true for transitions across save files or
 * snapshots).  */
20585
virDomainDefPtr
20586 20587
virDomainDefCopy(virDomainDefPtr src,
                 virCapsPtr caps,
20588
                 virDomainXMLOptionPtr xmlopt,
20589
                 bool migratable)
20590 20591
{
    char *xml;
20592 20593 20594
    virDomainDefPtr ret;
    unsigned int write_flags = VIR_DOMAIN_XML_WRITE_FLAGS;
    unsigned int read_flags = VIR_DOMAIN_XML_READ_FLAGS;
20595

20596 20597
    if (migratable)
        write_flags |= VIR_DOMAIN_XML_INACTIVE | VIR_DOMAIN_XML_MIGRATABLE;
20598

20599
    /* Easiest to clone via a round-trip through XML.  */
20600
    if (!(xml = virDomainDefFormat(src, write_flags)))
20601 20602
        return NULL;

20603
    ret = virDomainDefParseString(xml, caps, xmlopt, -1, read_flags);
20604 20605 20606 20607

    VIR_FREE(xml);
    return ret;
}
J
Jiri Denemark 已提交
20608

20609
virDomainDefPtr
20610 20611 20612
virDomainObjCopyPersistentDef(virDomainObjPtr dom,
                              virCapsPtr caps,
                              virDomainXMLOptionPtr xmlopt)
20613 20614 20615
{
    virDomainDefPtr cur;

20616
    cur = virDomainObjGetPersistentDef(caps, xmlopt, dom);
20617
    return virDomainDefCopy(cur, caps, xmlopt, false);
20618 20619
}

J
Jiri Denemark 已提交
20620 20621 20622 20623 20624 20625 20626 20627 20628 20629 20630 20631 20632 20633 20634 20635 20636

virDomainState
virDomainObjGetState(virDomainObjPtr dom, int *reason)
{
    if (reason)
        *reason = dom->state.reason;

    return dom->state.state;
}


void
virDomainObjSetState(virDomainObjPtr dom, virDomainState state, int reason)
{
    int last = -1;

    switch (state) {
O
Osier Yang 已提交
20637 20638 20639 20640 20641 20642 20643 20644 20645 20646 20647 20648 20649 20650 20651 20652 20653 20654 20655 20656 20657 20658 20659 20660 20661 20662
    case VIR_DOMAIN_NOSTATE:
        last = VIR_DOMAIN_NOSTATE_LAST;
        break;
    case VIR_DOMAIN_RUNNING:
        last = VIR_DOMAIN_RUNNING_LAST;
        break;
    case VIR_DOMAIN_BLOCKED:
        last = VIR_DOMAIN_BLOCKED_LAST;
        break;
    case VIR_DOMAIN_PAUSED:
        last = VIR_DOMAIN_PAUSED_LAST;
        break;
    case VIR_DOMAIN_SHUTDOWN:
        last = VIR_DOMAIN_SHUTDOWN_LAST;
        break;
    case VIR_DOMAIN_SHUTOFF:
        last = VIR_DOMAIN_SHUTOFF_LAST;
        break;
    case VIR_DOMAIN_CRASHED:
        last = VIR_DOMAIN_CRASHED_LAST;
        break;
    case VIR_DOMAIN_PMSUSPENDED:
        last = VIR_DOMAIN_PMSUSPENDED_LAST;
        break;
    default:
        last = -1;
J
Jiri Denemark 已提交
20663 20664 20665 20666 20667 20668 20669 20670 20671 20672 20673 20674 20675 20676 20677 20678 20679 20680 20681 20682 20683 20684 20685 20686 20687 20688 20689 20690 20691 20692 20693 20694 20695
    }

    if (last < 0) {
        VIR_ERROR(_("invalid domain state: %d"), state);
        return;
    }

    dom->state.state = state;
    if (reason > 0 && reason < last)
        dom->state.reason = reason;
    else
        dom->state.reason = 0;
}


const char *
virDomainStateReasonToString(virDomainState state, int reason)
{
    switch (state) {
    case VIR_DOMAIN_NOSTATE:
        return virDomainNostateReasonTypeToString(reason);
    case VIR_DOMAIN_RUNNING:
        return virDomainRunningReasonTypeToString(reason);
    case VIR_DOMAIN_BLOCKED:
        return virDomainBlockedReasonTypeToString(reason);
    case VIR_DOMAIN_PAUSED:
        return virDomainPausedReasonTypeToString(reason);
    case VIR_DOMAIN_SHUTDOWN:
        return virDomainShutdownReasonTypeToString(reason);
    case VIR_DOMAIN_SHUTOFF:
        return virDomainShutoffReasonTypeToString(reason);
    case VIR_DOMAIN_CRASHED:
        return virDomainCrashedReasonTypeToString(reason);
20696 20697 20698 20699
    case VIR_DOMAIN_PMSUSPENDED:
        return virDomainPMSuspendedReasonTypeToString(reason);
    case VIR_DOMAIN_LAST:
        break;
J
Jiri Denemark 已提交
20700
    }
20701 20702
    VIR_WARN("Unexpected domain state: %d", state);
    return NULL;
J
Jiri Denemark 已提交
20703 20704 20705 20706 20707 20708 20709 20710 20711 20712 20713 20714 20715 20716 20717 20718 20719 20720 20721 20722 20723
}


int
virDomainStateReasonFromString(virDomainState state, const char *reason)
{
    switch (state) {
    case VIR_DOMAIN_NOSTATE:
        return virDomainNostateReasonTypeFromString(reason);
    case VIR_DOMAIN_RUNNING:
        return virDomainRunningReasonTypeFromString(reason);
    case VIR_DOMAIN_BLOCKED:
        return virDomainBlockedReasonTypeFromString(reason);
    case VIR_DOMAIN_PAUSED:
        return virDomainPausedReasonTypeFromString(reason);
    case VIR_DOMAIN_SHUTDOWN:
        return virDomainShutdownReasonTypeFromString(reason);
    case VIR_DOMAIN_SHUTOFF:
        return virDomainShutoffReasonTypeFromString(reason);
    case VIR_DOMAIN_CRASHED:
        return virDomainCrashedReasonTypeFromString(reason);
20724 20725 20726 20727
    case VIR_DOMAIN_PMSUSPENDED:
        return virDomainPMSuspendedReasonTypeFromString(reason);
    case VIR_DOMAIN_LAST:
        break;
J
Jiri Denemark 已提交
20728
    }
20729 20730
    VIR_WARN("Unexpected domain state: %d", state);
    return -1;
J
Jiri Denemark 已提交
20731
}
20732 20733 20734 20735 20736 20737 20738 20739 20740 20741 20742 20743 20744 20745 20746 20747 20748 20749


/* Some access functions to gloss over the difference between NetDef
 * (<interface>) and ActualNetDef (<actual>). If the NetDef has an
 * ActualNetDef, return the requested value from the ActualNetDef,
 * otherwise return the value from the NetDef.
 */

int
virDomainNetGetActualType(virDomainNetDefPtr iface)
{
    if (iface->type != VIR_DOMAIN_NET_TYPE_NETWORK)
        return iface->type;
    if (!iface->data.network.actual)
        return iface->type;
    return iface->data.network.actual->type;
}

20750
const char *
20751 20752 20753 20754
virDomainNetGetActualBridgeName(virDomainNetDefPtr iface)
{
    if (iface->type == VIR_DOMAIN_NET_TYPE_BRIDGE)
        return iface->data.bridge.brname;
20755 20756
    if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
        iface->data.network.actual &&
20757 20758
        (iface->data.network.actual->type == VIR_DOMAIN_NET_TYPE_BRIDGE ||
         iface->data.network.actual->type == VIR_DOMAIN_NET_TYPE_NETWORK))
20759 20760
        return iface->data.network.actual->data.bridge.brname;
    return NULL;
20761 20762
}

20763
const char *
20764 20765 20766 20767
virDomainNetGetActualDirectDev(virDomainNetDefPtr iface)
{
    if (iface->type == VIR_DOMAIN_NET_TYPE_DIRECT)
        return iface->data.direct.linkdev;
20768 20769
    if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
        iface->data.network.actual &&
20770
        iface->data.network.actual->type == VIR_DOMAIN_NET_TYPE_DIRECT)
20771 20772
        return iface->data.network.actual->data.direct.linkdev;
    return NULL;
20773 20774 20775 20776 20777 20778 20779
}

int
virDomainNetGetActualDirectMode(virDomainNetDefPtr iface)
{
    if (iface->type == VIR_DOMAIN_NET_TYPE_DIRECT)
        return iface->data.direct.mode;
20780 20781
    if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
        iface->data.network.actual &&
20782
        iface->data.network.actual->type == VIR_DOMAIN_NET_TYPE_DIRECT)
20783 20784
        return iface->data.network.actual->data.direct.mode;
    return 0;
20785 20786
}

20787 20788 20789 20790 20791
virDomainHostdevDefPtr
virDomainNetGetActualHostdev(virDomainNetDefPtr iface)
{
    if (iface->type == VIR_DOMAIN_NET_TYPE_HOSTDEV)
        return &iface->data.hostdev.def;
E
Eric Blake 已提交
20792
    if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
20793
        iface->data.network.actual &&
20794
        iface->data.network.actual->type == VIR_DOMAIN_NET_TYPE_HOSTDEV)
20795 20796 20797 20798
        return &iface->data.network.actual->data.hostdev.def;
    return NULL;
}

20799
virNetDevVPortProfilePtr
20800
virDomainNetGetActualVirtPortProfile(virDomainNetDefPtr iface)
20801
{
A
Ansis Atteka 已提交
20802 20803 20804
    switch (iface->type) {
    case VIR_DOMAIN_NET_TYPE_DIRECT:
    case VIR_DOMAIN_NET_TYPE_BRIDGE:
20805
    case VIR_DOMAIN_NET_TYPE_HOSTDEV:
20806
        return iface->virtPortProfile;
A
Ansis Atteka 已提交
20807 20808 20809 20810 20811 20812
    case VIR_DOMAIN_NET_TYPE_NETWORK:
        if (!iface->data.network.actual)
            return NULL;
        switch (iface->data.network.actual->type) {
        case VIR_DOMAIN_NET_TYPE_DIRECT:
        case VIR_DOMAIN_NET_TYPE_BRIDGE:
20813
        case VIR_DOMAIN_NET_TYPE_HOSTDEV:
20814
            return iface->data.network.actual->virtPortProfile;
A
Ansis Atteka 已提交
20815 20816 20817 20818
        default:
            return NULL;
        }
    default:
20819
        return NULL;
A
Ansis Atteka 已提交
20820
    }
20821
}
20822

20823
virNetDevBandwidthPtr
20824 20825
virDomainNetGetActualBandwidth(virDomainNetDefPtr iface)
{
20826 20827 20828
    /* if there is an ActualNetDef, *always* return
     * its bandwidth rather than the NetDef's bandwidth.
     */
E
Eric Blake 已提交
20829
    if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
20830
        iface->data.network.actual)
20831 20832 20833
        return iface->data.network.actual->bandwidth;
    return iface->bandwidth;
}
20834

20835 20836 20837
virNetDevVlanPtr
virDomainNetGetActualVlan(virDomainNetDefPtr iface)
{
20838 20839 20840 20841 20842
    virNetDevVlanPtr vlan = &iface->vlan;

    /* if there is an ActualNetDef, *always* return
     * its vlan rather than the NetDef's vlan.
     */
20843
    if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
20844 20845 20846 20847 20848 20849
        iface->data.network.actual)
        vlan = &iface->data.network.actual->vlan;

    if (vlan->nTags > 0)
        return vlan;
    return NULL;
20850
}
20851

20852 20853 20854 20855 20856 20857 20858 20859 20860 20861 20862 20863

bool
virDomainNetGetActualTrustGuestRxFilters(virDomainNetDefPtr iface)
{
    if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
        iface->data.network.actual)
        return (iface->data.network.actual->trustGuestRxFilters
                == VIR_TRISTATE_BOOL_YES);
    return iface->trustGuestRxFilters == VIR_TRISTATE_BOOL_YES;
}


20864
/* Return listens[i] from the appropriate union for the graphics
20865
 * type, or NULL if this is an unsuitable type, or the index is out of
20866
 * bounds. If force0 is TRUE, i == 0, and there is no listen array,
20867 20868
 * allocate one with a single item. */
static virDomainGraphicsListenDefPtr
20869
virDomainGraphicsGetListen(virDomainGraphicsDefPtr def, size_t i, bool force0)
20870
{
E
Eric Blake 已提交
20871 20872 20873
    if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC ||
        def->type == VIR_DOMAIN_GRAPHICS_TYPE_RDP ||
        def->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE) {
20874

20875
        if (!def->listens && (i == 0) && force0) {
20876
            if (VIR_ALLOC(def->listens) >= 0)
20877 20878 20879
                def->nListens = 1;
        }

20880
        if (!def->listens || (def->nListens <= i))
20881 20882
            return NULL;

20883
        return &def->listens[i];
20884 20885 20886 20887 20888 20889 20890 20891 20892 20893 20894 20895 20896 20897 20898 20899 20900 20901 20902 20903 20904
    }

    /* it's a type that has no listens array */
    return NULL;
}


/* Access functions for the fields in a virDomainGraphicsDef's
 * "listens" array.
 *
 * NB: For simple backward compatibility with existing code, any of
 * the "Set" functions will auto-create listens[0] to store the new
 * setting, when necessary. Auto-creation beyond the first item is not
 * supported.
 *
 * Return values: All "Get" functions return the requested item, or
 * 0/NULL. (in the case of returned const char *, the caller should
 * make a copy if they want to keep it around). All "Set" functions
 * return 0 on success, -1 on failure. */

int
20905
virDomainGraphicsListenGetType(virDomainGraphicsDefPtr def, size_t i)
20906 20907
{
    virDomainGraphicsListenDefPtr listenInfo
20908
        = virDomainGraphicsGetListen(def, i, false);
20909 20910 20911 20912 20913 20914 20915 20916 20917 20918 20919

    if (!listenInfo)
        return VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NONE;
    return listenInfo->type;
}


/* NB: This function assumes type has not previously been set. It
 * *will not* free any existing address or network based on a change
 * in value of type. */
int
20920
virDomainGraphicsListenSetType(virDomainGraphicsDefPtr def, size_t i, int val)
20921 20922
{
    virDomainGraphicsListenDefPtr listenInfo
20923
        = virDomainGraphicsGetListen(def, i, true);
20924 20925 20926 20927 20928 20929 20930 20931 20932

    if (!listenInfo)
        return -1;
    listenInfo->type = val;
    return 0;
}


const char *
20933
virDomainGraphicsListenGetAddress(virDomainGraphicsDefPtr def, size_t i)
20934 20935
{
    virDomainGraphicsListenDefPtr listenInfo
20936
        = virDomainGraphicsGetListen(def, i, false);
20937

20938
    /* even a network can have a listen address */
20939
    if (!listenInfo ||
20940 20941
        !(listenInfo->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS ||
          listenInfo->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK))
20942 20943 20944 20945 20946 20947
        return NULL;
    return listenInfo->address;
}


/* Make a copy of up to len characters of address, and store it in
20948
 * listens[i].address. If setType is true, set the listen's type
20949 20950 20951
 * to 'address', otherwise leave type alone. */
int
virDomainGraphicsListenSetAddress(virDomainGraphicsDefPtr def,
20952
                                  size_t i, const char *address,
20953 20954 20955
                                  int len, bool setType)
{
    virDomainGraphicsListenDefPtr listenInfo
20956
        = virDomainGraphicsGetListen(def, i, true);
20957 20958 20959 20960 20961 20962 20963 20964 20965 20966 20967 20968

    if (!listenInfo)
        return -1;

    if (setType)
        listenInfo->type = VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS;

    if (!address) {
        listenInfo->address = NULL;
        return 0;
    }

20969
    if (VIR_STRNDUP(listenInfo->address, address, len) < 0)
20970 20971 20972 20973 20974 20975
        return -1;
    return 0;
}


const char *
20976
virDomainGraphicsListenGetNetwork(virDomainGraphicsDefPtr def, size_t i)
20977 20978
{
    virDomainGraphicsListenDefPtr listenInfo
20979
        = virDomainGraphicsGetListen(def, i, false);
20980 20981 20982 20983 20984 20985 20986 20987 20988

    if (!listenInfo ||
        (listenInfo->type != VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK))
        return NULL;
    return listenInfo->network;
}


/* Make a copy of up to len characters of address, and store it in
20989
 * listens[i].network */
20990 20991
int
virDomainGraphicsListenSetNetwork(virDomainGraphicsDefPtr def,
20992
                                  size_t i, const char *network, int len)
20993 20994
{
    virDomainGraphicsListenDefPtr listenInfo
20995
        = virDomainGraphicsGetListen(def, i, true);
20996 20997 20998 20999 21000 21001 21002 21003 21004 21005 21006

    if (!listenInfo)
        return -1;

    listenInfo->type = VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK;

    if (!network) {
        listenInfo->network = NULL;
        return 0;
    }

21007
    if (VIR_STRNDUP(listenInfo->network, network, len) < 0)
21008 21009 21010
        return -1;
    return 0;
}
21011 21012 21013 21014 21015 21016 21017 21018 21019 21020 21021 21022 21023 21024 21025

/**
 * virDomainNetFind:
 * @def: domain's def
 * @device: could be the interface name or MAC address
 *
 * Finds a domain's net def, given the interface name or MAC address
 *
 * Returns a pointer to the net def or NULL if not found.
 */
virDomainNetDefPtr
virDomainNetFind(virDomainDefPtr def, const char *device)
{
    bool isMac = false;
    virDomainNetDefPtr net = NULL;
21026
    virMacAddr mac;
21027
    size_t i;
21028

21029
    if (virMacAddrParse(device, &mac) == 0)
21030 21031 21032 21033
        isMac = true;

    if (isMac) {
        for (i = 0; i < def->nnets; i++) {
21034
            if (virMacAddrCmp(&mac, &def->nets[i]->mac) == 0) {
21035 21036 21037 21038 21039 21040 21041 21042 21043 21044 21045 21046 21047 21048 21049
                net = def->nets[i];
                break;
            }
        }
    } else { /* ifname */
        for (i = 0; i < def->nnets; i++) {
            if (STREQ_NULLABLE(device, def->nets[i]->ifname)) {
                net = def->nets[i];
                break;
            }
        }
    }

    return net;
}
21050 21051 21052 21053 21054 21055 21056 21057 21058 21059 21060 21061 21062 21063 21064 21065

/**
 * virDomainDeviceDefCopy:
 * @caps: Capabilities
 * @def: Domain definition to which @src belongs
 * @src: source to be copied
 *
 * virDomainDeviceDefCopy does a deep copy of only the parts of a
 * DeviceDef that are valid when just the flag VIR_DOMAIN_XML_INACTIVE is
 * set. This means that any part of the device xml that is conditionally
 * parsed/formatted based on some other flag being set (or on the INACTIVE
 * flag being reset) *will not* be copied to the destination. Caveat emptor.
 *
 * Returns a pointer to copied @src or NULL in case of error.
 */
virDomainDeviceDefPtr
21066
virDomainDeviceDefCopy(virDomainDeviceDefPtr src,
21067
                       const virDomainDef *def,
21068 21069
                       virCapsPtr caps,
                       virDomainXMLOptionPtr xmlopt)
21070 21071 21072 21073 21074 21075 21076
{
    virDomainDeviceDefPtr ret = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int flags = VIR_DOMAIN_XML_INACTIVE;
    char *xmlStr = NULL;
    int rc = -1;

21077
    switch ((virDomainDeviceType) src->type) {
21078 21079 21080 21081 21082 21083 21084 21085 21086 21087 21088 21089 21090 21091 21092 21093 21094 21095 21096 21097 21098 21099 21100 21101 21102 21103 21104 21105 21106 21107 21108 21109 21110 21111 21112 21113 21114 21115 21116
    case VIR_DOMAIN_DEVICE_DISK:
        rc = virDomainDiskDefFormat(&buf, src->data.disk, flags);
        break;
    case VIR_DOMAIN_DEVICE_LEASE:
        rc = virDomainLeaseDefFormat(&buf, src->data.lease);
        break;
    case VIR_DOMAIN_DEVICE_FS:
        rc = virDomainFSDefFormat(&buf, src->data.fs, flags);
        break;
    case VIR_DOMAIN_DEVICE_NET:
        rc = virDomainNetDefFormat(&buf, src->data.net, flags);
        break;
    case VIR_DOMAIN_DEVICE_INPUT:
        rc = virDomainInputDefFormat(&buf, src->data.input, flags);
        break;
    case VIR_DOMAIN_DEVICE_SOUND:
        rc = virDomainSoundDefFormat(&buf, src->data.sound, flags);
        break;
    case VIR_DOMAIN_DEVICE_VIDEO:
        rc = virDomainVideoDefFormat(&buf, src->data.video, flags);
        break;
    case VIR_DOMAIN_DEVICE_HOSTDEV:
        rc = virDomainHostdevDefFormat(&buf, src->data.hostdev, flags);
        break;
    case VIR_DOMAIN_DEVICE_WATCHDOG:
        rc = virDomainWatchdogDefFormat(&buf, src->data.watchdog, flags);
        break;
    case VIR_DOMAIN_DEVICE_CONTROLLER:
        rc = virDomainControllerDefFormat(&buf, src->data.controller, flags);
        break;
    case VIR_DOMAIN_DEVICE_GRAPHICS:
        rc = virDomainGraphicsDefFormat(&buf, src->data.graphics, flags);
        break;
    case VIR_DOMAIN_DEVICE_HUB:
        rc = virDomainHubDefFormat(&buf, src->data.hub, flags);
        break;
    case VIR_DOMAIN_DEVICE_REDIRDEV:
        rc = virDomainRedirdevDefFormat(&buf, src->data.redirdev, flags);
        break;
21117 21118 21119
    case VIR_DOMAIN_DEVICE_RNG:
        rc = virDomainRNGDefFormat(&buf, src->data.rng, flags);
        break;
21120 21121 21122
    case VIR_DOMAIN_DEVICE_CHR:
        rc = virDomainChrDefFormat(&buf, src->data.chr, flags);
        break;
21123 21124 21125
    case VIR_DOMAIN_DEVICE_TPM:
        rc = virDomainTPMDefFormat(&buf, src->data.tpm, flags);
        break;
21126 21127 21128
    case VIR_DOMAIN_DEVICE_PANIC:
        rc = virDomainPanicDefFormat(&buf, src->data.panic);
        break;
21129 21130 21131
    case VIR_DOMAIN_DEVICE_NONE:
    case VIR_DOMAIN_DEVICE_SMARTCARD:
    case VIR_DOMAIN_DEVICE_MEMBALLOON:
L
Li Zhang 已提交
21132
    case VIR_DOMAIN_DEVICE_NVRAM:
21133
    case VIR_DOMAIN_DEVICE_SHMEM:
21134
    case VIR_DOMAIN_DEVICE_LAST:
21135 21136 21137 21138
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Copying definition of '%d' type "
                         "is not implemented yet."),
                       src->type);
21139 21140 21141 21142 21143 21144 21145
        goto cleanup;
    }

    if (rc < 0)
        goto cleanup;

    xmlStr = virBufferContentAndReset(&buf);
21146
    ret = virDomainDeviceDefParse(xmlStr, def, caps, xmlopt, flags);
21147

21148
 cleanup:
21149 21150 21151
    VIR_FREE(xmlStr);
    return ret;
}
O
Osier Yang 已提交
21152 21153 21154 21155

struct virDomainListData {
    virConnectPtr conn;
    virDomainPtr *domains;
21156
    virDomainObjListFilter filter;
O
Osier Yang 已提交
21157 21158 21159 21160 21161 21162 21163 21164 21165 21166 21167 21168 21169 21170 21171 21172 21173 21174
    unsigned int flags;
    int ndomains;
    bool error;
};

#define MATCH(FLAG) (data->flags & (FLAG))
static void
virDomainListPopulate(void *payload,
                      const void *name ATTRIBUTE_UNUSED,
                      void *opaque)
{
    struct virDomainListData *data = opaque;
    virDomainObjPtr vm = payload;
    virDomainPtr dom;

    if (data->error)
        return;

21175
    virObjectLock(vm);
O
Osier Yang 已提交
21176 21177
    /* check if the domain matches the filter */

21178 21179 21180 21181 21182
    /* filter by the callback function (access control checks) */
    if (data->filter != NULL &&
        !data->filter(data->conn, vm->def))
        goto cleanup;

O
Osier Yang 已提交
21183 21184 21185 21186 21187 21188 21189 21190 21191 21192 21193 21194 21195 21196 21197 21198 21199 21200 21201 21202 21203 21204 21205 21206 21207 21208 21209 21210 21211 21212 21213 21214 21215 21216 21217 21218 21219 21220 21221 21222 21223 21224 21225 21226 21227 21228 21229 21230
    /* filter by active state */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) &&
        !((MATCH(VIR_CONNECT_LIST_DOMAINS_ACTIVE) &&
           virDomainObjIsActive(vm)) ||
          (MATCH(VIR_CONNECT_LIST_DOMAINS_INACTIVE) &&
           !virDomainObjIsActive(vm))))
        goto cleanup;

    /* filter by persistence */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_PERSISTENT) &&
        !((MATCH(VIR_CONNECT_LIST_DOMAINS_PERSISTENT) &&
           vm->persistent) ||
          (MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
           !vm->persistent)))
        goto cleanup;

    /* filter by domain state */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE)) {
        int st = virDomainObjGetState(vm, NULL);
        if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_RUNNING) &&
               st == VIR_DOMAIN_RUNNING) ||
              (MATCH(VIR_CONNECT_LIST_DOMAINS_PAUSED) &&
               st == VIR_DOMAIN_PAUSED) ||
              (MATCH(VIR_CONNECT_LIST_DOMAINS_SHUTOFF) &&
               st == VIR_DOMAIN_SHUTOFF) ||
              (MATCH(VIR_CONNECT_LIST_DOMAINS_OTHER) &&
               (st != VIR_DOMAIN_RUNNING &&
                st != VIR_DOMAIN_PAUSED &&
                st != VIR_DOMAIN_SHUTOFF))))
            goto cleanup;
    }

    /* filter by existence of managed save state */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_MANAGEDSAVE) &&
        !((MATCH(VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE) &&
           vm->hasManagedSave) ||
          (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE) &&
           !vm->hasManagedSave)))
            goto cleanup;

    /* filter by autostart option */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART) &&
        !((MATCH(VIR_CONNECT_LIST_DOMAINS_AUTOSTART) && vm->autostart) ||
          (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART) && !vm->autostart)))
        goto cleanup;

    /* filter by snapshot existence */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_SNAPSHOT)) {
21231
        int nsnap = virDomainSnapshotObjListNum(vm->snapshots, NULL, 0);
O
Osier Yang 已提交
21232 21233 21234 21235 21236 21237 21238 21239
        if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) && nsnap > 0) ||
              (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) && nsnap <= 0)))
            goto cleanup;
    }

    /* just count the machines */
    if (!data->domains) {
        data->ndomains++;
P
Pavel Hrdina 已提交
21240
        goto cleanup;
O
Osier Yang 已提交
21241 21242 21243 21244 21245 21246 21247 21248 21249 21250 21251
    }

    if (!(dom = virGetDomain(data->conn, vm->def->name, vm->def->uuid))) {
        data->error = true;
        goto cleanup;
    }

    dom->id = vm->def->id;

    data->domains[data->ndomains++] = dom;

21252
 cleanup:
21253
    virObjectUnlock(vm);
O
Osier Yang 已提交
21254 21255 21256 21257
    return;
}
#undef MATCH

21258 21259 21260 21261 21262 21263 21264 21265 21266 21267 21268 21269 21270 21271 21272 21273 21274 21275 21276 21277 21278 21279 21280

/**
 * virDomainListFree:
 * @list: list of domains to free
 *
 * Frees a NULL-terminated list of domains without messing with currently
 * set libvirt errors.
 */
void
virDomainListFree(virDomainPtr *list)
{
    virDomainPtr *next;

    if (!list)
        return;

    for (next = list; *next; next++)
        virObjectUnref(*next);

    VIR_FREE(list);
}


O
Osier Yang 已提交
21281
int
21282 21283 21284
virDomainObjListExport(virDomainObjListPtr doms,
                       virConnectPtr conn,
                       virDomainPtr **domains,
21285
                       virDomainObjListFilter filter,
21286
                       unsigned int flags)
O
Osier Yang 已提交
21287 21288 21289
{
    int ret = -1;

21290 21291 21292 21293 21294
    struct virDomainListData data = {
        conn, NULL,
        filter,
        flags, 0, false
    };
O
Osier Yang 已提交
21295

21296
    virObjectLock(doms);
21297 21298 21299
    if (domains &&
        VIR_ALLOC_N(data.domains, virHashSize(doms->objs) + 1) < 0)
        goto cleanup;
O
Osier Yang 已提交
21300

21301
    virHashForEach(doms->objs, virDomainListPopulate, &data);
O
Osier Yang 已提交
21302 21303 21304 21305 21306 21307 21308 21309 21310 21311 21312 21313 21314

    if (data.error)
        goto cleanup;

    if (data.domains) {
        /* trim the array to the final size */
        ignore_value(VIR_REALLOC_N(data.domains, data.ndomains + 1));
        *domains = data.domains;
        data.domains = NULL;
    }

    ret = data.ndomains;

21315
 cleanup:
21316
    virDomainListFree(data.domains);
21317
    virObjectUnlock(doms);
O
Osier Yang 已提交
21318 21319 21320
    return ret;
}

21321 21322 21323
virSecurityLabelDefPtr
virDomainDefGetSecurityLabelDef(virDomainDefPtr def, const char *model)
{
21324
    size_t i;
21325
    virSecurityLabelDefPtr seclabel = NULL;
21326 21327 21328 21329 21330 21331 21332 21333 21334 21335 21336

    if (def == NULL || model == NULL)
        return NULL;

    for (i = 0; i < def->nseclabels; i++) {
        if (def->seclabels[i]->model == NULL)
            continue;
        if (STREQ(def->seclabels[i]->model, model))
            return def->seclabels[i];
    }

21337
    return seclabel;
21338 21339 21340
}


21341 21342 21343
virSecurityDeviceLabelDefPtr
virDomainChrDefGetSecurityLabelDef(virDomainChrDefPtr def, const char *model)
{
21344
    size_t i;
21345 21346 21347 21348 21349 21350 21351 21352 21353 21354 21355

    if (def == NULL)
        return NULL;

    for (i = 0; i < def->nseclabels; i++) {
        if (STREQ_NULLABLE(def->seclabels[i]->model, model))
            return def->seclabels[i];
    }
    return NULL;
}

21356 21357 21358 21359 21360 21361 21362 21363 21364 21365 21366 21367 21368 21369 21370 21371 21372 21373 21374 21375 21376 21377 21378 21379

typedef struct {
    const char *devAlias;
    virDomainDeviceDefPtr dev;
} virDomainDefFindDeviceCallbackData;

static int
virDomainDefFindDeviceCallback(virDomainDefPtr def ATTRIBUTE_UNUSED,
                               virDomainDeviceDefPtr dev,
                               virDomainDeviceInfoPtr info,
                               void *opaque)
{
    virDomainDefFindDeviceCallbackData *data = opaque;

    if (STREQ_NULLABLE(info->alias, data->devAlias)) {
        *data->dev = *dev;
        return -1;
    }
    return 0;
}

int
virDomainDefFindDevice(virDomainDefPtr def,
                       const char *devAlias,
21380 21381
                       virDomainDeviceDefPtr dev,
                       bool reportError)
21382 21383 21384 21385 21386 21387 21388 21389
{
    virDomainDefFindDeviceCallbackData data = { devAlias, dev };

    dev->type = VIR_DOMAIN_DEVICE_NONE;
    virDomainDeviceInfoIterateInternal(def, virDomainDefFindDeviceCallback,
                                       true, &data);

    if (dev->type == VIR_DOMAIN_DEVICE_NONE) {
21390 21391 21392 21393 21394 21395
        if (reportError) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("no device found with alias %s"), devAlias);
        } else {
            VIR_DEBUG("no device found with alias %s", devAlias);
        }
21396 21397 21398 21399 21400
        return -1;
    }

    return 0;
}
21401 21402 21403 21404 21405 21406 21407 21408 21409 21410 21411

/**
 * virDomainDiskSourceIsBlockType:
 *
 * Check if the disk *source* is of block type. This just tries
 * to check from the type of disk def, not to probe the underlying
 * storage.
 *
 * Return true if its source is block type, or false otherwise.
 */
bool
21412
virDomainDiskSourceIsBlockType(virStorageSourcePtr src)
21413
{
21414
    if (!src->path)
21415 21416
        return false;

21417
    if (src->type == VIR_STORAGE_TYPE_BLOCK)
21418 21419 21420 21421 21422
        return true;

    /* For volume types, check the srcpool.
     * If it's a block type source pool, then it's possible
     */
21423 21424 21425
    if (src->type == VIR_STORAGE_TYPE_VOLUME &&
        src->srcpool &&
        src->srcpool->voltype == VIR_STORAGE_VOL_BLOCK) {
21426 21427 21428 21429
        /* We don't think the volume accessed by remote URI is
         * block type source, since we can't/shouldn't manage it
         * (e.g. set sgio=filtered|unfiltered for it) in libvirt.
         */
21430 21431
         if (src->srcpool->pooltype == VIR_STORAGE_POOL_ISCSI &&
             src->srcpool->mode == VIR_STORAGE_SOURCE_POOL_MODE_DIRECT)
21432 21433
             return false;

21434 21435 21436 21437
        return true;
    }
    return false;
}
21438 21439 21440 21441 21442 21443 21444 21445 21446 21447 21448 21449 21450 21451 21452 21453


char *
virDomainObjGetMetadata(virDomainObjPtr vm,
                        int type,
                        const char *uri ATTRIBUTE_UNUSED,
                        virCapsPtr caps,
                        virDomainXMLOptionPtr xmlopt,
                        unsigned int flags)
{
    virDomainDefPtr def;
    char *ret = NULL;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, NULL);

21454 21455 21456 21457 21458 21459
    if (type >= VIR_DOMAIN_METADATA_LAST) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unknown metadata type '%d'"), type);
        goto cleanup;
    }

21460 21461 21462 21463 21464 21465 21466 21467 21468
    if (virDomainLiveConfigHelperMethod(caps, xmlopt, vm, &flags, &def) < 0)
        goto cleanup;

    /* use correct domain definition according to flags */
    if (flags & VIR_DOMAIN_AFFECT_LIVE)
        def = vm->def;

    switch ((virDomainMetadataType) type) {
    case VIR_DOMAIN_METADATA_DESCRIPTION:
21469 21470
        if (VIR_STRDUP(ret, def->description) < 0)
            goto cleanup;
21471 21472 21473
        break;

    case VIR_DOMAIN_METADATA_TITLE:
21474 21475
        if (VIR_STRDUP(ret, def->title) < 0)
            goto cleanup;
21476 21477 21478
        break;

    case VIR_DOMAIN_METADATA_ELEMENT:
21479 21480 21481 21482 21483
        if (!def->metadata)
            break;

        if (virXMLExtractNamespaceXML(def->metadata, uri, &ret) < 0)
            goto cleanup;
21484 21485
        break;

21486
    /* coverity[dead_error_begin] */
21487
    case VIR_DOMAIN_METADATA_LAST:
21488 21489 21490
        break;
    }

21491
    if (!ret)
21492 21493 21494
        virReportError(VIR_ERR_NO_DOMAIN_METADATA, "%s",
                       _("Requested metadata element is not present"));

21495
 cleanup:
21496 21497
    return ret;
}
21498

21499 21500 21501 21502 21503

static int
virDomainDefSetMetadata(virDomainDefPtr def,
                        int type,
                        const char *metadata,
21504 21505
                        const char *key,
                        const char *uri)
21506
{
21507 21508
    xmlDocPtr doc = NULL;
    xmlNodePtr old;
21509
    xmlNodePtr new = NULL;
21510
    char *tmp;
21511 21512
    int ret = -1;

21513 21514 21515 21516 21517 21518
    if (type >= VIR_DOMAIN_METADATA_LAST) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unknown metadata type '%d'"), type);
        goto cleanup;
    }

21519 21520
    switch ((virDomainMetadataType) type) {
    case VIR_DOMAIN_METADATA_DESCRIPTION:
21521
        if (VIR_STRDUP(tmp, metadata) < 0)
21522
            goto cleanup;
21523 21524 21525

        VIR_FREE(def->description);
        def->description = tmp;
21526 21527 21528
        break;

    case VIR_DOMAIN_METADATA_TITLE:
21529
        if (VIR_STRDUP(tmp, metadata) < 0)
21530
            goto cleanup;
21531 21532 21533

        VIR_FREE(def->title);
        def->title = tmp;
21534 21535 21536
        break;

    case VIR_DOMAIN_METADATA_ELEMENT:
21537 21538 21539 21540 21541 21542 21543 21544 21545 21546 21547 21548 21549 21550 21551 21552 21553 21554 21555 21556 21557 21558 21559 21560 21561 21562 21563
        if (metadata) {
            /* parse and modify the xml from the user */
            if (!(doc = virXMLParseString(metadata, _("(metadata_xml)"))))
                goto cleanup;

            if (virXMLInjectNamespace(doc->children, uri, key) < 0)
                goto cleanup;

            /* create the root node if needed */
            if (!def->metadata &&
                !(def->metadata = xmlNewNode(NULL, (unsigned char *)"metadata"))) {
                virReportOOMError();
                goto cleanup;
            }

            if (!(new = xmlCopyNode(doc->children, 1))) {
                virReportOOMError();
                goto cleanup;
            }
        }

        /* remove possible other nodes sharing the namespace */
        while ((old = virXMLFindChildNodeByNs(def->metadata, uri))) {
            xmlUnlinkNode(old);
            xmlFreeNode(old);
        }

21564 21565
        if (new &&
            !(xmlAddChild(def->metadata, new))) {
21566 21567 21568 21569
            xmlFreeNode(new);
            virReportOOMError();
            goto cleanup;
        }
21570 21571
        break;

21572
    /* coverity[dead_error_begin] */
21573
    case VIR_DOMAIN_METADATA_LAST:
21574 21575 21576 21577 21578
        break;
    }

    ret = 0;

21579
 cleanup:
21580
    xmlFreeDoc(doc);
21581 21582 21583 21584
    return ret;
}


21585 21586 21587 21588
int
virDomainObjSetMetadata(virDomainObjPtr vm,
                        int type,
                        const char *metadata,
21589 21590
                        const char *key,
                        const char *uri,
21591 21592
                        virCapsPtr caps,
                        virDomainXMLOptionPtr xmlopt,
21593
                        const char *stateDir,
21594 21595 21596 21597 21598 21599 21600 21601 21602 21603
                        const char *configDir,
                        unsigned int flags)
{
    virDomainDefPtr persistentDef;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

    if (virDomainLiveConfigHelperMethod(caps, xmlopt, vm, &flags,
                                        &persistentDef) < 0)
21604
        return -1;
21605

21606
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
21607 21608
        if (virDomainDefSetMetadata(vm->def, type, metadata, key, uri) < 0)
            return -1;
21609

21610 21611 21612 21613
        if (virDomainSaveStatus(xmlopt, stateDir, vm) < 0)
            return -1;
    }

21614
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
21615 21616
        if (virDomainDefSetMetadata(persistentDef, type, metadata, key,
                                    uri) < 0)
21617
            return -1;
21618 21619

        if (virDomainSaveConfig(configDir, persistentDef) < 0)
21620
            return -1;
21621 21622
    }

21623
    return 0;
21624
}
21625 21626 21627 21628 21629 21630 21631 21632 21633 21634 21635 21636 21637


bool
virDomainDefNeedsPlacementAdvice(virDomainDefPtr def)
{
    if (def->placement_mode == VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO)
        return true;

    if (virDomainNumatuneHasPlacementAuto(def->numatune))
        return true;

    return false;
}