domain_conf.c 759.4 KB
Newer Older
1 2 3
/*
 * domain_conf.c: domain XML processing
 *
4
 * Copyright (C) 2006-2016 Red Hat, Inc.
5
 * Copyright (C) 2006-2008 Daniel P. Berrange
6
 * Copyright (c) 2015 SUSE LINUX Products GmbH, Nuernberg, Germany.
7 8 9 10 11 12 13 14 15 16 17 18
 *
 * 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
19
 * License along with this library.  If not, see
O
Osier Yang 已提交
20
 * <http://www.gnu.org/licenses/>.
21 22 23 24 25 26
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

27 28 29
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
30

31
#include "configmake.h"
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 "virxml.h"
39
#include "viruuid.h"
40
#include "virbuffer.h"
41
#include "virlog.h"
42
#include "nwfilter_conf.h"
43
#include "storage_conf.h"
44
#include "virstoragefile.h"
E
Eric Blake 已提交
45
#include "virfile.h"
46
#include "virbitmap.h"
M
Matthias Bolte 已提交
47
#include "count-one-bits.h"
48
#include "secret_conf.h"
49 50
#include "netdev_vport_profile_conf.h"
#include "netdev_bandwidth_conf.h"
51
#include "netdev_vlan_conf.h"
52
#include "device_conf.h"
53
#include "network_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");

61 62
/* This structure holds various callbacks and data needed
 * while parsing and creating domain XMLs */
63
struct _virDomainXMLOption {
64 65
    virObject parent;

66 67 68
    /* XML parser callbacks and defaults */
    virDomainDefParserConfig config;

69 70 71 72 73
    /* domain private data management callbacks */
    virDomainXMLPrivateDataCallbacks privateData;

    /* XML namespace callbacks */
    virDomainXMLNamespace ns;
74 75 76 77 78 79 80
};

#define VIR_DOMAIN_DEF_FORMAT_COMMON_FLAGS             \
    (VIR_DOMAIN_DEF_FORMAT_SECURE |                    \
     VIR_DOMAIN_DEF_FORMAT_INACTIVE |                  \
     VIR_DOMAIN_DEF_FORMAT_UPDATE_CPU |                \
     VIR_DOMAIN_DEF_FORMAT_MIGRATABLE)
81

82 83 84 85 86
VIR_ENUM_IMPL(virDomainTaint, VIR_DOMAIN_TAINT_LAST,
              "custom-argv",
              "custom-monitor",
              "high-privileges",
              "shell-scripts",
87
              "disk-probing",
88
              "external-launch",
89
              "host-cpu",
90
              "hook-script",
91 92
              "cdrom-passthrough",
              "custom-dtb");
93

94
VIR_ENUM_IMPL(virDomainVirt, VIR_DOMAIN_VIRT_LAST,
95
              "none",
96 97 98 99 100 101 102 103 104
              "qemu",
              "kqemu",
              "kvm",
              "xen",
              "lxc",
              "uml",
              "openvz",
              "test",
              "vmware",
105
              "hyperv",
D
Daniel Veillard 已提交
106
              "vbox",
D
Dmitry Guryanov 已提交
107
              "phyp",
R
Roman Bogorodskiy 已提交
108
              "parallels",
109 110
              "bhyve",
              "vz")
111

112 113 114 115 116
VIR_ENUM_IMPL(virDomainOS, VIR_DOMAIN_OSTYPE_LAST,
              "hvm",
              "xen",
              "linux",
              "exe",
117
              "uml")
118

119 120 121 122 123 124 125 126 127
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 已提交
128
              "pae",
129
              "hap",
130
              "viridian",
131
              "privnet",
132
              "hyperv",
133
              "kvm",
134
              "pvspinlock",
135
              "capabilities",
136
              "pmu",
M
Michal Privoznik 已提交
137 138
              "vmport",
              "gic")
139

140 141 142 143 144
VIR_ENUM_IMPL(virDomainCapabilitiesPolicy, VIR_DOMAIN_CAPABILITIES_POLICY_LAST,
              "default",
              "allow",
              "deny")

145
VIR_ENUM_IMPL(virDomainHyperv, VIR_DOMAIN_HYPERV_LAST,
146 147 148
              "relaxed",
              "vapic",
              "spinlocks")
149

150 151 152
VIR_ENUM_IMPL(virDomainKVM, VIR_DOMAIN_KVM_LAST,
              "hidden")

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
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")

192 193 194 195 196 197
VIR_ENUM_IMPL(virDomainLifecycle, VIR_DOMAIN_LIFECYCLE_LAST,
              "destroy",
              "restart",
              "rename-restart",
              "preserve")

198 199 200 201 202 203 204 205
VIR_ENUM_IMPL(virDomainLifecycleCrash, VIR_DOMAIN_LIFECYCLE_CRASH_LAST,
              "destroy",
              "restart",
              "rename-restart",
              "preserve",
              "coredump-destroy",
              "coredump-restart")

206 207 208 209 210 211 212
VIR_ENUM_IMPL(virDomainLockFailure, VIR_DOMAIN_LOCK_FAILURE_LAST,
              "default",
              "poweroff",
              "restart",
              "pause",
              "ignore")

213
VIR_ENUM_IMPL(virDomainDevice, VIR_DOMAIN_DEVICE_LAST,
214
              "none",
215
              "disk",
216
              "lease",
217 218 219 220
              "filesystem",
              "interface",
              "input",
              "sound",
221
              "video",
R
Richard Jones 已提交
222
              "hostdev",
223
              "watchdog",
224
              "controller",
M
Marc-André Lureau 已提交
225
              "graphics",
226
              "hub",
227 228 229
              "redirdev",
              "smartcard",
              "chr",
230
              "memballoon",
L
Li Zhang 已提交
231
              "nvram",
232
              "rng",
233
              "shmem",
234
              "tpm",
235 236
              "panic",
              "memory")
237

238 239
VIR_ENUM_IMPL(virDomainDeviceAddress, VIR_DOMAIN_DEVICE_ADDRESS_TYPE_LAST,
              "none",
240
              "pci",
241
              "drive",
E
Eric Blake 已提交
242
              "virtio-serial",
243
              "ccid",
244
              "usb",
245
              "spapr-vio",
246
              "virtio-s390",
247
              "ccw",
H
Hu Tao 已提交
248
              "virtio-mmio",
249 250
              "isa",
              "dimm")
251

252 253 254
VIR_ENUM_IMPL(virDomainDiskDevice, VIR_DOMAIN_DISK_DEVICE_LAST,
              "disk",
              "cdrom",
255 256
              "floppy",
              "lun")
257

J
J.B. Joret 已提交
258 259 260 261 262 263
VIR_ENUM_IMPL(virDomainDiskGeometryTrans, VIR_DOMAIN_DISK_TRANS_LAST,
              "default",
              "none",
              "auto",
              "lba")

264 265 266 267 268
VIR_ENUM_IMPL(virDomainDiskBus, VIR_DOMAIN_DISK_BUS_LAST,
              "ide",
              "fdc",
              "scsi",
              "virtio",
269
              "xen",
270
              "usb",
271
              "uml",
272 273
              "sata",
              "sd")
274

275 276 277 278
VIR_ENUM_IMPL(virDomainDiskCache, VIR_DOMAIN_DISK_CACHE_LAST,
              "default",
              "none",
              "writethrough",
279
              "writeback",
280 281
              "directsync",
              "unsafe")
282

283 284 285
VIR_ENUM_IMPL(virDomainDiskErrorPolicy, VIR_DOMAIN_DISK_ERROR_POLICY_LAST,
              "default",
              "stop",
286
              "report",
287 288
              "ignore",
              "enospace")
289

M
Matthias Dahl 已提交
290 291 292 293
VIR_ENUM_IMPL(virDomainDiskIo, VIR_DOMAIN_DISK_IO_LAST,
              "default",
              "native",
              "threads")
O
Osier Yang 已提交
294

295
VIR_ENUM_IMPL(virDomainDeviceSGIO, VIR_DOMAIN_DEVICE_SGIO_LAST,
O
Osier Yang 已提交
296 297 298 299
              "default",
              "filtered",
              "unfiltered")

300 301 302 303
VIR_ENUM_IMPL(virDomainController, VIR_DOMAIN_CONTROLLER_TYPE_LAST,
              "ide",
              "fdc",
              "scsi",
304
              "sata",
E
Eric Blake 已提交
305
              "virtio-serial",
306
              "ccid",
J
Ján Tomko 已提交
307 308 309 310 311
              "usb",
              "pci")

VIR_ENUM_IMPL(virDomainControllerModelPCI, VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST,
              "pci-root",
L
Laine Stump 已提交
312
              "pcie-root",
313
              "pci-bridge",
314
              "dmi-to-pci-bridge",
315
              "pcie-root-port",
316 317
              "pcie-switch-upstream-port",
              "pcie-switch-downstream-port")
318

319 320 321 322
VIR_ENUM_IMPL(virDomainControllerPCIModelName,
              VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_LAST,
              "none",
              "pci-bridge",
323
              "i82801b11-bridge",
324
              "ioh3420",
325 326
              "x3130-upstream",
              "xio3130-downstream")
327

328
VIR_ENUM_IMPL(virDomainControllerModelSCSI, VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LAST,
329
              "auto",
330 331
              "buslogic",
              "lsilogic",
332
              "lsisas1068",
333
              "vmpvscsi",
334
              "ibmvscsi",
335 336
              "virtio-scsi",
              "lsisas1078");
337

M
Marc-André Lureau 已提交
338 339 340 341 342 343 344 345 346
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 已提交
347
              "pci-ohci",
348 349
              "nec-xhci",
              "none")
M
Marc-André Lureau 已提交
350

351 352 353 354
VIR_ENUM_IMPL(virDomainFS, VIR_DOMAIN_FS_TYPE_LAST,
              "mount",
              "block",
              "file",
355
              "template",
356 357
              "ram",
              "bind")
358

359
VIR_ENUM_IMPL(virDomainFSDriver, VIR_DOMAIN_FS_DRIVER_TYPE_LAST,
360 361
              "default",
              "path",
362
              "handle",
363
              "loop",
D
Dmitry Guryanov 已提交
364 365
              "nbd",
              "ploop")
366

367 368 369 370 371
VIR_ENUM_IMPL(virDomainFSAccessMode, VIR_DOMAIN_FS_ACCESSMODE_LAST,
              "passthrough",
              "mapped",
              "squash")

372 373 374
VIR_ENUM_IMPL(virDomainFSWrpolicy, VIR_DOMAIN_FS_WRPOLICY_LAST,
              "default",
              "immediate")
375

376 377 378
VIR_ENUM_IMPL(virDomainNet, VIR_DOMAIN_NET_TYPE_LAST,
              "user",
              "ethernet",
M
Michele Paolino 已提交
379
              "vhostuser",
380 381 382 383
              "server",
              "client",
              "mcast",
              "network",
D
Daniel Veillard 已提交
384
              "bridge",
385
              "internal",
386
              "direct",
387 388
              "hostdev",
              "udp")
389

390 391 392 393 394
VIR_ENUM_IMPL(virDomainNetBackend, VIR_DOMAIN_NET_BACKEND_TYPE_LAST,
              "default",
              "qemu",
              "vhost")

395 396 397 398 399
VIR_ENUM_IMPL(virDomainNetVirtioTxMode, VIR_DOMAIN_NET_VIRTIO_TX_MODE_LAST,
              "default",
              "iothread",
              "timer")

400 401 402 403 404
VIR_ENUM_IMPL(virDomainNetInterfaceLinkState, VIR_DOMAIN_NET_INTERFACE_LINK_STATE_LAST,
              "default",
              "up",
              "down")

405 406 407 408 409
VIR_ENUM_IMPL(virDomainChrDeviceState, VIR_DOMAIN_CHR_DEVICE_STATE_LAST,
              "default",
              "connected",
              "disconnected");

G
Guannan Ren 已提交
410 411 412
VIR_ENUM_IMPL(virDomainChrSerialTarget,
              VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_LAST,
              "isa-serial",
M
Michal Privoznik 已提交
413 414
              "usb-serial",
              "pci-serial")
G
Guannan Ren 已提交
415

416 417
VIR_ENUM_IMPL(virDomainChrChannelTarget,
              VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_LAST,
418
              "none",
419 420 421
              "guestfwd",
              "virtio")

422 423
VIR_ENUM_IMPL(virDomainChrConsoleTarget,
              VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_LAST,
424
              "none",
425 426
              "serial",
              "xen",
C
Cole Robinson 已提交
427
              "uml",
428 429
              "virtio",
              "lxc",
430 431 432
              "openvz",
              "sclp",
              "sclplm")
433

434
VIR_ENUM_IMPL(virDomainChrDevice, VIR_DOMAIN_CHR_DEVICE_TYPE_LAST,
435 436
              "parallel",
              "serial",
437
              "console",
438
              "channel")
439

440 441 442 443 444 445 446 447 448 449
VIR_ENUM_IMPL(virDomainChr, VIR_DOMAIN_CHR_TYPE_LAST,
              "null",
              "vc",
              "pty",
              "dev",
              "file",
              "pipe",
              "stdio",
              "udp",
              "tcp",
450
              "unix",
451
              "spicevmc",
452 453
              "spiceport",
              "nmdm")
454

455 456 457 458 459 460
VIR_ENUM_IMPL(virDomainChrTcpProtocol, VIR_DOMAIN_CHR_TCP_PROTOCOL_LAST,
              "raw",
              "telnet",
              "telnets",
              "tls")

E
Eric Blake 已提交
461 462
VIR_ENUM_IMPL(virDomainChrSpicevmc, VIR_DOMAIN_CHR_SPICEVMC_LAST,
              "vdagent",
463 464
              "smartcard",
              "usbredir")
E
Eric Blake 已提交
465

E
Eric Blake 已提交
466 467 468 469 470
VIR_ENUM_IMPL(virDomainSmartcard, VIR_DOMAIN_SMARTCARD_TYPE_LAST,
              "host",
              "host-certificates",
              "passthrough")

471 472 473 474
VIR_ENUM_IMPL(virDomainSoundCodec, VIR_DOMAIN_SOUND_CODEC_TYPE_LAST,
              "duplex",
              "micro")

475 476 477
VIR_ENUM_IMPL(virDomainSoundModel, VIR_DOMAIN_SOUND_MODEL_LAST,
              "sb16",
              "es1370",
478
              "pcspk",
479
              "ac97",
480
              "ich6",
481 482
              "ich9",
              "usb")
483

484 485 486 487 488
VIR_ENUM_IMPL(virDomainKeyWrapCipherName,
              VIR_DOMAIN_KEY_WRAP_CIPHER_NAME_LAST,
              "aes",
              "dea")

489 490
VIR_ENUM_IMPL(virDomainMemballoonModel, VIR_DOMAIN_MEMBALLOON_MODEL_LAST,
              "virtio",
491
              "xen",
492 493
              "none")

494 495 496 497 498 499
VIR_ENUM_IMPL(virDomainSmbiosMode, VIR_DOMAIN_SMBIOS_LAST,
              "none",
              "emulate",
              "host",
              "sysinfo")

R
Richard Jones 已提交
500 501
VIR_ENUM_IMPL(virDomainWatchdogModel, VIR_DOMAIN_WATCHDOG_MODEL_LAST,
              "i6300esb",
502 503
              "ib700",
              "diag288")
R
Richard Jones 已提交
504 505 506 507 508 509

VIR_ENUM_IMPL(virDomainWatchdogAction, VIR_DOMAIN_WATCHDOG_ACTION_LAST,
              "reset",
              "shutdown",
              "poweroff",
              "pause",
H
Hu Tao 已提交
510
              "dump",
511 512
              "none",
              "inject-nmi")
R
Richard Jones 已提交
513

514 515 516 517 518 519
VIR_ENUM_IMPL(virDomainPanicModel, VIR_DOMAIN_PANIC_MODEL_LAST,
              "default",
              "isa",
              "pseries",
              "hyperv")

520 521 522 523 524
VIR_ENUM_IMPL(virDomainVideo, VIR_DOMAIN_VIDEO_TYPE_LAST,
              "vga",
              "cirrus",
              "vmvga",
              "xen",
525
              "vbox",
526
              "qxl",
M
Marc-André Lureau 已提交
527 528
              "parallels",
              "virtio")
529

530 531
VIR_ENUM_IMPL(virDomainInput, VIR_DOMAIN_INPUT_TYPE_LAST,
              "mouse",
L
Li Zhang 已提交
532
              "tablet",
533 534
              "keyboard",
              "passthrough")
535 536 537 538

VIR_ENUM_IMPL(virDomainInputBus, VIR_DOMAIN_INPUT_BUS_LAST,
              "ps2",
              "usb",
539
              "xen",
540 541
              "parallels",
              "virtio")
542 543 544

VIR_ENUM_IMPL(virDomainGraphics, VIR_DOMAIN_GRAPHICS_TYPE_LAST,
              "sdl",
545 546
              "vnc",
              "rdp",
547 548
              "desktop",
              "spice")
549

550 551 552 553 554
VIR_ENUM_IMPL(virDomainGraphicsListen, VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_LAST,
              "none",
              "address",
              "network")

555 556 557 558 559 560 561
VIR_ENUM_IMPL(virDomainGraphicsAuthConnected,
              VIR_DOMAIN_GRAPHICS_AUTH_CONNECTED_LAST,
              "default",
              "fail",
              "disconnect",
              "keep")

562 563 564 565 566 567 568
VIR_ENUM_IMPL(virDomainGraphicsVNCSharePolicy,
              VIR_DOMAIN_GRAPHICS_VNC_SHARE_LAST,
              "default",
              "allow-exclusive",
              "force-shared",
              "ignore")

569 570 571 572 573 574 575
VIR_ENUM_IMPL(virDomainGraphicsSpiceChannelName,
              VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_LAST,
              "main",
              "display",
              "inputs",
              "cursor",
              "playback",
E
Eric Blake 已提交
576
              "record",
577 578
              "smartcard",
              "usbredir");
579 580 581 582 583 584 585

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

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
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 已提交
610 611 612 613 614 615
VIR_ENUM_IMPL(virDomainGraphicsSpiceMouseMode,
              VIR_DOMAIN_GRAPHICS_SPICE_MOUSE_MODE_LAST,
              "default",
              "server",
              "client");

616 617 618 619 620 621 622
VIR_ENUM_IMPL(virDomainGraphicsSpiceStreamingMode,
              VIR_DOMAIN_GRAPHICS_SPICE_STREAMING_MODE_LAST,
              "default",
              "filter",
              "all",
              "off");

623 624 625 626 627 628
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 已提交
629 630
              "pci",
              "scsi")
631

632
VIR_ENUM_IMPL(virDomainHostdevSubsysPCIBackend,
633 634 635
              VIR_DOMAIN_HOSTDEV_PCI_BACKEND_TYPE_LAST,
              "default",
              "kvm",
636 637
              "vfio",
              "xen")
638

J
John Ferlan 已提交
639 640 641 642 643
VIR_ENUM_IMPL(virDomainHostdevSubsysSCSIProtocol,
              VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_LAST,
              "adapter",
              "iscsi")

644 645
VIR_ENUM_IMPL(virDomainHostdevCaps, VIR_DOMAIN_HOSTDEV_CAPS_TYPE_LAST,
              "storage",
646 647
              "misc",
              "net")
648

649 650 651 652 653 654 655
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,
656 657 658 659 660 661
              "nostate",
              "running",
              "blocked",
              "paused",
              "shutdown",
              "shutoff",
O
Osier Yang 已提交
662 663
              "crashed",
              "pmsuspended")
664

J
Jiri Denemark 已提交
665 666 667 668 669 670 671 672 673 674 675
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",
676
              "save canceled",
677 678
              "wakeup",
              "crashed")
J
Jiri Denemark 已提交
679 680 681 682 683 684 685 686 687 688 689 690

VIR_ENUM_IMPL(virDomainBlockedReason, VIR_DOMAIN_BLOCKED_LAST,
              "unknown")

VIR_ENUM_IMPL(virDomainPausedReason, VIR_DOMAIN_PAUSED_LAST,
              "unknown",
              "user",
              "migration",
              "save",
              "dump",
              "ioerror",
              "watchdog",
691
              "from snapshot",
692
              "shutdown",
693
              "snapshot",
694 695
              "panicked",
              "starting up")
J
Jiri Denemark 已提交
696 697 698

VIR_ENUM_IMPL(virDomainShutdownReason, VIR_DOMAIN_SHUTDOWN_LAST,
              "unknown",
699
              "user")
J
Jiri Denemark 已提交
700 701 702 703 704 705 706 707 708 709 710 711

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,
712 713
              "unknown",
              "panicked")
J
Jiri Denemark 已提交
714

715 716 717
VIR_ENUM_IMPL(virDomainPMSuspendedReason, VIR_DOMAIN_PMSUSPENDED_LAST,
              "unknown")

718
VIR_ENUM_IMPL(virDomainSeclabel, VIR_DOMAIN_SECLABEL_LAST,
719 720
              "default",
              "none",
721 722 723
              "dynamic",
              "static")

724 725
VIR_ENUM_IMPL(virDomainClockOffset, VIR_DOMAIN_CLOCK_OFFSET_LAST,
              "utc",
726
              "localtime",
727 728
              "variable",
              "timezone");
729

730 731 732 733
VIR_ENUM_IMPL(virDomainClockBasis, VIR_DOMAIN_CLOCK_BASIS_LAST,
              "utc",
              "localtime");

734 735 736 737 738
VIR_ENUM_IMPL(virDomainTimerName, VIR_DOMAIN_TIMER_NAME_LAST,
              "platform",
              "pit",
              "rtc",
              "hpet",
P
Paolo Bonzini 已提交
739
              "tsc",
740 741
              "kvmclock",
              "hypervclock");
742

743 744 745 746
VIR_ENUM_IMPL(virDomainTimerTrack, VIR_DOMAIN_TIMER_TRACK_LAST,
              "boot",
              "guest",
              "wall");
747 748 749 750 751 752 753 754 755 756 757

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",
758 759
              "paravirt",
              "smpsafe");
760

761 762 763 764 765 766
VIR_ENUM_IMPL(virDomainStartupPolicy, VIR_DOMAIN_STARTUP_POLICY_LAST,
              "default",
              "mandatory",
              "requisite",
              "optional");

O
Osier Yang 已提交
767 768 769 770
VIR_ENUM_IMPL(virDomainCpuPlacementMode, VIR_DOMAIN_CPU_PLACEMENT_MODE_LAST,
              "static",
              "auto");

771 772 773 774
VIR_ENUM_IMPL(virDomainDiskTray, VIR_DOMAIN_DISK_TRAY_LAST,
              "closed",
              "open");

775 776 777 778 779 780 781 782 783
VIR_ENUM_IMPL(virDomainRNGModel,
              VIR_DOMAIN_RNG_MODEL_LAST,
              "virtio");

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

784 785 786 787 788 789
VIR_ENUM_IMPL(virDomainTPMModel, VIR_DOMAIN_TPM_MODEL_LAST,
              "tpm-tis")

VIR_ENUM_IMPL(virDomainTPMBackend, VIR_DOMAIN_TPM_TYPE_LAST,
              "passthrough")

O
Osier Yang 已提交
790 791
VIR_ENUM_IMPL(virDomainDiskDiscard, VIR_DOMAIN_DISK_DISCARD_LAST,
              "default",
O
Osier Yang 已提交
792 793
              "unmap",
              "ignore")
794

795 796 797 798 799 800
VIR_ENUM_IMPL(virDomainDiskMirrorState, VIR_DOMAIN_DISK_MIRROR_STATE_LAST,
              "none",
              "yes",
              "abort",
              "pivot")

801 802 803 804 805
VIR_ENUM_IMPL(virDomainLoader,
              VIR_DOMAIN_LOADER_TYPE_LAST,
              "rom",
              "pflash")

E
Eric Blake 已提交
806 807 808 809 810 811
/* 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")

812 813 814
VIR_ENUM_IMPL(virDomainMemoryModel, VIR_DOMAIN_MEMORY_MODEL_LAST,
              "", "dimm")

815
static virClassPtr virDomainObjClass;
816
static virClassPtr virDomainXMLOptionClass;
817
static void virDomainObjDispose(void *obj);
818
static void virDomainXMLOptionClassDispose(void *obj);
819 820 821

static int virDomainObjOnceInit(void)
{
822
    if (!(virDomainObjClass = virClassNew(virClassForObjectLockable(),
823
                                          "virDomainObj",
824 825 826 827
                                          sizeof(virDomainObj),
                                          virDomainObjDispose)))
        return -1;

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

834 835 836 837 838
    return 0;
}

VIR_ONCE_GLOBAL_INIT(virDomainObj)

839

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

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

849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
/**
 * virDomainKeyWrapCipherDefParseXML:
 *
 * @def  Domain definition
 * @node An XML cipher node
 * @ctxt The XML context
 *
 * Parse the attributes from the cipher node and store the state
 * attribute in @def.
 *
 * A cipher node has the form of
 *
 *   <cipher name='aes|dea' state='on|off'/>
 *
 * Returns: 0 if the parse succeeded
 *         -1 otherwise
 */
static int
virDomainKeyWrapCipherDefParseXML(virDomainKeyWrapDefPtr keywrap,
                                  xmlNodePtr node,
                                  xmlXPathContextPtr ctxt)
{

    char *name = NULL;
    char *state = NULL;
    int state_type;
    int name_type;
    int ret = -1;
    xmlNodePtr oldnode = ctxt->node;

    ctxt->node = node;
    if (!(name = virXPathString("string(./@name)", ctxt))) {
        virReportError(VIR_ERR_CONF_SYNTAX, "%s",
                       _("missing name for cipher"));
        goto cleanup;
    }

    if ((name_type = virDomainKeyWrapCipherNameTypeFromString(name)) < 0) {
        virReportError(VIR_ERR_CONF_SYNTAX,
                       _("%s is not a supported cipher name"), name);
        goto cleanup;
    }

    if (!(state = virXPathString("string(./@state)", ctxt))) {
        virReportError(VIR_ERR_CONF_SYNTAX,
                       _("missing state for cipher named %s"), name);
        goto cleanup;
    }

    if ((state_type = virTristateSwitchTypeFromString(state)) < 0) {
        virReportError(VIR_ERR_CONF_SYNTAX,
                       _("%s is not a supported cipher state"), state);
        goto cleanup;
    }

    switch ((virDomainKeyWrapCipherName) name_type) {
    case VIR_DOMAIN_KEY_WRAP_CIPHER_NAME_AES:
        if (keywrap->aes != VIR_TRISTATE_SWITCH_ABSENT) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("A domain definition can have no more than "
                             "one cipher node with name %s"),
                           virDomainKeyWrapCipherNameTypeToString(name_type));

            goto cleanup;
        }
        keywrap->aes = state_type;
        break;

    case VIR_DOMAIN_KEY_WRAP_CIPHER_NAME_DEA:
        if (keywrap->dea != VIR_TRISTATE_SWITCH_ABSENT) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("A domain definition can have no more than "
                             "one cipher node with name %s"),
                           virDomainKeyWrapCipherNameTypeToString(name_type));

            goto cleanup;
        }
        keywrap->dea = state_type;
        break;

    case VIR_DOMAIN_KEY_WRAP_CIPHER_NAME_LAST:
        break;
    }

    ret = 0;

 cleanup:
    VIR_FREE(name);
    VIR_FREE(state);
    ctxt->node = oldnode;
    return ret;
}

static int
virDomainKeyWrapDefParseXML(virDomainDefPtr def, xmlXPathContextPtr ctxt)
{
    size_t i;
    int ret = -1;
    xmlNodePtr *nodes = NULL;
    int n;

950 951
    if ((n = virXPathNodeSet("./keywrap/cipher", ctxt, &nodes)) < 0)
        return n;
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973

    if (VIR_ALLOC(def->keywrap) < 0)
        goto cleanup;

    for (i = 0; i < n; i++) {
        if (virDomainKeyWrapCipherDefParseXML(def->keywrap, nodes[i], ctxt) < 0)
            goto cleanup;
    }

    if (!def->keywrap->aes &&
        !def->keywrap->dea)
        VIR_FREE(def->keywrap);

    ret = 0;

 cleanup:
    if (ret < 0)
        VIR_FREE(def->keywrap);
    VIR_FREE(nodes);
    return ret;
}

974

975
/**
976
 * virDomainXMLOptionNew:
977 978 979
 *
 * Allocate a new domain XML configuration
 */
980
virDomainXMLOptionPtr
981 982
virDomainXMLOptionNew(virDomainDefParserConfigPtr config,
                      virDomainXMLPrivateDataCallbacksPtr priv,
983
                      virDomainXMLNamespacePtr xmlns)
984
{
985
    virDomainXMLOptionPtr xmlopt;
986 987 988 989

    if (virDomainObjInitialize() < 0)
        return NULL;

990
    if (!(xmlopt = virObjectNew(virDomainXMLOptionClass)))
991 992 993
        return NULL;

    if (priv)
994
        xmlopt->privateData = *priv;
995

996 997 998
    if (config)
        xmlopt->config = *config;

999
    if (xmlns)
1000
        xmlopt->ns = *xmlns;
1001

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    /* 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;
    }

1014
    return xmlopt;
1015 1016 1017
}

/**
1018
 * virDomainXMLOptionGetNamespace:
1019
 *
1020
 * @xmlopt: XML parser configuration object
1021 1022
 *
 * Returns a pointer to the stored namespace structure.
1023
 * The lifetime of the pointer is equal to @xmlopt;
1024 1025
 */
virDomainXMLNamespacePtr
1026
virDomainXMLOptionGetNamespace(virDomainXMLOptionPtr xmlopt)
1027
{
1028
    return &xmlopt->ns;
1029 1030 1031
}


1032
void
1033
virBlkioDeviceArrayClear(virBlkioDevicePtr devices,
1034
                         int ndevices)
1035
{
1036
    size_t i;
1037 1038

    for (i = 0; i < ndevices; i++)
1039
        VIR_FREE(devices[i].path);
1040 1041 1042
}

/**
1043
 * virDomainBlkioDeviceParseXML
1044 1045 1046 1047 1048 1049
 *
 * this function parses a XML node:
 *
 *   <device>
 *     <path>/fully/qualified/device/path</path>
 *     <weight>weight</weight>
1050 1051 1052 1053
 *     <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>
1054 1055
 *   </device>
 *
1056
 * and fills a virBlkioDevicePtr struct.
1057 1058
 */
static int
1059
virDomainBlkioDeviceParseXML(xmlNodePtr root,
1060
                             virBlkioDevicePtr dev)
1061
{
1062
    char *c = NULL;
1063 1064 1065 1066 1067
    xmlNodePtr node;

    node = root->children;
    while (node) {
        if (node->type == XML_ELEMENT_NODE) {
1068 1069
            if (xmlStrEqual(node->name, BAD_CAST "path") && !dev->path) {
                dev->path = (char *)xmlNodeGetContent(node);
1070 1071
            } else if (xmlStrEqual(node->name, BAD_CAST "weight")) {
                c = (char *)xmlNodeGetContent(node);
1072
                if (virStrToLong_ui(c, NULL, 10, &dev->weight) < 0) {
1073 1074 1075
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("could not parse weight %s"),
                                   c);
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
                        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;
1113 1114 1115 1116 1117 1118
                }
                VIR_FREE(c);
            }
        }
        node = node->next;
    }
1119
    if (!dev->path) {
1120 1121
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("missing per-device path"));
1122 1123 1124 1125
        return -1;
    }

    return 0;
1126

1127
 error:
1128 1129 1130
    VIR_FREE(c);
    VIR_FREE(dev->path);
    return -1;
1131 1132 1133
}


1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
/**
 * virDomainDefCheckUnsupportedMemoryHotplug:
 * @def: domain definition
 *
 * Returns -1 if the domain definition would enable memory hotplug via the
 * <maxMemory> tunable and reports an error. Otherwise returns 0.
 */
int
virDomainDefCheckUnsupportedMemoryHotplug(virDomainDefPtr def)
{
    /* memory hotplug tunables are not supported by this driver */
1145
    if (virDomainDefHasMemoryHotplug(def)) {
1146 1147 1148 1149 1150 1151 1152 1153 1154
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("memory hotplug tunables <maxMemory> are not "
                         "supported by this hypervisor driver"));
        return -1;
    }

    return 0;
}

1155

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
/**
 * virDomainDeviceDefCheckUnsupportedMemoryDevice:
 * @dev: device definition
 *
 * Returns -1 if the device definition describes a memory device and reports an
 * error. Otherwise returns 0.
 */
int
virDomainDeviceDefCheckUnsupportedMemoryDevice(virDomainDeviceDefPtr dev)
{
    /* This driver doesn't yet know how to handle memory devices */
    if (dev->type == VIR_DOMAIN_DEVICE_MEMORY) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("memory devices are not supported by this driver"));
        return -1;
    }

    return 0;
}


1177
bool virDomainObjTaint(virDomainObjPtr obj,
1178
                       virDomainTaintFlags taint)
1179
{
E
Eric Blake 已提交
1180
    unsigned int flag = (1 << taint);
1181 1182 1183 1184 1185 1186 1187 1188

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

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

1189 1190 1191 1192 1193 1194 1195 1196 1197
static void
virDomainDeviceInfoFree(virDomainDeviceInfoPtr info)
{
    if (info) {
        virDomainDeviceInfoClear(info);
        VIR_FREE(info);
    }
}

1198

1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
static void
virDomainGraphicsAuthDefClear(virDomainGraphicsAuthDefPtr def)
{
    if (!def)
        return;

    VIR_FREE(def->passwd);

    /* Don't free def */
}

1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
static void
virDomainGraphicsListenDefClear(virDomainGraphicsListenDefPtr def)
{
    if (!def)
        return;

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

1221

1222 1223
void virDomainGraphicsDefFree(virDomainGraphicsDefPtr def)
{
1224
    size_t i;
1225

1226 1227 1228
    if (!def)
        return;

1229
    switch ((virDomainGraphicsType)def->type) {
1230
    case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
1231
        VIR_FREE(def->data.vnc.socket);
1232
        VIR_FREE(def->data.vnc.keymap);
1233
        virDomainGraphicsAuthDefClear(&def->data.vnc.auth);
1234 1235 1236 1237 1238 1239
        break;

    case VIR_DOMAIN_GRAPHICS_TYPE_SDL:
        VIR_FREE(def->data.sdl.display);
        VIR_FREE(def->data.sdl.xauth);
        break;
1240 1241 1242 1243 1244 1245 1246

    case VIR_DOMAIN_GRAPHICS_TYPE_RDP:
        break;

    case VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP:
        VIR_FREE(def->data.desktop.display);
        break;
1247 1248 1249

    case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
        VIR_FREE(def->data.spice.keymap);
1250
        virDomainGraphicsAuthDefClear(&def->data.spice.auth);
1251
        break;
1252 1253 1254

    case VIR_DOMAIN_GRAPHICS_TYPE_LAST:
        break;
1255 1256
    }

1257 1258
    for (i = 0; i < def->nListens; i++)
        virDomainGraphicsListenDefClear(&def->listens[i]);
1259 1260
    VIR_FREE(def->listens);

1261 1262 1263 1264 1265 1266 1267 1268
    VIR_FREE(def);
}

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

1269
    virDomainDeviceInfoClear(&def->info);
1270
    VIR_FREE(def->source.evdev);
1271 1272 1273
    VIR_FREE(def);
}

1274
void virDomainLeaseDefFree(virDomainLeaseDefPtr def)
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
{
    if (!def)
        return;

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

    VIR_FREE(def);
}

1286

1287 1288 1289 1290 1291
static void
virDomainVcpuInfoClear(virDomainVcpuInfoPtr info)
{
    if (!info)
        return;
1292 1293 1294

    virBitmapFree(info->cpumask);
    info->cpumask = NULL;
1295 1296 1297
}


1298 1299 1300 1301
int
virDomainDefSetVcpusMax(virDomainDefPtr def,
                        unsigned int maxvcpus)
{
1302
    size_t i;
1303

1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
    if (def->maxvcpus == maxvcpus)
        return 0;

    if (def->maxvcpus < maxvcpus) {
        if (VIR_EXPAND_N(def->vcpus, def->maxvcpus, maxvcpus - def->maxvcpus) < 0)
            return -1;
    } else {
        for (i = maxvcpus; i < def->maxvcpus; i++)
            virDomainVcpuInfoClear(&def->vcpus[i]);

        VIR_SHRINK_N(def->vcpus, def->maxvcpus, def->maxvcpus - maxvcpus);
    }
1316 1317 1318 1319 1320

    return 0;
}


1321 1322 1323
bool
virDomainDefHasVcpusOffline(const virDomainDef *def)
{
1324 1325 1326 1327 1328 1329 1330 1331
    size_t i;

    for (i = 0; i < def->maxvcpus; i++) {
        if (!def->vcpus[i].online)
            return true;
    }

    return false;
1332 1333 1334
}


1335 1336 1337 1338 1339 1340 1341
unsigned int
virDomainDefGetVcpusMax(const virDomainDef *def)
{
    return def->maxvcpus;
}


1342 1343 1344 1345
int
virDomainDefSetVcpus(virDomainDefPtr def,
                     unsigned int vcpus)
{
1346 1347
    size_t i;

1348 1349
    if (vcpus > def->maxvcpus) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1350
                       _("maxvcpus must not be less than current vcpus (%u < %zu)"),
1351 1352 1353 1354
                       vcpus, def->maxvcpus);
        return -1;
    }

1355 1356 1357 1358 1359
    for (i = 0; i < vcpus; i++)
        def->vcpus[i].online = true;

    for (i = vcpus; i < def->maxvcpus; i++)
        def->vcpus[i].online = false;
1360 1361 1362 1363 1364

    return 0;
}


1365 1366 1367
unsigned int
virDomainDefGetVcpus(const virDomainDef *def)
{
1368 1369 1370 1371 1372 1373 1374
    size_t i;
    unsigned int ret = 0;

    for (i = 0; i < def->maxvcpus; i++) {
        if (def->vcpus[i].online)
            ret++;
    }
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398

    return ret;
}


/**
 * virDomainDefGetOnlineVcpumap:
 * @def: domain definition
 *
 * Returns a bitmap representing state of individual vcpus.
 */
virBitmapPtr
virDomainDefGetOnlineVcpumap(const virDomainDef *def)
{
    virBitmapPtr ret = NULL;
    size_t i;

    if (!(ret = virBitmapNew(def->maxvcpus)))
        return NULL;

    for (i = 0; i < def->maxvcpus; i++) {
        if (def->vcpus[i].online)
            ignore_value(virBitmapSetBit(ret, i));
    }
1399 1400

    return ret;
1401 1402 1403
}


1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
virDomainVcpuInfoPtr
virDomainDefGetVcpu(virDomainDefPtr def,
                    unsigned int vcpu)
{
    if (vcpu > def->maxvcpus) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("vCPU '%u' is not present in domain definition"),
                       vcpu);
        return NULL;
    }

    return &def->vcpus[vcpu];
}


1419 1420 1421 1422 1423 1424 1425 1426 1427
/**
 * virDomainDefHasVcpuPin:
 * @def: domain definition
 *
 * This helper returns true if any of the domain's vcpus has cpu pinning set
 */
static bool
virDomainDefHasVcpuPin(const virDomainDef *def)
{
1428 1429 1430 1431 1432 1433 1434 1435
    size_t i;

    for (i = 0; i < def->maxvcpus; i++) {
        if (def->vcpus[i].cpumask)
            return true;
    }

    return false;
1436 1437 1438
}


1439
virDomainDiskDefPtr
1440
virDomainDiskDefNew(virDomainXMLOptionPtr xmlopt)
1441 1442 1443
{
    virDomainDiskDefPtr ret;

1444 1445
    if (VIR_ALLOC(ret) < 0)
        return NULL;
1446

1447
    if (VIR_ALLOC(ret->src) < 0)
1448 1449
        goto error;

1450 1451 1452 1453 1454
    if (xmlopt &&
        xmlopt->privateData.diskNew &&
        !(ret->privateData = xmlopt->privateData.diskNew()))
        goto error;

1455
    return ret;
1456 1457

 error:
1458
    virDomainDiskDefFree(ret);
1459
    return NULL;
1460 1461 1462
}


1463 1464 1465 1466 1467 1468
void
virDomainDiskDefFree(virDomainDiskDefPtr def)
{
    if (!def)
        return;

1469
    virStorageSourceFree(def->src);
1470 1471
    VIR_FREE(def->serial);
    VIR_FREE(def->dst);
1472
    virStorageSourceFree(def->mirror);
1473 1474 1475
    VIR_FREE(def->wwn);
    VIR_FREE(def->vendor);
    VIR_FREE(def->product);
1476
    VIR_FREE(def->domain_name);
1477
    virDomainDeviceInfoClear(&def->info);
1478
    virObjectUnref(def->privateData);
1479

1480 1481 1482
    VIR_FREE(def);
}

1483

1484 1485 1486
int
virDomainDiskGetType(virDomainDiskDefPtr def)
{
1487
    return def->src->type;
1488 1489 1490 1491 1492 1493
}


void
virDomainDiskSetType(virDomainDiskDefPtr def, int type)
{
1494
    def->src->type = type;
1495 1496 1497 1498
}


const char *
1499
virDomainDiskGetSource(virDomainDiskDef const *def)
1500
{
1501
    return def->src->path;
1502 1503 1504 1505 1506 1507 1508
}


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

1511
    ret = VIR_STRDUP(def->src->path, src);
1512
    if (ret < 0)
1513
        def->src->path = tmp;
1514 1515 1516 1517 1518 1519 1520 1521 1522
    else
        VIR_FREE(tmp);
    return ret;
}


const char *
virDomainDiskGetDriver(virDomainDiskDefPtr def)
{
1523
    return def->src->driverName;
1524 1525 1526 1527 1528 1529 1530
}


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

1533
    ret = VIR_STRDUP(def->src->driverName, name);
1534
    if (ret < 0)
1535
        def->src->driverName = tmp;
1536 1537 1538 1539 1540 1541 1542 1543 1544
    else
        VIR_FREE(tmp);
    return ret;
}


int
virDomainDiskGetFormat(virDomainDiskDefPtr def)
{
1545
    return def->src->format;
1546 1547 1548 1549 1550 1551
}


void
virDomainDiskSetFormat(virDomainDiskDefPtr def, int format)
{
1552
    def->src->format = format;
1553 1554 1555
}


1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
static virDomainControllerDefPtr
virDomainControllerDefNew(virDomainControllerType type)
{
    virDomainControllerDefPtr def;

    if (VIR_ALLOC(def) < 0)
        return NULL;

    def->type = type;
    def->model = -1;

    /* initialize anything that has a non-0 default */
    switch ((virDomainControllerType) def->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL:
        def->opts.vioserial.ports = -1;
        def->opts.vioserial.vectors = -1;
        break;
    case VIR_DOMAIN_CONTROLLER_TYPE_PCI:
1574
        def->opts.pciopts.chassisNr = -1;
1575 1576
        def->opts.pciopts.chassis = -1;
        def->opts.pciopts.port = -1;
1577
        break;
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
    case VIR_DOMAIN_CONTROLLER_TYPE_IDE:
    case VIR_DOMAIN_CONTROLLER_TYPE_FDC:
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
    case VIR_DOMAIN_CONTROLLER_TYPE_SATA:
    case VIR_DOMAIN_CONTROLLER_TYPE_CCID:
    case VIR_DOMAIN_CONTROLLER_TYPE_USB:
    case VIR_DOMAIN_CONTROLLER_TYPE_LAST:
        break;
    }

    return def;
}


1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
void virDomainControllerDefFree(virDomainControllerDefPtr def)
{
    if (!def)
        return;

    virDomainDeviceInfoClear(&def->info);

    VIR_FREE(def);
}

1602 1603 1604 1605 1606 1607 1608
void virDomainFSDefFree(virDomainFSDefPtr def)
{
    if (!def)
        return;

    VIR_FREE(def->src);
    VIR_FREE(def->dst);
1609
    virDomainDeviceInfoClear(&def->info);
1610 1611 1612 1613

    VIR_FREE(def);
}

1614 1615 1616 1617 1618 1619 1620 1621
void
virDomainActualNetDefFree(virDomainActualNetDefPtr def)
{
    if (!def)
        return;

    switch (def->type) {
    case VIR_DOMAIN_NET_TYPE_BRIDGE:
1622
    case VIR_DOMAIN_NET_TYPE_NETWORK:
1623 1624 1625 1626 1627
        VIR_FREE(def->data.bridge.brname);
        break;
    case VIR_DOMAIN_NET_TYPE_DIRECT:
        VIR_FREE(def->data.direct.linkdev);
        break;
1628 1629 1630
    case VIR_DOMAIN_NET_TYPE_HOSTDEV:
        virDomainHostdevDefClear(&def->data.hostdev.def);
        break;
1631 1632 1633 1634
    default:
        break;
    }

1635
    VIR_FREE(def->virtPortProfile);
1636
    virNetDevBandwidthFree(def->bandwidth);
1637
    virNetDevVlanClear(&def->vlan);
1638 1639 1640
    VIR_FREE(def);
}

1641 1642
void virDomainNetDefFree(virDomainNetDefPtr def)
{
1643 1644
    size_t i;

1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
    if (!def)
        return;

    VIR_FREE(def->model);

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

M
Michele Paolino 已提交
1655 1656 1657 1658
    case VIR_DOMAIN_NET_TYPE_VHOSTUSER:
        virDomainChrSourceDefFree(def->data.vhostuser);
        break;

1659 1660 1661
    case VIR_DOMAIN_NET_TYPE_SERVER:
    case VIR_DOMAIN_NET_TYPE_CLIENT:
    case VIR_DOMAIN_NET_TYPE_MCAST:
1662
    case VIR_DOMAIN_NET_TYPE_UDP:
1663
        VIR_FREE(def->data.socket.address);
1664
        VIR_FREE(def->data.socket.localaddr);
1665 1666 1667 1668
        break;

    case VIR_DOMAIN_NET_TYPE_NETWORK:
        VIR_FREE(def->data.network.name);
1669 1670
        VIR_FREE(def->data.network.portgroup);
        virDomainActualNetDefFree(def->data.network.actual);
1671 1672 1673 1674 1675
        break;

    case VIR_DOMAIN_NET_TYPE_BRIDGE:
        VIR_FREE(def->data.bridge.brname);
        break;
D
Daniel Veillard 已提交
1676 1677 1678 1679

    case VIR_DOMAIN_NET_TYPE_INTERNAL:
        VIR_FREE(def->data.internal.name);
        break;
1680 1681 1682 1683

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

1685 1686 1687 1688
    case VIR_DOMAIN_NET_TYPE_HOSTDEV:
        virDomainHostdevDefClear(&def->data.hostdev.def);
        break;

S
Stefan Berger 已提交
1689 1690 1691
    case VIR_DOMAIN_NET_TYPE_USER:
    case VIR_DOMAIN_NET_TYPE_LAST:
        break;
1692 1693
    }

1694 1695
    VIR_FREE(def->backend.tap);
    VIR_FREE(def->backend.vhost);
1696
    VIR_FREE(def->virtPortProfile);
1697
    VIR_FREE(def->script);
1698
    VIR_FREE(def->domain_name);
1699
    VIR_FREE(def->ifname);
1700 1701
    VIR_FREE(def->ifname_guest);
    VIR_FREE(def->ifname_guest_actual);
1702

1703 1704 1705 1706
    for (i = 0; i < def->nips; i++)
        VIR_FREE(def->ips[i]);
    VIR_FREE(def->ips);

1707
    for (i = 0; i < def->nroutes; i++)
1708
        virNetworkRouteDefFree(def->routes[i]);
1709 1710
    VIR_FREE(def->routes);

1711
    virDomainDeviceInfoClear(&def->info);
1712

1713 1714 1715
    VIR_FREE(def->filter);
    virNWFilterHashTableFree(def->filterparams);

1716
    virNetDevBandwidthFree(def->bandwidth);
1717
    virNetDevVlanClear(&def->vlan);
1718

1719 1720 1721
    VIR_FREE(def);
}

1722
void ATTRIBUTE_NONNULL(1)
1723
virDomainChrSourceDefClear(virDomainChrSourceDefPtr def)
1724 1725 1726 1727 1728 1729 1730 1731 1732
{
    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;

1733 1734 1735 1736 1737
    case VIR_DOMAIN_CHR_TYPE_NMDM:
        VIR_FREE(def->data.nmdm.master);
        VIR_FREE(def->data.nmdm.slave);
        break;

1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
    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;
1753 1754 1755 1756

    case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
        VIR_FREE(def->data.spiceport.channel);
        break;
1757
    }
1758 1759
}

1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
/* 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) {
1772
    case VIR_DOMAIN_CHR_TYPE_FILE:
1773 1774 1775
    case VIR_DOMAIN_CHR_TYPE_PTY:
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_PIPE:
1776 1777
        if (src->type == VIR_DOMAIN_CHR_TYPE_FILE)
            dest->data.file.append = src->data.file.append;
1778
        if (VIR_STRDUP(dest->data.file.path, src->data.file.path) < 0)
1779 1780 1781 1782
            return -1;
        break;

    case VIR_DOMAIN_CHR_TYPE_UDP:
1783
        if (VIR_STRDUP(dest->data.udp.bindHost, src->data.udp.bindHost) < 0)
1784 1785
            return -1;

1786
        if (VIR_STRDUP(dest->data.udp.bindService, src->data.udp.bindService) < 0)
1787 1788
            return -1;

1789
        if (VIR_STRDUP(dest->data.udp.connectHost, src->data.udp.connectHost) < 0)
1790 1791
            return -1;

1792
        if (VIR_STRDUP(dest->data.udp.connectService, src->data.udp.connectService) < 0)
1793 1794 1795 1796
            return -1;
        break;

    case VIR_DOMAIN_CHR_TYPE_TCP:
1797
        if (VIR_STRDUP(dest->data.tcp.host, src->data.tcp.host) < 0)
1798 1799
            return -1;

1800
        if (VIR_STRDUP(dest->data.tcp.service, src->data.tcp.service) < 0)
1801 1802 1803 1804
            return -1;
        break;

    case VIR_DOMAIN_CHR_TYPE_UNIX:
1805
        if (VIR_STRDUP(dest->data.nix.path, src->data.nix.path) < 0)
1806 1807
            return -1;
        break;
1808 1809 1810 1811 1812 1813 1814 1815

    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;
1816 1817
    }

S
Stefan Berger 已提交
1818 1819
    dest->type = src->type;

1820 1821 1822
    return 0;
}

1823 1824 1825 1826 1827 1828 1829 1830 1831
void virDomainChrSourceDefFree(virDomainChrSourceDefPtr def)
{
    if (!def)
        return;

    virDomainChrSourceDefClear(def);

    VIR_FREE(def);
}
1832

1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
/* 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;

1847
    switch ((virDomainChrType)src->type) {
1848 1849 1850 1851
    case VIR_DOMAIN_CHR_TYPE_FILE:
        return src->data.file.append == tgt->data.file.append &&
            STREQ_NULLABLE(src->data.file.path, tgt->data.file.path);
        break;
1852 1853 1854 1855 1856
    case VIR_DOMAIN_CHR_TYPE_PTY:
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_PIPE:
        return STREQ_NULLABLE(src->data.file.path, tgt->data.file.path);
        break;
1857 1858 1859 1860
    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;
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
    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;

1878 1879 1880 1881 1882
    case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
        return STREQ_NULLABLE(src->data.spiceport.channel,
                              tgt->data.spiceport.channel);
        break;

J
Ján Tomko 已提交
1883 1884 1885
    case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
        return src->data.spicevmc == tgt->data.spicevmc;

1886
    case VIR_DOMAIN_CHR_TYPE_NULL:
1887 1888
    case VIR_DOMAIN_CHR_TYPE_VC:
    case VIR_DOMAIN_CHR_TYPE_STDIO:
1889 1890
    case VIR_DOMAIN_CHR_TYPE_LAST:
        break;
1891 1892
    }

J
Ján Tomko 已提交
1893
    return true;
1894 1895
}

1896 1897
void virDomainChrDefFree(virDomainChrDefPtr def)
{
1898 1899
    size_t i;

1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
    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);
1921 1922
    virDomainDeviceInfoClear(&def->info);

1923 1924 1925 1926 1927 1928
    if (def->seclabels) {
        for (i = 0; i < def->nseclabels; i++)
            virSecurityDeviceLabelDefFree(def->seclabels[i]);
        VIR_FREE(def->seclabels);
    }

1929 1930 1931
    VIR_FREE(def);
}

E
Eric Blake 已提交
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
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);
}

1961 1962 1963 1964 1965 1966 1967 1968
void virDomainSoundCodecDefFree(virDomainSoundCodecDefPtr def)
{
    if (!def)
        return;

    VIR_FREE(def);
}

1969 1970 1971 1972 1973
void virDomainSoundDefFree(virDomainSoundDefPtr def)
{
    if (!def)
        return;

1974 1975
    virDomainDeviceInfoClear(&def->info);

1976
    size_t i;
1977
    for (i = 0; i < def->ncodecs; i++)
1978 1979 1980
        virDomainSoundCodecDefFree(def->codecs[i]);
    VIR_FREE(def->codecs);

1981 1982 1983
    VIR_FREE(def);
}

1984 1985 1986 1987 1988 1989 1990 1991 1992 1993
void virDomainMemballoonDefFree(virDomainMemballoonDefPtr def)
{
    if (!def)
        return;

    virDomainDeviceInfoClear(&def->info);

    VIR_FREE(def);
}

L
Li Zhang 已提交
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
void virDomainNVRAMDefFree(virDomainNVRAMDefPtr def)
{
    if (!def)
        return;

    virDomainDeviceInfoClear(&def->info);

    VIR_FREE(def);
}

R
Richard Jones 已提交
2004 2005 2006 2007 2008
void virDomainWatchdogDefFree(virDomainWatchdogDefPtr def)
{
    if (!def)
        return;

2009 2010
    virDomainDeviceInfoClear(&def->info);

R
Richard Jones 已提交
2011 2012 2013
    VIR_FREE(def);
}

2014 2015 2016 2017 2018 2019
void virDomainShmemDefFree(virDomainShmemDefPtr def)
{
    if (!def)
        return;

    virDomainDeviceInfoClear(&def->info);
2020
    virDomainChrSourceDefClear(&def->server.chr);
2021 2022 2023 2024
    VIR_FREE(def->name);
    VIR_FREE(def);
}

2025 2026 2027 2028 2029
void virDomainVideoDefFree(virDomainVideoDefPtr def)
{
    if (!def)
        return;

2030 2031
    virDomainDeviceInfoClear(&def->info);

2032
    VIR_FREE(def->accel);
2033 2034 2035
    VIR_FREE(def);
}

2036 2037 2038 2039
virDomainHostdevDefPtr virDomainHostdevDefAlloc(void)
{
    virDomainHostdevDefPtr def = NULL;

2040 2041
    if (VIR_ALLOC(def) < 0 ||
        VIR_ALLOC(def->info) < 0)
2042 2043 2044 2045
        VIR_FREE(def);
    return def;
}

2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
static void
virDomainHostdevSubsysSCSIiSCSIClear(virDomainHostdevSubsysSCSIiSCSIPtr iscsisrc)
{
    if (!iscsisrc)
        return;
    VIR_FREE(iscsisrc->path);
    virStorageNetHostDefFree(iscsisrc->nhosts, iscsisrc->hosts);
    virStorageAuthDefFree(iscsisrc->auth);
    iscsisrc->auth = NULL;
}

2057 2058
void virDomainHostdevDefClear(virDomainHostdevDefPtr def)
{
2059 2060
    size_t i;

2061 2062 2063 2064 2065 2066 2067
    if (!def)
        return;

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

2068 2069 2070 2071 2072
    /* If there is a parent device object, it will handle freeing
     * def->info.
     */
    if (def->parent.type == VIR_DOMAIN_DEVICE_NONE)
        virDomainDeviceInfoFree(def->info);
2073

H
Han Cheng 已提交
2074 2075
    switch (def->mode) {
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
2076 2077 2078 2079 2080 2081 2082
        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;
2083 2084
        case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_NET:
            VIR_FREE(def->source.caps.u.net.iface);
2085 2086 2087
            for (i = 0; i < def->source.caps.u.net.nips; i++)
                VIR_FREE(def->source.caps.u.net.ips[i]);
            VIR_FREE(def->source.caps.u.net.ips);
2088
            for (i = 0; i < def->source.caps.u.net.nroutes; i++)
2089
                virNetworkRouteDefFree(def->source.caps.u.net.routes[i]);
2090
            VIR_FREE(def->source.caps.u.net.routes);
2091
            break;
2092
        }
H
Han Cheng 已提交
2093 2094
        break;
    case VIR_DOMAIN_HOSTDEV_MODE_SUBSYS:
2095 2096 2097 2098 2099 2100 2101 2102 2103
        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 已提交
2104
        break;
2105
    }
2106 2107
}

2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
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);
}

2125 2126 2127 2128 2129
void virDomainHostdevDefFree(virDomainHostdevDefPtr def)
{
    if (!def)
        return;

2130 2131 2132
    /* free all subordinate objects */
    virDomainHostdevDefClear(def);

2133 2134 2135 2136 2137
    /* If there is a parent device object, it will handle freeing
     * the memory.
     */
    if (def->parent.type == VIR_DOMAIN_DEVICE_NONE)
        VIR_FREE(def);
2138 2139
}

M
Marc-André Lureau 已提交
2140 2141 2142 2143 2144 2145 2146 2147 2148
void virDomainHubDefFree(virDomainHubDefPtr def)
{
    if (!def)
        return;

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

2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
void virDomainRedirdevDefFree(virDomainRedirdevDefPtr def)
{
    if (!def)
        return;

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

    VIR_FREE(def);
}

2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173
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);
}

2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
void virDomainMemoryDefFree(virDomainMemoryDefPtr def)
{
    if (!def)
        return;

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

2184 2185 2186 2187 2188
void virDomainDeviceDefFree(virDomainDeviceDefPtr def)
{
    if (!def)
        return;

2189
    switch ((virDomainDeviceType) def->type) {
2190 2191 2192
    case VIR_DOMAIN_DEVICE_DISK:
        virDomainDiskDefFree(def->data.disk);
        break;
2193 2194 2195
    case VIR_DOMAIN_DEVICE_LEASE:
        virDomainLeaseDefFree(def->data.lease);
        break;
2196 2197 2198 2199 2200 2201 2202 2203 2204
    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;
2205 2206 2207
    case VIR_DOMAIN_DEVICE_VIDEO:
        virDomainVideoDefFree(def->data.video);
        break;
2208 2209 2210
    case VIR_DOMAIN_DEVICE_HOSTDEV:
        virDomainHostdevDefFree(def->data.hostdev);
        break;
R
Richard Jones 已提交
2211 2212 2213
    case VIR_DOMAIN_DEVICE_WATCHDOG:
        virDomainWatchdogDefFree(def->data.watchdog);
        break;
2214 2215 2216
    case VIR_DOMAIN_DEVICE_CONTROLLER:
        virDomainControllerDefFree(def->data.controller);
        break;
2217 2218 2219
    case VIR_DOMAIN_DEVICE_GRAPHICS:
        virDomainGraphicsDefFree(def->data.graphics);
        break;
M
Marc-André Lureau 已提交
2220 2221 2222
    case VIR_DOMAIN_DEVICE_HUB:
        virDomainHubDefFree(def->data.hub);
        break;
2223 2224 2225
    case VIR_DOMAIN_DEVICE_REDIRDEV:
        virDomainRedirdevDefFree(def->data.redirdev);
        break;
2226 2227 2228
    case VIR_DOMAIN_DEVICE_RNG:
        virDomainRNGDefFree(def->data.rng);
        break;
2229 2230 2231
    case VIR_DOMAIN_DEVICE_CHR:
        virDomainChrDefFree(def->data.chr);
        break;
2232
    case VIR_DOMAIN_DEVICE_FS:
2233 2234
        virDomainFSDefFree(def->data.fs);
        break;
2235
    case VIR_DOMAIN_DEVICE_SMARTCARD:
2236 2237
        virDomainSmartcardDefFree(def->data.smartcard);
        break;
2238
    case VIR_DOMAIN_DEVICE_MEMBALLOON:
2239 2240
        virDomainMemballoonDefFree(def->data.memballoon);
        break;
L
Li Zhang 已提交
2241
    case VIR_DOMAIN_DEVICE_NVRAM:
2242 2243
        virDomainNVRAMDefFree(def->data.nvram);
        break;
2244 2245 2246
    case VIR_DOMAIN_DEVICE_SHMEM:
        virDomainShmemDefFree(def->data.shmem);
        break;
2247 2248 2249
    case VIR_DOMAIN_DEVICE_TPM:
        virDomainTPMDefFree(def->data.tpm);
        break;
2250 2251 2252
    case VIR_DOMAIN_DEVICE_PANIC:
        virDomainPanicDefFree(def->data.panic);
        break;
2253 2254 2255
    case VIR_DOMAIN_DEVICE_MEMORY:
        virDomainMemoryDefFree(def->data.memory);
        break;
2256
    case VIR_DOMAIN_DEVICE_LAST:
2257
    case VIR_DOMAIN_DEVICE_NONE:
2258
        break;
2259 2260 2261 2262 2263
    }

    VIR_FREE(def);
}

2264 2265 2266 2267 2268 2269
static void
virDomainClockDefClear(virDomainClockDefPtr def)
{
    if (def->offset == VIR_DOMAIN_CLOCK_OFFSET_TIMEZONE)
        VIR_FREE(def->data.timezone);

2270
    size_t i;
2271 2272 2273 2274 2275
    for (i = 0; i < def->ntimers; i++)
        VIR_FREE(def->timers[i]);
    VIR_FREE(def->timers);
}

2276

2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
static bool
virDomainIOThreadIDArrayHasPin(virDomainDefPtr def)
{
    size_t i;

    for (i = 0; i < def->niothreadids; i++) {
        if (def->iothreadids[i]->cpumask)
            return true;
    }
    return false;
}


2290 2291 2292 2293 2294
void
virDomainIOThreadIDDefFree(virDomainIOThreadIDDefPtr def)
{
    if (!def)
        return;
2295
    virBitmapFree(def->cpumask);
2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315
    VIR_FREE(def);
}


static void
virDomainIOThreadIDDefArrayFree(virDomainIOThreadIDDefPtr *def,
                                int nids)
{
    size_t i;

    if (!def)
        return;

    for (i = 0; i < nids; i++)
        virDomainIOThreadIDDefFree(def[i]);

    VIR_FREE(def);
}


2316 2317 2318 2319
static int
virDomainIOThreadIDDefArrayInit(virDomainDefPtr def)
{
    int retval = -1;
2320 2321 2322 2323
    size_t i;
    ssize_t nxt = -1;
    virDomainIOThreadIDDefPtr iothrid = NULL;
    virBitmapPtr thrmap = NULL;
2324 2325 2326 2327 2328 2329 2330

    /* Same value (either 0 or some number), then we have none to fill in or
     * the iothreadid array was filled from the XML
     */
    if (def->iothreads == def->niothreadids)
        return 0;

2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
    /* iothread's are numbered starting at 1, account for that */
    if (!(thrmap = virBitmapNew(def->iothreads + 1)))
        goto error;
    virBitmapSetAll(thrmap);

    /* Clear 0 since we don't use it, then mark those which are
     * already provided by the user */
    ignore_value(virBitmapClearBit(thrmap, 0));
    for (i = 0; i < def->niothreadids; i++)
        ignore_value(virBitmapClearBit(thrmap,
                                       def->iothreadids[i]->iothread_id));

    /* resize array */
    if (VIR_REALLOC_N(def->iothreadids, def->iothreads) < 0)
        goto error;
2346

2347 2348 2349 2350 2351 2352
    /* Populate iothreadids[] using the set bit number from thrmap */
    while (def->niothreadids < def->iothreads) {
        if ((nxt = virBitmapNextSetBit(thrmap, nxt)) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("failed to populate iothreadids"));
            goto error;
2353
        }
2354 2355 2356 2357 2358
        if (VIR_ALLOC(iothrid) < 0)
            goto error;
        iothrid->iothread_id = nxt;
        iothrid->autofill = true;
        def->iothreadids[def->niothreadids++] = iothrid;
2359
    }
2360

2361 2362 2363
    retval = 0;

 error:
2364
    virBitmapFree(thrmap);
2365 2366 2367 2368
    return retval;
}


2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
void
virDomainResourceDefFree(virDomainResourceDefPtr resource)
{
    if (!resource)
        return;

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

H
Hu Tao 已提交
2379 2380 2381 2382 2383 2384 2385 2386 2387
void
virDomainPanicDefFree(virDomainPanicDefPtr panic)
{
    if (!panic)
        return;

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

2389 2390 2391 2392 2393 2394 2395 2396
void
virDomainLoaderDefFree(virDomainLoaderDefPtr loader)
{
    if (!loader)
        return;

    VIR_FREE(loader->path);
    VIR_FREE(loader->nvram);
2397
    VIR_FREE(loader->templt);
2398 2399 2400
    VIR_FREE(loader);
}

2401 2402
void virDomainDefFree(virDomainDefPtr def)
{
2403
    size_t i;
2404

2405 2406 2407
    if (!def)
        return;

2408 2409
    virDomainResourceDefFree(def->resource);

2410 2411 2412 2413
    for (i = 0; i < def->maxvcpus; i++)
        virDomainVcpuInfoClear(&def->vcpus[i]);
    VIR_FREE(def->vcpus);

2414 2415 2416 2417 2418 2419
    /* 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().
     */
2420
    for (i = 0; i < def->nhostdevs; i++)
2421 2422 2423
        virDomainHostdevDefFree(def->hostdevs[i]);
    VIR_FREE(def->hostdevs);

2424
    for (i = 0; i < def->nleases; i++)
2425 2426 2427
        virDomainLeaseDefFree(def->leases[i]);
    VIR_FREE(def->leases);

2428
    for (i = 0; i < def->ngraphics; i++)
2429 2430
        virDomainGraphicsDefFree(def->graphics[i]);
    VIR_FREE(def->graphics);
2431

2432
    for (i = 0; i < def->ninputs; i++)
2433 2434 2435
        virDomainInputDefFree(def->inputs[i]);
    VIR_FREE(def->inputs);

2436
    for (i = 0; i < def->ndisks; i++)
2437 2438 2439
        virDomainDiskDefFree(def->disks[i]);
    VIR_FREE(def->disks);

2440
    for (i = 0; i < def->ncontrollers; i++)
2441 2442 2443
        virDomainControllerDefFree(def->controllers[i]);
    VIR_FREE(def->controllers);

2444
    for (i = 0; i < def->nfss; i++)
2445 2446 2447
        virDomainFSDefFree(def->fss[i]);
    VIR_FREE(def->fss);

2448
    for (i = 0; i < def->nnets; i++)
2449 2450
        virDomainNetDefFree(def->nets[i]);
    VIR_FREE(def->nets);
2451

2452
    for (i = 0; i < def->nsmartcards; i++)
E
Eric Blake 已提交
2453 2454 2455
        virDomainSmartcardDefFree(def->smartcards[i]);
    VIR_FREE(def->smartcards);

2456
    for (i = 0; i < def->nserials; i++)
2457 2458 2459
        virDomainChrDefFree(def->serials[i]);
    VIR_FREE(def->serials);

2460
    for (i = 0; i < def->nparallels; i++)
2461 2462 2463
        virDomainChrDefFree(def->parallels[i]);
    VIR_FREE(def->parallels);

2464
    for (i = 0; i < def->nchannels; i++)
2465 2466 2467
        virDomainChrDefFree(def->channels[i]);
    VIR_FREE(def->channels);

2468
    for (i = 0; i < def->nconsoles; i++)
2469 2470
        virDomainChrDefFree(def->consoles[i]);
    VIR_FREE(def->consoles);
2471

2472
    for (i = 0; i < def->nsounds; i++)
2473 2474 2475
        virDomainSoundDefFree(def->sounds[i]);
    VIR_FREE(def->sounds);

2476
    for (i = 0; i < def->nvideos; i++)
2477 2478 2479
        virDomainVideoDefFree(def->videos[i]);
    VIR_FREE(def->videos);

2480
    for (i = 0; i < def->nhubs; i++)
M
Marc-André Lureau 已提交
2481 2482 2483
        virDomainHubDefFree(def->hubs[i]);
    VIR_FREE(def->hubs);

2484
    for (i = 0; i < def->nredirdevs; i++)
2485 2486 2487
        virDomainRedirdevDefFree(def->redirdevs[i]);
    VIR_FREE(def->redirdevs);

2488 2489 2490
    for (i = 0; i < def->nrngs; i++)
        virDomainRNGDefFree(def->rngs[i]);
    VIR_FREE(def->rngs);
2491

2492 2493 2494 2495
    for (i = 0; i < def->nmems; i++)
        virDomainMemoryDefFree(def->mems[i]);
    VIR_FREE(def->mems);

2496 2497
    virDomainTPMDefFree(def->tpm);

D
Dmitry Andreev 已提交
2498 2499 2500
    for (i = 0; i < def->npanics; i++)
        virDomainPanicDefFree(def->panics[i]);
    VIR_FREE(def->panics);
H
Hu Tao 已提交
2501

2502 2503 2504
    VIR_FREE(def->idmap.uidmap);
    VIR_FREE(def->idmap.gidmap);

2505
    VIR_FREE(def->os.machine);
2506
    VIR_FREE(def->os.init);
2507
    for (i = 0; def->os.initargv && def->os.initargv[i]; i++)
2508 2509
        VIR_FREE(def->os.initargv[i]);
    VIR_FREE(def->os.initargv);
2510 2511 2512
    VIR_FREE(def->os.kernel);
    VIR_FREE(def->os.initrd);
    VIR_FREE(def->os.cmdline);
2513
    VIR_FREE(def->os.dtb);
2514
    VIR_FREE(def->os.root);
2515
    virDomainLoaderDefFree(def->os.loader);
2516 2517 2518
    VIR_FREE(def->os.bootloader);
    VIR_FREE(def->os.bootloaderArgs);

2519
    virDomainClockDefClear(&def->clock);
2520

2521
    VIR_FREE(def->name);
2522
    virBitmapFree(def->cpumask);
2523
    VIR_FREE(def->emulator);
2524
    VIR_FREE(def->description);
2525
    VIR_FREE(def->title);
2526

2527 2528
    virBlkioDeviceArrayClear(def->blkio.devices,
                             def->blkio.ndevices);
2529 2530
    VIR_FREE(def->blkio.devices);

R
Richard Jones 已提交
2531 2532
    virDomainWatchdogDefFree(def->watchdog);

C
Chris Lalancette 已提交
2533
    virDomainMemballoonDefFree(def->memballoon);
L
Li Zhang 已提交
2534
    virDomainNVRAMDefFree(def->nvram);
C
Chris Lalancette 已提交
2535

2536 2537 2538 2539
    for (i = 0; i < def->mem.nhugepages; i++)
        virBitmapFree(def->mem.hugepages[i].nodemask);
    VIR_FREE(def->mem.hugepages);

2540 2541 2542
    for (i = 0; i < def->nseclabels; i++)
        virSecurityLabelDefFree(def->seclabels[i]);
    VIR_FREE(def->seclabels);
2543

2544 2545
    virCPUDefFree(def->cpu);

2546 2547
    virDomainIOThreadIDDefArrayFree(def->iothreadids, def->niothreadids);

2548
    virBitmapFree(def->cputune.emulatorpin);
2549

2550 2551 2552 2553 2554 2555 2556 2557
    for (i = 0; i < def->cputune.nvcpusched; i++)
        virBitmapFree(def->cputune.vcpusched[i].ids);
    VIR_FREE(def->cputune.vcpusched);

    for (i = 0; i < def->cputune.niothreadsched; i++)
        virBitmapFree(def->cputune.iothreadsched[i].ids);
    VIR_FREE(def->cputune.iothreadsched);

2558
    virDomainNumaFree(def->numa);
O
Osier Yang 已提交
2559

2560 2561
    virSysinfoDefFree(def->sysinfo);

2562 2563
    virDomainRedirFilterDefFree(def->redirfilter);

2564 2565 2566 2567
    for (i = 0; i < def->nshmems; i++)
        virDomainShmemDefFree(def->shmems[i]);
    VIR_FREE(def->shmems);

2568 2569
    VIR_FREE(def->keywrap);

2570 2571 2572
    if (def->namespaceData && def->ns.free)
        (def->ns.free)(def->namespaceData);

2573 2574
    xmlFreeNode(def->metadata);

2575 2576 2577
    VIR_FREE(def);
}

2578
static void virDomainObjDispose(void *obj)
2579
{
2580
    virDomainObjPtr dom = obj;
2581

2582
    VIR_DEBUG("obj=%p", dom);
2583
    virCondDestroy(&dom->cond);
2584 2585 2586
    virDomainDefFree(dom->def);
    virDomainDefFree(dom->newDef);

2587 2588 2589
    if (dom->privateDataFreeFunc)
        (dom->privateDataFreeFunc)(dom->privateData);

2590
    virDomainSnapshotObjListFree(dom->snapshots);
2591 2592
}

2593
virDomainObjPtr
2594
virDomainObjNew(virDomainXMLOptionPtr xmlopt)
2595 2596 2597
{
    virDomainObjPtr domain;

2598 2599 2600
    if (virDomainObjInitialize() < 0)
        return NULL;

2601
    if (!(domain = virObjectLockableNew(virDomainObjClass)))
2602 2603
        return NULL;

2604 2605 2606 2607 2608 2609
    if (virCondInit(&domain->cond) < 0) {
        virReportSystemError(errno, "%s",
                             _("failed to initialize domain condition"));
        goto error;
    }

2610
    if (xmlopt->privateData.alloc) {
2611
        if (!(domain->privateData = (xmlopt->privateData.alloc)()))
2612
            goto error;
2613
        domain->privateDataFreeFunc = xmlopt->privateData.free;
2614 2615 2616 2617 2618
    }

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

2619
    virObjectLock(domain);
J
Jiri Denemark 已提交
2620 2621
    virDomainObjSetState(domain, VIR_DOMAIN_SHUTOFF,
                                 VIR_DOMAIN_SHUTOFF_UNKNOWN);
2622

2623
    VIR_DEBUG("obj=%p", domain);
2624
    return domain;
2625

2626
 error:
2627 2628
    virObjectUnref(domain);
    return NULL;
2629 2630
}

2631

2632 2633 2634 2635 2636
virDomainDefPtr
virDomainDefNew(void)
{
    virDomainDefPtr ret;

2637 2638 2639 2640 2641
    if (VIR_ALLOC(ret) < 0)
        return NULL;

    if (!(ret->numa = virDomainNumaNew()))
        goto error;
2642

2643 2644 2645 2646
    ret->mem.hard_limit = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
    ret->mem.soft_limit = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
    ret->mem.swap_hard_limit = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

2647
    return ret;
2648 2649 2650 2651

 error:
    virDomainDefFree(ret);
    return NULL;
2652 2653 2654 2655 2656 2657 2658
}


virDomainDefPtr
virDomainDefNewFull(const char *name,
                    const unsigned char *uuid,
                    int id)
2659 2660 2661
{
    virDomainDefPtr def;

2662
    if (!(def = virDomainDefNew()))
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676
        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;
}


2677
void virDomainObjAssignDef(virDomainObjPtr domain,
2678
                           virDomainDefPtr def,
2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690
                           bool live,
                           virDomainDefPtr *oldDef)
{
    if (oldDef)
        *oldDef = NULL;
    if (virDomainObjIsActive(domain)) {
        if (oldDef)
            *oldDef = domain->newDef;
        else
            virDomainDefFree(domain->newDef);
        domain->newDef = def;
    } else {
2691
        if (live) {
2692 2693 2694 2695 2696
            /* save current configuration to be restored on domain shutdown */
            if (!domain->newDef)
                domain->newDef = domain->def;
            else
                virDomainDefFree(domain->def);
2697 2698
            domain->def = def;
        } else {
2699 2700 2701 2702
            if (oldDef)
                *oldDef = domain->def;
            else
                virDomainDefFree(domain->def);
2703 2704 2705 2706 2707
            domain->def = def;
        }
    }
}

2708

M
Michal Privoznik 已提交
2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
/**
 * virDomainObjEndAPI:
 * @vm: domain object
 *
 * Finish working with a domain object in an API.  This function
 * clears whatever was left of a domain that was gathered using
 * virDomainObjListFindByUUIDRef(). Currently that means only unlocking and
 * decrementing the reference counter of that domain.  And in order to
 * make sure the caller does not access the domain, the pointer is
 * cleared.
 */
void
virDomainObjEndAPI(virDomainObjPtr *vm)
{
    if (!*vm)
        return;

    virObjectUnlock(*vm);
    virObjectUnref(*vm);
    *vm = NULL;
}

2731

2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
void
virDomainObjBroadcast(virDomainObjPtr vm)
{
    virCondBroadcast(&vm->cond);
}


int
virDomainObjWait(virDomainObjPtr vm)
{
    if (virCondWait(&vm->cond, &vm->parent.lock) < 0) {
        virReportSystemError(errno, "%s",
                             _("failed to wait for domain condition"));
        return -1;
    }
    return 0;
}


2751 2752 2753 2754 2755 2756 2757 2758
/**
 * Waits for domain condition to be triggered for a specific period of time.
 *
 * Returns:
 *  -1 in case of error
 *  0 on success
 *  1 on timeout
 */
2759 2760 2761 2762
int
virDomainObjWaitUntil(virDomainObjPtr vm,
                      unsigned long long whenms)
{
2763 2764 2765 2766 2767 2768 2769
    if (virCondWaitUntil(&vm->cond, &vm->parent.lock, whenms) < 0) {
        if (errno != ETIMEDOUT) {
            virReportSystemError(errno, "%s",
                                 _("failed to wait for domain condition"));
            return -1;
        }
        return 1;
2770 2771 2772 2773 2774
    }
    return 0;
}


2775 2776 2777 2778 2779
/*
 * 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 已提交
2780
 * @param xmlopt pointer to XML parser configuration object
2781
 * @param domain domain object pointer
2782 2783 2784 2785
 * @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.
2786 2787 2788 2789
 * @return 0 on success, -1 on failure
 */
int
virDomainObjSetDefTransient(virCapsPtr caps,
2790
                            virDomainXMLOptionPtr xmlopt,
2791 2792
                            virDomainObjPtr domain,
                            bool live)
2793 2794 2795
{
    int ret = -1;

2796
    if (!virDomainObjIsActive(domain) && !live)
2797 2798 2799 2800 2801 2802 2803 2804
        return 0;

    if (!domain->persistent)
        return 0;

    if (domain->newDef)
        return 0;

2805
    if (!(domain->newDef = virDomainDefCopy(domain->def, caps, xmlopt, false)))
2806 2807 2808
        goto out;

    ret = 0;
2809
 out:
2810 2811 2812
    return ret;
}

2813 2814 2815 2816 2817
/*
 * Return the persistent domain configuration. If domain is transient,
 * return the running config.
 *
 * @param caps pointer to capabilities info
W
Wang Rui 已提交
2818
 * @param xmlopt pointer to XML parser configuration object
2819 2820 2821 2822 2823
 * @param domain domain object pointer
 * @return NULL on error, virDOmainDefPtr on success
 */
virDomainDefPtr
virDomainObjGetPersistentDef(virCapsPtr caps,
2824
                             virDomainXMLOptionPtr xmlopt,
2825 2826
                             virDomainObjPtr domain)
{
2827
    if (virDomainObjSetDefTransient(caps, xmlopt, domain, false) < 0)
2828 2829 2830 2831 2832 2833 2834 2835
        return NULL;

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

2836 2837 2838

/**
 * virDomainObjUpdateModificationImpact:
2839
 *
2840 2841 2842 2843 2844 2845 2846 2847 2848
 * @vm: domain object
 * @flags: flags to update the modification impact on
 *
 * Resolves virDomainModificationImpact flags in @flags so that they correctly
 * apply to the actual state of @vm. @flags may be modified after call to this
 * function.
 *
 * Returns 0 on success if @flags point to a valid combination for @vm or -1 on
 * error.
2849 2850
 */
int
2851 2852
virDomainObjUpdateModificationImpact(virDomainObjPtr vm,
                                     unsigned int *flags)
2853
{
2854
    bool isActive = virDomainObjIsActive(vm);
2855 2856 2857 2858 2859 2860 2861 2862 2863 2864

    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)) {
2865 2866
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain is not running"));
2867
        return -1;
2868 2869 2870
    }

    if (*flags & VIR_DOMAIN_AFFECT_CONFIG) {
2871
        if (!vm->persistent) {
2872
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
2873 2874
                           _("transient domains do not have any "
                             "persistent config"));
2875
            return -1;
2876
        }
2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900
    }

    return 0;
}


/*
 * 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,
                                virDomainXMLOptionPtr xmlopt,
                                virDomainObjPtr dom,
                                unsigned int *flags,
                                virDomainDefPtr *persistentDef)
{
    if (virDomainObjUpdateModificationImpact(dom, flags) < 0)
        return -1;

    if (*flags & VIR_DOMAIN_AFFECT_CONFIG) {
2901
        if (!(*persistentDef = virDomainObjGetPersistentDef(caps, xmlopt, dom))) {
2902 2903
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Get persistent config failed"));
2904
            return -1;
2905 2906 2907
        }
    }

2908 2909
    return 0;
}
2910

2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938

/**
 * virDomainObjGetDefs:
 *
 * @vm: domain object
 * @flags: for virDomainModificationImpact
 * @liveDef: Set to the pointer to the live definition of @vm.
 * @persDef: Set to the pointer to the config definition of @vm.
 *
 * Helper function to resolve @flags and retrieve correct domain pointer
 * objects. This function should be used only when the hypervisor driver always
 * creates vm->newDef once the vm is started. (qemu driver does that)
 *
 * If @liveDef or @persDef are set it implies that @flags request modification
 * of thereof.
 *
 * Returns 0 on success and sets @liveDef and @persDef; -1 if @flags are
 * inappropriate.
 */
int
virDomainObjGetDefs(virDomainObjPtr vm,
                    unsigned int flags,
                    virDomainDefPtr *liveDef,
                    virDomainDefPtr *persDef)
{
    if (liveDef)
        *liveDef = NULL;

2939
    if (persDef)
2940 2941 2942 2943 2944
        *persDef = NULL;

    if (virDomainObjUpdateModificationImpact(vm, &flags) < 0)
        return -1;

2945 2946
    if (virDomainObjIsActive(vm)) {
        if (liveDef && (flags & VIR_DOMAIN_AFFECT_LIVE))
2947 2948
            *liveDef = vm->def;

2949
        if (persDef && (flags & VIR_DOMAIN_AFFECT_CONFIG))
2950
            *persDef = vm->newDef;
2951 2952 2953 2954 2955 2956
    } else {
        if (persDef)
            *persDef = vm->def;
    }

    return 0;
2957 2958
}

2959

2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995
/**
 * virDomainObjGetOneDef:
 *
 * @vm: Domain object
 * @flags: for virDomainModificationImpact
 *
 * Helper function to resolve @flags and return the correct domain pointer
 * object. This function returns one of @vm->def or @vm->persistentDef
 * according to @flags. This helper should be used only in APIs that guarantee
 * that @flags contains exactly one of VIR_DOMAIN_AFFECT_LIVE or
 * VIR_DOMAIN_AFFECT_CONFIG and not both.
 *
 * Returns the correct definition pointer or NULL on error.
 */
virDomainDefPtr
virDomainObjGetOneDef(virDomainObjPtr vm,
                      unsigned int flags)
{
    if (flags & VIR_DOMAIN_AFFECT_LIVE && flags & VIR_DOMAIN_AFFECT_CONFIG) {
            virReportInvalidArg(ctl, "%s",
                                _("Flags 'VIR_DOMAIN_AFFECT_LIVE' and "
                                  "'VIR_DOMAIN_AFFECT_CONFIG' are mutually "
                                  "exclusive"));
            return NULL;
    }

    if (virDomainObjUpdateModificationImpact(vm, &flags) < 0)
        return NULL;

    if (virDomainObjIsActive(vm) && flags & VIR_DOMAIN_AFFECT_CONFIG)
        return vm->newDef;
    else
        return vm->def;
}


2996 2997 2998 2999 3000 3001 3002
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;
}
3003

3004 3005 3006 3007 3008 3009 3010 3011
int virDomainDeviceAddressIsValid(virDomainDeviceInfoPtr info,
                                  int type)
{
    if (info->type != type)
        return 0;

    switch (info->type) {
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI:
3012
        return virDevicePCIAddressIsValid(&info->addr.pci, false);
3013 3014

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE:
3015
        return 1;
3016

3017
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390:
3018
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO:
3019 3020 3021 3022 3023
        return 1;

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

3024
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB:
3025
        return 1;
3026 3027 3028 3029 3030
    }

    return 0;
}

3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064
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;
3065 3066
    case VIR_DOMAIN_DEVICE_SHMEM:
        return &device->data.shmem->info;
3067 3068
    case VIR_DOMAIN_DEVICE_RNG:
        return &device->data.rng->info;
3069 3070
    case VIR_DOMAIN_DEVICE_TPM:
        return &device->data.tpm->info;
3071 3072
    case VIR_DOMAIN_DEVICE_PANIC:
        return &device->data.panic->info;
3073 3074
    case VIR_DOMAIN_DEVICE_MEMORY:
        return &device->data.memory->info;
3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085

    /* 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;
}

3086
static bool
3087
virDomainDeviceInfoNeedsFormat(virDomainDeviceInfoPtr info, unsigned int flags)
3088 3089
{
    if (info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
3090
        return true;
3091
    if (info->alias && !(flags & VIR_DOMAIN_DEF_FORMAT_INACTIVE))
3092 3093 3094
        return true;
    if (info->mastertype != VIR_DOMAIN_CONTROLLER_MASTER_NONE)
        return true;
J
Ján Tomko 已提交
3095
    if ((info->rombar != VIR_TRISTATE_SWITCH_ABSENT) ||
3096 3097 3098 3099 3100
        info->romfile)
        return true;
    if (info->bootIndex)
        return true;
    return false;
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 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164
static bool
virDomainDeviceInfoAddressIsEqual(const virDomainDeviceInfo *a,
                                  const virDomainDeviceInfo *b)
{

    if (a->type != b->type)
        return false;

    switch ((virDomainDeviceAddressType) a->type) {
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE:
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_LAST:
    /* address types below don't have any specific data */
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO:
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390:
        break;

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI:
        /* the 'multi' field shouldn't be checked */
        if (a->addr.pci.domain != b->addr.pci.domain ||
            a->addr.pci.bus != b->addr.pci.bus ||
            a->addr.pci.slot != b->addr.pci.slot ||
            a->addr.pci.function != b->addr.pci.function)
            return false;
        break;

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE:
        if (memcmp(&a->addr.drive, &b->addr.drive, sizeof(a->addr.drive)))
            return false;
        break;

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL:
        if (memcmp(&a->addr.vioserial, &b->addr.vioserial, sizeof(a->addr.vioserial)))
            return false;
        break;

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID:
        if (memcmp(&a->addr.ccid, &b->addr.ccid, sizeof(a->addr.ccid)))
            return false;
        break;

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB:
        if (memcmp(&a->addr.usb, &b->addr.usb, sizeof(a->addr.usb)))
            return false;
        break;

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO:
        if (memcmp(&a->addr.spaprvio, &b->addr.spaprvio, sizeof(a->addr.spaprvio)))
            return false;
        break;

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW:
        /* the 'assigned' field denotes that the address was generated */
        if (a->addr.ccw.cssid != b->addr.ccw.cssid ||
            a->addr.ccw.ssid != b->addr.ccw.ssid ||
            a->addr.ccw.devno != b->addr.ccw.devno)
            return false;
        break;

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_ISA:
        if (memcmp(&a->addr.isa, &b->addr.isa, sizeof(a->addr.isa)))
            return false;
        break;
3165 3166 3167 3168 3169

    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM:
        if (memcmp(&a->addr.dimm, &b->addr.dimm, sizeof(a->addr.dimm)))
            return false;
        break;
3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191
    }

    return true;
}


static int
virDomainDefHasDeviceAddressIterator(virDomainDefPtr def ATTRIBUTE_UNUSED,
                                     virDomainDeviceDefPtr dev ATTRIBUTE_UNUSED,
                                     virDomainDeviceInfoPtr info,
                                     void *opaque)
{
    virDomainDeviceInfoPtr needle = opaque;

    /* break iteration if the info was found */
    if (virDomainDeviceInfoAddressIsEqual(info, needle))
        return -1;

    return 0;
}


3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204
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;

3205 3206
    if (VIR_STRDUP(dst->alias, src->alias) < 0 ||
        VIR_STRDUP(dst->romfile, src->romfile) < 0)
3207 3208 3209 3210
        return -1;
    return 0;
}

3211 3212
void virDomainDeviceInfoClear(virDomainDeviceInfoPtr info)
{
3213
    VIR_FREE(info->alias);
3214
    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB)
3215
        VIR_FREE(info->addr.usb.port);
3216 3217
    memset(&info->addr, 0, sizeof(info->addr));
    info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE;
3218
    VIR_FREE(info->romfile);
3219 3220 3221
}


3222
static int virDomainDeviceInfoClearAlias(virDomainDefPtr def ATTRIBUTE_UNUSED,
3223
                                         virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
3224 3225
                                         virDomainDeviceInfoPtr info,
                                         void *opaque ATTRIBUTE_UNUSED)
3226
{
3227 3228 3229 3230 3231
    VIR_FREE(info->alias);
    return 0;
}

static int virDomainDeviceInfoClearPCIAddress(virDomainDefPtr def ATTRIBUTE_UNUSED,
3232
                                              virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
3233 3234 3235 3236
                                              virDomainDeviceInfoPtr info,
                                              void *opaque ATTRIBUTE_UNUSED)
{
    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
3237 3238 3239
        memset(&info->addr, 0, sizeof(info->addr));
        info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE;
    }
3240
    return 0;
3241 3242
}

3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255
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;
}

3256 3257 3258 3259 3260
static int
virDomainDeviceInfoIterateInternal(virDomainDefPtr def,
                                   virDomainDeviceInfoCallback cb,
                                   bool all,
                                   void *opaque)
3261
{
3262
    size_t i;
3263
    virDomainDeviceDef device;
3264

3265
    device.type = VIR_DOMAIN_DEVICE_DISK;
3266
    for (i = 0; i < def->ndisks; i++) {
3267 3268
        device.data.disk = def->disks[i];
        if (cb(def, &device, &def->disks[i]->info, opaque) < 0)
3269
            return -1;
3270 3271
    }
    device.type = VIR_DOMAIN_DEVICE_NET;
3272
    for (i = 0; i < def->nnets; i++) {
3273 3274
        device.data.net = def->nets[i];
        if (cb(def, &device, &def->nets[i]->info, opaque) < 0)
3275
            return -1;
3276 3277
    }
    device.type = VIR_DOMAIN_DEVICE_SOUND;
3278
    for (i = 0; i < def->nsounds; i++) {
3279 3280
        device.data.sound = def->sounds[i];
        if (cb(def, &device, &def->sounds[i]->info, opaque) < 0)
3281
            return -1;
3282 3283
    }
    device.type = VIR_DOMAIN_DEVICE_HOSTDEV;
3284
    for (i = 0; i < def->nhostdevs; i++) {
3285
        device.data.hostdev = def->hostdevs[i];
3286
        if (cb(def, &device, def->hostdevs[i]->info, opaque) < 0)
3287
            return -1;
3288 3289
    }
    device.type = VIR_DOMAIN_DEVICE_VIDEO;
3290
    for (i = 0; i < def->nvideos; i++) {
3291 3292
        device.data.video = def->videos[i];
        if (cb(def, &device, &def->videos[i]->info, opaque) < 0)
3293
            return -1;
3294 3295
    }
    device.type = VIR_DOMAIN_DEVICE_CONTROLLER;
3296
    for (i = 0; i < def->ncontrollers; i++) {
3297 3298
        device.data.controller = def->controllers[i];
        if (cb(def, &device, &def->controllers[i]->info, opaque) < 0)
3299
            return -1;
3300 3301
    }
    device.type = VIR_DOMAIN_DEVICE_SMARTCARD;
3302
    for (i = 0; i < def->nsmartcards; i++) {
3303 3304
        device.data.smartcard = def->smartcards[i];
        if (cb(def, &device, &def->smartcards[i]->info, opaque) < 0)
E
Eric Blake 已提交
3305
            return -1;
3306 3307
    }
    device.type = VIR_DOMAIN_DEVICE_CHR;
3308
    for (i = 0; i < def->nserials; i++) {
3309 3310
        device.data.chr = def->serials[i];
        if (cb(def, &device, &def->serials[i]->info, opaque) < 0)
3311
            return -1;
3312
    }
3313
    for (i = 0; i < def->nparallels; i++) {
3314 3315
        device.data.chr = def->parallels[i];
        if (cb(def, &device, &def->parallels[i]->info, opaque) < 0)
3316
            return -1;
3317
    }
3318
    for (i = 0; i < def->nchannels; i++) {
3319 3320
        device.data.chr = def->channels[i];
        if (cb(def, &device, &def->channels[i]->info, opaque) < 0)
3321
            return -1;
3322
    }
3323
    for (i = 0; i < def->nconsoles; i++) {
3324 3325 3326 3327
        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) &&
3328
             def->os.type == VIR_DOMAIN_OSTYPE_HVM)
3329
            continue;
3330 3331
        device.data.chr = def->consoles[i];
        if (cb(def, &device, &def->consoles[i]->info, opaque) < 0)
3332
            return -1;
3333 3334
    }
    device.type = VIR_DOMAIN_DEVICE_INPUT;
3335
    for (i = 0; i < def->ninputs; i++) {
3336 3337
        device.data.input = def->inputs[i];
        if (cb(def, &device, &def->inputs[i]->info, opaque) < 0)
3338
            return -1;
3339 3340
    }
    device.type = VIR_DOMAIN_DEVICE_FS;
3341
    for (i = 0; i < def->nfss; i++) {
3342 3343
        device.data.fs = def->fss[i];
        if (cb(def, &device, &def->fss[i]->info, opaque) < 0)
3344
            return -1;
3345 3346 3347 3348 3349
    }
    if (def->watchdog) {
        device.type = VIR_DOMAIN_DEVICE_WATCHDOG;
        device.data.watchdog = def->watchdog;
        if (cb(def, &device, &def->watchdog->info, opaque) < 0)
3350
            return -1;
3351 3352 3353 3354 3355
    }
    if (def->memballoon) {
        device.type = VIR_DOMAIN_DEVICE_MEMBALLOON;
        device.data.memballoon = def->memballoon;
        if (cb(def, &device, &def->memballoon->info, opaque) < 0)
3356
            return -1;
3357
    }
3358 3359 3360 3361
    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)
3362 3363
            return -1;
    }
L
Li Zhang 已提交
3364 3365 3366 3367 3368 3369
    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;
    }
3370
    device.type = VIR_DOMAIN_DEVICE_HUB;
3371
    for (i = 0; i < def->nhubs; i++) {
3372 3373
        device.data.hub = def->hubs[i];
        if (cb(def, &device, &def->hubs[i]->info, opaque) < 0)
M
Marc-André Lureau 已提交
3374
            return -1;
3375
    }
3376 3377 3378 3379 3380 3381
    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;
    }
3382 3383 3384 3385 3386 3387
    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;
    }
D
Dmitry Andreev 已提交
3388 3389 3390 3391
    device.type = VIR_DOMAIN_DEVICE_PANIC;
    for (i = 0; i < def->npanics; i++) {
        device.data.panic = def->panics[i];
        if (cb(def, &device, &def->panics[i]->info, opaque) < 0)
3392 3393
            return -1;
    }
3394

3395 3396 3397 3398 3399 3400 3401
    device.type = VIR_DOMAIN_DEVICE_MEMORY;
    for (i = 0; i < def->nmems; i++) {
        device.data.memory = def->mems[i];
        if (cb(def, &device, &def->mems[i]->info, opaque) < 0)
            return -1;
    }

3402 3403
    /* Coverity is not very happy with this - all dead_error_condition */
#if !STATIC_ANALYSIS
3404
    /* This switch statement is here to trigger compiler warning when adding
E
Eric Blake 已提交
3405
     * a new device type. When you are adding a new field to the switch you
M
Martin Kletzander 已提交
3406
     * also have to add an iteration statement above. Otherwise the switch
3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427
     * 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 已提交
3428
    case VIR_DOMAIN_DEVICE_NVRAM:
3429
    case VIR_DOMAIN_DEVICE_SHMEM:
3430
    case VIR_DOMAIN_DEVICE_TPM:
3431
    case VIR_DOMAIN_DEVICE_PANIC:
3432
    case VIR_DOMAIN_DEVICE_LAST:
3433
    case VIR_DOMAIN_DEVICE_RNG:
3434
    case VIR_DOMAIN_DEVICE_MEMORY:
3435 3436
        break;
    }
3437
#endif
3438

3439
    return 0;
3440 3441 3442
}


3443 3444 3445 3446 3447 3448 3449 3450 3451
int
virDomainDeviceInfoIterate(virDomainDefPtr def,
                           virDomainDeviceInfoCallback cb,
                           void *opaque)
{
    return virDomainDeviceInfoIterateInternal(def, cb, false, opaque);
}


3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465
bool
virDomainDefHasDeviceAddress(virDomainDefPtr def,
                             virDomainDeviceInfoPtr info)
{
    if (virDomainDeviceInfoIterateInternal(def,
                                           virDomainDefHasDeviceAddressIterator,
                                           true,
                                           info) < 0)
        return true;

    return false;
}


3466 3467 3468 3469 3470 3471 3472 3473
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;
3474
    size_t i;
3475 3476 3477 3478 3479

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

    for (i = 0; i < def->ncontrollers; i++) {
        cont = def->controllers[i];
3480
        if ((int) cont->idx > max_idx[cont->type])
3481 3482 3483 3484 3485 3486 3487 3488
            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)))
3489
            goto cleanup;
3490 3491 3492 3493 3494 3495 3496 3497 3498
        nbitmaps++;
    }

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

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

J
Ján Tomko 已提交
3499
        if (virBitmapIsBitSet(bitmaps[cont->type], cont->idx)) {
3500 3501 3502 3503 3504 3505 3506 3507 3508 3509
            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;
3510
 cleanup:
3511 3512 3513 3514 3515
    for (i = 0; i < nbitmaps; i++)
        virBitmapFree(bitmaps[i]);
    return ret;
}

3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537
static int
virDomainDefRejectDuplicatePanics(virDomainDefPtr def)
{
    bool exists[VIR_DOMAIN_PANIC_MODEL_LAST];
    size_t i;

    for (i = 0; i < VIR_DOMAIN_PANIC_MODEL_LAST; i++)
         exists[i] = false;

    for (i = 0; i < def->npanics; i++) {
        virDomainPanicModel model = def->panics[i]->model;
        if (exists[model]) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("Multiple panic devices with model '%s'"),
                           virDomainPanicModelTypeToString(model));
            return -1;
        }
        exists[model] = true;
    }

    return 0;
}
3538

3539
/**
3540 3541
 * virDomainDefMetadataSanitize:
 * @def: Sanitize metadata for this def
3542 3543
 *
 * This function removes metadata elements in @def that share the namespace.
3544 3545
 * The first metadata entry of every duplicate namespace is kept. Additionally
 * elements with no namespace are deleted.
3546 3547
 */
static void
3548
virDomainDefMetadataSanitize(virDomainDefPtr def)
3549 3550 3551
{
    xmlNodePtr child;
    xmlNodePtr next;
3552
    xmlNodePtr dupl;
3553 3554 3555 3556

    if (!def || !def->metadata)
        return;

3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568
    child = def->metadata->children;
    while (child) {
        /* remove metadata entries that don't have any namespace at all */
        if (!child->ns || !child->ns->href) {
            dupl = child;
            child = child->next;

            xmlUnlinkNode(dupl);
            xmlFreeNode(dupl);
            continue;
        }

3569 3570 3571 3572
        /* check that every other child of @root doesn't share the namespace of
         * the current one and delete them possibly */
        next = child->next;
        while (next) {
3573
            dupl = NULL;
3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586

            if (child->ns && next->ns &&
                STREQ_NULLABLE((const char *) child->ns->href,
                               (const char *) next->ns->href))
                dupl = next;

            next = next->next;

            if (dupl) {
                xmlUnlinkNode(dupl);
                xmlFreeNode(dupl);
            }
        }
3587 3588

        child = child->next;
3589 3590 3591 3592
    }
}


3593
static int
3594 3595
virDomainDefPostParseMemory(virDomainDefPtr def,
                            unsigned int parseFlags)
3596
{
3597
    size_t i;
3598 3599
    unsigned long long numaMemory = 0;
    unsigned long long hotplugMemory = 0;
3600

3601 3602 3603 3604 3605
    /* Attempt to infer the initial memory size from the sum NUMA memory sizes
     * in case ABI updates are allowed or the <memory> element wasn't specified */
    if (def->mem.total_memory == 0 ||
        parseFlags & VIR_DOMAIN_DEF_PARSE_ABI_UPDATE)
        numaMemory = virDomainNumaGetMemorySize(def->numa);
3606

3607 3608 3609 3610
    if (numaMemory) {
        virDomainDefSetMemoryInitial(def, numaMemory);
    } else {
        /* calculate the sizes of hotplug memory */
3611
        for (i = 0; i < def->nmems; i++)
3612 3613 3614 3615 3616 3617 3618 3619 3620 3621
            hotplugMemory += def->mems[i]->size;

        if (hotplugMemory > def->mem.total_memory) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("Total size of memory devices exceeds the total "
                             "memory size"));
            return -1;
        }

        virDomainDefSetMemoryInitial(def, def->mem.total_memory - hotplugMemory);
3622 3623
    }

3624 3625 3626 3627 3628 3629 3630
    if (virDomainDefGetMemoryInitial(def) == 0) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Memory size must be specified via <memory> or in the "
                         "<numa> configuration"));
        return -1;
    }

3631 3632
    if (def->mem.cur_balloon > virDomainDefGetMemoryActual(def) ||
        def->mem.cur_balloon == 0)
3633
        def->mem.cur_balloon = virDomainDefGetMemoryActual(def);
3634

3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650
    if ((def->mem.max_memory || def->mem.memory_slots) &&
        !(def->mem.max_memory && def->mem.memory_slots)) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("both maximum memory size and "
                         "memory slot count must be specified"));
        return -1;
    }

    if (def->mem.max_memory &&
        def->mem.max_memory < virDomainDefGetMemoryActual(def)) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("maximum memory size must be equal or greater than "
                         "the actual memory size"));
        return -1;
    }

3651 3652 3653 3654 3655
    return 0;
}


static int
3656
virDomainDefAddConsoleCompat(virDomainDefPtr def)
3657 3658 3659
{
    size_t i;

3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673
    /*
     * 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
     */
3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686

    /* Only the first console (if there are any) can be of type serial,
     * verify that no other 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;
        }
    }
3687
    if (def->nconsoles > 0 && def->os.type == VIR_DOMAIN_OSTYPE_HVM &&
3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701
        (def->consoles[0]->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL ||
         def->consoles[0]->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_NONE)) {

        /* 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) {
3702 3703 3704 3705
            if (VIR_APPEND_ELEMENT(def->serials,
                                   def->nserials,
                                   def->consoles[0]) < 0)
                return -1;
3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722

            /* 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)
3723
                return -1;
3724 3725 3726 3727 3728

            /* 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;
        }
3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749
    } else if (def->os.type == VIR_DOMAIN_OSTYPE_HVM && def->nserials > 0 &&
               def->serials[0]->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL &&
               def->serials[0]->targetType == VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_ISA) {
        /* Create a stub console to match the serial port.
         * console[0] either does not exist
         *                or has a different type than SERIAL or NONE.
         */
        virDomainChrDefPtr chr;
        if (VIR_ALLOC(chr) < 0)
            return -1;

        if (VIR_INSERT_ELEMENT(def->consoles,
                               0,
                               def->nconsoles,
                               chr) < 0) {
            VIR_FREE(chr);
            return -1;
        }

        def->consoles[0]->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE;
        def->consoles[0]->targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL;
3750 3751
    }

3752 3753 3754 3755 3756
    return 0;
}


static int
3757
virDomainDefPostParseTimer(virDomainDefPtr def)
3758 3759 3760
{
    size_t i;

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

3765 3766
        if (timer->name == VIR_DOMAIN_TIMER_NAME_KVMCLOCK ||
            timer->name == VIR_DOMAIN_TIMER_NAME_HYPERVCLOCK) {
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 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815
            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;
            }
        }
    }

3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846
    return 0;
}


static int
virDomainDefPostParseInternal(virDomainDefPtr def,
                              virCapsPtr caps ATTRIBUTE_UNUSED,
                              unsigned int parseFlags)
{
    /* verify init path for container based domains */
    if (def->os.type == VIR_DOMAIN_OSTYPE_EXE && !def->os.init) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("init binary must be specified"));
        return -1;
    }

    if (virDomainDefPostParseMemory(def, parseFlags) < 0)
        return -1;

    if (virDomainDefAddConsoleCompat(def) < 0)
        return -1;

    if (virDomainDefRejectDuplicateControllers(def) < 0)
        return -1;

    if (virDomainDefRejectDuplicatePanics(def) < 0)
        return -1;

    if (virDomainDefPostParseTimer(def) < 0)
        return -1;

3847
    /* clean up possibly duplicated metadata entries */
3848
    virDomainDefMetadataSanitize(def);
3849

3850 3851 3852 3853
    return 0;
}


3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902
/* Check if a drive type address $controller:$bus:$target:$unit is already
 * taken by a disk or not.
 */
static bool
virDomainDriveAddressIsUsedByDisk(const virDomainDef *def,
                                  virDomainDiskBus type,
                                  unsigned int controller,
                                  unsigned int bus,
                                  unsigned int target,
                                  unsigned int unit)
{
    virDomainDiskDefPtr disk;
    size_t i;

    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 == bus &&
            disk->info.addr.drive.target == target)
            return true;
    }

    return false;
}


/* Check if a drive type address $controller:$target:$bus:$unit is already
 * taken by a host device or not.
 */
static bool
virDomainDriveAddressIsUsedByHostdev(const virDomainDef *def,
                                     virDomainHostdevSubsysType type,
                                     unsigned int controller,
                                     unsigned int bus,
                                     unsigned int target,
                                     unsigned int unit)
{
    virDomainHostdevDefPtr hostdev;
    size_t i;

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

3903 3904
        if (hostdev->source.subsys.type != type ||
            hostdev->info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE)
3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970
            continue;

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

    return false;
}


static bool
virDomainSCSIDriveAddressIsUsed(const virDomainDef *def,
                                unsigned int controller,
                                unsigned int bus,
                                unsigned int target,
                                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, bus, target, unit) ||
        virDomainDriveAddressIsUsedByHostdev(def,
                                             VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI,
                                             controller, bus, target, unit))
        return true;

    return false;
}


/* Find out the next usable "unit" of a specific controller */
static int
virDomainControllerSCSINextUnit(const virDomainDef *def,
                                unsigned int max_unit,
                                unsigned int controller)
{
    size_t i;

    for (i = 0; i < max_unit; i++) {
        /* Default to assigning addresses using bus = target = 0 */
        if (!virDomainSCSIDriveAddressIsUsed(def, controller, 0, 0, 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,
                              const virDomainDef *def,
                              virDomainHostdevDefPtr hostdev)
{
    int next_unit = 0;
    unsigned controller = 0;
    size_t i;
3971
    int ret;
3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989

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

        controller++;
        ret = virDomainControllerSCSINextUnit(def,
                                              xmlopt->config.hasWideSCSIBus ?
                                              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;
        }
    }

3990 3991 3992 3993 3994 3995
    /* NB: Do not attempt calling virDomainDefMaybeAddController to
     * automagically add a "new" controller. Doing so will result in
     * qemuDomainFindOrCreateSCSIDiskController "finding" the controller
     * in the domain def list and thus not hotplugging the controller as
     * well as the hostdev in the event that there are either no SCSI
     * controllers defined or there was no space on an existing one.
3996 3997
     */

3998 3999 4000 4001 4002 4003 4004 4005 4006 4007
    hostdev->info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE;
    hostdev->info->addr.drive.controller = controller;
    hostdev->info->addr.drive.bus = 0;
    hostdev->info->addr.drive.target = 0;
    hostdev->info->addr.drive.unit = next_unit;

    return 0;
}


4008 4009
static int
virDomainDeviceDefPostParseInternal(virDomainDeviceDefPtr dev,
4010
                                    const virDomainDef *def,
4011
                                    virCapsPtr caps ATTRIBUTE_UNUSED,
4012
                                    unsigned int parseFlags ATTRIBUTE_UNUSED,
4013
                                    virDomainXMLOptionPtr xmlopt)
4014
{
4015 4016
    if (dev->type == VIR_DOMAIN_DEVICE_CHR) {
        virDomainChrDefPtr chr = dev->data.chr;
4017 4018
        const virDomainChrDef **arrPtr;
        size_t i, cnt;
4019

4020
        virDomainChrGetDomainPtrs(def, chr->deviceType, &arrPtr, &cnt);
4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031

        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;

4032 4033 4034
            for (i = 0; i < cnt; i++) {
                if (arrPtr[i]->target.port > maxport)
                    maxport = arrPtr[i]->target.port;
4035 4036 4037 4038 4039
            }

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

4041 4042 4043 4044 4045 4046 4047 4048
    /* 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;
    }

4049 4050 4051 4052
    /* verify disk source */
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        virDomainDiskDefPtr disk = dev->data.disk;

4053 4054
        /* internal snapshots and config files are currently supported
         * only with rbd: */
4055 4056 4057 4058 4059 4060 4061 4062
        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;
            }
4063 4064 4065 4066 4067 4068 4069

            if (disk->src->configFile) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("<config> element is currently supported "
                                 "only with 'rbd' disks"));
                return -1;
            }
4070
        }
4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092

        /* Validate LUN configuration
         * NOTE: virStorageTranslateDiskSourcePool is not run yet, so for
         *       disk "volume"'s, the closest we can get at config time is
         *       to ensure mode isn't direct since host/default will allow
         *       lun/block usage. At run time if it's determined the wrong
         *       voltype and pooltype values are set, then failure occurs
         */
        if (disk->device == VIR_DOMAIN_DISK_DEVICE_LUN &&
            !(disk->src->type == VIR_STORAGE_TYPE_BLOCK ||
              (disk->src->type == VIR_STORAGE_TYPE_NETWORK &&
               disk->src->protocol == VIR_STORAGE_NET_PROTOCOL_ISCSI) ||
              (disk->src->type == VIR_STORAGE_TYPE_VOLUME &&
               disk->src->srcpool &&
               disk->src->srcpool->mode !=
               VIR_STORAGE_SOURCE_POOL_MODE_DIRECT))) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk '%s' improperly configured for a "
                             "device='lun'"),
                           disk->dst);
            return -1;
        }
4093 4094

        if (disk->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
4095
            virDomainDiskDefAssignAddress(xmlopt, disk, def) < 0)
4096
            return -1;
4097 4098
    }

4099 4100 4101 4102 4103 4104
    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);
    }

4105 4106 4107 4108
    if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV) {
        virDomainHostdevDefPtr hdev = dev->data.hostdev;

        if (hdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
4109 4110 4111 4112
            hdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI) {

            if (hdev->info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
                virDomainHostdevAssignAddress(xmlopt, def, hdev) < 0) {
4113 4114 4115
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("Cannot assign SCSI host device address"));
                return -1;
4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135
            } else {
                /* Ensure provided address doesn't conflict with existing
                 * scsi disk drive address
                 */
                virDomainDeviceDriveAddressPtr addr = &hdev->info->addr.drive;
                if (virDomainDriveAddressIsUsedByDisk(def,
                                                      VIR_DOMAIN_DISK_BUS_SCSI,
                                                      addr->controller,
                                                      addr->bus,
                                                      addr->target,
                                                      addr->unit)) {
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("SCSI host address controller='%u' "
                                     "bus='%u' target='%u' unit='%u' in "
                                     "use by a SCSI disk"),
                                   addr->controller, addr->bus,
                                   addr->target, addr->unit);
                    return -1;
                }
            }
4136 4137
        }
    }
4138 4139 4140 4141
    return 0;
}


4142 4143
static int
virDomainDeviceDefPostParse(virDomainDeviceDefPtr dev,
4144
                            const virDomainDef *def,
4145
                            virCapsPtr caps,
4146
                            unsigned int flags,
4147 4148 4149 4150
                            virDomainXMLOptionPtr xmlopt)
{
    int ret;

4151
    if (xmlopt->config.devicesPostParseCallback) {
4152
        ret = xmlopt->config.devicesPostParseCallback(dev, def, caps, flags,
4153 4154 4155 4156 4157
                                                      xmlopt->config.priv);
        if (ret < 0)
            return ret;
    }

4158
    if ((ret = virDomainDeviceDefPostParseInternal(dev, def, caps, flags, xmlopt)) < 0)
4159 4160
        return ret;

4161 4162 4163 4164 4165 4166 4167 4168
    return 0;
}


struct virDomainDefPostParseDeviceIteratorData {
    virDomainDefPtr def;
    virCapsPtr caps;
    virDomainXMLOptionPtr xmlopt;
4169
    unsigned int parseFlags;
4170 4171 4172 4173 4174 4175 4176 4177 4178 4179
};


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


4185
int
4186 4187
virDomainDefPostParse(virDomainDefPtr def,
                      virCapsPtr caps,
4188
                      unsigned int parseFlags,
4189 4190 4191 4192 4193 4194 4195
                      virDomainXMLOptionPtr xmlopt)
{
    int ret;
    struct virDomainDefPostParseDeviceIteratorData data = {
        .def = def,
        .caps = caps,
        .xmlopt = xmlopt,
4196
        .parseFlags = parseFlags,
4197 4198 4199
    };

    /* call the domain config callback */
4200
    if (xmlopt->config.domainPostParseCallback) {
4201
        ret = xmlopt->config.domainPostParseCallback(def, caps, parseFlags,
4202 4203 4204 4205 4206 4207
                                                     xmlopt->config.priv);
        if (ret < 0)
            return ret;
    }

    /* iterate the devices */
4208 4209 4210 4211
    if ((ret = virDomainDeviceInfoIterateInternal(def,
                                                  virDomainDefPostParseDeviceIterator,
                                                  true,
                                                  &data)) < 0)
4212 4213
        return ret;

4214

4215
    if ((ret = virDomainDefPostParseInternal(def, caps, parseFlags)) < 0)
4216 4217
        return ret;

4218 4219 4220 4221
    return 0;
}


4222 4223
void virDomainDefClearPCIAddresses(virDomainDefPtr def)
{
4224
    virDomainDeviceInfoIterate(def, virDomainDeviceInfoClearPCIAddress, NULL);
D
Daniel P. Berrange 已提交
4225 4226
}

4227 4228 4229 4230 4231
void virDomainDefClearCCWAddresses(virDomainDefPtr def)
{
    virDomainDeviceInfoIterate(def, virDomainDeviceInfoClearCCWAddress, NULL);
}

D
Daniel P. Berrange 已提交
4232 4233
void virDomainDefClearDeviceAliases(virDomainDefPtr def)
{
4234
    virDomainDeviceInfoIterate(def, virDomainDeviceInfoClearAlias, NULL);
4235 4236 4237
}


4238
/* Generate a string representation of a device address
4239
 * @info address Device address to stringify
4240
 */
E
Eric Blake 已提交
4241 4242 4243
static int ATTRIBUTE_NONNULL(2)
virDomainDeviceInfoFormat(virBufferPtr buf,
                          virDomainDeviceInfoPtr info,
E
Eric Blake 已提交
4244
                          unsigned int flags)
4245
{
4246
    if ((flags & VIR_DOMAIN_DEF_FORMAT_ALLOW_BOOT) && info->bootIndex)
4247
        virBufferAsprintf(buf, "<boot order='%d'/>\n", info->bootIndex);
4248

D
Daniel P. Berrange 已提交
4249
    if (info->alias &&
4250
        !(flags & VIR_DOMAIN_DEF_FORMAT_INACTIVE)) {
4251
        virBufferAsprintf(buf, "<alias name='%s'/>\n", info->alias);
D
Daniel P. Berrange 已提交
4252 4253
    }

4254
    if (info->mastertype == VIR_DOMAIN_CONTROLLER_MASTER_USB) {
4255
        virBufferAsprintf(buf, "<master startport='%d'/>\n",
4256 4257 4258
                          info->master.usb.startport);
    }

4259
    if ((flags & VIR_DOMAIN_DEF_FORMAT_ALLOW_ROM) &&
4260 4261
        (info->rombar || info->romfile)) {

4262
        virBufferAddLit(buf, "<rom");
4263 4264
        if (info->rombar) {

J
Ján Tomko 已提交
4265
            const char *rombar = virTristateSwitchTypeToString(info->rombar);
4266 4267

            if (!rombar) {
4268 4269 4270
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected rom bar value %d"),
                               info->rombar);
4271 4272 4273
                return -1;
            }
            virBufferAsprintf(buf, " bar='%s'", rombar);
4274
        }
4275
        if (info->romfile)
4276
            virBufferEscapeString(buf, " file='%s'", info->romfile);
4277
        virBufferAddLit(buf, "/>\n");
4278 4279
    }

4280 4281
    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE ||
        info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390)
4282 4283 4284
        return 0;

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

4288
    switch ((virDomainDeviceAddressType) info->type) {
4289
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI:
4290
        virBufferAsprintf(buf, " domain='0x%.4x' bus='0x%.2x' slot='0x%.2x' function='0x%.1x'",
4291 4292 4293 4294
                          info->addr.pci.domain,
                          info->addr.pci.bus,
                          info->addr.pci.slot,
                          info->addr.pci.function);
4295 4296
        if (info->addr.pci.multi) {
           virBufferAsprintf(buf, " multifunction='%s'",
J
Ján Tomko 已提交
4297
                             virTristateSwitchTypeToString(info->addr.pci.multi));
4298
        }
4299 4300
        break;

4301
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE:
4302
        virBufferAsprintf(buf, " controller='%d' bus='%d' target='%d' unit='%d'",
4303 4304
                          info->addr.drive.controller,
                          info->addr.drive.bus,
4305
                          info->addr.drive.target,
4306 4307 4308
                          info->addr.drive.unit);
        break;

4309
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL:
4310
        virBufferAsprintf(buf, " controller='%d' bus='%d' port='%d'",
4311
                          info->addr.vioserial.controller,
4312 4313
                          info->addr.vioserial.bus,
                          info->addr.vioserial.port);
4314 4315
        break;

E
Eric Blake 已提交
4316
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID:
4317
        virBufferAsprintf(buf, " controller='%d' slot='%d'",
E
Eric Blake 已提交
4318 4319 4320 4321
                          info->addr.ccid.controller,
                          info->addr.ccid.slot);
        break;

M
Marc-André Lureau 已提交
4322
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB:
4323
        virBufferAsprintf(buf, " bus='%d' port='%s'",
M
Marc-André Lureau 已提交
4324 4325 4326 4327
                          info->addr.usb.bus,
                          info->addr.usb.port);
        break;

4328 4329 4330 4331 4332
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO:
        if (info->addr.spaprvio.has_reg)
            virBufferAsprintf(buf, " reg='0x%llx'", info->addr.spaprvio.reg);
        break;

4333 4334 4335 4336 4337 4338 4339
    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;

4340 4341 4342
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO:
        break;

H
Hu Tao 已提交
4343 4344 4345 4346 4347 4348 4349
    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;

4350 4351 4352 4353 4354 4355
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM:
        virBufferAsprintf(buf, " slot='%u'", info->addr.dimm.slot);
        virBufferAsprintf(buf, " base='0x%llx'", info->addr.dimm.base);

        break;

4356 4357 4358 4359
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390:
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE:
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_LAST:
        break;
4360 4361 4362 4363 4364 4365
    }

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

4366
static int
4367
virDomainDeviceDriveAddressParseXML(xmlNodePtr node,
4368 4369
                                    virDomainDeviceDriveAddressPtr addr)
{
4370
    char *bus, *unit, *controller, *target;
4371 4372 4373 4374 4375 4376
    int ret = -1;

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

    controller = virXMLPropString(node, "controller");
    bus = virXMLPropString(node, "bus");
4377
    target = virXMLPropString(node, "target");
4378 4379 4380
    unit = virXMLPropString(node, "unit");

    if (controller &&
4381
        virStrToLong_uip(controller, NULL, 10, &addr->controller) < 0) {
4382 4383
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'controller' attribute"));
4384 4385 4386 4387
        goto cleanup;
    }

    if (bus &&
4388
        virStrToLong_uip(bus, NULL, 10, &addr->bus) < 0) {
4389 4390
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'bus' attribute"));
4391 4392 4393
        goto cleanup;
    }

4394
    if (target &&
4395
        virStrToLong_uip(target, NULL, 10, &addr->target) < 0) {
4396 4397
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'target' attribute"));
4398 4399 4400
        goto cleanup;
    }

4401
    if (unit &&
4402
        virStrToLong_uip(unit, NULL, 10, &addr->unit) < 0) {
4403 4404
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'unit' attribute"));
4405 4406 4407 4408 4409
        goto cleanup;
    }

    ret = 0;

4410
 cleanup:
4411 4412
    VIR_FREE(controller);
    VIR_FREE(bus);
4413
    VIR_FREE(target);
4414 4415 4416 4417
    VIR_FREE(unit);
    return ret;
}

4418 4419 4420 4421 4422 4423 4424

static int
virDomainDeviceVirtioSerialAddressParseXML(
    xmlNodePtr node,
    virDomainDeviceVirtioSerialAddressPtr addr
)
{
4425
    char *controller, *bus, *port;
4426 4427 4428 4429 4430 4431
    int ret = -1;

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

    controller = virXMLPropString(node, "controller");
    bus = virXMLPropString(node, "bus");
4432
    port = virXMLPropString(node, "port");
4433 4434

    if (controller &&
4435
        virStrToLong_uip(controller, NULL, 10, &addr->controller) < 0) {
4436 4437
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'controller' attribute"));
4438 4439 4440 4441
        goto cleanup;
    }

    if (bus &&
4442
        virStrToLong_uip(bus, NULL, 10, &addr->bus) < 0) {
4443 4444
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'bus' attribute"));
4445 4446 4447
        goto cleanup;
    }

4448
    if (port &&
4449
        virStrToLong_uip(port, NULL, 10, &addr->port) < 0) {
4450 4451
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'port' attribute"));
4452 4453 4454
        goto cleanup;
    }

4455 4456
    ret = 0;

4457
 cleanup:
4458 4459
    VIR_FREE(controller);
    VIR_FREE(bus);
E
Eric Blake 已提交
4460
    VIR_FREE(port);
4461 4462 4463
    return ret;
}

4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480
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 &&
4481
            virStrToLong_uip(cssid, NULL, 0, &addr->cssid) < 0) {
4482 4483 4484 4485 4486
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot parse <address> 'cssid' attribute"));
            goto cleanup;
        }
        if (ssid &&
4487
            virStrToLong_uip(ssid, NULL, 0, &addr->ssid) < 0) {
4488 4489 4490 4491 4492
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot parse <address> 'ssid' attribute"));
            goto cleanup;
        }
        if (devno &&
4493
            virStrToLong_uip(devno, NULL, 0, &addr->devno) < 0) {
4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514
            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;

4515
 cleanup:
4516 4517 4518 4519 4520 4521
    VIR_FREE(cssid);
    VIR_FREE(ssid);
    VIR_FREE(devno);
    return ret;
}

E
Eric Blake 已提交
4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534
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 &&
4535
        virStrToLong_uip(controller, NULL, 10, &addr->controller) < 0) {
4536 4537
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'controller' attribute"));
E
Eric Blake 已提交
4538 4539 4540 4541
        goto cleanup;
    }

    if (slot &&
4542
        virStrToLong_uip(slot, NULL, 10, &addr->slot) < 0) {
4543 4544
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'slot' attribute"));
E
Eric Blake 已提交
4545 4546 4547 4548 4549
        goto cleanup;
    }

    ret = 0;

4550
 cleanup:
E
Eric Blake 已提交
4551 4552 4553 4554 4555
    VIR_FREE(controller);
    VIR_FREE(slot);
    return ret;
}

4556 4557 4558 4559
static int
virDomainDeviceUSBAddressParseXML(xmlNodePtr node,
                                  virDomainDeviceUSBAddressPtr addr)
{
4560 4561
    char *port, *bus, *tmp;
    unsigned int p;
4562 4563 4564 4565 4566 4567 4568 4569
    int ret = -1;

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

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

    if (port &&
4570
        ((virStrToLong_uip(port, &tmp, 10, &p) < 0 || (*tmp != '\0' && *tmp != '.')) ||
4571 4572 4573
         (*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'))))) {
4574 4575
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'port' attribute"));
4576 4577 4578
        goto cleanup;
    }

4579 4580 4581
    addr->port = port;
    port = NULL;

4582
    if (bus &&
4583
        virStrToLong_uip(bus, NULL, 10, &addr->bus) < 0) {
4584 4585
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <address> 'bus' attribute"));
4586 4587 4588 4589 4590
        goto cleanup;
    }

    ret = 0;

4591
 cleanup:
4592 4593 4594 4595 4596
    VIR_FREE(bus);
    VIR_FREE(port);
    return ret;
}

4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608
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) {
4609 4610
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot parse <address> 'reg' attribute"));
4611 4612 4613 4614 4615 4616 4617 4618
            ret = -1;
            goto cleanup;
        }

        addr->has_reg = true;
    }

    ret = 0;
4619
 cleanup:
4620 4621 4622 4623
    VIR_FREE(reg);
    return ret;
}

4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636
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) {
4637 4638
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot parse <master> 'startport' attribute"));
4639 4640 4641 4642 4643
        goto cleanup;
    }

    ret = 0;

4644
 cleanup:
4645 4646 4647 4648
    VIR_FREE(startport);
    return ret;
}

4649 4650 4651
static int
virDomainDeviceBootParseXML(xmlNodePtr node,
                            int *bootIndex,
4652
                            virHashTablePtr bootHash)
4653 4654 4655 4656 4657 4658 4659
{
    char *order;
    int boot;
    int ret = -1;

    order = virXMLPropString(node, "order");
    if (!order) {
4660 4661
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing boot order attribute"));
4662 4663 4664
        goto cleanup;
    } else if (virStrToLong_i(order, NULL, 10, &boot) < 0 ||
               boot <= 0) {
4665 4666 4667
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("incorrect boot order '%s', expecting positive integer"),
                       order);
4668 4669 4670
        goto cleanup;
    }

4671 4672 4673 4674 4675
    if (bootHash) {
        if (virHashLookup(bootHash, order)) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("boot order '%s' used for more than one device"),
                           order);
4676 4677
            goto cleanup;
        }
4678 4679 4680

        if (virHashAddEntry(bootHash, order, (void *) 1) < 0)
            goto cleanup;
4681 4682 4683 4684 4685
    }

    *bootIndex = boot;
    ret = 0;

4686
 cleanup:
4687 4688 4689 4690
    VIR_FREE(order);
    return ret;
}

H
Hu Tao 已提交
4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704
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 &&
4705
        virStrToLong_uip(iobase, NULL, 16, &addr->iobase) < 0) {
H
Hu Tao 已提交
4706 4707 4708 4709 4710 4711
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Cannot parse <address> 'iobase' attribute"));
        goto cleanup;
    }

    if (irq &&
4712
        virStrToLong_uip(irq, NULL, 16, &addr->irq) < 0) {
H
Hu Tao 已提交
4713 4714 4715 4716 4717 4718
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Cannot parse <address> 'irq' attribute"));
        goto cleanup;
    }

    ret = 0;
4719
 cleanup:
H
Hu Tao 已提交
4720 4721 4722 4723 4724
    VIR_FREE(iobase);
    VIR_FREE(irq);
    return ret;
}

4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759

static int
virDomainDeviceDimmAddressParseXML(xmlNodePtr node,
                                   virDomainDeviceDimmAddressPtr addr)
{
    int ret = -1;
    char *tmp = NULL;

    if (!(tmp = virXMLPropString(node, "slot")) ||
        virStrToLong_uip(tmp, NULL, 10, &addr->slot) < 0) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("invalid or missing dimm slot id '%s'"),
                       NULLSTR(tmp));
        goto cleanup;
    }
    VIR_FREE(tmp);

    if (!(tmp = virXMLPropString(node, "base")) ||
        virStrToLong_ullp(tmp, NULL, 16, &addr->base) < 0) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("invalid or missing dimm base address '%s'"),
                       NULLSTR(tmp));
        goto cleanup;
    }
    VIR_FREE(tmp);

    ret = 0;

 cleanup:
    VIR_FREE(tmp);

    return ret;
}


4760 4761 4762 4763
/* Parse the XML definition for a device address
 * @param node XML nodeset to parse for device address definition
 */
static int
4764
virDomainDeviceInfoParseXML(xmlNodePtr node,
4765
                            virHashTablePtr bootHash,
4766
                            virDomainDeviceInfoPtr info,
E
Eric Blake 已提交
4767
                            unsigned int flags)
4768 4769 4770
{
    xmlNodePtr cur;
    xmlNodePtr address = NULL;
4771
    xmlNodePtr master = NULL;
D
Daniel P. Berrange 已提交
4772
    xmlNodePtr alias = NULL;
4773 4774
    xmlNodePtr boot = NULL;
    xmlNodePtr rom = NULL;
4775 4776 4777 4778 4779 4780 4781 4782
    char *type = NULL;
    int ret = -1;

    virDomainDeviceInfoClear(info);

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
D
Daniel P. Berrange 已提交
4783
            if (alias == NULL &&
4784
                !(flags & VIR_DOMAIN_DEF_PARSE_INACTIVE) &&
D
Daniel P. Berrange 已提交
4785 4786 4787 4788
                xmlStrEqual(cur->name, BAD_CAST "alias")) {
                alias = cur;
            } else if (address == NULL &&
                       xmlStrEqual(cur->name, BAD_CAST "address")) {
4789
                address = cur;
4790 4791 4792
            } else if (master == NULL &&
                       xmlStrEqual(cur->name, BAD_CAST "master")) {
                master = cur;
4793
            } else if (boot == NULL &&
4794
                       (flags & VIR_DOMAIN_DEF_PARSE_ALLOW_BOOT) &&
4795 4796 4797
                       xmlStrEqual(cur->name, BAD_CAST "boot")) {
                boot = cur;
            } else if (rom == NULL &&
4798
                       (flags & VIR_DOMAIN_DEF_PARSE_ALLOW_ROM) &&
4799 4800
                       xmlStrEqual(cur->name, BAD_CAST "rom")) {
                rom = cur;
4801 4802 4803 4804 4805
            }
        }
        cur = cur->next;
    }

D
Daniel P. Berrange 已提交
4806 4807 4808
    if (alias)
        info->alias = virXMLPropString(alias, "name");

4809 4810 4811 4812 4813 4814
    if (master) {
        info->mastertype = VIR_DOMAIN_CONTROLLER_MASTER_USB;
        if (virDomainDeviceUSBMasterParseXML(master, &info->master.usb) < 0)
            goto cleanup;
    }

4815
    if (boot) {
4816
        if (virDomainDeviceBootParseXML(boot, &info->bootIndex, bootHash))
4817 4818 4819 4820 4821
            goto cleanup;
    }

    if (rom) {
        char *rombar = virXMLPropString(rom, "bar");
4822
        if (rombar &&
J
Ján Tomko 已提交
4823
            ((info->rombar = virTristateSwitchTypeFromString(rombar)) <= 0)) {
4824 4825
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown rom bar value '%s'"), rombar);
4826 4827 4828 4829
            VIR_FREE(rombar);
            goto cleanup;
        }
        VIR_FREE(rombar);
4830
        info->romfile = virXMLPropString(rom, "file");
4831 4832
    }

4833 4834 4835 4836 4837 4838
    if (!address)
        return 0;

    type = virXMLPropString(address, "type");

    if (type) {
4839
        if ((info->type = virDomainDeviceAddressTypeFromString(type)) <= 0) {
4840
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4841
                           _("unknown address type '%s'"), type);
4842 4843 4844
            goto cleanup;
        }
    } else {
4845 4846
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("No type specified for device address"));
4847 4848 4849
        goto cleanup;
    }

4850
    switch ((virDomainDeviceAddressType) info->type) {
4851
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI:
4852
        if (virDevicePCIAddressParseXML(address, &info->addr.pci) < 0)
4853 4854 4855
            goto cleanup;
        break;

4856
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE:
4857
        if (virDomainDeviceDriveAddressParseXML(address, &info->addr.drive) < 0)
4858 4859 4860
            goto cleanup;
        break;

4861 4862 4863 4864 4865 4866
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL:
        if (virDomainDeviceVirtioSerialAddressParseXML
                (address, &info->addr.vioserial) < 0)
            goto cleanup;
        break;

E
Eric Blake 已提交
4867 4868 4869 4870 4871
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID:
        if (virDomainDeviceCcidAddressParseXML(address, &info->addr.ccid) < 0)
            goto cleanup;
        break;

4872 4873 4874 4875 4876
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB:
        if (virDomainDeviceUSBAddressParseXML(address, &info->addr.usb) < 0)
            goto cleanup;
        break;

4877 4878 4879 4880 4881
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO:
        if (virDomainDeviceSpaprVioAddressParseXML(address, &info->addr.spaprvio) < 0)
            goto cleanup;
        break;

4882 4883 4884 4885 4886 4887
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW:
        if (virDomainDeviceCCWAddressParseXML
                (address, &info->addr.ccw) < 0)
            goto cleanup;
        break;

4888 4889 4890
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO:
        break;

H
Hu Tao 已提交
4891 4892 4893 4894 4895
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_ISA:
        if (virDomainDeviceISAAddressParseXML(address, &info->addr.isa) < 0)
            goto cleanup;
        break;

4896 4897 4898
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390:
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("virtio-s390 bus doesn't have an address"));
4899
        goto cleanup;
4900

4901 4902 4903 4904 4905
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM:
        if (virDomainDeviceDimmAddressParseXML(address, &info->addr.dimm) < 0)
            goto cleanup;
        break;

4906 4907 4908
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE:
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_LAST:
        break;
4909 4910 4911 4912
    }

    ret = 0;

4913
 cleanup:
D
Daniel P. Berrange 已提交
4914 4915
    if (ret == -1)
        VIR_FREE(info->alias);
4916 4917 4918 4919
    VIR_FREE(type);
    return ret;
}

4920 4921
static int
virDomainParseLegacyDeviceAddress(char *devaddr,
4922
                                  virDevicePCIAddressPtr pci)
4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936
{
    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;
}
4937

4938
static int
4939
virDomainHostdevSubsysUSBDefParseXML(xmlNodePtr node,
4940 4941 4942 4943
                                     virDomainHostdevDefPtr def)
{

    int ret = -1;
4944
    bool got_product, got_vendor;
4945
    xmlNodePtr cur;
4946
    char *startupPolicy = NULL;
4947
    char *autoAddress;
4948
    virDomainHostdevSubsysUSBPtr usbsrc = &def->source.subsys.u.usb;
4949 4950 4951 4952 4953

    if ((startupPolicy = virXMLPropString(node, "startupPolicy"))) {
        def->startupPolicy =
            virDomainStartupPolicyTypeFromString(startupPolicy);
        if (def->startupPolicy <= 0) {
4954
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4955 4956 4957 4958 4959 4960 4961
                           _("Unknown startup policy '%s'"),
                           startupPolicy);
            VIR_FREE(startupPolicy);
            goto out;
        }
        VIR_FREE(startupPolicy);
    }
4962

4963 4964
    if ((autoAddress = virXMLPropString(node, "autoAddress"))) {
        if (STREQ(autoAddress, "yes"))
4965
            usbsrc->autoAddress = true;
4966 4967 4968
        VIR_FREE(autoAddress);
    }

4969 4970
    /* Product can validly be 0, so we need some extra help to determine
     * if it is uninitialized*/
4971 4972
    got_product = false;
    got_vendor = false;
4973 4974 4975 4976 4977 4978 4979 4980

    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) {
4981
                    got_vendor = true;
4982
                    if (virStrToLong_ui(vendor, NULL, 0, &usbsrc->vendor) < 0) {
4983 4984
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("cannot parse vendor id %s"), vendor);
4985 4986 4987 4988 4989
                        VIR_FREE(vendor);
                        goto out;
                    }
                    VIR_FREE(vendor);
                } else {
4990 4991
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("usb vendor needs id"));
4992 4993 4994 4995 4996 4997
                    goto out;
                }
            } else if (xmlStrEqual(cur->name, BAD_CAST "product")) {
                char* product = virXMLPropString(cur, "id");

                if (product) {
4998
                    got_product = true;
4999
                    if (virStrToLong_ui(product, NULL, 0,
5000
                                        &usbsrc->product) < 0) {
5001 5002 5003
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("cannot parse product %s"),
                                       product);
5004 5005 5006 5007 5008
                        VIR_FREE(product);
                        goto out;
                    }
                    VIR_FREE(product);
                } else {
5009 5010
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("usb product needs id"));
5011 5012 5013 5014 5015 5016 5017
                    goto out;
                }
            } else if (xmlStrEqual(cur->name, BAD_CAST "address")) {
                char *bus, *device;

                bus = virXMLPropString(cur, "bus");
                if (bus) {
5018
                    if (virStrToLong_ui(bus, NULL, 0, &usbsrc->bus) < 0) {
5019 5020
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("cannot parse bus %s"), bus);
5021 5022 5023 5024 5025
                        VIR_FREE(bus);
                        goto out;
                    }
                    VIR_FREE(bus);
                } else {
5026 5027
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("usb address needs bus id"));
5028 5029 5030 5031 5032
                    goto out;
                }

                device = virXMLPropString(cur, "device");
                if (device) {
5033
                    if (virStrToLong_ui(device, NULL, 0, &usbsrc->device) < 0) {
5034 5035 5036
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("cannot parse device %s"),
                                       device);
5037 5038 5039 5040 5041
                        VIR_FREE(device);
                        goto out;
                    }
                    VIR_FREE(device);
                } else {
5042 5043
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("usb address needs device id"));
5044 5045 5046
                    goto out;
                }
            } else {
5047 5048 5049
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unknown usb source type '%s'"),
                               cur->name);
5050 5051 5052 5053 5054 5055
                goto out;
            }
        }
        cur = cur->next;
    }

5056
    if (got_vendor && usbsrc->vendor == 0) {
5057 5058
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("vendor cannot be 0."));
5059 5060 5061 5062
        goto out;
    }

    if (!got_vendor && got_product) {
5063 5064
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing vendor"));
5065 5066 5067
        goto out;
    }
    if (got_vendor && !got_product) {
5068 5069
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing product"));
5070 5071 5072 5073
        goto out;
    }

    ret = 0;
5074
 out:
5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086
    return ret;
}

/* The internal XML for host PCI device's original states:
 *
 * <origstates>
 *   <unbind/>
 *   <removeslot/>
 *   <reprobe/>
 * </origstates>
 */
static int
5087
virDomainHostdevSubsysPCIOrigStatesDefParseXML(xmlNodePtr node,
5088 5089 5090 5091 5092 5093 5094 5095
                                               virDomainHostdevOrigStatesPtr def)
{
    xmlNodePtr cur;
    cur = node->children;

    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if (xmlStrEqual(cur->name, BAD_CAST "unbind")) {
5096
                def->states.pci.unbind_from_stub = true;
5097
            } else if (xmlStrEqual(cur->name, BAD_CAST "removeslot")) {
5098
                def->states.pci.remove_slot = true;
5099
            } else if (xmlStrEqual(cur->name, BAD_CAST "reprobe")) {
5100
                def->states.pci.reprobe = true;
5101
            } else {
5102 5103 5104
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unsupported element '%s' of 'origstates'"),
                               cur->name);
5105 5106 5107 5108 5109 5110 5111 5112 5113 5114
                return -1;
            }
        }
        cur = cur->next;
    }

    return 0;
}

static int
5115
virDomainHostdevSubsysPCIDefParseXML(xmlNodePtr node,
5116 5117 5118 5119 5120 5121 5122 5123 5124 5125
                                     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")) {
5126
                virDevicePCIAddressPtr addr =
5127
                    &def->source.subsys.u.pci.addr;
5128

5129
                if (virDevicePCIAddressParseXML(cur, addr) < 0)
5130
                    goto out;
5131
            } else if ((flags & VIR_DOMAIN_DEF_PARSE_STATUS) &&
5132 5133 5134 5135 5136
                       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,
5137
                                                      &def->info->addr.pci) < 0) {
5138 5139 5140
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to parse devaddr parameter '%s'"),
                                   devaddr);
5141 5142 5143
                    VIR_FREE(devaddr);
                    goto out;
                }
5144
                def->info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
5145
            } else if ((flags & VIR_DOMAIN_DEF_PARSE_PCI_ORIG_STATES) &&
5146 5147
                       xmlStrEqual(cur->name, BAD_CAST "origstates")) {
                virDomainHostdevOrigStatesPtr states = &def->origstates;
5148
                if (virDomainHostdevSubsysPCIOrigStatesDefParseXML(cur, states) < 0)
5149 5150
                    goto out;
            } else {
5151 5152 5153
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unknown pci source type '%s'"),
                               cur->name);
5154 5155 5156 5157 5158 5159 5160
                goto out;
            }
        }
        cur = cur->next;
    }

    ret = 0;
5161
 out:
5162 5163 5164
    return ret;
}

5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237
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 已提交
5238
static int
5239 5240
virDomainHostdevSubsysSCSIHostDefParseXML(xmlNodePtr sourcenode,
                                          virDomainHostdevSubsysSCSIPtr scsisrc)
H
Han Cheng 已提交
5241 5242 5243 5244 5245
{
    int ret = -1;
    bool got_address = false, got_adapter = false;
    xmlNodePtr cur;
    char *bus = NULL, *target = NULL, *unit = NULL;
5246
    virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
H
Han Cheng 已提交
5247

5248
    cur = sourcenode->children;
H
Han Cheng 已提交
5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267
    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;
                }

5268
                if (virStrToLong_uip(bus, NULL, 0, &scsihostsrc->bus) < 0) {
H
Han Cheng 已提交
5269 5270 5271 5272 5273
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("cannot parse bus '%s'"), bus);
                    goto cleanup;
                }

5274
                if (virStrToLong_uip(target, NULL, 0,
5275
                                    &scsihostsrc->target) < 0) {
H
Han Cheng 已提交
5276 5277 5278 5279 5280
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("cannot parse target '%s'"), target);
                    goto cleanup;
                }

5281
                if (virStrToLong_ullp(unit, NULL, 0, &scsihostsrc->unit) < 0) {
H
Han Cheng 已提交
5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294
                    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;
                }
5295
                if (!(scsihostsrc->adapter = virXMLPropString(cur, "name"))) {
H
Han Cheng 已提交
5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319
                    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;
5320
 cleanup:
H
Han Cheng 已提交
5321 5322 5323 5324 5325 5326
    VIR_FREE(bus);
    VIR_FREE(target);
    VIR_FREE(unit);
    return ret;
}

J
John Ferlan 已提交
5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391
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;
}

5392 5393 5394 5395
static int
virDomainHostdevSubsysSCSIDefParseXML(xmlNodePtr sourcenode,
                                      virDomainHostdevSubsysSCSIPtr scsisrc)
{
J
John Ferlan 已提交
5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417
    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;
5418 5419
}

5420

5421
static int
5422 5423 5424 5425 5426
virDomainHostdevDefParseXMLSubsys(xmlNodePtr node,
                                  xmlXPathContextPtr ctxt,
                                  const char *type,
                                  virDomainHostdevDefPtr def,
                                  unsigned int flags)
5427 5428 5429
{
    xmlNodePtr sourcenode;
    char *managed = NULL;
O
Osier Yang 已提交
5430
    char *sgio = NULL;
5431
    char *rawio = NULL;
5432 5433
    char *backendStr = NULL;
    int backend;
5434
    int ret = -1;
5435
    virDomainHostdevSubsysPCIPtr pcisrc = &def->source.subsys.u.pci;
5436
    virDomainHostdevSubsysSCSIPtr scsisrc = &def->source.subsys.u.scsi;
5437 5438 5439 5440 5441 5442

    /* @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 已提交
5443
    if ((managed = virXMLPropString(node, "managed")) != NULL) {
5444
        if (STREQ(managed, "yes"))
5445
            def->managed = true;
5446 5447
    }

O
Osier Yang 已提交
5448
    sgio = virXMLPropString(node, "sgio");
5449
    rawio = virXMLPropString(node, "rawio");
O
Osier Yang 已提交
5450

5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461
    /* @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) {
5462
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5463 5464
                           _("unknown host device source address type '%s'"),
                           type);
5465 5466 5467
            goto error;
        }
    } else {
5468 5469
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("missing source address type"));
5470 5471 5472 5473
        goto error;
    }

    if (!(sourcenode = virXPathNode("./source", ctxt))) {
5474 5475
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Missing <source> element in hostdev device"));
5476 5477
        goto error;
    }
5478 5479 5480 5481 5482 5483 5484 5485 5486

    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 已提交
5487
    if (sgio) {
5488
        if (def->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI) {
O
Osier Yang 已提交
5489 5490 5491 5492 5493
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("sgio is only supported for scsi host device"));
            goto error;
        }

5494
        if ((scsisrc->sgio = virDomainDeviceSGIOTypeFromString(sgio)) <= 0) {
5495
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
O
Osier Yang 已提交
5496 5497 5498 5499 5500
                           _("unknown sgio mode '%s'"), sgio);
            goto error;
        }
    }

5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515
    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;
        }
    }

5516 5517
    switch (def->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
5518
        if (virDomainHostdevSubsysPCIDefParseXML(sourcenode, def, flags) < 0)
5519
            goto error;
5520

5521
        backend = VIR_DOMAIN_HOSTDEV_PCI_BACKEND_DEFAULT;
5522
        if ((backendStr = virXPathString("string(./driver/@name)", ctxt)) &&
5523
            (((backend = virDomainHostdevSubsysPCIBackendTypeFromString(backendStr)) < 0) ||
5524
             backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_DEFAULT)) {
5525
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5526 5527 5528 5529
                           _("Unknown PCI device <driver name='%s'/> "
                             "has been specified"), backendStr);
            goto error;
        }
5530
        pcisrc->backend = backend;
5531

5532
        break;
5533

5534
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
5535
        if (virDomainHostdevSubsysUSBDefParseXML(sourcenode, def) < 0)
5536 5537
            goto error;
        break;
H
Han Cheng 已提交
5538 5539

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
5540
        if (virDomainHostdevSubsysSCSIDefParseXML(sourcenode, scsisrc) < 0)
H
Han Cheng 已提交
5541 5542 5543
            goto error;
        break;

5544
    default:
5545 5546 5547
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("address type='%s' not supported in hostdev interfaces"),
                       virDomainHostdevSubsysTypeToString(def->source.subsys.type));
5548 5549
        goto error;
    }
5550

5551
    ret = 0;
5552
 error:
5553
    VIR_FREE(managed);
O
Osier Yang 已提交
5554
    VIR_FREE(sgio);
5555
    VIR_FREE(rawio);
5556
    VIR_FREE(backendStr);
5557 5558 5559
    return ret;
}

5560 5561 5562 5563
static virDomainNetIpDefPtr
virDomainNetIpParseXML(xmlNodePtr node)
{
    /* Parse the prefix in every case */
5564
    virDomainNetIpDefPtr ip = NULL, ret = NULL;
5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579
    char *prefixStr = NULL;
    unsigned int prefixValue = 0;
    char *familyStr = NULL;
    int family = AF_UNSPEC;
    char *address = NULL;

    if (!(prefixStr = virXMLPropString(node, "prefix")) ||
        (virStrToLong_ui(prefixStr, NULL, 10, &prefixValue) < 0)) {
        // Don't shout, as some old config may not have a prefix
        VIR_DEBUG("Missing or invalid network prefix");
    }

    if (!(address = virXMLPropString(node, "address"))) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Missing network address"));
5580
        goto cleanup;
5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591
    }

    familyStr = virXMLPropString(node, "family");
    if (familyStr && STREQ(familyStr, "ipv4"))
        family = AF_INET;
    else if (familyStr && STREQ(familyStr, "ipv6"))
        family = AF_INET6;
    else
        family = virSocketAddrNumericFamily(address);

    if (VIR_ALLOC(ip) < 0)
5592
        goto cleanup;
5593 5594 5595 5596 5597

    if (virSocketAddrParse(&ip->address, address, family) < 0) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Failed to parse IP address: '%s'"),
                       address);
5598
        goto cleanup;
5599 5600 5601
    }
    ip->prefix = prefixValue;

5602 5603
    ret = ip;
    ip = NULL;
5604

5605
 cleanup:
5606 5607 5608 5609
    VIR_FREE(prefixStr);
    VIR_FREE(familyStr);
    VIR_FREE(address);
    VIR_FREE(ip);
5610
    return ret;
5611 5612
}

5613 5614 5615 5616 5617 5618 5619
static int
virDomainHostdevDefParseXMLCaps(xmlNodePtr node ATTRIBUTE_UNUSED,
                                xmlXPathContextPtr ctxt,
                                const char *type,
                                virDomainHostdevDefPtr def)
{
    xmlNodePtr sourcenode;
5620 5621
    xmlNodePtr *ipnodes = NULL;
    int nipnodes;
5622 5623
    xmlNodePtr *routenodes = NULL;
    int nroutenodes;
5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636
    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) {
5637
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670
                           _("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;
5671 5672 5673 5674 5675 5676 5677
    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;
        }
5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697

        /* Parse possible IP addresses */
        if ((nipnodes = virXPathNodeSet("./ip", ctxt, &ipnodes)) < 0)
            goto error;

        if (nipnodes) {
            size_t i;
            for (i = 0; i < nipnodes; i++) {
                virDomainNetIpDefPtr ip = virDomainNetIpParseXML(ipnodes[i]);

                if (!ip)
                    goto error;

                if (VIR_APPEND_ELEMENT(def->source.caps.u.net.ips,
                                       def->source.caps.u.net.nips, ip) < 0) {
                    VIR_FREE(ip);
                    goto error;
                }
            }
        }
5698 5699 5700 5701 5702 5703 5704 5705

        /* Look for possible gateways */
        if ((nroutenodes = virXPathNodeSet("./route", ctxt, &routenodes)) < 0)
            goto error;

        if (nroutenodes) {
            size_t i;
            for (i = 0; i < nroutenodes; i++) {
5706
                virNetworkRouteDefPtr route = NULL;
5707

5708 5709 5710
                if (!(route = virNetworkRouteDefParseXML(_("Domain hostdev device"),
                                                         routenodes[i],
                                                         ctxt)))
5711 5712
                    goto error;

5713

5714 5715
                if (VIR_APPEND_ELEMENT(def->source.caps.u.net.routes,
                                       def->source.caps.u.net.nroutes, route) < 0) {
5716
                    virNetworkRouteDefFree(route);
5717 5718 5719 5720
                    goto error;
                }
            }
        }
5721
        break;
5722 5723 5724 5725 5726 5727 5728
    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("address type='%s' not supported in hostdev interfaces"),
                       virDomainHostdevCapsTypeToString(def->source.caps.type));
        goto error;
    }
    ret = 0;
5729
 error:
5730
    VIR_FREE(ipnodes);
5731
    VIR_FREE(routenodes);
5732 5733 5734
    return ret;
}

5735
int
H
Han Cheng 已提交
5736 5737 5738
virDomainDeviceFindControllerModel(virDomainDefPtr def,
                                   virDomainDeviceInfoPtr info,
                                   int controllerType)
5739 5740
{
    int model = -1;
5741
    size_t i;
5742 5743 5744

    for (i = 0; i < def->ncontrollers; i++) {
        if (def->controllers[i]->type == controllerType &&
H
Han Cheng 已提交
5745
            def->controllers[i]->idx == info->addr.drive.controller)
5746 5747 5748 5749 5750 5751
            model = def->controllers[i]->model;
    }

    return model;
}

5752 5753 5754 5755 5756
virDomainDiskDefPtr
virDomainDiskFindByBusAndDst(virDomainDefPtr def,
                             int bus,
                             char *dst)
{
5757
    size_t i;
5758 5759 5760 5761

    if (!dst)
        return NULL;

5762
    for (i = 0; i < def->ndisks; i++) {
5763 5764 5765 5766 5767 5768 5769 5770 5771
        if (def->disks[i]->bus == bus &&
            STREQ(def->disks[i]->dst, dst)) {
            return def->disks[i];
        }
    }

    return NULL;
}

5772

5773
int
5774
virDomainDiskDefAssignAddress(virDomainXMLOptionPtr xmlopt,
5775 5776
                              virDomainDiskDefPtr def,
                              const virDomainDef *vmdef)
5777 5778
{
    int idx = virDiskNameToIndex(def->dst);
5779 5780 5781 5782
    if (idx < 0) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("Unknown disk name '%s' and no address specified"),
                       def->dst);
5783
        return -1;
5784
    }
5785 5786

    switch (def->bus) {
5787 5788 5789 5790
    case VIR_DOMAIN_DISK_BUS_SCSI: {
        unsigned int controller;
        unsigned int unit;

5791
        def->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE;
5792

5793
        if (xmlopt->config.hasWideSCSIBus) {
5794 5795 5796 5797 5798
            /* 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.
             */
5799 5800
            controller = idx / 15;
            unit = idx % 15;
5801 5802

            /* Skip the SCSI controller at unit 7 */
5803 5804
            if (unit >= 7)
                ++unit;
5805 5806 5807
        } else {
            /* For a narrow SCSI bus we define the default mapping to be
             * 7 units per bus, 1 bus per controller, many controllers */
5808 5809
            controller = idx / 7;
            unit = idx % 7;
5810 5811
        }

5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822
        if (virDomainDriveAddressIsUsedByHostdev(vmdef,
                                                 VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI,
                                                 controller, 0, 0, unit)) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("using disk target name '%s' conflicts with "
                             "SCSI host device address controller='%u' "
                             "bus='%u' target='%u' unit='%u"),
                           def->dst, controller, 0, 0, unit);
            return -1;
        }

5823 5824 5825 5826
        def->info.addr.drive.controller = controller;
        def->info.addr.drive.bus = 0;
        def->info.addr.drive.target = 0;
        def->info.addr.drive.unit = unit;
5827
        break;
5828
    }
5829 5830 5831 5832 5833 5834 5835 5836 5837 5838

    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 已提交
5839 5840 5841 5842 5843 5844 5845 5846 5847
    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;

5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860
    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;
    }
5861 5862

    return 0;
5863 5864
}

5865 5866
static virSecurityLabelDefPtr
virSecurityLabelDefParseXML(xmlXPathContextPtr ctxt,
5867
                            unsigned int flags)
E
Eric Blake 已提交
5868 5869
{
    char *p;
5870
    virSecurityLabelDefPtr seclabel = NULL;
E
Eric Blake 已提交
5871

5872 5873 5874 5875
    p = virXPathStringLimit("string(./@model)",
                            VIR_SECURITY_MODEL_BUFLEN - 1, ctxt);

    if (!(seclabel = virSecurityLabelDefNew(p)))
5876
        goto error;
5877
    VIR_FREE(p);
E
Eric Blake 已提交
5878

5879 5880 5881
    /* set default value */
    seclabel->type = VIR_DOMAIN_SECLABEL_DYNAMIC;

5882
    p = virXPathStringLimit("string(./@type)",
5883 5884 5885 5886
                            VIR_SECURITY_LABEL_BUFLEN - 1, ctxt);
    if (p) {
        seclabel->type = virDomainSeclabelTypeFromString(p);
        if (seclabel->type <= 0) {
5887
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5888
                           _("invalid security type '%s'"), p);
E
Eric Blake 已提交
5889 5890
            goto error;
        }
5891
    }
5892

5893 5894 5895 5896 5897
    if (seclabel->type == VIR_DOMAIN_SECLABEL_STATIC ||
        seclabel->type == VIR_DOMAIN_SECLABEL_NONE)
        seclabel->relabel = false;

    VIR_FREE(p);
5898
    p = virXPathStringLimit("string(./@relabel)",
E
Eric Blake 已提交
5899
                            VIR_SECURITY_LABEL_BUFLEN-1, ctxt);
5900
    if (p) {
E
Eric Blake 已提交
5901
        if (STREQ(p, "yes")) {
5902
            seclabel->relabel = true;
E
Eric Blake 已提交
5903
        } else if (STREQ(p, "no")) {
5904
            seclabel->relabel = false;
E
Eric Blake 已提交
5905
        } else {
5906 5907
            virReportError(VIR_ERR_XML_ERROR,
                           _("invalid security relabel value %s"), p);
5908
            goto error;
E
Eric Blake 已提交
5909 5910
        }
    }
5911
    VIR_FREE(p);
E
Eric Blake 已提交
5912

5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924
    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;
    }
5925 5926 5927 5928

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

5929
    if (STREQ_NULLABLE(seclabel->model, "none")) {
5930
        if (flags & VIR_DOMAIN_DEF_PARSE_INACTIVE) {
5931
            /* Fix older configurations */
5932 5933
            seclabel->type = VIR_DOMAIN_SECLABEL_NONE;
            seclabel->relabel = false;
5934
        } else {
5935
            if (seclabel->type != VIR_DOMAIN_SECLABEL_NONE) {
5936 5937
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unsupported type='%s' to model 'none'"),
5938
                               virDomainSeclabelTypeToString(seclabel->type));
5939 5940 5941 5942 5943
                goto error;
            }
            /* combination of relabel='yes' and type='static'
             * is checked a few lines above. */
        }
5944
        return seclabel;
5945
    }
5946

E
Eric Blake 已提交
5947
    /* Only parse label, if using static labels, or
5948
     * if the 'live' VM XML is requested
E
Eric Blake 已提交
5949
     */
5950
    if (seclabel->type == VIR_DOMAIN_SECLABEL_STATIC ||
5951
        (!(flags & VIR_DOMAIN_DEF_PARSE_INACTIVE) &&
5952
         seclabel->type != VIR_DOMAIN_SECLABEL_NONE)) {
5953
        p = virXPathStringLimit("string(./label[1])",
E
Eric Blake 已提交
5954
                                VIR_SECURITY_LABEL_BUFLEN-1, ctxt);
5955
        if (p == NULL) {
5956 5957
            virReportError(VIR_ERR_XML_ERROR,
                           "%s", _("security label is missing"));
5958
            goto error;
E
Eric Blake 已提交
5959 5960
        }

5961
        seclabel->label = p;
5962
        p = NULL;
E
Eric Blake 已提交
5963 5964 5965
    }

    /* Only parse imagelabel, if requested live XML with relabeling */
5966
    if (seclabel->relabel &&
5967
        (!(flags & VIR_DOMAIN_DEF_PARSE_INACTIVE) &&
5968
         seclabel->type != VIR_DOMAIN_SECLABEL_NONE)) {
5969
        p = virXPathStringLimit("string(./imagelabel[1])",
E
Eric Blake 已提交
5970 5971
                                VIR_SECURITY_LABEL_BUFLEN-1, ctxt);
        if (p == NULL) {
5972 5973
            virReportError(VIR_ERR_XML_ERROR,
                           "%s", _("security imagelabel is missing"));
E
Eric Blake 已提交
5974 5975
            goto error;
        }
5976
        seclabel->imagelabel = p;
5977
        p = NULL;
E
Eric Blake 已提交
5978 5979
    }

E
Eric Blake 已提交
5980
    /* Only parse baselabel for dynamic label type */
5981
    if (seclabel->type == VIR_DOMAIN_SECLABEL_DYNAMIC) {
5982
        p = virXPathStringLimit("string(./baselabel[1])",
E
Eric Blake 已提交
5983
                                VIR_SECURITY_LABEL_BUFLEN-1, ctxt);
5984
        seclabel->baselabel = p;
5985
        p = NULL;
E
Eric Blake 已提交
5986 5987
    }

5988
    return seclabel;
E
Eric Blake 已提交
5989

5990
 error:
5991 5992
    VIR_FREE(p);
    virSecurityLabelDefFree(seclabel);
5993
    return NULL;
E
Eric Blake 已提交
5994 5995
}

5996
static int
5997
virSecurityLabelDefsParseXML(virDomainDefPtr def,
5998 5999 6000
                             xmlXPathContextPtr ctxt,
                             virCapsPtr caps,
                             unsigned int flags)
6001
{
6002
    size_t i = 0, j;
6003
    int n;
6004
    xmlNodePtr *list = NULL, saved_node;
6005
    virCapsHostPtr host = &caps->host;
6006

6007 6008 6009 6010
    /* Check args and save context */
    if (def == NULL || ctxt == NULL)
        return 0;
    saved_node = ctxt->node;
6011

6012
    /* Allocate a security labels based on XML */
6013 6014 6015
    if ((n = virXPathNodeSet("./seclabel", ctxt, &list)) < 0)
        goto error;
    if (n == 0)
6016 6017
        return 0;

6018
    if (VIR_ALLOC_N(def->seclabels, n) < 0)
6019
        goto error;
6020

6021 6022
    /* Parse each "seclabel" tag */
    for (i = 0; i < n; i++) {
6023 6024
        virSecurityLabelDefPtr seclabel;

6025
        ctxt->node = list[i];
6026
        if (!(seclabel = virSecurityLabelDefParseXML(ctxt, flags)))
6027
            goto error;
6028 6029 6030 6031

        for (j = 0; j < i; j++) {
            if (STREQ_NULLABLE(seclabel->model, def->seclabels[j]->model)) {
                virReportError(VIR_ERR_XML_DETAIL,
E
Erik Skultety 已提交
6032
                               _("seclabel for model %s is already provided"),
6033 6034 6035 6036 6037 6038 6039
                               seclabel->model);
                virSecurityLabelDefFree(seclabel);
                goto error;
            }
        }

        def->seclabels[i] = seclabel;
6040
    }
6041 6042 6043
    def->nseclabels = n;
    ctxt->node = saved_node;
    VIR_FREE(list);
6044

6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057
    /* 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 &&
6058
             (flags & VIR_DOMAIN_DEF_PARSE_INACTIVE))) {
6059 6060 6061
            /* Copy model from host. */
            VIR_DEBUG("Found seclabel without a model, using '%s'",
                      host->secModels[0].model);
6062
            if (VIR_STRDUP(def->seclabels[0]->model, host->secModels[0].model) < 0)
6063
                goto error;
6064 6065

            if (STREQ(def->seclabels[0]->model, "none") &&
6066
                flags & VIR_DOMAIN_DEF_PARSE_INACTIVE) {
6067 6068 6069 6070
                /* Fix older configurations */
                def->seclabels[0]->type = VIR_DOMAIN_SECLABEL_NONE;
                def->seclabels[0]->relabel = false;
            }
6071 6072 6073 6074 6075 6076 6077 6078 6079
        } else {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing security model in domain seclabel"));
            goto error;
        }
    }

    /* Checking missing model information */
    if (def->nseclabels > 1) {
6080
        for (; n; n--) {
6081 6082
            if (def->seclabels[n - 1]->model == NULL) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
6083 6084
                               _("missing security model "
                                 "when using multiple labels"));
6085 6086
                goto error;
            }
6087 6088
        }
    }
6089

6090
    return 0;
6091

6092
 error:
6093
    ctxt->node = saved_node;
6094
    for (; i > 0; i--)
6095 6096
        virSecurityLabelDefFree(def->seclabels[i - 1]);
    VIR_FREE(def->seclabels);
6097
    def->nseclabels = 0;
6098 6099 6100
    VIR_FREE(list);
    return -1;
}
6101

6102
/* Parse the <seclabel> from a disk or character device. */
6103
static int
6104 6105
virSecurityDeviceLabelDefParseXML(virSecurityDeviceLabelDefPtr **seclabels_rtn,
                                  size_t *nseclabels_rtn,
6106
                                  virSecurityLabelDefPtr *vmSeclabels,
6107 6108
                                  int nvmSeclabels, xmlXPathContextPtr ctxt,
                                  unsigned int flags)
6109
{
6110
    virSecurityDeviceLabelDefPtr *seclabels = NULL;
6111
    size_t nseclabels = 0;
6112 6113
    int n;
    size_t i, j;
6114 6115
    xmlNodePtr *list = NULL;
    virSecurityLabelDefPtr vmDef = NULL;
6116
    char *model, *relabel, *label, *labelskip;
6117

6118 6119 6120
    if ((n = virXPathNodeSet("./seclabel", ctxt, &list)) < 0)
        goto error;
    if (n == 0)
6121 6122
        return 0;

6123
    if (VIR_ALLOC_N(seclabels, n) < 0)
6124
        goto error;
6125
    nseclabels = n;
6126
    for (i = 0; i < n; i++) {
6127
        if (VIR_ALLOC(seclabels[i]) < 0)
6128
            goto error;
6129 6130
    }

6131 6132 6133
    for (i = 0; i < n; i++) {
        /* get model associated to this override */
        model = virXMLPropString(list[i], "model");
6134 6135
        if (model) {
            /* find the security label that it's being overridden */
6136 6137 6138 6139 6140 6141
            for (j = 0; j < nvmSeclabels; j++) {
                if (STREQ(vmSeclabels[j]->model, model)) {
                    vmDef = vmSeclabels[j];
                    break;
                }
            }
6142 6143 6144 6145 6146 6147 6148 6149 6150

            /* check for duplicate seclabels */
            for (j = 0; j < i; j++) {
                if (STREQ_NULLABLE(model, seclabels[j]->model)) {
                    virReportError(VIR_ERR_XML_DETAIL,
                                   _("seclabel for model %s is already provided"), model);
                    goto error;
                }
            }
6151
            seclabels[i]->model = model;
6152 6153 6154
        }

        /* Can't use overrides if top-level doesn't allow relabeling.  */
6155
        if (vmDef && !vmDef->relabel) {
6156 6157 6158 6159 6160 6161 6162 6163 6164
            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")) {
6165
                seclabels[i]->relabel = true;
6166
            } else if (STREQ(relabel, "no")) {
6167
                seclabels[i]->relabel = false;
6168 6169 6170 6171 6172 6173 6174 6175 6176
            } else {
                virReportError(VIR_ERR_XML_ERROR,
                               _("invalid security relabel value %s"),
                               relabel);
                VIR_FREE(relabel);
                goto error;
            }
            VIR_FREE(relabel);
        } else {
6177
            seclabels[i]->relabel = true;
6178 6179
        }

6180 6181 6182
        /* labelskip is only parsed on live images */
        labelskip = virXMLPropString(list[i], "labelskip");
        seclabels[i]->labelskip = false;
6183
        if (labelskip && !(flags & VIR_DOMAIN_DEF_PARSE_INACTIVE))
6184 6185 6186
            seclabels[i]->labelskip = STREQ(labelskip, "yes");
        VIR_FREE(labelskip);

6187 6188 6189
        ctxt->node = list[i];
        label = virXPathStringLimit("string(./label)",
                                    VIR_SECURITY_LABEL_BUFLEN-1, ctxt);
6190
        seclabels[i]->label = label;
6191

6192
        if (label && !seclabels[i]->relabel) {
6193 6194 6195
            virReportError(VIR_ERR_XML_ERROR,
                           _("Cannot specify a label if relabelling is "
                             "turned off. model=%s"),
6196
                             NULLSTR(seclabels[i]->model));
6197 6198 6199 6200
            goto error;
        }
    }
    VIR_FREE(list);
6201 6202 6203 6204

    *nseclabels_rtn = nseclabels;
    *seclabels_rtn = seclabels;

6205
    return 0;
6206

6207
 error:
6208
    for (i = 0; i < nseclabels; i++)
6209 6210
        virSecurityDeviceLabelDefFree(seclabels[i]);
    VIR_FREE(seclabels);
6211 6212
    VIR_FREE(list);
    return -1;
6213 6214 6215
}


6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227
/* 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;

6228
    if (VIR_ALLOC(def) < 0)
6229 6230 6231 6232 6233
        return NULL;

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
E
Eric Blake 已提交
6234
            if (!key && xmlStrEqual(cur->name, BAD_CAST "key")) {
6235
                key = (char *)xmlNodeGetContent(cur);
E
Eric Blake 已提交
6236 6237
            } else if (!lockspace &&
                       xmlStrEqual(cur->name, BAD_CAST "lockspace")) {
6238
                lockspace = (char *)xmlNodeGetContent(cur);
E
Eric Blake 已提交
6239 6240
            } else if (!path &&
                       xmlStrEqual(cur->name, BAD_CAST "target")) {
6241 6242 6243 6244 6245 6246 6247 6248
                path = virXMLPropString(cur, "path");
                offset = virXMLPropString(cur, "offset");
            }
        }
        cur = cur->next;
    }

    if (!key) {
6249 6250
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Missing 'key' element for lease"));
6251 6252 6253
        goto error;
    }
    if (!path) {
6254 6255
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Missing 'target' element for lease"));
6256 6257 6258 6259 6260
        goto error;
    }

    if (offset &&
        virStrToLong_ull(offset, NULL, 10, &def->offset) < 0) {
6261 6262
        virReportError(VIR_ERR_XML_ERROR,
                       _("Malformed lease target offset %s"), offset);
6263 6264 6265 6266 6267 6268 6269 6270
        goto error;
    }

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

6271
 cleanup:
6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284
    VIR_FREE(lockspace);
    VIR_FREE(key);
    VIR_FREE(path);
    VIR_FREE(offset);

    return def;

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

6285 6286
static int
virDomainDiskSourcePoolDefParse(xmlNodePtr node,
6287
                                virStorageSourcePoolDefPtr *srcpool)
6288
{
6289
    char *mode = NULL;
6290
    virStorageSourcePoolDefPtr source;
6291 6292
    int ret = -1;

6293 6294 6295 6296 6297 6298 6299
    *srcpool = NULL;

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

    source->pool = virXMLPropString(node, "pool");
    source->volume = virXMLPropString(node, "volume");
6300
    mode = virXMLPropString(node, "mode");
6301 6302

    /* CD-ROM and Floppy allows no source */
6303 6304 6305 6306
    if (!source->pool && !source->volume) {
        ret = 0;
        goto cleanup;
    }
6307

6308
    if (!source->pool || !source->volume) {
6309 6310 6311 6312 6313 6314
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("'pool' and 'volume' must be specified together "
                         "for 'pool' type source"));
        goto cleanup;
    }

6315
    if (mode &&
6316
        (source->mode = virStorageSourcePoolModeTypeFromString(mode)) <= 0) {
6317
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6318 6319 6320 6321 6322
                       _("unknown source mode '%s' for volume type disk"),
                       mode);
        goto cleanup;
    }

6323 6324
    *srcpool = source;
    source = NULL;
6325 6326
    ret = 0;

6327
 cleanup:
6328
    virStorageSourcePoolDefFree(source);
6329
    VIR_FREE(mode);
6330 6331 6332
    return ret;
}

6333

6334
int
6335
virDomainDiskSourceParse(xmlNodePtr node,
6336
                         xmlXPathContextPtr ctxt,
6337
                         virStorageSourcePtr src)
6338 6339
{
    int ret = -1;
6340
    char *protocol = NULL;
6341 6342 6343
    xmlNodePtr saveNode = ctxt->node;

    ctxt->node = node;
6344

6345
    switch ((virStorageType)src->type) {
E
Eric Blake 已提交
6346
    case VIR_STORAGE_TYPE_FILE:
6347
        src->path = virXMLPropString(node, "file");
6348
        break;
E
Eric Blake 已提交
6349
    case VIR_STORAGE_TYPE_BLOCK:
6350
        src->path = virXMLPropString(node, "dev");
6351
        break;
E
Eric Blake 已提交
6352
    case VIR_STORAGE_TYPE_DIR:
6353
        src->path = virXMLPropString(node, "dir");
6354
        break;
E
Eric Blake 已提交
6355
    case VIR_STORAGE_TYPE_NETWORK:
6356 6357 6358 6359
        if (!(protocol = virXMLPropString(node, "protocol"))) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing network source protocol type"));
            goto cleanup;
6360
        }
6361

6362
        if ((src->protocol = virStorageNetProtocolTypeFromString(protocol)) <= 0) {
6363
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6364 6365
                           _("unknown protocol type '%s'"), protocol);
            goto cleanup;
6366 6367
        }

6368 6369
        if (!(src->path = virXMLPropString(node, "name")) &&
            src->protocol != VIR_STORAGE_NET_PROTOCOL_NBD) {
6370
            virReportError(VIR_ERR_XML_ERROR, "%s",
6371
                           _("missing name for disk source"));
6372
            goto cleanup;
6373
        }
6374

6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395
        /* 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';
        }

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

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

6402 6403
        if (virDomainStorageHostParse(node, &src->hosts, &src->nhosts) < 0)
            goto cleanup;
6404
        break;
E
Eric Blake 已提交
6405
    case VIR_STORAGE_TYPE_VOLUME:
6406
        if (virDomainDiskSourcePoolDefParse(node, &src->srcpool) < 0)
6407
            goto cleanup;
6408
        break;
6409 6410
    case VIR_STORAGE_TYPE_NONE:
    case VIR_STORAGE_TYPE_LAST:
6411 6412
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected disk type %s"),
6413
                       virStorageTypeToString(src->type));
6414
        goto cleanup;
6415 6416
    }

6417 6418 6419
    /* 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 */
6420 6421
    if (src->path && !*src->path)
        VIR_FREE(src->path);
6422 6423 6424

    ret = 0;

6425
 cleanup:
6426
    VIR_FREE(protocol);
6427
    ctxt->node = saveNode;
6428 6429 6430 6431
    return ret;
}


6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457
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);
6458
    if (backingStore->type <= 0) {
6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470
        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);
6471
    if (backingStore->format <= 0) {
6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482
        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;
    }

6483
    if (virDomainDiskSourceParse(source, ctxt, backingStore) < 0 ||
6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499
        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;
}


6500 6501
#define VENDOR_LEN  8
#define PRODUCT_LEN 16
6502

6503 6504 6505 6506
/* Parse the XML definition for a disk
 * @param node XML nodeset to parse for disk definition
 */
static virDomainDiskDefPtr
6507
virDomainDiskDefParseXML(virDomainXMLOptionPtr xmlopt,
6508
                         xmlNodePtr node,
L
Lei Li 已提交
6509
                         xmlXPathContextPtr ctxt,
6510
                         virHashTablePtr bootHash,
6511 6512
                         virSecurityLabelDefPtr* vmSeclabels,
                         int nvmSeclabels,
E
Eric Blake 已提交
6513
                         unsigned int flags)
6514
{
6515
    virDomainDiskDefPtr def;
6516
    xmlNodePtr sourceNode = NULL;
6517
    xmlNodePtr cur;
L
Lei Li 已提交
6518
    xmlNodePtr save_ctxt = ctxt->node;
6519 6520
    char *type = NULL;
    char *device = NULL;
6521
    char *snapshot = NULL;
6522
    char *rawio = NULL;
O
Osier Yang 已提交
6523
    char *sgio = NULL;
6524 6525
    char *driverName = NULL;
    char *driverType = NULL;
6526
    bool source = false;
6527
    char *target = NULL;
J
J.B. Joret 已提交
6528
    char *trans = NULL;
6529
    char *bus = NULL;
6530
    char *cachetag = NULL;
6531
    char *error_policy = NULL;
6532
    char *rerror_policy = NULL;
M
Matthias Dahl 已提交
6533
    char *iotag = NULL;
6534
    char *ioeventfd = NULL;
6535
    char *event_idx = NULL;
O
Osier Yang 已提交
6536
    char *copy_on_read = NULL;
6537
    char *driverIOThread = NULL;
6538
    char *devaddr = NULL;
6539
    virStorageEncryptionPtr encryption = NULL;
6540
    char *serial = NULL;
6541
    char *startupPolicy = NULL;
6542
    virStorageAuthDefPtr authdef = NULL;
6543
    char *tray = NULL;
6544
    char *removable = NULL;
6545 6546
    char *logical_block_size = NULL;
    char *physical_block_size = NULL;
O
Osier Yang 已提交
6547
    char *wwn = NULL;
6548 6549
    char *vendor = NULL;
    char *product = NULL;
O
Osier Yang 已提交
6550
    char *discard = NULL;
E
Eric Blake 已提交
6551 6552
    char *mirrorFormat = NULL;
    char *mirrorType = NULL;
6553
    char *domain_name = NULL;
6554 6555
    int expected_secret_usage = -1;
    int auth_secret_usage = -1;
6556
    int ret = 0;
6557

6558
    if (!(def = virDomainDiskDefNew(xmlopt)))
6559 6560
        return NULL;

J
J.B. Joret 已提交
6561 6562 6563 6564 6565
    def->geometry.cylinders = 0;
    def->geometry.heads = 0;
    def->geometry.sectors = 0;
    def->geometry.trans = VIR_DOMAIN_DISK_TRANS_DEFAULT;

V
Viktor Mihajlovski 已提交
6566 6567
    def->blockio.logical_block_size = 0;
    def->blockio.physical_block_size = 0;
6568

L
Lei Li 已提交
6569 6570
    ctxt->node = node;

6571 6572
    type = virXMLPropString(node, "type");
    if (type) {
6573
        if ((def->src->type = virStorageTypeFromString(type)) <= 0) {
6574
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6575
                           _("unknown disk type '%s'"), type);
6576 6577 6578
            goto error;
        }
    } else {
6579
        def->src->type = VIR_STORAGE_TYPE_FILE;
6580 6581
    }

6582 6583
    snapshot = virXMLPropString(node, "snapshot");

6584
    rawio = virXMLPropString(node, "rawio");
O
Osier Yang 已提交
6585
    sgio = virXMLPropString(node, "sgio");
6586

6587 6588 6589
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
6590
            if (!source && xmlStrEqual(cur->name, BAD_CAST "source")) {
6591 6592
                sourceNode = cur;

6593
                if (virDomainDiskSourceParse(cur, ctxt, def->src) < 0)
6594
                    goto error;
6595 6596

                source = true;
6597

6598 6599
                if (def->src->type == VIR_STORAGE_TYPE_NETWORK) {
                    if (def->src->protocol == VIR_STORAGE_NET_PROTOCOL_ISCSI)
6600
                        expected_secret_usage = VIR_SECRET_USAGE_TYPE_ISCSI;
6601
                    else if (def->src->protocol == VIR_STORAGE_NET_PROTOCOL_RBD)
6602
                        expected_secret_usage = VIR_SECRET_USAGE_TYPE_CEPH;
6603
                }
6604

6605 6606
                startupPolicy = virXMLPropString(cur, "startupPolicy");

E
Eric Blake 已提交
6607 6608
            } else if (!target &&
                       xmlStrEqual(cur->name, BAD_CAST "target")) {
6609 6610
                target = virXMLPropString(cur, "dev");
                bus = virXMLPropString(cur, "bus");
6611
                tray = virXMLPropString(cur, "tray");
6612
                removable = virXMLPropString(cur, "removable");
6613 6614 6615 6616 6617 6618

                /* HACK: Work around for compat with Xen
                 * driver in previous libvirt releases */
                if (target &&
                    STRPREFIX(target, "ioemu:"))
                    memmove(target, target+6, strlen(target)-5);
6619 6620 6621
            } else if (!domain_name &&
                       xmlStrEqual(cur->name, BAD_CAST "backenddomain")) {
                domain_name = virXMLPropString(cur, "name");
J
J.B. Joret 已提交
6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644
            } 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) {
6645
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
J
J.B. Joret 已提交
6646 6647 6648 6649 6650
                                       _("invalid translation value '%s'"),
                                       trans);
                        goto error;
                    }
                }
V
Viktor Mihajlovski 已提交
6651
            } else if (xmlStrEqual(cur->name, BAD_CAST "blockio")) {
6652 6653 6654 6655
                logical_block_size =
                    virXMLPropString(cur, "logical_block_size");
                if (logical_block_size &&
                    virStrToLong_ui(logical_block_size, NULL, 0,
V
Viktor Mihajlovski 已提交
6656
                                    &def->blockio.logical_block_size) < 0) {
6657 6658 6659 6660 6661 6662 6663 6664 6665
                    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 已提交
6666
                                    &def->blockio.physical_block_size) < 0) {
6667 6668 6669 6670 6671
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("invalid physical block size '%s'"),
                                   physical_block_size);
                    goto error;
                }
E
Eric Blake 已提交
6672 6673
            } else if (!driverName &&
                       xmlStrEqual(cur->name, BAD_CAST "driver")) {
6674 6675
                driverName = virXMLPropString(cur, "name");
                driverType = virXMLPropString(cur, "type");
6676 6677 6678 6679 6680 6681
                if (STREQ_NULLABLE(driverType, "aio")) {
                    /* In-place conversion to "raw", for Xen back-compat */
                    driverType[0] = 'r';
                    driverType[1] = 'a';
                    driverType[2] = 'w';
                }
6682
                cachetag = virXMLPropString(cur, "cache");
6683
                error_policy = virXMLPropString(cur, "error_policy");
6684
                rerror_policy = virXMLPropString(cur, "rerror_policy");
M
Matthias Dahl 已提交
6685
                iotag = virXMLPropString(cur, "io");
6686
                ioeventfd = virXMLPropString(cur, "ioeventfd");
6687
                event_idx = virXMLPropString(cur, "event_idx");
O
Osier Yang 已提交
6688
                copy_on_read = virXMLPropString(cur, "copy_on_read");
O
Osier Yang 已提交
6689
                discard = virXMLPropString(cur, "discard");
6690
                driverIOThread = virXMLPropString(cur, "iothread");
6691 6692
            } else if (!def->mirror &&
                       xmlStrEqual(cur->name, BAD_CAST "mirror") &&
6693
                       !(flags & VIR_DOMAIN_DEF_PARSE_INACTIVE)) {
6694
                char *ready;
E
Eric Blake 已提交
6695
                char *blockJob;
6696 6697 6698

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

E
Eric Blake 已提交
6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714
                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 已提交
6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736
                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 已提交
6737 6738 6739 6740 6741 6742
                    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 已提交
6743
                    mirrorFormat = virXMLPropString(cur, "format");
6744
                }
6745 6746 6747 6748 6749 6750 6751 6752 6753
                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 已提交
6754 6755 6756 6757 6758 6759 6760 6761 6762
                }
                if (mirrorType) {
                    xmlNodePtr mirrorNode;

                    if (!(mirrorNode = virXPathNode("./mirror/source", ctxt))) {
                        virReportError(VIR_ERR_XML_ERROR, "%s",
                                       _("mirror requires source element"));
                        goto error;
                    }
6763 6764
                    if (virDomainDiskSourceParse(mirrorNode, ctxt,
                                                 def->mirror) < 0)
E
Eric Blake 已提交
6765
                        goto error;
6766
                }
6767 6768
                ready = virXMLPropString(cur, "ready");
                if (ready) {
6769 6770 6771 6772 6773 6774 6775 6776
                    if ((def->mirrorState =
                         virDomainDiskMirrorStateTypeFromString(ready)) < 0) {
                        virReportError(VIR_ERR_XML_ERROR,
                                       _("unknown mirror ready state %s"),
                                       ready);
                        VIR_FREE(ready);
                        goto error;
                    }
6777 6778
                    VIR_FREE(ready);
                }
6779 6780
            } else if (!authdef &&
                       xmlStrEqual(cur->name, BAD_CAST "auth")) {
6781 6782
                if (!(authdef = virStorageAuthDefParse(node->doc, cur)))
                    goto error;
6783 6784
                /* Disk volume types won't have the secrettype filled in until
                 * after virStorageTranslateDiskSourcePool is run
6785
                 */
6786 6787
                if (def->src->type != VIR_STORAGE_TYPE_VOLUME &&
                    (auth_secret_usage =
6788 6789 6790 6791
                     virSecretUsageTypeFromString(authdef->secrettype)) < 0) {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("invalid secret type %s"),
                                   authdef->secrettype);
6792 6793
                    goto error;
                }
L
Lei Li 已提交
6794
            } else if (xmlStrEqual(cur->name, BAD_CAST "iotune")) {
6795 6796 6797 6798 6799 6800 6801 6802
                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 已提交
6803 6804 6805
                    def->blkdeviotune.total_bytes_sec = 0;
                }

6806 6807 6808 6809 6810 6811 6812 6813
                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 已提交
6814 6815 6816
                    def->blkdeviotune.read_bytes_sec = 0;
                }

6817 6818 6819 6820 6821 6822 6823 6824
                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 已提交
6825 6826 6827
                    def->blkdeviotune.write_bytes_sec = 0;
                }

6828 6829 6830 6831 6832 6833 6834 6835
                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 已提交
6836 6837 6838
                    def->blkdeviotune.total_iops_sec = 0;
                }

6839 6840 6841 6842 6843 6844 6845 6846
                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 已提交
6847 6848 6849
                    def->blkdeviotune.read_iops_sec = 0;
                }

6850 6851 6852 6853 6854 6855 6856 6857
                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 已提交
6858 6859 6860
                    def->blkdeviotune.write_iops_sec = 0;
                }

6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903
                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 已提交
6904 6905 6906 6907
                if ((def->blkdeviotune.total_bytes_sec &&
                     def->blkdeviotune.read_bytes_sec) ||
                    (def->blkdeviotune.total_bytes_sec &&
                     def->blkdeviotune.write_bytes_sec)) {
6908
                    virReportError(VIR_ERR_XML_ERROR, "%s",
6909 6910
                                   _("total and read/write bytes_sec "
                                     "cannot be set at the same time"));
L
Lei Li 已提交
6911 6912 6913 6914 6915 6916 6917
                    goto error;
                }

                if ((def->blkdeviotune.total_iops_sec &&
                     def->blkdeviotune.read_iops_sec) ||
                    (def->blkdeviotune.total_iops_sec &&
                     def->blkdeviotune.write_iops_sec)) {
6918
                    virReportError(VIR_ERR_XML_ERROR, "%s",
6919 6920
                                   _("total and read/write iops_sec "
                                     "cannot be set at the same time"));
L
Lei Li 已提交
6921 6922
                    goto error;
                }
6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943

                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;
                }

6944
            } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
6945
                def->src->readonly = true;
6946
            } else if (xmlStrEqual(cur->name, BAD_CAST "shareable")) {
6947
                def->src->shared = true;
6948
            } else if (xmlStrEqual(cur->name, BAD_CAST "transient")) {
6949
                def->transient = true;
6950
            } else if ((flags & VIR_DOMAIN_DEF_PARSE_STATUS) &&
6951
                       xmlStrEqual(cur->name, BAD_CAST "state")) {
6952
                /* Legacy back-compat. Don't add any more attributes here */
6953
                devaddr = virXMLPropString(cur, "devaddr");
6954 6955
            } else if (encryption == NULL &&
                       xmlStrEqual(cur->name, BAD_CAST "encryption")) {
6956
                encryption = virStorageEncryptionParseNode(node->doc,
6957 6958 6959
                                                           cur);
                if (encryption == NULL)
                    goto error;
E
Eric Blake 已提交
6960 6961
            } else if (!serial &&
                       xmlStrEqual(cur->name, BAD_CAST "serial")) {
6962
                serial = (char *)xmlNodeGetContent(cur);
O
Osier Yang 已提交
6963 6964 6965 6966 6967 6968
            } else if (!wwn &&
                       xmlStrEqual(cur->name, BAD_CAST "wwn")) {
                wwn = (char *)xmlNodeGetContent(cur);

                if (!virValidateWWN(wwn))
                    goto error;
6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987
            } 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 已提交
6988
                if (strlen(product) > PRODUCT_LEN) {
6989 6990 6991 6992 6993 6994 6995 6996 6997 6998
                    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;
                }
6999
            } else if (xmlStrEqual(cur->name, BAD_CAST "boot")) {
7000
                /* boot is parsed as part of virDomainDeviceInfoParseXML */
7001 7002 7003 7004 7005
            }
        }
        cur = cur->next;
    }

7006 7007 7008 7009 7010
    /* Disk volume types will have authentication information handled in
     * virStorageTranslateDiskSourcePool
     */
    if (def->src->type != VIR_STORAGE_TYPE_VOLUME &&
        auth_secret_usage != -1 && auth_secret_usage != expected_secret_usage) {
7011 7012
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid secret type '%s'"),
7013
                       virSecretUsageTypeToString(auth_secret_usage));
7014 7015 7016
        goto error;
    }

7017 7018 7019
    device = virXMLPropString(node, "device");
    if (device) {
        if ((def->device = virDomainDiskDeviceTypeFromString(device)) < 0) {
7020
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7021
                           _("unknown disk device '%s'"), device);
7022 7023 7024 7025 7026 7027 7028
            goto error;
        }
    } else {
        def->device = VIR_DOMAIN_DISK_DEVICE_DISK;
    }

    /* Only CDROM and Floppy devices are allowed missing source path
7029 7030
     * to indicate no media present. LUN is for raw access CD-ROMs
     * that are not attached to a physical device presently */
7031
    if (virStorageSourceIsEmpty(def->src) &&
7032
        (def->device == VIR_DOMAIN_DISK_DEVICE_DISK ||
7033
         (flags & VIR_DOMAIN_DEF_PARSE_DISK_SOURCE))) {
7034 7035
        virReportError(VIR_ERR_NO_SOURCE,
                       target ? "%s" : NULL, target);
7036 7037 7038
        goto error;
    }

7039 7040 7041 7042
    /* If source is present, check for an optional seclabel override.  */
    if (sourceNode) {
        xmlNodePtr saved_node = ctxt->node;
        ctxt->node = sourceNode;
7043 7044
        if (virSecurityDeviceLabelDefParseXML(&def->src->seclabels,
                                              &def->src->nseclabels,
7045
                                              vmSeclabels,
7046
                                              nvmSeclabels,
7047 7048
                                              ctxt,
                                              flags) < 0)
7049 7050 7051 7052
            goto error;
        ctxt->node = saved_node;
    }

7053
    if (!target && !(flags & VIR_DOMAIN_DEF_PARSE_DISK_SOURCE)) {
7054
        if (def->src->srcpool) {
7055 7056
            char *tmp;
            if (virAsprintf(&tmp, "pool = '%s', volume = '%s'",
7057
                def->src->srcpool->pool, def->src->srcpool->volume) < 0)
7058 7059 7060 7061 7062
                goto error;

            virReportError(VIR_ERR_NO_TARGET, "%s", tmp);
            VIR_FREE(tmp);
        } else {
7063
            virReportError(VIR_ERR_NO_TARGET, def->src->path ? "%s" : NULL, def->src->path);
7064
        }
7065 7066 7067
        goto error;
    }

7068
    if (!(flags & VIR_DOMAIN_DEF_PARSE_DISK_SOURCE)) {
7069 7070 7071 7072 7073 7074
        if (def->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
            !STRPREFIX(target, "fd")) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid floppy device name: %s"), target);
            goto error;
        }
7075

7076 7077 7078
        /* Force CDROM to be listed as read only */
        if (def->device == VIR_DOMAIN_DISK_DEVICE_CDROM)
            def->src->readonly = true;
7079

7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090
        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;
        }
7091 7092
    }

7093
    if (snapshot) {
E
Eric Blake 已提交
7094
        def->snapshot = virDomainSnapshotLocationTypeFromString(snapshot);
7095
        if (def->snapshot <= 0) {
7096
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7097 7098
                           _("unknown disk snapshot setting '%s'"),
                           snapshot);
7099 7100
            goto error;
        }
7101
    } else if (def->src->readonly) {
E
Eric Blake 已提交
7102
        def->snapshot = VIR_DOMAIN_SNAPSHOT_LOCATION_NONE;
7103 7104
    }

O
Osier Yang 已提交
7105 7106 7107 7108 7109 7110 7111 7112
    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;
    }

7113
    if (rawio) {
7114
        if ((def->rawio = virTristateBoolTypeFromString(rawio)) <= 0) {
O
Osier Yang 已提交
7115 7116 7117 7118 7119 7120 7121 7122
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown disk rawio setting '%s'"),
                           rawio);
            goto error;
        }
    }

    if (sgio) {
7123
        if ((def->sgio = virDomainDeviceSGIOTypeFromString(sgio)) <= 0) {
7124
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
O
Osier Yang 已提交
7125
                           _("unknown disk sgio mode '%s'"), sgio);
7126 7127 7128 7129
            goto error;
        }
    }

7130 7131
    if (bus) {
        if ((def->bus = virDomainDiskBusTypeFromString(bus)) < 0) {
7132
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7133
                           _("unknown disk bus type '%s'"), bus);
7134 7135 7136 7137 7138
            goto error;
        }
    } else {
        if (def->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
            def->bus = VIR_DOMAIN_DISK_BUS_FDC;
7139
        } else if (!(flags & VIR_DOMAIN_DEF_PARSE_DISK_SOURCE)) {
7140 7141 7142 7143 7144 7145 7146 7147
            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;
7148 7149
            else if (STRPREFIX(target, "ubd"))
                def->bus = VIR_DOMAIN_DISK_BUS_UML;
7150 7151 7152 7153 7154
            else
                def->bus = VIR_DOMAIN_DISK_BUS_IDE;
        }
    }

7155 7156
    if (tray) {
        if ((def->tray_status = virDomainDiskTrayTypeFromString(tray)) < 0) {
7157
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7158
                           _("unknown disk tray status '%s'"), tray);
7159 7160 7161 7162 7163
            goto error;
        }

        if (def->device != VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
            def->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
7164 7165
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("tray is only valid for cdrom and floppy"));
7166 7167 7168 7169 7170 7171 7172 7173
            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;
    }

7174
    if (removable) {
J
Ján Tomko 已提交
7175
        if ((def->removable = virTristateSwitchTypeFromString(removable)) < 0) {
7176
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7177 7178 7179 7180 7181 7182 7183 7184 7185 7186
                           _("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 {
7187
        if (def->bus == VIR_DOMAIN_DISK_BUS_USB)
J
Ján Tomko 已提交
7188
            def->removable = VIR_TRISTATE_SWITCH_ABSENT;
7189 7190
    }

7191 7192
    if (def->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
        def->bus != VIR_DOMAIN_DISK_BUS_FDC) {
7193 7194
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid bus type '%s' for floppy disk"), bus);
7195 7196 7197 7198
        goto error;
    }
    if (def->device != VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
        def->bus == VIR_DOMAIN_DISK_BUS_FDC) {
7199 7200
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid bus type '%s' for disk"), bus);
7201 7202 7203
        goto error;
    }

7204 7205
    if (cachetag &&
        (def->cachemode = virDomainDiskCacheTypeFromString(cachetag)) < 0) {
7206
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7207
                       _("unknown disk cache mode '%s'"), cachetag);
7208 7209 7210
        goto error;
    }

7211
    if (error_policy &&
7212
        (def->error_policy = virDomainDiskErrorPolicyTypeFromString(error_policy)) <= 0) {
7213
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7214
                       _("unknown disk error policy '%s'"), error_policy);
7215 7216 7217
        goto error;
    }

7218 7219 7220 7221
    if (rerror_policy &&
        (((def->rerror_policy
           = virDomainDiskErrorPolicyTypeFromString(rerror_policy)) <= 0) ||
         (def->rerror_policy == VIR_DOMAIN_DISK_ERROR_POLICY_ENOSPACE))) {
7222
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7223 7224
                       _("unknown disk read error policy '%s'"),
                       rerror_policy);
7225 7226 7227
        goto error;
    }

M
Matthias Dahl 已提交
7228 7229 7230
    if (iotag) {
        if ((def->iomode = virDomainDiskIoTypeFromString(iotag)) < 0 ||
            def->iomode == VIR_DOMAIN_DISK_IO_DEFAULT) {
7231
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7232
                           _("unknown disk io mode '%s'"), iotag);
M
Matthias Dahl 已提交
7233 7234 7235 7236
            goto error;
        }
    }

7237
    if (ioeventfd) {
7238 7239
        int val;

7240
        if (def->bus != VIR_DOMAIN_DISK_BUS_VIRTIO) {
7241
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7242 7243
                           _("disk ioeventfd mode supported "
                             "only for virtio bus"));
7244 7245 7246
            goto error;
        }

J
Ján Tomko 已提交
7247
        if ((val = virTristateSwitchTypeFromString(ioeventfd)) <= 0) {
7248 7249 7250
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown disk ioeventfd mode '%s'"),
                           ioeventfd);
7251 7252
            goto error;
        }
7253
        def->ioeventfd = val;
7254 7255
    }

7256 7257
    if (event_idx) {
        if (def->bus != VIR_DOMAIN_DISK_BUS_VIRTIO) {
7258
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
7259 7260
                           _("disk event_idx mode supported "
                             "only for virtio bus"));
7261 7262 7263 7264
            goto error;
        }

        int idx;
J
Ján Tomko 已提交
7265
        if ((idx = virTristateSwitchTypeFromString(event_idx)) <= 0) {
7266 7267 7268
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown disk event_idx mode '%s'"),
                           event_idx);
7269 7270 7271 7272 7273
            goto error;
        }
        def->event_idx = idx;
    }

O
Osier Yang 已提交
7274 7275
    if (copy_on_read) {
        int cor;
J
Ján Tomko 已提交
7276
        if ((cor = virTristateSwitchTypeFromString(copy_on_read)) <= 0) {
7277 7278 7279
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown disk copy_on_read mode '%s'"),
                           copy_on_read);
O
Osier Yang 已提交
7280 7281 7282 7283 7284
            goto error;
        }
        def->copy_on_read = cor;
    }

O
Osier Yang 已提交
7285 7286 7287 7288 7289 7290 7291 7292
    if (discard) {
        if ((def->discard = virDomainDiskDiscardTypeFromString(discard)) <= 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown disk discard mode '%s'"), discard);
            goto error;
        }
    }

7293
    if (driverIOThread) {
7294 7295
        if (virStrToLong_uip(driverIOThread, NULL, 10, &def->iothread) < 0 ||
            def->iothread == 0) {
7296 7297 7298 7299 7300 7301 7302
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid iothread attribute in disk driver "
                             "element: %s"), driverIOThread);
            goto error;
        }
    }

7303
    if (devaddr) {
7304 7305
        if (virDomainParseLegacyDeviceAddress(devaddr,
                                              &def->info.addr.pci) < 0) {
7306 7307 7308
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to parse devaddr parameter '%s'"),
                           devaddr);
7309 7310 7311 7312
            goto error;
        }
        def->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
    } else {
7313
        if (virDomainDeviceInfoParseXML(node, bootHash, &def->info,
7314
                                        flags | VIR_DOMAIN_DEF_PARSE_ALLOW_BOOT) < 0)
7315
            goto error;
7316 7317
    }

7318
    if (startupPolicy) {
7319
        int val;
7320

7321
        if ((val = virDomainStartupPolicyTypeFromString(startupPolicy)) <= 0) {
7322 7323 7324
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown startupPolicy value '%s'"),
                           startupPolicy);
7325 7326 7327
            goto error;
        }

7328
        if (def->src->type == VIR_STORAGE_TYPE_NETWORK) {
7329 7330 7331
            virReportError(VIR_ERR_XML_ERROR,
                           _("Setting disk %s is not allowed for "
                             "disk of network type"),
7332
                           startupPolicy);
7333 7334
            goto error;
        }
7335 7336 7337 7338 7339 7340 7341 7342 7343

        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;
        }
7344
        def->startupPolicy = val;
7345 7346
    }

7347 7348
    def->dst = target;
    target = NULL;
7349 7350
    def->src->auth = authdef;
    authdef = NULL;
7351
    def->src->driverName = driverName;
7352
    driverName = NULL;
7353
    def->src->encryption = encryption;
7354
    encryption = NULL;
7355 7356
    def->domain_name = domain_name;
    domain_name = NULL;
7357 7358
    def->serial = serial;
    serial = NULL;
O
Osier Yang 已提交
7359 7360
    def->wwn = wwn;
    wwn = NULL;
7361 7362 7363 7364
    def->vendor = vendor;
    vendor = NULL;
    def->product = product;
    product = NULL;
7365

7366
    if (driverType) {
7367 7368
        def->src->format = virStorageFileFormatTypeFromString(driverType);
        if (def->src->format <= 0) {
7369 7370 7371 7372 7373 7374
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown driver format value '%s'"),
                           driverType);
            goto error;
        }
    }
7375

7376
    if (!(flags & VIR_DOMAIN_DEF_PARSE_DISK_SOURCE)) {
7377 7378 7379
        if (virDomainDiskBackingStoreParse(ctxt, def->src) < 0)
            goto error;
    }
7380

7381
 cleanup:
7382 7383
    VIR_FREE(bus);
    VIR_FREE(type);
7384
    VIR_FREE(snapshot);
7385
    VIR_FREE(rawio);
O
Osier Yang 已提交
7386
    VIR_FREE(sgio);
7387
    VIR_FREE(target);
7388
    VIR_FREE(tray);
7389
    VIR_FREE(removable);
J
J.B. Joret 已提交
7390
    VIR_FREE(trans);
7391
    VIR_FREE(device);
7392
    virStorageAuthDefFree(authdef);
7393 7394
    VIR_FREE(driverType);
    VIR_FREE(driverName);
7395
    VIR_FREE(cachetag);
7396
    VIR_FREE(error_policy);
7397
    VIR_FREE(rerror_policy);
M
Matthias Dahl 已提交
7398
    VIR_FREE(iotag);
7399
    VIR_FREE(ioeventfd);
7400
    VIR_FREE(event_idx);
O
Osier Yang 已提交
7401
    VIR_FREE(copy_on_read);
O
Osier Yang 已提交
7402
    VIR_FREE(discard);
7403
    VIR_FREE(driverIOThread);
7404
    VIR_FREE(devaddr);
7405
    VIR_FREE(serial);
7406
    virStorageEncryptionFree(encryption);
7407
    VIR_FREE(startupPolicy);
7408 7409
    VIR_FREE(logical_block_size);
    VIR_FREE(physical_block_size);
O
Osier Yang 已提交
7410
    VIR_FREE(wwn);
7411 7412
    VIR_FREE(vendor);
    VIR_FREE(product);
E
Eric Blake 已提交
7413 7414
    VIR_FREE(mirrorType);
    VIR_FREE(mirrorFormat);
7415
    VIR_FREE(domain_name);
7416

L
Lei Li 已提交
7417
    ctxt->node = save_ctxt;
7418 7419
    return def;

7420
 error:
7421 7422 7423 7424 7425
    virDomainDiskDefFree(def);
    def = NULL;
    goto cleanup;
}

7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447
/**
 * 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.
 */
7448 7449
static int
virDomainParseScaledValue(const char *xpath,
7450
                          const char *units_xpath,
7451 7452 7453 7454 7455 7456 7457 7458
                          xmlXPathContextPtr ctxt,
                          unsigned long long *val,
                          unsigned long long scale,
                          unsigned long long max,
                          bool required)
{
    char *xpath_full = NULL;
    char *unit = NULL;
7459
    char *bytes_str = NULL;
7460 7461 7462 7463 7464 7465
    int ret = -1;
    unsigned long long bytes;

    *val = 0;
    if (virAsprintf(&xpath_full, "string(%s)", xpath) < 0)
        goto cleanup;
7466 7467 7468 7469 7470 7471

    bytes_str = virXPathString(xpath_full, ctxt);
    if (!bytes_str) {
        if (!required) {
            ret = 0;
        } else {
7472
            virReportError(VIR_ERR_XML_ERROR,
7473
                           _("missing element or attribute '%s'"),
7474
                           xpath);
7475
        }
7476 7477 7478 7479
        goto cleanup;
    }
    VIR_FREE(xpath_full);

7480 7481
    if (virStrToLong_ullp(bytes_str, NULL, 10, &bytes) < 0) {
        virReportError(VIR_ERR_XML_ERROR,
7482
                       _("Invalid value '%s' for element or attribute '%s'"),
7483 7484 7485 7486
                       bytes_str, xpath);
        goto cleanup;
    }

7487 7488 7489 7490
    if ((units_xpath &&
         virAsprintf(&xpath_full, "string(%s)", units_xpath) < 0) ||
        (!units_xpath &&
         virAsprintf(&xpath_full, "string(%s/@unit)", xpath) < 0))
7491 7492 7493 7494 7495 7496 7497 7498
        goto cleanup;
    unit = virXPathString(xpath_full, ctxt);

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

    *val = bytes;
    ret = 1;
7499
 cleanup:
7500
    VIR_FREE(bytes_str);
7501 7502 7503 7504 7505 7506
    VIR_FREE(xpath_full);
    VIR_FREE(unit);
    return ret;
}


7507 7508 7509 7510 7511 7512 7513 7514
/**
 * 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
7515
 *
7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528
 * 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.
 */
7529
int
7530 7531 7532 7533 7534 7535
virDomainParseMemory(const char *xpath,
                     const char *units_xpath,
                     xmlXPathContextPtr ctxt,
                     unsigned long long *mem,
                     bool required,
                     bool capped)
7536 7537 7538
{
    unsigned long long bytes, max;

7539
    max = virMemoryMaxValue(capped);
7540

J
Ján Tomko 已提交
7541 7542 7543
    if (virDomainParseScaledValue(xpath, units_xpath, ctxt,
                                  &bytes, 1024, max, required) < 0)
        return -1;
7544 7545 7546

    /* Yes, we really do use kibibytes for our internal sizing.  */
    *mem = VIR_DIV_UP(bytes, 1024);
7547 7548 7549

    if (*mem >= VIR_DIV_UP(max, 1024)) {
        virReportError(VIR_ERR_OVERFLOW, "%s", _("size value too large"));
J
Ján Tomko 已提交
7550
        return -1;
7551
    }
J
Ján Tomko 已提交
7552
    return 0;
7553 7554 7555
}


7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599
/**
 * virDomainParseMemoryLimit:
 *
 * @xpath: XPath to memory amount
 * @units_xpath: XPath to units attribute
 * @ctxt: XPath context
 * @mem: scaled memory amount is stored here
 *
 * 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.  The value must not exceed VIR_DOMAIN_MEMORY_PARAM_UNLIMITED
 * once scaled.
 *
 * This helper should be used only on *_limit memory elements.
 *
 * Return 0 on success, -1 on failure after issuing error.
 */
static int
virDomainParseMemoryLimit(const char *xpath,
                          const char *units_xpath,
                          xmlXPathContextPtr ctxt,
                          unsigned long long *mem)
{
    int ret;
    unsigned long long bytes;

    ret = virDomainParseScaledValue(xpath, units_xpath, ctxt, &bytes, 1024,
                                    VIR_DOMAIN_MEMORY_PARAM_UNLIMITED << 10,
                                    false);

    if (ret < 0)
        return -1;

    if (ret == 0)
        *mem = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
    else
        *mem = virMemoryLimitTruncate(VIR_DIV_UP(bytes, 1024));

    return 0;
}


7600 7601 7602 7603 7604 7605 7606
bool
virDomainDefHasMemoryHotplug(const virDomainDef *def)
{
    return def->mem.memory_slots > 0 || def->mem.max_memory > 0;
}


7607 7608 7609 7610 7611 7612 7613 7614 7615
/**
 * virDomainDefGetMemoryInitial:
 * @def: domain definition
 *
 * Returns the size of the initial amount of guest memory. The initial amount
 * is the memory size is either the configured amount in the <memory> element
 * or the sum of memory sizes of NUMA nodes in case NUMA is enabled in @def.
 */
unsigned long long
7616
virDomainDefGetMemoryInitial(const virDomainDef *def)
7617
{
7618
    return def->mem.initial_memory;
7619 7620 7621 7622
}


/**
7623
 * virDomainDefSetMemoryTotal:
7624 7625 7626
 * @def: domain definition
 * @size: size to set
 *
7627 7628
 * Sets the total memory size in @def. This function should be used only by
 * hypervisors that don't support memory hotplug.
7629 7630
 */
void
7631 7632
virDomainDefSetMemoryTotal(virDomainDefPtr def,
                           unsigned long long size)
7633
{
7634
    def->mem.total_memory = size;
7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650
    def->mem.initial_memory = size;
}


/**
 * virDomainDefSetMemoryInitial:
 * @def: domain definition
 * @size: size to set
 *
 * Sets the initial memory size (without memory modules) in @def.
 */
void
virDomainDefSetMemoryInitial(virDomainDefPtr def,
                             unsigned long long size)
{
    def->mem.initial_memory = size;
7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664
}


/**
 * virDomainDefGetMemoryActual:
 * @def: domain definition
 *
 * Returns the current maximum memory size usable by the domain described by
 * @def. This size is a sum of size returned by virDomainDefGetMemoryInitial
 * and possible additional memory devices.
 */
unsigned long long
virDomainDefGetMemoryActual(virDomainDefPtr def)
{
7665 7666 7667
    unsigned long long ret;
    size_t i;

7668 7669 7670 7671
    ret = def->mem.initial_memory;

    for (i = 0; i < def->nmems; i++)
        ret += def->mems[i]->size;
7672 7673

    return ret;
7674 7675 7676
}


7677
static int
7678
virDomainControllerModelTypeFromString(const virDomainControllerDef *def,
7679 7680 7681 7682
                                       const char *model)
{
    if (def->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI)
        return virDomainControllerModelSCSITypeFromString(model);
7683 7684
    else if (def->type == VIR_DOMAIN_CONTROLLER_TYPE_USB)
        return virDomainControllerModelUSBTypeFromString(model);
J
Ján Tomko 已提交
7685 7686
    else if (def->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI)
        return virDomainControllerModelPCITypeFromString(model);
7687 7688 7689 7690

    return -1;
}

7691 7692 7693 7694
/* Parse the XML definition for a controller
 * @param node XML nodeset to parse for controller definition
 */
static virDomainControllerDefPtr
7695
virDomainControllerDefParseXML(xmlNodePtr node,
7696
                               xmlXPathContextPtr ctxt,
E
Eric Blake 已提交
7697
                               unsigned int flags)
7698
{
7699 7700
    virDomainControllerDefPtr def = NULL;
    int type = 0;
7701
    xmlNodePtr cur = NULL;
7702
    char *typeStr = NULL;
7703
    char *idx = NULL;
7704
    char *model = NULL;
7705
    char *queues = NULL;
7706 7707
    char *cmd_per_lun = NULL;
    char *max_sectors = NULL;
7708 7709
    bool processedModel = false;
    char *modelName = NULL;
7710 7711
    bool processedTarget = false;
    char *chassisNr = NULL;
7712 7713
    char *chassis = NULL;
    char *port = NULL;
7714
    char *ioeventfd = NULL;
7715
    xmlNodePtr saved = ctxt->node;
7716
    int rc;
7717 7718

    ctxt->node = node;
7719

7720 7721 7722
    typeStr = virXMLPropString(node, "type");
    if (typeStr) {
        if ((type = virDomainControllerTypeFromString(typeStr)) < 0) {
7723
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7724
                           _("Unknown controller type '%s'"), typeStr);
7725 7726 7727 7728
            goto error;
        }
    }

7729 7730 7731
    if (!(def = virDomainControllerDefNew(type)))
        goto error;

7732 7733
    idx = virXMLPropString(node, "index");
    if (idx) {
7734 7735
        if (virStrToLong_ui(idx, NULL, 10, &def->idx) < 0 ||
            def->idx > INT_MAX) {
7736 7737
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Cannot parse controller index %s"), idx);
7738 7739 7740 7741
            goto error;
        }
    }

7742 7743
    model = virXMLPropString(node, "model");
    if (model) {
7744
        if ((def->model = virDomainControllerModelTypeFromString(def, model)) < 0) {
7745
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
7746
                           _("Unknown model type '%s'"), model);
7747 7748 7749 7750
            goto error;
        }
    }

7751 7752 7753
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
7754
            if (xmlStrEqual(cur->name, BAD_CAST "driver")) {
7755
                queues = virXMLPropString(cur, "queues");
7756 7757
                cmd_per_lun = virXMLPropString(cur, "cmd_per_lun");
                max_sectors = virXMLPropString(cur, "max_sectors");
7758
                ioeventfd = virXMLPropString(cur, "ioeventfd");
7759 7760 7761 7762 7763 7764 7765 7766 7767
            } else if (xmlStrEqual(cur->name, BAD_CAST "model")) {
                if (processedModel) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("Multiple <model> elements in "
                                     "controller definition not allowed"));
                    goto error;
                }
                modelName = virXMLPropString(cur, "name");
                processedModel = true;
7768 7769 7770 7771 7772 7773 7774 7775
            } else if (xmlStrEqual(cur->name, BAD_CAST "target")) {
                if (processedTarget) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("Multiple <target> elements in "
                                     "controller definition not allowed"));
                    goto error;
                }
                chassisNr = virXMLPropString(cur, "chassisNr");
7776 7777
                chassis = virXMLPropString(cur, "chassis");
                port = virXMLPropString(cur, "port");
7778
                processedTarget = true;
7779
            }
7780
        }
7781 7782 7783 7784 7785 7786 7787
        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;
7788 7789
    }

7790 7791 7792 7793 7794 7795 7796 7797 7798
    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);
7799
        goto error;
7800 7801
    }

7802 7803 7804
    if (ioeventfd &&
        (def->ioeventfd = virTristateSwitchTypeFromString(ioeventfd)) < 0) {
        virReportError(VIR_ERR_XML_ERROR,
7805
                       _("Malformed 'ioeventfd' value %s'"), ioeventfd);
7806 7807 7808
        goto error;
    }

7809 7810 7811 7812
    if (def->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
        def->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE) {
        VIR_DEBUG("Ignoring device address for none model usb controller");
    } else if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0) {
7813
        goto error;
7814
    }
7815

7816 7817 7818 7819 7820 7821 7822
    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) {
7823 7824
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid ports: %s"), ports);
7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835
                VIR_FREE(ports);
                goto error;
            }
        }
        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) {
7836 7837
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid vectors: %s"), vectors);
7838 7839 7840 7841 7842 7843 7844
                VIR_FREE(vectors);
                goto error;
            }
        }
        VIR_FREE(vectors);
        break;
    }
7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866
    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 已提交
7867 7868 7869
    case VIR_DOMAIN_CONTROLLER_TYPE_PCI:
        switch (def->model) {
        case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
7870 7871
        case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT: {
            unsigned long long bytes;
J
Ján Tomko 已提交
7872 7873
            if (def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
L
Laine Stump 已提交
7874
                               _("pci-root and pcie-root controllers should not "
J
Ján Tomko 已提交
7875 7876 7877
                                 "have an address"));
                goto error;
            }
7878 7879
            if (def->idx != 0) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
L
Laine Stump 已提交
7880 7881
                               _("pci-root and pcie-root controllers "
                                 "should have index 0"));
7882 7883
                goto error;
            }
7884 7885
            if ((rc = virDomainParseScaledValue("./pcihole64", NULL,
                                                ctxt, &bytes, 1024,
7886 7887
                                                1024ULL * ULONG_MAX, false)) < 0)
                goto error;
7888

7889 7890 7891 7892
            if (rc == 1)
                def->opts.pciopts.pcihole64 = true;
            def->opts.pciopts.pcihole64size = VIR_DIV_UP(bytes, 1024);
        }
J
Ján Tomko 已提交
7893
        }
7894 7895 7896 7897 7898 7899 7900 7901
        if (modelName &&
            (def->opts.pciopts.modelName
             = virDomainControllerPCIModelNameTypeFromString(modelName)) <= 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Unknown PCI controller model name '%s'"),
                           modelName);
            goto error;
        }
7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918
        if (chassisNr) {
            if (virStrToLong_i(chassisNr, NULL, 0,
                               &def->opts.pciopts.chassisNr) < 0) {
                virReportError(VIR_ERR_XML_ERROR,
                               _("Invalid chassisNr '%s' in PCI controller"),
                               chassisNr);
                goto error;
            }
            if (def->opts.pciopts.chassisNr < 0 ||
                def->opts.pciopts.chassisNr > 255) {
                virReportError(VIR_ERR_XML_ERROR,
                               _("PCI controller chassisNr '%s' out of range "
                                 "- must be 0-255"),
                               chassisNr);
                goto error;
            }
        }
7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952
        if (chassis) {
            if (virStrToLong_i(chassis, NULL, 0,
                               &def->opts.pciopts.chassis) < 0) {
                virReportError(VIR_ERR_XML_ERROR,
                               _("Invalid chassis '%s' in PCI controller"),
                               chassis);
                goto error;
            }
            if (def->opts.pciopts.chassis < 0 ||
                def->opts.pciopts.chassis > 255) {
                virReportError(VIR_ERR_XML_ERROR,
                               _("PCI controller chassis '%s' out of range "
                                 "- must be 0-255"),
                               chassis);
                goto error;
            }
        }
        if (port) {
            if (virStrToLong_i(port, NULL, 0,
                               &def->opts.pciopts.port) < 0) {
                virReportError(VIR_ERR_XML_ERROR,
                               _("Invalid port '%s' in PCI controller"),
                               port);
                goto error;
            }
            if (def->opts.pciopts.port < 0 ||
                def->opts.pciopts.port > 255) {
                virReportError(VIR_ERR_XML_ERROR,
                               _("PCI controller port '%s' out of range "
                                 "- must be 0-255"),
                               port);
                goto error;
            }
        }
7953
        break;
7954 7955 7956 7957 7958

    default:
        break;
    }

7959
    if (def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
7960
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO &&
7961
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW &&
7962
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390 &&
7963
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO &&
7964
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
7965 7966
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Controllers must use the 'pci' address type"));
7967 7968 7969
        goto error;
    }

7970
 cleanup:
7971
    ctxt->node = saved;
7972
    VIR_FREE(typeStr);
7973
    VIR_FREE(idx);
7974
    VIR_FREE(model);
7975
    VIR_FREE(queues);
7976 7977
    VIR_FREE(cmd_per_lun);
    VIR_FREE(max_sectors);
7978
    VIR_FREE(modelName);
7979
    VIR_FREE(chassisNr);
7980 7981
    VIR_FREE(chassis);
    VIR_FREE(port);
7982
    VIR_FREE(ioeventfd);
7983 7984 7985 7986 7987 7988 7989 7990 7991

    return def;

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

7992

7993 7994 7995 7996 7997 7998 7999 8000
void
virDomainNetGenerateMAC(virDomainXMLOptionPtr xmlopt,
                        virMacAddrPtr mac)
{
    virMacAddrGenerate(xmlopt->config.macPrefix, mac);
}


8001 8002 8003 8004
/* Parse the XML definition for a disk
 * @param node XML nodeset to parse for disk definition
 */
static virDomainFSDefPtr
8005
virDomainFSDefParseXML(xmlNodePtr node,
8006
                       xmlXPathContextPtr ctxt,
8007 8008
                       unsigned int flags)
{
8009
    virDomainFSDefPtr def;
8010
    xmlNodePtr cur, save_node = ctxt->node;
8011
    char *type = NULL;
8012
    char *fsdriver = NULL;
8013 8014
    char *source = NULL;
    char *target = NULL;
8015
    char *format = NULL;
8016
    char *accessmode = NULL;
8017
    char *wrpolicy = NULL;
8018
    char *usage = NULL;
8019
    char *units = NULL;
8020

8021 8022
    ctxt->node = node;

8023
    if (VIR_ALLOC(def) < 0)
8024 8025 8026 8027 8028
        return NULL;

    type = virXMLPropString(node, "type");
    if (type) {
        if ((def->type = virDomainFSTypeFromString(type)) < 0) {
8029
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8030
                           _("unknown filesystem type '%s'"), type);
8031 8032 8033 8034 8035 8036
            goto error;
        }
    } else {
        def->type = VIR_DOMAIN_FS_TYPE_MOUNT;
    }

8037 8038 8039
    accessmode = virXMLPropString(node, "accessmode");
    if (accessmode) {
        if ((def->accessmode = virDomainFSAccessModeTypeFromString(accessmode)) < 0) {
8040
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8041
                           _("unknown accessmode '%s'"), accessmode);
8042 8043 8044 8045 8046 8047
            goto error;
        }
    } else {
        def->accessmode = VIR_DOMAIN_FS_ACCESSMODE_PASSTHROUGH;
    }

8048 8049 8050
    if (virDomainParseScaledValue("./space_hard_limit[1]",
                                  NULL, ctxt, &def->space_hard_limit,
                                  1, ULLONG_MAX, false) < 0)
8051 8052
        goto error;

8053 8054 8055
    if (virDomainParseScaledValue("./space_soft_limit[1]",
                                  NULL, ctxt, &def->space_soft_limit,
                                  1, ULLONG_MAX, false) < 0)
8056 8057
        goto error;

8058 8059 8060
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
E
Eric Blake 已提交
8061 8062
            if (!source &&
                xmlStrEqual(cur->name, BAD_CAST "source")) {
8063

8064
                if (def->type == VIR_DOMAIN_FS_TYPE_MOUNT ||
8065
                    def->type == VIR_DOMAIN_FS_TYPE_BIND) {
8066
                    source = virXMLPropString(cur, "dir");
8067
                } else if (def->type == VIR_DOMAIN_FS_TYPE_FILE) {
8068
                    source = virXMLPropString(cur, "file");
8069
                } else if (def->type == VIR_DOMAIN_FS_TYPE_BLOCK) {
8070
                    source = virXMLPropString(cur, "dev");
8071
                } else if (def->type == VIR_DOMAIN_FS_TYPE_TEMPLATE) {
8072
                    source = virXMLPropString(cur, "name");
8073
                } else if (def->type == VIR_DOMAIN_FS_TYPE_RAM) {
8074
                    usage = virXMLPropString(cur, "usage");
8075
                    units = virXMLPropString(cur, "units");
8076
                }
E
Eric Blake 已提交
8077 8078
            } else if (!target &&
                       xmlStrEqual(cur->name, BAD_CAST "target")) {
8079 8080
                target = virXMLPropString(cur, "dir");
            } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
8081
                def->readonly = true;
8082 8083 8084 8085 8086 8087 8088
            } 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");
8089 8090 8091 8092 8093
            }
        }
        cur = cur->next;
    }

8094
    if (fsdriver) {
8095
        if ((def->fsdriver = virDomainFSDriverTypeFromString(fsdriver)) <= 0) {
8096
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8097
                           _("unknown fs driver type '%s'"), fsdriver);
8098 8099 8100 8101
            goto error;
        }
    }

8102 8103 8104 8105 8106 8107 8108 8109
    if (format) {
        if ((def->format = virStorageFileFormatTypeFromString(format)) <= 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown driver format value '%s'"), format);
            goto error;
        }
    }

8110 8111
    if (wrpolicy) {
        if ((def->wrpolicy = virDomainFSWrpolicyTypeFromString(wrpolicy)) <= 0) {
8112 8113
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown filesystem write policy '%s'"), wrpolicy);
8114 8115 8116 8117 8118 8119
            goto error;
        }
    } else {
        def->wrpolicy = VIR_DOMAIN_FS_WRPOLICY_DEFAULT;
    }

8120 8121
    if (source == NULL &&
        def->type != VIR_DOMAIN_FS_TYPE_RAM) {
8122 8123
        virReportError(VIR_ERR_NO_SOURCE,
                       target ? "%s" : NULL, target);
8124 8125 8126 8127
        goto error;
    }

    if (target == NULL) {
8128 8129
        virReportError(VIR_ERR_NO_TARGET,
                       source ? "%s" : NULL, source);
8130 8131 8132
        goto error;
    }

8133 8134
    if (def->type == VIR_DOMAIN_FS_TYPE_RAM) {
        if (!usage) {
8135 8136
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing 'usage' attribute for RAM filesystem"));
8137 8138 8139
            goto error;
        }
        if (virStrToLong_ull(usage, NULL, 10, &def->usage) < 0) {
8140 8141 8142
            virReportError(VIR_ERR_XML_ERROR,
                           _("cannot parse usage '%s' for RAM filesystem"),
                           usage);
8143 8144
            goto error;
        }
8145
        if (virScaleInteger(&def->usage, units,
8146
                            1024, ULLONG_MAX) < 0)
8147 8148 8149
            goto error;
    }

8150 8151 8152 8153 8154
    def->src = source;
    source = NULL;
    def->dst = target;
    target = NULL;

8155
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
8156 8157
        goto error;

8158
 cleanup:
8159
    ctxt->node = save_node;
8160
    VIR_FREE(type);
8161
    VIR_FREE(fsdriver);
8162 8163
    VIR_FREE(target);
    VIR_FREE(source);
8164
    VIR_FREE(accessmode);
8165
    VIR_FREE(wrpolicy);
8166
    VIR_FREE(usage);
8167
    VIR_FREE(units);
8168
    VIR_FREE(format);
8169 8170 8171 8172 8173 8174 8175 8176 8177

    return def;

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

8178 8179 8180
static int
virDomainActualNetDefParseXML(xmlNodePtr node,
                              xmlXPathContextPtr ctxt,
8181 8182 8183
                              virDomainNetDefPtr parent,
                              virDomainActualNetDefPtr *def,
                              unsigned int flags)
8184 8185 8186 8187
{
    virDomainActualNetDefPtr actual = NULL;
    int ret = -1;
    xmlNodePtr save_ctxt = ctxt->node;
8188
    xmlNodePtr bandwidth_node = NULL;
8189
    xmlNodePtr vlanNode;
8190
    xmlNodePtr virtPortNode;
8191 8192
    char *type = NULL;
    char *mode = NULL;
8193
    char *addrtype = NULL;
8194
    char *trustGuestRxFilters = NULL;
8195
    char *macTableManager = NULL;
8196

8197
    if (VIR_ALLOC(actual) < 0)
8198 8199 8200 8201 8202 8203
        return -1;

    ctxt->node = node;

    type = virXMLPropString(node, "type");
    if (!type) {
8204 8205
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("missing type attribute in interface's <actual> element"));
8206 8207 8208
        goto error;
    }
    if ((actual->type = virDomainNetTypeFromString(type)) < 0) {
8209
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8210
                       _("unknown type '%s' in interface's <actual> element"), type);
8211 8212 8213
        goto error;
    }
    if (actual->type != VIR_DOMAIN_NET_TYPE_BRIDGE &&
8214
        actual->type != VIR_DOMAIN_NET_TYPE_DIRECT &&
8215
        actual->type != VIR_DOMAIN_NET_TYPE_HOSTDEV &&
8216
        actual->type != VIR_DOMAIN_NET_TYPE_NETWORK) {
8217 8218 8219
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unsupported type '%s' in interface's <actual> element"),
                       type);
8220 8221 8222
        goto error;
    }

8223 8224 8225 8226 8227 8228 8229 8230 8231 8232
    trustGuestRxFilters = virXMLPropString(node, "trustGuestRxFilters");
    if (trustGuestRxFilters &&
        ((actual->trustGuestRxFilters
          = virTristateBoolTypeFromString(trustGuestRxFilters)) <= 0)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("unknown trustGuestRxFilters value '%s'"),
                       trustGuestRxFilters);
        goto error;
    }

8233 8234 8235 8236 8237
    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) {
8238 8239 8240
            /* the virtualport in <actual> should always already
             * have an instanceid/interfaceid if its required,
             * so don't let the parser generate one */
8241
            if (!(actual->virtPortProfile
8242 8243 8244
                  = virNetDevVPortProfileParse(virtPortNode,
                                               VIR_VPORT_XML_REQUIRE_ALL_ATTRIBUTES |
                                               VIR_VPORT_XML_REQUIRE_TYPE))) {
8245 8246 8247 8248 8249 8250
                goto error;
            }
        } else {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("<virtualport> element unsupported for type='%s'"
                             " in interface's <actual> element"), type);
A
Ansis Atteka 已提交
8251
            goto error;
8252 8253
        }
    }
8254

8255
    if (actual->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
8256 8257 8258 8259 8260
        actual->data.direct.linkdev = virXPathString("string(./source[1]/@dev)", ctxt);

        mode = virXPathString("string(./source[1]/@mode)", ctxt);
        if (mode) {
            int m;
8261
            if ((m = virNetDevMacVLanModeTypeFromString(mode)) < 0) {
8262
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
J
Ján Tomko 已提交
8263
                               _("Unknown mode '%s' in interface <actual> element"),
8264
                               mode);
8265 8266 8267 8268
                goto error;
            }
            actual->data.direct.mode = m;
        }
8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280
    } 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 已提交
8281
        if (!addrtype && virXPathNode("./source/vendor", ctxt) &&
8282
            VIR_STRDUP(addrtype, "usb") < 0)
8283
            goto error;
8284 8285 8286
        hostdev->mode = VIR_DOMAIN_HOSTDEV_MODE_SUBSYS;
        if (virDomainHostdevDefParseXMLSubsys(node, ctxt, addrtype,
                                              hostdev, flags) < 0) {
8287 8288
            goto error;
        }
8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299
    } 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);
8300 8301 8302
    }
    if (actual->type == VIR_DOMAIN_NET_TYPE_BRIDGE ||
        actual->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
8303
        char *brname = virXPathString("string(./source/@bridge)", ctxt);
8304 8305

        if (!brname && actual->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
8306 8307 8308 8309 8310 8311
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing <source> element with bridge name in "
                             "interface's <actual> element"));
            goto error;
        }
        actual->data.bridge.brname = brname;
8312 8313 8314 8315 8316 8317 8318 8319 8320 8321
        macTableManager = virXPathString("string(./source/@macTableManager)", ctxt);
        if (macTableManager &&
            (actual->data.bridge.macTableManager
             = virNetworkBridgeMACTableManagerTypeFromString(macTableManager)) <= 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid macTableManager setting '%s' "
                             "in domain interface's <actual> element"),
                           macTableManager);
            goto error;
        }
8322 8323
    }

8324 8325
    bandwidth_node = virXPathNode("./bandwidth", ctxt);
    if (bandwidth_node &&
8326 8327 8328
        virNetDevBandwidthParse(&actual->bandwidth,
                                bandwidth_node,
                                actual->type) < 0)
8329 8330
        goto error;

8331 8332 8333 8334
    vlanNode = virXPathNode("./vlan", ctxt);
    if (vlanNode && virNetDevVlanParse(vlanNode, ctxt, &actual->vlan) < 0)
       goto error;

8335 8336 8337
    *def = actual;
    actual = NULL;
    ret = 0;
8338
 error:
8339 8340
    VIR_FREE(type);
    VIR_FREE(mode);
8341
    VIR_FREE(addrtype);
8342
    VIR_FREE(trustGuestRxFilters);
8343
    VIR_FREE(macTableManager);
8344 8345 8346 8347 8348
    virDomainActualNetDefFree(actual);

    ctxt->node = save_ctxt;
    return ret;
}
8349

E
Eric Blake 已提交
8350
#define NET_MODEL_CHARS \
8351
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"
E
Eric Blake 已提交
8352

8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377

int
virDomainNetAppendIpAddress(virDomainNetDefPtr def,
                            const char *address,
                            int family,
                            unsigned int prefix)
{
    virDomainNetIpDefPtr ipDef = NULL;
    if (VIR_ALLOC(ipDef) < 0)
        return -1;

    if (virSocketAddrParse(&ipDef->address, address, family) < 0)
        goto error;
    ipDef->prefix = prefix;

    if (VIR_APPEND_ELEMENT(def->ips, def->nips, ipDef) < 0)
        goto error;

    return 0;

 error:
    VIR_FREE(ipDef);
    return -1;
}

8378 8379 8380 8381
/* Parse the XML definition for a network interface
 * @param node XML nodeset to parse for net definition
 * @return 0 on success, -1 on failure
 */
8382
static virDomainNetDefPtr
8383
virDomainNetDefParseXML(virDomainXMLOptionPtr xmlopt,
8384
                        xmlNodePtr node,
8385
                        xmlXPathContextPtr ctxt,
8386
                        virHashTablePtr bootHash,
8387
                        char *prefix,
E
Eric Blake 已提交
8388
                        unsigned int flags)
8389
{
8390
    virDomainNetDefPtr def;
8391
    virDomainHostdevDefPtr hostdev;
8392 8393 8394 8395
    xmlNodePtr cur;
    char *macaddr = NULL;
    char *type = NULL;
    char *network = NULL;
8396
    char *portgroup = NULL;
8397 8398 8399
    char *bridge = NULL;
    char *dev = NULL;
    char *ifname = NULL;
8400 8401
    char *ifname_guest = NULL;
    char *ifname_guest_actual = NULL;
8402 8403 8404
    char *script = NULL;
    char *address = NULL;
    char *port = NULL;
8405 8406
    char *localaddr = NULL;
    char *localport = NULL;
8407
    char *model = NULL;
8408
    char *backend = NULL;
8409
    char *txmode = NULL;
8410
    char *ioeventfd = NULL;
8411
    char *event_idx = NULL;
8412
    char *queues = NULL;
8413
    char *str = NULL;
8414
    char *filter = NULL;
D
Daniel Veillard 已提交
8415
    char *internal = NULL;
8416
    char *devaddr = NULL;
8417
    char *mode = NULL;
8418
    char *linkstate = NULL;
8419
    char *addrtype = NULL;
8420
    char *domain_name = NULL;
M
Michele Paolino 已提交
8421 8422 8423
    char *vhostuser_mode = NULL;
    char *vhostuser_path = NULL;
    char *vhostuser_type = NULL;
8424
    char *trustGuestRxFilters = NULL;
8425
    char *vhost_path = NULL;
8426
    virNWFilterHashTablePtr filterparams = NULL;
8427
    virDomainActualNetDefPtr actual = NULL;
8428
    xmlNodePtr oldnode = ctxt->node;
8429
    int ret, val;
8430 8431 8432
    size_t i;
    size_t nips = 0;
    virDomainNetIpDefPtr *ips = NULL;
8433
    size_t nroutes = 0;
8434
    virNetworkRouteDefPtr *routes = NULL;
8435

8436
    if (VIR_ALLOC(def) < 0)
8437 8438
        return NULL;

8439 8440
    ctxt->node = node;

8441 8442
    type = virXMLPropString(node, "type");
    if (type != NULL) {
S
Stefan Berger 已提交
8443
        if ((int)(def->type = virDomainNetTypeFromString(type)) < 0) {
8444
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8445
                           _("unknown interface type '%s'"), type);
8446 8447 8448 8449 8450 8451
            goto error;
        }
    } else {
        def->type = VIR_DOMAIN_NET_TYPE_USER;
    }

8452 8453 8454 8455 8456 8457 8458 8459 8460 8461
    trustGuestRxFilters = virXMLPropString(node, "trustGuestRxFilters");
    if (trustGuestRxFilters &&
        ((def->trustGuestRxFilters
          = virTristateBoolTypeFromString(trustGuestRxFilters)) <= 0)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("unknown trustGuestRxFilters value '%s'"),
                       trustGuestRxFilters);
        goto error;
    }

8462 8463 8464
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
E
Eric Blake 已提交
8465
            if (!macaddr && xmlStrEqual(cur->name, BAD_CAST "mac")) {
8466
                macaddr = virXMLPropString(cur, "address");
E
Eric Blake 已提交
8467 8468 8469
            } else if (!network &&
                       def->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
                       xmlStrEqual(cur->name, BAD_CAST "source")) {
8470
                network = virXMLPropString(cur, "network");
8471
                portgroup = virXMLPropString(cur, "portgroup");
E
Eric Blake 已提交
8472 8473 8474
            } else if (!internal &&
                       def->type == VIR_DOMAIN_NET_TYPE_INTERNAL &&
                       xmlStrEqual(cur->name, BAD_CAST "source")) {
D
Daniel Veillard 已提交
8475
                internal = virXMLPropString(cur, "name");
G
Guannan Ren 已提交
8476
            } else if (!bridge &&
E
Eric Blake 已提交
8477 8478
                       def->type == VIR_DOMAIN_NET_TYPE_BRIDGE &&
                       xmlStrEqual(cur->name, BAD_CAST "source")) {
8479
                bridge = virXMLPropString(cur, "bridge");
E
Eric Blake 已提交
8480
            } else if (!dev &&
8481 8482
                       (def->type == VIR_DOMAIN_NET_TYPE_ETHERNET ||
                        def->type == VIR_DOMAIN_NET_TYPE_DIRECT) &&
8483
                       xmlStrEqual(cur->name, BAD_CAST "source")) {
8484 8485
                dev  = virXMLPropString(cur, "dev");
                mode = virXMLPropString(cur, "mode");
M
Michele Paolino 已提交
8486 8487 8488 8489 8490 8491
            } 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");
8492 8493
            } else if (!def->virtPortProfile
                       && xmlStrEqual(cur->name, BAD_CAST "virtualport")) {
8494
                if (def->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
8495
                    if (!(def->virtPortProfile
8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507
                          = 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))) {
8508 8509 8510 8511 8512 8513
                        goto error;
                    }
                } else {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("<virtualport> element unsupported for"
                                     " <interface type='%s'>"), type);
8514
                    goto error;
8515
                }
G
Guannan Ren 已提交
8516
            } else if (!address &&
E
Eric Blake 已提交
8517 8518
                       (def->type == VIR_DOMAIN_NET_TYPE_SERVER ||
                        def->type == VIR_DOMAIN_NET_TYPE_CLIENT ||
8519 8520
                        def->type == VIR_DOMAIN_NET_TYPE_MCAST ||
                        def->type == VIR_DOMAIN_NET_TYPE_UDP) &&
E
Eric Blake 已提交
8521
                       xmlStrEqual(cur->name, BAD_CAST "source")) {
8522 8523
                address = virXMLPropString(cur, "address");
                port = virXMLPropString(cur, "port");
8524 8525 8526 8527 8528 8529 8530
                if (!localaddr && def->type == VIR_DOMAIN_NET_TYPE_UDP) {
                    xmlNodePtr tmpnode = ctxt->node;
                    ctxt->node = cur;
                    localaddr = virXPathString("string(./local/@address)", ctxt);
                    localport = virXPathString("string(./local/@port)", ctxt);
                    ctxt->node = tmpnode;
                }
8531 8532 8533 8534 8535 8536 8537 8538
            } else if (xmlStrEqual(cur->name, BAD_CAST "ip")) {
                virDomainNetIpDefPtr ip = NULL;

                if (!(ip = virDomainNetIpParseXML(cur)))
                    goto error;

                if (VIR_APPEND_ELEMENT(ips, nips, ip) < 0)
                    goto error;
8539
            } else if (xmlStrEqual(cur->name, BAD_CAST "route")) {
8540 8541 8542
                virNetworkRouteDefPtr route = NULL;
                if (!(route = virNetworkRouteDefParseXML(_("Domain interface"),
                                                         cur, ctxt)))
8543 8544
                    goto error;

8545 8546
                if (VIR_APPEND_ELEMENT(routes, nroutes, route) < 0) {
                    virNetworkRouteDefFree(route);
8547
                    goto error;
8548
                }
E
Eric Blake 已提交
8549
            } else if (!ifname &&
8550 8551
                       xmlStrEqual(cur->name, BAD_CAST "target")) {
                ifname = virXMLPropString(cur, "dev");
E
Eric Blake 已提交
8552
                if (ifname &&
8553
                    (flags & VIR_DOMAIN_DEF_PARSE_INACTIVE) &&
8554 8555
                     (STRPREFIX(ifname, VIR_NET_GENERATED_PREFIX) ||
                      (prefix && STRPREFIX(ifname, prefix)))) {
8556 8557 8558
                    /* An auto-generated target name, blank it out */
                    VIR_FREE(ifname);
                }
8559 8560 8561 8562
            } 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 已提交
8563
            } else if (!linkstate &&
8564 8565
                       xmlStrEqual(cur->name, BAD_CAST "link")) {
                linkstate = virXMLPropString(cur, "state");
E
Eric Blake 已提交
8566
            } else if (!script &&
8567 8568
                       xmlStrEqual(cur->name, BAD_CAST "script")) {
                script = virXMLPropString(cur, "path");
8569 8570 8571
            } else if (!domain_name &&
                       xmlStrEqual(cur->name, BAD_CAST "backenddomain")) {
                domain_name = virXMLPropString(cur, "name");
8572
            } else if (xmlStrEqual(cur->name, BAD_CAST "model")) {
8573
                model = virXMLPropString(cur, "type");
8574
            } else if (xmlStrEqual(cur->name, BAD_CAST "driver")) {
8575
                backend = virXMLPropString(cur, "name");
8576
                txmode = virXMLPropString(cur, "txmode");
8577
                ioeventfd = virXMLPropString(cur, "ioeventfd");
8578
                event_idx = virXMLPropString(cur, "event_idx");
8579
                queues = virXMLPropString(cur, "queues");
8580
            } else if (xmlStrEqual(cur->name, BAD_CAST "filterref")) {
8581 8582 8583 8584 8585 8586
                if (filter) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("Invalid specification of multiple <filterref>s "
                                     "in a single <interface>"));
                    goto error;
                }
8587
                filter = virXMLPropString(cur, "filter");
8588
                virNWFilterHashTableFree(filterparams);
8589
                filterparams = virNWFilterParseParamAttributes(cur);
8590
            } else if ((flags & VIR_DOMAIN_DEF_PARSE_STATUS) &&
8591
                       xmlStrEqual(cur->name, BAD_CAST "state")) {
8592
                /* Legacy back-compat. Don't add any more attributes here */
8593
                devaddr = virXMLPropString(cur, "devaddr");
8594
            } else if (xmlStrEqual(cur->name, BAD_CAST "boot")) {
8595
                /* boot is parsed as part of virDomainDeviceInfoParseXML */
E
Eric Blake 已提交
8596
            } else if (!actual &&
8597
                       (flags & VIR_DOMAIN_DEF_PARSE_ACTUAL_NET) &&
E
Eric Blake 已提交
8598
                       def->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
8599
                       xmlStrEqual(cur->name, BAD_CAST "actual")) {
8600 8601
                if (virDomainActualNetDefParseXML(cur, ctxt, def,
                                                  &actual, flags) < 0) {
8602
                    goto error;
8603
                }
8604
            } else if (xmlStrEqual(cur->name, BAD_CAST "bandwidth")) {
8605 8606 8607
                if (virNetDevBandwidthParse(&def->bandwidth,
                                            cur,
                                            def->type) < 0)
8608
                    goto error;
8609 8610 8611
            } else if (xmlStrEqual(cur->name, BAD_CAST "vlan")) {
                if (virNetDevVlanParse(cur, ctxt, &def->vlan) < 0)
                    goto error;
8612
            } else if (xmlStrEqual(cur->name, BAD_CAST "backend")) {
8613 8614 8615 8616 8617 8618
                char *tmp = NULL;

                if ((tmp = virXMLPropString(cur, "tap")))
                    def->backend.tap = virFileSanitizePath(tmp);
                VIR_FREE(tmp);

8619 8620
                if (!vhost_path && (tmp = virXMLPropString(cur, "vhost")))
                    vhost_path = virFileSanitizePath(tmp);
8621
                VIR_FREE(tmp);
8622 8623 8624 8625 8626 8627
            }
        }
        cur = cur->next;
    }

    if (macaddr) {
8628
        if (virMacAddrParse((const char *)macaddr, &def->mac) < 0) {
8629 8630 8631
            virReportError(VIR_ERR_XML_ERROR,
                           _("unable to parse mac address '%s'"),
                           (const char *)macaddr);
8632 8633
            goto error;
        }
8634
        if (virMacAddrIsMulticast(&def->mac)) {
8635 8636 8637
            virReportError(VIR_ERR_XML_ERROR,
                           _("expected unicast mac address, found multicast '%s'"),
                           (const char *)macaddr);
8638 8639
            goto error;
        }
8640
    } else {
8641
        virDomainNetGenerateMAC(xmlopt, &def->mac);
8642 8643
    }

8644
    if (devaddr) {
8645 8646
        if (virDomainParseLegacyDeviceAddress(devaddr,
                                              &def->info.addr.pci) < 0) {
8647 8648 8649
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to parse devaddr parameter '%s'"),
                           devaddr);
8650 8651 8652 8653
            goto error;
        }
        def->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
    } else {
8654
        if (virDomainDeviceInfoParseXML(node, bootHash, &def->info,
8655 8656
                                        flags | VIR_DOMAIN_DEF_PARSE_ALLOW_BOOT
                                        | VIR_DOMAIN_DEF_PARSE_ALLOW_ROM) < 0)
8657 8658 8659 8660 8661 8662
            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 &&
8663
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO &&
8664
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW &&
8665
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390 &&
8666
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO &&
8667
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
8668 8669
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Network interfaces must use 'pci' address type"));
8670 8671 8672
        goto error;
    }

8673 8674 8675
    switch (def->type) {
    case VIR_DOMAIN_NET_TYPE_NETWORK:
        if (network == NULL) {
8676 8677 8678
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No <source> 'network' attribute "
                             "specified with <interface type='network'/>"));
8679 8680 8681 8682
            goto error;
        }
        def->data.network.name = network;
        network = NULL;
8683 8684 8685 8686
        def->data.network.portgroup = portgroup;
        portgroup = NULL;
        def->data.network.actual = actual;
        actual = NULL;
8687 8688
        break;

M
Michele Paolino 已提交
8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734
    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;

8735
        if (STREQ(vhostuser_mode, "server")) {
M
Michele Paolino 已提交
8736
            def->data.vhostuser->data.nix.listen = true;
8737
        } else if (STREQ(vhostuser_mode, "client")) {
M
Michele Paolino 已提交
8738
            def->data.vhostuser->data.nix.listen = false;
8739
        } else {
M
Michele Paolino 已提交
8740 8741 8742 8743 8744 8745 8746 8747
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Wrong <source> 'mode' attribute "
                             "specified with <interface "
                             "type='vhostuser'/>"));
            goto error;
        }
        break;

8748 8749 8750 8751 8752 8753 8754 8755 8756
    case VIR_DOMAIN_NET_TYPE_ETHERNET:
        if (dev != NULL) {
            def->data.ethernet.dev = dev;
            dev = NULL;
        }
        break;

    case VIR_DOMAIN_NET_TYPE_BRIDGE:
        if (bridge == NULL) {
8757 8758 8759
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No <source> 'bridge' attribute "
                             "specified with <interface type='bridge'/>"));
8760 8761 8762 8763 8764 8765 8766 8767 8768
            goto error;
        }
        def->data.bridge.brname = bridge;
        bridge = NULL;
        break;

    case VIR_DOMAIN_NET_TYPE_CLIENT:
    case VIR_DOMAIN_NET_TYPE_SERVER:
    case VIR_DOMAIN_NET_TYPE_MCAST:
8769
    case VIR_DOMAIN_NET_TYPE_UDP:
8770
        if (port == NULL) {
8771 8772 8773
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No <source> 'port' attribute "
                             "specified with socket interface"));
8774 8775 8776
            goto error;
        }
        if (virStrToLong_i(port, NULL, 10, &def->data.socket.port) < 0) {
8777 8778 8779
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot parse <source> 'port' attribute "
                             "with socket interface"));
8780 8781 8782 8783 8784
            goto error;
        }

        if (address == NULL) {
            if (def->type == VIR_DOMAIN_NET_TYPE_CLIENT ||
8785 8786
                def->type == VIR_DOMAIN_NET_TYPE_MCAST ||
                def->type == VIR_DOMAIN_NET_TYPE_UDP) {
8787 8788 8789
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("No <source> 'address' attribute "
                                 "specified with socket interface"));
8790 8791 8792 8793 8794 8795
                goto error;
            }
        } else {
            def->data.socket.address = address;
            address = NULL;
        }
8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821

        if (def->type != VIR_DOMAIN_NET_TYPE_UDP)
            break;

        if (localport == NULL) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No <local> 'port' attribute "
                             "specified with socket interface"));
            goto error;
        }
        if (virStrToLong_i(localport, NULL, 10, &def->data.socket.localport) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot parse <local> 'port' attribute "
                             "with socket interface"));
            goto error;
        }

        if (localaddr == NULL) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No <local> 'address' attribute "
                             "specified with socket interface"));
            goto error;
        } else {
            def->data.socket.localaddr = localaddr;
            localaddr = NULL;
        }
8822 8823
        break;

D
Daniel Veillard 已提交
8824 8825
    case VIR_DOMAIN_NET_TYPE_INTERNAL:
        if (internal == NULL) {
8826 8827 8828
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No <source> 'name' attribute specified "
                             "with <interface type='internal'/>"));
D
Daniel Veillard 已提交
8829 8830 8831 8832 8833
            goto error;
        }
        def->data.internal.name = internal;
        internal = NULL;
        break;
8834 8835 8836

    case VIR_DOMAIN_NET_TYPE_DIRECT:
        if (dev == NULL) {
8837 8838 8839
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No <source> 'dev' attribute specified "
                             "with <interface type='direct'/>"));
8840 8841 8842 8843
            goto error;
        }

        if (mode != NULL) {
8844
            if ((val = virNetDevMacVLanModeTypeFromString(mode)) < 0) {
8845
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
J
Ján Tomko 已提交
8846
                               _("Unknown mode has been specified"));
8847 8848
                goto error;
            }
8849
            def->data.direct.mode = val;
E
Eric Blake 已提交
8850
        } else {
8851
            def->data.direct.mode = VIR_NETDEV_MACVLAN_MODE_VEPA;
E
Eric Blake 已提交
8852
        }
8853 8854 8855 8856

        def->data.direct.linkdev = dev;
        dev = NULL;

8857
        if (flags & VIR_DOMAIN_DEF_PARSE_INACTIVE)
8858
            VIR_FREE(ifname);
8859

8860
        break;
S
Stefan Berger 已提交
8861

8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872
    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 已提交
8873
        if (!addrtype && virXPathNode("./source/vendor", ctxt) &&
8874
            VIR_STRDUP(addrtype, "usb") < 0)
8875
            goto error;
8876 8877 8878
        hostdev->mode = VIR_DOMAIN_HOSTDEV_MODE_SUBSYS;
        if (virDomainHostdevDefParseXMLSubsys(node, ctxt, addrtype,
                                              hostdev, flags) < 0) {
8879 8880 8881 8882
            goto error;
        }
        break;

S
Stefan Berger 已提交
8883 8884 8885
    case VIR_DOMAIN_NET_TYPE_USER:
    case VIR_DOMAIN_NET_TYPE_LAST:
        break;
8886 8887
    }

8888 8889 8890 8891
    for (i = 0; i < nips; i++) {
        if (VIR_APPEND_ELEMENT(def->ips, def->nips, ips[i]) < 0)
            goto error;
    }
8892 8893
    def->nroutes = nroutes;
    def->routes = routes;
8894

8895 8896 8897 8898
    if (script != NULL) {
        def->script = script;
        script = NULL;
    }
8899 8900 8901 8902
    if (domain_name != NULL) {
        def->domain_name = domain_name;
        domain_name = NULL;
    }
8903 8904 8905 8906
    if (ifname != NULL) {
        def->ifname = ifname;
        ifname = NULL;
    }
8907 8908 8909 8910 8911 8912 8913 8914
    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;
    }
8915 8916 8917 8918 8919

    /* 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 已提交
8920
     * QEMU PPC64 supports spapr-vlan
8921 8922
     */
    if (model != NULL) {
E
Eric Blake 已提交
8923
        if (strspn(model, NET_MODEL_CHARS) < strlen(model)) {
8924 8925
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("Model name contains invalid characters"));
E
Eric Blake 已提交
8926
            goto error;
8927 8928 8929 8930 8931
        }
        def->model = model;
        model = NULL;
    }

8932 8933
    if (def->type != VIR_DOMAIN_NET_TYPE_HOSTDEV &&
        STREQ_NULLABLE(def->model, "virtio")) {
8934
        if (backend != NULL) {
8935 8936
            if ((val = virDomainNetBackendTypeFromString(backend)) < 0 ||
                val == VIR_DOMAIN_NET_BACKEND_TYPE_DEFAULT) {
8937
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8938 8939 8940
                               _("Unknown interface <driver name='%s'> "
                                 "has been specified"),
                               backend);
8941 8942
                goto error;
            }
8943
            def->driver.virtio.name = val;
8944
        }
8945
        if (txmode != NULL) {
8946 8947
            if ((val = virDomainNetVirtioTxModeTypeFromString(txmode)) < 0 ||
                val == VIR_DOMAIN_NET_VIRTIO_TX_MODE_DEFAULT) {
8948
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8949 8950 8951
                               _("Unknown interface <driver txmode='%s'> "
                                 "has been specified"),
                               txmode);
8952 8953
                goto error;
            }
8954
            def->driver.virtio.txmode = val;
8955
        }
8956
        if (ioeventfd) {
J
Ján Tomko 已提交
8957
            if ((val = virTristateSwitchTypeFromString(ioeventfd)) <= 0) {
8958 8959 8960
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown interface ioeventfd mode '%s'"),
                               ioeventfd);
8961 8962
                goto error;
            }
8963
            def->driver.virtio.ioeventfd = val;
8964
        }
8965
        if (event_idx) {
8966
            if ((val = virTristateSwitchTypeFromString(event_idx)) <= 0) {
8967 8968 8969
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown interface event_idx mode '%s'"),
                               event_idx);
8970 8971
                goto error;
            }
8972
            def->driver.virtio.event_idx = val;
8973
        }
8974 8975
        if (queues) {
            unsigned int q;
8976
            if (virStrToLong_uip(queues, NULL, 10, &q) < 0) {
8977 8978 8979 8980 8981
                virReportError(VIR_ERR_XML_DETAIL,
                               _("'queues' attribute must be positive number: %s"),
                               queues);
                goto error;
            }
8982 8983
            if (q > 1)
                def->driver.virtio.queues = q;
8984
        }
8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044
        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);
9045 9046 9047 9048 9049 9050 9051 9052 9053 9054
        if ((str = virXPathString("string(./driver/host/@mrg_rxbuf)", ctxt))) {
            if ((val = virTristateSwitchTypeFromString(str)) <= 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown host mrg_rxbuf mode '%s'"),
                               str);
                goto error;
            }
            def->driver.virtio.host.mrg_rxbuf = val;
        }
        VIR_FREE(str);
9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103
        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;
        }
9104 9105
        def->backend.vhost = vhost_path;
        vhost_path = NULL;
9106
    }
9107

9108 9109 9110
    def->linkstate = VIR_DOMAIN_NET_INTERFACE_LINK_STATE_DEFAULT;
    if (linkstate != NULL) {
        if ((def->linkstate = virDomainNetInterfaceLinkStateTypeFromString(linkstate)) <= 0) {
9111 9112 9113
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown interface link state '%s'"),
                           linkstate);
9114 9115 9116 9117
            goto error;
        }
    }

9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132
    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;
        }
    }

9133 9134 9135 9136
    ret = virXPathULong("string(./tune/sndbuf)", ctxt, &def->tune.sndbuf);
    if (ret >= 0) {
        def->tune.sndbuf_specified = true;
    } else if (ret == -2) {
9137 9138
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("sndbuf must be a positive integer"));
9139 9140 9141
        goto error;
    }

9142
 cleanup:
9143
    ctxt->node = oldnode;
9144 9145
    VIR_FREE(macaddr);
    VIR_FREE(network);
9146
    VIR_FREE(portgroup);
9147 9148
    VIR_FREE(address);
    VIR_FREE(port);
M
Michele Paolino 已提交
9149 9150 9151
    VIR_FREE(vhostuser_type);
    VIR_FREE(vhostuser_path);
    VIR_FREE(vhostuser_mode);
9152
    VIR_FREE(ifname);
9153 9154
    VIR_FREE(ifname_guest);
    VIR_FREE(ifname_guest_actual);
9155
    VIR_FREE(dev);
9156
    virDomainActualNetDefFree(actual);
9157 9158 9159
    VIR_FREE(script);
    VIR_FREE(bridge);
    VIR_FREE(model);
9160
    VIR_FREE(backend);
9161
    VIR_FREE(txmode);
9162
    VIR_FREE(ioeventfd);
9163
    VIR_FREE(event_idx);
9164
    VIR_FREE(queues);
9165
    VIR_FREE(str);
9166
    VIR_FREE(filter);
9167
    VIR_FREE(type);
D
Daniel Veillard 已提交
9168
    VIR_FREE(internal);
9169
    VIR_FREE(devaddr);
S
Stefan Berger 已提交
9170
    VIR_FREE(mode);
9171
    VIR_FREE(linkstate);
9172
    VIR_FREE(addrtype);
9173
    VIR_FREE(domain_name);
9174
    VIR_FREE(trustGuestRxFilters);
9175
    VIR_FREE(ips);
9176
    VIR_FREE(vhost_path);
9177 9178
    VIR_FREE(localaddr);
    VIR_FREE(localport);
9179
    virNWFilterHashTableFree(filterparams);
9180 9181 9182

    return def;

9183
 error:
9184 9185 9186 9187 9188
    virDomainNetDefFree(def);
    def = NULL;
    goto cleanup;
}

9189
static int
9190 9191
virDomainChrDefaultTargetType(int devtype)
{
9192
    switch ((virDomainChrDeviceType) devtype) {
9193
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
9194 9195 9196
        virReportError(VIR_ERR_XML_ERROR,
                       _("target type must be specified for %s device"),
                       virDomainChrDeviceTypeToString(devtype));
9197
        return -1;
9198 9199

    case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
9200
        return VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_NONE;
9201

9202
    case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
9203
        return VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_ISA;
G
Guannan Ren 已提交
9204

9205
    case VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL:
9206
    case VIR_DOMAIN_CHR_DEVICE_TYPE_LAST:
9207 9208 9209 9210
        /* No target type yet*/
        break;
    }

9211
    return 0;
9212 9213 9214
}

static int
9215
virDomainChrTargetTypeFromString(virDomainChrDefPtr def,
9216
                                 int devtype,
9217 9218 9219 9220
                                 const char *targetType)
{
    int ret = -1;

9221 9222
    if (!targetType)
        return virDomainChrDefaultTargetType(devtype);
9223

9224
    switch ((virDomainChrDeviceType) devtype) {
9225
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
9226
        ret = virDomainChrChannelTargetTypeFromString(targetType);
9227 9228
        break;

9229
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
9230
        ret = virDomainChrConsoleTargetTypeFromString(targetType);
C
Cole Robinson 已提交
9231
        break;
9232

9233
    case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
9234
        ret = virDomainChrSerialTargetTypeFromString(targetType);
G
Guannan Ren 已提交
9235 9236
        break;

9237
    case VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL:
9238
    case VIR_DOMAIN_CHR_DEVICE_TYPE_LAST:
9239
        /* No target type yet*/
9240
        ret = 0;
9241 9242 9243
        break;
    }

G
Guannan Ren 已提交
9244 9245
    def->targetTypeAttr = true;

9246 9247 9248 9249
    return ret;
}

static int
9250
virDomainChrDefParseTargetXML(virDomainChrDefPtr def,
9251 9252
                              xmlNodePtr cur,
                              unsigned int flags)
9253 9254 9255
{
    int ret = -1;
    unsigned int port;
9256 9257 9258
    char *targetType = virXMLPropString(cur, "type");
    char *addrStr = NULL;
    char *portStr = NULL;
9259
    char *stateStr = NULL;
9260 9261

    if ((def->targetType =
9262 9263
         virDomainChrTargetTypeFromString(def, def->deviceType,
                                          targetType)) < 0) {
9264
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9265 9266
                       _("unknown target type '%s' specified for character device"),
                       targetType);
9267 9268 9269 9270 9271 9272 9273 9274 9275 9276
        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");

9277
            if (VIR_ALLOC(def->target.addr) < 0)
9278 9279
                goto error;

9280
            if (addrStr == NULL) {
9281 9282 9283
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("guestfwd channel does not "
                                 "define a target address"));
9284 9285 9286
                goto error;
            }

9287
            if (virSocketAddrParse(def->target.addr, addrStr, AF_UNSPEC) < 0)
9288 9289
                goto error;

9290
            if (def->target.addr->data.stor.ss_family != AF_INET) {
9291 9292 9293
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               "%s", _("guestfwd channel only supports "
                                       "IPv4 addresses"));
9294 9295 9296 9297
                goto error;
            }

            if (portStr == NULL) {
9298 9299 9300
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("guestfwd channel does "
                                 "not define a target port"));
9301 9302 9303 9304
                goto error;
            }

            if (virStrToLong_ui(portStr, NULL, 10, &port) < 0) {
9305 9306 9307
                virReportError(VIR_ERR_XML_ERROR,
                               _("Invalid port number: %s"),
                               portStr);
9308 9309 9310
                goto error;
            }

9311
            virSocketAddrSetPort(def->target.addr, port);
9312 9313 9314 9315
            break;

        case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO:
            def->target.name = virXMLPropString(cur, "name");
9316

9317
            if (!(flags & VIR_DOMAIN_DEF_PARSE_INACTIVE) &&
9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329
                (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;
            }
9330 9331 9332 9333 9334 9335 9336
            break;
        }
        break;

    default:
        portStr = virXMLPropString(cur, "port");
        if (portStr == NULL) {
9337 9338
            /* Set to negative value to indicate we should set it later */
            def->target.port = -1;
9339 9340 9341 9342
            break;
        }

        if (virStrToLong_ui(portStr, NULL, 10, &port) < 0) {
9343 9344 9345
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid port number: %s"),
                           portStr);
9346 9347
            goto error;
        }
9348
        def->target.port = port;
9349 9350 9351 9352 9353
        break;
    }


    ret = 0;
9354
 error:
9355 9356 9357
    VIR_FREE(targetType);
    VIR_FREE(addrStr);
    VIR_FREE(portStr);
9358
    VIR_FREE(stateStr);
9359 9360 9361 9362

    return ret;
}

9363 9364 9365
#define SERIAL_CHANNEL_NAME_CHARS \
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-."

9366 9367 9368 9369 9370 9371 9372
/* 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,
9373 9374 9375 9376 9377
                              xmlNodePtr cur, unsigned int flags,
                              virDomainChrDefPtr chr_def,
                              xmlXPathContextPtr ctxt,
                              virSecurityLabelDefPtr* vmSeclabels,
                              int nvmSeclabels)
9378
{
9379 9380 9381 9382 9383 9384 9385
    char *bindHost = NULL;
    char *bindService = NULL;
    char *connectHost = NULL;
    char *connectService = NULL;
    char *path = NULL;
    char *mode = NULL;
    char *protocol = NULL;
9386
    char *channel = NULL;
9387 9388
    char *master = NULL;
    char *slave = NULL;
9389
    char *append = NULL;
9390
    int remaining = 0;
9391 9392 9393 9394

    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if (xmlStrEqual(cur->name, BAD_CAST "source")) {
9395
                if (!mode)
9396 9397
                    mode = virXMLPropString(cur, "mode");

9398
                switch ((virDomainChrType) def->type) {
9399
                case VIR_DOMAIN_CHR_TYPE_FILE:
9400 9401 9402 9403
                case VIR_DOMAIN_CHR_TYPE_PTY:
                case VIR_DOMAIN_CHR_TYPE_DEV:
                case VIR_DOMAIN_CHR_TYPE_PIPE:
                case VIR_DOMAIN_CHR_TYPE_UNIX:
9404 9405
                    if (!append && def->type == VIR_DOMAIN_CHR_TYPE_FILE)
                        append = virXMLPropString(cur, "append");
9406
                    /* PTY path is only parsed from live xml.  */
9407
                    if (!path  &&
9408
                        (def->type != VIR_DOMAIN_CHR_TYPE_PTY ||
9409
                         !(flags & VIR_DOMAIN_DEF_PARSE_INACTIVE)))
9410 9411 9412 9413 9414 9415
                        path = virXMLPropString(cur, "path");

                    break;

                case VIR_DOMAIN_CHR_TYPE_UDP:
                case VIR_DOMAIN_CHR_TYPE_TCP:
9416 9417
                    if (!mode || STREQ(mode, "connect")) {
                        if (!connectHost)
9418
                            connectHost = virXMLPropString(cur, "host");
9419
                        if (!connectService)
9420
                            connectService = virXMLPropString(cur, "service");
9421 9422
                    } else if (STREQ(mode, "bind")) {
                        if (!bindHost)
9423
                            bindHost = virXMLPropString(cur, "host");
9424
                        if (!bindService)
9425
                            bindService = virXMLPropString(cur, "service");
9426
                    } else {
9427
                        virReportError(VIR_ERR_INTERNAL_ERROR,
9428
                                       _("Unknown source mode '%s'"), mode);
9429
                        goto error;
9430 9431
                    }

9432
                    if (def->type == VIR_DOMAIN_CHR_TYPE_UDP)
9433
                        VIR_FREE(mode);
9434 9435
                    break;

9436 9437 9438 9439 9440
                case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
                    if (!channel)
                        channel = virXMLPropString(cur, "channel");
                    break;

9441 9442 9443 9444 9445 9446 9447
                case VIR_DOMAIN_CHR_TYPE_NMDM:
                    if (!master)
                        master = virXMLPropString(cur, "master");
                    if (!slave)
                        slave = virXMLPropString(cur, "slave");
                    break;

9448 9449 9450 9451 9452 9453
                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;
9454
                }
9455 9456 9457 9458 9459 9460 9461 9462 9463

                /* 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,
9464 9465
                                                          ctxt,
                                                          flags) < 0) {
9466 9467 9468 9469 9470
                        ctxt->node = saved_node;
                        goto error;
                    }
                    ctxt->node = saved_node;
                }
9471
            } else if (xmlStrEqual(cur->name, BAD_CAST "protocol")) {
9472
                if (!protocol)
9473
                    protocol = virXMLPropString(cur, "type");
9474 9475
            } else {
                remaining++;
9476 9477 9478 9479 9480
            }
        }
        cur = cur->next;
    }

9481
    switch ((virDomainChrType) def->type) {
9482
    case VIR_DOMAIN_CHR_TYPE_NULL:
9483
    case VIR_DOMAIN_CHR_TYPE_VC:
9484 9485
    case VIR_DOMAIN_CHR_TYPE_STDIO:
    case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
9486
    case VIR_DOMAIN_CHR_TYPE_LAST:
9487 9488
        break;

9489
    case VIR_DOMAIN_CHR_TYPE_FILE:
9490 9491 9492 9493
    case VIR_DOMAIN_CHR_TYPE_PTY:
    case VIR_DOMAIN_CHR_TYPE_DEV:
    case VIR_DOMAIN_CHR_TYPE_PIPE:
        if (append && def->type == VIR_DOMAIN_CHR_TYPE_FILE &&
9494 9495 9496 9497 9498
            (def->data.file.append = virTristateSwitchTypeFromString(append)) <= 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid append attribute value '%s'"), append);
            goto error;
        }
9499
        if (!path &&
9500
            def->type != VIR_DOMAIN_CHR_TYPE_PTY) {
9501 9502
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing source path attribute for char device"));
9503 9504 9505 9506 9507 9508 9509
            goto error;
        }

        def->data.file.path = path;
        path = NULL;
        break;

9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528
    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;

9529
    case VIR_DOMAIN_CHR_TYPE_TCP:
9530 9531
        if (!mode || STREQ(mode, "connect")) {
            if (!connectHost) {
9532 9533
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Missing source host attribute for char device"));
9534 9535
                goto error;
            }
9536 9537

            if (!connectService) {
9538 9539
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Missing source service attribute for char device"));
9540 9541 9542 9543 9544 9545 9546
                goto error;
            }

            def->data.tcp.host = connectHost;
            connectHost = NULL;
            def->data.tcp.service = connectService;
            connectService = NULL;
9547
            def->data.tcp.listen = false;
9548
        } else {
9549
            if (!bindHost) {
9550 9551
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Missing source host attribute for char device"));
9552 9553
                goto error;
            }
9554 9555

            if (!bindService) {
9556 9557
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Missing source service attribute for char device"));
9558 9559 9560 9561 9562 9563 9564
                goto error;
            }

            def->data.tcp.host = bindHost;
            bindHost = NULL;
            def->data.tcp.service = bindService;
            bindService = NULL;
9565
            def->data.tcp.listen = true;
9566
        }
9567

9568
        if (!protocol)
9569
            def->data.tcp.protocol = VIR_DOMAIN_CHR_TCP_PROTOCOL_RAW;
9570 9571
        else if ((def->data.tcp.protocol =
                  virDomainChrTcpProtocolTypeFromString(protocol)) < 0) {
9572
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9573
                           _("Unknown protocol '%s'"), protocol);
9574 9575 9576
            goto error;
        }

9577 9578 9579
        break;

    case VIR_DOMAIN_CHR_TYPE_UDP:
9580
        if (!connectService) {
9581 9582
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing source service attribute for char device"));
9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597
            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:
9598 9599
        /* path can be auto generated */
        if (!path &&
9600 9601
            (!chr_def ||
             chr_def->targetType != VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO)) {
9602 9603
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing source path attribute for char device"));
9604 9605 9606
            goto error;
        }

9607
        def->data.nix.listen = mode != NULL && STRNEQ(mode, "connect");
9608 9609 9610 9611

        def->data.nix.path = path;
        path = NULL;
        break;
9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626

    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;
9627 9628
    }

9629
 cleanup:
9630 9631 9632 9633 9634 9635 9636
    VIR_FREE(mode);
    VIR_FREE(protocol);
    VIR_FREE(bindHost);
    VIR_FREE(bindService);
    VIR_FREE(connectHost);
    VIR_FREE(connectService);
    VIR_FREE(path);
9637
    VIR_FREE(channel);
9638
    VIR_FREE(append);
9639

9640 9641
    return remaining;

9642
 error:
9643 9644 9645 9646 9647
    virDomainChrSourceDefClear(def);
    remaining = -1;
    goto cleanup;
}

M
Michal Novotny 已提交
9648 9649 9650 9651
/* Create a new character device definition and set
 * default port.
 */
virDomainChrDefPtr
9652 9653
virDomainChrDefNew(void)
{
M
Michal Novotny 已提交
9654 9655
    virDomainChrDefPtr def = NULL;

9656
    if (VIR_ALLOC(def) < 0)
M
Michal Novotny 已提交
9657 9658 9659 9660 9661 9662
        return NULL;

    def->target.port = -1;
    return def;
}

9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699
/* 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>
 *
9700 9701 9702 9703 9704
 * <serial type="nmdm">
 *   <source master="/dev/nmdm0A" slave="/dev/nmdm0B"/>
 *   <target port="1">
 * </serial>
 *
9705 9706
 */
static virDomainChrDefPtr
9707
virDomainChrDefParseXML(xmlXPathContextPtr ctxt,
9708
                        xmlNodePtr node,
9709 9710
                        virSecurityLabelDefPtr* vmSeclabels,
                        int nvmSeclabels,
E
Eric Blake 已提交
9711 9712
                        unsigned int flags)
{
9713 9714 9715 9716
    xmlNodePtr cur;
    char *type = NULL;
    const char *nodeName;
    virDomainChrDefPtr def;
9717
    bool seenTarget = false;
9718

M
Michal Novotny 已提交
9719
    if (!(def = virDomainChrDefNew()))
9720 9721 9722 9723 9724 9725
        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) {
9726
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9727 9728
                       _("unknown type presented to host for character device: %s"),
                       type);
9729 9730 9731 9732 9733
        goto error;
    }

    nodeName = (const char *) node->name;
    if ((def->deviceType = virDomainChrDeviceTypeFromString(nodeName)) < 0) {
9734
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9735 9736
                       _("unknown character device type: %s"),
                       nodeName);
9737
        goto error;
9738 9739 9740
    }

    cur = node->children;
9741 9742 9743 9744
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if (xmlStrEqual(cur->name, BAD_CAST "target")) {
                seenTarget = true;
9745
                if (virDomainChrDefParseTargetXML(def, cur, flags) < 0)
9746
                    goto error;
9747 9748
            }
        }
9749
        cur = cur->next;
9750 9751
    }

9752
    if (!seenTarget &&
9753
        ((def->targetType = virDomainChrDefaultTargetType(def->deviceType)) < 0))
9754
        goto error;
9755

9756 9757 9758 9759
    if (virDomainChrSourceDefParseXML(&def->source, node->children, flags, def,
                                      ctxt, vmSeclabels, nvmSeclabels) < 0)
        goto error;

E
Eric Blake 已提交
9760 9761
    if (def->source.type == VIR_DOMAIN_CHR_TYPE_SPICEVMC) {
        if (def->targetType != VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO) {
9762 9763 9764
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("spicevmc device type only supports "
                             "virtio"));
E
Eric Blake 已提交
9765 9766 9767 9768
            goto error;
        } else {
            def->source.data.spicevmc = VIR_DOMAIN_CHR_SPICEVMC_VDAGENT;
        }
9769 9770
    }

9771 9772 9773 9774
    if (def->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL &&
        def->targetType == VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_GUESTFWD) {
        VIR_DEBUG("Ignoring device address for gustfwd channel");
    } else if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0) {
9775
        goto error;
9776 9777
    }

9778

G
Guannan Ren 已提交
9779 9780 9781 9782 9783 9784 9785 9786 9787
    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;
    }

9788
 cleanup:
9789 9790
    VIR_FREE(type);

9791 9792
    return def;

9793
 error:
9794 9795 9796 9797 9798
    virDomainChrDefFree(def);
    def = NULL;
    goto cleanup;
}

E
Eric Blake 已提交
9799 9800
static virDomainSmartcardDefPtr
virDomainSmartcardDefParseXML(xmlNodePtr node,
E
Eric Blake 已提交
9801
                              unsigned int flags)
E
Eric Blake 已提交
9802 9803 9804 9805 9806
{
    xmlNodePtr cur;
    char *mode = NULL;
    char *type = NULL;
    virDomainSmartcardDefPtr def;
9807
    size_t i;
E
Eric Blake 已提交
9808

9809
    if (VIR_ALLOC(def) < 0)
E
Eric Blake 已提交
9810 9811 9812 9813
        return NULL;

    mode = virXMLPropString(node, "mode");
    if (mode == NULL) {
9814 9815
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing smartcard device mode"));
E
Eric Blake 已提交
9816 9817 9818
        goto error;
    }
    if ((def->type = virDomainSmartcardTypeFromString(mode)) < 0) {
9819
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9820 9821
                       _("unknown smartcard device mode: %s"),
                       mode);
E
Eric Blake 已提交
9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835
        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) {
9836 9837 9838
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("host-certificates mode needs "
                                     "exactly three certificates"));
E
Eric Blake 已提交
9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855
                    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 != '/') {
9856 9857 9858
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("expecting absolute path: %s"),
                                   def->data.cert.database);
E
Eric Blake 已提交
9859 9860 9861 9862 9863 9864
                    goto error;
                }
            }
            cur = cur->next;
        }
        if (i < 3) {
9865 9866 9867
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("host-certificates mode needs "
                             "exactly three certificates"));
E
Eric Blake 已提交
9868 9869 9870 9871 9872 9873 9874
            goto error;
        }
        break;

    case VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH:
        type = virXMLPropString(node, "type");
        if (type == NULL) {
9875 9876 9877
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("passthrough mode requires a character "
                             "device type attribute"));
E
Eric Blake 已提交
9878 9879 9880
            goto error;
        }
        if ((def->data.passthru.type = virDomainChrTypeFromString(type)) < 0) {
9881
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9882 9883
                           _("unknown type presented to host for "
                             "character device: %s"), type);
E
Eric Blake 已提交
9884 9885 9886 9887
            goto error;
        }

        cur = node->children;
9888 9889
        if (virDomainChrSourceDefParseXML(&def->data.passthru, cur, flags,
                                          NULL, NULL, NULL, 0) < 0)
E
Eric Blake 已提交
9890
            goto error;
9891 9892

        if (def->data.passthru.type == VIR_DOMAIN_CHR_TYPE_SPICEVMC) {
E
Eric Blake 已提交
9893 9894
            def->data.passthru.data.spicevmc
                = VIR_DOMAIN_CHR_SPICEVMC_SMARTCARD;
9895
        }
E
Eric Blake 已提交
9896

E
Eric Blake 已提交
9897 9898 9899
        break;

    default:
9900 9901
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unknown smartcard mode"));
E
Eric Blake 已提交
9902 9903 9904
        goto error;
    }

9905
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
E
Eric Blake 已提交
9906 9907 9908
        goto error;
    if (def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
        def->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCID) {
9909 9910
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Controllers must use the 'ccid' address type"));
E
Eric Blake 已提交
9911 9912 9913
        goto error;
    }

9914
 cleanup:
E
Eric Blake 已提交
9915 9916 9917 9918 9919
    VIR_FREE(mode);
    VIR_FREE(type);

    return def;

9920
 error:
E
Eric Blake 已提交
9921 9922 9923 9924 9925
    virDomainSmartcardDefFree(def);
    def = NULL;
    goto cleanup;
}

9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937
/* 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
9938
virDomainTPMDefParseXML(xmlNodePtr node,
9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950
                        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;

9951
    if (VIR_ALLOC(def) < 0)
9952 9953 9954 9955 9956
        return NULL;

    model = virXMLPropString(node, "model");
    if (model != NULL &&
        (int)(def->model = virDomainTPMModelTypeFromString(model)) < 0) {
9957
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974
                       _("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;
    }

9975 9976 9977 9978 9979 9980
    if (nbackends == 0) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing TPM device backend"));
        goto error;
    }

9981 9982 9983 9984 9985 9986 9987
    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) {
9988
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9989 9990 9991 9992 9993 9994 9995 9996
                       _("Unknown TPM backend type '%s'"),
                       backend);
        goto error;
    }

    switch (def->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
        path = virXPathString("string(./backend/device/@path)", ctxt);
9997
        if (!path && VIR_STRDUP(path, VIR_DOMAIN_TPM_DEFAULT_DEVICE) < 0)
9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009
            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;

10010
 cleanup:
10011 10012 10013 10014 10015 10016 10017 10018
    VIR_FREE(type);
    VIR_FREE(path);
    VIR_FREE(model);
    VIR_FREE(backend);
    VIR_FREE(backends);
    ctxt->node = save;
    return def;

10019
 error:
10020 10021 10022 10023 10024
    virDomainTPMDefFree(def);
    def = NULL;
    goto cleanup;
}

10025 10026 10027 10028
static virDomainPanicDefPtr
virDomainPanicDefParseXML(xmlNodePtr node)
{
    virDomainPanicDefPtr panic;
10029
    char *model = NULL;
10030 10031 10032 10033 10034 10035 10036

    if (VIR_ALLOC(panic) < 0)
        return NULL;

    if (virDomainDeviceInfoParseXML(node, NULL, &panic->info, 0) < 0)
        goto error;

10037 10038 10039 10040 10041 10042 10043 10044 10045 10046
    model = virXMLPropString(node, "model");
    if (model != NULL &&
        (panic->model = virDomainPanicModelTypeFromString(model)) < 0) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("unknown panic model '%s'"), model);
        goto error;
    }

 cleanup:
    VIR_FREE(model);
10047
    return panic;
10048

10049 10050
 error:
    virDomainPanicDefFree(panic);
10051 10052
    panic = NULL;
    goto cleanup;
10053 10054
}

10055
/* Parse the XML definition for an input device */
10056
static virDomainInputDefPtr
L
Li Zhang 已提交
10057
virDomainInputDefParseXML(const virDomainDef *dom,
10058
                          xmlNodePtr node,
10059
                          xmlXPathContextPtr ctxt,
E
Eric Blake 已提交
10060 10061
                          unsigned int flags)
{
10062
    xmlNodePtr save = ctxt->node;
10063
    virDomainInputDefPtr def;
10064
    char *evdev = NULL;
10065 10066 10067
    char *type = NULL;
    char *bus = NULL;

10068
    if (VIR_ALLOC(def) < 0)
10069 10070
        return NULL;

10071 10072
    ctxt->node = node;

10073 10074 10075 10076
    type = virXMLPropString(node, "type");
    bus = virXMLPropString(node, "bus");

    if (!type) {
10077 10078
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing input device type"));
10079 10080 10081 10082
        goto error;
    }

    if ((def->type = virDomainInputTypeFromString(type)) < 0) {
10083
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10084
                       _("unknown input device type '%s'"), type);
10085 10086 10087 10088 10089
        goto error;
    }

    if (bus) {
        if ((def->bus = virDomainInputBusTypeFromString(bus)) < 0) {
10090
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10091
                           _("unknown input bus type '%s'"), bus);
10092 10093 10094
            goto error;
        }

10095
        if (dom->os.type == VIR_DOMAIN_OSTYPE_HVM) {
L
Li Zhang 已提交
10096 10097 10098
            if (def->bus == VIR_DOMAIN_INPUT_BUS_PS2 &&
                def->type != VIR_DOMAIN_INPUT_TYPE_MOUSE &&
                def->type != VIR_DOMAIN_INPUT_TYPE_KBD) {
10099 10100 10101
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("ps2 bus does not support %s input device"),
                               type);
10102 10103 10104
                goto error;
            }
            if (def->bus == VIR_DOMAIN_INPUT_BUS_XEN) {
10105 10106 10107
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unsupported input bus %s"),
                               bus);
10108 10109
                goto error;
            }
10110
        } else if (dom->os.type == VIR_DOMAIN_OSTYPE_XEN) {
10111
            if (def->bus != VIR_DOMAIN_INPUT_BUS_XEN) {
10112 10113 10114
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unsupported input bus %s"),
                               bus);
10115
                goto error;
10116
            }
L
Li Zhang 已提交
10117 10118
            if (def->type != VIR_DOMAIN_INPUT_TYPE_MOUSE &&
                def->type != VIR_DOMAIN_INPUT_TYPE_KBD) {
10119 10120 10121
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("xen bus does not support %s input device"),
                               type);
10122 10123
                goto error;
            }
10124
        } else {
10125 10126
            if (dom->virtType == VIR_DOMAIN_VIRT_VZ ||
                dom->virtType == VIR_DOMAIN_VIRT_PARALLELS) {
10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148
                if (def->bus != VIR_DOMAIN_INPUT_BUS_PARALLELS) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("parallels containers don't support "
                                     "input bus %s"),
                                   bus);
                    goto error;
                }

                if (def->type != VIR_DOMAIN_INPUT_TYPE_MOUSE &&
                    def->type != VIR_DOMAIN_INPUT_TYPE_KBD) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("parallels bus does not support "
                                     "%s input device"),
                                   type);
                    goto error;
                }
            } else {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Input devices are not supported by this "
                                 "virtualization driver."));
                goto error;
            }
10149 10150
        }
    } else {
10151
        if (dom->os.type == VIR_DOMAIN_OSTYPE_HVM) {
L
Li Zhang 已提交
10152
            if ((def->type == VIR_DOMAIN_INPUT_TYPE_MOUSE ||
10153 10154
                def->type == VIR_DOMAIN_INPUT_TYPE_KBD) &&
                (ARCH_IS_X86(dom->os.arch) || dom->os.arch == VIR_ARCH_NONE)) {
10155
                def->bus = VIR_DOMAIN_INPUT_BUS_PS2;
10156
            } else {
10157
                def->bus = VIR_DOMAIN_INPUT_BUS_USB;
10158
            }
10159
        } else if (dom->os.type == VIR_DOMAIN_OSTYPE_XEN) {
10160
            def->bus = VIR_DOMAIN_INPUT_BUS_XEN;
10161
        } else {
10162 10163
            if ((dom->virtType == VIR_DOMAIN_VIRT_VZ ||
                 dom->virtType == VIR_DOMAIN_VIRT_PARALLELS))
10164
                def->bus = VIR_DOMAIN_INPUT_BUS_PARALLELS;
10165 10166 10167
        }
    }

10168
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
10169 10170
        goto error;

10171 10172 10173
    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) {
10174 10175
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Invalid address for a USB device"));
10176 10177 10178
        goto error;
    }

10179 10180 10181 10182 10183 10184 10185 10186
    if ((evdev = virXPathString("string(./source/@evdev)", ctxt)))
        def->source.evdev = virFileSanitizePath(evdev);
    if (def->type == VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH && !def->source.evdev) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Missing evdev path for input device passthrough"));
        goto error;
    }

10187
 cleanup:
10188
    VIR_FREE(evdev);
10189 10190 10191
    VIR_FREE(type);
    VIR_FREE(bus);

10192
    ctxt->node = save;
10193 10194
    return def;

10195
 error:
10196 10197 10198 10199 10200 10201
    virDomainInputDefFree(def);
    def = NULL;
    goto cleanup;
}


E
Eric Blake 已提交
10202
/* Parse the XML definition for a hub device */
M
Marc-André Lureau 已提交
10203 10204 10205 10206 10207 10208
static virDomainHubDefPtr
virDomainHubDefParseXML(xmlNodePtr node, unsigned int flags)
{
    virDomainHubDefPtr def;
    char *type = NULL;

10209
    if (VIR_ALLOC(def) < 0)
M
Marc-André Lureau 已提交
10210 10211 10212 10213 10214
        return NULL;

    type = virXMLPropString(node, "type");

    if (!type) {
10215 10216
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing hub device type"));
M
Marc-André Lureau 已提交
10217 10218 10219 10220
        goto error;
    }

    if ((def->type = virDomainHubTypeFromString(type)) < 0) {
10221
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10222
                       _("unknown hub device type '%s'"), type);
M
Marc-André Lureau 已提交
10223 10224 10225
        goto error;
    }

10226
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
M
Marc-André Lureau 已提交
10227 10228
        goto error;

10229
 cleanup:
M
Marc-André Lureau 已提交
10230 10231 10232 10233
    VIR_FREE(type);

    return def;

10234
 error:
M
Marc-André Lureau 已提交
10235 10236 10237 10238 10239 10240
    virDomainHubDefFree(def);
    def = NULL;
    goto cleanup;
}


10241 10242
/* Parse the XML definition for a clock timer */
static virDomainTimerDefPtr
10243
virDomainTimerDefParseXML(xmlNodePtr node,
E
Eric Blake 已提交
10244
                          xmlXPathContextPtr ctxt)
10245 10246 10247 10248
{
    char *name = NULL;
    char *present = NULL;
    char *tickpolicy = NULL;
10249
    char *track = NULL;
10250 10251 10252 10253
    char *mode = NULL;

    virDomainTimerDefPtr def;
    xmlNodePtr oldnode = ctxt->node;
10254 10255
    xmlNodePtr catchup;
    int ret;
10256

10257
    if (VIR_ALLOC(def) < 0)
10258 10259 10260 10261 10262 10263
        return NULL;

    ctxt->node = node;

    name = virXMLPropString(node, "name");
    if (name == NULL) {
10264 10265
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing timer name"));
10266 10267 10268
        goto error;
    }
    if ((def->name = virDomainTimerNameTypeFromString(name)) < 0) {
10269
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10270
                       _("unknown timer name '%s'"), name);
10271 10272 10273 10274 10275 10276 10277 10278 10279 10280
        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 {
10281 10282
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown timer present value '%s'"), present);
10283 10284 10285 10286 10287 10288 10289 10290
            goto error;
        }
    }

    def->tickpolicy = -1;
    tickpolicy = virXMLPropString(node, "tickpolicy");
    if (tickpolicy != NULL) {
        if ((def->tickpolicy = virDomainTimerTickpolicyTypeFromString(tickpolicy)) < 0) {
10291
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10292
                           _("unknown timer tickpolicy '%s'"), tickpolicy);
10293 10294 10295 10296
            goto error;
        }
    }

10297 10298 10299 10300
    def->track = -1;
    track = virXMLPropString(node, "track");
    if (track != NULL) {
        if ((def->track = virDomainTimerTrackTypeFromString(track)) < 0) {
10301
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10302
                           _("unknown timer track '%s'"), track);
10303 10304 10305 10306
            goto error;
        }
    }

10307
    ret = virXPathULong("string(./frequency)", ctxt, &def->frequency);
10308 10309
    if (ret == -1) {
        def->frequency = 0;
10310
    } else if (ret < 0) {
10311 10312
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("invalid timer frequency"));
10313 10314 10315 10316 10317 10318 10319
        goto error;
    }

    def->mode = -1;
    mode = virXMLPropString(node, "mode");
    if (mode != NULL) {
        if ((def->mode = virDomainTimerModeTypeFromString(mode)) < 0) {
10320
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10321
                           _("unknown timer mode '%s'"), mode);
10322 10323 10324 10325
            goto error;
        }
    }

10326
    catchup = virXPathNode("./catchup", ctxt);
10327 10328 10329 10330 10331 10332
    if (catchup != NULL) {
        ret = virXPathULong("string(./catchup/@threshold)", ctxt,
                            &def->catchup.threshold);
        if (ret == -1) {
            def->catchup.threshold = 0;
        } else if (ret < 0) {
10333 10334
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("invalid catchup threshold"));
10335 10336 10337 10338 10339 10340 10341
            goto error;
        }

        ret = virXPathULong("string(./catchup/@slew)", ctxt, &def->catchup.slew);
        if (ret == -1) {
            def->catchup.slew = 0;
        } else if (ret < 0) {
10342 10343
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("invalid catchup slew"));
10344 10345 10346 10347 10348 10349 10350
            goto error;
        }

        ret = virXPathULong("string(./catchup/@limit)", ctxt, &def->catchup.limit);
        if (ret == -1) {
            def->catchup.limit = 0;
        } else if (ret < 0) {
10351 10352
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("invalid catchup limit"));
10353 10354 10355 10356
            goto error;
        }
    }

10357
 cleanup:
10358 10359 10360
    VIR_FREE(name);
    VIR_FREE(present);
    VIR_FREE(tickpolicy);
10361
    VIR_FREE(track);
10362 10363 10364 10365 10366
    VIR_FREE(mode);
    ctxt->node = oldnode;

    return def;

10367
 error:
10368 10369 10370 10371
    VIR_FREE(def);
    goto cleanup;
}

10372 10373

static int
10374 10375 10376
virDomainGraphicsAuthDefParseXML(xmlNodePtr node,
                                 virDomainGraphicsAuthDefPtr def,
                                 int type)
10377 10378
{
    char *validTo = NULL;
10379
    char *connected = virXMLPropString(node, "connected");
10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403

    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') {
10404 10405 10406
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot parse password validity time '%s', expect YYYY-MM-DDTHH:MM:SS"),
                           validTo);
10407 10408 10409 10410 10411 10412 10413 10414 10415 10416
            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);
10417
        def->expires = true;
10418 10419
    }

10420 10421 10422
    if (connected) {
        int action = virDomainGraphicsAuthConnectedTypeFromString(connected);
        if (action <= 0) {
10423 10424 10425
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown connected value %s"),
                           connected);
10426 10427 10428 10429 10430 10431 10432 10433
            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) {
10434 10435
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("VNC supports connected='keep' only"));
10436 10437 10438 10439 10440 10441
            return -1;
        }

        def->connected = action;
    }

10442 10443 10444
    return 0;
}

10445 10446 10447 10448 10449 10450 10451 10452 10453
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");
10454 10455
    char *fromConfig = virXMLPropString(node, "fromConfig");
    int tmp;
10456 10457

    if (!type) {
10458 10459
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("graphics listen type must be specified"));
10460 10461 10462 10463
        goto error;
    }

    if ((def->type = virDomainGraphicsListenTypeFromString(type)) < 0) {
10464
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10465
                       _("unknown graphics listen type '%s'"), type);
10466 10467 10468 10469 10470 10471 10472
        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 已提交
10473 10474
        (def->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS ||
         (def->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK &&
10475
          !(flags & VIR_DOMAIN_DEF_PARSE_INACTIVE)))) {
10476 10477 10478 10479 10480 10481 10482
        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
10483
             * type='network' */
10484 10485
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("network attribute not allowed when listen type is not network"));
10486 10487 10488 10489 10490 10491
            goto error;
        }
        def->network = network;
        network = NULL;
    }

10492
    if (fromConfig &&
10493
        flags & VIR_DOMAIN_DEF_PARSE_STATUS) {
10494 10495 10496 10497 10498 10499 10500 10501 10502
        if (virStrToLong_i(fromConfig, NULL, 10, &tmp) < 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid fromConfig value: %s"),
                           fromConfig);
            goto error;
        }
        def->fromConfig = tmp != 0;
    }

10503
    ret = 0;
10504
 error:
10505 10506 10507 10508 10509
    if (ret < 0)
        virDomainGraphicsListenDefClear(def);
    VIR_FREE(type);
    VIR_FREE(address);
    VIR_FREE(network);
10510
    VIR_FREE(fromConfig);
10511 10512 10513
    return ret;
}

10514

10515 10516
/* Parse the XML definition for a graphics device */
static virDomainGraphicsDefPtr
10517 10518 10519
virDomainGraphicsDefParseXML(xmlNodePtr node,
                             xmlXPathContextPtr ctxt,
                             unsigned int flags)
E
Eric Blake 已提交
10520
{
10521 10522
    virDomainGraphicsDefPtr def;
    char *type = NULL;
10523 10524 10525 10526
    int nListens;
    xmlNodePtr *listenNodes = NULL;
    char *listenAddr = NULL;
    xmlNodePtr save = ctxt->node;
10527

10528
    if (VIR_ALLOC(def) < 0)
10529 10530
        return NULL;

10531 10532
    ctxt->node = node;

10533 10534 10535
    type = virXMLPropString(node, "type");

    if (!type) {
10536 10537
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing graphics device type"));
10538 10539 10540 10541
        goto error;
    }

    if ((def->type = virDomainGraphicsTypeFromString(type)) < 0) {
10542
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10543
                       _("unknown graphics device type '%s'"), type);
10544 10545 10546
        goto error;
    }

E
Eric Blake 已提交
10547 10548 10549
    if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC ||
        def->type == VIR_DOMAIN_GRAPHICS_TYPE_RDP ||
        def->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE) {
10550 10551 10552 10553 10554 10555 10556

        /* parse the <listen> subelements for graphics types that support it */
        nListens = virXPathNodeSet("./listen", ctxt, &listenNodes);
        if (nListens < 0)
            goto error;

        if (nListens > 0) {
10557
            size_t i;
10558

10559
            if (VIR_ALLOC_N(def->listens, nListens) < 0)
10560 10561
                goto error;

10562 10563 10564
            for (i = 0; i < nListens; i++) {
                int ret = virDomainGraphicsListenDefParseXML(&def->listens[i],
                                                             listenNodes[i],
10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593
                                                             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;
10594
                size_t i;
10595

10596 10597
                for (i = 0; i < nListens; i++) {
                    if (virDomainGraphicsListenGetType(def, i)
10598
                        == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS) {
10599
                        found = virDomainGraphicsListenGetAddress(def, i);
10600
                        if (STREQ_NULLABLE(found, listenAddr))
10601 10602 10603 10604
                            matched = true;
                        break;
                    }
                }
10605
                if (found && !matched) {
10606 10607 10608
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("graphics listen attribute %s must match address "
                                     "attribute of first listen element (found %s)"),
10609
                                   listenAddr, found);
10610
                    goto error;
10611 10612 10613 10614
                } else if (!found) {
                    /* quietly ignore listen address if none of the listens
                     * are of type address */
                    VIR_FREE(listenAddr);
10615 10616 10617 10618 10619
                }
            }
        }
    }

10620 10621
    if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC) {
        char *port = virXMLPropString(node, "port");
M
Martin Kletzander 已提交
10622
        char *websocket = virXMLPropString(node, "websocket");
10623
        char *sharePolicy = virXMLPropString(node, "sharePolicy");
10624 10625 10626 10627
        char *autoport;

        if (port) {
            if (virStrToLong_i(port, NULL, 10, &def->data.vnc.port) < 0) {
10628 10629
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("cannot parse vnc port %s"), port);
10630 10631 10632 10633 10634 10635
                VIR_FREE(port);
                goto error;
            }
            VIR_FREE(port);
            /* Legacy compat syntax, used -1 for auto-port */
            if (def->data.vnc.port == -1) {
10636
                if (flags & VIR_DOMAIN_DEF_PARSE_INACTIVE)
10637
                    def->data.vnc.port = 0;
10638
                def->data.vnc.autoport = true;
10639 10640 10641
            }
        } else {
            def->data.vnc.port = 0;
10642
            def->data.vnc.autoport = true;
10643 10644 10645 10646
        }

        if ((autoport = virXMLPropString(node, "autoport")) != NULL) {
            if (STREQ(autoport, "yes")) {
10647
                if (flags & VIR_DOMAIN_DEF_PARSE_INACTIVE)
10648
                    def->data.vnc.port = 0;
10649
                def->data.vnc.autoport = true;
10650 10651 10652 10653
            }
            VIR_FREE(autoport);
        }

M
Martin Kletzander 已提交
10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665
        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);
        }

10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680
        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);
        }

10681
        def->data.vnc.socket = virXMLPropString(node, "socket");
10682
        def->data.vnc.keymap = virXMLPropString(node, "keymap");
10683

10684 10685
        if (virDomainGraphicsAuthDefParseXML(node, &def->data.vnc.auth,
                                             def->type) < 0)
10686
            goto error;
10687
    } else if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL) {
10688 10689 10690 10691
        char *fullscreen = virXMLPropString(node, "fullscreen");

        if (fullscreen != NULL) {
            if (STREQ(fullscreen, "yes")) {
10692
                def->data.sdl.fullscreen = true;
10693
            } else if (STREQ(fullscreen, "no")) {
10694
                def->data.sdl.fullscreen = false;
10695
            } else {
10696 10697
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unknown fullscreen value '%s'"), fullscreen);
10698 10699 10700 10701
                VIR_FREE(fullscreen);
                goto error;
            }
            VIR_FREE(fullscreen);
E
Eric Blake 已提交
10702
        } else {
10703
            def->data.sdl.fullscreen = false;
E
Eric Blake 已提交
10704
        }
10705 10706
        def->data.sdl.xauth = virXMLPropString(node, "xauth");
        def->data.sdl.display = virXMLPropString(node, "display");
10707 10708 10709 10710 10711 10712 10713 10714
    } 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) {
10715 10716
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("cannot parse rdp port %s"), port);
10717 10718 10719
                VIR_FREE(port);
                goto error;
            }
M
Michal Privoznik 已提交
10720 10721
            /* Legacy compat syntax, used -1 for auto-port */
            if (def->data.rdp.port == -1)
10722
                def->data.rdp.autoport = true;
M
Michal Privoznik 已提交
10723

10724 10725 10726
            VIR_FREE(port);
        } else {
            def->data.rdp.port = 0;
10727
            def->data.rdp.autoport = true;
10728 10729 10730
        }

        if ((autoport = virXMLPropString(node, "autoport")) != NULL) {
M
Michal Privoznik 已提交
10731
            if (STREQ(autoport, "yes"))
10732
                def->data.rdp.autoport = true;
M
Michal Privoznik 已提交
10733

10734 10735 10736
            VIR_FREE(autoport);
        }

10737
        if (def->data.rdp.autoport && (flags & VIR_DOMAIN_DEF_PARSE_INACTIVE))
M
Michal Privoznik 已提交
10738 10739
            def->data.rdp.port = 0;

10740
        if ((replaceUser = virXMLPropString(node, "replaceUser")) != NULL) {
10741
            if (STREQ(replaceUser, "yes"))
10742
                def->data.rdp.replaceUser = true;
10743 10744 10745 10746
            VIR_FREE(replaceUser);
        }

        if ((multiUser = virXMLPropString(node, "multiUser")) != NULL) {
10747
            if (STREQ(multiUser, "yes"))
10748
                def->data.rdp.multiUser = true;
10749 10750 10751 10752 10753 10754 10755 10756
            VIR_FREE(multiUser);
        }

    } else if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP) {
        char *fullscreen = virXMLPropString(node, "fullscreen");

        if (fullscreen != NULL) {
            if (STREQ(fullscreen, "yes")) {
10757
                def->data.desktop.fullscreen = true;
10758
            } else if (STREQ(fullscreen, "no")) {
10759
                def->data.desktop.fullscreen = false;
10760
            } else {
10761 10762
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unknown fullscreen value '%s'"), fullscreen);
10763 10764 10765 10766
                VIR_FREE(fullscreen);
                goto error;
            }
            VIR_FREE(fullscreen);
E
Eric Blake 已提交
10767
        } else {
10768
            def->data.desktop.fullscreen = false;
E
Eric Blake 已提交
10769
        }
10770 10771

        def->data.desktop.display = virXMLPropString(node, "display");
10772
    } else if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE) {
10773
        xmlNodePtr cur;
10774 10775 10776
        char *port = virXMLPropString(node, "port");
        char *tlsPort;
        char *autoport;
10777 10778
        char *defaultMode;
        int defaultModeVal;
10779 10780 10781

        if (port) {
            if (virStrToLong_i(port, NULL, 10, &def->data.spice.port) < 0) {
10782 10783
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("cannot parse spice port %s"), port);
10784 10785 10786 10787 10788
                VIR_FREE(port);
                goto error;
            }
            VIR_FREE(port);
        } else {
10789
            def->data.spice.port = 0;
10790 10791 10792 10793 10794
        }

        tlsPort = virXMLPropString(node, "tlsPort");
        if (tlsPort) {
            if (virStrToLong_i(tlsPort, NULL, 10, &def->data.spice.tlsPort) < 0) {
10795 10796
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("cannot parse spice tlsPort %s"), tlsPort);
10797 10798 10799 10800 10801 10802 10803 10804 10805
                VIR_FREE(tlsPort);
                goto error;
            }
            VIR_FREE(tlsPort);
        } else {
            def->data.spice.tlsPort = 0;
        }

        if ((autoport = virXMLPropString(node, "autoport")) != NULL) {
M
Michal Privoznik 已提交
10806
            if (STREQ(autoport, "yes"))
10807
                def->data.spice.autoport = true;
10808 10809 10810
            VIR_FREE(autoport);
        }

10811 10812 10813 10814
        def->data.spice.defaultMode = VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_ANY;

        if ((defaultMode = virXMLPropString(node, "defaultMode")) != NULL) {
            if ((defaultModeVal = virDomainGraphicsSpiceChannelModeTypeFromString(defaultMode)) < 0) {
10815
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10816 10817
                               _("unknown default spice channel mode %s"),
                               defaultMode);
10818 10819 10820 10821 10822 10823 10824
                VIR_FREE(defaultMode);
                goto error;
            }
            def->data.spice.defaultMode = defaultModeVal;
            VIR_FREE(defaultMode);
        }

M
Michal Privoznik 已提交
10825 10826
        if (def->data.spice.port == -1 && def->data.spice.tlsPort == -1) {
            /* Legacy compat syntax, used -1 for auto-port */
10827
            def->data.spice.autoport = true;
M
Michal Privoznik 已提交
10828 10829
        }

10830
        if (def->data.spice.autoport && (flags & VIR_DOMAIN_DEF_PARSE_INACTIVE)) {
M
Michal Privoznik 已提交
10831 10832 10833 10834
            def->data.spice.port = 0;
            def->data.spice.tlsPort = 0;
        }

10835
        def->data.spice.keymap = virXMLPropString(node, "keymap");
10836

10837 10838
        if (virDomainGraphicsAuthDefParseXML(node, &def->data.spice.auth,
                                             def->type) < 0)
10839
            goto error;
10840 10841 10842 10843 10844

        cur = node->children;
        while (cur != NULL) {
            if (cur->type == XML_ELEMENT_NODE) {
                if (xmlStrEqual(cur->name, BAD_CAST "channel")) {
10845
                    char *name, *mode;
10846 10847 10848 10849 10850
                    int nameval, modeval;
                    name = virXMLPropString(cur, "name");
                    mode = virXMLPropString(cur, "mode");

                    if (!name || !mode) {
10851 10852
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("spice channel missing name/mode"));
E
Eric Blake 已提交
10853 10854
                        VIR_FREE(name);
                        VIR_FREE(mode);
10855 10856 10857 10858
                        goto error;
                    }

                    if ((nameval = virDomainGraphicsSpiceChannelNameTypeFromString(name)) < 0) {
10859
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10860 10861
                                       _("unknown spice channel name %s"),
                                       name);
E
Eric Blake 已提交
10862 10863
                        VIR_FREE(name);
                        VIR_FREE(mode);
10864 10865 10866
                        goto error;
                    }
                    if ((modeval = virDomainGraphicsSpiceChannelModeTypeFromString(mode)) < 0) {
10867
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10868 10869
                                       _("unknown spice channel mode %s"),
                                       mode);
E
Eric Blake 已提交
10870 10871
                        VIR_FREE(name);
                        VIR_FREE(mode);
10872 10873
                        goto error;
                    }
E
Eric Blake 已提交
10874 10875
                    VIR_FREE(name);
                    VIR_FREE(mode);
10876 10877

                    def->data.spice.channels[nameval] = modeval;
10878
                } else if (xmlStrEqual(cur->name, BAD_CAST "image")) {
10879
                    char *compression = virXMLPropString(cur, "compression");
10880 10881 10882
                    int compressionVal;

                    if (!compression) {
10883 10884
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("spice image missing compression"));
10885 10886 10887 10888 10889
                        goto error;
                    }

                    if ((compressionVal =
                         virDomainGraphicsSpiceImageCompressionTypeFromString(compression)) <= 0) {
10890 10891 10892
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                       _("unknown spice image compression %s"),
                                       compression);
10893 10894 10895 10896 10897 10898 10899
                        VIR_FREE(compression);
                        goto error;
                    }
                    VIR_FREE(compression);

                    def->data.spice.image = compressionVal;
                } else if (xmlStrEqual(cur->name, BAD_CAST "jpeg")) {
10900
                    char *compression = virXMLPropString(cur, "compression");
10901 10902 10903
                    int compressionVal;

                    if (!compression) {
10904 10905
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("spice jpeg missing compression"));
10906 10907 10908 10909 10910
                        goto error;
                    }

                    if ((compressionVal =
                         virDomainGraphicsSpiceJpegCompressionTypeFromString(compression)) <= 0) {
10911 10912 10913
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                       _("unknown spice jpeg compression %s"),
                                       compression);
10914 10915 10916 10917 10918 10919 10920
                        VIR_FREE(compression);
                        goto error;
                    }
                    VIR_FREE(compression);

                    def->data.spice.jpeg = compressionVal;
                } else if (xmlStrEqual(cur->name, BAD_CAST "zlib")) {
10921
                    char *compression = virXMLPropString(cur, "compression");
10922 10923 10924
                    int compressionVal;

                    if (!compression) {
10925 10926
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("spice zlib missing compression"));
10927 10928 10929 10930 10931
                        goto error;
                    }

                    if ((compressionVal =
                         virDomainGraphicsSpiceZlibCompressionTypeFromString(compression)) <= 0) {
10932 10933 10934
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                       _("unknown spice zlib compression %s"),
                                       compression);
10935 10936 10937
                        VIR_FREE(compression);
                        goto error;
                    }
10938
                    VIR_FREE(compression);
10939 10940 10941

                    def->data.spice.zlib = compressionVal;
                } else if (xmlStrEqual(cur->name, BAD_CAST "playback")) {
10942
                    char *compression = virXMLPropString(cur, "compression");
10943 10944 10945
                    int compressionVal;

                    if (!compression) {
10946 10947
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("spice playback missing compression"));
10948 10949 10950 10951
                        goto error;
                    }

                    if ((compressionVal =
J
Ján Tomko 已提交
10952
                         virTristateSwitchTypeFromString(compression)) <= 0) {
10953
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10954
                                       _("unknown spice playback compression"));
10955 10956 10957 10958 10959 10960 10961
                        VIR_FREE(compression);
                        goto error;

                    }
                    VIR_FREE(compression);

                    def->data.spice.playback = compressionVal;
10962
                } else if (xmlStrEqual(cur->name, BAD_CAST "streaming")) {
10963
                    char *mode = virXMLPropString(cur, "mode");
10964 10965 10966
                    int modeVal;

                    if (!mode) {
10967 10968
                        virReportError(VIR_ERR_XML_ERROR, "%s",
                                       _("spice streaming missing mode"));
10969 10970 10971 10972
                        goto error;
                    }
                    if ((modeVal =
                         virDomainGraphicsSpiceStreamingModeTypeFromString(mode)) <= 0) {
10973
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
10974
                                       _("unknown spice streaming mode"));
10975 10976 10977 10978 10979 10980 10981
                        VIR_FREE(mode);
                        goto error;

                    }
                    VIR_FREE(mode);

                    def->data.spice.streaming = modeVal;
10982
                } else if (xmlStrEqual(cur->name, BAD_CAST "clipboard")) {
10983
                    char *copypaste = virXMLPropString(cur, "copypaste");
10984 10985 10986
                    int copypasteVal;

                    if (!copypaste) {
10987 10988
                        virReportError(VIR_ERR_XML_ERROR, "%s",
                                       _("spice clipboard missing copypaste"));
10989 10990 10991 10992
                        goto error;
                    }

                    if ((copypasteVal =
J
Ján Tomko 已提交
10993
                         virTristateBoolTypeFromString(copypaste)) <= 0) {
10994
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
10995
                                       _("unknown copypaste value '%s'"), copypaste);
10996 10997 10998 10999 11000 11001
                        VIR_FREE(copypaste);
                        goto error;
                    }
                    VIR_FREE(copypaste);

                    def->data.spice.copypaste = copypasteVal;
11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012
                } 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 已提交
11013
                         virTristateBoolTypeFromString(enable)) <= 0) {
11014 11015 11016 11017 11018 11019 11020 11021
                        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 已提交
11022
                } else if (xmlStrEqual(cur->name, BAD_CAST "mouse")) {
11023
                    char *mode = virXMLPropString(cur, "mode");
P
Peng Zhou 已提交
11024 11025 11026
                    int modeVal;

                    if (!mode) {
11027 11028
                        virReportError(VIR_ERR_XML_ERROR, "%s",
                                       _("spice mouse missing mode"));
P
Peng Zhou 已提交
11029 11030 11031 11032
                        goto error;
                    }

                    if ((modeVal = virDomainGraphicsSpiceMouseModeTypeFromString(mode)) <= 0) {
11033
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11034 11035
                                       _("unknown mouse mode value '%s'"),
                                       mode);
P
Peng Zhou 已提交
11036 11037 11038 11039 11040 11041
                        VIR_FREE(mode);
                        goto error;
                    }
                    VIR_FREE(mode);

                    def->data.spice.mousemode = modeVal;
11042 11043 11044 11045
                }
            }
            cur = cur->next;
        }
11046 11047
    }

11048
 cleanup:
11049
    VIR_FREE(type);
11050 11051
    VIR_FREE(listenNodes);
    VIR_FREE(listenAddr);
11052

11053
    ctxt->node = save;
11054 11055
    return def;

11056
 error:
11057 11058 11059 11060 11061 11062
    virDomainGraphicsDefFree(def);
    def = NULL;
    goto cleanup;
}


11063
static virDomainSoundCodecDefPtr
11064
virDomainSoundCodecDefParseXML(xmlNodePtr node)
11065 11066 11067 11068
{
    char *type;
    virDomainSoundCodecDefPtr def;

11069
    if (VIR_ALLOC(def) < 0)
11070 11071 11072 11073
        return NULL;

    type = virXMLPropString(node, "type");
    if ((def->type = virDomainSoundCodecTypeFromString(type)) < 0) {
11074
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11075
                       _("unknown codec type '%s'"), type);
11076 11077 11078
        goto error;
    }

11079
 cleanup:
11080 11081 11082 11083
    VIR_FREE(type);

    return def;

11084
 error:
11085 11086 11087 11088 11089 11090
    virDomainSoundCodecDefFree(def);
    def = NULL;
    goto cleanup;
}


11091
static virDomainSoundDefPtr
11092
virDomainSoundDefParseXML(xmlNodePtr node,
11093
                          xmlXPathContextPtr ctxt,
E
Eric Blake 已提交
11094
                          unsigned int flags)
11095
{
11096 11097
    char *model;
    virDomainSoundDefPtr def;
11098
    xmlNodePtr save = ctxt->node;
11099

11100
    if (VIR_ALLOC(def) < 0)
11101 11102
        return NULL;

11103 11104
    ctxt->node = node;

11105 11106
    model = virXMLPropString(node, "model");
    if ((def->model = virDomainSoundModelTypeFromString(model)) < 0) {
11107
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11108
                       _("unknown sound model '%s'"), model);
11109 11110 11111
        goto error;
    }

11112 11113
    if (def->model == VIR_DOMAIN_SOUND_MODEL_ICH6 ||
        def->model == VIR_DOMAIN_SOUND_MODEL_ICH9) {
11114 11115 11116 11117 11118 11119 11120 11121 11122
        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) {
11123
            size_t i;
11124 11125 11126 11127 11128 11129

            if (VIR_ALLOC_N(def->codecs, ncodecs) < 0) {
                VIR_FREE(codecNodes);
                goto error;
            }

11130 11131
            for (i = 0; i < ncodecs; i++) {
                virDomainSoundCodecDefPtr codec = virDomainSoundCodecDefParseXML(codecNodes[i]);
11132 11133
                if (codec == NULL) {
                    VIR_FREE(codecNodes);
11134
                    goto error;
11135
                }
11136 11137 11138 11139 11140 11141 11142 11143

                codec->cad = def->ncodecs; /* that will do for now */
                def->codecs[def->ncodecs++] = codec;
            }
            VIR_FREE(codecNodes);
        }
    }

11144
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
11145 11146
        goto error;

11147
 cleanup:
11148 11149
    VIR_FREE(model);

11150
    ctxt->node = save;
11151 11152
    return def;

11153
 error:
11154 11155 11156 11157 11158
    virDomainSoundDefFree(def);
    def = NULL;
    goto cleanup;
}

11159

R
Richard Jones 已提交
11160
static virDomainWatchdogDefPtr
11161
virDomainWatchdogDefParseXML(xmlNodePtr node,
E
Eric Blake 已提交
11162
                             unsigned int flags)
11163
{
R
Richard Jones 已提交
11164 11165 11166 11167 11168

    char *model = NULL;
    char *action = NULL;
    virDomainWatchdogDefPtr def;

11169
    if (VIR_ALLOC(def) < 0)
R
Richard Jones 已提交
11170 11171
        return NULL;

11172
    model = virXMLPropString(node, "model");
R
Richard Jones 已提交
11173
    if (model == NULL) {
11174 11175
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("watchdog must contain model name"));
R
Richard Jones 已提交
11176 11177
        goto error;
    }
11178
    def->model = virDomainWatchdogModelTypeFromString(model);
R
Richard Jones 已提交
11179
    if (def->model < 0) {
11180
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11181
                       _("unknown watchdog model '%s'"), model);
R
Richard Jones 已提交
11182 11183 11184
        goto error;
    }

11185
    action = virXMLPropString(node, "action");
11186
    if (action == NULL) {
R
Richard Jones 已提交
11187
        def->action = VIR_DOMAIN_WATCHDOG_ACTION_RESET;
11188
    } else {
11189
        def->action = virDomainWatchdogActionTypeFromString(action);
R
Richard Jones 已提交
11190
        if (def->action < 0) {
11191
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11192
                           _("unknown watchdog action '%s'"), action);
R
Richard Jones 已提交
11193 11194 11195 11196
            goto error;
        }
    }

11197
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
11198 11199
        goto error;

11200
 cleanup:
11201 11202
    VIR_FREE(action);
    VIR_FREE(model);
R
Richard Jones 已提交
11203 11204 11205

    return def;

11206
 error:
11207
    virDomainWatchdogDefFree(def);
R
Richard Jones 已提交
11208 11209 11210 11211 11212
    def = NULL;
    goto cleanup;
}


11213
static virDomainRNGDefPtr
11214
virDomainRNGDefParseXML(xmlNodePtr node,
11215 11216 11217
                        xmlXPathContextPtr ctxt,
                        unsigned int flags)
{
11218 11219 11220
    char *model = NULL;
    char *backend = NULL;
    char *type = NULL;
11221 11222 11223 11224 11225
    virDomainRNGDefPtr def;
    xmlNodePtr save = ctxt->node;
    xmlNodePtr *backends = NULL;
    int nbackends;

11226
    if (VIR_ALLOC(def) < 0)
11227 11228 11229 11230 11231 11232 11233 11234
        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) {
11235
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, _("unknown RNG model '%s'"), model);
11236 11237 11238 11239 11240
        goto error;
    }

    ctxt->node = node;

11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253
    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;
    }

11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269
    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) {
11270
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11271 11272 11273 11274
                       _("unknown RNG backend model '%s'"), backend);
        goto error;
    }

11275
    switch ((virDomainRNGBackend) def->backend) {
11276 11277
    case VIR_DOMAIN_RNG_BACKEND_RANDOM:
        def->source.file = virXPathString("string(./backend)", ctxt);
11278 11279
        if (def->source.file &&
            STRNEQ(def->source.file, "/dev/random") &&
11280 11281 11282 11283 11284 11285
            STRNEQ(def->source.file, "/dev/hwrng")) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("file '%s' is not a supported random source"),
                           def->source.file);
            goto error;
        }
11286 11287 11288 11289 11290 11291 11292 11293 11294
        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;
        }

11295
        if (VIR_ALLOC(def->source.chardev) < 0)
11296 11297 11298 11299
            goto error;

        def->source.chardev->type = virDomainChrTypeFromString(type);
        if (def->source.chardev->type < 0) {
11300
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318
                           _("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;

11319
 cleanup:
11320 11321 11322 11323 11324 11325 11326
    VIR_FREE(model);
    VIR_FREE(backend);
    VIR_FREE(type);
    VIR_FREE(backends);
    ctxt->node = save;
    return def;

11327
 error:
11328 11329 11330 11331 11332 11333
    virDomainRNGDefFree(def);
    def = NULL;
    goto cleanup;
}


11334
static virDomainMemballoonDefPtr
11335
virDomainMemballoonDefParseXML(xmlNodePtr node,
11336
                               xmlXPathContextPtr ctxt,
E
Eric Blake 已提交
11337
                               unsigned int flags)
11338 11339
{
    char *model;
11340
    char *deflate = NULL;
11341
    virDomainMemballoonDefPtr def;
11342
    xmlNodePtr save = ctxt->node;
11343
    unsigned int period = 0;
11344

11345
    if (VIR_ALLOC(def) < 0)
11346 11347 11348
        return NULL;

    model = virXMLPropString(node, "model");
11349
    if (model == NULL) {
11350
        virReportError(VIR_ERR_XML_ERROR, "%s",
11351
                       _("balloon memory must contain model name"));
11352 11353
        goto error;
    }
11354

11355
    if ((def->model = virDomainMemballoonModelTypeFromString(model)) < 0) {
11356
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11357
                       _("unknown memory balloon model '%s'"), model);
11358 11359 11360
        goto error;
    }

11361 11362 11363 11364 11365 11366 11367
    if ((deflate = virXMLPropString(node, "autodeflate")) &&
        (def->autodeflate = virTristateSwitchTypeFromString(deflate)) <= 0) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("invalid autodeflate attribute value '%s'"), deflate);
        goto error;
    }

11368
    ctxt->node = node;
11369
    if (virXPathUInt("string(./stats/@period)", ctxt, &period) < -1) {
11370 11371 11372 11373 11374
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("invalid statistics collection period"));
        goto error;
    }

11375 11376 11377 11378
    def->period = period;
    if (def->period < 0)
        def->period = 0;

11379 11380 11381
    if (def->model == VIR_DOMAIN_MEMBALLOON_MODEL_NONE)
        VIR_DEBUG("Ignoring device address for none model Memballoon");
    else if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
11382 11383
        goto error;

11384
 cleanup:
11385
    VIR_FREE(model);
11386
    VIR_FREE(deflate);
11387

11388
    ctxt->node = save;
11389 11390
    return def;

11391
 error:
11392 11393 11394 11395 11396
    virDomainMemballoonDefFree(def);
    def = NULL;
    goto cleanup;
}

L
Li Zhang 已提交
11397
static virDomainNVRAMDefPtr
11398
virDomainNVRAMDefParseXML(xmlNodePtr node,
L
Li Zhang 已提交
11399 11400 11401 11402
                          unsigned int flags)
{
   virDomainNVRAMDefPtr def;

11403
    if (VIR_ALLOC(def) < 0)
L
Li Zhang 已提交
11404 11405 11406 11407 11408 11409 11410
        return NULL;

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

    return def;

11411
 error:
L
Li Zhang 已提交
11412 11413 11414 11415
    virDomainNVRAMDefFree(def);
    return NULL;
}

11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439
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;
    }

11440 11441
    if (virDomainParseScaledValue("./size[1]", NULL, ctxt,
                                  &def->size, 1, ULLONG_MAX, false) < 0)
11442 11443
        goto cleanup;

11444
    if ((server = virXPathNode("./server[1]", ctxt))) {
11445 11446
        def->server.enabled = true;

11447 11448
        def->server.chr.type = VIR_DOMAIN_CHR_TYPE_UNIX;
        def->server.chr.data.nix.listen = false;
11449
        if ((tmp = virXMLPropString(server, "path")))
11450
            def->server.chr.data.nix.path = virFileSanitizePath(tmp);
11451 11452 11453
        VIR_FREE(tmp);
    }

11454
    if ((msi = virXPathNode("./msi[1]", ctxt))) {
11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465
        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);

11466 11467 11468 11469 11470 11471 11472 11473 11474 11475
        if ((tmp = virXMLPropString(msi, "ioeventfd"))) {
            int val;

            if ((val = virTristateSwitchTypeFromString(tmp)) <= 0) {
                virReportError(VIR_ERR_XML_ERROR,
                               _("invalid msi ioeventfd setting for shmem: '%s'"),
                               tmp);
                goto cleanup;
            }
            def->msi.ioeventfd = val;
11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499
        }
        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;
}

11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558
static int
virSysinfoBIOSParseXML(xmlNodePtr node,
                       xmlXPathContextPtr ctxt,
                       virSysinfoBIOSDefPtr *bios)
{
    int ret = -1;
    virSysinfoBIOSDefPtr def;

    if (!xmlStrEqual(node->name, BAD_CAST "bios")) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("XML does not contain expected 'bios' element"));
        return ret;
    }

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

    def->vendor = virXPathString("string(entry[@name='vendor'])", ctxt);
    def->version = virXPathString("string(entry[@name='version'])", ctxt);
    def->date = virXPathString("string(entry[@name='date'])", ctxt);
    def->release = virXPathString("string(entry[@name='release'])", ctxt);
    if (def->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->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 cleanup;
        }
    }

    if (!def->vendor && !def->version &&
        !def->date && !def->release) {
        virSysinfoBIOSDefFree(def);
        def = NULL;
    }

    *bios = def;
    def = NULL;
    ret = 0;
 cleanup:
    virSysinfoBIOSDefFree(def);
    return ret;
}

11559 11560 11561
static int
virSysinfoSystemParseXML(xmlNodePtr node,
                         xmlXPathContextPtr ctxt,
M
Michal Privoznik 已提交
11562
                         virSysinfoSystemDefPtr *sysdef,
11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624
                         unsigned char *domUUID,
                         bool uuid_generated)
{
    int ret = -1;
    virSysinfoSystemDefPtr def;
    char *tmpUUID = NULL;

    if (!xmlStrEqual(node->name, BAD_CAST "system")) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("XML does not contain expected 'system' element"));
        return ret;
    }

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

    def->manufacturer =
        virXPathString("string(entry[@name='manufacturer'])", ctxt);
    def->product =
        virXPathString("string(entry[@name='product'])", ctxt);
    def->version =
        virXPathString("string(entry[@name='version'])", ctxt);
    def->serial =
        virXPathString("string(entry[@name='serial'])", ctxt);
    tmpUUID = virXPathString("string(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 cleanup;
        }
        if (uuid_generated) {
            memcpy(domUUID, uuidbuf, VIR_UUID_BUFLEN);
        } else if (memcmp(domUUID, uuidbuf, VIR_UUID_BUFLEN) != 0) {
            virReportError(VIR_ERR_XML_DETAIL, "%s",
                           _("UUID mismatch between <uuid> and "
                             "<sysinfo>"));
            goto cleanup;
        }
        /* 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->uuid, uuidstr) < 0)
            goto cleanup;
    }
    def->sku =
        virXPathString("string(entry[@name='sku'])", ctxt);
    def->family =
        virXPathString("string(entry[@name='family'])", ctxt);

    if (!def->manufacturer && !def->product && !def->version &&
        !def->serial && !def->uuid && !def->sku && !def->family) {
        virSysinfoSystemDefFree(def);
        def = NULL;
    }

M
Michal Privoznik 已提交
11625
    *sysdef = def;
11626 11627 11628 11629 11630 11631 11632 11633
    def = NULL;
    ret = 0;
 cleanup:
    virSysinfoSystemDefFree(def);
    VIR_FREE(tmpUUID);
    return ret;
}

11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688
static int
virSysinfoBaseBoardParseXML(xmlXPathContextPtr ctxt,
                            virSysinfoBaseBoardDefPtr *baseBoard,
                            size_t *nbaseBoard)
{
    int ret = -1;
    virSysinfoBaseBoardDefPtr boards = NULL;
    size_t i, nboards = 0;
    xmlNodePtr *nodes = NULL, oldnode = ctxt->node;
    int n;

    if ((n = virXPathNodeSet("./baseBoard", ctxt, &nodes)) < 0)
        return ret;

    if (n && VIR_ALLOC_N(boards, n) < 0)
        goto cleanup;

    for (i = 0; i < n; i++) {
        virSysinfoBaseBoardDefPtr def = boards + nboards;

        ctxt->node = nodes[i];

        def->manufacturer =
            virXPathString("string(entry[@name='manufacturer'])", ctxt);
        def->product =
            virXPathString("string(entry[@name='product'])", ctxt);
        def->version =
            virXPathString("string(entry[@name='version'])", ctxt);
        def->serial =
            virXPathString("string(entry[@name='serial'])", ctxt);
        def->asset =
            virXPathString("string(entry[@name='asset'])", ctxt);
        def->location =
            virXPathString("string(entry[@name='location'])", ctxt);

        if (!def->manufacturer && !def->product && !def->version &&
            !def->serial && !def->asset && !def->location) {
            /* nada */
        } else {
            nboards++;
        }
    }

    *baseBoard = boards;
    *nbaseBoard = nboards;
    boards = NULL;
    nboards = 0;
    ret = 0;
 cleanup:
    VIR_FREE(boards);
    VIR_FREE(nodes);
    ctxt->node = oldnode;
    return ret;
}

11689
static virSysinfoDefPtr
11690
virSysinfoParseXML(xmlNodePtr node,
11691 11692 11693
                  xmlXPathContextPtr ctxt,
                  unsigned char *domUUID,
                  bool uuid_generated)
11694 11695
{
    virSysinfoDefPtr def;
11696
    xmlNodePtr oldnode, tmpnode;
11697 11698 11699
    char *type;

    if (!xmlStrEqual(node->name, BAD_CAST "sysinfo")) {
11700 11701
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("XML does not contain expected 'sysinfo' element"));
11702
        return NULL;
11703 11704
    }

11705
    if (VIR_ALLOC(def) < 0)
11706
        return NULL;
11707 11708 11709

    type = virXMLPropString(node, "type");
    if (type == NULL) {
11710 11711
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("sysinfo must contain a type attribute"));
11712 11713
        goto error;
    }
11714
    if ((def->type = virSysinfoTypeFromString(type)) < 0) {
11715
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11716
                       _("unknown sysinfo type '%s'"), type);
11717 11718 11719 11720
        goto error;
    }

    /* Extract BIOS related metadata */
11721 11722 11723 11724 11725
    if ((tmpnode = virXPathNode("./bios[1]", ctxt)) != NULL) {
        oldnode = ctxt->node;
        ctxt->node = tmpnode;
        if (virSysinfoBIOSParseXML(tmpnode, ctxt, &def->bios) < 0) {
            ctxt->node = oldnode;
11726 11727
            goto error;
        }
11728
        ctxt->node = oldnode;
11729
    }
11730 11731

    /* Extract system related metadata */
11732 11733 11734 11735 11736 11737
    if ((tmpnode = virXPathNode("./system[1]", ctxt)) != NULL) {
        oldnode = ctxt->node;
        ctxt->node = tmpnode;
        if (virSysinfoSystemParseXML(tmpnode, ctxt, &def->system,
                                     domUUID, uuid_generated) < 0) {
            ctxt->node = oldnode;
11738 11739
            goto error;
        }
11740
        ctxt->node = oldnode;
11741
    }
11742

11743 11744 11745 11746
    /* Extract system base board metadata */
    if (virSysinfoBaseBoardParseXML(ctxt, &def->baseBoard, &def->nbaseBoard) < 0)
        goto error;

11747
 cleanup:
11748
    VIR_FREE(type);
11749
    return def;
11750

11751
 error:
11752 11753 11754 11755
    virSysinfoDefFree(def);
    def = NULL;
    goto cleanup;
}
11756

11757
unsigned int
11758
virDomainVideoDefaultRAM(const virDomainDef *def,
11759
                         const virDomainVideoType type)
11760
{
11761 11762 11763 11764
    /* Defer setting default vram to the Xen drivers */
    if (def->virtType == VIR_DOMAIN_VIRT_XEN)
        return 0;

11765 11766 11767 11768 11769 11770
    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 已提交
11771 11772
        else if (def->virtType == VIR_DOMAIN_VIRT_VMWARE)
            return 4 * 1024;
11773
        else
11774
            return 16 * 1024;
11775 11776 11777 11778 11779 11780
        break;

    case VIR_DOMAIN_VIDEO_TYPE_XEN:
        /* Original Xen PVFB hardcoded to 4 MB */
        return 4 * 1024;

11781
    case VIR_DOMAIN_VIDEO_TYPE_QXL:
11782
        /* QEMU use 64M as the minimal video memory for qxl device */
11783 11784
        return 64 * 1024;

11785 11786 11787 11788 11789 11790 11791
    default:
        return 0;
    }
}


int
11792
virDomainVideoDefaultType(const virDomainDef *def)
11793 11794 11795 11796 11797 11798 11799
{
    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:
11800 11801
        if (def->os.type == VIR_DOMAIN_OSTYPE_XEN ||
            def->os.type == VIR_DOMAIN_OSTYPE_LINUX)
11802
            return VIR_DOMAIN_VIDEO_TYPE_XEN;
11803
        else if ARCH_IS_PPC64(def->os.arch)
11804
            return VIR_DOMAIN_VIDEO_TYPE_VGA;
11805 11806 11807 11808 11809 11810
        else
            return VIR_DOMAIN_VIDEO_TYPE_CIRRUS;

    case VIR_DOMAIN_VIRT_VBOX:
        return VIR_DOMAIN_VIDEO_TYPE_VBOX;

M
Matthias Bolte 已提交
11811 11812 11813
    case VIR_DOMAIN_VIRT_VMWARE:
        return VIR_DOMAIN_VIDEO_TYPE_VMVGA;

11814
    case VIR_DOMAIN_VIRT_VZ:
11815
    case VIR_DOMAIN_VIRT_PARALLELS:
11816
        if (def->os.type == VIR_DOMAIN_OSTYPE_HVM)
11817
            return VIR_DOMAIN_VIDEO_TYPE_VGA;
11818 11819
        else
            return VIR_DOMAIN_VIDEO_TYPE_PARALLELS;
11820 11821 11822 11823 11824
    default:
        return -1;
    }
}

11825
static virDomainVideoAccelDefPtr
11826 11827
virDomainVideoAccelDefParseXML(xmlNodePtr node)
{
11828 11829
    xmlNodePtr cur;
    virDomainVideoAccelDefPtr def;
11830
    char *accel2d = NULL;
11831 11832
    char *accel3d = NULL;
    int val;
11833 11834 11835 11836

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
11837
            if (!accel3d && !accel2d &&
11838
                xmlStrEqual(cur->name, BAD_CAST "acceleration")) {
11839 11840
                accel3d = virXMLPropString(cur, "accel3d");
                accel2d = virXMLPropString(cur, "accel2d");
11841 11842 11843 11844 11845
            }
        }
        cur = cur->next;
    }

11846
    if (!accel3d && !accel2d)
11847
        return NULL;
11848

11849
    if (VIR_ALLOC(def) < 0)
11850
        goto cleanup;
11851

11852
    if (accel3d) {
11853 11854 11855 11856 11857 11858
        if ((val = virTristateBoolTypeFromString(accel3d)) <= 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown accel3d value '%s'"), accel3d);
            goto cleanup;
        }
        def->accel3d = val;
11859 11860
    }

11861
    if (accel2d) {
11862 11863 11864 11865 11866 11867
        if ((val = virTristateBoolTypeFromString(accel2d)) <= 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown accel2d value '%s'"), accel2d);
            goto cleanup;
        }
        def->accel2d = val;
11868 11869
    }

11870 11871 11872
 cleanup:
    VIR_FREE(accel2d);
    VIR_FREE(accel3d);
11873 11874 11875
    return def;
}

11876
static virDomainVideoDefPtr
11877 11878
virDomainVideoDefParseXML(xmlNodePtr node,
                          const virDomainDef *dom,
E
Eric Blake 已提交
11879 11880
                          unsigned int flags)
{
11881 11882 11883 11884 11885
    virDomainVideoDefPtr def;
    xmlNodePtr cur;
    char *type = NULL;
    char *heads = NULL;
    char *vram = NULL;
11886
    char *ram = NULL;
11887
    char *vgamem = NULL;
11888
    char *primary = NULL;
11889

11890
    if (VIR_ALLOC(def) < 0)
11891 11892 11893 11894 11895
        return NULL;

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
11896
            if (!type && !vram && !ram && !heads &&
11897 11898
                xmlStrEqual(cur->name, BAD_CAST "model")) {
                type = virXMLPropString(cur, "type");
11899
                ram = virXMLPropString(cur, "ram");
11900
                vram = virXMLPropString(cur, "vram");
11901
                vgamem = virXMLPropString(cur, "vgamem");
11902
                heads = virXMLPropString(cur, "heads");
11903

11904
                if ((primary = virXMLPropString(cur, "primary")) != NULL) {
11905 11906
                    if (STREQ(primary, "yes"))
                        def->primary = 1;
11907 11908
                    VIR_FREE(primary);
                }
11909

11910
                def->accel = virDomainVideoAccelDefParseXML(cur);
11911 11912 11913 11914 11915 11916 11917
            }
        }
        cur = cur->next;
    }

    if (type) {
        if ((def->type = virDomainVideoTypeFromString(type)) < 0) {
11918
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
11919
                           _("unknown video model '%s'"), type);
11920 11921 11922 11923
            goto error;
        }
    } else {
        if ((def->type = virDomainVideoDefaultType(dom)) < 0) {
11924 11925
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("missing video model and cannot determine default"));
11926 11927 11928 11929
            goto error;
        }
    }

11930 11931 11932 11933 11934 11935
    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;
        }
11936
        if (virStrToLong_uip(ram, NULL, 10, &def->ram) < 0) {
11937 11938 11939 11940 11941 11942 11943 11944
            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);
    }

11945
    if (vram) {
11946
        if (virStrToLong_uip(vram, NULL, 10, &def->vram) < 0) {
11947
            virReportError(VIR_ERR_XML_ERROR,
11948
                           _("cannot parse video vram '%s'"), vram);
11949 11950 11951 11952 11953 11954
            goto error;
        }
    } else {
        def->vram = virDomainVideoDefaultRAM(dom, def->type);
    }

11955 11956 11957 11958 11959 11960
    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;
        }
11961
        if (virStrToLong_uip(vgamem, NULL, 10, &def->vgamem) < 0) {
11962 11963 11964 11965 11966 11967
            virReportError(VIR_ERR_XML_ERROR,
                           _("cannot parse video vgamem '%s'"), vgamem);
            goto error;
        }
    }

11968
    if (heads) {
11969
        if (virStrToLong_uip(heads, NULL, 10, &def->heads) < 0) {
11970 11971
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot parse video heads '%s'"), heads);
11972 11973 11974 11975 11976 11977
            goto error;
        }
    } else {
        def->heads = 1;
    }

11978
    if (virDomainDeviceInfoParseXML(node, NULL, &def->info, flags) < 0)
11979 11980
        goto error;

11981
    VIR_FREE(type);
11982
    VIR_FREE(ram);
11983
    VIR_FREE(vram);
11984
    VIR_FREE(vgamem);
11985 11986 11987 11988
    VIR_FREE(heads);

    return def;

11989
 error:
11990 11991
    virDomainVideoDefFree(def);
    VIR_FREE(type);
11992
    VIR_FREE(ram);
11993
    VIR_FREE(vram);
11994
    VIR_FREE(vgamem);
11995 11996 11997 11998
    VIR_FREE(heads);
    return NULL;
}

11999
static virDomainHostdevDefPtr
12000
virDomainHostdevDefParseXML(xmlNodePtr node,
12001
                            xmlXPathContextPtr ctxt,
12002
                            virHashTablePtr bootHash,
E
Eric Blake 已提交
12003
                            unsigned int flags)
12004
{
12005
    virDomainHostdevDefPtr def;
12006 12007 12008
    xmlNodePtr save = ctxt->node;
    char *mode = virXMLPropString(node, "mode");
    char *type = virXMLPropString(node, "type");
12009

12010
    ctxt->node = node;
12011

12012
    if (!(def = virDomainHostdevDefAlloc()))
12013 12014
        goto error;

12015 12016
    if (mode) {
        if ((def->mode = virDomainHostdevModeTypeFromString(mode)) < 0) {
12017
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030
                           _("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;
12031 12032 12033 12034 12035
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
        /* parse managed/mode/type, and the <source> element */
        if (virDomainHostdevDefParseXMLCaps(node, ctxt, type, def) < 0)
            goto error;
        break;
12036 12037 12038
    default:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unexpected hostdev mode %d"), def->mode);
12039
        goto error;
12040
    }
12041

12042
    if (def->info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
12043
        if (virDomainDeviceInfoParseXML(node, bootHash, def->info,
12044 12045
                                        flags  | VIR_DOMAIN_DEF_PARSE_ALLOW_BOOT
                                        | VIR_DOMAIN_DEF_PARSE_ALLOW_ROM) < 0)
12046 12047 12048 12049 12050 12051
            goto error;
    }

    if (def->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
        switch (def->source.subsys.type) {
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
12052 12053
            if (def->info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
                def->info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
12054 12055
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("PCI host devices must use 'pci' address type"));
12056 12057 12058
                goto error;
            }
            break;
H
Han Cheng 已提交
12059
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
12060 12061
            if (def->info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
                def->info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE) {
H
Han Cheng 已提交
12062
                virReportError(VIR_ERR_XML_ERROR, "%s",
12063 12064
                               _("SCSI host device must use 'drive' "
                                 "address type"));
H
Han Cheng 已提交
12065 12066
                goto error;
            }
O
Osier Yang 已提交
12067 12068
            if (virXPathBoolean("boolean(./readonly)", ctxt))
                def->readonly = true;
12069 12070
            if (virXPathBoolean("boolean(./shareable)", ctxt))
                def->shareable = true;
H
Han Cheng 已提交
12071
            break;
12072 12073 12074
        }
    }

12075
 cleanup:
12076 12077
    VIR_FREE(type);
    VIR_FREE(mode);
12078
    ctxt->node = save;
12079 12080
    return def;

12081
 error:
12082 12083 12084 12085 12086
    virDomainHostdevDefFree(def);
    def = NULL;
    goto cleanup;
}

12087

12088
static virDomainRedirdevDefPtr
12089
virDomainRedirdevDefParseXML(xmlNodePtr node,
12090
                             virHashTablePtr bootHash,
12091 12092 12093 12094 12095
                             unsigned int flags)
{
    xmlNodePtr cur;
    virDomainRedirdevDefPtr def;
    char *bus, *type = NULL;
12096
    int remaining;
12097

12098
    if (VIR_ALLOC(def) < 0)
12099 12100 12101 12102 12103
        return NULL;

    bus = virXMLPropString(node, "bus");
    if (bus) {
        if ((def->bus = virDomainRedirdevBusTypeFromString(bus)) < 0) {
12104
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
12105
                           _("unknown redirdev bus '%s'"), bus);
12106 12107 12108 12109 12110 12111 12112 12113 12114
            goto error;
        }
    } else {
        def->bus = VIR_DOMAIN_REDIRDEV_BUS_USB;
    }

    type = virXMLPropString(node, "type");
    if (type) {
        if ((def->source.chr.type = virDomainChrTypeFromString(type)) < 0) {
12115
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
12116
                           _("unknown redirdev character device type '%s'"), type);
12117 12118 12119
            goto error;
        }
    } else {
12120 12121
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing type in redirdev"));
12122 12123 12124 12125
        goto error;
    }

    cur = node->children;
12126 12127 12128 12129 12130 12131 12132
    /* 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;
12133

12134
    if (def->source.chr.type == VIR_DOMAIN_CHR_TYPE_SPICEVMC)
12135 12136
        def->source.chr.data.spicevmc = VIR_DOMAIN_CHR_SPICEVMC_USBREDIR;

12137
    if (virDomainDeviceInfoParseXML(node, bootHash, &def->info,
12138
                                    flags | VIR_DOMAIN_DEF_PARSE_ALLOW_BOOT) < 0)
12139 12140 12141 12142 12143
        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) {
12144 12145
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Invalid address for a USB device"));
12146 12147 12148 12149
        goto error;
    }


12150
 cleanup:
12151 12152 12153 12154
    VIR_FREE(bus);
    VIR_FREE(type);
    return def;

12155
 error:
12156 12157 12158 12159 12160
    virDomainRedirdevDefFree(def);
    def = NULL;
    goto cleanup;
}

12161
/*
J
Ján Tomko 已提交
12162
 * This is the helper function to convert USB device version from a
12163 12164 12165
 * 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.
J
Ján Tomko 已提交
12166 12167
 * e.g. USB version 2.0 is reported as 0x0200,
 *      USB version 4.07 as 0x0407
12168 12169
 */
static int
12170 12171
virDomainRedirFilterUSBVersionHelper(const char *version,
                                     virDomainRedirFilterUSBDevDefPtr def)
12172
{
J
Ján Tomko 已提交
12173 12174
    unsigned int major, minor;
    char *s = NULL;
12175

J
Ján Tomko 已提交
12176 12177 12178 12179
    if ((virStrToLong_ui(version, &s, 10, &major)) < 0 ||
        *s++ != '.' ||
        (virStrToLong_ui(s, NULL, 10, &minor)) < 0)
        goto error;
12180

J
Ján Tomko 已提交
12181 12182
    if (major >= 100 || minor >= 100)
        goto error;
12183

J
Ján Tomko 已提交
12184 12185 12186
    /* Treat JJ.M as JJ.M0, not JJ.0M */
    if (strlen(s) == 1)
        minor *= 10;
12187

J
Ján Tomko 已提交
12188 12189
    def->version = (major / 10) << 12 | (major % 10) << 8 |
                   (minor / 10) << 4 | (minor % 10) << 0;
12190

J
Ján Tomko 已提交
12191
    return 0;
12192

J
Ján Tomko 已提交
12193 12194 12195 12196
 error:
    virReportError(VIR_ERR_XML_ERROR,
                   _("Cannot parse USB device version %s"), version);
    return -1;
12197 12198
}

12199 12200
static virDomainRedirFilterUSBDevDefPtr
virDomainRedirFilterUSBDevDefParseXML(xmlNodePtr node)
12201 12202 12203 12204
{
    char *class;
    char *vendor = NULL, *product = NULL;
    char *version = NULL, *allow = NULL;
12205
    virDomainRedirFilterUSBDevDefPtr def;
12206

12207
    if (VIR_ALLOC(def) < 0)
12208 12209 12210 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 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252
        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;
12253
        else if ((virDomainRedirFilterUSBVersionHelper(version, def)) < 0)
12254 12255 12256 12257 12258 12259 12260
            goto error;
    } else {
        def->version = -1;
    }

    allow = virXMLPropString(node, "allow");
    if (allow) {
12261
        if (STREQ(allow, "yes")) {
12262
            def->allow = true;
12263
        } else if (STREQ(allow, "no")) {
12264
            def->allow = false;
12265
        } else {
12266 12267 12268 12269 12270 12271 12272 12273 12274 12275
            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;
    }

12276
 cleanup:
12277 12278 12279 12280 12281 12282 12283
    VIR_FREE(class);
    VIR_FREE(vendor);
    VIR_FREE(product);
    VIR_FREE(version);
    VIR_FREE(allow);
    return def;

12284
 error:
12285 12286 12287 12288 12289 12290
    VIR_FREE(def);
    def = NULL;
    goto cleanup;
}

static virDomainRedirFilterDefPtr
12291
virDomainRedirFilterDefParseXML(xmlNodePtr node,
12292 12293 12294 12295 12296 12297 12298 12299 12300
                                xmlXPathContextPtr ctxt)
{
    int n;
    size_t i;
    xmlNodePtr *nodes = NULL;
    xmlNodePtr save = ctxt->node;
    virDomainRedirFilterDefPtr def = NULL;

    if (VIR_ALLOC(def) < 0)
12301
        goto error;
12302 12303

    ctxt->node = node;
12304
    if ((n = virXPathNodeSet("./usbdev", ctxt, &nodes)) < 0)
12305 12306 12307
        goto error;

    if (n && VIR_ALLOC_N(def->usbdevs, n) < 0)
12308
        goto error;
12309 12310

    for (i = 0; i < n; i++) {
12311 12312
        virDomainRedirFilterUSBDevDefPtr usbdev =
            virDomainRedirFilterUSBDevDefParseXML(nodes[i]);
12313 12314 12315 12316 12317 12318 12319 12320 12321 12322

        if (!usbdev)
            goto error;
        def->usbdevs[def->nusbdevs++] = usbdev;
    }
    VIR_FREE(nodes);

    ctxt->node = save;
    return def;

12323
 error:
12324 12325 12326 12327 12328
    VIR_FREE(nodes);
    virDomainRedirFilterDefFree(def);
    return NULL;
}

12329 12330 12331 12332 12333 12334 12335
static int
virDomainEventActionParseXML(xmlXPathContextPtr ctxt,
                             const char *name,
                             const char *xpath,
                             int *val,
                             int defaultVal,
                             virEventActionFromStringFunc convFunc)
12336
{
12337
    char *tmp = virXPathString(xpath, ctxt);
12338 12339 12340
    if (tmp == NULL) {
        *val = defaultVal;
    } else {
12341
        *val = convFunc(tmp);
12342
        if (*val < 0) {
12343
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
12344
                           _("unknown %s action: %s"), name, tmp);
12345 12346 12347 12348 12349 12350 12351 12352
            VIR_FREE(tmp);
            return -1;
        }
        VIR_FREE(tmp);
    }
    return 0;
}

12353 12354 12355 12356 12357 12358 12359 12360
static int
virDomainPMStateParseXML(xmlXPathContextPtr ctxt,
                         const char *xpath,
                         int *val)
{
    int ret = -1;
    char *tmp = virXPathString(xpath, ctxt);
    if (tmp) {
J
Ján Tomko 已提交
12361
        *val = virTristateBoolTypeFromString(tmp);
12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374
        if (*val < 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown PM state value %s"), tmp);
            goto cleanup;
        }
    }

    ret = 0;
 cleanup:
    VIR_FREE(tmp);
    return ret;
}

12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393

static int
virDomainMemorySourceDefParseXML(xmlNodePtr node,
                                 xmlXPathContextPtr ctxt,
                                 virDomainMemoryDefPtr def)
{
    int ret = -1;
    char *nodemask = NULL;
    xmlNodePtr save = ctxt->node;
    ctxt->node = node;

    if (virDomainParseMemory("./pagesize", "./pagesize/@unit", ctxt,
                             &def->pagesize, false, false) < 0)
        goto cleanup;

    if ((nodemask = virXPathString("string(./nodemask)", ctxt))) {
        if (virBitmapParse(nodemask, 0, &def->sourceNodes,
                           VIR_DOMAIN_CPUMASK_LEN) < 0)
            goto cleanup;
12394 12395 12396 12397 12398 12399

        if (virBitmapIsAllClear(def->sourceNodes)) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Invalid value of 'nodemask': %s"), nodemask);
            goto cleanup;
        }
12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418
    }

    ret = 0;

 cleanup:
    VIR_FREE(nodemask);
    ctxt->node = save;
    return ret;
}


static int
virDomainMemoryTargetDefParseXML(xmlNodePtr node,
                                 xmlXPathContextPtr ctxt,
                                 virDomainMemoryDefPtr def)
{
    int ret = -1;
    xmlNodePtr save = ctxt->node;
    ctxt->node = node;
12419
    int rv;
12420

12421 12422 12423 12424 12425
    /* initialize to value which marks that the user didn't specify it */
    def->targetNode = -1;

    if ((rv = virXPathInt("string(./node)", ctxt, &def->targetNode)) == -2 ||
        (rv == 0 && def->targetNode < 0)) {
12426
        virReportError(VIR_ERR_XML_ERROR, "%s",
12427
                       _("invalid value of memory device node"));
12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488
        goto cleanup;
    }

    if (virDomainParseMemory("./size", "./size/@unit", ctxt,
                             &def->size, true, false) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    ctxt->node = save;
    return ret;
}


static virDomainMemoryDefPtr
virDomainMemoryDefParseXML(xmlNodePtr memdevNode,
                           xmlXPathContextPtr ctxt,
                           unsigned int flags)
{
    char *tmp = NULL;
    xmlNodePtr save = ctxt->node;
    xmlNodePtr node;
    virDomainMemoryDefPtr def;

    ctxt->node = memdevNode;

    if (VIR_ALLOC(def) < 0)
        return NULL;

    if (!(tmp = virXMLPropString(memdevNode, "model"))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing memory model"));
        goto error;
    }

    if ((def->model = virDomainMemoryModelTypeFromString(tmp)) < 0) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("invalid memory model '%s'"), tmp);
        goto error;
    }
    VIR_FREE(tmp);

    /* source */
    if ((node = virXPathNode("./source", ctxt)) &&
        virDomainMemorySourceDefParseXML(node, ctxt, def) < 0)
        goto error;

    /* target */
    if (!(node = virXPathNode("./target", ctxt))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing <target> element for <memory> device"));
        goto error;
    }

    if (virDomainMemoryTargetDefParseXML(node, ctxt, def) < 0)
        goto error;

    if (virDomainDeviceInfoParseXML(memdevNode, NULL, &def->info, flags) < 0)
        goto error;

12489
    ctxt->node = save;
12490 12491 12492 12493 12494 12495 12496 12497 12498 12499
    return def;

 error:
    VIR_FREE(tmp);
    virDomainMemoryDefFree(def);
    ctxt->node = save;
    return NULL;
}


12500
virDomainDeviceDefPtr
12501
virDomainDeviceDefParse(const char *xmlStr,
12502
                        const virDomainDef *def,
12503 12504
                        virCapsPtr caps,
                        virDomainXMLOptionPtr xmlopt,
12505
                        unsigned int flags)
12506 12507 12508
{
    xmlDocPtr xml;
    xmlNodePtr node;
12509
    xmlXPathContextPtr ctxt = NULL;
12510
    virDomainDeviceDefPtr dev = NULL;
12511
    char *netprefix;
12512

12513
    if (!(xml = virXMLParseStringCtxt(xmlStr, _("(device_definition)"), &ctxt)))
12514
        goto error;
12515

12516
    node = ctxt->node;
12517

12518
    if (VIR_ALLOC(dev) < 0)
12519 12520
        goto error;

12521 12522 12523 12524 12525 12526 12527 12528 12529
    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 {
12530
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
12531 12532 12533 12534 12535 12536 12537 12538
                           _("unknown device type '%s'"),
                           node->name);
            goto error;
        }
    }

    switch ((virDomainDeviceType) dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
12539
        if (!(dev->data.disk = virDomainDiskDefParseXML(xmlopt, node, ctxt,
12540 12541
                                                        NULL, def->seclabels,
                                                        def->nseclabels,
12542
                                                        flags)))
12543
            goto error;
12544 12545
        break;
    case VIR_DOMAIN_DEVICE_LEASE:
12546 12547
        if (!(dev->data.lease = virDomainLeaseDefParseXML(node)))
            goto error;
12548 12549
        break;
    case VIR_DOMAIN_DEVICE_FS:
12550
        if (!(dev->data.fs = virDomainFSDefParseXML(node, ctxt, flags)))
12551
            goto error;
12552 12553
        break;
    case VIR_DOMAIN_DEVICE_NET:
12554
        netprefix = caps->host.netprefix;
12555
        if (!(dev->data.net = virDomainNetDefParseXML(xmlopt, node, ctxt,
12556
                                                      NULL, netprefix, flags)))
12557
            goto error;
12558 12559
        break;
    case VIR_DOMAIN_DEVICE_INPUT:
12560 12561
        if (!(dev->data.input = virDomainInputDefParseXML(def, node,
                                                          ctxt, flags)))
12562
            goto error;
12563 12564
        break;
    case VIR_DOMAIN_DEVICE_SOUND:
12565
        if (!(dev->data.sound = virDomainSoundDefParseXML(node, ctxt, flags)))
12566
            goto error;
12567 12568
        break;
    case VIR_DOMAIN_DEVICE_WATCHDOG:
12569
        if (!(dev->data.watchdog = virDomainWatchdogDefParseXML(node, flags)))
R
Richard Jones 已提交
12570
            goto error;
12571 12572
        break;
    case VIR_DOMAIN_DEVICE_VIDEO:
12573
        if (!(dev->data.video = virDomainVideoDefParseXML(node, def, flags)))
12574
            goto error;
12575 12576
        break;
    case VIR_DOMAIN_DEVICE_HOSTDEV:
12577
        if (!(dev->data.hostdev = virDomainHostdevDefParseXML(node, ctxt,
12578
                                                              NULL, flags)))
12579
            goto error;
12580 12581
        break;
    case VIR_DOMAIN_DEVICE_CONTROLLER:
12582 12583
        if (!(dev->data.controller = virDomainControllerDefParseXML(node, ctxt,
                                                                    flags)))
12584
            goto error;
12585 12586
        break;
    case VIR_DOMAIN_DEVICE_GRAPHICS:
12587
        if (!(dev->data.graphics = virDomainGraphicsDefParseXML(node, ctxt, flags)))
12588
            goto error;
12589 12590
        break;
    case VIR_DOMAIN_DEVICE_HUB:
M
Marc-André Lureau 已提交
12591 12592
        if (!(dev->data.hub = virDomainHubDefParseXML(node, flags)))
            goto error;
12593 12594
        break;
    case VIR_DOMAIN_DEVICE_REDIRDEV:
12595
        if (!(dev->data.redirdev = virDomainRedirdevDefParseXML(node, NULL, flags)))
12596
            goto error;
12597 12598
        break;
    case VIR_DOMAIN_DEVICE_RNG:
12599 12600
        if (!(dev->data.rng = virDomainRNGDefParseXML(node, ctxt, flags)))
            goto error;
12601 12602
        break;
    case VIR_DOMAIN_DEVICE_CHR:
12603 12604 12605 12606 12607 12608
        if (!(dev->data.chr = virDomainChrDefParseXML(ctxt,
                                                      node,
                                                      def->seclabels,
                                                      def->nseclabels,
                                                      flags)))
            goto error;
12609 12610
        break;
    case VIR_DOMAIN_DEVICE_SMARTCARD:
12611 12612
        if (!(dev->data.smartcard = virDomainSmartcardDefParseXML(node, flags)))
            goto error;
12613 12614
        break;
    case VIR_DOMAIN_DEVICE_MEMBALLOON:
12615 12616 12617
        if (!(dev->data.memballoon = virDomainMemballoonDefParseXML(node,
                                                                    ctxt,
                                                                    flags)))
12618
            goto error;
12619 12620
        break;
    case VIR_DOMAIN_DEVICE_NVRAM:
12621 12622
        if (!(dev->data.nvram = virDomainNVRAMDefParseXML(node, flags)))
            goto error;
12623
        break;
12624 12625 12626 12627
    case VIR_DOMAIN_DEVICE_SHMEM:
        if (!(dev->data.shmem = virDomainShmemDefParseXML(node, ctxt, flags)))
            goto error;
        break;
12628 12629 12630 12631
    case VIR_DOMAIN_DEVICE_TPM:
        if (!(dev->data.tpm = virDomainTPMDefParseXML(node, ctxt, flags)))
            goto error;
        break;
12632 12633 12634 12635
    case VIR_DOMAIN_DEVICE_PANIC:
        if (!(dev->data.panic = virDomainPanicDefParseXML(node)))
            goto error;
        break;
12636 12637 12638 12639
    case VIR_DOMAIN_DEVICE_MEMORY:
        if (!(dev->data.memory = virDomainMemoryDefParseXML(node, ctxt, flags)))
            goto error;
        break;
12640 12641 12642
    case VIR_DOMAIN_DEVICE_NONE:
    case VIR_DOMAIN_DEVICE_LAST:
        break;
12643 12644
    }

12645
    /* callback to fill driver specific device aspects */
12646
    if (virDomainDeviceDefPostParse(dev, def, caps, flags, xmlopt) < 0)
12647 12648
        goto error;

12649
 cleanup:
12650
    xmlFreeDoc(xml);
12651
    xmlXPathFreeContext(ctxt);
12652 12653
    return dev;

12654
 error:
12655
    VIR_FREE(dev);
12656
    goto cleanup;
12657
}
M
Matthias Bolte 已提交
12658 12659


12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682
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;
    }

12683
    flags |= VIR_DOMAIN_DEF_PARSE_DISK_SOURCE;
12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700
    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;
}


12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713
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 已提交
12714 12715 12716
    case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
        type = virDomainChrSerialTargetTypeToString(targetType);
        break;
12717 12718 12719 12720 12721 12722 12723
    default:
        break;
    }

    return type;
}

L
Laine Stump 已提交
12724 12725 12726
int
virDomainHostdevInsert(virDomainDefPtr def, virDomainHostdevDefPtr hostdev)
{
12727 12728

    return VIR_APPEND_ELEMENT(def->hostdevs, def->nhostdevs, hostdev);
L
Laine Stump 已提交
12729 12730
}

12731
virDomainHostdevDefPtr
L
Laine Stump 已提交
12732 12733
virDomainHostdevRemove(virDomainDefPtr def, size_t i)
{
12734 12735
    virDomainHostdevDefPtr hostdev = def->hostdevs[i];

12736
    VIR_DELETE_ELEMENT(def->hostdevs, i, def->nhostdevs);
12737
    return hostdev;
L
Laine Stump 已提交
12738 12739
}

12740 12741

static int
12742 12743
virDomainHostdevMatchSubsysUSB(virDomainHostdevDefPtr first,
                               virDomainHostdevDefPtr second)
12744
{
12745 12746 12747 12748
    virDomainHostdevSubsysUSBPtr first_usbsrc = &first->source.subsys.u.usb;
    virDomainHostdevSubsysUSBPtr second_usbsrc = &second->source.subsys.u.usb;

    if (first_usbsrc->bus && first_usbsrc->device) {
12749
        /* specified by bus location on host */
12750 12751
        if (first_usbsrc->bus == second_usbsrc->bus &&
            first_usbsrc->device == second_usbsrc->device)
12752 12753 12754
            return 1;
    } else {
        /* specified by product & vendor id */
12755 12756
        if (first_usbsrc->product == second_usbsrc->product &&
            first_usbsrc->vendor == second_usbsrc->vendor)
12757 12758 12759 12760 12761 12762
            return 1;
    }
    return 0;
}

static int
12763 12764
virDomainHostdevMatchSubsysPCI(virDomainHostdevDefPtr first,
                               virDomainHostdevDefPtr second)
12765
{
12766 12767 12768 12769 12770 12771 12772
    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)
12773 12774 12775 12776
        return 1;
    return 0;
}

H
Han Cheng 已提交
12777
static int
12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789
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 已提交
12790 12791 12792
        return 1;
    return 0;
}
12793

12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809
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;
}

12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821
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 已提交
12822
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
12823 12824 12825
        if (a->source.subsys.u.scsi.protocol !=
            b->source.subsys.u.scsi.protocol)
            return 0;
12826 12827 12828 12829 12830
        if (a->source.subsys.u.scsi.protocol ==
            VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI)
            return virDomainHostdevMatchSubsysSCSIiSCSI(a, b);
        else
            return virDomainHostdevMatchSubsysSCSIHost(a, b);
12831 12832 12833 12834 12835
    }
    return 0;
}


12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852
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);
}

12853 12854 12855 12856 12857 12858 12859 12860
static int
virDomainHostdevMatchCapsNet(virDomainHostdevDefPtr a,
                              virDomainHostdevDefPtr b)
{
    return STREQ_NULLABLE(a->source.caps.u.net.iface,
                          b->source.caps.u.net.iface);
}

12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873

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);
12874 12875
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_NET:
        return virDomainHostdevMatchCapsNet(a, b);
12876 12877 12878 12879 12880
    }
    return 0;
}


12881 12882 12883 12884 12885 12886 12887 12888 12889 12890
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);
12891 12892
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
        return virDomainHostdevMatchCaps(a, b);
12893 12894 12895 12896
    }
    return 0;
}

L
Laine Stump 已提交
12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907
/* 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;
12908
    size_t i;
L
Laine Stump 已提交
12909 12910 12911 12912 12913

    if (!found)
        found = &local_found;
    *found = NULL;

12914
    for (i = 0; i < def->nhostdevs; i++) {
12915 12916
        if (virDomainHostdevMatch(match, def->hostdevs[i])) {
            *found = def->hostdevs[i];
L
Laine Stump 已提交
12917 12918 12919 12920 12921 12922
            break;
        }
    }
    return *found ? i : -1;
}

12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944
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;
}

12945

12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977
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;
}

12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988
virDomainDiskDefPtr
virDomainDiskByAddress(virDomainDefPtr def,
                       virDevicePCIAddressPtr pci_address,
                       unsigned int bus,
                       unsigned int target,
                       unsigned int unit)
{
    int idx = virDomainDiskIndexByAddress(def, pci_address, bus, target, unit);
    return idx < 0 ? NULL : def->disks[idx];
}

12989 12990 12991
int
virDomainDiskIndexByName(virDomainDefPtr def, const char *name,
                         bool allow_ambiguous)
12992 12993
{
    virDomainDiskDefPtr vdisk;
12994
    size_t i;
12995
    int candidate = -1;
12996

12997 12998 12999 13000
    /* 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.  */
13001 13002
    for (i = 0; i < def->ndisks; i++) {
        vdisk = def->disks[i];
13003 13004 13005
        if (*name != '/') {
            if (STREQ(vdisk->dst, name))
                return i;
13006
        } else if (STREQ_NULLABLE(virDomainDiskGetSource(vdisk), name)) {
13007 13008 13009 13010 13011 13012
            if (allow_ambiguous)
                return i;
            if (candidate >= 0)
                return -1;
            candidate = i;
        }
13013
    }
13014 13015 13016 13017 13018 13019 13020 13021 13022
    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)
{
13023
    int idx = virDomainDiskIndexByName(def, name, true);
13024

13025
    return idx < 0 ? NULL : virDomainDiskGetSource(def->disks[idx]);
13026 13027
}

13028 13029 13030 13031 13032 13033 13034 13035 13036
virDomainDiskDefPtr
virDomainDiskByName(virDomainDefPtr def,
                    const char *name,
                    bool allow_ambiguous)
{
    int idx = virDomainDiskIndexByName(def, name, allow_ambiguous);
    return idx < 0 ? NULL : def->disks[idx];
}

13037 13038
int virDomainDiskInsert(virDomainDefPtr def,
                        virDomainDiskDefPtr disk)
13039 13040
{

13041 13042 13043 13044 13045 13046
    if (VIR_REALLOC_N(def->disks, def->ndisks+1) < 0)
        return -1;

    virDomainDiskInsertPreAlloced(def, disk);

    return 0;
13047 13048
}

13049 13050 13051
void virDomainDiskInsertPreAlloced(virDomainDefPtr def,
                                   virDomainDiskDefPtr disk)
{
13052
    int idx;
13053 13054 13055 13056 13057 13058 13059 13060
    /* 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
     */
13061
    for (idx = (def->ndisks - 1); idx >= 0; idx--) {
13062 13063
        /* If bus matches and current disk is after
         * new disk, then new disk should go here */
13064 13065
        if (def->disks[idx]->bus == disk->bus &&
            (virDiskNameToIndex(def->disks[idx]->dst) >
13066
             virDiskNameToIndex(disk->dst))) {
13067 13068
            insertAt = idx;
        } else if (def->disks[idx]->bus == disk->bus &&
13069 13070 13071 13072
                   insertAt == -1) {
            /* Last disk with match bus is before the
             * new disk, then put new disk just after
             */
13073
            insertAt = idx + 1;
13074 13075 13076
        }
    }

13077 13078 13079
    /* VIR_INSERT_ELEMENT_INPLACE will never return an error here. */
    ignore_value(VIR_INSERT_ELEMENT_INPLACE(def->disks, insertAt,
                                            def->ndisks, disk));
13080 13081 13082
}


13083 13084
virDomainDiskDefPtr
virDomainDiskRemove(virDomainDefPtr def, size_t i)
13085
{
13086
    virDomainDiskDefPtr disk = def->disks[i];
13087

13088
    VIR_DELETE_ELEMENT(def->disks, i, def->ndisks);
13089
    return disk;
13090 13091
}

13092 13093
virDomainDiskDefPtr
virDomainDiskRemoveByName(virDomainDefPtr def, const char *name)
13094
{
13095 13096
    int idx = virDomainDiskIndexByName(def, name, false);
    if (idx < 0)
13097
        return NULL;
13098
    return virDomainDiskRemove(def, idx);
13099 13100
}

13101 13102
int virDomainNetInsert(virDomainDefPtr def, virDomainNetDefPtr net)
{
13103 13104 13105 13106 13107 13108 13109 13110 13111 13112
    /* 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);
13113
        return -1;
13114
    }
13115 13116 13117
    return 0;
}

13118 13119 13120 13121
/* virDomainNetFindIdx: search according to mac address and guest side
 *                      PCI address (if specified)
 *
 * Return: index of match if unique match found
13122
 *         -1 otherwise and an error is logged
13123 13124 13125
 */
int
virDomainNetFindIdx(virDomainDefPtr def, virDomainNetDefPtr net)
13126
{
13127 13128
    size_t i;
    int matchidx = -1;
13129
    char mac[VIR_MAC_STRING_BUFLEN];
13130 13131
    bool PCIAddrSpecified = virDomainDeviceAddressIsValid(&net->info,
                                                          VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI);
13132

13133 13134
    for (i = 0; i < def->nnets; i++) {
        if (virMacAddrCmp(&def->nets[i]->mac, &net->mac))
13135 13136 13137 13138 13139 13140 13141 13142 13143
            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.
             */
13144 13145 13146 13147
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("multiple devices matching mac address %s found"),
                           virMacAddrFormat(&net->mac, mac));
            return -1;
13148 13149
        }
        if (PCIAddrSpecified) {
13150
            if (virDevicePCIAddressEqual(&def->nets[i]->info.addr.pci,
13151 13152 13153 13154
                                         &net->info.addr.pci)) {
                /* exit early if the pci address was specified and
                 * it matches, as this guarantees no duplicates.
                 */
13155
                matchidx = i;
13156 13157 13158 13159
                break;
            }
        } else {
            /* no PCI address given, so there may be multiple matches */
13160
            matchidx = i;
13161 13162
        }
    }
13163
    if (matchidx < 0) {
13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177
        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));
        }
13178
    }
13179
    return matchidx;
13180 13181
}

13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202
bool
virDomainHasNet(virDomainDefPtr def, virDomainNetDefPtr net)
{
    size_t i;
    bool PCIAddrSpecified = virDomainDeviceAddressIsValid(&net->info,
                                                          VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI);

    for (i = 0; i < def->nnets; i++) {
        if (virMacAddrCmp(&def->nets[i]->mac, &net->mac))
            continue;

        if (PCIAddrSpecified) {
            if (virDevicePCIAddressEqual(&def->nets[i]->info.addr.pci,
                                         &net->info.addr.pci))
                return true;
        } else {
            return true;
        }
    }
    return false;
}
13203

13204 13205 13206 13207
void
virDomainNetRemoveHostdev(virDomainDefPtr def,
                          virDomainNetDefPtr net)
{
13208 13209 13210 13211 13212 13213
    /* 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;
13214

13215
    if (hostdev) {
13216 13217 13218
        for (i = 0; i < def->nhostdevs; i++) {
            if (def->hostdevs[i] == hostdev) {
                virDomainHostdevRemove(def, i);
13219 13220 13221 13222
                break;
            }
        }
    }
13223 13224 13225 13226 13227 13228 13229 13230 13231
}


virDomainNetDefPtr
virDomainNetRemove(virDomainDefPtr def, size_t i)
{
    virDomainNetDefPtr net = def->nets[i];

    virDomainNetRemoveHostdev(def, net);
13232
    VIR_DELETE_ELEMENT(def->nets, i, def->nnets);
13233
    return net;
13234 13235
}

13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250
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)
{
13251
    int idx;
13252 13253
    /* Tenatively plan to insert controller at the end. */
    int insertAt = -1;
13254
    virDomainControllerDefPtr current = NULL;
13255 13256 13257 13258 13259 13260

    /* 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
     */
13261
    for (idx = (def->ncontrollers - 1); idx >= 0; idx--) {
13262 13263 13264 13265 13266 13267 13268
        current = def->controllers[idx];
        if (current->type == controller->type) {
            if (current->idx > controller->idx) {
                /* If bus matches and current controller is after
                 * new controller, then new controller should go here
                 * */
                insertAt = idx;
13269 13270 13271 13272 13273 13274 13275 13276
            } else if (controller->info.mastertype == VIR_DOMAIN_CONTROLLER_MASTER_NONE &&
                       current->info.mastertype != VIR_DOMAIN_CONTROLLER_MASTER_NONE &&
                       current->idx == controller->idx) {
                /* If bus matches and index matches and new controller is
                 * master and current isn't a master, then new controller
                 * should go here to be placed before its companion
                 */
                insertAt = idx;
13277 13278 13279 13280 13281 13282
            } else if (insertAt == -1) {
                /* Last controller with match bus is before the
                 * new controller, then put new controller just after
                 */
                insertAt = idx + 1;
            }
13283 13284 13285
        }
    }

13286 13287 13288
    /* VIR_INSERT_ELEMENT_INPLACE will never return an error here. */
    ignore_value(VIR_INSERT_ELEMENT_INPLACE(def->controllers, insertAt,
                                            def->ncontrollers, controller));
13289 13290
}

13291 13292 13293 13294
int
virDomainControllerFind(virDomainDefPtr def,
                        int type, int idx)
{
13295
    size_t i;
13296

13297
    for (i = 0; i < def->ncontrollers; i++) {
13298 13299 13300 13301 13302 13303 13304 13305 13306
        if ((def->controllers[i]->type == type) &&
            (def->controllers[i]->idx == idx)) {
            return i;
        }
    }

    return -1;
}

13307

13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319
static int
virDomainControllerFindUnusedIndex(virDomainDefPtr def, int type)
{
    int idx = 0;

    while (virDomainControllerFind(def, type, idx) >= 0)
        idx++;

    return idx;
}


13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352
const char *
virDomainControllerAliasFind(virDomainDefPtr def,
                             int type, int idx)
{
    int contIndex;
    const char *contTypeStr = virDomainControllerTypeToString(type);

    if (!contTypeStr) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unknown controller type %d"),
                       type);
        return NULL;
    }

    contIndex = virDomainControllerFind(def, type, idx);
    if (contIndex < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find %s controller with index %d "
                         "required for device"),
                       contTypeStr, idx);
        return NULL;
    }
    if (!def->controllers[contIndex]->info.alias) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Device alias was not set for %s controller "
                         "with index %d "),
                       contTypeStr, idx);
        return NULL;
    }
    return def->controllers[contIndex]->info.alias;
}


13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366
int
virDomainControllerFindByType(virDomainDefPtr def,
                              int type)
{
    size_t i;

    for (i = 0; i < def->ncontrollers; i++) {
        if (def->controllers[i]->type == type)
            return i;
    }

    return -1;
}

13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383
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;
}

13384 13385 13386 13387 13388
virDomainControllerDefPtr
virDomainControllerRemove(virDomainDefPtr def, size_t i)
{
    virDomainControllerDefPtr controller = def->controllers[i];

13389
    VIR_DELETE_ELEMENT(def->controllers, i, def->ncontrollers);
13390 13391
    return controller;
}
13392

13393 13394 13395 13396
int virDomainLeaseIndex(virDomainDefPtr def,
                        virDomainLeaseDefPtr lease)
{
    virDomainLeaseDefPtr vlease;
13397
    size_t i;
13398 13399 13400

    for (i = 0; i < def->nleases; i++) {
        vlease = def->leases[i];
L
Luyao Huang 已提交
13401 13402 13403 13404
        /* Either both must have lockspaces present which match.. */
        if (vlease->lockspace && lease->lockspace) {
            if (STRNEQ(vlease->lockspace, lease->lockspace))
                continue;
13405
        /* ...or neither must have a lockspace present */
L
Luyao Huang 已提交
13406
        } else if (vlease->lockspace || lease->lockspace) {
13407
            continue;
L
Luyao Huang 已提交
13408 13409
        }

13410 13411 13412 13413 13414 13415 13416 13417 13418
        if (STREQ(vlease->key, lease->key))
            return i;
    }
    return -1;
}


int virDomainLeaseInsertPreAlloc(virDomainDefPtr def)
{
13419
    return VIR_EXPAND_N(def->leases, def->nleases, 1);
13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442
}

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;
}


13443 13444
virDomainLeaseDefPtr
virDomainLeaseRemoveAt(virDomainDefPtr def, size_t i)
13445
{
13446 13447 13448

    virDomainLeaseDefPtr lease = def->leases[i];

13449
    VIR_DELETE_ELEMENT(def->leases, i, def->nleases);
13450
    return lease;
13451 13452 13453
}


13454 13455 13456
virDomainLeaseDefPtr
virDomainLeaseRemove(virDomainDefPtr def,
                     virDomainLeaseDefPtr lease)
13457
{
13458 13459
    int idx = virDomainLeaseIndex(def, lease);
    if (idx < 0)
13460
        return NULL;
13461
    return virDomainLeaseRemoveAt(def, idx);
13462 13463
}

13464
bool
13465 13466 13467 13468 13469 13470 13471 13472 13473 13474
virDomainChrEquals(virDomainChrDefPtr src,
                   virDomainChrDefPtr tgt)
{
    if (!src || !tgt)
        return src == tgt;

    if (src->deviceType != tgt->deviceType ||
        !virDomainChrSourceDefIsEqual(&src->source, &tgt->source))
        return false;

13475
    switch ((virDomainChrDeviceType) src->deviceType) {
13476 13477 13478
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL:
        if (src->targetType != tgt->targetType)
            return false;
13479
        switch ((virDomainChrChannelTargetType) src->targetType) {
13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514
        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)
{
13515 13516 13517
    virDomainChrDefPtr chr;
    const virDomainChrDef **arrPtr;
    size_t i, cnt;
13518

13519
    virDomainChrGetDomainPtrs(def, target->deviceType, &arrPtr, &cnt);
13520

13521 13522 13523
    for (i = 0; i < cnt; i++) {
        /* Cast away const */
        chr = (virDomainChrDefPtr) arrPtr[i];
13524 13525 13526 13527 13528 13529
        if (virDomainChrEquals(chr, target))
            return chr;
    }
    return NULL;
}

13530 13531 13532 13533 13534

/* Return the address within vmdef to be modified when working with a
 * chrdefptr of the given type.  */
static void
virDomainChrGetDomainPtrsInternal(virDomainDefPtr vmdef,
13535
                                  virDomainChrDeviceType type,
13536 13537
                                  virDomainChrDefPtr ***arrPtr,
                                  size_t **cntPtr)
13538
{
13539
    switch (type) {
13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560
    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:
13561 13562
        *arrPtr = NULL;
        *cntPtr = NULL;
13563 13564 13565 13566
        break;
    }
}

13567

13568 13569 13570 13571
/* Return the array within vmdef that can contain a chrdefptr of the
 * given type.  */
void
virDomainChrGetDomainPtrs(const virDomainDef *vmdef,
13572
                          virDomainChrDeviceType type,
13573 13574 13575
                          const virDomainChrDef ***arrPtr,
                          size_t *cntPtr)
{
13576 13577
    virDomainChrDef ***arrVar = NULL;
    size_t *cntVar = NULL;
13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590

    /* 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;
    }
}

13591

13592
int
13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606
virDomainChrPreAlloc(virDomainDefPtr vmdef,
                     virDomainChrDefPtr chr)
{
    virDomainChrDefPtr **arrPtr = NULL;
    size_t *cntPtr = NULL;

    virDomainChrGetDomainPtrsInternal(vmdef, chr->deviceType, &arrPtr, &cntPtr);

    return VIR_REALLOC_N(*arrPtr, *cntPtr + 1);
}

void
virDomainChrInsertPreAlloced(virDomainDefPtr vmdef,
                             virDomainChrDefPtr chr)
13607
{
13608 13609
    virDomainChrDefPtr **arrPtr = NULL;
    size_t *cntPtr = NULL;
13610

13611
    virDomainChrGetDomainPtrsInternal(vmdef, chr->deviceType, &arrPtr, &cntPtr);
13612

13613
    ignore_value(VIR_APPEND_ELEMENT_INPLACE(*arrPtr, *cntPtr, chr));
13614 13615 13616 13617 13618 13619
}

virDomainChrDefPtr
virDomainChrRemove(virDomainDefPtr vmdef,
                   virDomainChrDefPtr chr)
{
13620 13621
    virDomainChrDefPtr ret, **arrPtr = NULL;
    size_t i, *cntPtr = NULL;
13622

13623
    virDomainChrGetDomainPtrsInternal(vmdef, chr->deviceType, &arrPtr, &cntPtr);
13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637

    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;
}
13638

13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708

int
virDomainRNGInsert(virDomainDefPtr def,
                   virDomainRNGDefPtr rng,
                   bool inplace)
{
    if (inplace)
        return VIR_APPEND_ELEMENT_INPLACE(def->rngs, def->nrngs, rng);
    else
        return VIR_APPEND_ELEMENT(def->rngs, def->nrngs, rng);
}


ssize_t
virDomainRNGFind(virDomainDefPtr def,
                 virDomainRNGDefPtr rng)
{
    size_t i;

    for (i = 0; i < def->nrngs; i++) {
        virDomainRNGDefPtr tmp = def->rngs[i];

        if (rng->model != tmp->model || rng->backend != tmp->backend)
            continue;

        if (rng->rate != tmp->rate || rng->period != tmp->period)
            continue;

        switch ((virDomainRNGBackend) rng->backend) {
        case VIR_DOMAIN_RNG_BACKEND_RANDOM:
            if (STRNEQ_NULLABLE(rng->source.file, tmp->source.file))
                continue;
            break;

        case VIR_DOMAIN_RNG_BACKEND_EGD:
            if (!virDomainChrSourceDefIsEqual(rng->source.chardev,
                                              tmp->source.chardev))
                continue;
            break;

        case VIR_DOMAIN_RNG_BACKEND_LAST:
            break;
        }

        if (rng->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
            !virDomainDeviceInfoAddressIsEqual(&rng->info, &tmp->info))
            continue;

        break;
    }

    if (i < def->nrngs)
        return i;

    return -1;
}


virDomainRNGDefPtr
virDomainRNGRemove(virDomainDefPtr def,
                   size_t idx)
{
    virDomainRNGDefPtr ret = def->rngs[idx];

    VIR_DELETE_ELEMENT(def->rngs, idx, def->nrngs);

    return ret;
}


13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804
static int
virDomainMemoryFindByDefInternal(virDomainDefPtr def,
                                 virDomainMemoryDefPtr mem,
                                 bool allowAddressFallback)
{
    size_t i;

    for (i = 0; i < def->nmems; i++) {
        virDomainMemoryDefPtr tmp = def->mems[i];

        /* address, if present */
        if (allowAddressFallback) {
            if (tmp->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
                continue;
        } else {
            if (mem->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
                !virDomainDeviceInfoAddressIsEqual(&tmp->info, &mem->info))
                continue;
        }

        /* alias, if present */
        if (mem->info.alias &&
            STRNEQ_NULLABLE(tmp->info.alias, mem->info.alias))
            continue;

        /* target info -> always present */
        if (tmp->model != mem->model ||
            tmp->targetNode != mem->targetNode ||
            tmp->size != mem->size)
            continue;

        /* source stuff -> match with device */
        if (tmp->pagesize != mem->pagesize)
            continue;

        if (!virBitmapEqual(tmp->sourceNodes, mem->sourceNodes))
            continue;

        break;
    }

    if (i == def->nmems)
        return -1;

    return i;
}


int
virDomainMemoryFindByDef(virDomainDefPtr def,
                         virDomainMemoryDefPtr mem)
{
    return virDomainMemoryFindByDefInternal(def, mem, false);
}


int
virDomainMemoryFindInactiveByDef(virDomainDefPtr def,
                                 virDomainMemoryDefPtr mem)
{
    int ret;

    if ((ret = virDomainMemoryFindByDefInternal(def, mem, false)) < 0)
        ret = virDomainMemoryFindByDefInternal(def, mem, true);

    return ret;
}


int
virDomainMemoryInsert(virDomainDefPtr def,
                      virDomainMemoryDefPtr mem)
{
    int id = def->nmems;

    if (mem->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
        virDomainDefHasDeviceAddress(def, &mem->info)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain already contains a device with the same "
                         "address"));
        return -1;
    }

    if (VIR_APPEND_ELEMENT(def->mems, def->nmems, mem) < 0)
        return -1;

    return id;
}


virDomainMemoryDefPtr
virDomainMemoryRemove(virDomainDefPtr def,
                      int idx)
{
    virDomainMemoryDefPtr ret = def->mems[idx];
    VIR_DELETE_ELEMENT(def->mems, idx, def->nmems);
13805 13806 13807 13808 13809

    /* fix up balloon size */
    if (def->mem.cur_balloon > virDomainDefGetMemoryActual(def))
        def->mem.cur_balloon = virDomainDefGetMemoryActual(def);

13810 13811 13812 13813
    return ret;
}


13814 13815 13816 13817
char *
virDomainDefGetDefaultEmulator(virDomainDefPtr def,
                               virCapsPtr caps)
{
13818
    char *retemu;
13819
    virCapsDomainDataPtr capsdata;
13820

13821 13822 13823
    if (!(capsdata = virCapabilitiesDomainDataLookup(caps, def->os.type,
            def->os.arch, def->virtType, NULL, NULL)))
        return NULL;
13824

13825 13826
    if (VIR_STRDUP(retemu, capsdata->emulator) < 0) {
        VIR_FREE(capsdata);
13827 13828
        return NULL;
    }
13829
    VIR_FREE(capsdata);
13830 13831 13832
    return retemu;
}

13833 13834
static int
virDomainDefParseBootXML(xmlXPathContextPtr ctxt,
13835
                         virDomainDefPtr def)
13836 13837
{
    xmlNodePtr *nodes = NULL;
13838 13839
    size_t i;
    int n;
M
Martin Kletzander 已提交
13840
    char *tmp = NULL;
13841
    int ret = -1;
M
Michal Privoznik 已提交
13842
    unsigned long deviceBoot, serialPorts;
13843 13844

    if (virXPathULong("count(./devices/disk[boot]"
13845
                      "|./devices/interface[boot]"
13846 13847
                      "|./devices/hostdev[boot]"
                      "|./devices/redirdev[boot])", ctxt, &deviceBoot) < 0) {
13848 13849
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot count boot devices"));
13850 13851
        goto cleanup;
    }
13852 13853

    /* analysis of the boot devices */
13854
    if ((n = virXPathNodeSet("./os/boot", ctxt, &nodes)) < 0)
13855 13856
        goto cleanup;

13857
    if (n > 0 && deviceBoot) {
13858 13859 13860
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("per-device boot elements cannot be used"
                         " together with os/boot elements"));
13861 13862 13863
        goto cleanup;
    }

13864
    for (i = 0; i < n && i < VIR_DOMAIN_BOOT_LAST; i++) {
13865 13866 13867
        int val;
        char *dev = virXMLPropString(nodes[i], "dev");
        if (!dev) {
13868 13869
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("missing boot device"));
13870 13871 13872
            goto cleanup;
        }
        if ((val = virDomainBootTypeFromString(dev)) < 0) {
13873
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
13874 13875
                           _("unknown boot device '%s'"),
                           dev);
13876 13877 13878 13879 13880 13881
            VIR_FREE(dev);
            goto cleanup;
        }
        VIR_FREE(dev);
        def->os.bootDevs[def->os.nBootDevs++] = val;
    }
13882
    if (def->os.nBootDevs == 0 && !deviceBoot) {
13883 13884 13885 13886
        def->os.nBootDevs = 1;
        def->os.bootDevs[0] = VIR_DOMAIN_BOOT_DISK;
    }

M
Martin Kletzander 已提交
13887 13888
    tmp = virXPathString("string(./os/bootmenu[1]/@enable)", ctxt);
    if (tmp) {
J
Ján Tomko 已提交
13889
        def->os.bootmenu = virTristateBoolTypeFromString(tmp);
13890 13891 13892 13893 13894
        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 已提交
13895
                     tmp);
J
Ján Tomko 已提交
13896
            def->os.bootmenu = VIR_TRISTATE_BOOL_NO;
13897
        }
M
Martin Kletzander 已提交
13898
        VIR_FREE(tmp);
13899 13900
    }

13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913
    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 已提交
13914 13915 13916
    tmp = virXPathString("string(./os/bios[1]/@useserial)", ctxt);
    if (tmp) {
        if (STREQ(tmp, "yes")) {
M
Michal Privoznik 已提交
13917 13918
            if (virXPathULong("count(./devices/serial)",
                              ctxt, &serialPorts) < 0) {
13919 13920 13921
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("need at least one serial port "
                                 "for useserial"));
M
Michal Privoznik 已提交
13922 13923
                goto cleanup;
            }
J
Ján Tomko 已提交
13924
            def->os.bios.useserial = VIR_TRISTATE_BOOL_YES;
M
Michal Privoznik 已提交
13925
        } else {
J
Ján Tomko 已提交
13926
            def->os.bios.useserial = VIR_TRISTATE_BOOL_NO;
M
Michal Privoznik 已提交
13927
        }
M
Martin Kletzander 已提交
13928
        VIR_FREE(tmp);
M
Michal Privoznik 已提交
13929 13930
    }

13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944
    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;
    }

13945 13946
    ret = 0;

13947
 cleanup:
13948
    VIR_FREE(tmp);
13949 13950 13951 13952
    VIR_FREE(nodes);
    return ret;
}

13953

G
Gao feng 已提交
13954 13955
static int virDomainIdMapEntrySort(const void *a, const void *b)
{
13956 13957
    const virDomainIdMapEntry *entrya = a;
    const virDomainIdMapEntry *entryb = b;
G
Gao feng 已提交
13958 13959 13960 13961 13962 13963 13964 13965 13966

    if (entrya->start > entryb->start)
        return 1;
    else if (entrya->start < entryb->start)
        return -1;
    else
        return 0;
}

13967 13968 13969 13970 13971 13972 13973 13974 13975
/* 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,
13976
                          xmlNodePtr *node,
13977 13978 13979 13980 13981 13982
                          size_t num)
{
    size_t i;
    virDomainIdMapEntryPtr idmap = NULL;
    xmlNodePtr save_ctxt = ctxt->node;

13983
    if (VIR_ALLOC_N(idmap, num) < 0)
13984 13985 13986 13987 13988 13989 13990
        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) {
13991 13992
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("invalid idmap start/target/count settings"));
13993 13994 13995 13996 13997
            VIR_FREE(idmap);
            goto cleanup;
        }
    }

G
Gao feng 已提交
13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008
    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;
    }

14009
 cleanup:
14010 14011 14012 14013
    ctxt->node = save_ctxt;
    return idmap;
}

14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057
/* Parse the XML definition for an IOThread ID
 *
 * Format is :
 *
 *     <iothreads>4</iothreads>
 *     <iothreadids>
 *       <iothread id='1'/>
 *       <iothread id='3'/>
 *       <iothread id='5'/>
 *       <iothread id='7'/>
 *     </iothreadids>
 */
static virDomainIOThreadIDDefPtr
virDomainIOThreadIDDefParseXML(xmlNodePtr node,
                               xmlXPathContextPtr ctxt)
{
    virDomainIOThreadIDDefPtr iothrid;
    xmlNodePtr oldnode = ctxt->node;
    char *tmp = NULL;

    if (VIR_ALLOC(iothrid) < 0)
        return NULL;

    ctxt->node = node;

    if (!(tmp = virXPathString("string(./@id)", ctxt))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Missing 'id' attribute in <iothread> element"));
        goto error;
    }
    if (virStrToLong_uip(tmp, NULL, 10, &iothrid->iothread_id) < 0 ||
        iothrid->iothread_id == 0) {
        virReportError(VIR_ERR_XML_ERROR,
                        _("invalid iothread 'id' value '%s'"), tmp);
        goto error;
    }

 cleanup:
    VIR_FREE(tmp);
    ctxt->node = oldnode;
    return iothrid;

 error:
    virDomainIOThreadIDDefFree(iothrid);
J
John Ferlan 已提交
14058
    iothrid = NULL;
14059 14060 14061 14062
    goto cleanup;
}


14063
/* Parse the XML definition for a vcpupin
14064 14065 14066 14067
 *
 * vcpupin has the form of
 *   <vcpupin vcpu='0' cpuset='0'/>
 */
14068 14069 14070
static int
virDomainVcpuPinDefParseXML(virDomainDefPtr def,
                            xmlNodePtr node)
14071
{
14072
    virDomainVcpuInfoPtr vcpu;
14073
    unsigned int vcpuid;
14074
    char *tmp = NULL;
14075
    int ret = -1;
14076

14077 14078 14079
    if (!(tmp = virXMLPropString(node, "vcpu"))) {
        virReportError(VIR_ERR_XML_ERROR, "%s", _("missing vcpu id in vcpupin"));
        goto cleanup;
14080
    }
14081

14082 14083 14084
    if (virStrToLong_uip(tmp, NULL, 10, &vcpuid) < 0) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("invalid setting for vcpu '%s'"), tmp);
14085
        goto cleanup;
14086
    }
14087
    VIR_FREE(tmp);
14088

14089 14090 14091 14092 14093 14094 14095 14096 14097
    if (!(vcpu = virDomainDefGetVcpu(def, vcpuid)) ||
        !vcpu->online) {
        /* To avoid the regression when daemon loading domain confs, we can't
         * simply error out if <vcpupin> nodes greater than current vcpus.
         * Ignore them instead. */
        VIR_WARN("Ignoring vcpupin for missing vcpus");
        ret = 0;
        goto cleanup;
    }
14098 14099

    if (!(tmp = virXMLPropString(node, "cpuset"))) {
14100 14101 14102 14103
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("missing cpuset for vcpupin"));
        goto cleanup;
    }
14104

14105 14106 14107 14108
    if (vcpu->cpumask) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("duplicate vcpupin for vcpu '%d'"), vcpuid);
        goto cleanup;
14109
    }
14110

14111 14112
    if (virBitmapParse(tmp, 0, &vcpu->cpumask, VIR_DOMAIN_CPUMASK_LEN) < 0)
        goto cleanup;
14113

14114
    if (virBitmapIsAllClear(vcpu->cpumask)) {
14115 14116
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Invalid value of 'cpuset': %s"), tmp);
14117
        goto cleanup;
14118 14119
    }

14120 14121
    ret = 0;

14122 14123
 cleanup:
    VIR_FREE(tmp);
14124
    return ret;
14125 14126 14127 14128 14129 14130 14131
}


/* Parse the XML definition for a iothreadpin
 * and an iothreadspin has the form
 *   <iothreadpin iothread='1' cpuset='2'/>
 */
14132
static int
14133 14134
virDomainIOThreadPinDefParseXML(xmlNodePtr node,
                                xmlXPathContextPtr ctxt,
14135
                                virDomainDefPtr def)
14136
{
14137 14138
    int ret = -1;
    virDomainIOThreadIDDefPtr iothrid;
14139
    virBitmapPtr cpumask = NULL;
14140 14141 14142 14143 14144 14145
    xmlNodePtr oldnode = ctxt->node;
    unsigned int iothreadid;
    char *tmp = NULL;

    ctxt->node = node;

14146 14147 14148
    if (!(tmp = virXPathString("string(./@iothread)", ctxt))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing iothread id in iothreadpin"));
14149
        goto cleanup;
14150
    }
14151

14152 14153 14154
    if (virStrToLong_uip(tmp, NULL, 10, &iothreadid) < 0) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("invalid setting for iothread '%s'"), tmp);
14155
        goto cleanup;
14156 14157
    }
    VIR_FREE(tmp);
14158

14159 14160 14161
    if (iothreadid == 0) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("zero is an invalid iothread id value"));
14162
        goto cleanup;
14163
    }
14164

14165 14166 14167 14168
    if (!(iothrid = virDomainIOThreadIDFind(def, iothreadid))) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Cannot find 'iothread' : %u"),
                       iothreadid);
J
John Ferlan 已提交
14169
        goto cleanup;
14170 14171
    }

14172
    if (!(tmp = virXMLPropString(node, "cpuset"))) {
14173 14174
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("missing cpuset for iothreadpin"));
14175
        goto cleanup;
14176 14177
    }

14178 14179
    if (virBitmapParse(tmp, 0, &cpumask, VIR_DOMAIN_CPUMASK_LEN) < 0)
        goto cleanup;
14180

14181
    if (virBitmapIsAllClear(cpumask)) {
14182 14183 14184
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Invalid value of 'cpuset': %s"),
                       tmp);
14185
        goto cleanup;
14186 14187
    }

14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198
    if (iothrid->cpumask) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("duplicate iothreadpin for same iothread '%u'"),
                       iothreadid);
        goto cleanup;
    }

    iothrid->cpumask = cpumask;
    cpumask = NULL;
    ret = 0;

14199
 cleanup:
14200
    VIR_FREE(tmp);
14201
    virBitmapFree(cpumask);
14202
    ctxt->node = oldnode;
14203
    return ret;
14204 14205
}

14206

14207 14208 14209 14210
/* Parse the XML definition for emulatorpin.
 * emulatorpin has the form of
 *   <emulatorpin cpuset='0'/>
 */
14211
static virBitmapPtr
14212 14213
virDomainEmulatorPinDefParseXML(xmlNodePtr node)
{
14214
    virBitmapPtr def = NULL;
14215 14216 14217 14218 14219
    char *tmp = NULL;

    if (!(tmp = virXMLPropString(node, "cpuset"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("missing cpuset for emulatorpin"));
14220
        return NULL;
14221 14222
    }

14223 14224 14225 14226 14227 14228 14229 14230 14231 14232
    if (virBitmapParse(tmp, 0, &def, VIR_DOMAIN_CPUMASK_LEN) < 0)
        goto cleanup;

    if (virBitmapIsAllClear(def)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Invalid value of 'cpuset': %s"), tmp);
        virBitmapFree(def);
        def = NULL;
        goto cleanup;
    }
14233

14234
 cleanup:
14235 14236 14237 14238 14239
    VIR_FREE(tmp);
    return def;
}


14240 14241
static virDomainControllerDefPtr
virDomainDefAddController(virDomainDefPtr def, int type, int idx, int model)
14242 14243 14244
{
    virDomainControllerDefPtr cont;

14245
    if (!(cont = virDomainControllerDefNew(type)))
14246 14247 14248 14249
        return NULL;

    if (idx < 0)
        idx = virDomainControllerFindUnusedIndex(def, type);
14250 14251

    cont->idx = idx;
14252
    cont->model = model;
14253

14254
    if (VIR_APPEND_ELEMENT_COPY(def->controllers, def->ncontrollers, cont) < 0) {
14255
        VIR_FREE(cont);
14256
        return NULL;
14257 14258
    }

14259 14260 14261 14262
    return cont;
}


14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316
/**
 * virDomainDefAddUSBController:
 * @def:   the domain
 * @idx:   index for new controller (or -1 for "lowest unused index")
 * @model: VIR_DOMAIN_CONTROLLER_MODEL_USB_* or -1
 *
 * Add a USB controller of the specified model (or default model for
 * current machinetype if model == -1). If model is ich9-usb-ehci,
 * also add companion uhci1, uhci2, and uhci3 controllers at the same
 * index.
 *
 * Returns 0 on success, -1 on failure.
 */
int
virDomainDefAddUSBController(virDomainDefPtr def, int idx, int model)
{
    virDomainControllerDefPtr cont; /* this is a *copy* of the DefPtr */

    cont = virDomainDefAddController(def, VIR_DOMAIN_CONTROLLER_TYPE_USB,
                                     idx, model);
    if (!cont)
        return -1;

    if (model != VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_EHCI1)
        return 0;

    /* When the initial controller is ich9-usb-ehci, also add the
     * companion controllers
     */

    idx = cont->idx; /* in case original request was "-1" */

    if (!(cont = virDomainDefAddController(def, VIR_DOMAIN_CONTROLLER_TYPE_USB,
                                           idx, VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI1)))
        return -1;
    cont->info.mastertype = VIR_DOMAIN_CONTROLLER_MASTER_USB;
    cont->info.master.usb.startport = 0;

    if (!(cont = virDomainDefAddController(def, VIR_DOMAIN_CONTROLLER_TYPE_USB,
                                           idx, VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI2)))
        return -1;
    cont->info.mastertype = VIR_DOMAIN_CONTROLLER_MASTER_USB;
    cont->info.master.usb.startport = 2;

    if (!(cont = virDomainDefAddController(def, VIR_DOMAIN_CONTROLLER_TYPE_USB,
                                           idx, VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI3)))
        return -1;
    cont->info.mastertype = VIR_DOMAIN_CONTROLLER_MASTER_USB;
    cont->info.master.usb.startport = 4;

    return 0;
}


14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331
int
virDomainDefMaybeAddController(virDomainDefPtr def,
                               int type,
                               int idx,
                               int model)
{
    /* skip if a specific index was given and it is already
     * in use for that type of controller
     */
    if (idx >= 0 && virDomainControllerFind(def, type, idx) >= 0)
        return 0;

    if (virDomainDefAddController(def, type, idx, model))
        return 1;
    return -1;
14332 14333
}

E
Eric Blake 已提交
14334

14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363
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;
}


14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374
static int
virDomainHugepagesParseXML(xmlNodePtr node,
                           xmlXPathContextPtr ctxt,
                           virDomainHugePagePtr hugepage)
{
    int ret = -1;
    xmlNodePtr oldnode = ctxt->node;
    char *unit = NULL, *nodeset = NULL;

    ctxt->node = node;

14375 14376
    if (virDomainParseMemory("./@size", "./@unit", ctxt,
                             &hugepage->size, true, false) < 0)
14377 14378
        goto cleanup;

14379
    if (!hugepage->size) {
14380 14381 14382 14383 14384 14385 14386 14387 14388
        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;
14389 14390 14391 14392 14393 14394

        if (virBitmapIsAllClear(hugepage->nodemask)) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Invalid value of 'nodeset': %s"), nodeset);
            goto cleanup;
        }
14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405
    }

    ret = 0;
 cleanup:
    VIR_FREE(unit);
    VIR_FREE(nodeset);
    ctxt->node = oldnode;
    return ret;
}


14406 14407 14408 14409 14410 14411 14412 14413 14414
static virDomainResourceDefPtr
virDomainResourceDefParse(xmlNodePtr node,
                          xmlXPathContextPtr ctxt)
{
    virDomainResourceDefPtr def = NULL;
    xmlNodePtr tmp = ctxt->node;

    ctxt->node = node;

14415
    if (VIR_ALLOC(def) < 0)
14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427
        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;

14428
 error:
14429 14430 14431 14432 14433
    ctxt->node = tmp;
    virDomainResourceDefFree(def);
    return NULL;
}

14434 14435 14436 14437
static int
virDomainDefMaybeAddHostdevSCSIcontroller(virDomainDefPtr def)
{
    /* Look for any hostdev scsi dev */
14438
    size_t i;
14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450
    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;
        }
    }

14451 14452 14453
    if (maxController == -1)
        return 0;

14454 14455 14456 14457 14458 14459 14460
    for (i = 0; i <= maxController; i++) {
        if (virDomainDefMaybeAddController(def, VIR_DOMAIN_CONTROLLER_TYPE_SCSI, i, -1) < 0)
            return -1;
    }

    return 0;
}
14461

14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497
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;
}

14498 14499 14500 14501 14502 14503

static virBitmapPtr
virDomainSchedulerParse(xmlNodePtr node,
                        const char *name,
                        virProcessSchedPolicy *policy,
                        int *priority)
14504
{
14505
    virBitmapPtr ret = NULL;
14506
    char *tmp = NULL;
14507
    int pol = 0;
14508

14509
    if (!(tmp = virXMLPropString(node, name))) {
14510 14511 14512 14513 14514 14515
        virReportError(VIR_ERR_XML_ERROR,
                       _("Missing attribute '%s' in element '%sched'"),
                       name, name);
        goto error;
    }

14516
    if (virBitmapParse(tmp, 0, &ret, VIR_DOMAIN_CPUMASK_LEN) < 0)
14517 14518
        goto error;

14519
    if (virBitmapIsAllClear(ret)) {
14520
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
14521
                       _("'%s' scheduler bitmap '%s' is empty"),
14522 14523 14524
                       name, tmp);
        goto error;
    }
14525

14526 14527
    VIR_FREE(tmp);

14528 14529 14530 14531 14532 14533 14534 14535
    if (!(tmp = virXMLPropString(node, "scheduler"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing scheduler attribute"));
        goto error;
    }

    if ((pol = virProcessSchedPolicyTypeFromString(tmp)) <= 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
14536
                       _("Invalid scheduler attribute: '%s'"), tmp);
14537 14538
        goto error;
    }
14539
    *policy = pol;
14540 14541

    VIR_FREE(tmp);
14542 14543 14544 14545

    if (pol == VIR_PROC_POLICY_FIFO ||
        pol == VIR_PROC_POLICY_RR) {
        if (!(tmp = virXMLPropString(node, "priority"))) {
14546 14547
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("Missing scheduler priority"));
14548 14549
            goto error;
        }
14550 14551

        if (virStrToLong_i(tmp, NULL, 10, priority) < 0) {
14552 14553 14554
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("Invalid value for element priority"));
            goto error;
14555
        }
14556
        VIR_FREE(tmp);
14557 14558
    }

14559
    return ret;
14560 14561 14562

 error:
    VIR_FREE(tmp);
14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586
    virBitmapFree(ret);
    return NULL;
}


static int
virDomainThreadSchedParse(xmlNodePtr node,
                          unsigned int minid,
                          unsigned int maxid,
                          const char *name,
                          virDomainThreadSchedParamPtr sp)
{
    if (!(sp->ids = virDomainSchedulerParse(node, name, &sp->policy,
                                            &sp->priority)))
        return -1;

    if (virBitmapNextSetBit(sp->ids, -1) < minid ||
        virBitmapLastSetBit(sp->ids) > maxid) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("%sched bitmap is out of range"), name);
        return -1;
    }

    return 0;
14587
}
14588

14589 14590 14591 14592 14593 14594 14595

static int
virDomainVcpuParse(virDomainDefPtr def,
                   xmlXPathContextPtr ctxt)
{
    int n;
    char *tmp = NULL;
14596
    unsigned int maxvcpus;
14597
    unsigned int vcpus;
14598 14599
    int ret = -1;

14600
    if ((n = virXPathUInt("string(./vcpu[1])", ctxt, &maxvcpus)) < 0) {
14601 14602 14603 14604 14605 14606
        if (n == -2) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("maximum vcpus count must be an integer"));
            goto cleanup;
        }

14607
        maxvcpus = 1;
14608 14609
    }

14610 14611 14612
    if (virDomainDefSetVcpusMax(def, maxvcpus) < 0)
        goto cleanup;

14613
    if ((n = virXPathUInt("string(./vcpu[1]/@current)", ctxt, &vcpus)) < 0) {
14614 14615 14616 14617 14618 14619
        if (n == -2) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("current vcpus count must be an integer"));
            goto cleanup;
        }

14620
        vcpus = maxvcpus;
14621 14622
    }

14623 14624 14625
    if (virDomainDefSetVcpus(def, vcpus) < 0)
        goto cleanup;

14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664
    tmp = virXPathString("string(./vcpu[1]/@placement)", ctxt);
    if (tmp) {
        if ((def->placement_mode =
             virDomainCpuPlacementModeTypeFromString(tmp)) < 0) {
             virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                            _("Unsupported CPU placement mode '%s'"),
                            tmp);
             goto cleanup;
        }
        VIR_FREE(tmp);
    } else {
        def->placement_mode = VIR_DOMAIN_CPU_PLACEMENT_MODE_STATIC;
    }

    if (def->placement_mode != VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO) {
        tmp = virXPathString("string(./vcpu[1]/@cpuset)", ctxt);
        if (tmp) {
            if (virBitmapParse(tmp, 0, &def->cpumask,
                               VIR_DOMAIN_CPUMASK_LEN) < 0)
                goto cleanup;

            if (virBitmapIsAllClear(def->cpumask)) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("Invalid value of 'cpuset': %s"), tmp);
                goto cleanup;
            }

            VIR_FREE(tmp);
        }
    }

    ret = 0;

 cleanup:
    VIR_FREE(tmp);

    return ret;
}

14665
static virDomainDefPtr
14666
virDomainDefParseXML(xmlDocPtr xml,
14667 14668
                     xmlNodePtr root,
                     xmlXPathContextPtr ctxt,
14669 14670
                     virCapsPtr caps,
                     virDomainXMLOptionPtr xmlopt,
14671
                     unsigned int flags)
14672 14673 14674
{
    xmlNodePtr *nodes = NULL, node = NULL;
    char *tmp = NULL;
14675
    size_t i, j;
J
John Ferlan 已提交
14676
    int n, virtType;
14677
    long id = -1;
14678
    virDomainDefPtr def;
14679
    bool uuid_generated = false;
14680
    virHashTablePtr bootHash = NULL;
14681 14682
    bool usb_none = false;
    bool usb_other = false;
14683
    bool usb_master = false;
14684
    bool primaryVideo = false;
14685
    char *netprefix = NULL;
14686

14687 14688
    if (flags & VIR_DOMAIN_DEF_PARSE_VALIDATE) {
        char *schema = virFileFindResource("domain.rng",
14689
                                           abs_topsrcdir "/docs/schemas",
14690 14691 14692 14693 14694 14695 14696 14697 14698 14699
                                           PKGDATADIR "/schemas");
        if (!schema)
            return NULL;
        if (virXMLValidateAgainstSchema(schema, xml) < 0) {
            VIR_FREE(schema);
            return NULL;
        }
        VIR_FREE(schema);
    }

14700
    if (!(def = virDomainDefNew()))
14701
        return NULL;
14702

14703
    if (!(flags & VIR_DOMAIN_DEF_PARSE_INACTIVE))
E
Eric Blake 已提交
14704
        if (virXPathLong("string(./@id)", ctxt, &id) < 0)
14705 14706
            id = -1;
    def->id = (int)id;
14707

14708
    /* Find out what type of virtualization to use */
14709
    if (!(tmp = virXPathString("string(./@type)", ctxt))) {
14710 14711
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing domain type attribute"));
14712 14713 14714
        goto error;
    }

J
John Ferlan 已提交
14715
    if ((virtType = virDomainVirtTypeFromString(tmp)) < 0) {
14716
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
14717
                       _("invalid domain type %s"), tmp);
14718 14719
        goto error;
    }
J
John Ferlan 已提交
14720
    def->virtType = virtType;
14721 14722
    VIR_FREE(tmp);

14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766
    def->os.bootloader = virXPathString("string(./bootloader)", ctxt);
    def->os.bootloaderArgs = virXPathString("string(./bootloader_args)", ctxt);

    tmp = virXPathString("string(./os/type[1])", ctxt);
    if (!tmp) {
        if (def->os.bootloader) {
            def->os.type = VIR_DOMAIN_OSTYPE_XEN;
        } else {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("an os <type> must be specified"));
            goto error;
        }
    } else {
        if ((def->os.type = virDomainOSTypeFromString(tmp)) < 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown OS type '%s'"), tmp);
            goto error;
        }
        VIR_FREE(tmp);
    }

    /*
     * 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 (def->os.type == VIR_DOMAIN_OSTYPE_LINUX &&
        def->virtType == VIR_DOMAIN_VIRT_XEN) {
        def->os.type = VIR_DOMAIN_OSTYPE_XEN;
    }

    tmp = virXPathString("string(./os/type[1]/@arch)", ctxt);
    if (tmp && !(def->os.arch = virArchFromString(tmp))) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Unknown architecture %s"),
                       tmp);
        goto error;
    }
    VIR_FREE(tmp);

    def->os.machine = virXPathString("string(./os/type[1]/@machine)", ctxt);
    def->emulator = virXPathString("string(./devices/emulator[1])", ctxt);

    if (!(flags & VIR_DOMAIN_DEF_PARSE_SKIP_OSTYPE_CHECKS)) {
14767 14768 14769 14770 14771 14772 14773 14774
        /* If the logic here seems fairly arbitrary, that's because it is :)
         * This is duplicating how the code worked before
         * CapabilitiesDomainDataLookup was added. We can simplify this,
         * but it would take a bit of work because the test suite fails
         * in numerous minor ways. */
        bool use_virttype = ((def->os.arch == VIR_ARCH_NONE) ||
            !def->os.machine);
        virCapsDomainDataPtr capsdata = NULL;
14775

14776
        if (!(capsdata = virCapabilitiesDomainDataLookup(caps, def->os.type,
14777
                def->os.arch, use_virttype ? def->virtType : VIR_DOMAIN_VIRT_NONE,
14778 14779
                NULL, NULL)))
            goto error;
14780

14781 14782 14783 14784 14785 14786
        if (!def->os.arch)
            def->os.arch = capsdata->arch;
        if ((!def->os.machine &&
             VIR_STRDUP(def->os.machine, capsdata->machinetype) < 0)) {
            VIR_FREE(capsdata);
            goto error;
14787
        }
14788
        VIR_FREE(capsdata);
14789 14790
    }

14791
    /* Extract domain name */
14792
    if (!(def->name = virXPathString("string(./name[1])", ctxt))) {
14793
        virReportError(VIR_ERR_NO_NAME, NULL);
14794 14795 14796
        goto error;
    }

14797 14798 14799
    /* 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. */
14800
    tmp = virXPathString("string(./uuid[1])", ctxt);
14801
    if (!tmp) {
14802
        if (virUUIDGenerate(def->uuid)) {
14803 14804
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Failed to generate UUID"));
14805 14806
            goto error;
        }
14807
        uuid_generated = true;
14808 14809
    } else {
        if (virUUIDParse(tmp, def->uuid) < 0) {
14810 14811
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("malformed uuid element"));
14812 14813 14814 14815 14816
            goto error;
        }
        VIR_FREE(tmp);
    }

14817 14818 14819
    /* Extract short description of domain (title) */
    def->title = virXPathString("string(./title[1])", ctxt);
    if (def->title && strchr(def->title, '\n')) {
14820 14821
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Domain title can't contain newlines"));
14822 14823 14824
        goto error;
    }

14825
    /* Extract documentation if present */
14826
    def->description = virXPathString("string(./description[1])", ctxt);
14827

E
Eric Blake 已提交
14828 14829
    /* analysis of security label, done early even though we format it
     * late, so devices can refer to this for defaults */
14830
    if (virSecurityLabelDefsParseXML(def, ctxt, caps, flags) == -1)
E
Eric Blake 已提交
14831 14832
        goto error;

14833
    /* Extract domain memory */
14834
    if (virDomainParseMemory("./memory[1]", NULL, ctxt,
14835
                             &def->mem.total_memory, false, true) < 0)
14836 14837
        goto error;

14838
    if (virDomainParseMemory("./currentMemory[1]", NULL, ctxt,
14839
                             &def->mem.cur_balloon, false, true) < 0)
E
Eric Blake 已提交
14840
        goto error;
14841

14842 14843 14844 14845 14846 14847 14848 14849 14850 14851
    if (virDomainParseMemory("./maxMemory[1]", NULL, ctxt,
                             &def->mem.max_memory, false, false) < 0)
        goto error;

    if (virXPathUInt("string(./maxMemory[1]/@slots)", ctxt, &def->mem.memory_slots) == -2) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Failed to parse memory slot count"));
        goto error;
    }

14852
    /* and info about it */
14853
    if ((tmp = virXPathString("string(./memory[1]/@dumpCore)", ctxt)) &&
J
Ján Tomko 已提交
14854
        (def->mem.dump_core = virTristateSwitchTypeFromString(tmp)) <= 0) {
14855
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
14856 14857
                       _("Invalid memory core dump attribute value '%s'"), tmp);
        goto error;
14858
    }
14859
    VIR_FREE(tmp);
14860

14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908
    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;
        }
    }
14909

14910 14911 14912
    if ((node = virXPathNode("./memoryBacking/nosharepages", ctxt)))
        def->mem.nosharepages = true;

14913 14914 14915
    if (virXPathBoolean("boolean(./memoryBacking/locked)", ctxt))
        def->mem.locked = true;

14916 14917 14918 14919 14920
    /* Extract blkio cgroup tunables */
    if (virXPathUInt("string(./blkiotune/weight)", ctxt,
                     &def->blkio.weight) < 0)
        def->blkio.weight = 0;

14921
    if ((n = virXPathNodeSet("./blkiotune/device", ctxt, &nodes)) < 0) {
14922 14923
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot extract blkiotune nodes"));
14924 14925 14926
        goto error;
    }
    if (n && VIR_ALLOC_N(def->blkio.devices, n) < 0)
14927
        goto error;
14928 14929

    for (i = 0; i < n; i++) {
14930 14931
        if (virDomainBlkioDeviceParseXML(nodes[i],
                                         &def->blkio.devices[i]) < 0)
14932 14933
            goto error;
        def->blkio.ndevices++;
14934 14935 14936
        for (j = 0; j < i; j++) {
            if (STREQ(def->blkio.devices[j].path,
                      def->blkio.devices[i].path)) {
14937
                virReportError(VIR_ERR_XML_ERROR,
14938
                               _("duplicate blkio device path '%s'"),
14939
                               def->blkio.devices[i].path);
14940 14941 14942
                goto error;
            }
        }
14943 14944 14945
    }
    VIR_FREE(nodes);

14946
    /* Extract other memory tunables */
14947 14948
    if (virDomainParseMemoryLimit("./memtune/hard_limit[1]", NULL, ctxt,
                                  &def->mem.hard_limit) < 0)
E
Eric Blake 已提交
14949
        goto error;
14950

14951 14952
    if (virDomainParseMemoryLimit("./memtune/soft_limit[1]", NULL, ctxt,
                                  &def->mem.soft_limit) < 0)
E
Eric Blake 已提交
14953
        goto error;
14954

14955
    if (virDomainParseMemory("./memtune/min_guarantee[1]", NULL, ctxt,
14956
                             &def->mem.min_guarantee, false, false) < 0)
E
Eric Blake 已提交
14957
        goto error;
14958

14959 14960
    if (virDomainParseMemoryLimit("./memtune/swap_hard_limit[1]", NULL, ctxt,
                                  &def->mem.swap_hard_limit) < 0)
E
Eric Blake 已提交
14961
        goto error;
14962

14963
    if (virDomainVcpuParse(def, ctxt) < 0)
14964
        goto error;
14965

14966 14967 14968 14969 14970 14971 14972 14973 14974
    /* 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);

14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000
    /* Extract any iothread id's defined */
    if ((n = virXPathNodeSet("./iothreadids/iothread", ctxt, &nodes)) < 0)
        goto error;

    if (n > def->iothreads)
        def->iothreads = n;

    if (n && VIR_ALLOC_N(def->iothreadids, n) < 0)
        goto error;

    for (i = 0; i < n; i++) {
        virDomainIOThreadIDDefPtr iothrid = NULL;
        if (!(iothrid = virDomainIOThreadIDDefParseXML(nodes[i], ctxt)))
            goto error;

        if (virDomainIOThreadIDFind(def, iothrid->iothread_id)) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("duplicate iothread id '%u' found"),
                           iothrid->iothread_id);
            virDomainIOThreadIDDefFree(iothrid);
            goto error;
        }
        def->iothreadids[def->niothreadids++] = iothrid;
    }
    VIR_FREE(nodes);

15001 15002
    if (virDomainIOThreadIDDefArrayInit(def) < 0)
        goto error;
15003

15004
    /* Extract cpu tunables. */
15005 15006
    if ((n = virXPathULong("string(./cputune/shares[1])", ctxt,
                           &def->cputune.shares)) < -1) {
15007 15008 15009
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("can't parse cputune shares value"));
        goto error;
15010 15011
    } else if (n == 0) {
        def->cputune.sharesSpecified = true;
15012
    }
15013

15014
    if (virXPathULongLong("string(./cputune/period[1])", ctxt,
15015 15016 15017 15018 15019
                          &def->cputune.period) < -1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("can't parse cputune period value"));
        goto error;
    }
15020

15021 15022 15023 15024 15025 15026 15027 15028
    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;
    }

15029
    if (virXPathLongLong("string(./cputune/quota[1])", ctxt,
15030 15031 15032 15033 15034
                         &def->cputune.quota) < -1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("can't parse cputune quota value"));
        goto error;
    }
15035

15036 15037
    if (def->cputune.quota > 0 &&
        (def->cputune.quota < 1000 ||
E
Eric Blake 已提交
15038
         def->cputune.quota > 18446744073709551LL)) {
15039 15040 15041 15042 15043 15044
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Value of cputune quota must be in range "
                         "[1000, 18446744073709551]"));
        goto error;
    }

15045
    if (virXPathULongLong("string(./cputune/emulator_period[1])", ctxt,
15046 15047 15048 15049 15050
                          &def->cputune.emulator_period) < -1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("can't parse cputune emulator period value"));
        goto error;
    }
15051

15052 15053 15054 15055 15056 15057 15058 15059 15060
    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;
    }

15061
    if (virXPathLongLong("string(./cputune/emulator_quota[1])", ctxt,
15062 15063 15064
                         &def->cputune.emulator_quota) < -1) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("can't parse cputune emulator quota value"));
15065 15066 15067
        goto error;
    }

15068 15069
    if (def->cputune.emulator_quota > 0 &&
        (def->cputune.emulator_quota < 1000 ||
E
Eric Blake 已提交
15070
         def->cputune.emulator_quota > 18446744073709551LL)) {
15071 15072 15073 15074 15075 15076
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Value of cputune emulator_quota must be in range "
                         "[1000, 18446744073709551]"));
        goto error;
    }

15077 15078 15079
    if ((n = virXPathNodeSet("./cputune/vcpupin", ctxt, &nodes)) < 0)
        goto error;

15080
    for (i = 0; i < n; i++) {
15081
        if (virDomainVcpuPinDefParseXML(def, nodes[i]))
15082 15083 15084 15085
            goto error;
    }
    VIR_FREE(nodes);

T
Tang Chen 已提交
15086 15087 15088 15089 15090 15091 15092
    if ((n = virXPathNodeSet("./cputune/emulatorpin", ctxt, &nodes)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot extract emulatorpin nodes"));
        goto error;
    }

    if (n) {
15093 15094 15095 15096 15097 15098
        if (n > 1) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("only one emulatorpin is supported"));
            VIR_FREE(nodes);
            goto error;
        }
T
Tang Chen 已提交
15099

15100
        if (!(def->cputune.emulatorpin = virDomainEmulatorPinDefParseXML(nodes[0])))
15101
            goto error;
T
Tang Chen 已提交
15102 15103 15104
    }
    VIR_FREE(nodes);

15105 15106 15107 15108 15109 15110 15111

    if ((n = virXPathNodeSet("./cputune/iothreadpin", ctxt, &nodes)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot extract iothreadpin nodes"));
        goto error;
    }

15112
    for (i = 0; i < n; i++) {
15113
        if (virDomainIOThreadPinDefParseXML(nodes[i], ctxt, def) < 0)
15114
            goto error;
15115 15116 15117
    }
    VIR_FREE(nodes);

15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129
    if ((n = virXPathNodeSet("./cputune/vcpusched", ctxt, &nodes)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot extract vcpusched nodes"));
        goto error;
    }
    if (n) {
        if (VIR_ALLOC_N(def->cputune.vcpusched, n) < 0)
            goto error;
        def->cputune.nvcpusched = n;

        for (i = 0; i < def->cputune.nvcpusched; i++) {
            if (virDomainThreadSchedParse(nodes[i],
15130 15131
                                          0,
                                          virDomainDefGetVcpusMax(def) - 1,
15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154
                                          "vcpus",
                                          &def->cputune.vcpusched[i]) < 0)
                goto error;

            for (j = 0; j < i; j++) {
                if (virBitmapOverlaps(def->cputune.vcpusched[i].ids,
                                      def->cputune.vcpusched[j].ids)) {
                    virReportError(VIR_ERR_XML_DETAIL, "%s",
                                   _("vcpusched attributes 'vcpus' "
                                     "must not overlap"));
                    goto error;
                }
            }
        }
    }
    VIR_FREE(nodes);

    if ((n = virXPathNodeSet("./cputune/iothreadsched", ctxt, &nodes)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot extract iothreadsched nodes"));
        goto error;
    }
    if (n) {
15155
        if (n > def->niothreadids) {
15156 15157 15158 15159 15160 15161 15162 15163 15164 15165
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("too many iothreadsched nodes in cputune"));
            goto error;
        }

        if (VIR_ALLOC_N(def->cputune.iothreadsched, n) < 0)
            goto error;
        def->cputune.niothreadsched = n;

        for (i = 0; i < def->cputune.niothreadsched; i++) {
15166 15167
            ssize_t pos = -1;

15168
            if (virDomainThreadSchedParse(nodes[i],
15169
                                          1, UINT_MAX,
15170 15171 15172 15173
                                          "iothreads",
                                          &def->cputune.iothreadsched[i]) < 0)
                goto error;

15174 15175 15176 15177 15178 15179 15180 15181 15182 15183
            while ((pos = virBitmapNextSetBit(def->cputune.iothreadsched[i].ids,
                                              pos)) > -1) {
                if (!virDomainIOThreadIDFind(def, pos)) {
                    virReportError(VIR_ERR_XML_DETAIL, "%s",
                                   _("iothreadsched attribute 'iothreads' "
                                     "uses undefined iothread ids"));
                    goto error;
                }
            }

15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195
            for (j = 0; j < i; j++) {
                if (virBitmapOverlaps(def->cputune.iothreadsched[i].ids,
                                      def->cputune.iothreadsched[j].ids)) {
                    virReportError(VIR_ERR_XML_DETAIL, "%s",
                                   _("iothreadsched attributes 'iothreads' "
                                     "must not overlap"));
                    goto error;
                }
            }
        }
    }
    VIR_FREE(nodes);
15196

M
Martin Kletzander 已提交
15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207
    /* 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 &&
15208
            virDomainDefGetVcpusMax(def) >
M
Martin Kletzander 已提交
15209 15210 15211 15212 15213 15214
            def->cpu->sockets * def->cpu->cores * def->cpu->threads) {
            virReportError(VIR_ERR_XML_DETAIL, "%s",
                           _("Maximum CPUs greater than topology limit"));
            goto error;
        }

15215 15216
    }

15217
    if (virDomainNumaDefCPUParseXML(def->numa, ctxt) < 0)
15218 15219
        goto error;

15220
    if (virDomainNumaGetCPUCountTotal(def->numa) > virDomainDefGetVcpusMax(def)) {
15221 15222 15223 15224
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Number of CPUs in <numa> exceeds the"
                         " <vcpu> count"));
        goto error;
M
Martin Kletzander 已提交
15225 15226
    }

15227
    if (virDomainNumaGetMaxCPUID(def->numa) >= virDomainDefGetVcpusMax(def)) {
15228 15229 15230 15231 15232
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("CPU IDs in <numa> exceed the <vcpu> count"));
        goto error;
    }

15233
    if (virDomainNumatuneParseXML(def->numa,
15234 15235 15236
                                  def->placement_mode ==
                                  VIR_DOMAIN_CPU_PLACEMENT_MODE_STATIC,
                                  ctxt) < 0)
15237 15238
        goto error;

15239
    if (virDomainNumatuneHasPlacementAuto(def->numa) &&
15240
        !def->cpumask && !virDomainDefHasVcpuPin(def) &&
15241 15242
        !def->cputune.emulatorpin &&
        !virDomainIOThreadIDArrayHasPin(def))
15243 15244
        def->placement_mode = VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO;

15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261
    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);

15262
    if ((n = virXPathNodeSet("./features/*", ctxt, &nodes)) < 0)
15263
        goto error;
15264

15265
    for (i = 0; i < n; i++) {
15266 15267
        int val = virDomainFeatureTypeFromString((const char *)nodes[i]->name);
        if (val < 0) {
15268
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15269
                           _("unexpected feature '%s'"), nodes[i]->name);
15270 15271
            goto error;
        }
15272

15273
        switch ((virDomainFeature) val) {
15274 15275
        case VIR_DOMAIN_FEATURE_APIC:
            if ((tmp = virXPathString("string(./features/apic/@eoi)", ctxt))) {
15276
                int eoi;
J
Ján Tomko 已提交
15277
                if ((eoi = virTristateSwitchTypeFromString(tmp)) <= 0) {
15278
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15279
                                   _("unknown value for attribute eoi: '%s'"),
15280 15281
                                   tmp);
                    goto error;
15282
                }
15283 15284
                def->apic_eoi = eoi;
                VIR_FREE(tmp);
15285
            }
15286 15287 15288 15289 15290 15291 15292
            /* 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:
15293
        case VIR_DOMAIN_FEATURE_KVM:
J
Ján Tomko 已提交
15294
            def->features[val] = VIR_TRISTATE_SWITCH_ON;
15295 15296
            break;

15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308
        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 已提交
15309
                def->features[val] = VIR_TRISTATE_SWITCH_ABSENT;
15310 15311 15312
            }
            ctxt->node = node;
            break;
15313 15314

        case VIR_DOMAIN_FEATURE_PMU:
15315
        case VIR_DOMAIN_FEATURE_PVSPINLOCK:
15316
        case VIR_DOMAIN_FEATURE_VMPORT:
15317 15318 15319
            node = ctxt->node;
            ctxt->node = nodes[i];
            if ((tmp = virXPathString("string(./@state)", ctxt))) {
J
Ján Tomko 已提交
15320
                if ((def->features[val] = virTristateSwitchTypeFromString(tmp)) == -1) {
15321
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
Y
Yuri Chornoivan 已提交
15322
                                   _("unknown state attribute '%s' of feature '%s'"),
15323 15324 15325
                                   tmp, virDomainFeatureTypeToString(val));
                    goto error;
                }
15326
                VIR_FREE(tmp);
15327
            } else {
J
Ján Tomko 已提交
15328
                def->features[val] = VIR_TRISTATE_SWITCH_ON;
15329 15330 15331 15332
            }
            ctxt->node = node;
            break;

M
Michal Privoznik 已提交
15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348
        case VIR_DOMAIN_FEATURE_GIC:
            node = ctxt->node;
            ctxt->node = nodes[i];
            if ((tmp = virXPathString("string(./@version)", ctxt))) {
                if (virStrToLong_uip(tmp, NULL, 10, &def->gic_version) < 0 ||
                    def->gic_version == 0) {
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("malformed gic version: %s"), tmp);
                    goto error;
                }
                VIR_FREE(tmp);
            }
            def->features[val] = VIR_TRISTATE_SWITCH_ON;
            ctxt->node = node;
            break;

15349
        /* coverity[dead_error_begin] */
15350 15351
        case VIR_DOMAIN_FEATURE_LAST:
            break;
15352 15353
        }
    }
15354
    VIR_FREE(nodes);
15355

J
Ján Tomko 已提交
15356
    if (def->features[VIR_DOMAIN_FEATURE_HYPERV] == VIR_TRISTATE_SWITCH_ON) {
15357 15358 15359 15360 15361 15362 15363 15364 15365
        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) {
15366
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15367 15368 15369 15370 15371 15372 15373
                               _("unsupported HyperV Enlightenment feature: %s"),
                               nodes[i]->name);
                goto error;
            }

            ctxt->node = nodes[i];

15374
            switch ((virDomainHyperv) feature) {
15375
                case VIR_DOMAIN_HYPERV_RELAXED:
15376
                case VIR_DOMAIN_HYPERV_VAPIC:
15377 15378 15379 15380 15381 15382 15383 15384
                    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 已提交
15385
                    if ((value = virTristateSwitchTypeFromString(tmp)) < 0) {
15386
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15387 15388 15389 15390 15391 15392
                                       _("invalid value of state argument "
                                         "for HyperV Enlightenment feature '%s'"),
                                       nodes[i]->name);
                        goto error;
                    }

15393
                    VIR_FREE(tmp);
15394 15395 15396
                    def->hyperv_features[feature] = value;
                    break;

15397 15398 15399 15400 15401 15402 15403 15404 15405
                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 已提交
15406
                    if ((value = virTristateSwitchTypeFromString(tmp)) < 0) {
15407
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15408 15409 15410 15411 15412 15413 15414
                                       _("invalid value of state argument "
                                         "for HyperV Enlightenment feature '%s'"),
                                       nodes[i]->name);
                        goto error;
                    }

                    VIR_FREE(tmp);
J
Ján Tomko 已提交
15415
                    if (value == VIR_TRISTATE_SWITCH_ON) {
15416 15417 15418 15419 15420 15421
                        if (virXPathUInt("string(./@retries)", ctxt,
                                     &def->hyperv_spinlocks) < 0) {
                            virReportError(VIR_ERR_XML_ERROR, "%s",
                                           _("invalid HyperV spinlock retry count"));
                            goto error;
                        }
15422

15423 15424 15425 15426 15427 15428
                        if (def->hyperv_spinlocks < 0xFFF) {
                            virReportError(VIR_ERR_XML_ERROR, "%s",
                                           _("HyperV spinlock retry count must be "
                                             "at least 4095"));
                            goto error;
                        }
15429 15430 15431 15432
                    }
                    def->hyperv_features[feature] = value;
                    break;

15433
                /* coverity[dead_error_begin] */
15434 15435 15436 15437 15438 15439 15440 15441
                case VIR_DOMAIN_HYPERV_LAST:
                    break;
            }
        }
        VIR_FREE(nodes);
        ctxt->node = node;
    }

15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481
    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;

15482
                /* coverity[dead_error_begin] */
15483 15484 15485 15486 15487 15488 15489 15490
                case VIR_DOMAIN_KVM_LAST:
                    break;
            }
        }
        VIR_FREE(nodes);
        ctxt->node = node;
    }

15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506
    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 已提交
15507
                if ((def->caps_features[val] = virTristateSwitchTypeFromString(tmp)) == -1) {
15508 15509 15510 15511 15512 15513 15514
                    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 已提交
15515
                def->caps_features[val] = VIR_TRISTATE_SWITCH_ON;
15516 15517 15518 15519 15520 15521
            }
            ctxt->node = node;
        }
    }
    VIR_FREE(nodes);

15522 15523 15524 15525 15526
    if (virDomainEventActionParseXML(ctxt, "on_reboot",
                                     "string(./on_reboot[1])",
                                     &def->onReboot,
                                     VIR_DOMAIN_LIFECYCLE_RESTART,
                                     virDomainLifecycleTypeFromString) < 0)
15527 15528
        goto error;

15529 15530 15531 15532 15533
    if (virDomainEventActionParseXML(ctxt, "on_poweroff",
                                     "string(./on_poweroff[1])",
                                     &def->onPoweroff,
                                     VIR_DOMAIN_LIFECYCLE_DESTROY,
                                     virDomainLifecycleTypeFromString) < 0)
15534 15535
        goto error;

15536 15537 15538 15539 15540
    if (virDomainEventActionParseXML(ctxt, "on_crash",
                                     "string(./on_crash[1])",
                                     &def->onCrash,
                                     VIR_DOMAIN_LIFECYCLE_CRASH_DESTROY,
                                     virDomainLifecycleCrashTypeFromString) < 0)
15541 15542
        goto error;

15543 15544 15545 15546 15547 15548 15549
    if (virDomainEventActionParseXML(ctxt, "on_lockfailure",
                                     "string(./on_lockfailure[1])",
                                     &def->onLockFailure,
                                     VIR_DOMAIN_LOCK_FAILURE_DEFAULT,
                                     virDomainLockFailureTypeFromString) < 0)
        goto error;

15550 15551 15552 15553 15554 15555 15556 15557 15558 15559
    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;

15560 15561
    if ((tmp = virXPathString("string(./clock/@offset)", ctxt)) &&
        (def->clock.offset = virDomainClockOffsetTypeFromString(tmp)) < 0) {
15562
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15563 15564
                       _("unknown clock offset '%s'"), tmp);
        goto error;
15565
    }
15566 15567
    VIR_FREE(tmp);

15568
    switch (def->clock.offset) {
15569 15570 15571 15572 15573 15574 15575
    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 {
15576 15577
                if (virStrToLong_ll(tmp, NULL, 10,
                                    &def->clock.data.variable.adjustment) < 0) {
15578 15579 15580
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("unknown clock adjustment '%s'"),
                                   tmp);
15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598
                    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;

15599 15600
    case VIR_DOMAIN_CLOCK_OFFSET_VARIABLE:
        if (virXPathLongLong("number(./clock/@adjustment)", ctxt,
15601 15602
                             &def->clock.data.variable.adjustment) < 0)
            def->clock.data.variable.adjustment = 0;
15603 15604 15605
        if (virXPathLongLong("number(./clock/@adjustment0)", ctxt,
                             &def->clock.data.variable.adjustment0) < 0)
            def->clock.data.variable.adjustment0 = 0;
15606 15607 15608
        tmp = virXPathString("string(./clock/@basis)", ctxt);
        if (tmp) {
            if ((def->clock.data.variable.basis = virDomainClockBasisTypeFromString(tmp)) < 0) {
15609
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
15610
                               _("unknown clock basis '%s'"), tmp);
15611 15612 15613 15614 15615 15616
                goto error;
            }
            VIR_FREE(tmp);
        } else {
            def->clock.data.variable.basis = VIR_DOMAIN_CLOCK_BASIS_UTC;
        }
15617 15618 15619 15620 15621
        break;

    case VIR_DOMAIN_CLOCK_OFFSET_TIMEZONE:
        def->clock.data.timezone = virXPathString("string(./clock/@timezone)", ctxt);
        if (!def->clock.data.timezone) {
15622 15623
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("missing 'timezone' attribute for clock with offset='timezone'"));
15624 15625
            goto error;
        }
15626 15627
        break;
    }
15628

15629
    if ((n = virXPathNodeSet("./clock/timer", ctxt, &nodes)) < 0)
15630
        goto error;
15631

15632
    if (n && VIR_ALLOC_N(def->clock.timers, n) < 0)
15633
        goto error;
15634

15635
    for (i = 0; i < n; i++) {
15636
        virDomainTimerDefPtr timer = virDomainTimerDefParseXML(nodes[i],
E
Eric Blake 已提交
15637
                                                               ctxt);
15638 15639 15640 15641 15642 15643 15644
        if (!timer)
            goto error;

        def->clock.timers[def->clock.ntimers++] = timer;
    }
    VIR_FREE(nodes);

15645

15646 15647 15648 15649 15650 15651 15652 15653 15654
    /*
     * 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)
     */

15655
    if (def->os.type == VIR_DOMAIN_OSTYPE_EXE) {
15656
        def->os.init = virXPathString("string(./os/init[1])", ctxt);
15657
        def->os.cmdline = virXPathString("string(./os/cmdline[1])", ctxt);
15658

15659
        if ((n = virXPathNodeSet("./os/initarg", ctxt, &nodes)) < 0)
15660 15661 15662
            goto error;

        if (VIR_ALLOC_N(def->os.initargv, n+1) < 0)
15663
            goto error;
15664
        for (i = 0; i < n; i++) {
15665 15666
            if (!nodes[i]->children ||
                !nodes[i]->children->content) {
15667 15668
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("No data supplied for <initarg> element"));
15669 15670
                goto error;
            }
15671 15672 15673
            if (VIR_STRDUP(def->os.initargv[i],
                           (const char*) nodes[i]->children->content) < 0)
                goto error;
15674 15675 15676
        }
        def->os.initargv[n] = NULL;
        VIR_FREE(nodes);
15677 15678
    }

15679 15680 15681
    if (def->os.type == VIR_DOMAIN_OSTYPE_XEN ||
        def->os.type == VIR_DOMAIN_OSTYPE_HVM ||
        def->os.type == VIR_DOMAIN_OSTYPE_UML) {
15682 15683
        xmlNodePtr loader_node;

15684 15685 15686
        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);
15687
        def->os.dtb = virXPathString("string(./os/dtb[1])", ctxt);
15688
        def->os.root = virXPathString("string(./os/root[1])", ctxt);
15689 15690 15691 15692 15693 15694 15695 15696
        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);
15697
            def->os.loader->templt = virXPathString("string(./os/nvram[1]/@template)", ctxt);
15698
        }
15699
    }
15700

15701
    if (def->os.type == VIR_DOMAIN_OSTYPE_HVM) {
15702 15703 15704
        if (virDomainDefParseBootXML(ctxt, def) < 0)
            goto error;
        if (!(bootHash = virHashCreate(5, NULL)))
15705
            goto error;
15706 15707 15708 15709
    }


    /* analysis of the disk devices */
15710
    if ((n = virXPathNodeSet("./devices/disk", ctxt, &nodes)) < 0)
15711
        goto error;
15712

15713
    if (n && VIR_ALLOC_N(def->disks, n) < 0)
15714
        goto error;
15715

15716
    for (i = 0; i < n; i++) {
15717
        virDomainDiskDefPtr disk = virDomainDiskDefParseXML(xmlopt,
15718
                                                            nodes[i],
L
Lei Li 已提交
15719
                                                            ctxt,
15720
                                                            bootHash,
15721 15722
                                                            def->seclabels,
                                                            def->nseclabels,
15723
                                                            flags);
15724 15725 15726
        if (!disk)
            goto error;

15727
        virDomainDiskInsertPreAlloced(def, disk);
15728 15729 15730
    }
    VIR_FREE(nodes);

15731
    /* analysis of the controller devices */
15732
    if ((n = virXPathNodeSet("./devices/controller", ctxt, &nodes)) < 0)
15733
        goto error;
15734

15735
    if (n && VIR_ALLOC_N(def->controllers, n) < 0)
15736
        goto error;
15737

15738
    for (i = 0; i < n; i++) {
15739
        virDomainControllerDefPtr controller = virDomainControllerDefParseXML(nodes[i],
15740
                                                                              ctxt,
15741 15742 15743 15744
                                                                              flags);
        if (!controller)
            goto error;

15745 15746 15747 15748
        /* 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) {
15749
                    virDomainControllerDefFree(controller);
15750 15751 15752 15753 15754 15755 15756 15757
                    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) {
15758
                    virDomainControllerDefFree(controller);
15759 15760 15761 15762 15763 15764 15765
                    virReportError(VIR_ERR_XML_DETAIL, "%s",
                                   _("Can't add another USB controller: "
                                     "USB is disabled for this domain"));
                    goto error;
                }
                usb_other = true;
            }
15766 15767 15768

            if (controller->info.mastertype == VIR_DOMAIN_CONTROLLER_MASTER_NONE)
                usb_master = true;
15769 15770
        }

15771
        virDomainControllerInsertPreAlloced(def, controller);
15772 15773 15774
    }
    VIR_FREE(nodes);

15775 15776 15777 15778 15779 15780
    if (usb_other && !usb_master) {
        virReportError(VIR_ERR_XML_DETAIL, "%s",
                       _("No master USB controller specified"));
        goto error;
    }

15781 15782
    /* analysis of the resource leases */
    if ((n = virXPathNodeSet("./devices/lease", ctxt, &nodes)) < 0) {
15783 15784
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot extract device leases"));
15785 15786 15787
        goto error;
    }
    if (n && VIR_ALLOC_N(def->leases, n) < 0)
15788
        goto error;
15789
    for (i = 0; i < n; i++) {
15790 15791 15792 15793 15794 15795 15796 15797
        virDomainLeaseDefPtr lease = virDomainLeaseDefParseXML(nodes[i]);
        if (!lease)
            goto error;

        def->leases[def->nleases++] = lease;
    }
    VIR_FREE(nodes);

15798
    /* analysis of the filesystems */
15799
    if ((n = virXPathNodeSet("./devices/filesystem", ctxt, &nodes)) < 0)
15800
        goto error;
15801
    if (n && VIR_ALLOC_N(def->fss, n) < 0)
15802
        goto error;
15803
    for (i = 0; i < n; i++) {
15804
        virDomainFSDefPtr fs = virDomainFSDefParseXML(nodes[i], ctxt,
15805
                                                      flags);
15806 15807 15808
        if (!fs)
            goto error;

15809
        def->fss[def->nfss++] = fs;
15810 15811 15812
    }
    VIR_FREE(nodes);

15813
    /* analysis of the network devices */
15814
    if ((n = virXPathNodeSet("./devices/interface", ctxt, &nodes)) < 0)
15815
        goto error;
15816
    if (n && VIR_ALLOC_N(def->nets, n) < 0)
15817
        goto error;
15818
    netprefix = caps->host.netprefix;
15819
    for (i = 0; i < n; i++) {
15820
        virDomainNetDefPtr net = virDomainNetDefParseXML(xmlopt,
15821
                                                         nodes[i],
15822
                                                         ctxt,
15823
                                                         bootHash,
15824
                                                         netprefix,
15825
                                                         flags);
15826 15827 15828
        if (!net)
            goto error;

15829
        def->nets[def->nnets++] = net;
15830

15831 15832 15833 15834 15835 15836
        /* <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) {
15837
            goto error;
15838
        }
15839 15840 15841 15842
    }
    VIR_FREE(nodes);


E
Eric Blake 已提交
15843
    /* analysis of the smartcard devices */
15844
    if ((n = virXPathNodeSet("./devices/smartcard", ctxt, &nodes)) < 0)
E
Eric Blake 已提交
15845 15846
        goto error;
    if (n && VIR_ALLOC_N(def->smartcards, n) < 0)
15847
        goto error;
E
Eric Blake 已提交
15848

15849
    for (i = 0; i < n; i++) {
E
Eric Blake 已提交
15850 15851 15852 15853 15854 15855 15856 15857 15858 15859
        virDomainSmartcardDefPtr card = virDomainSmartcardDefParseXML(nodes[i],
                                                                      flags);
        if (!card)
            goto error;

        def->smartcards[def->nsmartcards++] = card;
    }
    VIR_FREE(nodes);


15860
    /* analysis of the character devices */
15861
    if ((n = virXPathNodeSet("./devices/parallel", ctxt, &nodes)) < 0)
15862
        goto error;
15863
    if (n && VIR_ALLOC_N(def->parallels, n) < 0)
15864
        goto error;
15865

15866
    for (i = 0; i < n; i++) {
15867
        virDomainChrDefPtr chr = virDomainChrDefParseXML(ctxt,
15868
                                                         nodes[i],
15869 15870
                                                         def->seclabels,
                                                         def->nseclabels,
15871
                                                         flags);
15872 15873 15874
        if (!chr)
            goto error;

15875 15876
        if (chr->target.port == -1) {
            int maxport = -1;
15877
            for (j = 0; j < i; j++) {
15878 15879 15880 15881 15882
                if (def->parallels[j]->target.port > maxport)
                    maxport = def->parallels[j]->target.port;
            }
            chr->target.port = maxport + 1;
        }
15883
        def->parallels[def->nparallels++] = chr;
15884 15885 15886
    }
    VIR_FREE(nodes);

15887
    if ((n = virXPathNodeSet("./devices/serial", ctxt, &nodes)) < 0)
15888
        goto error;
15889

15890
    if (n && VIR_ALLOC_N(def->serials, n) < 0)
15891
        goto error;
15892

15893
    for (i = 0; i < n; i++) {
15894
        virDomainChrDefPtr chr = virDomainChrDefParseXML(ctxt,
15895
                                                         nodes[i],
15896 15897
                                                         def->seclabels,
                                                         def->nseclabels,
15898
                                                         flags);
15899 15900 15901
        if (!chr)
            goto error;

15902 15903
        if (chr->target.port == -1) {
            int maxport = -1;
15904
            for (j = 0; j < i; j++) {
15905 15906 15907 15908 15909
                if (def->serials[j]->target.port > maxport)
                    maxport = def->serials[j]->target.port;
            }
            chr->target.port = maxport + 1;
        }
15910
        def->serials[def->nserials++] = chr;
15911 15912 15913
    }
    VIR_FREE(nodes);

15914
    if ((n = virXPathNodeSet("./devices/console", ctxt, &nodes)) < 0) {
15915 15916
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot extract console devices"));
15917 15918 15919
        goto error;
    }
    if (n && VIR_ALLOC_N(def->consoles, n) < 0)
15920
        goto error;
15921

15922
    for (i = 0; i < n; i++) {
15923
        virDomainChrDefPtr chr = virDomainChrDefParseXML(ctxt,
15924
                                                         nodes[i],
15925 15926
                                                         def->seclabels,
                                                         def->nseclabels,
15927
                                                         flags);
15928 15929
        if (!chr)
            goto error;
15930

15931 15932
        chr->target.port = i;
        def->consoles[def->nconsoles++] = chr;
15933
    }
15934
    VIR_FREE(nodes);
15935

15936
    if ((n = virXPathNodeSet("./devices/channel", ctxt, &nodes)) < 0)
15937 15938
        goto error;
    if (n && VIR_ALLOC_N(def->channels, n) < 0)
15939
        goto error;
15940

15941
    for (i = 0; i < n; i++) {
15942
        virDomainChrDefPtr chr = virDomainChrDefParseXML(ctxt,
15943
                                                         nodes[i],
15944 15945
                                                         def->seclabels,
                                                         def->nseclabels,
15946 15947 15948 15949 15950 15951 15952 15953
                                                         flags);
        if (!chr)
            goto error;

        def->channels[def->nchannels++] = chr;
    }
    VIR_FREE(nodes);

15954 15955

    /* analysis of the input devices */
15956
    if ((n = virXPathNodeSet("./devices/input", ctxt, &nodes)) < 0)
15957
        goto error;
15958
    if (n && VIR_ALLOC_N(def->inputs, n) < 0)
15959
        goto error;
15960

15961
    for (i = 0; i < n; i++) {
L
Li Zhang 已提交
15962
        virDomainInputDefPtr input = virDomainInputDefParseXML(def,
15963
                                                               nodes[i],
15964
                                                               ctxt,
15965
                                                               flags);
15966 15967 15968
        if (!input)
            goto error;

15969 15970
        /* Check if USB bus is required */
        if (input->bus == VIR_DOMAIN_INPUT_BUS_USB && usb_none) {
15971
            virDomainInputDefFree(input);
15972 15973 15974 15975 15976
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Can't add USB input device. "
                             "USB bus is disabled"));
            goto error;
        }
15977

15978
        def->inputs[def->ninputs++] = input;
15979 15980 15981
    }
    VIR_FREE(nodes);

15982
    /* analysis of the graphics devices */
15983
    if ((n = virXPathNodeSet("./devices/graphics", ctxt, &nodes)) < 0)
15984
        goto error;
15985
    if (n && VIR_ALLOC_N(def->graphics, n) < 0)
15986
        goto error;
15987
    for (i = 0; i < n; i++) {
15988
        virDomainGraphicsDefPtr graphics = virDomainGraphicsDefParseXML(nodes[i],
15989
                                                                        ctxt,
15990
                                                                        flags);
15991 15992 15993
        if (!graphics)
            goto error;

15994
        def->graphics[def->ngraphics++] = graphics;
15995 15996 15997 15998
    }
    VIR_FREE(nodes);

    /* analysis of the sound devices */
15999
    if ((n = virXPathNodeSet("./devices/sound", ctxt, &nodes)) < 0)
16000
        goto error;
16001
    if (n && VIR_ALLOC_N(def->sounds, n) < 0)
16002
        goto error;
16003
    for (i = 0; i < n; i++) {
16004
        virDomainSoundDefPtr sound = virDomainSoundDefParseXML(nodes[i],
16005
                                                               ctxt,
16006
                                                               flags);
16007 16008 16009
        if (!sound)
            goto error;

16010
        def->sounds[def->nsounds++] = sound;
16011 16012 16013
    }
    VIR_FREE(nodes);

16014
    /* analysis of the video devices */
16015
    if ((n = virXPathNodeSet("./devices/video", ctxt, &nodes)) < 0)
16016 16017
        goto error;
    if (n && VIR_ALLOC_N(def->videos, n) < 0)
16018
        goto error;
16019
    for (i = 0; i < n; i++) {
16020
        j = def->nvideos;
16021
        virDomainVideoDefPtr video = virDomainVideoDefParseXML(nodes[j],
16022 16023 16024 16025
                                                               def,
                                                               flags);
        if (!video)
            goto error;
16026 16027 16028

        if (video->primary) {
            if (primaryVideo) {
16029
                virDomainVideoDefFree(video);
16030 16031 16032 16033 16034
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("Only one primary video device is supported"));
                goto error;
            }

16035
            j = 0;
16036 16037
            primaryVideo = true;
        }
16038
        if (VIR_INSERT_ELEMENT_INPLACE(def->videos,
16039
                                       j,
16040 16041
                                       def->nvideos,
                                       video) < 0) {
16042
            virDomainVideoDefFree(video);
16043
            goto error;
16044
        }
16045 16046 16047
    }
    VIR_FREE(nodes);

16048
    /* For backwards compatibility, if no <video> tag is set but there
16049 16050 16051 16052
     * is a <graphics> tag, then we add a single video tag */
    if (def->ngraphics && !def->nvideos) {
        virDomainVideoDefPtr video;
        if (VIR_ALLOC(video) < 0)
16053
            goto error;
16054 16055
        video->type = virDomainVideoDefaultType(def);
        if (video->type < 0) {
16056 16057
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot determine default video type"));
16058 16059 16060 16061 16062 16063 16064
            VIR_FREE(video);
            goto error;
        }
        video->vram = virDomainVideoDefaultRAM(def, video->type);
        video->heads = 1;
        if (VIR_ALLOC_N(def->videos, 1) < 0) {
            virDomainVideoDefFree(video);
16065
            goto error;
16066 16067 16068 16069
        }
        def->videos[def->nvideos++] = video;
    }

16070
    /* analysis of the host devices */
16071
    if ((n = virXPathNodeSet("./devices/hostdev", ctxt, &nodes)) < 0)
16072
        goto error;
16073
    if (n && VIR_REALLOC_N(def->hostdevs, def->nhostdevs + n) < 0)
16074
        goto error;
16075
    for (i = 0; i < n; i++) {
16076 16077
        virDomainHostdevDefPtr hostdev;

16078
        hostdev = virDomainHostdevDefParseXML(nodes[i], ctxt, bootHash, flags);
16079 16080 16081
        if (!hostdev)
            goto error;

16082 16083 16084 16085 16086
        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"));
16087
            virDomainHostdevDefFree(hostdev);
16088 16089 16090
            goto error;
        }

16091
        def->hostdevs[def->nhostdevs++] = hostdev;
16092 16093 16094 16095 16096 16097 16098 16099 16100

        /* For a domain definition, we need to check if the controller
         * for this hostdev exists yet and if not add it. This cannot be
         * done during virDomainHostdevAssignAddress (as part of device
         * post processing) because that will result in the failure to
         * load the controller during hostdev hotplug.
         */
        if (virDomainDefMaybeAddHostdevSCSIcontroller(def) < 0)
            goto error;
16101 16102 16103
    }
    VIR_FREE(nodes);

R
Richard Jones 已提交
16104 16105
    /* analysis of the watchdog devices */
    def->watchdog = NULL;
16106
    if ((n = virXPathNodeSet("./devices/watchdog", ctxt, &nodes)) < 0)
R
Richard Jones 已提交
16107 16108
        goto error;
    if (n > 1) {
16109 16110
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("only a single watchdog device is supported"));
R
Richard Jones 已提交
16111 16112 16113 16114
        goto error;
    }
    if (n > 0) {
        virDomainWatchdogDefPtr watchdog =
16115
            virDomainWatchdogDefParseXML(nodes[0], flags);
R
Richard Jones 已提交
16116 16117 16118 16119 16120 16121 16122
        if (!watchdog)
            goto error;

        def->watchdog = watchdog;
        VIR_FREE(nodes);
    }

16123 16124
    /* analysis of the memballoon devices */
    def->memballoon = NULL;
16125
    if ((n = virXPathNodeSet("./devices/memballoon", ctxt, &nodes)) < 0)
16126 16127
        goto error;
    if (n > 1) {
16128 16129
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("only a single memory balloon device is supported"));
16130 16131 16132 16133
        goto error;
    }
    if (n > 0) {
        virDomainMemballoonDefPtr memballoon =
16134
            virDomainMemballoonDefParseXML(nodes[0], ctxt, flags);
16135 16136 16137 16138 16139 16140 16141
        if (!memballoon)
            goto error;

        def->memballoon = memballoon;
        VIR_FREE(nodes);
    }

16142
    /* Parse the RNG devices */
16143 16144
    if ((n = virXPathNodeSet("./devices/rng", ctxt, &nodes)) < 0)
        goto error;
16145
    if (n && VIR_ALLOC_N(def->rngs, n) < 0)
16146
        goto error;
16147 16148 16149 16150 16151
    for (i = 0; i < n; i++) {
        virDomainRNGDefPtr rng = virDomainRNGDefParseXML(nodes[i],
                                                         ctxt,
                                                         flags);
        if (!rng)
16152
            goto error;
16153 16154

        def->rngs[def->nrngs++] = rng;
16155
    }
16156 16157 16158 16159 16160 16161 16162 16163 16164 16165 16166 16167 16168 16169 16170 16171 16172
    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);
16173

16174
    if ((n = virXPathNodeSet("./devices/nvram", ctxt, &nodes)) < 0)
L
Li Zhang 已提交
16175 16176 16177 16178 16179 16180 16181 16182 16183 16184 16185 16186 16187 16188 16189
        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 已提交
16190
    /* analysis of the hub devices */
16191
    if ((n = virXPathNodeSet("./devices/hub", ctxt, &nodes)) < 0)
M
Marc-André Lureau 已提交
16192 16193
        goto error;
    if (n && VIR_ALLOC_N(def->hubs, n) < 0)
16194
        goto error;
16195
    for (i = 0; i < n; i++) {
M
Marc-André Lureau 已提交
16196 16197 16198 16199
        virDomainHubDefPtr hub = virDomainHubDefParseXML(nodes[i], flags);
        if (!hub)
            goto error;

16200
        if (hub->type == VIR_DOMAIN_HUB_TYPE_USB && usb_none) {
16201
            virDomainHubDefFree(hub);
16202 16203 16204 16205 16206 16207
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Can't add USB hub: "
                             "USB is disabled for this domain"));
            goto error;
        }

M
Marc-André Lureau 已提交
16208 16209 16210 16211
        def->hubs[def->nhubs++] = hub;
    }
    VIR_FREE(nodes);

16212
    /* analysis of the redirected devices */
16213
    if ((n = virXPathNodeSet("./devices/redirdev", ctxt, &nodes)) < 0)
16214 16215
        goto error;
    if (n && VIR_ALLOC_N(def->redirdevs, n) < 0)
16216
        goto error;
16217
    for (i = 0; i < n; i++) {
16218
        virDomainRedirdevDefPtr redirdev = virDomainRedirdevDefParseXML(nodes[i],
16219
                                                                        bootHash,
16220 16221 16222 16223
                                                                        flags);
        if (!redirdev)
            goto error;

16224 16225 16226 16227
        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"));
16228
            virDomainRedirdevDefFree(redirdev);
16229 16230 16231
            goto error;
        }

16232 16233 16234 16235
        def->redirdevs[def->nredirdevs++] = redirdev;
    }
    VIR_FREE(nodes);

16236
    /* analysis of the redirection filter rules */
16237
    if ((n = virXPathNodeSet("./devices/redirfilter", ctxt, &nodes)) < 0)
16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248 16249 16250 16251 16252 16253 16254
        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 已提交
16255
    /* analysis of the panic devices */
16256
    if ((n = virXPathNodeSet("./devices/panic", ctxt, &nodes)) < 0)
H
Hu Tao 已提交
16257
        goto error;
D
Dmitry Andreev 已提交
16258
    if (n && VIR_ALLOC_N(def->panics, n) < 0)
H
Hu Tao 已提交
16259
        goto error;
D
Dmitry Andreev 已提交
16260
    for (i = 0; i < n; i++) {
H
Hu Tao 已提交
16261
        virDomainPanicDefPtr panic =
D
Dmitry Andreev 已提交
16262
            virDomainPanicDefParseXML(nodes[i]);
H
Hu Tao 已提交
16263 16264 16265
        if (!panic)
            goto error;

D
Dmitry Andreev 已提交
16266
        def->panics[def->npanics++] = panic;
H
Hu Tao 已提交
16267
    }
D
Dmitry Andreev 已提交
16268
    VIR_FREE(nodes);
H
Hu Tao 已提交
16269

16270
    /* analysis of the shmem devices */
16271
    if ((n = virXPathNodeSet("./devices/shmem", ctxt, &nodes)) < 0)
16272 16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287
        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 已提交
16288

16289 16290 16291 16292 16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305
    /* analysis of memory devices */
    if ((n = virXPathNodeSet("./devices/memory", ctxt, &nodes)) < 0)
        goto error;
    if (n && VIR_ALLOC_N(def->mems, n) < 0)
        goto error;

    for (i = 0; i < n; i++) {
        virDomainMemoryDefPtr mem = virDomainMemoryDefParseXML(nodes[i],
                                                               ctxt,
                                                               flags);
        if (!mem)
            goto error;

        def->mems[def->nmems++] = mem;
    }
    VIR_FREE(nodes);

16306 16307 16308 16309 16310 16311 16312 16313 16314 16315 16316 16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329 16330 16331 16332 16333 16334 16335 16336 16337
    /* 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;
    }

16338 16339 16340
    if ((node = virXPathNode("./sysinfo[1]", ctxt)) != NULL) {
        xmlNodePtr oldnode = ctxt->node;
        ctxt->node = node;
16341 16342
        def->sysinfo = virSysinfoParseXML(node, ctxt,
                                          def->uuid, uuid_generated);
16343 16344 16345 16346 16347
        ctxt->node = oldnode;

        if (def->sysinfo == NULL)
            goto error;
    }
16348 16349

    if ((tmp = virXPathString("string(./os/smbios/@mode)", ctxt))) {
16350 16351 16352
        int mode;

        if ((mode = virDomainSmbiosModeTypeFromString(tmp)) < 0) {
16353
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
16354
                           _("unknown smbios mode '%s'"), tmp);
16355 16356 16357 16358 16359
            goto error;
        }
        def->os.smbios_mode = mode;
        VIR_FREE(tmp);
    }
16360

16361 16362 16363
    if (virDomainKeyWrapDefParseXML(def, ctxt) < 0)
        goto error;

16364
    /* Extract custom metadata */
16365
    if ((node = virXPathNode("./metadata[1]", ctxt)) != NULL)
16366 16367
        def->metadata = xmlCopyNode(node, 1);

16368 16369 16370
    /* we have to make a copy of all of the callback pointers here since
     * we won't have the virCaps structure available during free
     */
16371
    def->ns = xmlopt->ns;
16372

16373 16374 16375
    if (def->ns.parse &&
        (def->ns.parse)(xml, root, ctxt, &def->namespaceData) < 0)
        goto error;
16376

16377
    /* callback to fill driver specific domain aspects */
16378
    if (virDomainDefPostParse(def, caps, flags, xmlopt) < 0)
16379 16380
        goto error;

16381 16382 16383 16384
    /* Auto-add any implied controllers which aren't present */
    if (virDomainDefAddImplicitControllers(def) < 0)
        goto error;

16385
    virHashFree(bootHash);
16386

16387 16388
    return def;

16389
 error:
16390 16391
    VIR_FREE(tmp);
    VIR_FREE(nodes);
16392
    virHashFree(bootHash);
16393 16394 16395 16396
    virDomainDefFree(def);
    return NULL;
}

16397

16398
static virDomainObjPtr
16399
virDomainObjParseXML(xmlDocPtr xml,
16400
                     xmlXPathContextPtr ctxt,
16401 16402
                     virCapsPtr caps,
                     virDomainXMLOptionPtr xmlopt,
16403
                     unsigned int flags)
16404 16405 16406 16407 16408 16409
{
    char *tmp = NULL;
    long val;
    xmlNodePtr config;
    xmlNodePtr oldnode;
    virDomainObjPtr obj;
16410
    xmlNodePtr *nodes = NULL;
16411 16412
    size_t i;
    int n;
J
Jiri Denemark 已提交
16413 16414
    int state;
    int reason = 0;
16415

16416
    if (!(obj = virDomainObjNew(xmlopt)))
16417 16418
        return NULL;

16419
    if (!(config = virXPathNode("./domain", ctxt))) {
16420 16421
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("no domain config"));
16422 16423 16424 16425 16426
        goto error;
    }

    oldnode = ctxt->node;
    ctxt->node = config;
16427
    obj->def = virDomainDefParseXML(xml, config, ctxt, caps, xmlopt, flags);
16428 16429 16430 16431
    ctxt->node = oldnode;
    if (!obj->def)
        goto error;

16432
    if (!(tmp = virXPathString("string(./@state)", ctxt))) {
16433 16434
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing domain state"));
16435 16436
        goto error;
    }
J
Jiri Denemark 已提交
16437
    if ((state = virDomainStateTypeFromString(tmp)) < 0) {
16438
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
16439
                       _("invalid domain state '%s'"), tmp);
16440 16441 16442 16443 16444
        VIR_FREE(tmp);
        goto error;
    }
    VIR_FREE(tmp);

J
Jiri Denemark 已提交
16445 16446
    if ((tmp = virXPathString("string(./@reason)", ctxt))) {
        if ((reason = virDomainStateReasonFromString(state, tmp)) < 0) {
16447
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
16448
                           _("invalid domain state reason '%s'"), tmp);
J
Jiri Denemark 已提交
16449 16450 16451 16452 16453 16454 16455 16456
            VIR_FREE(tmp);
            goto error;
        }
        VIR_FREE(tmp);
    }

    virDomainObjSetState(obj, state, reason);

E
Eric Blake 已提交
16457
    if (virXPathLong("string(./@pid)", ctxt, &val) < 0) {
16458 16459
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("invalid pid"));
16460 16461 16462 16463
        goto error;
    }
    obj->pid = (pid_t)val;

16464
    if ((n = virXPathNodeSet("./taint", ctxt, &nodes)) < 0)
16465
        goto error;
16466
    for (i = 0; i < n; i++) {
16467 16468 16469 16470
        char *str = virXMLPropString(nodes[i], "flag");
        if (str) {
            int flag = virDomainTaintTypeFromString(str);
            if (flag < 0) {
16471
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
16472
                               _("Unknown taint flag %s"), str);
16473
                VIR_FREE(str);
16474 16475
                goto error;
            }
16476
            VIR_FREE(str);
16477 16478 16479 16480 16481
            virDomainObjTaint(obj, flag);
        }
    }
    VIR_FREE(nodes);

16482
    if (xmlopt->privateData.parse &&
16483
        xmlopt->privateData.parse(ctxt, obj, &xmlopt->config) < 0)
16484
        goto error;
16485

16486 16487
    return obj;

16488
 error:
16489
    virObjectUnref(obj);
16490
    VIR_FREE(nodes);
16491 16492 16493 16494
    return NULL;
}


J
Jiri Denemark 已提交
16495 16496 16497 16498
static virDomainDefPtr
virDomainDefParse(const char *xmlStr,
                  const char *filename,
                  virCapsPtr caps,
16499
                  virDomainXMLOptionPtr xmlopt,
E
Eric Blake 已提交
16500
                  unsigned int flags)
16501
{
J
Jiri Denemark 已提交
16502 16503
    xmlDocPtr xml;
    virDomainDefPtr def = NULL;
16504
    int keepBlanksDefault = xmlKeepBlanksDefault(0);
J
Jiri Denemark 已提交
16505

16506
    if ((xml = virXMLParse(filename, xmlStr, _("(domain_definition)")))) {
16507
        def = virDomainDefParseNode(xml, xmlDocGetRootElement(xml), caps,
16508
                                    xmlopt, flags);
J
Jiri Denemark 已提交
16509
        xmlFreeDoc(xml);
16510
    }
J
Jiri Denemark 已提交
16511

16512
    xmlKeepBlanksDefault(keepBlanksDefault);
J
Jiri Denemark 已提交
16513
    return def;
16514
}
16515

16516
virDomainDefPtr
16517 16518
virDomainDefParseString(const char *xmlStr,
                        virCapsPtr caps,
16519
                        virDomainXMLOptionPtr xmlopt,
16520
                        unsigned int flags)
16521
{
16522
    return virDomainDefParse(xmlStr, NULL, caps, xmlopt, flags);
16523 16524
}

16525
virDomainDefPtr
16526 16527
virDomainDefParseFile(const char *filename,
                      virCapsPtr caps,
16528
                      virDomainXMLOptionPtr xmlopt,
16529
                      unsigned int flags)
16530
{
16531
    return virDomainDefParse(NULL, filename, caps, xmlopt, flags);
16532 16533 16534
}


16535
virDomainDefPtr
16536
virDomainDefParseNode(xmlDocPtr xml,
16537
                      xmlNodePtr root,
16538 16539
                      virCapsPtr caps,
                      virDomainXMLOptionPtr xmlopt,
16540
                      unsigned int flags)
16541 16542 16543 16544 16545
{
    xmlXPathContextPtr ctxt = NULL;
    virDomainDefPtr def = NULL;

    if (!xmlStrEqual(root->name, BAD_CAST "domain")) {
16546 16547 16548 16549
        virReportError(VIR_ERR_XML_ERROR,
                       _("unexpected root element <%s>, "
                         "expecting <domain>"),
                       root->name);
16550 16551 16552 16553 16554
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
16555
        virReportOOMError();
16556 16557 16558 16559
        goto cleanup;
    }

    ctxt->node = root;
16560
    def = virDomainDefParseXML(xml, root, ctxt, caps, xmlopt, flags);
16561

16562
 cleanup:
16563 16564 16565
    xmlXPathFreeContext(ctxt);
    return def;
}
16566 16567


16568
virDomainObjPtr
16569
virDomainObjParseNode(xmlDocPtr xml,
L
Laine Stump 已提交
16570
                      xmlNodePtr root,
16571 16572
                      virCapsPtr caps,
                      virDomainXMLOptionPtr xmlopt,
L
Laine Stump 已提交
16573
                      unsigned int flags)
16574 16575 16576 16577 16578
{
    xmlXPathContextPtr ctxt = NULL;
    virDomainObjPtr obj = NULL;

    if (!xmlStrEqual(root->name, BAD_CAST "domstatus")) {
16579 16580 16581 16582
        virReportError(VIR_ERR_XML_ERROR,
                       _("unexpected root element <%s>, "
                         "expecting <domstatus>"),
                       root->name);
16583 16584 16585
        goto cleanup;
    }

16586
    if (!(ctxt = xmlXPathNewContext(xml))) {
16587
        virReportOOMError();
16588 16589 16590 16591
        goto cleanup;
    }

    ctxt->node = root;
16592
    obj = virDomainObjParseXML(xml, ctxt, caps, xmlopt, flags);
16593

16594
 cleanup:
16595 16596 16597 16598
    xmlXPathFreeContext(ctxt);
    return obj;
}

H
Hu Tao 已提交
16599

16600
virDomainObjPtr
16601 16602
virDomainObjParseFile(const char *filename,
                      virCapsPtr caps,
16603
                      virDomainXMLOptionPtr xmlopt,
16604
                      unsigned int flags)
H
Hu Tao 已提交
16605 16606 16607
{
    xmlDocPtr xml;
    virDomainObjPtr obj = NULL;
16608
    int keepBlanksDefault = xmlKeepBlanksDefault(0);
H
Hu Tao 已提交
16609 16610

    if ((xml = virXMLParseFile(filename))) {
16611
        obj = virDomainObjParseNode(xml, xmlDocGetRootElement(xml),
16612
                                    caps, xmlopt, flags);
H
Hu Tao 已提交
16613 16614 16615
        xmlFreeDoc(xml);
    }

16616
    xmlKeepBlanksDefault(keepBlanksDefault);
H
Hu Tao 已提交
16617 16618 16619 16620
    return obj;
}


16621 16622 16623
static bool
virDomainTimerDefCheckABIStability(virDomainTimerDefPtr src,
                                   virDomainTimerDefPtr dst)
16624 16625
{
    if (src->name != dst->name) {
16626 16627 16628 16629
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target timer %s does not match source %s"),
                       virDomainTimerNameTypeToString(dst->name),
                       virDomainTimerNameTypeToString(src->name));
16630
        return false;
16631 16632 16633
    }

    if (src->present != dst->present) {
16634 16635 16636
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target timer presence %d does not match source %d"),
                       dst->present, src->present);
16637
        return false;
16638 16639 16640 16641
    }

    if (src->name == VIR_DOMAIN_TIMER_NAME_TSC) {
        if (src->frequency != dst->frequency) {
16642 16643 16644
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target TSC frequency %lu does not match source %lu"),
                           dst->frequency, src->frequency);
16645
            return false;
16646 16647 16648
        }

        if (src->mode != dst->mode) {
16649 16650 16651 16652
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target TSC mode %s does not match source %s"),
                           virDomainTimerModeTypeToString(dst->mode),
                           virDomainTimerModeTypeToString(src->mode));
16653
            return false;
16654 16655 16656
        }
    }

16657
    return true;
16658 16659 16660
}


16661 16662 16663
static bool
virDomainDeviceInfoCheckABIStability(virDomainDeviceInfoPtr src,
                                     virDomainDeviceInfoPtr dst)
16664 16665
{
    if (src->type != dst->type) {
16666 16667 16668 16669
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target device address type %s does not match source %s"),
                       virDomainDeviceAddressTypeToString(dst->type),
                       virDomainDeviceAddressTypeToString(src->type));
16670
        return false;
16671 16672
    }

16673
    switch ((virDomainDeviceAddressType) src->type) {
16674 16675 16676 16677 16678
    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) {
16679
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
16680 16681
                           _("Target device PCI address %04x:%02x:%02x.%02x "
                             "does not match source %04x:%02x:%02x.%02x"),
16682 16683 16684 16685
                           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);
16686
            return false;
16687 16688 16689 16690 16691 16692 16693
        }
        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) {
16694
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
16695 16696
                           _("Target device drive address %d:%d:%d "
                             "does not match source %d:%d:%d"),
16697 16698 16699 16700
                           dst->addr.drive.controller, dst->addr.drive.bus,
                           dst->addr.drive.unit,
                           src->addr.drive.controller, src->addr.drive.bus,
                           src->addr.drive.unit);
16701
            return false;
16702 16703 16704 16705 16706 16707 16708
        }
        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) {
16709
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
16710 16711
                           _("Target device virtio serial address %d:%d:%d "
                             "does not match source %d:%d:%d"),
16712 16713 16714 16715
                           dst->addr.vioserial.controller, dst->addr.vioserial.bus,
                           dst->addr.vioserial.port,
                           src->addr.vioserial.controller, src->addr.vioserial.bus,
                           src->addr.vioserial.port);
16716
            return false;
16717 16718 16719 16720 16721 16722
        }
        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) {
16723
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
16724 16725
                           _("Target device ccid address %d:%d "
                             "does not match source %d:%d"),
16726 16727 16728 16729
                           dst->addr.ccid.controller,
                           dst->addr.ccid.slot,
                           src->addr.ccid.controller,
                           src->addr.ccid.slot);
16730
            return false;
16731 16732
        }
        break;
H
Hu Tao 已提交
16733 16734 16735 16736 16737 16738 16739 16740 16741 16742 16743 16744 16745 16746

    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;
16747

16748 16749 16750 16751 16752 16753 16754 16755 16756 16757 16758 16759 16760 16761 16762 16763 16764 16765 16766 16767
    case VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM:
        if (src->addr.dimm.slot != dst->addr.dimm.slot) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target device dimm slot %u does not match "
                             "source %u"),
                           dst->addr.dimm.slot,
                           src->addr.dimm.slot);
            return false;
        }

        if (src->addr.dimm.base != dst->addr.dimm.base) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target device dimm base addres '%llx' does "
                             "not match source '%llx'"),
                           dst->addr.dimm.base,
                           src->addr.dimm.base);
            return false;
        }
        break;

16768 16769 16770 16771 16772 16773 16774 16775
    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;
16776 16777
    }

16778
    return true;
16779 16780 16781
}


16782 16783 16784
static bool
virDomainDiskDefCheckABIStability(virDomainDiskDefPtr src,
                                  virDomainDiskDefPtr dst)
16785 16786
{
    if (src->device != dst->device) {
16787 16788 16789 16790
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target disk device %s does not match source %s"),
                       virDomainDiskDeviceTypeToString(dst->device),
                       virDomainDiskDeviceTypeToString(src->device));
16791
        return false;
16792 16793 16794
    }

    if (src->bus != dst->bus) {
16795 16796 16797 16798
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target disk bus %s does not match source %s"),
                       virDomainDiskBusTypeToString(dst->bus),
                       virDomainDiskBusTypeToString(src->bus));
16799
        return false;
16800 16801 16802
    }

    if (STRNEQ(src->dst, dst->dst)) {
16803 16804 16805
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target disk %s does not match source %s"),
                       dst->dst, src->dst);
16806
        return false;
16807 16808 16809
    }

    if (STRNEQ_NULLABLE(src->serial, dst->serial)) {
16810 16811 16812
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target disk serial %s does not match source %s"),
                       NULLSTR(dst->serial), NULLSTR(src->serial));
16813
        return false;
16814 16815
    }

16816 16817 16818 16819 16820 16821 16822 16823
    if (STRNEQ_NULLABLE(src->wwn, dst->wwn)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target disk wwn '%s' does not match source '%s'"),
                       NULLSTR(dst->wwn), NULLSTR(src->wwn));
        return false;

    }

16824 16825
    if (src->src->readonly != dst->src->readonly ||
        src->src->shared != dst->src->shared) {
16826 16827
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Target disk access mode does not match source"));
16828
        return false;
16829 16830 16831
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
16832
        return false;
16833

16834
    return true;
16835 16836 16837
}


16838 16839 16840
static bool
virDomainControllerDefCheckABIStability(virDomainControllerDefPtr src,
                                        virDomainControllerDefPtr dst)
16841 16842
{
    if (src->type != dst->type) {
16843 16844 16845 16846
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target controller type %s does not match source %s"),
                       virDomainControllerTypeToString(dst->type),
                       virDomainControllerTypeToString(src->type));
16847
        return false;
16848 16849 16850
    }

    if (src->idx != dst->idx) {
16851 16852 16853
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target controller index %d does not match source %d"),
                       dst->idx, src->idx);
16854
        return false;
16855 16856 16857
    }

    if (src->model != dst->model) {
16858 16859 16860
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target controller model %d does not match source %d"),
                       dst->model, src->model);
16861
        return false;
16862 16863 16864 16865
    }

    if (src->type == VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL) {
        if (src->opts.vioserial.ports != dst->opts.vioserial.ports) {
16866 16867 16868
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target controller ports %d does not match source %d"),
                           dst->opts.vioserial.ports, src->opts.vioserial.ports);
16869
            return false;
16870 16871 16872
        }

        if (src->opts.vioserial.vectors != dst->opts.vioserial.vectors) {
16873 16874 16875
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target controller vectors %d does not match source %d"),
                           dst->opts.vioserial.vectors, src->opts.vioserial.vectors);
16876
            return false;
16877 16878 16879 16880
        }
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
16881
        return false;
16882

16883
    return true;
16884 16885 16886
}


16887 16888 16889
static bool
virDomainFsDefCheckABIStability(virDomainFSDefPtr src,
                                virDomainFSDefPtr dst)
16890 16891
{
    if (STRNEQ(src->dst, dst->dst)) {
16892 16893 16894
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target filesystem guest target %s does not match source %s"),
                       dst->dst, src->dst);
16895
        return false;
16896 16897 16898
    }

    if (src->readonly != dst->readonly) {
16899 16900
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Target filesystem access mode does not match source"));
16901
        return false;
16902 16903 16904
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
16905
        return false;
16906

16907
    return true;
16908 16909 16910
}


16911 16912 16913
static bool
virDomainNetDefCheckABIStability(virDomainNetDefPtr src,
                                 virDomainNetDefPtr dst)
16914
{
16915 16916 16917
    char srcmac[VIR_MAC_STRING_BUFLEN];
    char dstmac[VIR_MAC_STRING_BUFLEN];

16918
    if (virMacAddrCmp(&src->mac, &dst->mac) != 0) {
16919
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
16920 16921 16922 16923
                       _("Target network card mac %s"
                         " does not match source %s"),
                       virMacAddrFormat(&dst->mac, dstmac),
                       virMacAddrFormat(&src->mac, srcmac));
16924
        return false;
16925 16926 16927
    }

    if (STRNEQ_NULLABLE(src->model, dst->model)) {
16928 16929 16930
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target network card model %s does not match source %s"),
                       NULLSTR(dst->model), NULLSTR(src->model));
16931
        return false;
16932 16933 16934
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
16935
        return false;
16936

16937
    return true;
16938 16939 16940
}


16941 16942 16943
static bool
virDomainInputDefCheckABIStability(virDomainInputDefPtr src,
                                   virDomainInputDefPtr dst)
16944 16945
{
    if (src->type != dst->type) {
16946 16947 16948 16949
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target input device type %s does not match source %s"),
                       virDomainInputTypeToString(dst->type),
                       virDomainInputTypeToString(src->type));
16950
        return false;
16951 16952 16953
    }

    if (src->bus != dst->bus) {
16954 16955 16956 16957
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target input device bus %s does not match source %s"),
                       virDomainInputBusTypeToString(dst->bus),
                       virDomainInputBusTypeToString(src->bus));
16958
        return false;
16959 16960 16961
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
16962
        return false;
16963

16964
    return true;
16965 16966 16967
}


16968 16969 16970
static bool
virDomainSoundDefCheckABIStability(virDomainSoundDefPtr src,
                                   virDomainSoundDefPtr dst)
16971 16972
{
    if (src->model != dst->model) {
16973 16974 16975 16976
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target sound card model %s does not match source %s"),
                       virDomainSoundModelTypeToString(dst->model),
                       virDomainSoundModelTypeToString(src->model));
16977
        return false;
16978 16979 16980
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
16981
        return false;
16982

16983
    return true;
16984 16985 16986
}


16987 16988 16989
static bool
virDomainVideoDefCheckABIStability(virDomainVideoDefPtr src,
                                   virDomainVideoDefPtr dst)
16990 16991
{
    if (src->type != dst->type) {
16992 16993 16994 16995
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target video card model %s does not match source %s"),
                       virDomainVideoTypeToString(dst->type),
                       virDomainVideoTypeToString(src->type));
16996
        return false;
16997 16998
    }

16999 17000 17001 17002 17003 17004 17005
    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;
    }

17006
    if (src->vram != dst->vram) {
17007 17008 17009
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target video card vram %u does not match source %u"),
                       dst->vram, src->vram);
17010
        return false;
17011 17012
    }

17013 17014 17015 17016 17017 17018 17019
    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;
    }

17020
    if (src->heads != dst->heads) {
17021 17022 17023
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target video card heads %u does not match source %u"),
                       dst->heads, src->heads);
17024
        return false;
17025 17026 17027 17028
    }

    if ((src->accel && !dst->accel) ||
        (!src->accel && dst->accel)) {
17029 17030
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Target video card acceleration does not match source"));
17031
        return false;
17032 17033 17034
    }

    if (src->accel) {
17035
        if (src->accel->accel2d != dst->accel->accel2d) {
17036 17037
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target video card 2d accel %u does not match source %u"),
17038
                           dst->accel->accel2d, src->accel->accel2d);
17039
            return false;
17040 17041
        }

17042
        if (src->accel->accel3d != dst->accel->accel3d) {
17043 17044
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target video card 3d accel %u does not match source %u"),
17045
                           dst->accel->accel3d, src->accel->accel3d);
17046
            return false;
17047 17048 17049 17050
        }
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
17051
        return false;
17052

17053
    return true;
17054 17055 17056
}


17057 17058 17059
static bool
virDomainHostdevDefCheckABIStability(virDomainHostdevDefPtr src,
                                     virDomainHostdevDefPtr dst)
17060 17061
{
    if (src->mode != dst->mode) {
17062 17063 17064 17065
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target host device mode %s does not match source %s"),
                       virDomainHostdevModeTypeToString(dst->mode),
                       virDomainHostdevModeTypeToString(src->mode));
17066
        return false;
17067 17068
    }

17069 17070 17071 17072 17073 17074 17075
    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;
17076 17077
    }

17078
    if (!virDomainDeviceInfoCheckABIStability(src->info, dst->info))
17079
        return false;
17080

17081
    return true;
17082 17083 17084
}


17085 17086 17087
static bool
virDomainSmartcardDefCheckABIStability(virDomainSmartcardDefPtr src,
                                       virDomainSmartcardDefPtr dst)
17088 17089
{
    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
17090
        return false;
17091

17092
    return true;
17093 17094 17095
}


17096 17097 17098
static bool
virDomainSerialDefCheckABIStability(virDomainChrDefPtr src,
                                    virDomainChrDefPtr dst)
17099
{
17100 17101 17102 17103 17104 17105 17106 17107
    if (src->targetType != dst->targetType) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target serial type %s does not match source %s"),
                       virDomainChrSerialTargetTypeToString(dst->targetType),
                       virDomainChrSerialTargetTypeToString(src->targetType));
        return false;
    }

17108
    if (src->target.port != dst->target.port) {
17109 17110 17111
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target serial port %d does not match source %d"),
                       dst->target.port, src->target.port);
17112
        return false;
17113 17114 17115
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
17116
        return false;
17117

17118
    return true;
17119 17120 17121
}


17122 17123 17124
static bool
virDomainParallelDefCheckABIStability(virDomainChrDefPtr src,
                                      virDomainChrDefPtr dst)
17125 17126
{
    if (src->target.port != dst->target.port) {
17127
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17128
                       _("Target parallel port %d does not match source %d"),
17129
                       dst->target.port, src->target.port);
17130
        return false;
17131 17132 17133
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
17134
        return false;
17135

17136
    return true;
17137 17138 17139
}


17140 17141 17142
static bool
virDomainChannelDefCheckABIStability(virDomainChrDefPtr src,
                                     virDomainChrDefPtr dst)
17143 17144
{
    if (src->targetType != dst->targetType) {
17145 17146 17147 17148
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target channel type %s does not match source %s"),
                       virDomainChrChannelTargetTypeToString(dst->targetType),
                       virDomainChrChannelTargetTypeToString(src->targetType));
17149
        return false;
17150 17151 17152 17153
    }

    switch (src->targetType) {
    case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO:
17154
        if (STRNEQ_NULLABLE(src->target.name, dst->target.name)) {
17155 17156 17157
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target channel name %s does not match source %s"),
                           NULLSTR(dst->target.name), NULLSTR(src->target.name));
17158
            return false;
17159
        }
17160 17161 17162 17163 17164 17165 17166
        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"));
17167
            return false;
17168
        }
17169 17170
        break;
    case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_GUESTFWD:
E
Eric Blake 已提交
17171 17172
        if (memcmp(src->target.addr, dst->target.addr,
                   sizeof(*src->target.addr)) != 0) {
17173 17174
            char *saddr = virSocketAddrFormatFull(src->target.addr, true, ":");
            char *daddr = virSocketAddrFormatFull(dst->target.addr, true, ":");
17175 17176 17177
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target channel addr %s does not match source %s"),
                           NULLSTR(daddr), NULLSTR(saddr));
17178 17179
            VIR_FREE(saddr);
            VIR_FREE(daddr);
17180
            return false;
17181 17182 17183 17184 17185
        }
        break;
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
17186
        return false;
17187

17188
    return true;
17189 17190 17191
}


17192 17193 17194
static bool
virDomainConsoleDefCheckABIStability(virDomainChrDefPtr src,
                                     virDomainChrDefPtr dst)
17195 17196
{
    if (src->targetType != dst->targetType) {
17197 17198 17199 17200
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target console type %s does not match source %s"),
                       virDomainChrConsoleTargetTypeToString(dst->targetType),
                       virDomainChrConsoleTargetTypeToString(src->targetType));
17201
        return false;
17202 17203 17204
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
17205
        return false;
17206

17207
    return true;
17208 17209 17210
}


17211 17212 17213
static bool
virDomainWatchdogDefCheckABIStability(virDomainWatchdogDefPtr src,
                                      virDomainWatchdogDefPtr dst)
17214 17215
{
    if (src->model != dst->model) {
17216 17217 17218 17219
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target watchdog model %s does not match source %s"),
                       virDomainWatchdogModelTypeToString(dst->model),
                       virDomainWatchdogModelTypeToString(src->model));
17220
        return false;
17221 17222 17223
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
17224
        return false;
17225

17226
    return true;
17227 17228 17229
}


17230 17231 17232
static bool
virDomainMemballoonDefCheckABIStability(virDomainMemballoonDefPtr src,
                                        virDomainMemballoonDefPtr dst)
17233 17234
{
    if (src->model != dst->model) {
17235 17236 17237 17238
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target balloon model %s does not match source %s"),
                       virDomainMemballoonModelTypeToString(dst->model),
                       virDomainMemballoonModelTypeToString(src->model));
17239
        return false;
17240 17241
    }

17242 17243 17244 17245 17246 17247 17248 17249 17250
    if (src->autodeflate != dst->autodeflate) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target balloon autodeflate attribute value "
                         "'%s' does not match source '%s'"),
                       virTristateSwitchTypeToString(dst->autodeflate),
                       virTristateSwitchTypeToString(src->autodeflate));
        return false;
    }

17251
    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
17252
        return false;
17253

17254
    return true;
17255 17256 17257
}


17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276
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;
}


17277 17278 17279
static bool
virDomainHubDefCheckABIStability(virDomainHubDefPtr src,
                                 virDomainHubDefPtr dst)
M
Marc-André Lureau 已提交
17280 17281
{
    if (src->type != dst->type) {
17282 17283 17284 17285
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target hub device type %s does not match source %s"),
                       virDomainHubTypeToString(dst->type),
                       virDomainHubTypeToString(src->type));
17286
        return false;
M
Marc-André Lureau 已提交
17287 17288 17289
    }

    if (!virDomainDeviceInfoCheckABIStability(&src->info, &dst->info))
17290
        return false;
M
Marc-André Lureau 已提交
17291

17292
    return true;
M
Marc-André Lureau 已提交
17293 17294
}

17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308

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;
    }

17309
    switch ((virDomainRedirdevBus) src->bus) {
17310 17311 17312 17313 17314 17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330
    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;
}


17331 17332 17333 17334
static bool
virDomainRedirFilterDefCheckABIStability(virDomainRedirFilterDefPtr src,
                                         virDomainRedirFilterDefPtr dst)
{
17335
    size_t i;
17336 17337 17338 17339 17340 17341

    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);
17342
        return false;
17343 17344 17345
    }

    for (i = 0; i < src->nusbdevs; i++) {
17346 17347 17348
        virDomainRedirFilterUSBDevDefPtr srcUSBDev = src->usbdevs[i];
        virDomainRedirFilterUSBDevDefPtr dstUSBDev = dst->usbdevs[i];
        if (srcUSBDev->usbClass != dstUSBDev->usbClass) {
17349 17350
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           "%s", _("Target USB Class code does not match source"));
17351
            return false;
17352 17353
        }

17354
        if (srcUSBDev->vendor != dstUSBDev->vendor) {
17355 17356
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           "%s", _("Target USB vendor ID does not match source"));
17357
            return false;
17358 17359
        }

17360
        if (srcUSBDev->product != dstUSBDev->product) {
17361 17362
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           "%s", _("Target USB product ID does not match source"));
17363
            return false;
17364 17365
        }

17366
        if (srcUSBDev->version != dstUSBDev->version) {
17367 17368
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           "%s", _("Target USB version does not match source"));
17369
            return false;
17370 17371
        }

17372
        if (srcUSBDev->allow != dstUSBDev->allow) {
17373 17374
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Target USB allow '%s' does not match source '%s'"),
17375 17376
                             dstUSBDev->allow ? "yes" : "no",
                             srcUSBDev->allow ? "yes" : "no");
17377
            return false;
17378 17379 17380
        }
    }

17381
    return true;
17382
}
M
Marc-André Lureau 已提交
17383

17384 17385 17386 17387 17388 17389 17390

static bool
virDomainDefFeaturesCheckABIStability(virDomainDefPtr src,
                                      virDomainDefPtr dst)
{
    size_t i;

17391 17392 17393 17394 17395 17396
    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 已提交
17397 17398
                           virTristateSwitchTypeToString(src->features[i]),
                           virTristateSwitchTypeToString(dst->features[i]));
17399 17400
            return false;
        }
17401 17402 17403 17404 17405 17406 17407
    }

    /* 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 已提交
17408 17409
                       virTristateSwitchTypeToString(src->apic_eoi),
                       virTristateSwitchTypeToString(dst->apic_eoi));
17410 17411 17412
        return false;
    }

M
Michal Privoznik 已提交
17413 17414 17415 17416 17417 17418 17419 17420
    /* GIC version */
    if (src->gic_version != dst->gic_version) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Source GIC version '%u' does not match destination '%u'"),
                       src->gic_version, dst->gic_version);
        return false;
    }

17421
    /* hyperv */
J
Ján Tomko 已提交
17422
    if (src->features[VIR_DOMAIN_FEATURE_HYPERV] == VIR_TRISTATE_SWITCH_ON) {
17423
        for (i = 0; i < VIR_DOMAIN_HYPERV_LAST; i++) {
17424
            switch ((virDomainHyperv) i) {
17425 17426 17427 17428 17429 17430 17431 17432
            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 已提交
17433 17434
                                   virTristateSwitchTypeToString(src->hyperv_features[i]),
                                   virTristateSwitchTypeToString(dst->hyperv_features[i]));
17435 17436 17437 17438 17439 17440 17441 17442 17443 17444 17445 17446 17447 17448 17449 17450 17451
                    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;

17452
            /* coverity[dead_error_begin] */
17453 17454 17455 17456 17457 17458
            case VIR_DOMAIN_HYPERV_LAST:
                break;
            }
        }
    }

17459 17460 17461 17462 17463 17464 17465 17466 17467 17468 17469 17470 17471 17472 17473 17474 17475
    /* 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;

17476
            /* coverity[dead_error_begin] */
17477 17478 17479 17480 17481 17482
            case VIR_DOMAIN_KVM_LAST:
                break;
            }
        }
    }

17483 17484 17485
    return true;
}

H
Hu Tao 已提交
17486
static bool
17487 17488
virDomainPanicDefCheckABIStability(virDomainPanicDefPtr src,
                                   virDomainPanicDefPtr dst)
H
Hu Tao 已提交
17489
{
17490 17491 17492 17493 17494 17495 17496 17497
    if (src->model != dst->model) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target panic model '%s' does not match source '%s'"),
                       virDomainPanicModelTypeToString(dst->model),
                       virDomainPanicModelTypeToString(src->model));
        return false;
    }

H
Hu Tao 已提交
17498 17499 17500
    return virDomainDeviceInfoCheckABIStability(&src->info, &dst->info);
}

17501

17502 17503 17504 17505 17506 17507 17508 17509 17510 17511 17512 17513 17514 17515 17516 17517 17518 17519 17520 17521 17522 17523 17524 17525 17526 17527 17528 17529 17530 17531 17532 17533 17534 17535 17536 17537 17538 17539
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);
}


17540 17541 17542 17543 17544 17545 17546 17547 17548 17549 17550 17551 17552 17553 17554 17555 17556 17557 17558
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);
}

17559 17560 17561 17562 17563 17564 17565 17566 17567 17568 17569 17570 17571 17572 17573
static bool
virDomainMemoryDefCheckABIStability(virDomainMemoryDefPtr src,
                                    virDomainMemoryDefPtr dst)
{
    if (src->model != dst->model) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target memory device model '%s' "
                         "doesn't match source model '%s'"),
                       virDomainMemoryModelTypeToString(dst->model),
                       virDomainMemoryModelTypeToString(src->model));
        return false;
    }

    if (src->targetNode != dst->targetNode) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17574 17575
                       _("Target memory device targetNode '%d' "
                         "doesn't match source targetNode '%d'"),
17576 17577 17578 17579 17580 17581 17582 17583 17584 17585 17586 17587 17588 17589 17590 17591
                       dst->targetNode, src->targetNode);
        return false;
    }

    if (src->size != dst->size) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target memory device size '%llu' doesn't match "
                         "source memory device size '%llu'"),
                       dst->size, src->size);
        return false;
    }

    return virDomainDeviceInfoCheckABIStability(&src->info, &dst->info);
}


17592 17593 17594 17595 17596 17597 17598 17599 17600 17601 17602 17603 17604 17605 17606 17607 17608 17609 17610 17611 17612 17613 17614 17615 17616 17617 17618 17619 17620
static bool
virDomainDefVcpuCheckAbiStability(virDomainDefPtr src,
                                  virDomainDefPtr dst)
{
    size_t i;

    if (src->maxvcpus != dst->maxvcpus) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain vCPU max %zu does not match source %zu"),
                       dst->maxvcpus, src->maxvcpus);
        return false;
    }

    for (i = 0; i < src->maxvcpus; i++) {
        virDomainVcpuInfoPtr svcpu = &src->vcpus[i];
        virDomainVcpuInfoPtr dvcpu = &dst->vcpus[i];

        if (svcpu->online != dvcpu->online) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("State of vCPU '%zu' differs between source and "
                             "destination definitions"), i);
            return false;
        }
    }

    return true;
}


17621 17622 17623 17624
/* 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
 */
17625 17626 17627
bool
virDomainDefCheckABIStability(virDomainDefPtr src,
                              virDomainDefPtr dst)
17628
{
17629
    size_t i;
17630 17631 17632
    virErrorPtr err;
    char *strSrc;
    char *strDst;
17633 17634

    if (src->virtType != dst->virtType) {
17635 17636 17637 17638
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain virt type %s does not match source %s"),
                       virDomainVirtTypeToString(dst->virtType),
                       virDomainVirtTypeToString(src->virtType));
17639
        goto error;
17640 17641 17642 17643 17644 17645 17646
    }

    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);
17647 17648 17649
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain uuid %s does not match source %s"),
                       uuiddst, uuidsrc);
17650
        goto error;
17651 17652
    }

17653 17654 17655 17656
    /* 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
     */
17657
    if (STRNEQ_NULLABLE(src->name, dst->name)) {
17658 17659 17660
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain name '%s' does not match source '%s'"),
                       dst->name, src->name);
17661
        goto error;
17662 17663
    }

17664
    if (virDomainDefGetMemoryInitial(src) != virDomainDefGetMemoryInitial(dst)) {
17665 17666
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain max memory %lld does not match source %lld"),
17667 17668
                       virDomainDefGetMemoryInitial(dst),
                       virDomainDefGetMemoryInitial(src));
17669
        goto error;
17670 17671
    }
    if (src->mem.cur_balloon != dst->mem.cur_balloon) {
17672 17673 17674
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain current memory %lld does not match source %lld"),
                       dst->mem.cur_balloon, src->mem.cur_balloon);
17675
        goto error;
17676 17677
    }

17678 17679 17680
    if (!virDomainNumaCheckABIStability(src->numa, dst->numa))
        goto error;

17681 17682
    if (src->mem.memory_slots != dst->mem.memory_slots) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17683
                       _("Target domain memory slots count '%u' doesn't match source '%u'"),
17684 17685 17686 17687 17688 17689 17690 17691 17692 17693
                       dst->mem.memory_slots, src->mem.memory_slots);
        goto error;
    }
    if (src->mem.max_memory != dst->mem.max_memory) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target maximum memory size '%llu' doesn't match source '%llu'"),
                       dst->mem.max_memory, src->mem.max_memory);
        goto error;
    }

17694
    if (!virDomainDefVcpuCheckAbiStability(src, dst))
17695
        goto error;
17696

17697 17698 17699 17700 17701 17702 17703 17704
    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;
    }

17705
    if (src->os.type != dst->os.type) {
17706 17707
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain OS type %s does not match source %s"),
17708 17709
                       virDomainOSTypeToString(dst->os.type),
                       virDomainOSTypeToString(src->os.type));
17710
        goto error;
17711
    }
17712
    if (src->os.arch != dst->os.arch) {
17713 17714
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain architecture %s does not match source %s"),
17715 17716
                       virArchToString(dst->os.arch),
                       virArchToString(src->os.arch));
17717
        goto error;
17718
    }
17719
    if (STRNEQ_NULLABLE(src->os.machine, dst->os.machine)) {
17720
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17721 17722
                    _("Target domain machine type %s does not match source %s"),
                    dst->os.machine, src->os.machine);
17723
        goto error;
17724 17725 17726
    }

    if (src->os.smbios_mode != dst->os.smbios_mode) {
17727 17728 17729 17730
        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));
17731
        goto error;
17732 17733
    }

17734
    if (!virDomainDefFeaturesCheckABIStability(src, dst))
17735
        goto error;
17736 17737

    if (src->clock.ntimers != dst->clock.ntimers) {
17738 17739
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Target domain timers do not match source"));
17740
        goto error;
17741 17742
    }

17743
    for (i = 0; i < src->clock.ntimers; i++) {
17744 17745
        if (!virDomainTimerDefCheckABIStability(src->clock.timers[i],
                                                dst->clock.timers[i]))
17746
            goto error;
17747 17748 17749
    }

    if (!virCPUDefIsEqual(src->cpu, dst->cpu))
17750
        goto error;
17751 17752

    if (!virSysinfoIsEqual(src->sysinfo, dst->sysinfo))
17753
        goto error;
17754 17755

    if (src->ndisks != dst->ndisks) {
17756
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17757
                       _("Target domain disk count %zu does not match source %zu"),
17758
                       dst->ndisks, src->ndisks);
17759
        goto error;
17760 17761
    }

17762
    for (i = 0; i < src->ndisks; i++)
17763
        if (!virDomainDiskDefCheckABIStability(src->disks[i], dst->disks[i]))
17764
            goto error;
17765 17766

    if (src->ncontrollers != dst->ncontrollers) {
17767
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17768
                       _("Target domain controller count %zu "
17769
                         "does not match source %zu"),
17770
                       dst->ncontrollers, src->ncontrollers);
17771
        goto error;
17772 17773
    }

17774
    for (i = 0; i < src->ncontrollers; i++)
17775 17776
        if (!virDomainControllerDefCheckABIStability(src->controllers[i],
                                                     dst->controllers[i]))
17777
            goto error;
17778 17779

    if (src->nfss != dst->nfss) {
17780
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17781 17782
                       _("Target domain filesystem count %zu "
                         "does not match source %zu"),
17783
                       dst->nfss, src->nfss);
17784
        goto error;
17785 17786
    }

17787
    for (i = 0; i < src->nfss; i++)
17788
        if (!virDomainFsDefCheckABIStability(src->fss[i], dst->fss[i]))
17789
            goto error;
17790 17791

    if (src->nnets != dst->nnets) {
17792
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17793 17794
                       _("Target domain net card count %zu "
                         "does not match source %zu"),
17795
                       dst->nnets, src->nnets);
17796
        goto error;
17797 17798
    }

17799
    for (i = 0; i < src->nnets; i++)
17800
        if (!virDomainNetDefCheckABIStability(src->nets[i], dst->nets[i]))
17801
            goto error;
17802 17803

    if (src->ninputs != dst->ninputs) {
17804
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17805 17806
                       _("Target domain input device count %zu "
                         "does not match source %zu"),
17807
                       dst->ninputs, src->ninputs);
17808
        goto error;
17809 17810
    }

17811
    for (i = 0; i < src->ninputs; i++)
17812
        if (!virDomainInputDefCheckABIStability(src->inputs[i], dst->inputs[i]))
17813
            goto error;
17814 17815

    if (src->nsounds != dst->nsounds) {
17816
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17817 17818
                       _("Target domain sound card count %zu "
                         "does not match source %zu"),
17819
                       dst->nsounds, src->nsounds);
17820
        goto error;
17821 17822
    }

17823
    for (i = 0; i < src->nsounds; i++)
17824
        if (!virDomainSoundDefCheckABIStability(src->sounds[i], dst->sounds[i]))
17825
            goto error;
17826 17827

    if (src->nvideos != dst->nvideos) {
17828
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17829 17830
                       _("Target domain video card count %zu "
                         "does not match source %zu"),
17831
                       dst->nvideos, src->nvideos);
17832
        goto error;
17833 17834
    }

17835
    for (i = 0; i < src->nvideos; i++)
17836
        if (!virDomainVideoDefCheckABIStability(src->videos[i], dst->videos[i]))
17837
            goto error;
17838 17839

    if (src->nhostdevs != dst->nhostdevs) {
17840
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17841 17842
                       _("Target domain host device count %zu "
                         "does not match source %zu"),
17843
                       dst->nhostdevs, src->nhostdevs);
17844
        goto error;
17845 17846
    }

17847
    for (i = 0; i < src->nhostdevs; i++)
17848 17849
        if (!virDomainHostdevDefCheckABIStability(src->hostdevs[i],
                                                  dst->hostdevs[i]))
17850
            goto error;
17851 17852

    if (src->nsmartcards != dst->nsmartcards) {
17853
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17854 17855
                       _("Target domain smartcard count %zu "
                         "does not match source %zu"),
17856
                       dst->nsmartcards, src->nsmartcards);
17857
        goto error;
17858 17859
    }

17860
    for (i = 0; i < src->nsmartcards; i++)
17861 17862
        if (!virDomainSmartcardDefCheckABIStability(src->smartcards[i],
                                                    dst->smartcards[i]))
17863
            goto error;
17864 17865

    if (src->nserials != dst->nserials) {
17866
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17867 17868
                       _("Target domain serial port count %zu "
                         "does not match source %zu"),
17869
                       dst->nserials, src->nserials);
17870
        goto error;
17871 17872
    }

17873
    for (i = 0; i < src->nserials; i++)
17874 17875
        if (!virDomainSerialDefCheckABIStability(src->serials[i],
                                                 dst->serials[i]))
17876
            goto error;
17877 17878

    if (src->nparallels != dst->nparallels) {
17879
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17880 17881
                       _("Target domain parallel port count %zu "
                         "does not match source %zu"),
17882
                       dst->nparallels, src->nparallels);
17883
        goto error;
17884 17885
    }

17886
    for (i = 0; i < src->nparallels; i++)
17887 17888
        if (!virDomainParallelDefCheckABIStability(src->parallels[i],
                                                   dst->parallels[i]))
17889
            goto error;
17890 17891

    if (src->nchannels != dst->nchannels) {
17892
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17893 17894
                       _("Target domain channel count %zu "
                         "does not match source %zu"),
17895
                       dst->nchannels, src->nchannels);
17896
        goto error;
17897 17898
    }

17899
    for (i = 0; i < src->nchannels; i++)
17900 17901
        if (!virDomainChannelDefCheckABIStability(src->channels[i],
                                                  dst->channels[i]))
17902
            goto error;
17903

17904
    if (src->nconsoles != dst->nconsoles) {
17905
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17906 17907
                       _("Target domain console count %zu "
                         "does not match source %zu"),
17908
                       dst->nconsoles, src->nconsoles);
17909
        goto error;
17910 17911
    }

17912
    for (i = 0; i < src->nconsoles; i++)
17913 17914
        if (!virDomainConsoleDefCheckABIStability(src->consoles[i],
                                                  dst->consoles[i]))
17915
            goto error;
17916

M
Marc-André Lureau 已提交
17917
    if (src->nhubs != dst->nhubs) {
17918
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17919 17920
                       _("Target domain hub device count %zu "
                         "does not match source %zu"),
17921
                       dst->nhubs, src->nhubs);
17922
        goto error;
M
Marc-André Lureau 已提交
17923 17924
    }

17925
    for (i = 0; i < src->nhubs; i++)
M
Marc-André Lureau 已提交
17926
        if (!virDomainHubDefCheckABIStability(src->hubs[i], dst->hubs[i]))
17927
            goto error;
M
Marc-André Lureau 已提交
17928

17929 17930 17931 17932
    if (src->nredirdevs != dst->nredirdevs) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain redirected devices count %zu "
                         "does not match source %zu"),
17933
                       dst->nredirdevs, src->nredirdevs);
17934 17935 17936 17937 17938 17939 17940 17941 17942
        goto error;
    }

    for (i = 0; i < src->nredirdevs; i++) {
        if (!virDomainRedirdevDefCheckABIStability(src->redirdevs[i],
                                                   dst->redirdevs[i]))
            goto error;
    }

17943 17944 17945
    if ((!src->redirfilter && dst->redirfilter) ||
        (src->redirfilter && !dst->redirfilter)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17946 17947
                       _("Target domain USB redirection filter count %d "
                         "does not match source %d"),
17948
                       dst->redirfilter ? 1 : 0, src->redirfilter ? 1 : 0);
17949
        goto error;
17950 17951 17952
    }

    if (src->redirfilter &&
17953 17954
        !virDomainRedirFilterDefCheckABIStability(src->redirfilter,
                                                  dst->redirfilter))
17955
        goto error;
17956 17957 17958

    if ((!src->watchdog && dst->watchdog) ||
        (src->watchdog && !dst->watchdog)) {
17959
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17960 17961
                       _("Target domain watchdog count %d "
                         "does not match source %d"),
17962
                       dst->watchdog ? 1 : 0, src->watchdog ? 1 : 0);
17963
        goto error;
17964 17965 17966 17967
    }

    if (src->watchdog &&
        !virDomainWatchdogDefCheckABIStability(src->watchdog, dst->watchdog))
17968
        goto error;
17969 17970 17971

    if ((!src->memballoon && dst->memballoon) ||
        (src->memballoon && !dst->memballoon)) {
17972
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
17973 17974
                       _("Target domain memory balloon count %d "
                         "does not match source %d"),
17975
                       dst->memballoon ? 1 : 0, src->memballoon ? 1 : 0);
17976
        goto error;
17977 17978 17979
    }

    if (src->memballoon &&
17980 17981
        !virDomainMemballoonDefCheckABIStability(src->memballoon,
                                                 dst->memballoon))
17982
        goto error;
17983

17984 17985 17986 17987
    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);
17988
        goto error;
17989 17990 17991 17992 17993
    }

    for (i = 0; i < src->nrngs; i++)
        if (!virDomainRNGDefCheckABIStability(src->rngs[i], dst->rngs[i]))
            goto error;
17994

D
Dmitry Andreev 已提交
17995 17996 17997 17998
    if (src->npanics != dst->npanics) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain panic device count %zu "
                         "does not match source %zu"), dst->npanics, src->npanics);
17999
        goto error;
D
Dmitry Andreev 已提交
18000 18001 18002 18003 18004 18005
    }

    for (i = 0; i < src->npanics; i++) {
        if (!virDomainPanicDefCheckABIStability(src->panics[i], dst->panics[i]))
            goto error;
    }
H
Hu Tao 已提交
18006

18007 18008 18009 18010 18011 18012 18013 18014 18015 18016 18017 18018
    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;
    }

18019 18020 18021 18022 18023 18024 18025 18026 18027 18028
    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;
    }

18029 18030 18031 18032 18033 18034 18035 18036 18037 18038 18039 18040
    if (src->nmems != dst->nmems) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Target domain memory device count %zu "
                         "does not match source %zu"), dst->nmems, src->nmems);
        goto error;
    }

    for (i = 0; i < src->nmems; i++) {
        if (!virDomainMemoryDefCheckABIStability(src->mems[i], dst->mems[i]))
            goto error;
    }

18041 18042 18043 18044 18045 18046 18047 18048 18049 18050 18051 18052 18053 18054 18055 18056 18057 18058 18059 18060 18061 18062 18063 18064 18065 18066 18067 18068
    /* 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:
18069
    case VIR_DOMAIN_DEVICE_TPM:
18070
    case VIR_DOMAIN_DEVICE_PANIC:
18071
    case VIR_DOMAIN_DEVICE_SHMEM:
18072
    case VIR_DOMAIN_DEVICE_MEMORY:
18073 18074 18075 18076
        break;
    }
#endif

18077
    return true;
18078

18079
 error:
18080 18081
    err = virSaveLastError();

18082 18083
    strSrc = virDomainDefFormat(src, NULL, 0);
    strDst = virDomainDefFormat(dst, NULL, 0);
18084 18085 18086 18087 18088 18089 18090 18091 18092 18093
    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;
18094 18095 18096
}


18097 18098 18099 18100
static int
virDomainDefAddDiskControllersForType(virDomainDefPtr def,
                                      int controllerType,
                                      int diskBus)
18101
{
18102
    size_t i;
18103 18104
    int maxController = -1;

18105
    for (i = 0; i < def->ndisks; i++) {
18106 18107 18108 18109 18110 18111 18112 18113 18114 18115
        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;
    }

18116 18117 18118
    if (maxController == -1)
        return 0;

18119
    for (i = 0; i <= maxController; i++) {
18120
        if (virDomainDefMaybeAddController(def, controllerType, i, -1) < 0)
18121 18122 18123 18124 18125 18126 18127
            return -1;
    }

    return 0;
}


18128 18129
static int
virDomainDefMaybeAddVirtioSerialController(virDomainDefPtr def)
18130
{
C
Cole Robinson 已提交
18131
    /* Look for any virtio serial or virtio console devs */
18132
    size_t i;
18133

18134
    for (i = 0; i < def->nchannels; i++) {
18135 18136
        virDomainChrDefPtr channel = def->channels[i];

18137
        if (channel->targetType == VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO) {
18138 18139 18140 18141
            int idx = 0;
            if (channel->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_SERIAL)
                idx = channel->info.addr.vioserial.controller;

18142
            if (virDomainDefMaybeAddController(def,
18143
                VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL, idx, -1) < 0)
18144 18145 18146 18147
                return -1;
        }
    }

18148
    for (i = 0; i < def->nconsoles; i++) {
18149
        virDomainChrDefPtr console = def->consoles[i];
C
Cole Robinson 已提交
18150 18151 18152 18153 18154 18155 18156 18157

        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,
18158
                VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL, idx, -1) < 0)
C
Cole Robinson 已提交
18159 18160 18161 18162
                return -1;
        }
    }

18163 18164 18165 18166
    return 0;
}


E
Eric Blake 已提交
18167 18168 18169 18170
static int
virDomainDefMaybeAddSmartcardController(virDomainDefPtr def)
{
    /* Look for any smartcard devs */
18171
    size_t i;
E
Eric Blake 已提交
18172

18173
    for (i = 0; i < def->nsmartcards; i++) {
E
Eric Blake 已提交
18174 18175 18176 18177 18178 18179 18180
        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) {
18181
            size_t j;
E
Eric Blake 已提交
18182 18183 18184 18185 18186 18187 18188 18189 18190 18191 18192 18193 18194 18195 18196 18197
            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,
18198
                                           idx, -1) < 0)
E
Eric Blake 已提交
18199 18200 18201 18202 18203 18204
            return -1;
    }

    return 0;
}

18205
/*
18206
 * Based on the declared <address/> info for any devices,
18207
 * add necessary drive controllers which are not already present
18208 18209 18210
 * in the XML. This is for compat with existing apps which will
 * not know/care about <controller> info in the XML
 */
18211 18212
int
virDomainDefAddImplicitControllers(virDomainDefPtr def)
18213 18214 18215 18216 18217 18218 18219 18220 18221 18222 18223 18224 18225 18226 18227 18228
{
    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 已提交
18229 18230 18231 18232 18233
    if (virDomainDefAddDiskControllersForType(def,
                                              VIR_DOMAIN_CONTROLLER_TYPE_SATA,
                                              VIR_DOMAIN_DISK_BUS_SATA) < 0)
        return -1;

18234 18235 18236
    if (virDomainDefMaybeAddVirtioSerialController(def) < 0)
        return -1;

E
Eric Blake 已提交
18237 18238 18239
    if (virDomainDefMaybeAddSmartcardController(def) < 0)
        return -1;

H
Han Cheng 已提交
18240 18241 18242
    if (virDomainDefMaybeAddHostdevSCSIcontroller(def) < 0)
        return -1;

18243 18244 18245
    return 0;
}

18246 18247 18248 18249 18250 18251 18252 18253 18254 18255 18256 18257 18258 18259 18260 18261 18262 18263 18264 18265 18266 18267 18268 18269 18270 18271 18272 18273 18274 18275 18276 18277 18278 18279 18280 18281 18282 18283 18284 18285 18286 18287 18288 18289 18290 18291
virDomainIOThreadIDDefPtr
virDomainIOThreadIDFind(virDomainDefPtr def,
                        unsigned int iothread_id)
{
    size_t i;

    if (!def->iothreadids || !def->niothreadids)
        return NULL;

    for (i = 0; i < def->niothreadids; i++) {
        if (iothread_id == def->iothreadids[i]->iothread_id)
            return def->iothreadids[i];
    }

    return NULL;
}

virDomainIOThreadIDDefPtr
virDomainIOThreadIDAdd(virDomainDefPtr def,
                       unsigned int iothread_id)
{
    virDomainIOThreadIDDefPtr iothrid = NULL;

    if (virDomainIOThreadIDFind(def, iothread_id)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot duplicate iothread_id '%u' in iothreadids"),
                       iothread_id);
        return NULL;
    }

    if (VIR_ALLOC(iothrid) < 0)
        goto error;

    iothrid->iothread_id = iothread_id;

    if (VIR_APPEND_ELEMENT_COPY(def->iothreadids, def->niothreadids,
                                iothrid) < 0)
        goto error;

    return iothrid;

 error:
    virDomainIOThreadIDDefFree(iothrid);
    return NULL;
}

18292 18293 18294 18295 18296 18297 18298 18299 18300 18301 18302 18303 18304 18305 18306 18307 18308 18309 18310 18311 18312 18313 18314 18315 18316 18317 18318 18319 18320

/*
 * virDomainIOThreadIDMap:
 * @def: domain definition
 *
 * Returns a map of active iothreads for @def.
 */
virBitmapPtr
virDomainIOThreadIDMap(virDomainDefPtr def)
{
    unsigned int max = 0;
    size_t i;
    virBitmapPtr ret = NULL;

    for (i = 0; i < def->niothreadids; i++) {
        if (def->iothreadids[i]->iothread_id > max)
            max = def->iothreadids[i]->iothread_id;
    }

    if (!(ret = virBitmapNew(max)))
        return NULL;

    for (i = 0; i < def->niothreadids; i++)
        ignore_value(virBitmapSetBit(ret, def->iothreadids[i]->iothread_id));

    return ret;
}


18321 18322 18323 18324
void
virDomainIOThreadIDDel(virDomainDefPtr def,
                       unsigned int iothread_id)
{
18325 18326 18327 18328 18329 18330 18331 18332 18333 18334 18335 18336 18337 18338
    size_t i, j;

    for (i = 0; i < def->niothreadids; i++) {
        if (def->iothreadids[i]->iothread_id == iothread_id) {
            /* If we were sequential and removed a threadid in the
             * beginning or middle of the list, then unconditionally
             * clear the autofill flag so we don't lose these
             * definitions for XML formatting.
             */
            for (j = i + 1; j < def->niothreadids; j++)
                def->iothreadids[j]->autofill = false;

            virDomainIOThreadIDDefFree(def->iothreadids[i]);
            VIR_DELETE_ELEMENT(def->iothreadids, i, def->niothreadids);
18339 18340 18341 18342 18343 18344

            return;
        }
    }
}

18345 18346 18347 18348 18349 18350 18351 18352 18353 18354 18355 18356 18357 18358 18359 18360 18361 18362 18363 18364 18365 18366 18367
void
virDomainIOThreadSchedDelId(virDomainDefPtr def,
                            unsigned int iothreadid)
{
    size_t i;

    if (!def->cputune.iothreadsched || !def->cputune.niothreadsched)
        return;

    for (i = 0; i < def->cputune.niothreadsched; i++) {
        if (virBitmapIsBitSet(def->cputune.iothreadsched[i].ids, iothreadid)) {
            ignore_value(virBitmapClearBit(def->cputune.iothreadsched[i].ids,
                                           iothreadid));
            if (virBitmapIsAllClear(def->cputune.iothreadsched[i].ids)) {
                virBitmapFree(def->cputune.iothreadsched[i].ids);
                VIR_DELETE_ELEMENT(def->cputune.iothreadsched, i,
                                   def->cputune.niothreadsched);
            }
            return;
        }
    }
}

18368

18369
static int
18370 18371 18372 18373
virDomainEventActionDefFormat(virBufferPtr buf,
                              int type,
                              const char *name,
                              virEventActionToStringFunc convFunc)
18374
{
18375
    const char *typeStr = convFunc(type);
18376
    if (!typeStr) {
18377
        virReportError(VIR_ERR_INTERNAL_ERROR,
18378
                       _("unexpected %s action: %d"), name, type);
18379 18380 18381
        return -1;
    }

18382
    virBufferAsprintf(buf, "<%s>%s</%s>\n", name, typeStr, name);
18383 18384 18385 18386 18387

    return 0;
}


18388
static void
18389
virSecurityLabelDefFormat(virBufferPtr buf,
18390
                          virSecurityLabelDefPtr def)
18391 18392 18393 18394
{
    const char *sectype = virDomainSeclabelTypeToString(def->type);

    if (!sectype)
18395 18396 18397 18398 18399
        return;

    if (def->type == VIR_DOMAIN_SECLABEL_DEFAULT)
        return;

18400 18401
    /* To avoid backward compatibility issues, suppress DAC and 'none' labels
     * that are automatically generated.
18402
     */
18403 18404
    if ((STREQ_NULLABLE(def->model, "dac") ||
         STREQ_NULLABLE(def->model, "none")) && def->implicit)
18405 18406
        return;

18407 18408 18409
    virBufferAsprintf(buf, "<seclabel type='%s'",
                      sectype);

18410
    virBufferEscapeString(buf, " model='%s'", def->model);
18411

18412 18413 18414 18415 18416
    if (def->type == VIR_DOMAIN_SECLABEL_NONE) {
        virBufferAddLit(buf, "/>\n");
        return;
    }

18417
    virBufferAsprintf(buf, " relabel='%s'",
18418
                      def->relabel ? "yes" : "no");
18419

18420 18421
    if (def->label || def->imagelabel || def->baselabel) {
        virBufferAddLit(buf, ">\n");
18422 18423
        virBufferAdjustIndent(buf, 2);
        virBufferEscapeString(buf, "<label>%s</label>\n",
18424
                              def->label);
18425
        if (def->relabel)
18426
            virBufferEscapeString(buf, "<imagelabel>%s</imagelabel>\n",
18427 18428
                                  def->imagelabel);
        if (def->type == VIR_DOMAIN_SECLABEL_DYNAMIC)
18429
            virBufferEscapeString(buf, "<baselabel>%s</baselabel>\n",
18430
                                  def->baselabel);
18431
        virBufferAdjustIndent(buf, -2);
18432
        virBufferAddLit(buf, "</seclabel>\n");
18433 18434
    } else {
        virBufferAddLit(buf, "/>\n");
18435 18436 18437 18438
    }
}


18439 18440
static void
virSecurityDeviceLabelDefFormat(virBufferPtr buf,
18441 18442
                                virSecurityDeviceLabelDefPtr def,
                                unsigned int flags)
18443
{
18444 18445
    /* For offline output, skip elements that allow labels but have no
     * label specified (possible if labelskip was ignored on input).  */
18446
    if ((flags & VIR_DOMAIN_DEF_FORMAT_INACTIVE) && !def->label && def->relabel)
18447 18448
        return;

18449
    virBufferAddLit(buf, "<seclabel");
18450 18451

    if (def->model)
18452
        virBufferEscapeString(buf, " model='%s'", def->model);
18453

18454 18455 18456
    if (def->labelskip)
        virBufferAddLit(buf, " labelskip='yes'");
    else
18457
        virBufferAsprintf(buf, " relabel='%s'", def->relabel ? "yes" : "no");
18458

18459 18460
    if (def->label) {
        virBufferAddLit(buf, ">\n");
18461 18462
        virBufferAdjustIndent(buf, 2);
        virBufferEscapeString(buf, "<label>%s</label>\n",
18463
                              def->label);
18464
        virBufferAdjustIndent(buf, -2);
18465 18466 18467 18468 18469 18470 18471
        virBufferAddLit(buf, "</seclabel>\n");
    } else {
        virBufferAddLit(buf, "/>\n");
    }
}


18472 18473 18474 18475
static int
virDomainLeaseDefFormat(virBufferPtr buf,
                        virDomainLeaseDefPtr def)
{
18476 18477 18478 18479 18480
    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);
18481 18482 18483
    if (def->offset)
        virBufferAsprintf(buf, " offset='%llu'", def->offset);
    virBufferAddLit(buf, "/>\n");
18484 18485
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</lease>\n");
18486 18487 18488 18489

    return 0;
}

18490 18491 18492
static void
virDomainDiskGeometryDefFormat(virBufferPtr buf,
                               virDomainDiskDefPtr def)
J
J.B. Joret 已提交
18493 18494 18495 18496 18497 18498 18499 18500
{
    const char *trans =
        virDomainDiskGeometryTransTypeToString(def->geometry.trans);

    if (def->geometry.cylinders > 0 &&
        def->geometry.heads > 0 &&
        def->geometry.sectors > 0) {
        virBufferAsprintf(buf,
18501
                          "<geometry cyls='%u' heads='%u' secs='%u'",
J
J.B. Joret 已提交
18502 18503 18504 18505 18506 18507 18508 18509 18510 18511
                          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");
    }
}
18512

18513 18514 18515
static void
virDomainDiskBlockIoDefFormat(virBufferPtr buf,
                              virDomainDiskDefPtr def)
18516
{
V
Viktor Mihajlovski 已提交
18517 18518
    if (def->blockio.logical_block_size > 0 ||
        def->blockio.physical_block_size > 0) {
18519
        virBufferAddLit(buf, "<blockio");
V
Viktor Mihajlovski 已提交
18520
        if (def->blockio.logical_block_size > 0) {
18521 18522
            virBufferAsprintf(buf,
                              " logical_block_size='%u'",
V
Viktor Mihajlovski 已提交
18523
                              def->blockio.logical_block_size);
18524
        }
V
Viktor Mihajlovski 已提交
18525
        if (def->blockio.physical_block_size > 0) {
18526 18527
            virBufferAsprintf(buf,
                              " physical_block_size='%u'",
V
Viktor Mihajlovski 已提交
18528
                              def->blockio.physical_block_size);
18529 18530 18531 18532 18533
        }
        virBufferAddLit(buf, "/>\n");
    }
}

18534

18535
/* virDomainSourceDefFormatSeclabel:
18536 18537 18538 18539 18540
 *
 * This function automaticaly closes the <source> element and formats any
 * possible seclabels.
 */
static void
18541 18542 18543 18544 18545
virDomainDiskSourceDefFormatSeclabel(virBufferPtr buf,
                                     size_t nseclabels,
                                     virSecurityDeviceLabelDefPtr *seclabels,
                                     unsigned int flags,
                                     bool skipSeclables)
18546 18547 18548
{
    size_t n;

18549
    if (nseclabels && !skipSeclables) {
18550
        virBufferAddLit(buf, ">\n");
18551
        virBufferAdjustIndent(buf, 2);
18552 18553
        for (n = 0; n < nseclabels; n++)
            virSecurityDeviceLabelDefFormat(buf, seclabels[n], flags);
18554 18555
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</source>\n");
18556 18557 18558 18559 18560
    } else {
        virBufferAddLit(buf, "/>\n");
    }
}

18561 18562 18563 18564 18565 18566 18567 18568 18569 18570 18571 18572 18573 18574 18575
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)
18576
{
18577
    size_t n;
18578
    char *path = NULL;
18579
    const char *startupPolicy = NULL;
18580

18581 18582 18583
    if (policy)
        startupPolicy = virDomainStartupPolicyTypeToString(policy);

18584
    if (src->path || src->nhosts > 0 || src->srcpool || startupPolicy) {
18585
        switch ((virStorageType)src->type) {
E
Eric Blake 已提交
18586
        case VIR_STORAGE_TYPE_FILE:
18587
            virBufferAddLit(buf, "<source");
18588
            virBufferEscapeString(buf, " file='%s'", src->path);
18589 18590
            virBufferEscapeString(buf, " startupPolicy='%s'", startupPolicy);

18591 18592 18593
            virDomainDiskSourceDefFormatSeclabel(buf, src->nseclabels,
                                                 src->seclabels, flags,
                                                 skipSeclabels);
18594
            break;
18595

E
Eric Blake 已提交
18596
        case VIR_STORAGE_TYPE_BLOCK:
18597
            virBufferAddLit(buf, "<source");
18598
            virBufferEscapeString(buf, " dev='%s'", src->path);
18599 18600
            virBufferEscapeString(buf, " startupPolicy='%s'", startupPolicy);

18601 18602 18603
            virDomainDiskSourceDefFormatSeclabel(buf, src->nseclabels,
                                                 src->seclabels, flags,
                                                 skipSeclabels);
18604
            break;
18605

E
Eric Blake 已提交
18606
        case VIR_STORAGE_TYPE_DIR:
18607
            virBufferAddLit(buf, "<source");
18608
            virBufferEscapeString(buf, " dir='%s'", src->path);
18609
            virBufferEscapeString(buf, " startupPolicy='%s'", startupPolicy);
18610
            virBufferAddLit(buf, "/>\n");
18611
            break;
18612

E
Eric Blake 已提交
18613
        case VIR_STORAGE_TYPE_NETWORK:
18614
            virBufferAsprintf(buf, "<source protocol='%s'",
18615
                              virStorageNetProtocolTypeToString(src->protocol));
18616 18617 18618 18619 18620 18621 18622 18623 18624 18625


            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);
18626

18627
            if (src->nhosts == 0 && !src->snapshot && !src->configFile) {
18628 18629 18630
                virBufferAddLit(buf, "/>\n");
            } else {
                virBufferAddLit(buf, ">\n");
18631
                virBufferAdjustIndent(buf, 2);
18632

18633
                for (n = 0; n < src->nhosts; n++) {
18634
                    virBufferAddLit(buf, "<host");
18635 18636 18637 18638
                    virBufferEscapeString(buf, " name='%s'",
                                          src->hosts[n].name);
                    virBufferEscapeString(buf, " port='%s'",
                                          src->hosts[n].port);
18639

18640
                    if (src->hosts[n].transport)
18641
                        virBufferAsprintf(buf, " transport='%s'",
18642
                                          virStorageNetHostTransportTypeToString(src->hosts[n].transport));
18643

18644 18645
                    virBufferEscapeString(buf, " socket='%s'",
                                          src->hosts[n].socket);
18646

18647 18648
                    virBufferAddLit(buf, "/>\n");
                }
18649 18650 18651 18652

                virBufferEscapeString(buf, "<snapshot name='%s'/>\n",
                                      src->snapshot);

18653 18654 18655
                virBufferEscapeString(buf, "<config file='%s'/>\n",
                                      src->configFile);

18656 18657
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</source>\n");
18658 18659
            }
            break;
18660

E
Eric Blake 已提交
18661
        case VIR_STORAGE_TYPE_VOLUME:
18662
            virBufferAddLit(buf, "<source");
18663

18664 18665 18666 18667 18668
            if (src->srcpool) {
                virBufferEscapeString(buf, " pool='%s'", src->srcpool->pool);
                virBufferEscapeString(buf, " volume='%s'",
                                      src->srcpool->volume);
                if (src->srcpool->mode)
18669
                    virBufferAsprintf(buf, " mode='%s'",
18670
                                      virStorageSourcePoolModeTypeToString(src->srcpool->mode));
18671
            }
18672
            virBufferEscapeString(buf, " startupPolicy='%s'", startupPolicy);
18673

18674 18675 18676
            virDomainDiskSourceDefFormatSeclabel(buf, src->nseclabels,
                                                 src->seclabels, flags,
                                                 skipSeclabels);
18677
            break;
18678

18679
        case VIR_STORAGE_TYPE_NONE:
18680
        case VIR_STORAGE_TYPE_LAST:
18681
            virReportError(VIR_ERR_INTERNAL_ERROR,
18682
                           _("unexpected disk type %d"), src->type);
18683 18684 18685 18686 18687 18688
            return -1;
        }
    }

    return 0;
}
J
J.B. Joret 已提交
18689

18690

18691 18692 18693 18694 18695 18696 18697 18698 18699 18700
int
virDomainDiskSourceFormat(virBufferPtr buf,
                          virStorageSourcePtr src,
                          int policy,
                          unsigned int flags)
{
    return virDomainDiskSourceFormatInternal(buf, src, policy, flags, false);
}


18701 18702 18703 18704
static int
virDomainDiskBackingStoreFormat(virBufferPtr buf,
                                virStorageSourcePtr backingStore,
                                const char *backingStoreRaw,
18705
                                unsigned int idx)
18706 18707 18708 18709 18710 18711 18712 18713 18714 18715 18716 18717 18718 18719 18720 18721 18722 18723 18724 18725 18726 18727 18728 18729 18730 18731 18732
{
    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",
18733
                      type, idx);
18734 18735 18736
    virBufferAdjustIndent(buf, 2);

    virBufferAsprintf(buf, "<format type='%s'/>\n", format);
18737 18738
    /* We currently don't output seclabels for backing chain element */
    if (virDomainDiskSourceFormatInternal(buf, backingStore, 0, 0, true) < 0 ||
18739 18740 18741
        virDomainDiskBackingStoreFormat(buf,
                                        backingStore->backingStore,
                                        backingStore->backingStoreRaw,
18742
                                        idx + 1) < 0)
18743 18744 18745 18746 18747 18748 18749 18750
        return -1;

    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</backingStore>\n");
    return 0;
}


18751
static int
18752
virDomainDiskDefFormat(virBufferPtr buf,
D
Daniel P. Berrange 已提交
18753
                       virDomainDiskDefPtr def,
E
Eric Blake 已提交
18754
                       unsigned int flags)
18755
{
18756
    const char *type = virStorageTypeToString(def->src->type);
18757 18758
    const char *device = virDomainDiskDeviceTypeToString(def->device);
    const char *bus = virDomainDiskBusTypeToString(def->bus);
18759
    const char *cachemode = virDomainDiskCacheTypeToString(def->cachemode);
18760
    const char *error_policy = virDomainDiskErrorPolicyTypeToString(def->error_policy);
18761
    const char *rerror_policy = virDomainDiskErrorPolicyTypeToString(def->rerror_policy);
M
Matthias Dahl 已提交
18762
    const char *iomode = virDomainDiskIoTypeToString(def->iomode);
J
Ján Tomko 已提交
18763 18764 18765
    const char *ioeventfd = virTristateSwitchTypeToString(def->ioeventfd);
    const char *event_idx = virTristateSwitchTypeToString(def->event_idx);
    const char *copy_on_read = virTristateSwitchTypeToString(def->copy_on_read);
18766
    const char *sgio = virDomainDeviceSGIOTypeToString(def->sgio);
O
Osier Yang 已提交
18767
    const char *discard = virDomainDiskDiscardTypeToString(def->discard);
18768

18769
    if (!type || !def->src->type) {
18770
        virReportError(VIR_ERR_INTERNAL_ERROR,
18771
                       _("unexpected disk type %d"), def->src->type);
18772 18773 18774
        return -1;
    }
    if (!device) {
18775 18776
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected disk device %d"), def->device);
18777 18778 18779
        return -1;
    }
    if (!bus) {
18780 18781
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected disk bus %d"), def->bus);
18782 18783
        return -1;
    }
18784
    if (!cachemode) {
18785 18786
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected disk cache mode %d"), def->cachemode);
18787 18788
        return -1;
    }
M
Matthias Dahl 已提交
18789
    if (!iomode) {
18790 18791
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected disk io mode %d"), def->iomode);
M
Matthias Dahl 已提交
18792 18793
        return -1;
    }
O
Osier Yang 已提交
18794 18795 18796 18797 18798
    if (!sgio) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unexpected disk sgio mode '%d'"), def->sgio);
        return -1;
    }
18799

18800
    virBufferAsprintf(buf,
18801
                      "<disk type='%s' device='%s'",
18802
                      type, device);
18803 18804 18805
    if (def->rawio) {
        virBufferAsprintf(buf, " rawio='%s'",
                          virTristateBoolTypeToString(def->rawio));
18806
    }
O
Osier Yang 已提交
18807 18808 18809 18810

    if (def->sgio)
        virBufferAsprintf(buf, " sgio='%s'", sgio);

18811
    if (def->snapshot &&
18812 18813
        !(def->snapshot == VIR_DOMAIN_SNAPSHOT_LOCATION_NONE &&
          def->src->readonly))
18814
        virBufferAsprintf(buf, " snapshot='%s'",
E
Eric Blake 已提交
18815
                          virDomainSnapshotLocationTypeToString(def->snapshot));
18816
    virBufferAddLit(buf, ">\n");
18817
    virBufferAdjustIndent(buf, 2);
18818

18819
    if (def->src->driverName || def->src->format > 0 || def->cachemode ||
18820 18821
        def->error_policy || def->rerror_policy || def->iomode ||
        def->ioeventfd || def->event_idx || def->copy_on_read ||
18822
        def->discard || def->iothread) {
18823
        virBufferAddLit(buf, "<driver");
18824
        virBufferEscapeString(buf, " name='%s'", def->src->driverName);
18825
        if (def->src->format > 0)
18826
            virBufferAsprintf(buf, " type='%s'",
18827
                              virStorageFileFormatTypeToString(def->src->format));
18828
        if (def->cachemode)
18829
            virBufferAsprintf(buf, " cache='%s'", cachemode);
18830
        if (def->error_policy)
18831
            virBufferAsprintf(buf, " error_policy='%s'", error_policy);
18832 18833
        if (def->rerror_policy)
            virBufferAsprintf(buf, " rerror_policy='%s'", rerror_policy);
M
Matthias Dahl 已提交
18834
        if (def->iomode)
18835
            virBufferAsprintf(buf, " io='%s'", iomode);
18836 18837
        if (def->ioeventfd)
            virBufferAsprintf(buf, " ioeventfd='%s'", ioeventfd);
18838 18839
        if (def->event_idx)
            virBufferAsprintf(buf, " event_idx='%s'", event_idx);
O
Osier Yang 已提交
18840 18841
        if (def->copy_on_read)
            virBufferAsprintf(buf, " copy_on_read='%s'", copy_on_read);
O
Osier Yang 已提交
18842 18843
        if (def->discard)
            virBufferAsprintf(buf, " discard='%s'", discard);
18844 18845
        if (def->iothread)
            virBufferAsprintf(buf, " iothread='%u'", def->iothread);
18846
        virBufferAddLit(buf, "/>\n");
18847 18848
    }

18849 18850 18851
    if (def->src->auth) {
        if (virStorageAuthDefFormat(buf, def->src->auth) < 0)
            return -1;
18852 18853
    }

18854
    if (virDomainDiskSourceFormat(buf, def->src, def->startupPolicy,
18855
                                  flags) < 0)
18856
        return -1;
18857 18858 18859

    /* Don't format backingStore to inactive XMLs until the code for
     * persistent storage of backing chains is ready. */
18860
    if (!(flags & VIR_DOMAIN_DEF_FORMAT_INACTIVE) &&
18861 18862
        virDomainDiskBackingStoreFormat(buf, def->src->backingStore,
                                        def->src->backingStoreRaw, 1) < 0)
18863 18864
        return -1;

18865 18866
    virBufferEscapeString(buf, "<backenddomain name='%s'/>\n", def->domain_name);

J
J.B. Joret 已提交
18867
    virDomainDiskGeometryDefFormat(buf, def);
V
Viktor Mihajlovski 已提交
18868
    virDomainDiskBlockIoDefFormat(buf, def);
J
J.B. Joret 已提交
18869

18870 18871
    /* For now, mirroring is currently output-only: we only output it
     * for live domains, therefore we ignore it on input except for
18872 18873 18874 18875
     * 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. */
18876
    if (def->mirror && !(flags & VIR_DOMAIN_DEF_FORMAT_INACTIVE)) {
18877 18878 18879 18880
        const char *formatStr = NULL;

        if (def->mirror->format)
            formatStr = virStorageFileFormatTypeToString(def->mirror->format);
E
Eric Blake 已提交
18881 18882
        virBufferAsprintf(buf, "<mirror type='%s'",
                          virStorageTypeToString(def->mirror->type));
E
Eric Blake 已提交
18883 18884
        if (def->mirror->type == VIR_STORAGE_TYPE_FILE &&
            def->mirrorJob == VIR_DOMAIN_BLOCK_JOB_TYPE_COPY) {
18885 18886 18887
            virBufferEscapeString(buf, " file='%s'", def->mirror->path);
            virBufferEscapeString(buf, " format='%s'", formatStr);
        }
E
Eric Blake 已提交
18888 18889
        virBufferEscapeString(buf, " job='%s'",
                              virDomainBlockJobTypeToString(def->mirrorJob));
18890 18891 18892 18893 18894 18895
        if (def->mirrorState) {
            const char *mirror;

            mirror = virDomainDiskMirrorStateTypeToString(def->mirrorState);
            virBufferEscapeString(buf, " ready='%s'", mirror);
        }
E
Eric Blake 已提交
18896 18897
        virBufferAddLit(buf, ">\n");
        virBufferAdjustIndent(buf, 2);
18898
        virBufferEscapeString(buf, "<format type='%s'/>\n", formatStr);
E
Eric Blake 已提交
18899 18900 18901 18902
        if (virDomainDiskSourceFormat(buf, def->mirror, 0, 0) < 0)
            return -1;
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</mirror>\n");
18903 18904
    }

18905
    virBufferAsprintf(buf, "<target dev='%s' bus='%s'",
18906
                      def->dst, bus);
18907 18908
    if ((def->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY ||
         def->device == VIR_DOMAIN_DISK_DEVICE_CDROM) &&
E
Eric Blake 已提交
18909
        def->tray_status != VIR_DOMAIN_DISK_TRAY_CLOSED)
18910
        virBufferAsprintf(buf, " tray='%s'",
18911
                          virDomainDiskTrayTypeToString(def->tray_status));
18912
    if (def->bus == VIR_DOMAIN_DISK_BUS_USB &&
J
Ján Tomko 已提交
18913
        def->removable != VIR_TRISTATE_SWITCH_ABSENT) {
18914
        virBufferAsprintf(buf, " removable='%s'",
J
Ján Tomko 已提交
18915
                          virTristateSwitchTypeToString(def->removable));
18916 18917
    }
    virBufferAddLit(buf, "/>\n");
18918

L
Lei Li 已提交
18919 18920 18921 18922 18923 18924
    /*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 ||
18925 18926 18927 18928 18929 18930 18931 18932
        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) {
18933 18934
        virBufferAddLit(buf, "<iotune>\n");
        virBufferAdjustIndent(buf, 2);
L
Lei Li 已提交
18935
        if (def->blkdeviotune.total_bytes_sec) {
18936
            virBufferAsprintf(buf, "<total_bytes_sec>%llu</total_bytes_sec>\n",
L
Lei Li 已提交
18937 18938 18939 18940
                              def->blkdeviotune.total_bytes_sec);
        }

        if (def->blkdeviotune.read_bytes_sec) {
18941
            virBufferAsprintf(buf, "<read_bytes_sec>%llu</read_bytes_sec>\n",
L
Lei Li 已提交
18942 18943 18944 18945 18946
                              def->blkdeviotune.read_bytes_sec);

        }

        if (def->blkdeviotune.write_bytes_sec) {
18947
            virBufferAsprintf(buf, "<write_bytes_sec>%llu</write_bytes_sec>\n",
L
Lei Li 已提交
18948 18949 18950 18951
                              def->blkdeviotune.write_bytes_sec);
        }

        if (def->blkdeviotune.total_iops_sec) {
18952
            virBufferAsprintf(buf, "<total_iops_sec>%llu</total_iops_sec>\n",
L
Lei Li 已提交
18953 18954 18955 18956
                              def->blkdeviotune.total_iops_sec);
        }

        if (def->blkdeviotune.read_iops_sec) {
18957
            virBufferAsprintf(buf, "<read_iops_sec>%llu</read_iops_sec>\n",
L
Lei Li 已提交
18958 18959 18960 18961
                              def->blkdeviotune.read_iops_sec);
        }

        if (def->blkdeviotune.write_iops_sec) {
18962
            virBufferAsprintf(buf, "<write_iops_sec>%llu</write_iops_sec>\n",
L
Lei Li 已提交
18963 18964
                              def->blkdeviotune.write_iops_sec);
        }
18965 18966 18967 18968 18969 18970 18971 18972 18973 18974 18975 18976 18977 18978 18979 18980 18981 18982 18983 18984 18985 18986 18987 18988 18989 18990 18991 18992 18993 18994 18995 18996 18997 18998 18999 19000

        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);
        }

19001 19002
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</iotune>\n");
L
Lei Li 已提交
19003 19004
    }

19005
    if (def->src->readonly)
19006
        virBufferAddLit(buf, "<readonly/>\n");
19007
    if (def->src->shared)
19008
        virBufferAddLit(buf, "<shareable/>\n");
19009
    if (def->transient)
19010 19011 19012 19013 19014
        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);
19015 19016
    if (def->src->encryption &&
        virStorageEncryptionFormat(buf, def->src->encryption) < 0)
19017
        return -1;
19018
    if (virDomainDeviceInfoFormat(buf, &def->info,
19019
                                  flags | VIR_DOMAIN_DEF_FORMAT_ALLOW_BOOT) < 0)
19020
        return -1;
19021

19022 19023
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</disk>\n");
19024 19025 19026
    return 0;
}

19027 19028 19029 19030 19031 19032
static const char *
virDomainControllerModelTypeToString(virDomainControllerDefPtr def,
                                     int model)
{
    if (def->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI)
        return virDomainControllerModelSCSITypeToString(model);
19033 19034
    else if (def->type == VIR_DOMAIN_CONTROLLER_TYPE_USB)
        return virDomainControllerModelUSBTypeToString(model);
J
Ján Tomko 已提交
19035 19036
    else if (def->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI)
        return virDomainControllerModelPCITypeToString(model);
19037 19038 19039 19040

    return NULL;
}

19041
static int
19042
virDomainControllerDefFormat(virBufferPtr buf,
D
Daniel P. Berrange 已提交
19043
                             virDomainControllerDefPtr def,
E
Eric Blake 已提交
19044
                             unsigned int flags)
19045 19046
{
    const char *type = virDomainControllerTypeToString(def->type);
19047
    const char *model = NULL;
19048
    const char *modelName = NULL;
19049
    bool pcihole64 = false, pciModel = false, pciTarget = false;
19050 19051

    if (!type) {
19052 19053
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected controller type %d"), def->type);
19054 19055 19056
        return -1;
    }

19057
    if (def->model != -1) {
19058
        model = virDomainControllerModelTypeToString(def, def->model);
19059 19060

        if (!model) {
19061 19062
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected model type %d"), def->model);
19063 19064 19065 19066
            return -1;
        }
    }

19067
    virBufferAsprintf(buf,
19068
                      "<controller type='%s' index='%u'",
19069 19070
                      type, def->idx);

19071
    if (model)
19072 19073
        virBufferEscapeString(buf, " model='%s'", model);

19074 19075 19076
    switch (def->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL:
        if (def->opts.vioserial.ports != -1) {
19077
            virBufferAsprintf(buf, " ports='%d'",
19078 19079 19080
                              def->opts.vioserial.ports);
        }
        if (def->opts.vioserial.vectors != -1) {
19081
            virBufferAsprintf(buf, " vectors='%d'",
19082 19083 19084 19085
                              def->opts.vioserial.vectors);
        }
        break;

19086 19087 19088
    case VIR_DOMAIN_CONTROLLER_TYPE_PCI:
        if (def->opts.pciopts.pcihole64)
            pcihole64 = true;
19089 19090
        if (def->opts.pciopts.modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_NONE)
            pciModel = true;
19091 19092 19093
        if (def->opts.pciopts.chassisNr != -1 ||
            def->opts.pciopts.chassis != -1 ||
            def->opts.pciopts.port != -1)
19094
            pciTarget = true;
19095 19096
        break;

19097 19098 19099 19100
    default:
        break;
    }

19101
    if (pciModel || pciTarget ||
19102
        def->queues || def->cmd_per_lun || def->max_sectors || def->ioeventfd ||
19103
        virDomainDeviceInfoNeedsFormat(&def->info, flags) || pcihole64) {
19104
        virBufferAddLit(buf, ">\n");
19105
        virBufferAdjustIndent(buf, 2);
19106

19107 19108 19109 19110 19111 19112 19113 19114 19115 19116 19117
        if (pciModel) {
            modelName = virDomainControllerPCIModelNameTypeToString(def->opts.pciopts.modelName);
            if (!modelName) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected model name value %d"),
                               def->opts.pciopts.modelName);
                return -1;
            }
            virBufferAsprintf(buf, "<model name='%s'/>\n", modelName);
        }

19118 19119 19120 19121 19122
        if (pciTarget) {
            virBufferAddLit(buf, "<target");
            if (def->opts.pciopts.chassisNr != -1)
                virBufferAsprintf(buf, " chassisNr='%d'",
                                  def->opts.pciopts.chassisNr);
19123 19124 19125 19126 19127 19128
            if (def->opts.pciopts.chassis != -1)
                virBufferAsprintf(buf, " chassis='%d'",
                                  def->opts.pciopts.chassis);
            if (def->opts.pciopts.port != -1)
                virBufferAsprintf(buf, " port='0x%x'",
                                  def->opts.pciopts.port);
19129 19130 19131
            virBufferAddLit(buf, "/>\n");
        }

19132 19133
        if (def->queues || def->cmd_per_lun ||
            def->max_sectors || def->ioeventfd) {
19134 19135 19136
            virBufferAddLit(buf, "<driver");
            if (def->queues)
                virBufferAsprintf(buf, " queues='%u'", def->queues);
19137

19138 19139 19140 19141 19142
            if (def->cmd_per_lun)
                virBufferAsprintf(buf, " cmd_per_lun='%u'", def->cmd_per_lun);

            if (def->max_sectors)
                virBufferAsprintf(buf, " max_sectors='%u'", def->max_sectors);
19143 19144 19145 19146 19147

            if (def->ioeventfd) {
                virBufferAsprintf(buf, " ioeventfd='%s'",
                                  virTristateSwitchTypeToString(def->ioeventfd));
            }
19148 19149
            virBufferAddLit(buf, "/>\n");
        }
19150

19151
        if (virDomainDeviceInfoNeedsFormat(&def->info, flags) &&
19152
            virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
19153
            return -1;
19154

19155
        if (pcihole64) {
19156
            virBufferAsprintf(buf, "<pcihole64 unit='KiB'>%lu</"
19157 19158 19159
                              "pcihole64>\n", def->opts.pciopts.pcihole64size);
        }

19160 19161
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</controller>\n");
19162 19163 19164 19165 19166 19167 19168
    } else {
        virBufferAddLit(buf, "/>\n");
    }

    return 0;
}

19169 19170 19171 19172 19173

int
virDomainFSIndexByName(virDomainDefPtr def, const char *name)
{
    virDomainFSDefPtr fs;
19174
    size_t i;
19175 19176 19177 19178 19179 19180 19181 19182 19183 19184

    for (i = 0; i < def->nfss; i++) {
        fs = def->fss[i];
        if (STREQ(fs->dst, name))
            return i;
    }
    return -1;
}


19185
static int
19186
virDomainFSDefFormat(virBufferPtr buf,
19187
                     virDomainFSDefPtr def,
E
Eric Blake 已提交
19188
                     unsigned int flags)
19189 19190
{
    const char *type = virDomainFSTypeToString(def->type);
19191
    const char *accessmode = virDomainFSAccessModeTypeToString(def->accessmode);
19192
    const char *fsdriver = virDomainFSDriverTypeToString(def->fsdriver);
19193
    const char *wrpolicy = virDomainFSWrpolicyTypeToString(def->wrpolicy);
19194 19195

    if (!type) {
19196 19197
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected filesystem type %d"), def->type);
19198 19199 19200
        return -1;
    }

19201
   if (!accessmode) {
19202 19203
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected accessmode %d"), def->accessmode);
19204 19205 19206 19207
        return -1;
    }


19208
    virBufferAsprintf(buf,
19209
                      "<filesystem type='%s' accessmode='%s'>\n",
19210
                      type, accessmode);
19211
    virBufferAdjustIndent(buf, 2);
19212
    if (def->fsdriver) {
19213
        virBufferAsprintf(buf, "<driver type='%s'", fsdriver);
19214

19215 19216 19217 19218
        if (def->format)
            virBufferAsprintf(buf, " format='%s'",
                              virStorageFileFormatTypeToString(def->format));

19219
        /* Don't generate anything if wrpolicy is set to default */
19220
        if (def->wrpolicy)
19221 19222 19223
            virBufferAsprintf(buf, " wrpolicy='%s'", wrpolicy);

        virBufferAddLit(buf, "/>\n");
19224 19225
    }

19226 19227
    switch (def->type) {
    case VIR_DOMAIN_FS_TYPE_MOUNT:
19228
    case VIR_DOMAIN_FS_TYPE_BIND:
19229
        virBufferEscapeString(buf, "<source dir='%s'/>\n",
19230 19231
                              def->src);
        break;
19232

19233
    case VIR_DOMAIN_FS_TYPE_BLOCK:
19234
        virBufferEscapeString(buf, "<source dev='%s'/>\n",
19235 19236
                              def->src);
        break;
19237

19238
    case VIR_DOMAIN_FS_TYPE_FILE:
19239
        virBufferEscapeString(buf, "<source file='%s'/>\n",
19240 19241
                              def->src);
        break;
19242

19243
    case VIR_DOMAIN_FS_TYPE_TEMPLATE:
19244
        virBufferEscapeString(buf, "<source name='%s'/>\n",
19245 19246 19247 19248
                              def->src);
        break;

    case VIR_DOMAIN_FS_TYPE_RAM:
19249
        virBufferAsprintf(buf, "<source usage='%lld' units='KiB'/>\n",
19250 19251
                          def->usage / 1024);
        break;
19252 19253
    }

19254
    virBufferEscapeString(buf, "<target dir='%s'/>\n",
19255
                          def->dst);
19256 19257

    if (def->readonly)
19258
        virBufferAddLit(buf, "<readonly/>\n");
19259

19260 19261 19262
    if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
        return -1;

19263 19264

    if (def->space_hard_limit)
19265
        virBufferAsprintf(buf, "<space_hard_limit unit='bytes'>"
19266 19267
                          "%llu</space_hard_limit>\n", def->space_hard_limit);
    if (def->space_soft_limit) {
19268
        virBufferAsprintf(buf, "<space_soft_limit unit='bytes'>"
19269 19270
                          "%llu</space_soft_limit>\n", def->space_soft_limit);
    }
19271 19272
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</filesystem>\n");
19273 19274 19275
    return 0;
}

19276
static int
19277 19278 19279 19280 19281 19282 19283 19284 19285
virDomainNetIpsFormat(virBufferPtr buf, virDomainNetIpDefPtr *ips, size_t nips)
{
    size_t i;

    /* Output IP addresses */
    for (i = 0; i < nips; i++) {
        virSocketAddrPtr address = &ips[i]->address;
        char *ipStr = virSocketAddrFormat(address);
        const char *familyStr = NULL;
19286 19287 19288

        if (!ipStr)
            return -1;
19289 19290 19291 19292 19293 19294
        if (VIR_SOCKET_ADDR_IS_FAMILY(address, AF_INET6))
            familyStr = "ipv6";
        else if (VIR_SOCKET_ADDR_IS_FAMILY(address, AF_INET))
            familyStr = "ipv4";
        virBufferAsprintf(buf, "<ip address='%s'",
                          ipStr);
19295
        VIR_FREE(ipStr);
19296 19297 19298 19299 19300 19301
        if (familyStr)
            virBufferAsprintf(buf, " family='%s'", familyStr);
        if (ips[i]->prefix != 0)
            virBufferAsprintf(buf, " prefix='%u'", ips[i]->prefix);
        virBufferAddLit(buf, "/>\n");
    }
19302
    return 0;
19303 19304
}

19305
static int
19306
virDomainNetRoutesFormat(virBufferPtr buf,
19307
                         virNetworkRouteDefPtr *routes,
19308 19309 19310 19311
                         size_t nroutes)
{
    size_t i;

19312 19313 19314 19315
    for (i = 0; i < nroutes; i++)
        if (virNetworkRouteDefFormat(buf, routes[i]) < 0)
            return -1;
    return 0;
19316 19317
}

19318
static int
19319 19320 19321 19322
virDomainHostdevDefFormatSubsys(virBufferPtr buf,
                                virDomainHostdevDefPtr def,
                                unsigned int flags,
                                bool includeTypeInAddr)
19323
{
19324
    virDomainHostdevSubsysUSBPtr usbsrc = &def->source.subsys.u.usb;
19325
    virDomainHostdevSubsysPCIPtr pcisrc = &def->source.subsys.u.pci;
19326
    virDomainHostdevSubsysSCSIPtr scsisrc = &def->source.subsys.u.scsi;
19327
    virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
J
John Ferlan 已提交
19328
    virDomainHostdevSubsysSCSIiSCSIPtr iscsisrc = &scsisrc->u.iscsi;
19329

19330
    if (def->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
19331 19332 19333
        pcisrc->backend != VIR_DOMAIN_HOSTDEV_PCI_BACKEND_DEFAULT) {
        const char *backend =
            virDomainHostdevSubsysPCIBackendTypeToString(pcisrc->backend);
19334 19335 19336 19337

        if (!backend) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected pci hostdev driver name type %d"),
19338
                           pcisrc->backend);
19339 19340 19341 19342 19343
            return -1;
        }
        virBufferAsprintf(buf, "<driver name='%s'/>\n", backend);
    }

19344
    virBufferAddLit(buf, "<source");
J
John Ferlan 已提交
19345 19346 19347 19348 19349 19350
    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);
        }
19351
        if (usbsrc->autoAddress && (flags & VIR_DOMAIN_DEF_FORMAT_MIGRATABLE))
J
John Ferlan 已提交
19352 19353
            virBufferAddLit(buf, " autoAddress='yes'");

19354
        if (def->missing && !(flags & VIR_DOMAIN_DEF_FORMAT_INACTIVE))
J
John Ferlan 已提交
19355
            virBufferAddLit(buf, " missing='yes'");
19356
    }
19357

J
John Ferlan 已提交
19358 19359 19360 19361 19362 19363 19364 19365
    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);
    }
19366

19367 19368
    virBufferAddLit(buf, ">\n");

19369
    virBufferAdjustIndent(buf, 2);
E
Eric Blake 已提交
19370
    switch (def->source.subsys.type) {
19371
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
19372 19373 19374 19375 19376
        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) {
19377
            virBufferAsprintf(buf, "<address %sbus='%d' device='%d'/>\n",
19378
                              includeTypeInAddr ? "type='usb' " : "",
19379
                              usbsrc->bus, usbsrc->device);
19380 19381 19382
        }
        break;
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
19383
        if (virDevicePCIAddressFormat(buf, pcisrc->addr,
19384 19385 19386
                                      includeTypeInAddr) != 0)
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("PCI address Formatting failed"));
19387

19388
        if ((flags & VIR_DOMAIN_DEF_FORMAT_PCI_ORIG_STATES) &&
19389 19390 19391
            (def->origstates.states.pci.unbind_from_stub ||
             def->origstates.states.pci.remove_slot ||
             def->origstates.states.pci.reprobe)) {
19392
            virBufferAddLit(buf, "<origstates>\n");
19393
            virBufferAdjustIndent(buf, 2);
19394
            if (def->origstates.states.pci.unbind_from_stub)
19395
                virBufferAddLit(buf, "<unbind/>\n");
19396
            if (def->origstates.states.pci.remove_slot)
19397
                virBufferAddLit(buf, "<removeslot/>\n");
19398
            if (def->origstates.states.pci.reprobe)
19399 19400
                virBufferAddLit(buf, "<reprobe/>\n");
            virBufferAdjustIndent(buf, -2);
19401
            virBufferAddLit(buf, "</origstates>\n");
19402 19403
        }
        break;
H
Han Cheng 已提交
19404
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
J
John Ferlan 已提交
19405 19406 19407 19408 19409 19410 19411 19412 19413
        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,
19414
                              "<address %sbus='%u' target='%u' unit='%llu'/>\n",
J
John Ferlan 已提交
19415 19416 19417 19418
                              includeTypeInAddr ? "type='scsi' " : "",
                              scsihostsrc->bus, scsihostsrc->target,
                              scsihostsrc->unit);
        }
H
Han Cheng 已提交
19419
        break;
19420
    default:
19421 19422 19423
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected hostdev type %d"),
                       def->source.subsys.type);
19424 19425 19426
        return -1;
    }

J
John Ferlan 已提交
19427 19428 19429 19430 19431 19432 19433
    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;
    }

19434
    virBufferAdjustIndent(buf, -2);
19435
    virBufferAddLit(buf, "</source>\n");
J
John Ferlan 已提交
19436

19437 19438 19439
    return 0;
}

19440 19441 19442 19443 19444 19445 19446
static int
virDomainHostdevDefFormatCaps(virBufferPtr buf,
                              virDomainHostdevDefPtr def)
{
    virBufferAddLit(buf, "<source>\n");

    virBufferAdjustIndent(buf, 2);
E
Eric Blake 已提交
19447
    switch (def->source.caps.type) {
19448 19449 19450 19451 19452 19453 19454 19455
    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;
19456 19457 19458 19459
    case VIR_DOMAIN_HOSTDEV_CAPS_TYPE_NET:
        virBufferEscapeString(buf, "<interface>%s</interface>\n",
                              def->source.caps.u.net.iface);
        break;
19460 19461 19462 19463 19464 19465 19466 19467 19468
    default:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected hostdev type %d"),
                       def->source.caps.type);
        return -1;
    }

    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</source>\n");
19469 19470

    if (def->source.caps.type == VIR_DOMAIN_HOSTDEV_CAPS_TYPE_NET) {
19471 19472 19473
        if (virDomainNetIpsFormat(buf, def->source.caps.u.net.ips,
                                 def->source.caps.u.net.nips) < 0)
            return -1;
19474 19475 19476
        if (virDomainNetRoutesFormat(buf, def->source.caps.u.net.routes,
                                     def->source.caps.u.net.nroutes) < 0)
            return -1;
19477 19478
    }

19479 19480 19481
    return 0;
}

19482 19483 19484 19485 19486
/* 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.
 */
19487
static int
19488 19489 19490 19491
virDomainActualNetDefContentsFormat(virBufferPtr buf,
                                    virDomainNetDefPtr def,
                                    bool inSubelement,
                                    unsigned int flags)
19492
{
19493
    int actualType = virDomainNetGetActualType(def);
19494

19495
    if (actualType == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
19496
        if (virDomainHostdevDefFormatSubsys(buf, virDomainNetGetActualHostdev(def),
19497
                                            flags, true) < 0) {
19498 19499
            return -1;
        }
19500 19501 19502 19503 19504
    } 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
19505 19506 19507 19508 19509 19510 19511
             * network name and portgroup don't need to be included in
             * the <source> here 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 network/portgroup, because the
             * caller won't have done it).
19512
             */
19513 19514 19515 19516
            virBufferEscapeString(buf, " network='%s'",
                                  def->data.network.name);
            virBufferEscapeString(buf, " portgroup='%s'",
                                  def->data.network.portgroup);
19517
        }
19518 19519
        if (actualType == VIR_DOMAIN_NET_TYPE_BRIDGE ||
            actualType == VIR_DOMAIN_NET_TYPE_NETWORK) {
19520 19521
            int macTableManager = virDomainNetGetActualBridgeMACTableManager(def);

19522 19523 19524 19525 19526 19527
            /* 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));
19528 19529 19530 19531
            if (macTableManager) {
                virBufferAsprintf(buf, " macTableManager='%s'",
                                  virNetworkBridgeMACTableManagerTypeToString(macTableManager));
            }
19532 19533 19534 19535 19536 19537 19538 19539 19540 19541 19542 19543 19544 19545 19546 19547 19548
        } 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");
    }
19549 19550
    if (flags & VIR_DOMAIN_DEF_FORMAT_STATUS &&
        def->data.network.actual && def->data.network.actual->class_id) {
19551 19552
        virBufferAsprintf(buf, "<class id='%u'/>\n",
                          def->data.network.actual->class_id);
19553
    }
19554

19555
    if (virNetDevVlanFormat(virDomainNetGetActualVlan(def), buf) < 0)
19556
        return -1;
19557
    if (virNetDevVPortProfileFormat(virDomainNetGetActualVirtPortProfile(def), buf) < 0)
19558
        return -1;
19559
    if (virNetDevBandwidthFormat(virDomainNetGetActualBandwidth(def), buf) < 0)
19560
        return -1;
19561 19562 19563 19564 19565 19566 19567 19568 19569 19570 19571 19572
    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)
{
19573 19574
    unsigned int type;
    const char *typeStr;
19575 19576 19577

    if (!def)
        return 0;
19578 19579
    type = virDomainNetGetActualType(def);
    typeStr = virDomainNetTypeToString(type);
19580

19581 19582 19583 19584 19585 19586 19587 19588 19589 19590 19591 19592
    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'");
    }
19593 19594 19595
    if (def->trustGuestRxFilters)
        virBufferAsprintf(buf, " trustGuestRxFilters='%s'",
                          virTristateBoolTypeToString(def->trustGuestRxFilters));
19596 19597 19598
    virBufferAddLit(buf, ">\n");

    virBufferAdjustIndent(buf, 2);
19599
    if (virDomainActualNetDefContentsFormat(buf, def, true, flags) < 0)
19600
       return -1;
19601 19602
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</actual>\n");
19603
    return 0;
19604 19605
}

19606

19607 19608 19609 19610 19611 19612 19613 19614 19615 19616 19617 19618 19619 19620 19621 19622 19623 19624 19625 19626 19627 19628 19629 19630 19631 19632 19633 19634 19635 19636 19637 19638 19639 19640 19641 19642 19643 19644 19645 19646 19647 19648 19649 19650 19651 19652 19653 19654 19655 19656 19657 19658 19659 19660 19661 19662 19663 19664 19665 19666 19667 19668 19669 19670
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));
    }
19671 19672 19673 19674
    if (def->driver.virtio.host.mrg_rxbuf) {
        virBufferAsprintf(&buf, "mrg_rxbuf='%s' ",
                          virTristateSwitchTypeToString(def->driver.virtio.host.mrg_rxbuf));
    }
19675 19676 19677 19678 19679 19680 19681 19682 19683 19684
    virBufferTrim(&buf, " ", -1);

    if (virBufferCheckError(&buf) < 0)
        return -1;

    *outstr = virBufferContentAndReset(&buf);
    return 0;
}


19685 19686 19687 19688 19689 19690 19691 19692 19693 19694 19695 19696 19697 19698 19699 19700 19701 19702 19703 19704 19705 19706 19707 19708 19709 19710 19711 19712 19713 19714 19715 19716 19717 19718
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;
}


19719
int
19720
virDomainNetDefFormat(virBufferPtr buf,
19721
                      virDomainNetDefPtr def,
19722
                      char *prefix,
E
Eric Blake 已提交
19723
                      unsigned int flags)
19724
{
19725
    unsigned int actualType = virDomainNetGetActualType(def);
19726
    bool publicActual = false;
19727 19728
    const char *typeStr;
    virDomainHostdevDefPtr hostdef = NULL;
19729
    char macstr[VIR_MAC_STRING_BUFLEN];
19730

19731 19732 19733 19734 19735 19736
    /* publicActual is true if we should report the current state in
     * def->data.network.actual *instead of* the config (*not* in
     * addition to)
     */
    if (def->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
        def->data.network.actual &&
19737 19738 19739
        !(flags & (VIR_DOMAIN_DEF_FORMAT_INACTIVE |
                   VIR_DOMAIN_DEF_FORMAT_ACTUAL_NET |
                   VIR_DOMAIN_DEF_FORMAT_MIGRATABLE)))
19740 19741
        publicActual = true;

19742 19743 19744 19745 19746 19747 19748 19749 19750 19751 19752 19753 19754 19755 19756 19757
    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;
19758 19759
    }

19760
    virBufferAsprintf(buf, "<interface type='%s'", typeStr);
19761
    if (hostdef && hostdef->managed)
19762
        virBufferAddLit(buf, " managed='yes'");
19763 19764 19765
    if (def->trustGuestRxFilters)
        virBufferAsprintf(buf, " trustGuestRxFilters='%s'",
                          virTristateBoolTypeToString(def->trustGuestRxFilters));
19766
    virBufferAddLit(buf, ">\n");
19767

19768
    virBufferAdjustIndent(buf, 2);
19769 19770
    virBufferAsprintf(buf, "<mac address='%s'/>\n",
                      virMacAddrFormat(&def->mac, macstr));
19771

19772 19773 19774 19775 19776 19777 19778
    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)
19779
         */
19780
        if (virDomainActualNetDefContentsFormat(buf, def, false, flags) < 0)
19781
            return -1;
19782 19783 19784 19785 19786 19787 19788 19789 19790 19791 19792 19793 19794 19795 19796
    } 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");
19797

19798 19799 19800 19801
            /* ONLY for internal status storage - format the ActualNetDef
             * as a subelement of <interface> so that no persistent config
             * data is overwritten.
             */
19802
            if ((flags & VIR_DOMAIN_DEF_FORMAT_ACTUAL_NET) &&
19803 19804 19805
                (virDomainActualNetDefFormat(buf, def, flags) < 0))
                return -1;
            break;
19806

19807 19808 19809 19810
        case VIR_DOMAIN_NET_TYPE_ETHERNET:
            virBufferEscapeString(buf, "<source dev='%s'/>\n",
                                  def->data.ethernet.dev);
            break;
19811

M
Michele Paolino 已提交
19812 19813 19814 19815 19816
        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);
19817 19818 19819
                virBufferAsprintf(buf, " mode='%s'",
                                  def->data.vhostuser->data.nix.listen ?
                                  "server"  : "client");
M
Michele Paolino 已提交
19820 19821 19822 19823
                virBufferAddLit(buf, "/>\n");
            }
            break;

19824 19825 19826 19827
        case VIR_DOMAIN_NET_TYPE_BRIDGE:
            virBufferEscapeString(buf, "<source bridge='%s'/>\n",
                                  def->data.bridge.brname);
            break;
D
Daniel Veillard 已提交
19828

19829 19830 19831
        case VIR_DOMAIN_NET_TYPE_SERVER:
        case VIR_DOMAIN_NET_TYPE_CLIENT:
        case VIR_DOMAIN_NET_TYPE_MCAST:
19832
        case VIR_DOMAIN_NET_TYPE_UDP:
19833
            if (def->data.socket.address) {
19834 19835 19836
                virBufferAsprintf(buf, "<source address='%s' port='%d'",
                                  def->data.socket.address,
                                  def->data.socket.port);
19837
            } else {
19838
                virBufferAsprintf(buf, "<source port='%d'",
19839 19840
                                  def->data.socket.port);
            }
19841 19842 19843 19844 19845 19846 19847 19848 19849 19850 19851 19852 19853 19854

            if (def->type != VIR_DOMAIN_NET_TYPE_UDP) {
                virBufferAddLit(buf, "/>\n");
                break;
            }

            virBufferAddLit(buf, ">\n");
            virBufferAdjustIndent(buf, 2);

            virBufferAsprintf(buf, "<local address='%s' port='%d'/>\n",
                              def->data.socket.localaddr,
                              def->data.socket.localport);
            virBufferAdjustIndent(buf, -2);
            virBufferAddLit(buf, "</source>\n");
19855
            break;
D
Daniel Veillard 已提交
19856

19857 19858 19859 19860
        case VIR_DOMAIN_NET_TYPE_INTERNAL:
            virBufferEscapeString(buf, "<source name='%s'/>\n",
                                  def->data.internal.name);
            break;
S
Stefan Berger 已提交
19861

19862 19863 19864 19865 19866 19867 19868 19869 19870 19871 19872 19873 19874 19875 19876 19877 19878 19879
        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;
19880 19881
        }

19882 19883 19884 19885 19886 19887
        if (virNetDevVlanFormat(&def->vlan, buf) < 0)
            return -1;
        if (virNetDevVPortProfileFormat(def->virtPortProfile, buf) < 0)
            return -1;
        if (virNetDevBandwidthFormat(def->bandwidth, buf) < 0)
            return -1;
19888 19889
    }

19890 19891
    if (virDomainNetIpsFormat(buf, def->ips, def->nips) < 0)
        return -1;
19892 19893
    if (virDomainNetRoutesFormat(buf, def->routes, def->nroutes) < 0)
        return -1;
19894

19895
    virBufferEscapeString(buf, "<script path='%s'/>\n",
19896
                          def->script);
19897
    virBufferEscapeString(buf, "<backenddomain name='%s'/>\n", def->domain_name);
19898
    if (def->ifname &&
19899
        !((flags & VIR_DOMAIN_DEF_FORMAT_INACTIVE) &&
19900 19901
          (STRPREFIX(def->ifname, VIR_NET_GENERATED_PREFIX) ||
           (prefix && STRPREFIX(def->ifname, prefix))))) {
19902
        /* Skip auto-generated target names for inactive config. */
19903
        virBufferEscapeString(buf, "<target dev='%s'/>\n", def->ifname);
19904
    }
19905 19906 19907 19908 19909 19910 19911 19912 19913 19914 19915
    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");
    }
19916
    if (def->model) {
19917
        virBufferEscapeString(buf, "<model type='%s'/>\n",
19918
                              def->model);
19919
        if (STREQ(def->model, "virtio")) {
19920 19921
            char *str = NULL, *gueststr = NULL, *hoststr = NULL;
            int rc = 0;
19922

19923 19924 19925 19926
            if (virDomainVirtioNetDriverFormat(&str, def) < 0 ||
                virDomainVirtioNetGuestOptsFormat(&gueststr, def) < 0 ||
                virDomainVirtioNetHostOptsFormat(&hoststr, def) < 0)
                rc = -1;
19927

19928 19929 19930 19931 19932 19933 19934 19935 19936 19937 19938 19939 19940 19941 19942 19943
            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");
            }
19944
            VIR_FREE(str);
19945 19946 19947 19948 19949
            VIR_FREE(hoststr);
            VIR_FREE(gueststr);

            if (rc < 0)
                return -1;
19950 19951
        }
    }
19952 19953 19954 19955 19956 19957
    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");
    }
19958
    if (def->filter) {
19959 19960 19961
        if (virNWFilterFormatParamAttributes(buf, def->filterparams,
                                             def->filter) < 0)
            return -1;
19962
    }
19963

19964
    if (def->tune.sndbuf_specified) {
19965
        virBufferAddLit(buf,   "<tune>\n");
19966 19967 19968
        virBufferAdjustIndent(buf, 2);
        virBufferAsprintf(buf, "<sndbuf>%lu</sndbuf>\n", def->tune.sndbuf);
        virBufferAdjustIndent(buf, -2);
19969
        virBufferAddLit(buf,   "</tune>\n");
19970 19971
    }

19972 19973
    if (def->linkstate) {
        virBufferAsprintf(buf, "<link state='%s'/>\n",
19974
                          virDomainNetInterfaceLinkStateTypeToString(def->linkstate));
19975
    }
19976
    if (virDomainDeviceInfoFormat(buf, &def->info,
19977 19978
                                  flags | VIR_DOMAIN_DEF_FORMAT_ALLOW_BOOT
                                  | VIR_DOMAIN_DEF_FORMAT_ALLOW_ROM) < 0)
19979 19980
        return -1;

19981 19982
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</interface>\n");
19983 19984 19985 19986
    return 0;
}


19987 19988
/* Assumes that "<device" has already been generated, and starts
 * output at " type='type'>". */
19989
static int
19990
virDomainChrSourceDefFormat(virBufferPtr buf,
J
Ján Tomko 已提交
19991
                            virDomainChrDefPtr chr_def,
19992 19993
                            virDomainChrSourceDefPtr def,
                            bool tty_compat,
E
Eric Blake 已提交
19994
                            unsigned int flags)
19995 19996
{
    const char *type = virDomainChrTypeToString(def->type);
J
Ján Tomko 已提交
19997 19998 19999 20000 20001 20002 20003
    size_t nseclabels = 0;
    virSecurityDeviceLabelDefPtr *seclabels = NULL;

    if (chr_def) {
        nseclabels = chr_def->nseclabels;
        seclabels = chr_def->seclabels;
    }
20004

20005
    if (!type) {
20006 20007
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected char type %d"), def->type);
20008
        return -1;
20009 20010
    }

20011
    /* Compat with legacy <console tty='/dev/pts/5'/> syntax */
20012
    virBufferAsprintf(buf, " type='%s'", type);
20013
    if (tty_compat) {
C
Cole Robinson 已提交
20014
        virBufferEscapeString(buf, " tty='%s'",
20015 20016
                              def->data.file.path);
    }
C
Cole Robinson 已提交
20017
    virBufferAddLit(buf, ">\n");
20018

20019
    switch ((virDomainChrType)def->type) {
20020 20021 20022
    case VIR_DOMAIN_CHR_TYPE_NULL:
    case VIR_DOMAIN_CHR_TYPE_VC:
    case VIR_DOMAIN_CHR_TYPE_STDIO:
20023
    case VIR_DOMAIN_CHR_TYPE_SPICEVMC:
20024
    case VIR_DOMAIN_CHR_TYPE_LAST:
20025 20026 20027 20028 20029 20030 20031 20032
        /* 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 ||
20033
            (def->data.file.path &&
20034
             !(flags & VIR_DOMAIN_DEF_FORMAT_INACTIVE))) {
J
Ján Tomko 已提交
20035
            virBufferEscapeString(buf, "<source path='%s'",
20036
                                  def->data.file.path);
20037
            if (def->type == VIR_DOMAIN_CHR_TYPE_FILE &&
20038
                def->data.file.append != VIR_TRISTATE_SWITCH_ABSENT)
20039 20040
                virBufferAsprintf(buf, " append='%s'",
                    virTristateSwitchTypeToString(def->data.file.append));
J
Ján Tomko 已提交
20041
            virDomainSourceDefFormatSeclabel(buf, nseclabels, seclabels, flags);
20042 20043 20044
        }
        break;

20045
    case VIR_DOMAIN_CHR_TYPE_NMDM:
20046 20047 20048
        virBufferEscapeString(buf, "<source master='%s' ",
                              def->data.nmdm.master);
        virBufferEscapeString(buf, "slave='%s'/>\n", def->data.nmdm.slave);
20049 20050
        break;

20051 20052 20053
    case VIR_DOMAIN_CHR_TYPE_UDP:
        if (def->data.udp.bindService &&
            def->data.udp.bindHost) {
20054 20055 20056 20057
            virBufferEscapeString(buf, "<source mode='bind' host='%s' ",
                                  def->data.udp.bindHost);
            virBufferEscapeString(buf, "service='%s'/>\n",
                                  def->data.udp.bindService);
20058
        } else if (def->data.udp.bindHost) {
20059 20060
            virBufferEscapeString(buf, "<source mode='bind' host='%s'/>\n",
                                  def->data.udp.bindHost);
20061
        } else if (def->data.udp.bindService) {
20062 20063
            virBufferEscapeString(buf, "<source mode='bind' service='%s'/>\n",
                                  def->data.udp.bindService);
20064 20065 20066 20067
        }

        if (def->data.udp.connectService &&
            def->data.udp.connectHost) {
20068 20069 20070 20071
            virBufferEscapeString(buf, "<source mode='connect' host='%s' ",
                                  def->data.udp.connectHost);
            virBufferEscapeString(buf, "service='%s'/>\n",
                                  def->data.udp.connectService);
20072
        } else if (def->data.udp.connectHost) {
20073 20074
            virBufferEscapeString(buf, "<source mode='connect' host='%s'/>\n",
                                  def->data.udp.connectHost);
20075
        } else if (def->data.udp.connectService) {
20076 20077
            virBufferEscapeString(buf, "<source mode='connect' service='%s'/>\n",
                                  def->data.udp.connectService);
20078 20079 20080 20081
        }
        break;

    case VIR_DOMAIN_CHR_TYPE_TCP:
20082 20083 20084 20085
        virBufferAsprintf(buf, "<source mode='%s' ",
                          def->data.tcp.listen ? "bind" : "connect");
        virBufferEscapeString(buf, "host='%s' ", def->data.tcp.host);
        virBufferEscapeString(buf, "service='%s'/>\n", def->data.tcp.service);
20086
        virBufferAsprintf(buf, "<protocol type='%s'/>\n",
20087 20088
                          virDomainChrTcpProtocolTypeToString(
                              def->data.tcp.protocol));
20089 20090 20091
        break;

    case VIR_DOMAIN_CHR_TYPE_UNIX:
20092
        virBufferAsprintf(buf, "<source mode='%s'",
20093
                          def->data.nix.listen ? "bind" : "connect");
20094
        virBufferEscapeString(buf, " path='%s'", def->data.nix.path);
J
Ján Tomko 已提交
20095
        virDomainSourceDefFormatSeclabel(buf, nseclabels, seclabels, flags);
20096
        break;
20097 20098

    case VIR_DOMAIN_CHR_TYPE_SPICEPORT:
20099 20100
        virBufferEscapeString(buf, "<source channel='%s'/>\n",
                              def->data.spiceport.channel);
20101 20102
        break;

20103 20104
    }

20105 20106 20107 20108 20109 20110
    return 0;
}

static int
virDomainChrDefFormat(virBufferPtr buf,
                      virDomainChrDefPtr def,
E
Eric Blake 已提交
20111
                      unsigned int flags)
20112 20113 20114 20115 20116 20117 20118 20119 20120
{
    const char *elementName = virDomainChrDeviceTypeToString(def->deviceType);
    const char *targetType = virDomainChrTargetTypeToString(def->deviceType,
                                                            def->targetType);
    bool tty_compat;

    int ret = 0;

    if (!elementName) {
20121 20122 20123
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected char device type %d"),
                       def->deviceType);
20124 20125 20126
        return -1;
    }

20127 20128
    virBufferAsprintf(buf, "<%s", elementName);
    virBufferAdjustIndent(buf, 2);
20129 20130 20131
    tty_compat = (def->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE &&
                  def->target.port == 0 &&
                  def->source.type == VIR_DOMAIN_CHR_TYPE_PTY &&
20132
                  !(flags & VIR_DOMAIN_DEF_FORMAT_INACTIVE) &&
20133
                  def->source.data.file.path);
J
Ján Tomko 已提交
20134
    if (virDomainChrSourceDefFormat(buf, def, &def->source, tty_compat, flags) < 0)
20135 20136
        return -1;

20137
    /* Format <target> block */
20138
    switch (def->deviceType) {
20139 20140
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL: {
        if (!targetType) {
20141 20142
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not format channel target type"));
20143 20144
            return -1;
        }
20145
        virBufferAsprintf(buf, "<target type='%s'", targetType);
20146 20147 20148

        switch (def->targetType) {
        case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_GUESTFWD: {
20149
            int port = virSocketAddrGetPort(def->target.addr);
20150
            if (port < 0) {
20151 20152
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to format guestfwd port"));
20153 20154
                return -1;
            }
20155

20156
            char *addr = virSocketAddrFormat(def->target.addr);
20157
            if (addr == NULL)
20158
                return -1;
20159

20160
            virBufferAsprintf(buf, " address='%s' port='%d'",
20161 20162 20163
                              addr, port);
            VIR_FREE(addr);
            break;
20164 20165
        }

20166
        case VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO:
20167
            if (def->target.name)
20168
                virBufferEscapeString(buf, " name='%s'", def->target.name);
20169 20170

            if (def->state != VIR_DOMAIN_CHR_DEVICE_STATE_DEFAULT &&
20171
                !(flags & VIR_DOMAIN_DEF_PARSE_INACTIVE)) {
20172 20173 20174
                virBufferAsprintf(buf, " state='%s'",
                                  virDomainChrDeviceStateTypeToString(def->state));
            }
20175 20176 20177
            break;
        }

20178 20179
        virBufferAddLit(buf, "/>\n");
        break;
20180
    }
20181

20182
    case VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE:
20183
        virBufferAsprintf(buf,
20184
                          "<target type='%s' port='%d'/>\n",
20185 20186 20187 20188 20189
                          virDomainChrTargetTypeToString(def->deviceType,
                                                         def->targetType),
                          def->target.port);
        break;

G
Guannan Ren 已提交
20190 20191 20192
    case VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL:
        if (def->targetTypeAttr) {
            virBufferAsprintf(buf,
20193
                              "<target type='%s' port='%d'/>\n",
G
Guannan Ren 已提交
20194 20195 20196 20197 20198
                              virDomainChrTargetTypeToString(def->deviceType,
                                                             def->targetType),
                              def->target.port);
            break;
        }
20199
    default:
20200
        virBufferAsprintf(buf, "<target port='%d'/>\n",
20201
                          def->target.port);
20202
        break;
20203
    }
20204

20205
    if (virDomainDeviceInfoNeedsFormat(&def->info, flags)) {
20206 20207 20208
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
            return -1;
    }
20209

20210 20211
    virBufferAdjustIndent(buf, -2);
    virBufferAsprintf(buf, "</%s>\n", elementName);
20212

20213
    return ret;
20214 20215
}

E
Eric Blake 已提交
20216 20217 20218
static int
virDomainSmartcardDefFormat(virBufferPtr buf,
                            virDomainSmartcardDefPtr def,
E
Eric Blake 已提交
20219
                            unsigned int flags)
E
Eric Blake 已提交
20220 20221 20222 20223 20224
{
    const char *mode = virDomainSmartcardTypeToString(def->type);
    size_t i;

    if (!mode) {
20225 20226
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected smartcard type %d"), def->type);
E
Eric Blake 已提交
20227 20228 20229
        return -1;
    }

20230 20231
    virBufferAsprintf(buf, "<smartcard mode='%s'", mode);
    virBufferAdjustIndent(buf, 2);
E
Eric Blake 已提交
20232 20233
    switch (def->type) {
    case VIR_DOMAIN_SMARTCARD_TYPE_HOST:
20234
        if (!virDomainDeviceInfoNeedsFormat(&def->info, flags)) {
20235
            virBufferAdjustIndent(buf, -2);
E
Eric Blake 已提交
20236 20237 20238
            virBufferAddLit(buf, "/>\n");
            return 0;
        }
20239
        virBufferAddLit(buf, ">\n");
E
Eric Blake 已提交
20240 20241 20242 20243 20244
        break;

    case VIR_DOMAIN_SMARTCARD_TYPE_HOST_CERTIFICATES:
        virBufferAddLit(buf, ">\n");
        for (i = 0; i < VIR_DOMAIN_SMARTCARD_NUM_CERTIFICATES; i++)
20245
            virBufferEscapeString(buf, "<certificate>%s</certificate>\n",
E
Eric Blake 已提交
20246
                                  def->data.cert.file[i]);
20247
        virBufferEscapeString(buf, "<database>%s</database>\n",
20248
                              def->data.cert.database);
E
Eric Blake 已提交
20249 20250 20251
        break;

    case VIR_DOMAIN_SMARTCARD_TYPE_PASSTHROUGH:
J
Ján Tomko 已提交
20252
        if (virDomainChrSourceDefFormat(buf, NULL, &def->data.passthru, false,
E
Eric Blake 已提交
20253 20254 20255 20256 20257
                                        flags) < 0)
            return -1;
        break;

    default:
20258 20259
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected smartcard type %d"), def->type);
E
Eric Blake 已提交
20260 20261 20262 20263
        return -1;
    }
    if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
        return -1;
20264 20265
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</smartcard>\n");
E
Eric Blake 已提交
20266 20267 20268
    return 0;
}

20269 20270 20271 20272 20273 20274 20275
static int
virDomainSoundCodecDefFormat(virBufferPtr buf,
                             virDomainSoundCodecDefPtr def)
{
    const char *type = virDomainSoundCodecTypeToString(def->type);

    if (!type) {
20276 20277
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected codec type %d"), def->type);
20278 20279 20280
        return -1;
    }

20281
    virBufferAsprintf(buf, "<codec type='%s'/>\n",  type);
20282 20283 20284 20285

    return 0;
}

20286 20287 20288 20289 20290
static int
virDomainTPMDefFormat(virBufferPtr buf,
                      virDomainTPMDefPtr def,
                      unsigned int flags)
{
20291
    virBufferAsprintf(buf, "<tpm model='%s'>\n",
20292
                      virDomainTPMModelTypeToString(def->model));
20293 20294
    virBufferAdjustIndent(buf, 2);
    virBufferAsprintf(buf, "<backend type='%s'>\n",
20295
                      virDomainTPMBackendTypeToString(def->type));
20296
    virBufferAdjustIndent(buf, 2);
20297 20298 20299

    switch (def->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
20300
        virBufferEscapeString(buf, "<device path='%s'/>\n",
20301 20302 20303 20304 20305 20306
                              def->data.passthrough.source.data.file.path);
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

20307 20308
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</backend>\n");
20309

20310
    if (virDomainDeviceInfoNeedsFormat(&def->info, flags)) {
20311 20312 20313 20314
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
            return -1;
    }

20315 20316
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</tpm>\n");
20317 20318 20319 20320 20321

    return 0;
}


20322
static int
20323
virDomainSoundDefFormat(virBufferPtr buf,
D
Daniel P. Berrange 已提交
20324
                        virDomainSoundDefPtr def,
E
Eric Blake 已提交
20325
                        unsigned int flags)
20326 20327
{
    const char *model = virDomainSoundModelTypeToString(def->model);
20328
    bool children = false;
20329
    size_t i;
20330 20331

    if (!model) {
20332 20333
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected sound model %d"), def->model);
20334 20335 20336
        return -1;
    }

20337
    virBufferAsprintf(buf, "<sound model='%s'",  model);
20338

20339 20340 20341
    for (i = 0; i < def->ncodecs; i++) {
        if (!children) {
            virBufferAddLit(buf, ">\n");
20342
            virBufferAdjustIndent(buf, 2);
20343 20344 20345 20346 20347
            children = true;
        }
        virDomainSoundCodecDefFormat(buf, def->codecs[i]);
    }

20348
    if (virDomainDeviceInfoNeedsFormat(&def->info, flags)) {
20349 20350
        if (!children) {
            virBufferAddLit(buf, ">\n");
20351
            virBufferAdjustIndent(buf, 2);
20352 20353
            children = true;
        }
D
Daniel P. Berrange 已提交
20354
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
20355
            return -1;
20356 20357 20358
    }

    if (children) {
20359 20360
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</sound>\n");
20361 20362 20363 20364
    } else {
        virBufferAddLit(buf, "/>\n");
    }

20365 20366 20367
    return 0;
}

20368

20369 20370 20371
static int
virDomainMemballoonDefFormat(virBufferPtr buf,
                             virDomainMemballoonDefPtr def,
E
Eric Blake 已提交
20372
                             unsigned int flags)
20373 20374
{
    const char *model = virDomainMemballoonModelTypeToString(def->model);
20375 20376
    virBuffer childrenBuf = VIR_BUFFER_INITIALIZER;
    int indent = virBufferGetIndent(buf, false);
20377 20378

    if (!model) {
20379 20380
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected memballoon model %d"), def->model);
20381 20382 20383
        return -1;
    }

20384
    virBufferAsprintf(buf, "<memballoon model='%s'", model);
20385 20386 20387 20388 20389

    if (def->autodeflate != VIR_TRISTATE_SWITCH_ABSENT)
        virBufferAsprintf(buf, " autodeflate='%s'",
                          virTristateSwitchTypeToString(def->autodeflate));

20390
    virBufferAdjustIndent(&childrenBuf, indent + 2);
20391

20392
    if (def->period)
20393
        virBufferAsprintf(&childrenBuf, "<stats period='%i'/>\n", def->period);
20394

20395 20396 20397 20398
    if (virDomainDeviceInfoNeedsFormat(&def->info, flags) &&
        virDomainDeviceInfoFormat(&childrenBuf, &def->info, flags) < 0) {
        virBufferFreeAndReset(&childrenBuf);
        return -1;
20399 20400
    }

20401
    if (!virBufferUse(&childrenBuf)) {
20402
        virBufferAddLit(buf, "/>\n");
20403 20404 20405
    } else {
        virBufferAddLit(buf, ">\n");
        virBufferAddBuffer(buf, &childrenBuf);
20406
        virBufferAddLit(buf, "</memballoon>\n");
20407
    }
20408

20409 20410 20411
    return 0;
}

L
Li Zhang 已提交
20412 20413 20414 20415 20416
static int
virDomainNVRAMDefFormat(virBufferPtr buf,
                        virDomainNVRAMDefPtr def,
                        unsigned int flags)
{
20417 20418
    virBufferAddLit(buf, "<nvram>\n");
    virBufferAdjustIndent(buf, 2);
20419
    if (virDomainDeviceInfoNeedsFormat(&def->info, flags) &&
L
Li Zhang 已提交
20420 20421 20422
        virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
        return -1;

20423 20424
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</nvram>\n");
L
Li Zhang 已提交
20425 20426 20427 20428

    return 0;
}

20429

R
Richard Jones 已提交
20430
static int
20431
virDomainWatchdogDefFormat(virBufferPtr buf,
D
Daniel P. Berrange 已提交
20432
                           virDomainWatchdogDefPtr def,
E
Eric Blake 已提交
20433
                           unsigned int flags)
R
Richard Jones 已提交
20434
{
20435 20436
    const char *model = virDomainWatchdogModelTypeToString(def->model);
    const char *action = virDomainWatchdogActionTypeToString(def->action);
R
Richard Jones 已提交
20437 20438

    if (!model) {
20439 20440
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected watchdog model %d"), def->model);
R
Richard Jones 已提交
20441 20442 20443 20444
        return -1;
    }

    if (!action) {
20445 20446
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected watchdog action %d"), def->action);
R
Richard Jones 已提交
20447 20448 20449
        return -1;
    }

20450
    virBufferAsprintf(buf, "<watchdog model='%s' action='%s'",
R
Richard Jones 已提交
20451 20452
                      model, action);

20453
    if (virDomainDeviceInfoNeedsFormat(&def->info, flags)) {
20454
        virBufferAddLit(buf, ">\n");
20455
        virBufferAdjustIndent(buf, 2);
D
Daniel P. Berrange 已提交
20456
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
20457
            return -1;
20458 20459
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</watchdog>\n");
20460 20461 20462 20463
    } else {
        virBufferAddLit(buf, "/>\n");
    }

R
Richard Jones 已提交
20464 20465 20466
    return 0;
}

H
Hu Tao 已提交
20467
static int virDomainPanicDefFormat(virBufferPtr buf,
20468
                                   virDomainPanicDefPtr def)
H
Hu Tao 已提交
20469
{
20470 20471
    virBuffer childrenBuf = VIR_BUFFER_INITIALIZER;
    int indent = virBufferGetIndent(buf, false);
H
Hu Tao 已提交
20472

20473
    virBufferAddLit(buf, "<panic");
20474 20475 20476 20477 20478

    if (def->model)
        virBufferAsprintf(buf, " model='%s'",
                          virDomainPanicModelTypeToString(def->model));

20479 20480 20481 20482 20483 20484 20485 20486 20487 20488 20489
    virBufferAdjustIndent(&childrenBuf, indent + 2);
    if (virDomainDeviceInfoFormat(&childrenBuf, &def->info, 0) < 0)
        return -1;
    if (virBufferUse(&childrenBuf)) {
        virBufferAddLit(buf, ">\n");
        virBufferAddBuffer(buf, &childrenBuf);
        virBufferAddLit(buf, "</panic>\n");
    } else {
        virBufferAddLit(buf, "/>\n");
    }
    virBufferFreeAndReset(&childrenBuf);
H
Hu Tao 已提交
20490 20491
    return 0;
}
R
Richard Jones 已提交
20492

20493 20494 20495 20496 20497
static int
virDomainShmemDefFormat(virBufferPtr buf,
                        virDomainShmemDefPtr def,
                        unsigned int flags)
{
M
Martin Kletzander 已提交
20498
    virBufferEscapeString(buf, "<shmem name='%s'", def->name);
20499 20500 20501 20502

    if (!def->size &&
        !def->server.enabled &&
        !def->msi.enabled &&
20503
        !virDomainDeviceInfoNeedsFormat(&def->info, flags)) {
20504 20505 20506 20507 20508 20509 20510 20511 20512
        virBufferAddLit(buf, "/>\n");
        return 0;
    } else {
        virBufferAddLit(buf, ">\n");
    }

    virBufferAdjustIndent(buf, 2);

    if (def->size)
M
Martin Kletzander 已提交
20513
        virBufferAsprintf(buf, "<size unit='M'>%llu</size>\n", def->size >> 20);
20514 20515 20516

    if (def->server.enabled) {
        virBufferAddLit(buf, "<server");
20517
        virBufferEscapeString(buf, " path='%s'", def->server.chr.data.nix.path);
20518 20519 20520 20521 20522 20523 20524 20525 20526 20527 20528 20529 20530 20531 20532 20533 20534 20535 20536 20537 20538 20539
        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;
}

20540 20541 20542 20543 20544 20545 20546 20547
static int
virDomainRNGDefFormat(virBufferPtr buf,
                      virDomainRNGDefPtr def,
                      unsigned int flags)
{
    const char *model = virDomainRNGModelTypeToString(def->model);
    const char *backend = virDomainRNGBackendTypeToString(def->backend);

20548 20549
    virBufferAsprintf(buf, "<rng model='%s'>\n", model);
    virBufferAdjustIndent(buf, 2);
20550
    if (def->rate) {
20551
        virBufferAsprintf(buf, "<rate bytes='%u'", def->rate);
20552 20553 20554 20555
        if (def->period)
            virBufferAsprintf(buf, " period='%u'", def->period);
        virBufferAddLit(buf, "/>\n");
    }
20556
    virBufferAsprintf(buf, "<backend model='%s'", backend);
20557

20558
    switch ((virDomainRNGBackend) def->backend) {
20559
    case VIR_DOMAIN_RNG_BACKEND_RANDOM:
20560
        virBufferEscapeString(buf, ">%s</backend>\n", def->source.file);
20561 20562 20563 20564
        break;

    case VIR_DOMAIN_RNG_BACKEND_EGD:
        virBufferAdjustIndent(buf, 2);
J
Ján Tomko 已提交
20565
        if (virDomainChrSourceDefFormat(buf, NULL, def->source.chardev,
20566 20567 20568
                                        false, flags) < 0)
            return -1;
        virBufferAdjustIndent(buf, -2);
20569
        virBufferAddLit(buf, "</backend>\n");
20570 20571 20572 20573 20574

    case VIR_DOMAIN_RNG_BACKEND_LAST:
        break;
    }

20575
    if (virDomainDeviceInfoNeedsFormat(&def->info, flags)) {
20576 20577 20578 20579
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
            return -1;
    }

20580 20581
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</rng>\n");
20582 20583 20584 20585 20586 20587 20588 20589 20590
    return 0;
}

void
virDomainRNGDefFree(virDomainRNGDefPtr def)
{
    if (!def)
        return;

20591
    switch ((virDomainRNGBackend) def->backend) {
20592 20593 20594 20595 20596 20597 20598 20599 20600 20601
    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 已提交
20602
    virDomainDeviceInfoClear(&def->info);
20603 20604 20605
    VIR_FREE(def);
}

20606 20607 20608 20609 20610 20611 20612 20613 20614 20615 20616 20617 20618 20619 20620 20621 20622 20623 20624 20625 20626 20627 20628 20629 20630 20631 20632 20633 20634 20635 20636 20637 20638 20639 20640 20641 20642 20643 20644 20645 20646 20647 20648 20649

static int
virDomainMemorySourceDefFormat(virBufferPtr buf,
                               virDomainMemoryDefPtr def)
{
    char *bitmap = NULL;
    int ret = -1;

    if (!def->pagesize && !def->sourceNodes)
        return 0;

    virBufferAddLit(buf, "<source>\n");
    virBufferAdjustIndent(buf, 2);

    if (def->sourceNodes) {
        if (!(bitmap = virBitmapFormat(def->sourceNodes)))
            goto cleanup;

        virBufferAsprintf(buf, "<nodemask>%s</nodemask>\n", bitmap);
    }

    if (def->pagesize)
        virBufferAsprintf(buf, "<pagesize unit='KiB'>%llu</pagesize>\n",
                          def->pagesize);

    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</source>\n");

    ret = 0;

 cleanup:
    VIR_FREE(bitmap);
    return ret;
}


static void
virDomainMemoryTargetDefFormat(virBufferPtr buf,
                               virDomainMemoryDefPtr def)
{
    virBufferAddLit(buf, "<target>\n");
    virBufferAdjustIndent(buf, 2);

    virBufferAsprintf(buf, "<size unit='KiB'>%llu</size>\n", def->size);
20650 20651
    if (def->targetNode >= 0)
        virBufferAsprintf(buf, "<node>%d</node>\n", def->targetNode);
20652 20653 20654 20655 20656 20657 20658 20659 20660 20661 20662 20663 20664 20665 20666 20667 20668 20669 20670 20671 20672 20673 20674 20675 20676 20677 20678 20679 20680 20681

    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</target>\n");
}

static int
virDomainMemoryDefFormat(virBufferPtr buf,
                         virDomainMemoryDefPtr def,
                         unsigned int flags)
{
    const char *model = virDomainMemoryModelTypeToString(def->model);

    virBufferAsprintf(buf, "<memory model='%s'>\n", model);
    virBufferAdjustIndent(buf, 2);

    if (virDomainMemorySourceDefFormat(buf, def) < 0)
        return -1;

    virDomainMemoryTargetDefFormat(buf, def);

    if (virDomainDeviceInfoNeedsFormat(&def->info, flags)) {
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
            return -1;
    }

    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</memory>\n");
    return 0;
}

20682 20683 20684 20685
static void
virDomainVideoAccelDefFormat(virBufferPtr buf,
                             virDomainVideoAccelDefPtr def)
{
20686 20687 20688 20689 20690 20691 20692 20693 20694
    virBufferAddLit(buf, "<acceleration");
    if (def->accel3d) {
        virBufferAsprintf(buf, " accel3d='%s'",
                          virTristateBoolTypeToString(def->accel3d));
    }
    if (def->accel2d) {
        virBufferAsprintf(buf, " accel2d='%s'",
                          virTristateBoolTypeToString(def->accel2d));
    }
20695 20696 20697 20698
    virBufferAddLit(buf, "/>\n");
}


20699
static int
20700
virDomainVideoDefFormat(virBufferPtr buf,
D
Daniel P. Berrange 已提交
20701
                        virDomainVideoDefPtr def,
E
Eric Blake 已提交
20702
                        unsigned int flags)
20703 20704 20705 20706
{
    const char *model = virDomainVideoTypeToString(def->type);

    if (!model) {
20707 20708
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected video model %d"), def->type);
20709 20710 20711
        return -1;
    }

20712 20713 20714
    virBufferAddLit(buf, "<video>\n");
    virBufferAdjustIndent(buf, 2);
    virBufferAsprintf(buf, "<model type='%s'",
20715
                      model);
20716 20717
    if (def->ram)
        virBufferAsprintf(buf, " ram='%u'", def->ram);
20718
    if (def->vram)
20719
        virBufferAsprintf(buf, " vram='%u'", def->vram);
20720 20721
    if (def->vgamem)
        virBufferAsprintf(buf, " vgamem='%u'", def->vgamem);
20722
    if (def->heads)
20723
        virBufferAsprintf(buf, " heads='%u'", def->heads);
20724 20725
    if (def->primary)
        virBufferAddLit(buf, " primary='yes'");
20726 20727
    if (def->accel) {
        virBufferAddLit(buf, ">\n");
20728
        virBufferAdjustIndent(buf, 2);
20729
        virDomainVideoAccelDefFormat(buf, def->accel);
20730 20731
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</model>\n");
20732 20733 20734 20735
    } else {
        virBufferAddLit(buf, "/>\n");
    }

D
Daniel P. Berrange 已提交
20736
    if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
20737 20738
        return -1;

20739 20740
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</video>\n");
20741 20742 20743
    return 0;
}

20744
static int
20745
virDomainInputDefFormat(virBufferPtr buf,
20746
                        virDomainInputDefPtr def,
E
Eric Blake 已提交
20747
                        unsigned int flags)
20748 20749 20750 20751
{
    const char *type = virDomainInputTypeToString(def->type);
    const char *bus = virDomainInputBusTypeToString(def->bus);

P
Pavel Hrdina 已提交
20752 20753 20754 20755 20756
    /* don't format keyboard into migratable XML for backward compatibility */
    if (def->type == VIR_DOMAIN_INPUT_TYPE_KBD &&
        flags & VIR_DOMAIN_DEF_FORMAT_MIGRATABLE)
        return 0;

20757
    if (!type) {
20758 20759
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected input type %d"), def->type);
20760 20761 20762
        return -1;
    }
    if (!bus) {
20763 20764
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected input bus type %d"), def->bus);
20765 20766 20767
        return -1;
    }

20768
    virBufferAsprintf(buf, "<input type='%s' bus='%s'",
20769 20770
                      type, bus);

20771 20772
    if (virDomainDeviceInfoNeedsFormat(&def->info, flags) ||
        def->type == VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH) {
20773
        virBufferAddLit(buf, ">\n");
20774
        virBufferAdjustIndent(buf, 2);
20775
        virBufferEscapeString(buf, "<source evdev='%s'/>\n", def->source.evdev);
20776 20777
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
            return -1;
20778 20779
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</input>\n");
20780 20781 20782 20783
    } else {
        virBufferAddLit(buf, "/>\n");
    }

20784 20785 20786 20787
    return 0;
}


20788 20789 20790 20791 20792 20793 20794
static int
virDomainTimerDefFormat(virBufferPtr buf,
                        virDomainTimerDefPtr def)
{
    const char *name = virDomainTimerNameTypeToString(def->name);

    if (!name) {
20795 20796
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected timer name %d"), def->name);
20797 20798
        return -1;
    }
20799
    virBufferAsprintf(buf, "<timer name='%s'", name);
20800 20801 20802 20803 20804 20805 20806 20807 20808 20809 20810

    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) {
20811 20812 20813
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected timer tickpolicy %d"),
                           def->tickpolicy);
20814 20815
            return -1;
        }
20816
        virBufferAsprintf(buf, " tickpolicy='%s'", tickpolicy);
20817 20818 20819 20820
    }

    if ((def->name == VIR_DOMAIN_TIMER_NAME_PLATFORM)
        || (def->name == VIR_DOMAIN_TIMER_NAME_RTC)) {
20821 20822 20823 20824
        if (def->track != -1) {
            const char *track
                = virDomainTimerTrackTypeToString(def->track);
            if (!track) {
20825 20826 20827
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected timer track %d"),
                               def->track);
20828 20829
                return -1;
            }
20830
            virBufferAsprintf(buf, " track='%s'", track);
20831 20832 20833 20834
        }
    }

    if (def->name == VIR_DOMAIN_TIMER_NAME_TSC) {
20835
        if (def->frequency > 0)
20836
            virBufferAsprintf(buf, " frequency='%lu'", def->frequency);
20837 20838 20839 20840 20841

        if (def->mode != -1) {
            const char *mode
                = virDomainTimerModeTypeToString(def->mode);
            if (!mode) {
20842 20843 20844
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected timer mode %d"),
                               def->mode);
20845 20846
                return -1;
            }
20847
            virBufferAsprintf(buf, " mode='%s'", mode);
20848 20849 20850
        }
    }

E
Eric Blake 已提交
20851 20852
    if (def->catchup.threshold == 0 && def->catchup.slew == 0 &&
        def->catchup.limit == 0) {
20853 20854
        virBufferAddLit(buf, "/>\n");
    } else {
20855
        virBufferAddLit(buf, ">\n");
20856 20857
        virBufferAdjustIndent(buf, 2);
        virBufferAddLit(buf, "<catchup");
20858
        if (def->catchup.threshold > 0)
20859
            virBufferAsprintf(buf, " threshold='%lu'", def->catchup.threshold);
20860
        if (def->catchup.slew > 0)
20861
            virBufferAsprintf(buf, " slew='%lu'", def->catchup.slew);
20862
        if (def->catchup.limit > 0)
20863
            virBufferAsprintf(buf, " limit='%lu'", def->catchup.limit);
20864
        virBufferAddLit(buf, "/>\n");
20865 20866
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</timer>\n");
20867
    }
20868 20869 20870 20871

    return 0;
}

20872 20873 20874 20875 20876 20877 20878 20879
static void
virDomainGraphicsAuthDefFormatAttr(virBufferPtr buf,
                                   virDomainGraphicsAuthDefPtr def,
                                   unsigned int flags)
{
    if (!def->passwd)
        return;

20880
    if (flags & VIR_DOMAIN_DEF_FORMAT_SECURE)
20881 20882 20883 20884 20885 20886 20887 20888
        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);
20889
        virBufferAsprintf(buf, " passwdValidTo='%s'", strbuf);
20890
    }
20891 20892 20893 20894

    if (def->connected)
        virBufferEscapeString(buf, " connected='%s'",
                              virDomainGraphicsAuthConnectedTypeToString(def->connected));
20895 20896
}

20897 20898 20899 20900 20901 20902

static void
virDomainGraphicsListenDefFormat(virBufferPtr buf,
                                 virDomainGraphicsListenDefPtr def,
                                 unsigned int flags)
{
20903 20904
    /* If generating migratable XML, skip listen address
     * dragged in from config file */
20905
    if ((flags & VIR_DOMAIN_DEF_FORMAT_MIGRATABLE) && def->fromConfig)
20906 20907
        return;

20908
    virBufferAddLit(buf, "<listen");
20909 20910 20911 20912 20913 20914
    if (def->type) {
        virBufferAsprintf(buf, " type='%s'",
                          virDomainGraphicsListenTypeToString(def->type));
    }

    if (def->address &&
E
Eric Blake 已提交
20915 20916
        (def->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS ||
         (def->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK &&
20917
          !(flags & VIR_DOMAIN_DEF_FORMAT_INACTIVE)))) {
20918 20919 20920 20921 20922 20923 20924
        /* 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)) {
20925
        virBufferEscapeString(buf, " network='%s'", def->network);
20926 20927
    }

20928
    if (flags & VIR_DOMAIN_DEF_FORMAT_STATUS)
20929 20930
        virBufferAsprintf(buf, " fromConfig='%d'", def->fromConfig);

20931 20932 20933 20934
    virBufferAddLit(buf, "/>\n");
}


20935
static int
20936
virDomainGraphicsDefFormat(virBufferPtr buf,
20937
                           virDomainGraphicsDefPtr def,
E
Eric Blake 已提交
20938
                           unsigned int flags)
20939 20940
{
    const char *type = virDomainGraphicsTypeToString(def->type);
20941
    const char *listenAddr = NULL;
20942
    bool children = false;
20943
    size_t i;
20944 20945

    if (!type) {
20946 20947
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected net type %d"), def->type);
20948 20949 20950
        return -1;
    }

20951 20952 20953 20954
    /* find the first listen subelement with a valid address and
    * duplicate its address attribute as the listen attribute of
    * <graphics>. This is done to improve backward compatibility.
    */
20955
    for (i = 0; i < def->nListens; i++) {
20956 20957 20958 20959
        if (flags & VIR_DOMAIN_DEF_FORMAT_MIGRATABLE &&
            def->listens[i].fromConfig)
            continue;

20960 20961 20962 20963 20964 20965 20966
        if (def->listens[i].type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK &&
            flags & (VIR_DOMAIN_DEF_FORMAT_INACTIVE |
                     VIR_DOMAIN_DEF_FORMAT_MIGRATABLE))
            continue;

        if ((listenAddr = virDomainGraphicsListenGetAddress(def, i)))
            break;
20967 20968
    }

20969
    virBufferAsprintf(buf, "<graphics type='%s'", type);
20970 20971 20972

    switch (def->type) {
    case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
20973
        if (def->data.vnc.socket) {
20974
            virBufferEscapeString(buf, " socket='%s'", def->data.vnc.socket);
20975 20976
        } else {
            if (def->data.vnc.port &&
20977
                (!def->data.vnc.autoport || !(flags & VIR_DOMAIN_DEF_FORMAT_INACTIVE)))
20978
                virBufferAsprintf(buf, " port='%d'",
20979 20980 20981
                                  def->data.vnc.port);
            else if (def->data.vnc.autoport)
                virBufferAddLit(buf, " port='-1'");
20982

20983
            virBufferAsprintf(buf, " autoport='%s'",
20984
                              def->data.vnc.autoport ? "yes" : "no");
20985

M
Martin Kletzander 已提交
20986 20987 20988
            if (def->data.vnc.websocket)
                virBufferAsprintf(buf, " websocket='%d'", def->data.vnc.websocket);

20989 20990
            if (listenAddr)
                virBufferAsprintf(buf, " listen='%s'", listenAddr);
20991
        }
20992 20993 20994 20995 20996

        if (def->data.vnc.keymap)
            virBufferEscapeString(buf, " keymap='%s'",
                                  def->data.vnc.keymap);

20997 20998 20999 21000 21001
        if (def->data.vnc.sharePolicy)
            virBufferAsprintf(buf, " sharePolicy='%s'",
                              virDomainGraphicsVNCSharePolicyTypeToString(
                              def->data.vnc.sharePolicy));

21002
        virDomainGraphicsAuthDefFormatAttr(buf, &def->data.vnc.auth, flags);
21003 21004 21005 21006 21007 21008 21009 21010 21011 21012
        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);
21013 21014 21015
        if (def->data.sdl.fullscreen)
            virBufferAddLit(buf, " fullscreen='yes'");

21016
        break;
21017 21018 21019

    case VIR_DOMAIN_GRAPHICS_TYPE_RDP:
        if (def->data.rdp.port)
21020
            virBufferAsprintf(buf, " port='%d'",
21021 21022 21023 21024 21025
                              def->data.rdp.port);
        else if (def->data.rdp.autoport)
            virBufferAddLit(buf, " port='0'");

        if (def->data.rdp.autoport)
21026
            virBufferAddLit(buf, " autoport='yes'");
21027 21028

        if (def->data.rdp.replaceUser)
21029
            virBufferAddLit(buf, " replaceUser='yes'");
21030 21031

        if (def->data.rdp.multiUser)
21032
            virBufferAddLit(buf, " multiUser='yes'");
21033

21034 21035
        if (listenAddr)
            virBufferAsprintf(buf, " listen='%s'", listenAddr);
21036 21037 21038 21039 21040 21041 21042 21043 21044 21045 21046 21047 21048

        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;

21049 21050
    case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
        if (def->data.spice.port)
21051
            virBufferAsprintf(buf, " port='%d'",
21052 21053 21054
                              def->data.spice.port);

        if (def->data.spice.tlsPort)
21055
            virBufferAsprintf(buf, " tlsPort='%d'",
21056 21057
                              def->data.spice.tlsPort);

21058
        virBufferAsprintf(buf, " autoport='%s'",
21059 21060
                          def->data.spice.autoport ? "yes" : "no");

21061 21062
        if (listenAddr)
            virBufferAsprintf(buf, " listen='%s'", listenAddr);
21063 21064 21065 21066 21067

        if (def->data.spice.keymap)
            virBufferEscapeString(buf, " keymap='%s'",
                                  def->data.spice.keymap);

21068 21069 21070 21071
        if (def->data.spice.defaultMode != VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_ANY)
            virBufferAsprintf(buf, " defaultMode='%s'",
              virDomainGraphicsSpiceChannelModeTypeToString(def->data.spice.defaultMode));

21072
        virDomainGraphicsAuthDefFormatAttr(buf, &def->data.spice.auth, flags);
21073 21074
        break;

21075 21076
    }

21077 21078 21079 21080
    for (i = 0; i < def->nListens; i++) {
        if (virDomainGraphicsListenGetType(def, i)
            == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NONE)
            continue;
21081
        if (flags & VIR_DOMAIN_DEF_FORMAT_MIGRATABLE &&
21082 21083
            def->listens[i].fromConfig)
            continue;
21084 21085
        if (!children) {
            virBufferAddLit(buf, ">\n");
21086
            virBufferAdjustIndent(buf, 2);
21087
            children = true;
21088 21089 21090 21091
        }
        virDomainGraphicsListenDefFormat(buf, &def->listens[i], flags);
    }

21092
    if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE) {
21093
        for (i = 0; i < VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_LAST; i++) {
21094 21095 21096 21097 21098 21099
            int mode = def->data.spice.channels[i];
            if (mode == VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_ANY)
                continue;

            if (!children) {
                virBufferAddLit(buf, ">\n");
21100
                virBufferAdjustIndent(buf, 2);
21101
                children = true;
21102 21103
            }

21104
            virBufferAsprintf(buf, "<channel name='%s' mode='%s'/>\n",
21105 21106 21107
                              virDomainGraphicsSpiceChannelNameTypeToString(i),
                              virDomainGraphicsSpiceChannelModeTypeToString(mode));
        }
21108 21109
        if (!children && (def->data.spice.image || def->data.spice.jpeg ||
                          def->data.spice.zlib || def->data.spice.playback ||
P
Peng Zhou 已提交
21110
                          def->data.spice.streaming || def->data.spice.copypaste ||
21111
                          def->data.spice.mousemode || def->data.spice.filetransfer)) {
21112
            virBufferAddLit(buf, ">\n");
21113
            virBufferAdjustIndent(buf, 2);
21114
            children = true;
21115
        }
21116
        if (def->data.spice.image)
21117
            virBufferAsprintf(buf, "<image compression='%s'/>\n",
21118 21119
                              virDomainGraphicsSpiceImageCompressionTypeToString(def->data.spice.image));
        if (def->data.spice.jpeg)
21120
            virBufferAsprintf(buf, "<jpeg compression='%s'/>\n",
21121 21122
                              virDomainGraphicsSpiceJpegCompressionTypeToString(def->data.spice.jpeg));
        if (def->data.spice.zlib)
21123
            virBufferAsprintf(buf, "<zlib compression='%s'/>\n",
21124 21125
                              virDomainGraphicsSpiceZlibCompressionTypeToString(def->data.spice.zlib));
        if (def->data.spice.playback)
21126
            virBufferAsprintf(buf, "<playback compression='%s'/>\n",
J
Ján Tomko 已提交
21127
                              virTristateSwitchTypeToString(def->data.spice.playback));
21128
        if (def->data.spice.streaming)
21129
            virBufferAsprintf(buf, "<streaming mode='%s'/>\n",
21130
                              virDomainGraphicsSpiceStreamingModeTypeToString(def->data.spice.streaming));
P
Peng Zhou 已提交
21131
        if (def->data.spice.mousemode)
21132
            virBufferAsprintf(buf, "<mouse mode='%s'/>\n",
P
Peng Zhou 已提交
21133
                              virDomainGraphicsSpiceMouseModeTypeToString(def->data.spice.mousemode));
21134
        if (def->data.spice.copypaste)
21135
            virBufferAsprintf(buf, "<clipboard copypaste='%s'/>\n",
J
Ján Tomko 已提交
21136
                              virTristateBoolTypeToString(def->data.spice.copypaste));
21137
        if (def->data.spice.filetransfer)
21138
            virBufferAsprintf(buf, "<filetransfer enable='%s'/>\n",
J
Ján Tomko 已提交
21139
                              virTristateBoolTypeToString(def->data.spice.filetransfer));
21140 21141 21142
    }

    if (children) {
21143 21144
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</graphics>\n");
21145 21146 21147
    } else {
        virBufferAddLit(buf, "/>\n");
    }
21148 21149 21150 21151

    return 0;
}

21152 21153

static int
21154
virDomainHostdevDefFormat(virBufferPtr buf,
D
Daniel P. Berrange 已提交
21155
                          virDomainHostdevDefPtr def,
E
Eric Blake 已提交
21156
                          unsigned int flags)
21157 21158
{
    const char *mode = virDomainHostdevModeTypeToString(def->mode);
21159
    virDomainHostdevSubsysSCSIPtr scsisrc = &def->source.subsys.u.scsi;
21160 21161
    const char *type;

21162
    if (!mode) {
21163 21164
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected hostdev mode %d"), def->mode);
21165 21166 21167
        return -1;
    }

21168 21169 21170 21171 21172 21173 21174 21175 21176 21177
    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;
21178 21179 21180 21181 21182 21183 21184 21185 21186
    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;
21187
    default:
21188
        virReportError(VIR_ERR_INTERNAL_ERROR,
21189
                       _("unexpected hostdev mode %d"), def->mode);
21190 21191 21192
        return -1;
    }

21193
    virBufferAsprintf(buf, "<hostdev mode='%s' type='%s'",
21194
                      mode, type);
O
Osier Yang 已提交
21195 21196
    if (def->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
        virBufferAsprintf(buf, " managed='%s'",
21197
                          def->managed ? "yes" : "no");
O
Osier Yang 已提交
21198

21199 21200
        if (def->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
            scsisrc->sgio)
O
Osier Yang 已提交
21201
            virBufferAsprintf(buf, " sgio='%s'",
21202
                              virDomainDeviceSGIOTypeToString(scsisrc->sgio));
21203 21204 21205 21206 21207 21208

        if (def->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI &&
            scsisrc->rawio) {
            virBufferAsprintf(buf, " rawio='%s'",
                              virTristateBoolTypeToString(scsisrc->rawio));
        }
O
Osier Yang 已提交
21209 21210
    }
    virBufferAddLit(buf, ">\n");
21211
    virBufferAdjustIndent(buf, 2);
21212

21213 21214 21215 21216 21217
    switch (def->mode) {
    case VIR_DOMAIN_HOSTDEV_MODE_SUBSYS:
        if (virDomainHostdevDefFormatSubsys(buf, def, flags, false) < 0)
            return -1;
        break;
21218 21219 21220 21221
    case VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES:
        if (virDomainHostdevDefFormatCaps(buf, def) < 0)
            return -1;
        break;
21222
    }
O
Osier Yang 已提交
21223 21224 21225

    if (def->readonly)
        virBufferAddLit(buf, "<readonly/>\n");
21226 21227
    if (def->shareable)
        virBufferAddLit(buf, "<shareable/>\n");
21228

21229
    if (virDomainDeviceInfoFormat(buf, def->info,
21230 21231
                                  flags | VIR_DOMAIN_DEF_FORMAT_ALLOW_BOOT
                                  | VIR_DOMAIN_DEF_FORMAT_ALLOW_ROM) < 0)
21232 21233
        return -1;

21234 21235
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</hostdev>\n");
21236 21237 21238 21239

    return 0;
}

21240 21241 21242 21243 21244 21245 21246 21247 21248
static int
virDomainRedirdevDefFormat(virBufferPtr buf,
                           virDomainRedirdevDefPtr def,
                           unsigned int flags)
{
    const char *bus;

    bus = virDomainRedirdevBusTypeToString(def->bus);

21249 21250
    virBufferAsprintf(buf, "<redirdev bus='%s'", bus);
    virBufferAdjustIndent(buf, 2);
J
Ján Tomko 已提交
21251
    if (virDomainChrSourceDefFormat(buf, NULL, &def->source.chr, false, flags) < 0)
21252
        return -1;
21253
    if (virDomainDeviceInfoFormat(buf, &def->info,
21254
                                  flags | VIR_DOMAIN_DEF_FORMAT_ALLOW_BOOT) < 0)
21255
        return -1;
21256 21257
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</redirdev>\n");
21258 21259
    return 0;
}
21260

21261 21262 21263 21264 21265 21266
static int
virDomainRedirFilterDefFormat(virBufferPtr buf,
                              virDomainRedirFilterDefPtr filter)
{
    size_t i;

21267 21268 21269 21270
    /* no need format an empty redirfilter */
    if (filter->nusbdevs == 0)
        return 0;

21271 21272
    virBufferAddLit(buf, "<redirfilter>\n");
    virBufferAdjustIndent(buf, 2);
21273
    for (i = 0; i < filter->nusbdevs; i++) {
21274
        virDomainRedirFilterUSBDevDefPtr usbdev = filter->usbdevs[i];
21275
        virBufferAddLit(buf, "<usbdev");
21276 21277 21278 21279 21280 21281 21282 21283 21284 21285
        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)
21286
            virBufferAsprintf(buf, " version='%d.%02d'",
21287 21288 21289 21290 21291 21292 21293 21294
                                 ((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");

    }
21295 21296
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</redirfilter>\n");
21297 21298 21299
    return 0;
}

M
Marc-André Lureau 已提交
21300 21301
static int
virDomainHubDefFormat(virBufferPtr buf,
21302 21303
                      virDomainHubDefPtr def,
                      unsigned int flags)
M
Marc-André Lureau 已提交
21304 21305 21306 21307
{
    const char *type = virDomainHubTypeToString(def->type);

    if (!type) {
21308 21309
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected hub type %d"), def->type);
M
Marc-André Lureau 已提交
21310 21311 21312
        return -1;
    }

21313
    virBufferAsprintf(buf, "<hub type='%s'", type);
M
Marc-André Lureau 已提交
21314

21315
    if (virDomainDeviceInfoNeedsFormat(&def->info, flags)) {
M
Marc-André Lureau 已提交
21316
        virBufferAddLit(buf, ">\n");
21317
        virBufferAdjustIndent(buf, 2);
M
Marc-André Lureau 已提交
21318 21319
        if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)
            return -1;
21320 21321
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</hub>\n");
M
Marc-André Lureau 已提交
21322 21323 21324 21325 21326 21327 21328
    } else {
        virBufferAddLit(buf, "/>\n");
    }

    return 0;
}

21329 21330 21331 21332 21333

static void
virDomainResourceDefFormat(virBufferPtr buf,
                           virDomainResourceDefPtr def)
{
21334 21335 21336 21337 21338
    virBufferAddLit(buf, "<resource>\n");
    virBufferAdjustIndent(buf, 2);
    virBufferEscapeString(buf, "<partition>%s</partition>\n", def->partition);
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</resource>\n");
21339 21340 21341
}


21342 21343 21344 21345 21346 21347 21348 21349 21350 21351 21352 21353 21354 21355 21356 21357 21358 21359 21360 21361 21362 21363 21364 21365 21366 21367 21368 21369 21370 21371 21372 21373 21374 21375 21376 21377 21378 21379 21380 21381 21382 21383 21384 21385 21386 21387 21388
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");
}

21389 21390 21391 21392 21393 21394 21395 21396 21397 21398 21399 21400 21401 21402 21403
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);
21404 21405 21406 21407 21408 21409 21410 21411
    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");
    }
21412
}
21413

21414 21415 21416 21417 21418 21419 21420 21421 21422 21423 21424 21425 21426 21427 21428 21429 21430 21431
static void
virDomainKeyWrapDefFormat(virBufferPtr buf, virDomainKeyWrapDefPtr keywrap)
{
    virBufferAddLit(buf, "<keywrap>\n");
    virBufferAdjustIndent(buf, 2);

    if (keywrap->aes)
        virBufferAsprintf(buf, "<cipher name='aes' state='%s'/>\n",
                          virTristateSwitchTypeToString(keywrap->aes));

    if (keywrap->dea)
        virBufferAsprintf(buf, "<cipher name='dea' state='%s'/>\n",
                          virTristateSwitchTypeToString(keywrap->dea));

    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</keywrap>\n");
}

21432 21433 21434 21435 21436 21437
static bool
virDomainDefHasCapabilitiesFeatures(virDomainDefPtr def)
{
    size_t i;

    for (i = 0; i < VIR_DOMAIN_CAPS_FEATURE_LAST; i++) {
J
Ján Tomko 已提交
21438
        if (def->caps_features[i] != VIR_TRISTATE_SWITCH_ABSENT)
21439 21440 21441 21442 21443 21444
            return true;
    }

    return false;
}

21445 21446 21447 21448 21449 21450 21451 21452 21453 21454 21455 21456 21457 21458 21459 21460 21461 21462 21463 21464 21465 21466 21467 21468 21469 21470 21471 21472 21473 21474 21475 21476 21477 21478 21479 21480 21481 21482 21483 21484 21485 21486 21487 21488 21489 21490 21491 21492 21493 21494 21495 21496 21497 21498 21499 21500 21501 21502 21503 21504 21505 21506 21507 21508 21509 21510 21511 21512 21513 21514 21515 21516 21517 21518 21519 21520 21521 21522 21523 21524 21525 21526 21527 21528 21529 21530 21531 21532 21533 21534 21535 21536 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 21564 21565 21566 21567

static int
virDomainCputuneDefFormat(virBufferPtr buf,
                          virDomainDefPtr def)
{
    size_t i;
    virBuffer childrenBuf = VIR_BUFFER_INITIALIZER;
    int ret = -1;

    virBufferAdjustIndent(&childrenBuf, virBufferGetIndent(buf, false) + 2);

    if (def->cputune.sharesSpecified)
        virBufferAsprintf(&childrenBuf, "<shares>%lu</shares>\n",
                          def->cputune.shares);
    if (def->cputune.period)
        virBufferAsprintf(&childrenBuf, "<period>%llu</period>\n",
                          def->cputune.period);
    if (def->cputune.quota)
        virBufferAsprintf(&childrenBuf, "<quota>%lld</quota>\n",
                          def->cputune.quota);

    if (def->cputune.emulator_period)
        virBufferAsprintf(&childrenBuf, "<emulator_period>%llu"
                          "</emulator_period>\n",
                          def->cputune.emulator_period);

    if (def->cputune.emulator_quota)
        virBufferAsprintf(&childrenBuf, "<emulator_quota>%lld"
                          "</emulator_quota>\n",
                          def->cputune.emulator_quota);

    for (i = 0; i < def->maxvcpus; i++) {
        char *cpumask;
        virDomainVcpuInfoPtr vcpu = def->vcpus + i;

        if (!vcpu->cpumask)
            continue;

        if (!(cpumask = virBitmapFormat(vcpu->cpumask)))
            goto cleanup;

        virBufferAsprintf(&childrenBuf,
                          "<vcpupin vcpu='%zu' cpuset='%s'/>\n", i, cpumask);

        VIR_FREE(cpumask);
    }

    if (def->cputune.emulatorpin) {
        char *cpumask;
        virBufferAddLit(&childrenBuf, "<emulatorpin ");

        if (!(cpumask = virBitmapFormat(def->cputune.emulatorpin)))
            goto cleanup;

        virBufferAsprintf(&childrenBuf, "cpuset='%s'/>\n", cpumask);
        VIR_FREE(cpumask);
    }

    for (i = 0; i < def->niothreadids; i++) {
        char *cpumask;

        /* Ignore iothreadids with no cpumask */
        if (!def->iothreadids[i]->cpumask)
            continue;

        virBufferAsprintf(&childrenBuf, "<iothreadpin iothread='%u' ",
                          def->iothreadids[i]->iothread_id);

        if (!(cpumask = virBitmapFormat(def->iothreadids[i]->cpumask)))
            goto cleanup;

        virBufferAsprintf(&childrenBuf, "cpuset='%s'/>\n", cpumask);
        VIR_FREE(cpumask);
    }

    for (i = 0; i < def->cputune.nvcpusched; i++) {
        virDomainThreadSchedParamPtr sp = &def->cputune.vcpusched[i];
        char *ids = NULL;

        if (!(ids = virBitmapFormat(sp->ids)))
            goto cleanup;

        virBufferAsprintf(&childrenBuf, "<vcpusched vcpus='%s' scheduler='%s'",
                          ids, virProcessSchedPolicyTypeToString(sp->policy));
        VIR_FREE(ids);

        if (sp->policy == VIR_PROC_POLICY_FIFO ||
            sp->policy == VIR_PROC_POLICY_RR)
            virBufferAsprintf(&childrenBuf, " priority='%d'", sp->priority);
        virBufferAddLit(&childrenBuf, "/>\n");
    }

    for (i = 0; i < def->cputune.niothreadsched; i++) {
        virDomainThreadSchedParamPtr sp = &def->cputune.iothreadsched[i];
        char *ids = NULL;

        if (!(ids = virBitmapFormat(sp->ids)))
            goto cleanup;

        virBufferAsprintf(&childrenBuf, "<iothreadsched iothreads='%s' scheduler='%s'",
                          ids, virProcessSchedPolicyTypeToString(sp->policy));
        VIR_FREE(ids);

        if (sp->policy == VIR_PROC_POLICY_FIFO ||
            sp->policy == VIR_PROC_POLICY_RR)
            virBufferAsprintf(&childrenBuf, " priority='%d'", sp->priority);
        virBufferAddLit(&childrenBuf, "/>\n");
    }

    if (virBufferUse(&childrenBuf)) {
        virBufferAddLit(buf, "<cputune>\n");
        virBufferAddBuffer(buf, &childrenBuf);
        virBufferAddLit(buf, "</cputune>\n");
    }

    ret = 0;

 cleanup:
    virBufferFreeAndReset(&childrenBuf);
    return ret;
}


21568 21569 21570
/* This internal version appends to an existing buffer
 * (possibly with auto-indent), rather than flattening
 * to string.
21571 21572
 * Return -1 on failure.  */
int
21573
virDomainDefFormatInternal(virDomainDefPtr def,
21574
                           virCapsPtr caps,
21575 21576
                           unsigned int flags,
                           virBufferPtr buf)
21577 21578 21579
{
    unsigned char *uuid;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
21580
    const char *type = NULL;
H
Hu Tao 已提交
21581
    int n;
21582
    size_t i;
21583 21584
    virBuffer childrenBuf = VIR_BUFFER_INITIALIZER;
    int indent;
21585
    char *netprefix = NULL;
21586

21587 21588 21589 21590 21591
    virCheckFlags(VIR_DOMAIN_DEF_FORMAT_COMMON_FLAGS |
                  VIR_DOMAIN_DEF_FORMAT_STATUS |
                  VIR_DOMAIN_DEF_FORMAT_ACTUAL_NET |
                  VIR_DOMAIN_DEF_FORMAT_PCI_ORIG_STATES |
                  VIR_DOMAIN_DEF_FORMAT_CLOCK_ADJUST,
21592
                  -1);
21593

21594
    if (!(type = virDomainVirtTypeToString(def->virtType))) {
21595 21596
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected domain type %d"), def->virtType);
21597
        goto error;
21598 21599
    }

21600
    if (def->id == -1)
21601
        flags |= VIR_DOMAIN_DEF_FORMAT_INACTIVE;
21602

21603
    virBufferAsprintf(buf, "<domain type='%s'", type);
21604
    if (!(flags & VIR_DOMAIN_DEF_FORMAT_INACTIVE))
21605
        virBufferAsprintf(buf, " id='%d'", def->id);
21606
    if (def->namespaceData && def->ns.href)
21607 21608
        virBufferAsprintf(buf, " %s", (def->ns.href)());
    virBufferAddLit(buf, ">\n");
21609
    virBufferAdjustIndent(buf, 2);
21610

21611
    virBufferEscapeString(buf, "<name>%s</name>\n", def->name);
21612 21613 21614

    uuid = def->uuid;
    virUUIDFormat(uuid, uuidstr);
21615
    virBufferAsprintf(buf, "<uuid>%s</uuid>\n", uuidstr);
21616

21617
    virBufferEscapeString(buf, "<title>%s</title>\n", def->title);
21618

21619
    virBufferEscapeString(buf, "<description>%s</description>\n",
21620
                          def->description);
21621

21622 21623 21624 21625 21626 21627 21628 21629 21630 21631 21632 21633 21634
    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,
21635
                        virBufferGetIndent(buf, false) / 2, 1) < 0) {
21636 21637
            xmlBufferFree(xmlbuf);
            xmlIndentTreeOutput = oldIndentTreeOutput;
21638
            goto error;
21639
        }
21640
        virBufferAsprintf(buf, "%s\n", (char *) xmlBufferContent(xmlbuf));
21641 21642 21643 21644
        xmlBufferFree(xmlbuf);
        xmlIndentTreeOutput = oldIndentTreeOutput;
    }

21645
    if (virDomainDefHasMemoryHotplug(def)) {
21646 21647 21648 21649 21650
        virBufferAsprintf(buf,
                          "<maxMemory slots='%u' unit='KiB'>%llu</maxMemory>\n",
                          def->mem.memory_slots, def->mem.max_memory);
    }

21651
    virBufferAddLit(buf, "<memory");
21652 21653
    if (def->mem.dump_core)
        virBufferAsprintf(buf, " dumpCore='%s'",
J
Ján Tomko 已提交
21654
                          virTristateSwitchTypeToString(def->mem.dump_core));
21655
    virBufferAsprintf(buf, " unit='KiB'>%llu</memory>\n",
21656
                      virDomainDefGetMemoryActual(def));
21657

21658
    virBufferAsprintf(buf, "<currentMemory unit='KiB'>%llu</currentMemory>\n",
21659 21660
                      def->mem.cur_balloon);

21661 21662 21663 21664 21665 21666
    /* start format blkiotune */
    indent = virBufferGetIndent(buf, false);
    virBufferAdjustIndent(&childrenBuf, indent + 2);
    if (def->blkio.weight)
        virBufferAsprintf(&childrenBuf, "<weight>%u</weight>\n",
                          def->blkio.weight);
21667

21668 21669
    for (n = 0; n < def->blkio.ndevices; n++) {
        virBlkioDevicePtr dev = &def->blkio.devices[n];
21670

21671 21672 21673 21674 21675 21676 21677 21678 21679 21680 21681 21682 21683 21684 21685 21686 21687 21688 21689 21690 21691 21692 21693 21694 21695 21696 21697 21698
        if (!dev->weight && !dev->riops && !dev->wiops &&
            !dev->rbps && !dev->wbps)
            continue;
        virBufferAddLit(&childrenBuf, "<device>\n");
        virBufferAdjustIndent(&childrenBuf, 2);
        virBufferEscapeString(&childrenBuf, "<path>%s</path>\n",
                              dev->path);
        if (dev->weight)
            virBufferAsprintf(&childrenBuf, "<weight>%u</weight>\n",
                              dev->weight);
        if (dev->riops)
            virBufferAsprintf(&childrenBuf, "<read_iops_sec>%u</read_iops_sec>\n",
                              dev->riops);
        if (dev->wiops)
            virBufferAsprintf(&childrenBuf, "<write_iops_sec>%u</write_iops_sec>\n",
                              dev->wiops);
        if (dev->rbps)
            virBufferAsprintf(&childrenBuf, "<read_bytes_sec>%llu</read_bytes_sec>\n",
                              dev->rbps);
        if (dev->wbps)
            virBufferAsprintf(&childrenBuf, "<write_bytes_sec>%llu</write_bytes_sec>\n",
                              dev->wbps);
        virBufferAdjustIndent(&childrenBuf, -2);
        virBufferAddLit(&childrenBuf, "</device>\n");
    }
    if (virBufferUse(&childrenBuf)) {
        virBufferAddLit(buf, "<blkiotune>\n");
        virBufferAddBuffer(buf, &childrenBuf);
21699
        virBufferAddLit(buf, "</blkiotune>\n");
21700
    }
21701
    virBufferFreeAndReset(&childrenBuf);
21702

21703
    /* add memtune only if there are any */
21704 21705 21706
    if (virMemoryLimitIsSet(def->mem.hard_limit) ||
        virMemoryLimitIsSet(def->mem.soft_limit) ||
        virMemoryLimitIsSet(def->mem.swap_hard_limit) ||
21707
        def->mem.min_guarantee) {
21708 21709
        virBufferAddLit(buf, "<memtune>\n");
        virBufferAdjustIndent(buf, 2);
21710
        if (virMemoryLimitIsSet(def->mem.hard_limit)) {
21711
            virBufferAsprintf(buf, "<hard_limit unit='KiB'>"
21712 21713
                              "%llu</hard_limit>\n", def->mem.hard_limit);
        }
21714
        if (virMemoryLimitIsSet(def->mem.soft_limit)) {
21715
            virBufferAsprintf(buf, "<soft_limit unit='KiB'>"
21716 21717 21718
                              "%llu</soft_limit>\n", def->mem.soft_limit);
        }
        if (def->mem.min_guarantee) {
21719
            virBufferAsprintf(buf, "<min_guarantee unit='KiB'>"
21720 21721
                              "%llu</min_guarantee>\n", def->mem.min_guarantee);
        }
21722
        if (virMemoryLimitIsSet(def->mem.swap_hard_limit)) {
21723
            virBufferAsprintf(buf, "<swap_hard_limit unit='KiB'>"
21724 21725
                              "%llu</swap_hard_limit>\n", def->mem.swap_hard_limit);
        }
21726 21727
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</memtune>\n");
21728
    }
21729

21730
    if (def->mem.nhugepages || def->mem.nosharepages || def->mem.locked) {
21731 21732
        virBufferAddLit(buf, "<memoryBacking>\n");
        virBufferAdjustIndent(buf, 2);
21733 21734
        if (def->mem.nhugepages)
            virDomainHugepagesFormat(buf, def->mem.hugepages, def->mem.nhugepages);
21735
        if (def->mem.nosharepages)
21736
            virBufferAddLit(buf, "<nosharepages/>\n");
21737
        if (def->mem.locked)
21738 21739 21740
            virBufferAddLit(buf, "<locked/>\n");
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</memoryBacking>\n");
21741
    }
21742

21743
    virBufferAddLit(buf, "<vcpu");
21744 21745
    virBufferAsprintf(buf, " placement='%s'",
                      virDomainCpuPlacementModeTypeToString(def->placement_mode));
H
Hu Tao 已提交
21746 21747

    if (def->cpumask && !virBitmapIsAllSet(def->cpumask)) {
21748
        char *cpumask = NULL;
H
Hu Tao 已提交
21749
        if ((cpumask = virBitmapFormat(def->cpumask)) == NULL)
21750
            goto error;
21751
        virBufferAsprintf(buf, " cpuset='%s'", cpumask);
21752 21753
        VIR_FREE(cpumask);
    }
21754
    if (virDomainDefHasVcpusOffline(def))
21755
        virBufferAsprintf(buf, " current='%u'", virDomainDefGetVcpus(def));
21756
    virBufferAsprintf(buf, ">%u</vcpu>\n", virDomainDefGetVcpusMax(def));
21757

21758
    if (def->niothreadids > 0) {
21759 21760 21761 21762 21763 21764 21765 21766 21767 21768 21769 21770 21771 21772 21773 21774 21775 21776 21777 21778
        virBufferAsprintf(buf, "<iothreads>%u</iothreads>\n",
                          def->iothreads);
        /* Only print out iothreadids if we read at least one */
        for (i = 0; i < def->niothreadids; i++) {
            if (!def->iothreadids[i]->autofill)
                break;
        }
        if (i < def->niothreadids) {
            virBufferAddLit(buf, "<iothreadids>\n");
            virBufferAdjustIndent(buf, 2);
            for (i = 0; i < def->niothreadids; i++) {
                if (def->iothreadids[i]->autofill)
                    continue;
                virBufferAsprintf(buf, "<iothread id='%u'/>\n",
                                  def->iothreadids[i]->iothread_id);
            }
            virBufferAdjustIndent(buf, -2);
            virBufferAddLit(buf, "</iothreadids>\n");
        }
    }
21779

21780 21781
    if (virDomainCputuneDefFormat(buf, def) < 0)
        goto error;
21782

21783
    if (virDomainNumatuneFormatXML(buf, def->numa) < 0)
21784
        goto error;
21785

21786 21787 21788
    if (def->resource)
        virDomainResourceDefFormat(buf, def->resource);

21789
    if (def->sysinfo)
21790
        ignore_value(virSysinfoFormat(buf, def->sysinfo));
21791

21792
    if (def->os.bootloader) {
21793
        virBufferEscapeString(buf, "<bootloader>%s</bootloader>\n",
21794
                              def->os.bootloader);
21795
        virBufferEscapeString(buf,
21796
                              "<bootloader_args>%s</bootloader_args>\n",
21797
                              def->os.bootloaderArgs);
21798 21799
    }

21800 21801 21802
    virBufferAddLit(buf, "<os>\n");
    virBufferAdjustIndent(buf, 2);
    virBufferAddLit(buf, "<type");
21803
    if (def->os.arch)
21804
        virBufferAsprintf(buf, " arch='%s'", virArchToString(def->os.arch));
21805
    if (def->os.machine)
21806
        virBufferAsprintf(buf, " machine='%s'", def->os.machine);
21807 21808 21809 21810 21811 21812
    /*
     * 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 &&
21813 21814 21815
        def->os.type == VIR_DOMAIN_OSTYPE_XEN)
        virBufferAsprintf(buf, ">%s</type>\n",
                          virDomainOSTypeToString(VIR_DOMAIN_OSTYPE_LINUX));
21816
    else
21817 21818
        virBufferAsprintf(buf, ">%s</type>\n",
                          virDomainOSTypeToString(def->os.type));
21819

21820
    virBufferEscapeString(buf, "<init>%s</init>\n",
21821
                          def->os.init);
21822
    for (i = 0; def->os.initargv && def->os.initargv[i]; i++)
21823
        virBufferEscapeString(buf, "<initarg>%s</initarg>\n",
21824
                              def->os.initargv[i]);
21825 21826
    if (def->os.loader)
        virDomainLoaderDefFormat(buf, def->os.loader);
21827
    virBufferEscapeString(buf, "<kernel>%s</kernel>\n",
21828
                          def->os.kernel);
21829
    virBufferEscapeString(buf, "<initrd>%s</initrd>\n",
21830
                          def->os.initrd);
21831
    virBufferEscapeString(buf, "<cmdline>%s</cmdline>\n",
21832
                          def->os.cmdline);
21833
    virBufferEscapeString(buf, "<dtb>%s</dtb>\n",
21834
                          def->os.dtb);
21835
    virBufferEscapeString(buf, "<root>%s</root>\n",
21836
                          def->os.root);
21837 21838

    if (!def->os.bootloader) {
21839
        for (n = 0; n < def->os.nBootDevs; n++) {
21840 21841 21842
            const char *boottype =
                virDomainBootTypeToString(def->os.bootDevs[n]);
            if (!boottype) {
21843 21844 21845
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected boot device type %d"),
                               def->os.bootDevs[n]);
21846
                goto error;
21847
            }
21848
            virBufferAsprintf(buf, "<boot dev='%s'/>\n", boottype);
21849
        }
21850

21851 21852
        if (def->os.bootmenu) {
            virBufferAsprintf(buf, "<bootmenu enable='%s'",
J
Ján Tomko 已提交
21853
                              virTristateBoolTypeToString(def->os.bootmenu));
21854 21855 21856 21857
            if (def->os.bm_timeout_set)
                virBufferAsprintf(buf, " timeout='%u'", def->os.bm_timeout);
            virBufferAddLit(buf, "/>\n");
        }
M
Michal Privoznik 已提交
21858

21859
        if (def->os.bios.useserial || def->os.bios.rt_set) {
21860
            virBufferAddLit(buf, "<bios");
21861 21862
            if (def->os.bios.useserial)
                virBufferAsprintf(buf, " useserial='%s'",
J
Ján Tomko 已提交
21863
                                  virTristateBoolTypeToString(def->os.bios.useserial));
21864 21865 21866 21867
            if (def->os.bios.rt_set)
                virBufferAsprintf(buf, " rebootTimeout='%d'", def->os.bios.rt_delay);

            virBufferAddLit(buf, "/>\n");
M
Michal Privoznik 已提交
21868
        }
21869 21870
    }

21871 21872 21873 21874 21875
    if (def->os.smbios_mode) {
        const char *mode;

        mode = virDomainSmbiosModeTypeToString(def->os.smbios_mode);
        if (mode == NULL) {
21876 21877
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected smbios mode %d"), def->os.smbios_mode);
21878
            goto error;
21879
        }
21880
        virBufferAsprintf(buf, "<smbios mode='%s'/>\n", mode);
21881 21882
    }

21883 21884
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</os>\n");
21885

21886 21887

    if (def->idmap.uidmap) {
21888 21889
        virBufferAddLit(buf, "<idmap>\n");
        virBufferAdjustIndent(buf, 2);
21890 21891
        for (i = 0; i < def->idmap.nuidmap; i++) {
            virBufferAsprintf(buf,
21892
                              "<uid start='%u' target='%u' count='%u'/>\n",
21893 21894 21895 21896 21897 21898
                              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,
21899
                              "<gid start='%u' target='%u' count='%u'/>\n",
21900 21901 21902 21903
                              def->idmap.gidmap[i].start,
                              def->idmap.gidmap[i].target,
                              def->idmap.gidmap[i].count);
        }
21904 21905
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</idmap>\n");
21906 21907
    }

21908
    for (i = 0; i < VIR_DOMAIN_FEATURE_LAST; i++) {
J
Ján Tomko 已提交
21909
        if (def->features[i] != VIR_TRISTATE_SWITCH_ABSENT)
21910 21911
            break;
    }
21912

21913 21914
    if (i != VIR_DOMAIN_FEATURE_LAST ||
        virDomainDefHasCapabilitiesFeatures(def)) {
21915 21916
        virBufferAddLit(buf, "<features>\n");
        virBufferAdjustIndent(buf, 2);
21917

21918
        for (i = 0; i < VIR_DOMAIN_FEATURE_LAST; i++) {
21919 21920 21921 21922 21923 21924 21925
            const char *name = virDomainFeatureTypeToString(i);
            size_t j;

            if (!name) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected feature %zu"), i);
                goto error;
21926
            }
21927

21928
            switch ((virDomainFeature) i) {
21929 21930 21931 21932 21933
            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 已提交
21934 21935
                switch ((virTristateSwitch) def->features[i]) {
                case VIR_TRISTATE_SWITCH_ABSENT:
21936 21937
                    break;

J
Ján Tomko 已提交
21938
                case VIR_TRISTATE_SWITCH_ON:
21939
                   virBufferAsprintf(buf, "<%s/>\n", name);
21940 21941
                   break;

J
Ján Tomko 已提交
21942 21943
                case VIR_TRISTATE_SWITCH_LAST:
                case VIR_TRISTATE_SWITCH_OFF:
21944 21945 21946 21947 21948 21949 21950 21951
                   virReportError(VIR_ERR_INTERNAL_ERROR,
                                 _("Unexpected state of feature '%s'"), name);

                   goto error;
                   break;
                }

                break;
21952

21953
            case VIR_DOMAIN_FEATURE_PMU:
21954
            case VIR_DOMAIN_FEATURE_PVSPINLOCK:
21955
            case VIR_DOMAIN_FEATURE_VMPORT:
J
Ján Tomko 已提交
21956 21957 21958
                switch ((virTristateSwitch) def->features[i]) {
                case VIR_TRISTATE_SWITCH_LAST:
                case VIR_TRISTATE_SWITCH_ABSENT:
21959 21960
                    break;

J
Ján Tomko 已提交
21961
                case VIR_TRISTATE_SWITCH_ON:
21962
                   virBufferAsprintf(buf, "<%s state='on'/>\n", name);
21963 21964
                   break;

J
Ján Tomko 已提交
21965
                case VIR_TRISTATE_SWITCH_OFF:
21966
                   virBufferAsprintf(buf, "<%s state='off'/>\n", name);
21967 21968 21969 21970 21971
                   break;
                }

                break;

21972
            case VIR_DOMAIN_FEATURE_APIC:
J
Ján Tomko 已提交
21973
                if (def->features[i] == VIR_TRISTATE_SWITCH_ON) {
21974
                    virBufferAddLit(buf, "<apic");
21975 21976
                    if (def->apic_eoi) {
                        virBufferAsprintf(buf, " eoi='%s'",
J
Ján Tomko 已提交
21977
                                          virTristateSwitchTypeToString(def->apic_eoi));
21978
                    }
21979
                    virBufferAddLit(buf, "/>\n");
21980 21981
                }
                break;
21982

21983
            case VIR_DOMAIN_FEATURE_HYPERV:
J
Ján Tomko 已提交
21984
                if (def->features[i] != VIR_TRISTATE_SWITCH_ON)
21985
                    break;
21986

21987 21988
                virBufferAddLit(buf, "<hyperv>\n");
                virBufferAdjustIndent(buf, 2);
21989
                for (j = 0; j < VIR_DOMAIN_HYPERV_LAST; j++) {
21990
                    switch ((virDomainHyperv) j) {
21991 21992 21993
                    case VIR_DOMAIN_HYPERV_RELAXED:
                    case VIR_DOMAIN_HYPERV_VAPIC:
                        if (def->hyperv_features[j])
21994
                            virBufferAsprintf(buf, "<%s state='%s'/>\n",
21995
                                              virDomainHypervTypeToString(j),
J
Ján Tomko 已提交
21996
                                              virTristateSwitchTypeToString(
21997 21998 21999 22000 22001 22002 22003
                                                  def->hyperv_features[j]));
                        break;

                    case VIR_DOMAIN_HYPERV_SPINLOCKS:
                        if (def->hyperv_features[j] == 0)
                            break;

22004
                        virBufferAsprintf(buf, "<spinlocks state='%s'",
J
Ján Tomko 已提交
22005
                                          virTristateSwitchTypeToString(
22006
                                              def->hyperv_features[j]));
J
Ján Tomko 已提交
22007
                        if (def->hyperv_features[j] == VIR_TRISTATE_SWITCH_ON)
22008 22009 22010 22011 22012
                            virBufferAsprintf(buf, " retries='%d'",
                                              def->hyperv_spinlocks);
                        virBufferAddLit(buf, "/>\n");
                        break;

22013
                    /* coverity[dead_error_begin] */
22014 22015 22016
                    case VIR_DOMAIN_HYPERV_LAST:
                        break;
                    }
22017
                }
22018 22019
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</hyperv>\n");
22020 22021
                break;

22022 22023 22024 22025 22026 22027 22028 22029 22030 22031 22032 22033 22034 22035 22036 22037
            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;

22038
                    /* coverity[dead_error_begin] */
22039 22040 22041 22042 22043 22044 22045 22046
                    case VIR_DOMAIN_KVM_LAST:
                        break;
                    }
                }
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</kvm>\n");
                break;

22047 22048 22049 22050 22051 22052 22053 22054 22055
            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 已提交
22056
                    if (def->caps_features[j] != VIR_TRISTATE_SWITCH_ABSENT)
22057 22058
                        virBufferAsprintf(buf, "<%s state='%s'/>\n",
                                          virDomainCapsFeatureTypeToString(j),
J
Ján Tomko 已提交
22059
                                          virTristateSwitchTypeToString(
22060 22061 22062 22063 22064 22065
                                              def->caps_features[j]));
                }
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</capabilities>\n");
                break;

M
Michal Privoznik 已提交
22066 22067 22068 22069 22070 22071 22072 22073 22074 22075
            case VIR_DOMAIN_FEATURE_GIC:
                if (def->features[i] == VIR_TRISTATE_SWITCH_ON) {
                    virBufferAddLit(buf, "<gic");
                    if (def->gic_version)
                        virBufferAsprintf(buf, " version='%u'",
                                          def->gic_version);
                    virBufferAddLit(buf, "/>\n");
                }
                break;

22076
            /* coverity[dead_error_begin] */
22077 22078
            case VIR_DOMAIN_FEATURE_LAST:
                break;
22079 22080 22081
            }
        }

22082 22083
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</features>\n");
22084 22085
    }

22086
    if (virCPUDefFormatBufFull(buf, def->cpu, def->numa,
22087
                               !!(flags & VIR_DOMAIN_DEF_FORMAT_UPDATE_CPU)) < 0)
22088
        goto error;
22089

22090
    virBufferAsprintf(buf, "<clock offset='%s'",
22091
                      virDomainClockOffsetTypeToString(def->clock.offset));
22092
    switch (def->clock.offset) {
22093 22094 22095 22096 22097
    case VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME:
    case VIR_DOMAIN_CLOCK_OFFSET_UTC:
        if (def->clock.data.utc_reset)
            virBufferAddLit(buf, " adjustment='reset'");
        break;
22098
    case VIR_DOMAIN_CLOCK_OFFSET_VARIABLE:
22099 22100 22101
        virBufferAsprintf(buf, " adjustment='%lld' basis='%s'",
                          def->clock.data.variable.adjustment,
                          virDomainClockBasisTypeToString(def->clock.data.variable.basis));
22102
        if (flags & VIR_DOMAIN_DEF_FORMAT_CLOCK_ADJUST) {
22103 22104 22105 22106
            if (def->clock.data.variable.adjustment0)
                virBufferAsprintf(buf, " adjustment0='%lld'",
                                  def->clock.data.variable.adjustment0);
        }
22107 22108
        break;
    case VIR_DOMAIN_CLOCK_OFFSET_TIMEZONE:
22109
        virBufferEscapeString(buf, " timezone='%s'", def->clock.data.timezone);
22110 22111
        break;
    }
22112
    if (def->clock.ntimers == 0) {
22113
        virBufferAddLit(buf, "/>\n");
22114
    } else {
22115
        virBufferAddLit(buf, ">\n");
22116
        virBufferAdjustIndent(buf, 2);
22117
        for (n = 0; n < def->clock.ntimers; n++) {
22118
            if (virDomainTimerDefFormat(buf, def->clock.timers[n]) < 0)
22119
                goto error;
22120
        }
22121 22122
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</clock>\n");
22123
    }
22124

22125 22126 22127
    if (virDomainEventActionDefFormat(buf, def->onPoweroff,
                                      "on_poweroff",
                                      virDomainLifecycleTypeToString) < 0)
22128
        goto error;
22129 22130 22131
    if (virDomainEventActionDefFormat(buf, def->onReboot,
                                      "on_reboot",
                                      virDomainLifecycleTypeToString) < 0)
22132
        goto error;
22133 22134 22135
    if (virDomainEventActionDefFormat(buf, def->onCrash,
                                      "on_crash",
                                      virDomainLifecycleCrashTypeToString) < 0)
22136
        goto error;
22137 22138 22139 22140
    if (def->onLockFailure != VIR_DOMAIN_LOCK_FAILURE_DEFAULT &&
        virDomainEventActionDefFormat(buf, def->onLockFailure,
                                      "on_lockfailure",
                                      virDomainLockFailureTypeToString) < 0)
22141
        goto error;
22142

22143
    if (def->pm.s3 || def->pm.s4) {
22144 22145
        virBufferAddLit(buf, "<pm>\n");
        virBufferAdjustIndent(buf, 2);
22146
        if (def->pm.s3) {
22147
            virBufferAsprintf(buf, "<suspend-to-mem enabled='%s'/>\n",
J
Ján Tomko 已提交
22148
                              virTristateBoolTypeToString(def->pm.s3));
22149 22150
        }
        if (def->pm.s4) {
22151
            virBufferAsprintf(buf, "<suspend-to-disk enabled='%s'/>\n",
J
Ján Tomko 已提交
22152
                              virTristateBoolTypeToString(def->pm.s4));
22153
        }
22154 22155
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</pm>\n");
22156 22157
    }

22158 22159
    virBufferAddLit(buf, "<devices>\n");
    virBufferAdjustIndent(buf, 2);
22160

22161
    virBufferEscapeString(buf, "<emulator>%s</emulator>\n",
22162
                          def->emulator);
22163

22164
    for (n = 0; n < def->ndisks; n++)
22165
        if (virDomainDiskDefFormat(buf, def->disks[n], flags) < 0)
22166
            goto error;
22167

22168
    for (n = 0; n < def->ncontrollers; n++)
22169
        if (virDomainControllerDefFormat(buf, def->controllers[n], flags) < 0)
22170
            goto error;
22171

22172
    for (n = 0; n < def->nleases; n++)
22173
        if (virDomainLeaseDefFormat(buf, def->leases[n]) < 0)
22174
            goto error;
22175

22176
    for (n = 0; n < def->nfss; n++)
22177
        if (virDomainFSDefFormat(buf, def->fss[n], flags) < 0)
22178
            goto error;
22179

22180 22181
    if (caps)
        netprefix = caps->host.netprefix;
22182
    for (n = 0; n < def->nnets; n++)
22183
        if (virDomainNetDefFormat(buf, def->nets[n], netprefix, flags) < 0)
22184
            goto error;
22185

22186
    for (n = 0; n < def->nsmartcards; n++)
22187
        if (virDomainSmartcardDefFormat(buf, def->smartcards[n], flags) < 0)
22188
            goto error;
E
Eric Blake 已提交
22189

22190
    for (n = 0; n < def->nserials; n++)
22191
        if (virDomainChrDefFormat(buf, def->serials[n], flags) < 0)
22192
            goto error;
22193

22194
    for (n = 0; n < def->nparallels; n++)
22195
        if (virDomainChrDefFormat(buf, def->parallels[n], flags) < 0)
22196
            goto error;
22197

22198
    for (n = 0; n < def->nconsoles; n++) {
22199 22200 22201 22202
        virDomainChrDef console;
        /* Back compat, ignore the console element for hvm guests
         * if it is type == serial
         */
22203
        if (def->os.type == VIR_DOMAIN_OSTYPE_HVM &&
22204 22205
            (def->consoles[n]->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL ||
             def->consoles[n]->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_NONE) &&
22206 22207 22208
            (n < def->nserials)) {
            memcpy(&console, def->serials[n], sizeof(console));
            console.deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE;
G
Guannan Ren 已提交
22209
            console.targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL;
22210 22211 22212 22213
        } else {
            memcpy(&console, def->consoles[n], sizeof(console));
        }
        if (virDomainChrDefFormat(buf, &console, flags) < 0)
22214
            goto error;
22215
    }
22216 22217 22218 22219
    /* The back-compat console device stub is added when parsing the domain XML
     * and handled above, this is for formatting definitions created via other
     * means.
     */
22220
    if (def->os.type == VIR_DOMAIN_OSTYPE_HVM &&
22221 22222
        def->nconsoles == 0 &&
        def->nserials > 0) {
22223
        virDomainChrDef console;
22224
        memcpy(&console, def->serials[n], sizeof(console));
22225
        console.deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE;
22226
        console.targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL;
22227
        if (virDomainChrDefFormat(buf, &console, flags) < 0)
22228
            goto error;
22229 22230
    }

22231
    for (n = 0; n < def->nchannels; n++)
22232
        if (virDomainChrDefFormat(buf, def->channels[n], flags) < 0)
22233
            goto error;
22234

P
Pavel Hrdina 已提交
22235 22236
    for (n = 0; n < def->ninputs; n++) {
        if (virDomainInputDefFormat(buf, def->inputs[n], flags) < 0)
22237
            goto error;
P
Pavel Hrdina 已提交
22238
    }
22239

22240 22241 22242 22243 22244
    if (def->tpm) {
        if (virDomainTPMDefFormat(buf, def->tpm, flags) < 0)
            goto error;
    }

22245
    if (def->ngraphics > 0) {
22246
        for (n = 0; n < def->ngraphics; n++)
22247
            if (virDomainGraphicsDefFormat(buf, def->graphics[n], flags) < 0)
22248
                goto error;
22249 22250
    }

22251
    for (n = 0; n < def->nsounds; n++)
22252
        if (virDomainSoundDefFormat(buf, def->sounds[n], flags) < 0)
22253
            goto error;
22254

22255
    for (n = 0; n < def->nvideos; n++)
22256
        if (virDomainVideoDefFormat(buf, def->videos[n], flags) < 0)
22257
            goto error;
22258

22259
    for (n = 0; n < def->nhostdevs; n++) {
22260 22261 22262 22263
        /* 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 已提交
22264 22265
        if (def->hostdevs[n]->parent.type == VIR_DOMAIN_DEVICE_NONE &&
            virDomainHostdevDefFormat(buf, def->hostdevs[n], flags) < 0) {
22266
            goto error;
22267 22268
        }
    }
22269

22270
    for (n = 0; n < def->nredirdevs; n++)
22271
        if (virDomainRedirdevDefFormat(buf, def->redirdevs[n], flags) < 0)
22272
            goto error;
22273

22274 22275 22276
    if (def->redirfilter)
        virDomainRedirFilterDefFormat(buf, def->redirfilter);

22277
    for (n = 0; n < def->nhubs; n++)
22278
        if (virDomainHubDefFormat(buf, def->hubs[n], flags) < 0)
22279
            goto error;
M
Marc-André Lureau 已提交
22280

R
Richard Jones 已提交
22281
    if (def->watchdog)
22282
        virDomainWatchdogDefFormat(buf, def->watchdog, flags);
R
Richard Jones 已提交
22283

22284
    if (def->memballoon)
22285
        virDomainMemballoonDefFormat(buf, def->memballoon, flags);
22286

22287 22288 22289 22290
    for (n = 0; n < def->nrngs; n++) {
        if (virDomainRNGDefFormat(buf, def->rngs[n], flags))
            goto error;
    }
22291

L
Li Zhang 已提交
22292 22293 22294
    if (def->nvram)
        virDomainNVRAMDefFormat(buf, def->nvram, flags);

D
Dmitry Andreev 已提交
22295 22296 22297
    for (n = 0; n < def->npanics; n++)
        if (virDomainPanicDefFormat(buf, def->panics[n]) < 0)
            goto error;
H
Hu Tao 已提交
22298

22299 22300 22301 22302
    for (n = 0; n < def->nshmems; n++)
        if (virDomainShmemDefFormat(buf, def->shmems[n], flags) < 0)
            goto error;

22303 22304 22305 22306
    for (n = 0; n < def->nmems; n++)
        if (virDomainMemoryDefFormat(buf, def->mems[n], flags) < 0)
            goto error;

22307 22308
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</devices>\n");
22309

22310
    for (n = 0; n < def->nseclabels; n++)
22311
        virSecurityLabelDefFormat(buf, def->seclabels[n]);
22312

22313
    if (def->namespaceData && def->ns.format) {
22314
        if ((def->ns.format)(buf, def->namespaceData) < 0)
22315
            goto error;
22316 22317
    }

22318 22319 22320
    if (def->keywrap)
        virDomainKeyWrapDefFormat(buf, def->keywrap);

22321
    virBufferAdjustIndent(buf, -2);
22322
    virBufferAddLit(buf, "</domain>\n");
22323

22324 22325
    if (virBufferCheckError(buf) < 0)
        goto error;
22326

22327
    return 0;
22328

22329
 error:
22330
    virBufferFreeAndReset(buf);
22331
    virBufferFreeAndReset(&childrenBuf);
22332
    return -1;
22333 22334
}

22335 22336 22337 22338 22339 22340 22341 22342 22343 22344 22345 22346 22347 22348 22349 22350 22351
unsigned int virDomainDefFormatConvertXMLFlags(unsigned int flags)
{
    unsigned int formatFlags = 0;

    if (flags & VIR_DOMAIN_XML_SECURE)
        formatFlags |= VIR_DOMAIN_DEF_FORMAT_SECURE;
    if (flags & VIR_DOMAIN_XML_INACTIVE)
        formatFlags |= VIR_DOMAIN_DEF_FORMAT_INACTIVE;
    if (flags & VIR_DOMAIN_XML_UPDATE_CPU)
        formatFlags |= VIR_DOMAIN_DEF_FORMAT_UPDATE_CPU;
    if (flags & VIR_DOMAIN_XML_MIGRATABLE)
        formatFlags |= VIR_DOMAIN_DEF_FORMAT_MIGRATABLE;

    return formatFlags;
}


22352
char *
22353
virDomainDefFormat(virDomainDefPtr def, virCapsPtr caps, unsigned int flags)
22354
{
22355 22356
    virBuffer buf = VIR_BUFFER_INITIALIZER;

22357
    virCheckFlags(VIR_DOMAIN_DEF_FORMAT_COMMON_FLAGS, NULL);
22358
    if (virDomainDefFormatInternal(def, caps, flags, &buf) < 0)
22359 22360 22361
        return NULL;

    return virBufferContentAndReset(&buf);
22362 22363
}

22364

22365
char *
22366
virDomainObjFormat(virDomainXMLOptionPtr xmlopt,
22367
                   virDomainObjPtr obj,
22368
                   virCapsPtr caps,
22369
                   unsigned int flags)
22370 22371
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
J
Jiri Denemark 已提交
22372 22373
    int state;
    int reason;
22374
    size_t i;
22375

J
Jiri Denemark 已提交
22376
    state = virDomainObjGetState(obj, &reason);
22377
    virBufferAsprintf(&buf, "<domstatus state='%s' reason='%s' pid='%lld'>\n",
J
Jiri Denemark 已提交
22378 22379
                      virDomainStateTypeToString(state),
                      virDomainStateReasonToString(state, reason),
22380
                      (long long)obj->pid);
22381
    virBufferAdjustIndent(&buf, 2);
22382

22383
    for (i = 0; i < VIR_DOMAIN_TAINT_LAST; i++) {
22384
        if (obj->taint & (1 << i))
22385
            virBufferAsprintf(&buf, "<taint flag='%s'/>\n",
22386 22387 22388
                              virDomainTaintTypeToString(i));
    }

22389
    if (xmlopt->privateData.format &&
22390
        xmlopt->privateData.format(&buf, obj) < 0)
22391
        goto error;
22392

22393
    if (virDomainDefFormatInternal(obj->def, caps, flags, &buf) < 0)
22394 22395
        goto error;

22396
    virBufferAdjustIndent(&buf, -2);
22397 22398
    virBufferAddLit(&buf, "</domstatus>\n");

22399 22400
    if (virBufferCheckError(&buf) < 0)
        goto error;
22401 22402 22403

    return virBufferContentAndReset(&buf);

22404
 error:
22405
    virBufferFreeAndReset(&buf);
22406 22407 22408
    return NULL;
}

22409 22410 22411
static bool
virDomainDefHasUSB(virDomainDefPtr def)
{
22412
    size_t i;
22413 22414 22415 22416 22417 22418 22419 22420 22421 22422 22423 22424 22425 22426 22427 22428 22429 22430 22431 22432 22433 22434 22435 22436 22437 22438 22439 22440 22441 22442 22443

    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;
}

22444 22445 22446 22447 22448 22449 22450 22451 22452 22453 22454 22455 22456 22457 22458 22459 22460
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;
}

22461 22462 22463 22464 22465 22466 22467 22468 22469 22470 22471 22472 22473 22474 22475 22476 22477 22478 22479 22480 22481 22482 22483 22484 22485 22486 22487 22488

/**
 * virDomainDefGetDiskByWWN:
 * @def: domain definition
 * @wwn: wwn of a disk to find
 *
 * Returns a disk definition pointer corresponding to the given WWN identifier
 * or NULL either if @wwn was NULL or if disk with given WWN is not present in
 * the domain definition.
 */
static virDomainDiskDefPtr
virDomainDefGetDiskByWWN(virDomainDefPtr def,
                         const char *wwn)
{
    size_t i;

    if (!wwn)
        return NULL;

    for (i = 0; i < def->ndisks; i++) {
        if (STREQ_NULLABLE(def->disks[i]->wwn, wwn))
            return def->disks[i];
    }

    return NULL;
}


22489 22490
int
virDomainDefCompatibleDevice(virDomainDefPtr def,
22491 22492
                             virDomainDeviceDefPtr dev,
                             virDomainDeviceAction action)
22493
{
22494 22495
    virDomainDeviceInfoPtr info = virDomainDeviceGetInfo(dev);

22496 22497 22498
    if (action != VIR_DOMAIN_DEVICE_ACTION_ATTACH)
        return 0;

22499
    if (!virDomainDefHasUSB(def) &&
22500
        def->os.type != VIR_DOMAIN_OSTYPE_EXE &&
22501 22502 22503 22504 22505 22506 22507
        virDomainDeviceIsUSB(dev)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Device configuration is not compatible: "
                         "Domain has no USB bus support"));
        return -1;
    }

22508 22509 22510 22511 22512 22513 22514 22515 22516 22517 22518 22519 22520
    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;
    }

22521 22522 22523 22524 22525 22526 22527 22528 22529 22530 22531
    if (dev->type == VIR_DOMAIN_DEVICE_MEMORY) {
        unsigned long long sz = dev->data.memory->size;

        if ((virDomainDefGetMemoryActual(def) + sz) > def->mem.max_memory) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Attaching memory device with size '%llu' would "
                             "exceed domain's maxMemory config"), sz);
            return -1;
        }
    }

22532 22533 22534 22535 22536 22537 22538 22539 22540
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        if (!!virDomainDefGetDiskByWWN(def, dev->data.disk->wwn)) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Domain already has a disk with wwn '%s'"),
                           dev->data.disk->wwn);
            return -1;
        }
    }

22541 22542 22543
    return 0;
}

22544 22545 22546 22547
int
virDomainSaveXML(const char *configDir,
                 virDomainDefPtr def,
                 const char *xml)
22548
{
J
Ján Tomko 已提交
22549
    char uuidstr[VIR_UUID_STRING_BUFLEN];
22550
    char *configFile = NULL;
22551
    int ret = -1;
22552

22553 22554 22555
    if (!configDir)
        return 0;

22556
    if ((configFile = virDomainConfigFile(configDir, def->name)) == NULL)
22557 22558
        goto cleanup;

22559
    if (virFileMakePath(configDir) < 0) {
22560
        virReportSystemError(errno,
22561 22562
                             _("cannot create config directory '%s'"),
                             configDir);
22563 22564 22565
        goto cleanup;
    }

J
Ján Tomko 已提交
22566 22567 22568 22569
    virUUIDFormat(def->uuid, uuidstr);
    ret = virXMLSaveFile(configFile,
                         virXMLPickShellSafeComment(def->name, uuidstr), "edit",
                         xml);
22570

22571
 cleanup:
R
Ryota Ozaki 已提交
22572
    VIR_FREE(configFile);
22573 22574 22575
    return ret;
}

22576 22577
int
virDomainSaveConfig(const char *configDir,
22578
                    virCapsPtr caps,
22579
                    virDomainDefPtr def)
22580 22581 22582
{
    int ret = -1;
    char *xml;
22583

22584
    if (!(xml = virDomainDefFormat(def, caps, VIR_DOMAIN_DEF_FORMAT_SECURE)))
22585 22586
        goto cleanup;

22587
    if (virDomainSaveXML(configDir, def, xml))
22588 22589 22590
        goto cleanup;

    ret = 0;
22591
 cleanup:
22592
    VIR_FREE(xml);
22593 22594 22595
    return ret;
}

22596
int
22597
virDomainSaveStatus(virDomainXMLOptionPtr xmlopt,
22598
                    const char *statusDir,
22599 22600
                    virDomainObjPtr obj,
                    virCapsPtr caps)
22601
{
22602 22603 22604 22605 22606
    unsigned int flags = (VIR_DOMAIN_DEF_FORMAT_SECURE |
                          VIR_DOMAIN_DEF_FORMAT_STATUS |
                          VIR_DOMAIN_DEF_FORMAT_ACTUAL_NET |
                          VIR_DOMAIN_DEF_FORMAT_PCI_ORIG_STATES |
                          VIR_DOMAIN_DEF_FORMAT_CLOCK_ADJUST);
22607

22608 22609 22610
    int ret = -1;
    char *xml;

22611
    if (!(xml = virDomainObjFormat(xmlopt, obj, caps, flags)))
22612 22613
        goto cleanup;

22614
    if (virDomainSaveXML(statusDir, obj->def, xml))
22615 22616 22617
        goto cleanup;

    ret = 0;
22618
 cleanup:
22619 22620 22621 22622
    VIR_FREE(xml);
    return ret;
}

22623

22624 22625 22626 22627
int
virDomainDeleteConfig(const char *configDir,
                      const char *autostartDir,
                      virDomainObjPtr dom)
22628
{
22629 22630 22631
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

22632
    if ((configFile = virDomainConfigFile(configDir, dom->def->name)) == NULL)
22633
        goto cleanup;
22634 22635
    if ((autostartLink = virDomainConfigFile(autostartDir,
                                             dom->def->name)) == NULL)
22636
        goto cleanup;
22637 22638

    /* Not fatal if this doesn't work */
22639
    unlink(autostartLink);
22640
    dom->autostart = 0;
22641

22642 22643
    if (unlink(configFile) < 0 &&
        errno != ENOENT) {
22644
        virReportSystemError(errno,
22645 22646
                             _("cannot remove config %s"),
                             configFile);
22647
        goto cleanup;
22648 22649
    }

22650 22651
    ret = 0;

22652
 cleanup:
22653 22654 22655
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
    return ret;
22656
}
22657

22658 22659 22660
char
*virDomainConfigFile(const char *dir,
                     const char *name)
22661
{
22662
    char *ret;
22663

22664
    ignore_value(virAsprintf(&ret, "%s/%s.xml", dir, name));
22665 22666 22667
    return ret;
}

22668 22669
/* 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 已提交
22670
 *                                               hdd => (1,1), vdaa => (0,26))
22671 22672 22673 22674 22675
 * @param disk The disk device
 * @param busIdx parsed bus number
 * @param devIdx parsed device number
 * @return 0 on success, -1 on failure
 */
22676
int
22677
virDiskNameToBusDeviceIndex(virDomainDiskDefPtr disk,
22678
                            int *busIdx,
22679 22680
                            int *devIdx)
{
22681 22682

    int idx = virDiskNameToIndex(disk->dst);
22683
    if (idx < 0)
22684 22685 22686 22687 22688 22689 22690 22691 22692 22693 22694 22695 22696 22697 22698
        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:
22699
        case VIR_DOMAIN_DISK_BUS_SD:
22700 22701 22702 22703 22704 22705 22706 22707
        default:
            *busIdx = 0;
            *devIdx = idx;
            break;
    }

    return 0;
}
22708

22709 22710 22711 22712 22713 22714 22715 22716 22717 22718 22719 22720 22721 22722 22723 22724
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;
}

22725
virDomainFSDefPtr
22726
virDomainGetFilesystemForTarget(virDomainDefPtr def,
22727
                                const char *target)
22728
{
22729
    size_t i;
22730

22731
    for (i = 0; i < def->nfss; i++) {
22732
        if (STREQ(def->fss[i]->dst, target))
22733 22734 22735 22736 22737 22738
            return def->fss[i];
    }

    return NULL;
}

22739

22740 22741 22742 22743 22744
int
virDomainChrDefForeach(virDomainDefPtr def,
                       bool abortOnError,
                       virDomainChrDefIterator iter,
                       void *opaque)
22745
{
22746
    size_t i;
22747 22748
    int rc = 0;

22749
    for (i = 0; i < def->nserials; i++) {
22750 22751 22752 22753 22754 22755 22756 22757 22758
        if ((iter)(def,
                   def->serials[i],
                   opaque) < 0)
            rc = -1;

        if (abortOnError && rc != 0)
            goto done;
    }

22759
    for (i = 0; i < def->nparallels; i++) {
22760 22761 22762 22763 22764 22765 22766 22767 22768
        if ((iter)(def,
                   def->parallels[i],
                   opaque) < 0)
            rc = -1;

        if (abortOnError && rc != 0)
            goto done;
    }

22769
    for (i = 0; i < def->nchannels; i++) {
22770 22771 22772 22773 22774 22775 22776 22777
        if ((iter)(def,
                   def->channels[i],
                   opaque) < 0)
            rc = -1;

        if (abortOnError && rc != 0)
            goto done;
    }
22778
    for (i = 0; i < def->nconsoles; i++) {
22779
        if ((iter)(def,
22780
                   def->consoles[i],
22781 22782 22783 22784 22785 22786 22787
                   opaque) < 0)
            rc = -1;

        if (abortOnError && rc != 0)
            goto done;
    }

22788
 done:
22789 22790 22791 22792
    return rc;
}


22793 22794 22795 22796 22797
int
virDomainSmartcardDefForeach(virDomainDefPtr def,
                             bool abortOnError,
                             virDomainSmartcardDefIterator iter,
                             void *opaque)
E
Eric Blake 已提交
22798
{
22799
    size_t i;
E
Eric Blake 已提交
22800 22801
    int rc = 0;

22802
    for (i = 0; i < def->nsmartcards; i++) {
E
Eric Blake 已提交
22803 22804 22805 22806 22807 22808 22809 22810 22811
        if ((iter)(def,
                   def->smartcards[i],
                   opaque) < 0)
            rc = -1;

        if (abortOnError && rc != 0)
            goto done;
    }

22812
 done:
E
Eric Blake 已提交
22813 22814 22815 22816
    return rc;
}


22817
/* Call iter(disk, name, depth, opaque) for each element of disk and
22818
 * its backing chain in the pre-populated disk->src.backingStore.
22819 22820 22821
 * ignoreOpenFailure determines whether to warn about a chain that
 * mentions a backing file without also having metadata on that
 * file.  */
22822 22823 22824 22825 22826
int
virDomainDiskDefForeachPath(virDomainDiskDefPtr disk,
                            bool ignoreOpenFailure,
                            virDomainDiskDefPathIterator iter,
                            void *opaque)
22827 22828 22829
{
    int ret = -1;
    size_t depth = 0;
22830
    virStorageSourcePtr tmp;
22831
    char *brokenRaw = NULL;
22832

22833
    if (!ignoreOpenFailure) {
22834
        if (virStorageFileChainGetBroken(disk->src, &brokenRaw) < 0)
22835
            goto cleanup;
22836

22837
        if (brokenRaw) {
22838
            virReportError(VIR_ERR_INTERNAL_ERROR,
22839
                           _("unable to visit backing chain file %s"),
22840
                           brokenRaw);
22841 22842
            goto cleanup;
        }
22843 22844
    }

22845
    for (tmp = disk->src; tmp; tmp = tmp->backingStore) {
22846 22847 22848 22849 22850 22851 22852 22853 22854 22855
        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++;
22856
    }
22857 22858 22859

    ret = 0;

22860
 cleanup:
22861
    VIR_FREE(brokenRaw);
22862 22863
    return ret;
}
22864 22865


22866 22867 22868 22869
/* 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).  */
22870
virDomainDefPtr
22871 22872
virDomainDefCopy(virDomainDefPtr src,
                 virCapsPtr caps,
22873
                 virDomainXMLOptionPtr xmlopt,
22874
                 bool migratable)
22875 22876
{
    char *xml;
22877
    virDomainDefPtr ret;
22878 22879
    unsigned int format_flags = VIR_DOMAIN_DEF_FORMAT_SECURE;
    unsigned int parse_flags = VIR_DOMAIN_DEF_PARSE_INACTIVE;
22880

22881
    if (migratable)
22882
        format_flags |= VIR_DOMAIN_DEF_FORMAT_INACTIVE | VIR_DOMAIN_DEF_FORMAT_MIGRATABLE;
22883

22884
    /* Easiest to clone via a round-trip through XML.  */
22885
    if (!(xml = virDomainDefFormat(src, caps, format_flags)))
22886 22887
        return NULL;

22888
    ret = virDomainDefParseString(xml, caps, xmlopt, parse_flags);
22889 22890 22891 22892

    VIR_FREE(xml);
    return ret;
}
J
Jiri Denemark 已提交
22893

22894
virDomainDefPtr
22895 22896 22897
virDomainObjCopyPersistentDef(virDomainObjPtr dom,
                              virCapsPtr caps,
                              virDomainXMLOptionPtr xmlopt)
22898 22899 22900
{
    virDomainDefPtr cur;

22901
    cur = virDomainObjGetPersistentDef(caps, xmlopt, dom);
22902
    return virDomainDefCopy(cur, caps, xmlopt, false);
22903 22904
}

J
Jiri Denemark 已提交
22905 22906 22907 22908 22909 22910 22911 22912 22913 22914 22915 22916 22917 22918 22919 22920 22921

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 已提交
22922 22923 22924 22925 22926 22927 22928 22929 22930 22931 22932 22933 22934 22935 22936 22937 22938 22939 22940 22941 22942 22943 22944 22945 22946 22947
    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 已提交
22948 22949 22950 22951 22952 22953 22954 22955 22956 22957 22958 22959 22960 22961 22962 22963 22964 22965 22966 22967 22968 22969 22970 22971 22972 22973 22974 22975 22976 22977 22978 22979 22980
    }

    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);
22981 22982 22983 22984
    case VIR_DOMAIN_PMSUSPENDED:
        return virDomainPMSuspendedReasonTypeToString(reason);
    case VIR_DOMAIN_LAST:
        break;
J
Jiri Denemark 已提交
22985
    }
22986 22987
    VIR_WARN("Unexpected domain state: %d", state);
    return NULL;
J
Jiri Denemark 已提交
22988 22989 22990 22991 22992 22993 22994 22995 22996 22997 22998 22999 23000 23001 23002 23003 23004 23005 23006 23007 23008
}


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);
23009 23010 23011 23012
    case VIR_DOMAIN_PMSUSPENDED:
        return virDomainPMSuspendedReasonTypeFromString(reason);
    case VIR_DOMAIN_LAST:
        break;
J
Jiri Denemark 已提交
23013
    }
23014 23015
    VIR_WARN("Unexpected domain state: %d", state);
    return -1;
J
Jiri Denemark 已提交
23016
}
23017 23018 23019 23020 23021 23022 23023 23024 23025 23026 23027 23028 23029 23030 23031 23032 23033 23034


/* 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;
}

23035
const char *
23036 23037 23038 23039
virDomainNetGetActualBridgeName(virDomainNetDefPtr iface)
{
    if (iface->type == VIR_DOMAIN_NET_TYPE_BRIDGE)
        return iface->data.bridge.brname;
23040 23041
    if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
        iface->data.network.actual &&
23042 23043
        (iface->data.network.actual->type == VIR_DOMAIN_NET_TYPE_BRIDGE ||
         iface->data.network.actual->type == VIR_DOMAIN_NET_TYPE_NETWORK))
23044 23045
        return iface->data.network.actual->data.bridge.brname;
    return NULL;
23046 23047
}

23048 23049 23050 23051 23052 23053 23054 23055 23056 23057 23058
int
virDomainNetGetActualBridgeMACTableManager(virDomainNetDefPtr iface)
{
    if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
        iface->data.network.actual &&
        (iface->data.network.actual->type == VIR_DOMAIN_NET_TYPE_BRIDGE ||
         iface->data.network.actual->type == VIR_DOMAIN_NET_TYPE_NETWORK))
        return iface->data.network.actual->data.bridge.macTableManager;
    return 0;
}

23059
const char *
23060 23061 23062 23063
virDomainNetGetActualDirectDev(virDomainNetDefPtr iface)
{
    if (iface->type == VIR_DOMAIN_NET_TYPE_DIRECT)
        return iface->data.direct.linkdev;
23064 23065
    if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
        iface->data.network.actual &&
23066
        iface->data.network.actual->type == VIR_DOMAIN_NET_TYPE_DIRECT)
23067 23068
        return iface->data.network.actual->data.direct.linkdev;
    return NULL;
23069 23070 23071 23072 23073 23074 23075
}

int
virDomainNetGetActualDirectMode(virDomainNetDefPtr iface)
{
    if (iface->type == VIR_DOMAIN_NET_TYPE_DIRECT)
        return iface->data.direct.mode;
23076 23077
    if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
        iface->data.network.actual &&
23078
        iface->data.network.actual->type == VIR_DOMAIN_NET_TYPE_DIRECT)
23079 23080
        return iface->data.network.actual->data.direct.mode;
    return 0;
23081 23082
}

23083 23084 23085 23086 23087
virDomainHostdevDefPtr
virDomainNetGetActualHostdev(virDomainNetDefPtr iface)
{
    if (iface->type == VIR_DOMAIN_NET_TYPE_HOSTDEV)
        return &iface->data.hostdev.def;
E
Eric Blake 已提交
23088
    if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
23089
        iface->data.network.actual &&
23090
        iface->data.network.actual->type == VIR_DOMAIN_NET_TYPE_HOSTDEV)
23091 23092 23093 23094
        return &iface->data.network.actual->data.hostdev.def;
    return NULL;
}

23095
virNetDevVPortProfilePtr
23096
virDomainNetGetActualVirtPortProfile(virDomainNetDefPtr iface)
23097
{
A
Ansis Atteka 已提交
23098 23099 23100
    switch (iface->type) {
    case VIR_DOMAIN_NET_TYPE_DIRECT:
    case VIR_DOMAIN_NET_TYPE_BRIDGE:
23101
    case VIR_DOMAIN_NET_TYPE_HOSTDEV:
23102
        return iface->virtPortProfile;
A
Ansis Atteka 已提交
23103 23104 23105 23106 23107 23108
    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:
23109
        case VIR_DOMAIN_NET_TYPE_HOSTDEV:
23110
            return iface->data.network.actual->virtPortProfile;
A
Ansis Atteka 已提交
23111 23112 23113 23114
        default:
            return NULL;
        }
    default:
23115
        return NULL;
A
Ansis Atteka 已提交
23116
    }
23117
}
23118

23119
virNetDevBandwidthPtr
23120 23121
virDomainNetGetActualBandwidth(virDomainNetDefPtr iface)
{
23122 23123 23124
    /* if there is an ActualNetDef, *always* return
     * its bandwidth rather than the NetDef's bandwidth.
     */
E
Eric Blake 已提交
23125
    if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
23126
        iface->data.network.actual)
23127 23128 23129
        return iface->data.network.actual->bandwidth;
    return iface->bandwidth;
}
23130

23131 23132 23133
virNetDevVlanPtr
virDomainNetGetActualVlan(virDomainNetDefPtr iface)
{
23134 23135 23136 23137 23138
    virNetDevVlanPtr vlan = &iface->vlan;

    /* if there is an ActualNetDef, *always* return
     * its vlan rather than the NetDef's vlan.
     */
23139
    if (iface->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
23140 23141 23142 23143 23144 23145
        iface->data.network.actual)
        vlan = &iface->data.network.actual->vlan;

    if (vlan->nTags > 0)
        return vlan;
    return NULL;
23146
}
23147

23148 23149 23150 23151 23152 23153 23154 23155 23156 23157 23158 23159

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;
}


23160
/* Return listens[i] from the appropriate union for the graphics
23161
 * type, or NULL if this is an unsuitable type, or the index is out of
23162
 * bounds. If force0 is TRUE, i == 0, and there is no listen array,
23163 23164
 * allocate one with a single item. */
static virDomainGraphicsListenDefPtr
23165
virDomainGraphicsGetListen(virDomainGraphicsDefPtr def, size_t i, bool force0)
23166
{
E
Eric Blake 已提交
23167 23168 23169
    if (def->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC ||
        def->type == VIR_DOMAIN_GRAPHICS_TYPE_RDP ||
        def->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE) {
23170

23171
        if (!def->listens && (i == 0) && force0) {
23172
            if (VIR_ALLOC(def->listens) >= 0)
23173 23174 23175
                def->nListens = 1;
        }

23176
        if (!def->listens || (def->nListens <= i))
23177 23178
            return NULL;

23179
        return &def->listens[i];
23180 23181 23182 23183 23184 23185 23186 23187 23188 23189 23190 23191 23192 23193 23194 23195 23196 23197 23198 23199 23200
    }

    /* 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
23201
virDomainGraphicsListenGetType(virDomainGraphicsDefPtr def, size_t i)
23202 23203
{
    virDomainGraphicsListenDefPtr listenInfo
23204
        = virDomainGraphicsGetListen(def, i, false);
23205 23206 23207 23208 23209 23210 23211 23212 23213 23214 23215

    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
23216
virDomainGraphicsListenSetType(virDomainGraphicsDefPtr def, size_t i, int val)
23217 23218
{
    virDomainGraphicsListenDefPtr listenInfo
23219
        = virDomainGraphicsGetListen(def, i, true);
23220 23221 23222 23223 23224 23225 23226 23227 23228

    if (!listenInfo)
        return -1;
    listenInfo->type = val;
    return 0;
}


const char *
23229
virDomainGraphicsListenGetAddress(virDomainGraphicsDefPtr def, size_t i)
23230 23231
{
    virDomainGraphicsListenDefPtr listenInfo
23232
        = virDomainGraphicsGetListen(def, i, false);
23233

23234
    /* even a network can have a listen address */
23235
    if (!listenInfo ||
23236 23237
        !(listenInfo->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS ||
          listenInfo->type == VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK))
23238 23239 23240 23241 23242 23243
        return NULL;
    return listenInfo->address;
}


/* Make a copy of up to len characters of address, and store it in
23244
 * listens[i].address. If setType is true, set the listen's type
23245 23246 23247
 * to 'address', otherwise leave type alone. */
int
virDomainGraphicsListenSetAddress(virDomainGraphicsDefPtr def,
23248
                                  size_t i, const char *address,
23249 23250 23251
                                  int len, bool setType)
{
    virDomainGraphicsListenDefPtr listenInfo
23252
        = virDomainGraphicsGetListen(def, i, true);
23253 23254 23255 23256 23257 23258 23259 23260

    if (!listenInfo)
        return -1;

    if (setType)
        listenInfo->type = VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS;

    if (!address) {
23261
        VIR_FREE(listenInfo->address);
23262 23263 23264
        return 0;
    }

23265
    if (VIR_STRNDUP(listenInfo->address, address, len) < 0)
23266 23267 23268 23269 23270 23271
        return -1;
    return 0;
}


const char *
23272
virDomainGraphicsListenGetNetwork(virDomainGraphicsDefPtr def, size_t i)
23273 23274
{
    virDomainGraphicsListenDefPtr listenInfo
23275
        = virDomainGraphicsGetListen(def, i, false);
23276 23277 23278 23279 23280 23281 23282 23283 23284

    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
23285
 * listens[i].network */
23286 23287
int
virDomainGraphicsListenSetNetwork(virDomainGraphicsDefPtr def,
23288
                                  size_t i, const char *network, int len)
23289 23290
{
    virDomainGraphicsListenDefPtr listenInfo
23291
        = virDomainGraphicsGetListen(def, i, true);
23292 23293 23294 23295 23296 23297 23298

    if (!listenInfo)
        return -1;

    listenInfo->type = VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK;

    if (!network) {
23299
        VIR_FREE(listenInfo->network);
23300 23301 23302
        return 0;
    }

23303
    if (VIR_STRNDUP(listenInfo->network, network, len) < 0)
23304 23305 23306
        return -1;
    return 0;
}
23307 23308 23309 23310 23311 23312 23313 23314 23315 23316 23317 23318 23319 23320 23321

/**
 * 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;
23322
    virMacAddr mac;
23323
    size_t i;
23324

23325
    if (virMacAddrParse(device, &mac) == 0)
23326 23327 23328 23329
        isMac = true;

    if (isMac) {
        for (i = 0; i < def->nnets; i++) {
23330
            if (virMacAddrCmp(&mac, &def->nets[i]->mac) == 0) {
23331 23332 23333 23334 23335 23336 23337 23338 23339 23340 23341 23342 23343 23344 23345
                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;
}
23346 23347 23348 23349 23350 23351 23352 23353

/**
 * 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
23354
 * DeviceDef that are valid when just the flag VIR_DOMAIN_DEF_PARSE_INACTIVE is
23355 23356 23357 23358 23359 23360 23361
 * 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
23362
virDomainDeviceDefCopy(virDomainDeviceDefPtr src,
23363
                       const virDomainDef *def,
23364 23365
                       virCapsPtr caps,
                       virDomainXMLOptionPtr xmlopt)
23366 23367 23368
{
    virDomainDeviceDefPtr ret = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
23369
    int flags = VIR_DOMAIN_DEF_FORMAT_INACTIVE | VIR_DOMAIN_DEF_FORMAT_SECURE;
23370 23371
    char *xmlStr = NULL;
    int rc = -1;
23372
    char *netprefix;
23373

23374
    switch ((virDomainDeviceType) src->type) {
23375 23376 23377 23378 23379 23380 23381 23382 23383 23384
    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:
23385 23386
        netprefix = caps->host.netprefix;
        rc = virDomainNetDefFormat(&buf, src->data.net, netprefix, flags);
23387 23388 23389 23390 23391 23392 23393 23394 23395 23396 23397 23398 23399 23400 23401 23402 23403 23404 23405 23406 23407 23408 23409 23410 23411 23412 23413 23414
        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;
23415 23416 23417
    case VIR_DOMAIN_DEVICE_RNG:
        rc = virDomainRNGDefFormat(&buf, src->data.rng, flags);
        break;
23418 23419 23420
    case VIR_DOMAIN_DEVICE_CHR:
        rc = virDomainChrDefFormat(&buf, src->data.chr, flags);
        break;
23421 23422 23423
    case VIR_DOMAIN_DEVICE_TPM:
        rc = virDomainTPMDefFormat(&buf, src->data.tpm, flags);
        break;
23424 23425 23426
    case VIR_DOMAIN_DEVICE_PANIC:
        rc = virDomainPanicDefFormat(&buf, src->data.panic);
        break;
23427 23428 23429
    case VIR_DOMAIN_DEVICE_MEMORY:
        rc = virDomainMemoryDefFormat(&buf, src->data.memory, flags);
        break;
23430 23431 23432
    case VIR_DOMAIN_DEVICE_NONE:
    case VIR_DOMAIN_DEVICE_SMARTCARD:
    case VIR_DOMAIN_DEVICE_MEMBALLOON:
L
Li Zhang 已提交
23433
    case VIR_DOMAIN_DEVICE_NVRAM:
23434
    case VIR_DOMAIN_DEVICE_SHMEM:
23435
    case VIR_DOMAIN_DEVICE_LAST:
23436 23437 23438 23439
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Copying definition of '%d' type "
                         "is not implemented yet."),
                       src->type);
23440 23441 23442 23443 23444 23445 23446
        goto cleanup;
    }

    if (rc < 0)
        goto cleanup;

    xmlStr = virBufferContentAndReset(&buf);
23447 23448
    ret = virDomainDeviceDefParse(xmlStr, def, caps, xmlopt,
                                  VIR_DOMAIN_DEF_PARSE_INACTIVE);
23449

23450
 cleanup:
23451 23452 23453
    VIR_FREE(xmlStr);
    return ret;
}
O
Osier Yang 已提交
23454 23455


23456 23457 23458
virSecurityLabelDefPtr
virDomainDefGetSecurityLabelDef(virDomainDefPtr def, const char *model)
{
23459
    size_t i;
23460
    virSecurityLabelDefPtr seclabel = NULL;
23461 23462 23463 23464 23465 23466 23467 23468 23469 23470 23471

    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];
    }

23472
    return seclabel;
23473 23474 23475
}


23476 23477 23478
virSecurityDeviceLabelDefPtr
virDomainChrDefGetSecurityLabelDef(virDomainChrDefPtr def, const char *model)
{
23479
    size_t i;
23480 23481 23482 23483 23484 23485 23486 23487 23488 23489 23490

    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;
}

23491 23492 23493 23494 23495 23496 23497 23498 23499 23500 23501 23502 23503 23504 23505 23506 23507 23508 23509 23510 23511 23512 23513 23514

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,
23515 23516
                       virDomainDeviceDefPtr dev,
                       bool reportError)
23517 23518 23519 23520 23521 23522 23523 23524
{
    virDomainDefFindDeviceCallbackData data = { devAlias, dev };

    dev->type = VIR_DOMAIN_DEVICE_NONE;
    virDomainDeviceInfoIterateInternal(def, virDomainDefFindDeviceCallback,
                                       true, &data);

    if (dev->type == VIR_DOMAIN_DEVICE_NONE) {
23525 23526 23527 23528 23529 23530
        if (reportError) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("no device found with alias %s"), devAlias);
        } else {
            VIR_DEBUG("no device found with alias %s", devAlias);
        }
23531 23532 23533 23534 23535
        return -1;
    }

    return 0;
}
23536 23537 23538 23539 23540 23541 23542 23543 23544 23545 23546

/**
 * 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
23547 23548
virDomainDiskSourceIsBlockType(virStorageSourcePtr src,
                               bool report)
23549
{
23550 23551 23552 23553 23554
    if (!src->path) {
        if (report)
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("source path not found for device='lun' "
                             "using type='%d'"), src->type);
23555
        return false;
23556
    }
23557

23558
    if (src->type == VIR_STORAGE_TYPE_BLOCK)
23559 23560 23561 23562 23563
        return true;

    /* For volume types, check the srcpool.
     * If it's a block type source pool, then it's possible
     */
23564 23565 23566
    if (src->type == VIR_STORAGE_TYPE_VOLUME &&
        src->srcpool &&
        src->srcpool->voltype == VIR_STORAGE_VOL_BLOCK) {
23567 23568 23569 23570
        /* 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.
         */
23571
         if (src->srcpool->pooltype == VIR_STORAGE_POOL_ISCSI &&
23572 23573 23574 23575 23576
             src->srcpool->mode == VIR_STORAGE_SOURCE_POOL_MODE_DIRECT) {
             if (report)
                 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                                _("disk device='lun' for iSCSI is not "
                                  "supported with mode='direct'."));
23577
             return false;
23578
         }
23579

23580 23581
        return true;
    }
23582 23583 23584 23585
    if (report)
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("disk device='lun' is only valid for block "
                         "type disk source"));
23586 23587
    return false;
}
23588 23589 23590 23591 23592 23593 23594 23595 23596 23597 23598 23599 23600 23601 23602 23603


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);

23604 23605 23606 23607 23608 23609
    if (type >= VIR_DOMAIN_METADATA_LAST) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unknown metadata type '%d'"), type);
        goto cleanup;
    }

23610 23611 23612 23613 23614 23615 23616 23617 23618
    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:
23619 23620
        if (VIR_STRDUP(ret, def->description) < 0)
            goto cleanup;
23621 23622 23623
        break;

    case VIR_DOMAIN_METADATA_TITLE:
23624 23625
        if (VIR_STRDUP(ret, def->title) < 0)
            goto cleanup;
23626 23627 23628
        break;

    case VIR_DOMAIN_METADATA_ELEMENT:
23629 23630 23631 23632 23633
        if (!def->metadata)
            break;

        if (virXMLExtractNamespaceXML(def->metadata, uri, &ret) < 0)
            goto cleanup;
23634 23635
        break;

23636
    /* coverity[dead_error_begin] */
23637
    case VIR_DOMAIN_METADATA_LAST:
23638 23639 23640
        break;
    }

23641
    if (!ret)
23642 23643 23644
        virReportError(VIR_ERR_NO_DOMAIN_METADATA, "%s",
                       _("Requested metadata element is not present"));

23645
 cleanup:
23646 23647
    return ret;
}
23648

23649 23650 23651 23652 23653

static int
virDomainDefSetMetadata(virDomainDefPtr def,
                        int type,
                        const char *metadata,
23654 23655
                        const char *key,
                        const char *uri)
23656
{
23657 23658
    xmlDocPtr doc = NULL;
    xmlNodePtr old;
23659
    xmlNodePtr new = NULL;
23660
    char *tmp;
23661 23662
    int ret = -1;

23663 23664 23665 23666 23667 23668
    if (type >= VIR_DOMAIN_METADATA_LAST) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unknown metadata type '%d'"), type);
        goto cleanup;
    }

23669 23670
    switch ((virDomainMetadataType) type) {
    case VIR_DOMAIN_METADATA_DESCRIPTION:
23671
        if (VIR_STRDUP(tmp, metadata) < 0)
23672
            goto cleanup;
23673 23674 23675

        VIR_FREE(def->description);
        def->description = tmp;
23676 23677 23678
        break;

    case VIR_DOMAIN_METADATA_TITLE:
23679
        if (VIR_STRDUP(tmp, metadata) < 0)
23680
            goto cleanup;
23681 23682 23683

        VIR_FREE(def->title);
        def->title = tmp;
23684 23685 23686
        break;

    case VIR_DOMAIN_METADATA_ELEMENT:
23687 23688 23689 23690 23691 23692 23693 23694 23695 23696 23697 23698 23699 23700 23701 23702 23703 23704 23705 23706 23707 23708 23709 23710 23711 23712 23713
        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);
        }

23714 23715
        if (new &&
            !(xmlAddChild(def->metadata, new))) {
23716 23717 23718 23719
            xmlFreeNode(new);
            virReportOOMError();
            goto cleanup;
        }
23720 23721
        break;

23722
    /* coverity[dead_error_begin] */
23723
    case VIR_DOMAIN_METADATA_LAST:
23724 23725 23726 23727 23728
        break;
    }

    ret = 0;

23729
 cleanup:
23730
    xmlFreeDoc(doc);
23731 23732 23733 23734
    return ret;
}


23735 23736 23737 23738
int
virDomainObjSetMetadata(virDomainObjPtr vm,
                        int type,
                        const char *metadata,
23739 23740
                        const char *key,
                        const char *uri,
23741 23742
                        virCapsPtr caps,
                        virDomainXMLOptionPtr xmlopt,
23743
                        const char *stateDir,
23744 23745 23746 23747 23748 23749 23750 23751 23752 23753
                        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)
23754
        return -1;
23755

23756
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
23757 23758
        if (virDomainDefSetMetadata(vm->def, type, metadata, key, uri) < 0)
            return -1;
23759

23760
        if (virDomainSaveStatus(xmlopt, stateDir, vm, caps) < 0)
23761 23762 23763
            return -1;
    }

23764
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
23765 23766
        if (virDomainDefSetMetadata(persistentDef, type, metadata, key,
                                    uri) < 0)
23767
            return -1;
23768

23769
        if (virDomainSaveConfig(configDir, caps, persistentDef) < 0)
23770
            return -1;
23771 23772
    }

23773
    return 0;
23774
}
23775 23776 23777 23778 23779 23780 23781 23782


bool
virDomainDefNeedsPlacementAdvice(virDomainDefPtr def)
{
    if (def->placement_mode == VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO)
        return true;

23783
    if (virDomainNumatuneHasPlacementAuto(def->numa))
23784 23785 23786 23787
        return true;

    return false;
}
23788 23789


23790
int
23791 23792 23793
virDomainDiskDefCheckDuplicateInfo(virDomainDiskDefPtr a,
                                   virDomainDiskDefPtr b)
{
23794 23795 23796 23797 23798 23799 23800 23801 23802
    if (STREQ(a->dst, b->dst)) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("target '%s' duplicated for disk sources '%s' and '%s'"),
                       a->dst,
                       NULLSTR(virDomainDiskGetSource(a)),
                       NULLSTR(virDomainDiskGetSource(b)));
        return -1;
    }

23803 23804 23805 23806 23807 23808 23809 23810 23811 23812 23813 23814 23815 23816 23817 23818 23819 23820
    if (a->wwn && b->wwn && STREQ(a->wwn, b->wwn)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Disks '%s' and '%s' have identical WWN"),
                       a->dst, b->dst);
        return -1;
    }

    if (a->serial && b->serial && STREQ(a->serial, b->serial)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Disks '%s' and '%s' have identical serial"),
                       a->dst, b->dst);
        return -1;
    }

    return 0;
}


23821
int
23822
virDomainDefCheckDuplicateDiskInfo(virDomainDefPtr def)
23823 23824 23825 23826 23827
{
    size_t i;
    size_t j;

    for (i = 0; i < def->ndisks; i++) {
23828 23829 23830 23831
        for (j = i + 1; j < def->ndisks; j++) {
            if (virDomainDiskDefCheckDuplicateInfo(def->disks[i],
                                                   def->disks[j]) < 0)
                return -1;
23832 23833 23834 23835 23836
        }
    }

    return 0;
}