qemu_domain_address.c 115.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
/*
 * qemu_domain_address.c: QEMU domain address
 *
 * Copyright (C) 2006-2016 Red Hat, Inc.
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <config.h>

#include "qemu_domain_address.h"
#include "qemu_domain.h"
#include "viralloc.h"
#include "virerror.h"
#include "virlog.h"

#define VIR_FROM_THIS VIR_FROM_QEMU

VIR_LOG_INIT("qemu.qemu_domain_address");

#define VIO_ADDR_NET 0x1000ul
#define VIO_ADDR_SCSI 0x2000ul
#define VIO_ADDR_SERIAL 0x30000000ul
#define VIO_ADDR_NVRAM 0x3000ul


40 41
/**
 * @def: Domain definition
42
 * @cont: Domain controller def
43 44
 * @qemuCaps: qemu capabilities
 *
45 46
 * If the controller model is already defined, return it immediately;
 * otherwise, based on the @qemuCaps return a default model value.
47
 *
48
 * Returns model on success, -1 on failure with error set.
49
 */
50
int
51 52 53
qemuDomainGetSCSIControllerModel(const virDomainDef *def,
                                 const virDomainControllerDef *cont,
                                 virQEMUCapsPtr qemuCaps)
54
{
55 56 57 58 59
    if (cont->model > 0)
        return cont->model;

    if (qemuDomainIsPSeries(def))
        return VIR_DOMAIN_CONTROLLER_MODEL_SCSI_IBMVSCSI;
60 61
    else if (ARCH_IS_S390(def->os.arch))
        return VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI;
62 63 64 65 66 67 68 69 70
    else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_LSI))
        return VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC;
    else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_SCSI))
        return VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI;

    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Unable to determine model for SCSI controller idx=%d"),
                   cont->idx);
    return -1;
71 72 73
}


74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
/**
 * @def: Domain definition
 * @cont: Domain controller def
 * @qemuCaps: qemu capabilities
 *
 * Set the controller model based on the existing value and the
 * capabilities if possible.
 *
 * Returns 0 on success, -1 on failure with error set.
 */
int
qemuDomainSetSCSIControllerModel(const virDomainDef *def,
                                 virDomainControllerDefPtr cont,
                                 virQEMUCapsPtr qemuCaps)
{
    int model = qemuDomainGetSCSIControllerModel(def, cont, qemuCaps);

    if (model < 0)
        return -1;

    cont->model = model;
    return 0;
}


99 100 101 102 103 104 105 106 107 108 109
/**
 * @def: Domain definition
 * @info: Domain device info
 *
 * Using the device info, find the controller related to the
 * device by index and use that controller to return the model.
 *
 * Returns the model if found, -1 if not with an error message set
 */
int
qemuDomainFindSCSIControllerModel(const virDomainDef *def,
110
                                  virDomainDeviceInfoPtr info)
111 112 113 114 115 116 117 118 119 120
{
    virDomainControllerDefPtr cont;

    if (!(cont = virDomainDeviceFindSCSIController(def, info))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unable to find a SCSI controller for idx=%d"),
                       info->addr.drive.controller);
        return -1;
    }

121
    return cont->model;
122 123 124
}


125
static int
126
qemuDomainAssignVirtioSerialAddresses(virDomainDefPtr def)
127 128 129 130 131
{
    int ret = -1;
    size_t i;
    virDomainVirtioSerialAddrSetPtr addrs = NULL;

132
    if (!(addrs = virDomainVirtioSerialAddrSetCreateFromDomain(def)))
133 134 135 136 137 138 139 140 141
        goto cleanup;

    VIR_DEBUG("Finished reserving existing ports");

    for (i = 0; i < def->nconsoles; i++) {
        virDomainChrDefPtr chr = def->consoles[i];
        if (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE &&
            chr->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_VIRTIO &&
            !virDomainVirtioSerialAddrIsComplete(&chr->info) &&
142 143
            virDomainVirtioSerialAddrAutoAssignFromCache(def, addrs,
                                                         &chr->info, true) < 0)
144 145 146 147 148 149 150 151
            goto cleanup;
    }

    for (i = 0; i < def->nchannels; i++) {
        virDomainChrDefPtr chr = def->channels[i];
        if (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CHANNEL &&
            chr->targetType == VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO &&
            !virDomainVirtioSerialAddrIsComplete(&chr->info) &&
152 153
            virDomainVirtioSerialAddrAutoAssignFromCache(def, addrs,
                                                         &chr->info, false) < 0)
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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
            goto cleanup;
    }

    ret = 0;

 cleanup:
    virDomainVirtioSerialAddrSetFree(addrs);
    return ret;
}


static int
qemuDomainSpaprVIOFindByReg(virDomainDefPtr def ATTRIBUTE_UNUSED,
                            virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
                            virDomainDeviceInfoPtr info, void *opaque)
{
    virDomainDeviceInfoPtr target = opaque;

    if (info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO)
        return 0;

    /* Match a dev that has a reg, is not us, and has a matching reg */
    if (info->addr.spaprvio.has_reg && info != target &&
        info->addr.spaprvio.reg == target->addr.spaprvio.reg)
        /* Has to be < 0 so virDomainDeviceInfoIterate() will exit */
        return -1;

    return 0;
}


static int
qemuDomainAssignSpaprVIOAddress(virDomainDefPtr def,
                                virDomainDeviceInfoPtr info,
                                unsigned long long default_reg)
{
    bool user_reg;
    int ret;

    if (info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO)
        return 0;

    /* Check if the user has assigned the reg already, if so use it */
    user_reg = info->addr.spaprvio.has_reg;
    if (!user_reg) {
        info->addr.spaprvio.reg = default_reg;
        info->addr.spaprvio.has_reg = true;
    }

    ret = virDomainDeviceInfoIterate(def, qemuDomainSpaprVIOFindByReg, info);
    while (ret != 0) {
        if (user_reg) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("spapr-vio address %#llx already in use"),
                           info->addr.spaprvio.reg);
            return -EEXIST;
        }

        /* We assigned the reg, so try a new value */
        info->addr.spaprvio.reg += 0x1000;
        ret = virDomainDeviceInfoIterate(def, qemuDomainSpaprVIOFindByReg,
                                         info);
    }

    return 0;
}


static int
223
qemuDomainAssignSpaprVIOAddresses(virDomainDefPtr def)
224 225 226 227 228 229 230
{
    size_t i;
    int ret = -1;

    /* Default values match QEMU. See spapr_(llan|vscsi|vty).c */

    for (i = 0; i < def->nnets; i++) {
231 232
        virDomainNetDefPtr net = def->nets[i];

233
        if (STREQ_NULLABLE(net->model, "spapr-vlan"))
234 235 236
            net->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO;

        if (qemuDomainAssignSpaprVIOAddress(def, &net->info, VIO_ADDR_NET) < 0)
237 238 239 240
            goto cleanup;
    }

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

243
        if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_IBMVSCSI &&
244 245 246 247 248
            cont->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI) {
            cont->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO;
        }
        if (qemuDomainAssignSpaprVIOAddress(def, &cont->info,
                                            VIO_ADDR_SCSI) < 0) {
249
            goto cleanup;
250
        }
251 252 253 254
    }

    for (i = 0; i < def->nserials; i++) {
        if (def->serials[i]->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL &&
255
            def->serials[i]->targetType == VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SPAPR_VIO) {
256
            def->serials[i]->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO;
257
        }
258 259 260 261 262 263
        if (qemuDomainAssignSpaprVIOAddress(def, &def->serials[i]->info,
                                            VIO_ADDR_SERIAL) < 0)
            goto cleanup;
    }

    if (def->nvram) {
264
        if (qemuDomainIsPSeries(def))
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
            def->nvram->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO;
        if (qemuDomainAssignSpaprVIOAddress(def, &def->nvram->info,
                                            VIO_ADDR_NVRAM) < 0)
            goto cleanup;
    }

    /* No other devices are currently supported on spapr-vio */

    ret = 0;

 cleanup:
    return ret;
}


280 281 282 283 284 285 286 287 288 289 290 291 292
static void
qemuDomainPrimeVfioDeviceAddresses(virDomainDefPtr def,
                                   virDomainDeviceAddressType type)
{
    size_t i;

    for (i = 0; i < def->nhostdevs; i++) {
        virDomainHostdevSubsysPtr subsys = &def->hostdevs[i]->source.subsys;

        if (virHostdevIsMdevDevice(def->hostdevs[i]) &&
            subsys->u.mdev.model == VIR_MDEV_MODEL_TYPE_VFIO_CCW &&
            def->hostdevs[i]->info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
            def->hostdevs[i]->info->type = type;
B
Boris Fiuczynski 已提交
293 294 295 296

        if (virHostdevIsMdevDevice(def->hostdevs[i]) &&
            subsys->u.mdev.model == VIR_MDEV_MODEL_TYPE_VFIO_AP)
            def->hostdevs[i]->info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE;
297 298 299 300
    }
}


301 302 303 304 305 306
static void
qemuDomainPrimeVirtioDeviceAddresses(virDomainDefPtr def,
                                     virDomainDeviceAddressType type)
{
    /*
       declare address-less virtio devices to be of address type 'type'
307 308
       disks, networks, videos, consoles, controllers, memballoon and rng
       in this order
309 310
       if type is ccw filesystem and vsock devices are declared to be of
       address type ccw
311 312 313 314 315 316 317 318 319 320
    */
    size_t i;

    for (i = 0; i < def->ndisks; i++) {
        if (def->disks[i]->bus == VIR_DOMAIN_DISK_BUS_VIRTIO &&
            def->disks[i]->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
            def->disks[i]->info.type = type;
    }

    for (i = 0; i < def->nnets; i++) {
321 322
        virDomainNetDefPtr net = def->nets[i];

323
        if (virDomainNetIsVirtioModel(net) &&
324 325
            net->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
            net->info.type = type;
326 327 328
        }
    }

329 330 331 332 333 334 335 336
    for (i = 0; i < def->nvideos; i++) {
        virDomainVideoDefPtr video = def->videos[i];

        if (video->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
            video->type == VIR_DOMAIN_VIDEO_TYPE_VIRTIO)
            video->info.type = type;
    }

337
    for (i = 0; i < def->ninputs; i++) {
338
        if (def->inputs[i]->bus == VIR_DOMAIN_INPUT_BUS_VIRTIO &&
339 340 341 342 343
            def->inputs[i]->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
            def->inputs[i]->info.type = type;
    }

    for (i = 0; i < def->ncontrollers; i++) {
344 345 346 347 348 349 350
        virDomainControllerDefPtr cont = def->controllers[i];

        if ((cont->type == VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL ||
             cont->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI) &&
            cont->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
            cont->info.type = type;
        }
351 352
    }

353 354 355 356 357 358 359 360
    for (i = 0; i < def->nhostdevs; i++) {
        if (def->hostdevs[i]->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
            def->hostdevs[i]->source.subsys.type ==
            VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI_HOST &&
            def->hostdevs[i]->info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
            def->hostdevs[i]->info->type = type;
    }

361 362
    /* All memballoon devices accepted by the qemu driver are virtio */
    if (virDomainDefHasMemballoon(def) &&
363 364 365 366
        def->memballoon->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
        def->memballoon->info.type = type;

    for (i = 0; i < def->nrngs; i++) {
367 368
        /* All <rng> devices accepted by the qemu driver are virtio */
        if (def->rngs[i]->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
369 370 371 372 373 374 375 376
            def->rngs[i]->info.type = type;
    }

    if (type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW) {
        for (i = 0; i < def->nfss; i++) {
            if (def->fss[i]->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
                def->fss[i]->info.type = type;
        }
377 378 379 380
        if (def->vsock &&
            def->vsock->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
            def->vsock->info.type = type;
        }
381 382 383 384 385 386 387 388 389 390 391 392
    }
}


/*
 * Three steps populating CCW devnos
 * 1. Allocate empty address set
 * 2. Gather addresses with explicit devno
 * 3. Assign defaults to the rest
 */
static int
qemuDomainAssignS390Addresses(virDomainDefPtr def,
T
Tomasz Flendrich 已提交
393
                              virQEMUCapsPtr qemuCaps)
394 395 396 397
{
    int ret = -1;
    virDomainCCWAddressSetPtr addrs = NULL;

398
    if (qemuDomainIsS390CCW(def) &&
399
        virQEMUCapsGet(qemuCaps, QEMU_CAPS_CCW)) {
400 401 402
        if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VFIO_CCW))
            qemuDomainPrimeVfioDeviceAddresses(
                def, VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW);
403 404 405
        qemuDomainPrimeVirtioDeviceAddresses(
            def, VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW);

406
        if (!(addrs = virDomainCCWAddressSetCreateFromDomain(def)))
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
            goto cleanup;

    } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_S390)) {
        /* deal with legacy virtio-s390 */
        qemuDomainPrimeVirtioDeviceAddresses(
            def, VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390);
    }

    ret = 0;

 cleanup:
    virDomainCCWAddressSetFree(addrs);

    return ret;
}


424 425 426 427 428 429 430 431 432
static int
qemuDomainHasVirtioMMIODevicesCallback(virDomainDefPtr def ATTRIBUTE_UNUSED,
                                       virDomainDeviceDefPtr dev ATTRIBUTE_UNUSED,
                                       virDomainDeviceInfoPtr info,
                                       void *opaque)
{
    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO) {
        /* We can stop iterating as soon as we find the first
         * virtio-mmio device */
433
        *((bool *)opaque) = true;
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
        return -1;
    }

    return 0;
}


/**
 * qemuDomainHasVirtioMMIODevices:
 * @def: domain definition
 *
 * Scan @def looking for devices with a virtio-mmio address.
 *
 * Returns: true if there are any, false otherwise
 */
static bool
qemuDomainHasVirtioMMIODevices(virDomainDefPtr def)
{
    bool result = false;

    virDomainDeviceInfoIterate(def,
                               qemuDomainHasVirtioMMIODevicesCallback,
                               &result);

    return result;
}


462
static void
463 464 465
qemuDomainAssignARMVirtioMMIOAddresses(virDomainDefPtr def,
                                       virQEMUCapsPtr qemuCaps)
{
S
Stefan Schallenberg 已提交
466 467
    if (def->os.arch != VIR_ARCH_ARMV6L &&
        def->os.arch != VIR_ARCH_ARMV7L &&
468 469 470 471
        def->os.arch != VIR_ARCH_AARCH64)
        return;

    if (!(STRPREFIX(def->os.machine, "vexpress-") ||
472
          qemuDomainIsARMVirt(def)))
473 474
        return;

475
    /* We use virtio-mmio by default on mach-virt guests only if they already
476 477 478
     * have at least one virtio-mmio device: in all other cases, assuming
     * the QEMU binary supports all necessary capabilities (PCIe Root plus
     * some kind of PCIe Root Port), we prefer virtio-pci */
479
    if (qemuDomainHasPCIeRoot(def) &&
480 481
        (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_PCIE_ROOT_PORT) ||
         virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_IOH3420)) &&
482 483 484 485 486 487
        !qemuDomainHasVirtioMMIODevices(def)) {
        qemuDomainPrimeVirtioDeviceAddresses(def,
                                             VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI);
    } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIRTIO_MMIO)) {
        qemuDomainPrimeVirtioDeviceAddresses(def,
                                             VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO);
488 489 490 491
    }
}


492 493 494 495 496 497 498 499 500 501 502 503 504 505
static void
qemuDomainAssignRISCVVirtioMMIOAddresses(virDomainDefPtr def,
                                         virQEMUCapsPtr qemuCaps)
{
    if (!qemuDomainIsRISCVVirt(def))
        return;

    if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIRTIO_MMIO)) {
        qemuDomainPrimeVirtioDeviceAddresses(def,
                                             VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO);
    }
}


506 507 508 509 510
static void
qemuDomainAssignVirtioMMIOAddresses(virDomainDefPtr def,
                                    virQEMUCapsPtr qemuCaps)
{
    qemuDomainAssignARMVirtioMMIOAddresses(def, qemuCaps);
511 512

    qemuDomainAssignRISCVVirtioMMIOAddresses(def, qemuCaps);
513 514 515
}


516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
static bool
qemuDomainDeviceSupportZPCI(virDomainDeviceDefPtr device)
{
    switch ((virDomainDeviceType)device->type) {
    case VIR_DOMAIN_DEVICE_CHR:
        return false;

    case VIR_DOMAIN_DEVICE_CONTROLLER:
    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_GRAPHICS:
    case VIR_DOMAIN_DEVICE_HUB:
    case VIR_DOMAIN_DEVICE_REDIRDEV:
    case VIR_DOMAIN_DEVICE_SMARTCARD:
    case VIR_DOMAIN_DEVICE_MEMBALLOON:
    case VIR_DOMAIN_DEVICE_NVRAM:
    case VIR_DOMAIN_DEVICE_RNG:
    case VIR_DOMAIN_DEVICE_SHMEM:
    case VIR_DOMAIN_DEVICE_TPM:
    case VIR_DOMAIN_DEVICE_PANIC:
    case VIR_DOMAIN_DEVICE_MEMORY:
    case VIR_DOMAIN_DEVICE_IOMMU:
    case VIR_DOMAIN_DEVICE_VSOCK:
        break;

    case VIR_DOMAIN_DEVICE_NONE:
    case VIR_DOMAIN_DEVICE_LAST:
    default:
        virReportEnumRangeError(virDomainDeviceType, device->type);
        return false;
    }

    return true;
}


static virPCIDeviceAddressExtensionFlags
qemuDomainDeviceCalculatePCIAddressExtensionFlags(virQEMUCapsPtr qemuCaps,
                                                  virDomainDeviceDefPtr dev)
{
    virPCIDeviceAddressExtensionFlags extFlags = 0;

    if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_ZPCI) &&
        qemuDomainDeviceSupportZPCI(dev)) {
        extFlags |= VIR_PCI_ADDRESS_EXTENSION_ZPCI;
    }

    return extFlags;
}


574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
/**
 * qemuDomainDeviceCalculatePCIConnectFlags:
 *
 * @dev: The device to be checked
 * @pcieFlags: flags to use for a known PCI Express device
 * @virtioFlags: flags to use for a virtio device (properly vetted
 *       for the current qemu binary and arch/machinetype)
 *
 * Lowest level function to determine PCI connectFlags for a
 * device. This function relies on the next higher-level function
 * determining the value for pcieFlags and virtioFlags in advance -
 * this is to make it more efficient to call multiple times.
 *
 * Returns appropriate virDomainPCIConnectFlags for this device in
 * this domain, or 0 if the device doesn't connect using PCI. There
 * is no failure.
 */
static virDomainPCIConnectFlags
qemuDomainDeviceCalculatePCIConnectFlags(virDomainDeviceDefPtr dev,
593
                                         virQEMUDriverPtr driver,
594
                                         virDomainPCIConnectFlags pcieFlags,
595
                                         virDomainPCIConnectFlags virtioFlags)
596 597 598 599
{
    virDomainPCIConnectFlags pciFlags = (VIR_PCI_CONNECT_TYPE_PCI_DEVICE |
                                         VIR_PCI_CONNECT_HOTPLUGGABLE);

600
    switch ((virDomainDeviceType)dev->type) {
601 602 603
    case VIR_DOMAIN_DEVICE_CONTROLLER: {
        virDomainControllerDefPtr cont = dev->data.controller;

604
        switch ((virDomainControllerType)cont->type) {
605 606 607 608 609 610 611 612
        case VIR_DOMAIN_CONTROLLER_TYPE_PCI:
            return virDomainPCIControllerModelToConnectType(cont->model);

        case VIR_DOMAIN_CONTROLLER_TYPE_SATA:
            return pciFlags;

        case VIR_DOMAIN_CONTROLLER_TYPE_USB:
            switch ((virDomainControllerModelUSB) cont->model) {
613 614 615 616 617 618 619 620 621
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_DEFAULT:
                /* qemuDomainControllerDefPostParse should have
                 * changed 'model' to an explicit USB model in
                 * most cases. Since we're still on the default
                 * though, we must be going to use "-usb", which
                 * is assumed to be a PCI default
                 */
                return pciFlags;

622
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_NEC_XHCI:
623
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_QEMU_XHCI:
624
                return pcieFlags;
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640

            case VIR_DOMAIN_CONTROLLER_MODEL_USB_EHCI:
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_EHCI1:
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI1:
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI2:
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI3:
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_VT82C686B_UHCI:
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX3_UHCI:
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX4_UHCI:
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_PCI_OHCI:
                return pciFlags;

            case VIR_DOMAIN_CONTROLLER_MODEL_USB_QUSB1: /* xen only */
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_QUSB2: /* xen only */
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE:
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_LAST:
641
                return 0;
642
            }
643
            break;
644 645

        case VIR_DOMAIN_CONTROLLER_TYPE_IDE:
646 647
            return pciFlags;

648
        case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
649
            switch ((virDomainControllerModelSCSI) cont->model) {
650 651 652
            case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_DEFAULT:
                return 0;

653
            case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI:
654
            case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_NON_TRANSITIONAL:
655 656
                return virtioFlags;

657 658
            /* Transitional devices only work in conventional PCI slots */
            case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_TRANSITIONAL:
659 660 661 662 663 664 665 666 667 668 669 670
            case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_AUTO:
            case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_BUSLOGIC:
            case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC:
            case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068:
            case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VMPVSCSI:
            case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_IBMVSCSI:
            case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1078:
                return pciFlags;

            case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LAST:
                return 0;
            }
671
            break;
672

673
        case VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL:
674 675 676 677 678 679 680 681 682 683 684 685 686 687
            switch ((virDomainControllerModelVirtioSerial) cont->model) {
            case VIR_DOMAIN_CONTROLLER_MODEL_VIRTIO_SERIAL_VIRTIO_TRANSITIONAL:
                /* Transitional devices only work in conventional PCI slots */
                return pciFlags;

            case VIR_DOMAIN_CONTROLLER_MODEL_VIRTIO_SERIAL_VIRTIO:
            case VIR_DOMAIN_CONTROLLER_MODEL_VIRTIO_SERIAL_VIRTIO_NON_TRANSITIONAL:
            case VIR_DOMAIN_CONTROLLER_MODEL_VIRTIO_SERIAL_DEFAULT:
                return virtioFlags;

            case VIR_DOMAIN_CONTROLLER_MODEL_VIRTIO_SERIAL_LAST:
                return 0;
            }
            break;
688 689 690

        case VIR_DOMAIN_CONTROLLER_TYPE_FDC:
        case VIR_DOMAIN_CONTROLLER_TYPE_CCID:
691
        case VIR_DOMAIN_CONTROLLER_TYPE_XENBUS:
692 693 694 695 696
        case VIR_DOMAIN_CONTROLLER_TYPE_LAST:
            /* should be 0 */
            return pciFlags;
        }
    }
697
        break;
698 699 700

    case VIR_DOMAIN_DEVICE_FS:
        /* the only type of filesystem so far is virtio-9p-pci */
701 702 703 704 705 706 707 708 709 710 711 712
        switch ((virDomainFSModel) dev->data.fs->model) {
        case VIR_DOMAIN_FS_MODEL_VIRTIO_TRANSITIONAL:
            /* Transitional devices only work in conventional PCI slots */
            return pciFlags;
        case VIR_DOMAIN_FS_MODEL_VIRTIO:
        case VIR_DOMAIN_FS_MODEL_VIRTIO_NON_TRANSITIONAL:
        case VIR_DOMAIN_FS_MODEL_DEFAULT:
            return virtioFlags;
        case VIR_DOMAIN_FS_MODEL_LAST:
            break;
        }
        return 0;
713 714 715 716 717 718 719 720 721

    case VIR_DOMAIN_DEVICE_NET: {
        virDomainNetDefPtr net = dev->data.net;

        /* NB: a type='hostdev' will use PCI, but its
         * address is assigned when we're assigning the
         * addresses for other hostdev devices.
         */
        if (net->type == VIR_DOMAIN_NET_TYPE_HOSTDEV ||
722
            STREQ_NULLABLE(net->model, "usb-net")) {
723
            return 0;
724
        }
725

726 727 728 729 730 731 732
        if (STREQ_NULLABLE(net->model, "virtio") ||
            STREQ_NULLABLE(net->model, "virtio-non-transitional"))
            return virtioFlags;

        /* Transitional devices only work in conventional PCI slots */
        if (STREQ_NULLABLE(net->model, "virtio-transitional"))
            return pciFlags;
733

734
        if (STREQ_NULLABLE(net->model, "e1000e"))
735 736
            return pcieFlags;

737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
        return pciFlags;
    }

    case VIR_DOMAIN_DEVICE_SOUND:
        switch ((virDomainSoundModel) dev->data.sound->model) {
        case VIR_DOMAIN_SOUND_MODEL_ES1370:
        case VIR_DOMAIN_SOUND_MODEL_AC97:
        case VIR_DOMAIN_SOUND_MODEL_ICH6:
        case VIR_DOMAIN_SOUND_MODEL_ICH9:
            return pciFlags;

        case VIR_DOMAIN_SOUND_MODEL_SB16:
        case VIR_DOMAIN_SOUND_MODEL_PCSPK:
        case VIR_DOMAIN_SOUND_MODEL_USB:
        case VIR_DOMAIN_SOUND_MODEL_LAST:
752
            return 0;
753
        }
754
        break;
755 756 757 758

    case VIR_DOMAIN_DEVICE_DISK:
        switch ((virDomainDiskBus) dev->data.disk->bus) {
        case VIR_DOMAIN_DISK_BUS_VIRTIO:
759 760 761 762 763 764 765 766 767 768 769 770 771
            /* only virtio disks use PCI */
            switch ((virDomainDiskModel) dev->data.disk->model) {
            case VIR_DOMAIN_DISK_MODEL_VIRTIO_TRANSITIONAL:
                /* Transitional devices only work in conventional PCI slots */
                return pciFlags;
            case VIR_DOMAIN_DISK_MODEL_VIRTIO:
            case VIR_DOMAIN_DISK_MODEL_VIRTIO_NON_TRANSITIONAL:
            case VIR_DOMAIN_DISK_MODEL_DEFAULT:
                return virtioFlags;
            case VIR_DOMAIN_DISK_MODEL_LAST:
                break;
            }
            return 0;
772 773 774 775 776 777 778 779 780 781

        case VIR_DOMAIN_DISK_BUS_IDE:
        case VIR_DOMAIN_DISK_BUS_FDC:
        case VIR_DOMAIN_DISK_BUS_SCSI:
        case VIR_DOMAIN_DISK_BUS_XEN:
        case VIR_DOMAIN_DISK_BUS_USB:
        case VIR_DOMAIN_DISK_BUS_UML:
        case VIR_DOMAIN_DISK_BUS_SATA:
        case VIR_DOMAIN_DISK_BUS_SD:
        case VIR_DOMAIN_DISK_BUS_LAST:
782
            return 0;
783
        }
784
        break;
785

786 787 788 789 790 791
    case VIR_DOMAIN_DEVICE_HOSTDEV: {
        virDomainHostdevDefPtr hostdev = dev->data.hostdev;
        bool isExpress = false;
        virPCIDevicePtr pciDev;
        virPCIDeviceAddressPtr hostAddr = &hostdev->source.subsys.u.pci.addr;

792 793 794 795
        if (!virHostdevIsMdevDevice(hostdev) &&
            (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
             (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
              hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI_HOST))) {
796 797 798 799 800 801 802 803 804 805 806
            return 0;
        }

        if (pciFlags == pcieFlags) {
            /* This arch/qemu only supports legacy PCI, so there
             * is no point in checking if the device is an Express
             * device.
             */
            return pciFlags;
        }

807
        if (virDeviceInfoPCIAddressIsPresent(hostdev->info)) {
808 809 810 811 812 813 814 815 816 817 818
            /* A guest-side address has already been assigned, so
             * we can avoid reading the PCI config, and just use
             * pcieFlags, since the pciConnectFlags checking is
             * more relaxed when an address is already assigned
             * than it is when we're looking for a new address (so
             * validation will pass regardless of whether we set
             * the flags to PCI or PCIe).
             */
            return pcieFlags;
        }

819 820 821 822 823
        /* mdevs don't have corresponding files in /sys that we can poke to
         * try and figure out whether they are legacy PCI or PCI Express, so
         * the logic below would never work; instead, we just go ahead and
         * assume they're PCI Express. This is a very reasonable assumption,
         * as all current mdev-capable devices are indeed PCI Express */
824 825 826
        if (hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_MDEV)
            return pcieFlags;

827
        /* according to pbonzini, from the guest PoV vhost-scsi devices
828
         * are the same as virtio-scsi, so they should follow virtio logic
829
         */
830 831 832 833 834 835 836 837 838 839 840 841 842 843
        if (hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI_HOST) {
            switch ((virDomainHostdevSubsysSCSIVHostModelType) hostdev->source.subsys.u.scsi_host.model) {
            case VIR_DOMAIN_HOSTDEV_SUBSYS_SCSI_VHOST_MODEL_TYPE_VIRTIO_TRANSITIONAL:
                /* Transitional devices only work in conventional PCI slots */
                return pciFlags;
            case VIR_DOMAIN_HOSTDEV_SUBSYS_SCSI_VHOST_MODEL_TYPE_VIRTIO:
            case VIR_DOMAIN_HOSTDEV_SUBSYS_SCSI_VHOST_MODEL_TYPE_VIRTIO_NON_TRANSITIONAL:
            case VIR_DOMAIN_HOSTDEV_SUBSYS_SCSI_VHOST_MODEL_TYPE_DEFAULT:
                return virtioFlags;
            case VIR_DOMAIN_HOSTDEV_SUBSYS_SCSI_VHOST_MODEL_TYPE_LAST:
                break;
            }
            return 0;
        }
844

845 846 847 848 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
        if (!(pciDev = virPCIDeviceNew(hostAddr->domain,
                                       hostAddr->bus,
                                       hostAddr->slot,
                                       hostAddr->function))) {
            /* libvirt should be able to perform all the
             * operations in virPCIDeviceNew() even if it's
             * running unprivileged, so if this fails, the device
             * apparently doesn't currently exist on the host.
             * Since the overwhelming majority of assignable host
             * devices are PCIe, assume this one is too.
             */
            return pcieFlags;
        }

        if (!driver->privileged) {
            /* unprivileged libvirtd is unable to read *all* of a
             * device's PCI config (it can only read the first 64
             * bytes, which isn't enough for the check that's done
             * in virPCIDeviceIsPCIExpress()), so instead of
             * trying and failing, we make an educated guess based
             * on the length of the device's config file - if it
             * is 256 bytes, then it is definitely a legacy PCI
             * device. If it's larger than that, then it is
             * *probably PCIe (although it could be PCI-x, but
             * those are extremely rare). If the config file can't
             * be found (in which case the "length" will be -1),
             * then we blindly assume the most likely outcome -
             * PCIe.
             */
            off_t configLen
               = virFileLength(virPCIDeviceGetConfigPath(pciDev), -1);

            virPCIDeviceFree(pciDev);

            if (configLen == 256)
                return pciFlags;

            return pcieFlags;
        }

        /* If we are running with privileges, we can examine the
         * PCI config contents with virPCIDeviceIsPCIExpress() for
         * a definitive answer.
         */
        isExpress = virPCIDeviceIsPCIExpress(pciDev);
        virPCIDeviceFree(pciDev);

        if (isExpress)
            return pcieFlags;

895
        return pciFlags;
896
    }
897 898 899

    case VIR_DOMAIN_DEVICE_MEMBALLOON:
        switch ((virDomainMemballoonModel) dev->data.memballoon->model) {
900 901 902
        case VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO_TRANSITIONAL:
            /* Transitional devices only work in conventional PCI slots */
            return pciFlags;
903
        case VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO:
904
        case VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO_NON_TRANSITIONAL:
905
            return virtioFlags;
906 907 908 909

        case VIR_DOMAIN_MEMBALLOON_MODEL_XEN:
        case VIR_DOMAIN_MEMBALLOON_MODEL_NONE:
        case VIR_DOMAIN_MEMBALLOON_MODEL_LAST:
910
            return 0;
911
        }
912
        break;
913 914 915

    case VIR_DOMAIN_DEVICE_RNG:
        switch ((virDomainRNGModel) dev->data.rng->model) {
916 917 918
        case VIR_DOMAIN_RNG_MODEL_VIRTIO_TRANSITIONAL:
            /* Transitional devices only work in conventional PCI slots */
            return pciFlags;
919
        case VIR_DOMAIN_RNG_MODEL_VIRTIO:
920
        case VIR_DOMAIN_RNG_MODEL_VIRTIO_NON_TRANSITIONAL:
921
            return virtioFlags;
922 923

        case VIR_DOMAIN_RNG_MODEL_LAST:
924
            return 0;
925
        }
926
        break;
927 928 929 930 931 932 933 934 935 936

    case VIR_DOMAIN_DEVICE_WATCHDOG:
        /* only one model connects using PCI */
        switch ((virDomainWatchdogModel) dev->data.watchdog->model) {
        case VIR_DOMAIN_WATCHDOG_MODEL_I6300ESB:
            return pciFlags;

        case VIR_DOMAIN_WATCHDOG_MODEL_IB700:
        case VIR_DOMAIN_WATCHDOG_MODEL_DIAG288:
        case VIR_DOMAIN_WATCHDOG_MODEL_LAST:
937
            return 0;
938
        }
939
        break;
940 941

    case VIR_DOMAIN_DEVICE_VIDEO:
942
        switch ((virDomainVideoType)dev->data.video->type) {
943
        case VIR_DOMAIN_VIDEO_TYPE_VIRTIO:
944 945
            return virtioFlags;

946 947 948 949 950 951 952 953 954
        case VIR_DOMAIN_VIDEO_TYPE_VGA:
        case VIR_DOMAIN_VIDEO_TYPE_CIRRUS:
        case VIR_DOMAIN_VIDEO_TYPE_VMVGA:
        case VIR_DOMAIN_VIDEO_TYPE_XEN:
        case VIR_DOMAIN_VIDEO_TYPE_VBOX:
        case VIR_DOMAIN_VIDEO_TYPE_QXL:
        case VIR_DOMAIN_VIDEO_TYPE_PARALLELS:
            return pciFlags;

955
        case VIR_DOMAIN_VIDEO_TYPE_DEFAULT:
F
Fabian Freyer 已提交
956
        case VIR_DOMAIN_VIDEO_TYPE_GOP:
957
        case VIR_DOMAIN_VIDEO_TYPE_NONE:
958
        case VIR_DOMAIN_VIDEO_TYPE_LAST:
959
            return 0;
960
        }
961
        break;
962 963 964 965 966 967 968

    case VIR_DOMAIN_DEVICE_SHMEM:
        return pciFlags;

    case VIR_DOMAIN_DEVICE_INPUT:
        switch ((virDomainInputBus) dev->data.input->bus) {
        case VIR_DOMAIN_INPUT_BUS_VIRTIO:
969 970 971 972 973 974 975 976 977 978 979 980
            switch ((virDomainInputModel) dev->data.input->model) {
            case VIR_DOMAIN_INPUT_MODEL_VIRTIO_TRANSITIONAL:
                /* Transitional devices only work in conventional PCI slots */
                return pciFlags;
            case VIR_DOMAIN_INPUT_MODEL_VIRTIO:
            case VIR_DOMAIN_INPUT_MODEL_VIRTIO_NON_TRANSITIONAL:
            case VIR_DOMAIN_INPUT_MODEL_DEFAULT:
                return virtioFlags;
            case VIR_DOMAIN_INPUT_MODEL_LAST:
                break;
            }
            return 0;
981 982 983 984 985 986

        case VIR_DOMAIN_INPUT_BUS_PS2:
        case VIR_DOMAIN_INPUT_BUS_USB:
        case VIR_DOMAIN_INPUT_BUS_XEN:
        case VIR_DOMAIN_INPUT_BUS_PARALLELS:
        case VIR_DOMAIN_INPUT_BUS_LAST:
987
            return 0;
988
        }
989
        break;
990 991

    case VIR_DOMAIN_DEVICE_CHR:
992
        switch ((virDomainChrSerialTargetType)dev->data.chr->targetType) {
993 994 995 996 997
        case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_PCI:
            return pciFlags;

        case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_ISA:
        case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_USB:
998
        case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SPAPR_VIO:
999
        case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SYSTEM:
1000
        case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_SCLP:
1001
        case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_NONE:
1002
        case VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_LAST:
1003
            return 0;
1004
        }
1005
        break;
1006

J
Ján Tomko 已提交
1007
    case VIR_DOMAIN_DEVICE_VSOCK:
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
        switch ((virDomainVsockModel) dev->data.vsock->model) {
        case VIR_DOMAIN_VSOCK_MODEL_VIRTIO_TRANSITIONAL:
            /* Transitional devices only work in conventional PCI slots */
            return pciFlags;
        case VIR_DOMAIN_VSOCK_MODEL_VIRTIO:
        case VIR_DOMAIN_VSOCK_MODEL_VIRTIO_NON_TRANSITIONAL:
            return virtioFlags;

        case VIR_DOMAIN_VSOCK_MODEL_DEFAULT:
        case VIR_DOMAIN_VSOCK_MODEL_LAST:
            return 0;
        }
        break;
J
Ján Tomko 已提交
1021

1022
        /* These devices don't ever connect with PCI */
1023 1024 1025 1026 1027 1028 1029
    case VIR_DOMAIN_DEVICE_NVRAM:
    case VIR_DOMAIN_DEVICE_TPM:
    case VIR_DOMAIN_DEVICE_PANIC:
    case VIR_DOMAIN_DEVICE_MEMORY:
    case VIR_DOMAIN_DEVICE_HUB:
    case VIR_DOMAIN_DEVICE_REDIRDEV:
    case VIR_DOMAIN_DEVICE_SMARTCARD:
1030
        /* These devices don't even have a DeviceInfo */
1031 1032 1033 1034 1035
    case VIR_DOMAIN_DEVICE_LEASE:
    case VIR_DOMAIN_DEVICE_GRAPHICS:
    case VIR_DOMAIN_DEVICE_IOMMU:
    case VIR_DOMAIN_DEVICE_LAST:
    case VIR_DOMAIN_DEVICE_NONE:
1036
        return 0;
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
    }

    /* We can never get here, because all cases are covered in the
     * switch, and they all return, but the compiler will still
     * complain "control reaches end of non-void function" unless
     * we add the following return.
     */
    return 0;
}


typedef struct {
    virDomainPCIConnectFlags virtioFlags;
    virDomainPCIConnectFlags pcieFlags;
1051
    virQEMUDriverPtr driver;
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
} qemuDomainFillDevicePCIConnectFlagsIterData;


/**
 * qemuDomainFillDevicePCIConnectFlagsIterInit:
 *
 * Initialize the iterator data that is used when calling
 * qemuDomainCalculateDevicePCIConnectFlags().
 */
static void
qemuDomainFillDevicePCIConnectFlagsIterInit(virDomainDefPtr def,
                                            virQEMUCapsPtr qemuCaps,
1064
                                            virQEMUDriverPtr driver,
1065 1066
                                            qemuDomainFillDevicePCIConnectFlagsIterData *data)
{
1067 1068
    data->driver = driver;

1069
    if (qemuDomainHasPCIeRoot(def)) {
1070 1071 1072 1073 1074 1075 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
        data->pcieFlags = (VIR_PCI_CONNECT_TYPE_PCIE_DEVICE |
                           VIR_PCI_CONNECT_HOTPLUGGABLE);
    } else {
        data->pcieFlags = (VIR_PCI_CONNECT_TYPE_PCI_DEVICE |
                           VIR_PCI_CONNECT_HOTPLUGGABLE);
    }

    if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_PCI_DISABLE_LEGACY)) {
        data->virtioFlags = data->pcieFlags;
    } else {
        data->virtioFlags = (VIR_PCI_CONNECT_TYPE_PCI_DEVICE |
                             VIR_PCI_CONNECT_HOTPLUGGABLE);
    }
}


/**
 * qemuDomainFillDevicePCIConnectFlagsIter:
 *
 * @def: the entire DomainDef
 * @dev: The device to be checked
 * @info: virDomainDeviceInfo within the device
 * @opaque: points to iterator data setup beforehand.
 *
 * Sets the pciConnectFlags for a single device's info. Has properly
 * formatted arguments to be called by virDomainDeviceInfoIterate().
 *
 * Always returns 0 - there is no failure.
 */
static int
qemuDomainFillDevicePCIConnectFlagsIter(virDomainDefPtr def ATTRIBUTE_UNUSED,
                                        virDomainDeviceDefPtr dev,
                                        virDomainDeviceInfoPtr info,
                                        void *opaque)
{
    qemuDomainFillDevicePCIConnectFlagsIterData *data = opaque;

    info->pciConnectFlags
1108 1109
        = qemuDomainDeviceCalculatePCIConnectFlags(dev, data->driver,
                                                   data->pcieFlags,
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
                                                   data->virtioFlags);
    return 0;
}


/**
 * qemuDomainFillAllPCIConnectFlags:
 *
 * @def: the entire DomainDef
 * @qemuCaps: as you'd expect
 *
 * Set the info->pciConnectFlags for all devices in the domain.
 *
 * Returns 0 on success or -1 on failure (the only possibility of
 * failure would be some internal problem with
 * virDomainDeviceInfoIterate())
 */
1127
static int
1128
qemuDomainFillAllPCIConnectFlags(virDomainDefPtr def,
1129 1130
                                 virQEMUCapsPtr qemuCaps,
                                 virQEMUDriverPtr driver)
1131 1132 1133
{
    qemuDomainFillDevicePCIConnectFlagsIterData data;

1134
    qemuDomainFillDevicePCIConnectFlagsIterInit(def, qemuCaps, driver, &data);
1135 1136 1137 1138 1139 1140 1141

    return virDomainDeviceInfoIterate(def,
                                      qemuDomainFillDevicePCIConnectFlagsIter,
                                      &data);
}


1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
/**
 * qemuDomainFillDevicePCIExtensionFlagsIter:
 *
 * @def: the entire DomainDef
 * @dev: The device to be checked
 * @info: virDomainDeviceInfo within the device
 * @opaque: qemu capabilities
 *
 * Sets the pciAddressExtFlags for a single device's info. Has properly
 * formatted arguments to be called by virDomainDeviceInfoIterate().
 *
 * Always returns 0 - there is no failure.
 */
static int
qemuDomainFillDevicePCIExtensionFlagsIter(virDomainDefPtr def ATTRIBUTE_UNUSED,
                                          virDomainDeviceDefPtr dev,
                                          virDomainDeviceInfoPtr info,
                                          void *opaque)
{
    virQEMUCapsPtr qemuCaps = opaque;

    info->pciAddrExtFlags =
        qemuDomainDeviceCalculatePCIAddressExtensionFlags(qemuCaps, dev);

    return 0;
}


/**
 * qemuDomainFillAllPCIExtensionFlags:
 *
 * @def: the entire DomainDef
 * @qemuCaps: as you'd expect
 *
 * Set the info->pciAddressExtFlags for all devices in the domain.
 *
 * Returns 0 on success or -1 on failure (the only possibility of
 * failure would be some internal problem with
 * virDomainDeviceInfoIterate())
 */
static int
qemuDomainFillAllPCIExtensionFlags(virDomainDefPtr def,
                                   virQEMUCapsPtr qemuCaps)
{
    return virDomainDeviceInfoIterate(def,
                                      qemuDomainFillDevicePCIExtensionFlagsIter,
                                      qemuCaps);
}


1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
/**
 * qemuDomainFindUnusedIsolationGroupIter:
 * @def: domain definition
 * @dev: device definition
 * @info: device information
 * @opaque: user data
 *
 * Used to implement qemuDomainFindUnusedIsolationGroup(). You probably
 * don't want to call this directly.
 *
 * Return: 0 if the isolation group is not used by the device, <1 otherwise.
 */
static int
qemuDomainFindUnusedIsolationGroupIter(virDomainDefPtr def ATTRIBUTE_UNUSED,
                                       virDomainDeviceDefPtr dev ATTRIBUTE_UNUSED,
                                       virDomainDeviceInfoPtr info,
                                       void *opaque)
{
    unsigned int *isolationGroup = opaque;

    if (info->isolationGroup == *isolationGroup)
        return -1;

    return 0;
}


/**
 * qemuDomainFindUnusedIsolationGroup:
 * @def: domain definition
 *
 * Find an isolation group that is not used by any device in @def yet.
 *
 * Normally, we'd look up the device's IOMMU group and base its isolation
 * group on that; however, when a network interface uses a network backed
 * by SR-IOV Virtual Functions, we can't know at PCI address assignment
 * time which host device will be used so we can't look up its IOMMU group.
 *
 * We still want such a device to be isolated: this function can be used
 * to obtain a synthetic isolation group usable for the purpose.
 *
 * Return: unused isolation group
 */
static unsigned int
qemuDomainFindUnusedIsolationGroup(virDomainDefPtr def)
{
    unsigned int isolationGroup = UINT_MAX;

    /* We start from the highest possible isolation group and work our
     * way backwards so that we're working in a completely different range
     * from IOMMU groups, thus avoiding clashes. We're realistically going
     * to call this function just a few times per guest anyway */
    while (isolationGroup > 0 &&
           virDomainDeviceInfoIterate(def,
                                      qemuDomainFindUnusedIsolationGroupIter,
                                      &isolationGroup) < 0) {
        isolationGroup--;
    }

    return isolationGroup;
}


/**
 * qemuDomainFillDeviceIsolationGroup:
 * @def: domain definition
 * @dev: device definition
 *
 * Fill isolation group information for a single device.
 *
 * Return: 0 on success, <0 on failure
 * */
int
qemuDomainFillDeviceIsolationGroup(virDomainDefPtr def,
                                   virDomainDeviceDefPtr dev)
{
    /* Only host devices need their isolation group to be different from
     * the default. Interfaces of type hostdev are just host devices in
     * disguise, but we don't need to handle them separately because for
     * each such interface a corresponding hostdev is also added to the
     * guest configuration */
    if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV) {
        virDomainHostdevDefPtr hostdev = dev->data.hostdev;
        virDomainDeviceInfoPtr info = hostdev->info;
        virPCIDeviceAddressPtr hostAddr;
        int tmp;

        /* Only PCI host devices are subject to isolation */
        if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
            hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI) {
            goto skip;
        }

        hostAddr = &hostdev->source.subsys.u.pci.addr;

        /* If a non-default isolation has already been assigned to the
         * device, we can avoid looking up the information again */
        if (info->isolationGroup > 0)
            goto skip;

        /* The isolation group depends on the IOMMU group assigned by the host */
        tmp = virPCIDeviceAddressGetIOMMUGroupNum(hostAddr);

        if (tmp < 0) {
1296 1297 1298 1299 1300
            VIR_WARN("Can't look up isolation group for host device "
                     "%04x:%02x:%02x.%x, device won't be isolated",
                     hostAddr->domain, hostAddr->bus,
                     hostAddr->slot, hostAddr->function);
            goto skip;
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
        }

        /* The isolation group for a host device is its IOMMU group,
         * increased by one: this is because zero is a valid IOMMU group but
         * that's also the default isolation group, which we want to save
         * for emulated devices. Shifting isolation groups for host devices
         * by one ensures there is no overlap */
        info->isolationGroup = tmp + 1;

        VIR_DEBUG("Isolation group for host device %04x:%02x:%02x.%x is %u",
                  hostAddr->domain, hostAddr->bus,
                  hostAddr->slot, hostAddr->function,
                  info->isolationGroup);

    } else if (dev->type == VIR_DOMAIN_DEVICE_NET) {
        virDomainNetDefPtr iface = dev->data.net;
        virDomainDeviceInfoPtr info = &iface->info;
        unsigned int tmp;

        /* Network interfaces can ultimately result in the guest being
         * assigned a host device if the libvirt network they're connected
         * to is of type hostdev. All other kinds of network interfaces don't
         * require us to isolate the guest device, so we can skip them */
        if (iface->type != VIR_DOMAIN_NET_TYPE_NETWORK ||
1325
            virDomainNetResolveActualType(iface) != VIR_DOMAIN_NET_TYPE_HOSTDEV) {
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
            goto skip;
        }

        /* If a non-default isolation has already been assigned to the
         * device, we can avoid looking up the information again */
        if (info->isolationGroup > 0)
            goto skip;

        /* Obtain a synthetic isolation group for the device, since at this
         * point in time we don't have access to the IOMMU group of the host
         * device that will eventually be used by the guest */
        tmp = qemuDomainFindUnusedIsolationGroup(def);

        if (tmp == 0) {
1340 1341 1342 1343 1344
            VIR_WARN("Can't obtain usable isolation group for interface "
                     "configured to use hostdev-backed network '%s', "
                     "device won't be isolated",
                     iface->data.network.name);
            goto skip;
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
        }

        info->isolationGroup = tmp;

        VIR_DEBUG("Isolation group for interface configured to use "
                  "hostdev-backed network '%s' is %u",
                  iface->data.network.name, info->isolationGroup);
    }

 skip:
1355
    return 0;
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
}


/**
 * qemuDomainFillDeviceIsolationGroupIter:
 * @def: domain definition
 * @dev: device definition
 * @info: device information
 * @opaque: user data
 *
 * A version of qemuDomainFillDeviceIsolationGroup() to be used
 * with virDomainDeviceInfoIterate()
 *
 * Return: 0 on success, <0 on failure
 */
static int
qemuDomainFillDeviceIsolationGroupIter(virDomainDefPtr def,
                                       virDomainDeviceDefPtr dev,
                                       virDomainDeviceInfoPtr info ATTRIBUTE_UNUSED,
                                       void *opaque ATTRIBUTE_UNUSED)
{
    return qemuDomainFillDeviceIsolationGroup(def, dev);
}


/**
 * qemuDomainSetupIsolationGroups:
 * @def: domain definition
 *
 * High-level function to set up isolation groups for all devices
 * and controllers in @def. Isolation groups will only be set up if
 * the guest architecture and machine type require it, so this
 * function can and should be called unconditionally before attempting
 * to assign any PCI address.
 *
 * Return: 0 on success, <0 on failure
 */
static int
qemuDomainSetupIsolationGroups(virDomainDefPtr def)
{
    int idx;
    int ret = -1;

    /* Only pSeries guests care about isolation groups at the moment */
    if (!qemuDomainIsPSeries(def))
        return 0;

    idx = virDomainControllerFind(def, VIR_DOMAIN_CONTROLLER_TYPE_PCI, 0);
    if (idx < 0)
        goto cleanup;

    /* We want to prevent hostdevs from being plugged into the default PHB:
     * we can make sure that doesn't happen by locking its isolation group */
    def->controllers[idx]->info.isolationGroupLocked = true;

    /* Fill in isolation groups for all other devices */
    if (virDomainDeviceInfoIterate(def,
                                   qemuDomainFillDeviceIsolationGroupIter,
                                   NULL) < 0) {
        goto cleanup;
    }

    ret = 0;

 cleanup:
    return ret;
}


1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
/**
 * qemuDomainFillDevicePCIConnectFlags:
 *
 * @def: the entire DomainDef
 * @dev: The device to be checked
 * @qemuCaps: as you'd expect
 *
 * Set the info->pciConnectFlags for a single device.
 *
 * No return value.
 */
1436
static void
1437 1438
qemuDomainFillDevicePCIConnectFlags(virDomainDefPtr def,
                                    virDomainDeviceDefPtr dev,
1439 1440
                                    virQEMUCapsPtr qemuCaps,
                                    virQEMUDriverPtr driver)
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
{
    virDomainDeviceInfoPtr info = virDomainDeviceGetInfo(dev);

    if (info) {
        /* qemuDomainDeviceCalculatePCIConnectFlags() is called with
         * the data setup in the ...IterData by ...IterInit() rather
         * than setting the values directly here.  It may seem like
         * pointless posturing, but it's done this way to eliminate
         * duplicated setup code while allowing more efficient
         * operation when it's being done repeatedly with the device
         * iterator (since qemuDomainFillAllPCIConnectFlags() only
         * calls ...IterInit() once for all devices).
         */
        qemuDomainFillDevicePCIConnectFlagsIterData data;

1456
        qemuDomainFillDevicePCIConnectFlagsIterInit(def, qemuCaps, driver, &data);
1457 1458

        info->pciConnectFlags
1459 1460
            = qemuDomainDeviceCalculatePCIConnectFlags(dev, data.driver,
                                                       data.pcieFlags,
1461 1462 1463 1464 1465
                                                       data.virtioFlags);
    }
}


1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
/**
 * qemuDomainFillDevicePCIExtensionFlags:
 *
 * @dev: The device to be checked
 * @info: virDomainDeviceInfo within the device
 * @qemuCaps: as you'd expect
 *
 * Set the info->pciAddressExtFlags for a single device.
 *
 * No return value.
 */
static void
qemuDomainFillDevicePCIExtensionFlags(virDomainDeviceDefPtr dev,
                                      virDomainDeviceInfoPtr info,
                                      virQEMUCapsPtr qemuCaps)
{
    info->pciAddrExtFlags =
        qemuDomainDeviceCalculatePCIAddressExtensionFlags(qemuCaps, dev);
}


1487
static int
1488
qemuDomainPCIAddressReserveNextAddr(virDomainPCIAddressSetPtr addrs,
1489
                                    virDomainDeviceInfoPtr dev)
1490
{
1491 1492
    return virDomainPCIAddressReserveNextAddr(addrs, dev,
                                              dev->pciConnectFlags, -1);
1493 1494 1495
}


1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
static int
qemuDomainAssignPCIAddressExtension(virDomainDefPtr def ATTRIBUTE_UNUSED,
                                    virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
                                    virDomainDeviceInfoPtr info,
                                    void *opaque)
{
    virDomainPCIAddressSetPtr addrs = opaque;
    virPCIDeviceAddressPtr addr = &info->addr.pci;

    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)
        addr->extFlags = info->pciAddrExtFlags;

    if (virDeviceInfoPCIAddressExtensionIsWanted(info))
        return virDomainPCIAddressExtensionReserveNextAddr(addrs, addr);

    return 0;
}

1514 1515 1516 1517 1518 1519 1520 1521
static int
qemuDomainCollectPCIAddress(virDomainDefPtr def ATTRIBUTE_UNUSED,
                            virDomainDeviceDefPtr device,
                            virDomainDeviceInfoPtr info,
                            void *opaque)
{
    virDomainPCIAddressSetPtr addrs = opaque;
    int ret = -1;
1522
    virPCIDeviceAddressPtr addr = &info->addr.pci;
1523

1524
    if (!virDeviceInfoPCIAddressIsPresent(info) ||
1525 1526
        ((device->type == VIR_DOMAIN_DEVICE_HOSTDEV) &&
         (device->data.hostdev->parent.type != VIR_DOMAIN_DEVICE_NONE))) {
1527 1528 1529 1530 1531 1532 1533
        /* If a hostdev has a parent, its info will be a part of the
         * parent, and will have its address collected during the scan
         * of the parent's device type.
        */
        return 0;
    }

1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
    /* If we get to here, the device has a PCI address assigned in the
     * config and we should mark it as in-use. But if the
     * pciConnectFlags are 0, then this device shouldn't have a PCI
     * address associated with it. *BUT* since there are cases in the
     * past where we've apparently allowed that, we need to pretend
     * for now that it's okay, otherwise an existing domain could
     * "disappear" from the list of domains due to a parse failure. We
     * can fix this by just forcing the pciConnectFlags to be
     * PCI_DEVICE (and then relying on validation functions to report
     * inappropriate address types.
     */
    if (!info->pciConnectFlags) {
1546
        char *addrStr = virPCIDeviceAddressAsString(&info->addr.pci);
1547 1548 1549 1550 1551 1552 1553 1554 1555

        VIR_WARN("qemuDomainDeviceCalculatePCIConnectFlags() thinks that the "
                 "device with PCI address %s should not have a PCI address",
                 addrStr ? addrStr : "(unknown)");
        VIR_FREE(addrStr);

        info->pciConnectFlags = VIR_PCI_CONNECT_TYPE_PCI_DEVICE;
    }

1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
    /* Ignore implicit controllers on slot 0:0:1.0:
     * implicit IDE controller on 0:0:1.1 (no qemu command line)
     * implicit USB controller on 0:0:1.2 (-usb)
     *
     * If the machine does have a PCI bus, they will get reserved
     * in qemuDomainAssignDevicePCISlots().
     */

    /* These are the IDE and USB controllers in the PIIX3, hardcoded
     * to bus 0 slot 1.  They cannot be attached to a PCIe slot, only
     * PCI.
     */
    if (device->type == VIR_DOMAIN_DEVICE_CONTROLLER && addr->domain == 0 &&
        addr->bus == 0 && addr->slot == 1) {
        virDomainControllerDefPtr cont = device->data.controller;

        if ((cont->type == VIR_DOMAIN_CONTROLLER_TYPE_IDE && cont->idx == 0 &&
             addr->function == 1) ||
            (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_USB && cont->idx == 0 &&
             (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX3_UHCI ||
1576 1577
              cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_DEFAULT) &&
             addr->function == 2)) {
1578 1579 1580 1581 1582 1583 1584
            /* Note the check for nbuses > 0 - if there are no PCI
             * buses, we skip this check. This is a quirk required for
             * some machinetypes such as s390, which pretend to have a
             * PCI bus for long enough to generate the "-usb" on the
             * commandline, but that don't really care if a PCI bus
             * actually exists. */
            if (addrs->nbuses > 0 &&
1585
                !(addrs->buses[0].flags & VIR_PCI_CONNECT_TYPE_PCI_DEVICE)) {
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Bus 0 must be PCI for integrated PIIX3 "
                                 "USB or IDE controllers"));
                return -1;
            } else {
                return 0;
            }
        }
    }

1596
    if (virDomainPCIAddressReserveAddr(addrs, addr,
1597 1598
                                       info->pciConnectFlags,
                                       info->isolationGroup) < 0) {
1599
        goto cleanup;
1600
    }
1601 1602 1603 1604 1605 1606

    ret = 0;
 cleanup:
    return ret;
}

1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
static int
qemuDomainCollectPCIAddressExtension(virDomainDefPtr def ATTRIBUTE_UNUSED,
                                     virDomainDeviceDefPtr device,
                                     virDomainDeviceInfoPtr info,
                                     void *opaque)
{
    virDomainPCIAddressSetPtr addrs = opaque;
    virPCIDeviceAddressPtr addr = &info->addr.pci;

    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)
        addr->extFlags = info->pciAddrExtFlags;

    if (!virDeviceInfoPCIAddressExtensionIsPresent(info) ||
        ((device->type == VIR_DOMAIN_DEVICE_HOSTDEV) &&
         (device->data.hostdev->parent.type != VIR_DOMAIN_DEVICE_NONE))) {
        /* If a hostdev has a parent, its info will be a part of the
         * parent, and will have its address collected during the scan
         * of the parent's device type.
        */
        return 0;
    }

    return virDomainPCIAddressExtensionReserveAddr(addrs, addr);
}

1632 1633
static virDomainPCIAddressSetPtr
qemuDomainPCIAddressSetCreate(virDomainDefPtr def,
1634
                              virQEMUCapsPtr qemuCaps,
1635 1636 1637 1638 1639
                              unsigned int nbuses,
                              bool dryRun)
{
    virDomainPCIAddressSetPtr addrs;
    size_t i;
1640 1641
    bool hasPCIeRoot = false;
    virDomainControllerModelPCI defaultModel;
1642
    virPCIDeviceAddressExtensionFlags extFlags = VIR_PCI_ADDRESS_EXTENSION_NONE;
1643

1644 1645 1646 1647
    if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_ZPCI))
        extFlags |= VIR_PCI_ADDRESS_EXTENSION_ZPCI;

    if ((addrs = virDomainPCIAddressSetAlloc(nbuses, extFlags)) == NULL)
1648 1649 1650 1651
        return NULL;

    addrs->dryRun = dryRun;

1652 1653
    /* pSeries domains support multiple pci-root controllers */
    if (qemuDomainIsPSeries(def))
1654
        addrs->areMultipleRootsSupported = true;
1655

1656 1657 1658
    if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_PCIE_PCI_BRIDGE))
        addrs->isPCIeToPCIBridgeSupported = true;

1659
    for (i = 0; i < def->ncontrollers; i++) {
1660 1661
        virDomainControllerDefPtr cont = def->controllers[i];
        size_t idx = cont->idx;
1662

1663
        if (cont->type != VIR_DOMAIN_CONTROLLER_TYPE_PCI)
1664 1665 1666 1667 1668
            continue;

        if (idx >= addrs->nbuses) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Inappropriate new pci controller index %zu "
1669
                             "exceeds addrs array length"), idx);
1670 1671 1672
            goto error;
        }

1673
        if (virDomainPCIAddressBusSetModel(&addrs->buses[idx], cont->model) < 0)
1674
            goto error;
1675

1676 1677 1678 1679
        /* Forward the information about isolation groups */
        addrs->buses[idx].isolationGroup = cont->info.isolationGroup;
        addrs->buses[idx].isolationGroupLocked = cont->info.isolationGroupLocked;

1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
        if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT)
            hasPCIeRoot = true;
    }

    if (nbuses > 0 && !addrs->buses[0].model) {
        /* This is just here to replicate a safety measure already in
         * an older version of this code. In practice, the root bus
         * should have already been added at index 0 prior to
         * assigning addresses to devices.
         */
        if (virDomainPCIAddressBusSetModel(&addrs->buses[0],
                                           VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT) < 0)
            goto error;
    }

    /* Now fill in a reasonable model for all the buses in the set
     * that don't yet have a corresponding controller in the domain
     * config.
     */
1699 1700 1701 1702
    if (qemuDomainIsPSeries(def)) {
        /* pSeries guests should use PHBs (pci-root controllers) */
        defaultModel = VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT;
    } else if (hasPCIeRoot) {
1703
        defaultModel = VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT_PORT;
1704
    } else {
1705
        defaultModel = VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE;
1706
    }
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718

    for (i = 1; i < addrs->nbuses; i++) {

        if (addrs->buses[i].model)
            continue;

        if (virDomainPCIAddressBusSetModel(&addrs->buses[i], defaultModel) < 0)
            goto error;

        VIR_DEBUG("Auto-adding <controller type='pci' model='%s' index='%zu'/>",
                  virDomainControllerModelPCITypeToString(defaultModel), i);
    }
1719 1720 1721 1722

    if (virDomainDeviceInfoIterate(def, qemuDomainCollectPCIAddress, addrs) < 0)
        goto error;

1723 1724 1725 1726 1727 1728
    if (virDomainDeviceInfoIterate(def,
                                   qemuDomainCollectPCIAddressExtension,
                                   addrs) < 0) {
        goto error;
    }

1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
    return addrs;

 error:
    virDomainPCIAddressSetFree(addrs);
    return NULL;
}


static int
qemuDomainValidateDevicePCISlotsPIIX3(virDomainDefPtr def,
                                      virQEMUCapsPtr qemuCaps,
                                      virDomainPCIAddressSetPtr addrs)
{
    int ret = -1;
    size_t i;
1744
    virPCIDeviceAddress tmp_addr;
1745 1746
    bool qemuDeviceVideoUsable = virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIDEO_PRIMARY);
    char *addrStr = NULL;
1747 1748
    virDomainPCIConnectFlags flags = (VIR_PCI_CONNECT_HOTPLUGGABLE
                                      | VIR_PCI_CONNECT_TYPE_PCI_DEVICE);
1749 1750 1751

    /* Verify that first IDE and USB controllers (if any) is on the PIIX3, fn 1 */
    for (i = 0; i < def->ncontrollers; i++) {
1752 1753
        virDomainControllerDefPtr cont = def->controllers[i];

1754
        /* First IDE controller lives on the PIIX3 at slot=1, function=1 */
1755 1756
        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_IDE &&
            cont->idx == 0) {
1757
            if (virDeviceInfoPCIAddressIsPresent(&cont->info)) {
1758 1759 1760 1761
                if (cont->info.addr.pci.domain != 0 ||
                    cont->info.addr.pci.bus != 0 ||
                    cont->info.addr.pci.slot != 1 ||
                    cont->info.addr.pci.function != 1) {
1762 1763 1764 1765 1766
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("Primary IDE controller must have PCI address 0:0:1.1"));
                    goto cleanup;
                }
            } else {
1767 1768 1769 1770 1771
                cont->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
                cont->info.addr.pci.domain = 0;
                cont->info.addr.pci.bus = 0;
                cont->info.addr.pci.slot = 1;
                cont->info.addr.pci.function = 1;
1772
            }
1773 1774 1775
        } else if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
                   cont->idx == 0 &&
                   (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX3_UHCI ||
1776
                    cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_DEFAULT)) {
1777
            if (virDeviceInfoPCIAddressIsPresent(&cont->info)) {
1778 1779 1780 1781
                if (cont->info.addr.pci.domain != 0 ||
                    cont->info.addr.pci.bus != 0 ||
                    cont->info.addr.pci.slot != 1 ||
                    cont->info.addr.pci.function != 2) {
1782
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1783
                                   _("PIIX3 USB controller at index 0 must have PCI address 0:0:1.2"));
1784 1785 1786
                    goto cleanup;
                }
            } else {
1787 1788 1789 1790 1791
                cont->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
                cont->info.addr.pci.domain = 0;
                cont->info.addr.pci.bus = 0;
                cont->info.addr.pci.slot = 1;
                cont->info.addr.pci.function = 2;
1792
            }
1793 1794 1795
        } else {
            /* this controller is not skipped in qemuDomainCollectPCIAddress */
            continue;
1796
        }
1797 1798 1799
        if (addrs->nbuses &&
            virDomainPCIAddressReserveAddr(addrs, &cont->info.addr.pci, flags, 0) < 0)
            goto cleanup;
1800 1801
    }

1802
    /* Implicit PIIX3 devices living on slot 1 not handled above */
1803 1804 1805
    if (addrs->nbuses) {
        memset(&tmp_addr, 0, sizeof(tmp_addr));
        tmp_addr.slot = 1;
1806 1807 1808 1809 1810
        /* ISA Bridge at 00:01.0 */
        if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags, 0) < 0)
            goto cleanup;
        /* Bridge at 00:01.3 */
        tmp_addr.function = 3;
1811
        if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags, 0) < 0)
1812 1813 1814
            goto cleanup;
    }

1815 1816
    if (def->nvideos > 0 &&
        def->videos[0]->type != VIR_DOMAIN_VIDEO_TYPE_NONE) {
1817 1818 1819 1820 1821 1822 1823
        /* Because the PIIX3 integrated IDE/USB controllers are
         * already at slot 1, when qemu looks for the first free slot
         * to place the VGA controller (which is always the first
         * device added after integrated devices), it *always* ends up
         * at slot 2.
         */
        virDomainVideoDefPtr primaryVideo = def->videos[0];
1824

1825
        if (virDeviceInfoPCIAddressIsWanted(&primaryVideo->info)) {
1826 1827 1828
            memset(&tmp_addr, 0, sizeof(tmp_addr));
            tmp_addr.slot = 2;

1829
            if (!(addrStr = virPCIDeviceAddressAsString(&tmp_addr)))
1830 1831
                goto cleanup;
            if (!virDomainPCIAddressValidate(addrs, &tmp_addr,
1832
                                             addrStr, flags, true))
1833 1834 1835 1836
                goto cleanup;

            if (virDomainPCIAddressSlotInUse(addrs, &tmp_addr)) {
                if (qemuDeviceVideoUsable) {
1837
                    if (qemuDomainPCIAddressReserveNextAddr(addrs,
1838
                                                            &primaryVideo->info) < 0) {
1839
                        goto cleanup;
1840
                    }
1841 1842 1843 1844 1845 1846 1847
                } else {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("PCI address 0:0:2.0 is in use, "
                                     "QEMU needs it for primary video"));
                    goto cleanup;
                }
            } else {
1848
                if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags, 0) < 0)
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
                    goto cleanup;
                primaryVideo->info.addr.pci = tmp_addr;
                primaryVideo->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
            }
        } else if (!qemuDeviceVideoUsable) {
            if (primaryVideo->info.addr.pci.domain != 0 ||
                primaryVideo->info.addr.pci.bus != 0 ||
                primaryVideo->info.addr.pci.slot != 2 ||
                primaryVideo->info.addr.pci.function != 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Primary video card must have PCI address 0:0:2.0"));
                goto cleanup;
            }
            /* If TYPE == PCI, then qemuDomainCollectPCIAddress() function
             * has already reserved the address, so we must skip */
        }
    } else if (addrs->nbuses && !qemuDeviceVideoUsable) {
        memset(&tmp_addr, 0, sizeof(tmp_addr));
        tmp_addr.slot = 2;

        if (virDomainPCIAddressSlotInUse(addrs, &tmp_addr)) {
            VIR_DEBUG("PCI address 0:0:2.0 in use, future addition of a video"
                      " device will not be possible without manual"
                      " intervention");
1873
        } else if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags, 0) < 0) {
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
            goto cleanup;
        }
    }
    ret = 0;
 cleanup:
    VIR_FREE(addrStr);
    return ret;
}


static int
qemuDomainValidateDevicePCISlotsQ35(virDomainDefPtr def,
                                    virQEMUCapsPtr qemuCaps,
                                    virDomainPCIAddressSetPtr addrs)
{
    int ret = -1;
    size_t i;
1891
    virPCIDeviceAddress tmp_addr;
1892 1893
    bool qemuDeviceVideoUsable = virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIDEO_PRIMARY);
    char *addrStr = NULL;
1894
    virDomainPCIConnectFlags flags = VIR_PCI_CONNECT_TYPE_PCIE_DEVICE;
1895 1896

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

        switch (cont->type) {
1900 1901 1902 1903 1904
        case VIR_DOMAIN_CONTROLLER_TYPE_SATA:
            /* Verify that the first SATA controller is at 00:1F.2 the
             * q35 machine type *always* has a SATA controller at this
             * address.
             */
1905
            if (cont->idx == 0) {
1906
                if (virDeviceInfoPCIAddressIsPresent(&cont->info)) {
1907 1908 1909 1910
                    if (cont->info.addr.pci.domain != 0 ||
                        cont->info.addr.pci.bus != 0 ||
                        cont->info.addr.pci.slot != 0x1F ||
                        cont->info.addr.pci.function != 2) {
1911 1912 1913 1914 1915
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("Primary SATA controller must have PCI address 0:0:1f.2"));
                        goto cleanup;
                    }
                } else {
1916 1917 1918 1919 1920
                    cont->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
                    cont->info.addr.pci.domain = 0;
                    cont->info.addr.pci.bus = 0;
                    cont->info.addr.pci.slot = 0x1F;
                    cont->info.addr.pci.function = 2;
1921 1922 1923 1924 1925
                }
            }
            break;

        case VIR_DOMAIN_CONTROLLER_TYPE_USB:
1926 1927
            if ((cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI1) &&
                (cont->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)) {
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
                /* Try to assign the first found USB2 controller to
                 * 00:1D.0 and 2nd to 00:1A.0 (because that is their
                 * standard location on real Q35 hardware) unless they
                 * are already taken, but don't insist on it.
                 *
                 * (NB: all other controllers at the same index will
                 * get assigned to the same slot as the UHCI1 when
                 * addresses are later assigned to all devices.)
                 */
                bool assign = false;

                memset(&tmp_addr, 0, sizeof(tmp_addr));
                tmp_addr.slot = 0x1D;
                if (!virDomainPCIAddressSlotInUse(addrs, &tmp_addr)) {
                    assign = true;
                } else {
                    tmp_addr.slot = 0x1A;
                    if (!virDomainPCIAddressSlotInUse(addrs, &tmp_addr))
                        assign = true;
                }
                if (assign) {
1949
                    if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags, 0) < 0)
1950
                        goto cleanup;
1951

1952 1953 1954 1955 1956 1957
                    cont->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
                    cont->info.addr.pci.domain = 0;
                    cont->info.addr.pci.bus = 0;
                    cont->info.addr.pci.slot = tmp_addr.slot;
                    cont->info.addr.pci.function = 0;
                    cont->info.addr.pci.multi = VIR_TRISTATE_SWITCH_ON;
1958 1959 1960 1961 1962
                }
            }
            break;

        case VIR_DOMAIN_CONTROLLER_TYPE_PCI:
1963 1964
            if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE &&
                cont->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
1965 1966 1967 1968 1969 1970 1971
                /* Try to assign this bridge to 00:1E.0 (because that
                * is its standard location on real hardware) unless
                * it's already taken, but don't insist on it.
                */
                memset(&tmp_addr, 0, sizeof(tmp_addr));
                tmp_addr.slot = 0x1E;
                if (!virDomainPCIAddressSlotInUse(addrs, &tmp_addr)) {
1972
                    if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags, 0) < 0)
1973
                        goto cleanup;
1974

1975 1976 1977 1978 1979
                    cont->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
                    cont->info.addr.pci.domain = 0;
                    cont->info.addr.pci.bus = 0;
                    cont->info.addr.pci.slot = 0x1E;
                    cont->info.addr.pci.function = 0;
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
                }
            }
            break;
        }
    }

    /* Reserve slot 0x1F function 0 (ISA bridge, not in config model)
     * and function 3 (SMBus, also not (yet) in config model). As with
     * the SATA controller, these devices are always present in a q35
     * machine; there is no way to not have them.
     */
    if (addrs->nbuses) {
        memset(&tmp_addr, 0, sizeof(tmp_addr));
        tmp_addr.slot = 0x1F;
        tmp_addr.function = 0;
        tmp_addr.multi = VIR_TRISTATE_SWITCH_ON;
1996
        if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags, 0) < 0)
1997
           goto cleanup;
1998

1999 2000
        tmp_addr.function = 3;
        tmp_addr.multi = VIR_TRISTATE_SWITCH_ABSENT;
2001
        if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags, 0) < 0)
2002 2003 2004
           goto cleanup;
    }

2005 2006
    if (def->nvideos > 0 &&
        def->videos[0]->type != VIR_DOMAIN_VIDEO_TYPE_NONE) {
2007 2008
        /* NB: unlike the pc machinetypes, on q35 machinetypes the
         * integrated devices are at slot 0x1f, so when qemu looks for
2009
         * the first free slot for the first VGA, it will always be at
2010 2011 2012 2013
         * slot 1 (which was used up by the integrated PIIX3 devices
         * on pc machinetypes).
         */
        virDomainVideoDefPtr primaryVideo = def->videos[0];
2014
        if (virDeviceInfoPCIAddressIsWanted(&primaryVideo->info)) {
2015 2016 2017
            memset(&tmp_addr, 0, sizeof(tmp_addr));
            tmp_addr.slot = 1;

2018
            if (!(addrStr = virPCIDeviceAddressAsString(&tmp_addr)))
2019 2020
                goto cleanup;
            if (!virDomainPCIAddressValidate(addrs, &tmp_addr,
2021
                                             addrStr, flags, true))
2022 2023 2024 2025
                goto cleanup;

            if (virDomainPCIAddressSlotInUse(addrs, &tmp_addr)) {
                if (qemuDeviceVideoUsable) {
2026
                    if (qemuDomainPCIAddressReserveNextAddr(addrs,
2027
                                                            &primaryVideo->info) < 0)
2028 2029 2030 2031 2032 2033 2034 2035
                        goto cleanup;
                } else {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("PCI address 0:0:1.0 is in use, "
                                     "QEMU needs it for primary video"));
                    goto cleanup;
                }
            } else {
2036
                if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags, 0) < 0)
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
                    goto cleanup;
                primaryVideo->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
                primaryVideo->info.addr.pci = tmp_addr;
            }
        } else if (!qemuDeviceVideoUsable) {
            if (primaryVideo->info.addr.pci.domain != 0 ||
                primaryVideo->info.addr.pci.bus != 0 ||
                primaryVideo->info.addr.pci.slot != 1 ||
                primaryVideo->info.addr.pci.function != 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Primary video card must have PCI address 0:0:1.0"));
                goto cleanup;
            }
            /* If TYPE == PCI, then qemuDomainCollectPCIAddress() function
             * has already reserved the address, so we must skip */
        }
    } else if (addrs->nbuses && !qemuDeviceVideoUsable) {
        memset(&tmp_addr, 0, sizeof(tmp_addr));
        tmp_addr.slot = 1;

        if (virDomainPCIAddressSlotInUse(addrs, &tmp_addr)) {
            VIR_DEBUG("PCI address 0:0:1.0 in use, future addition of a video"
                      " device will not be possible without manual"
                      " intervention");
            virResetLastError();
2062
        } else if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags, 0) < 0) {
2063 2064 2065
            goto cleanup;
        }
    }
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079

    memset(&tmp_addr, 0, sizeof(tmp_addr));
    tmp_addr.slot = 0x1B;
    if (!virDomainPCIAddressSlotInUse(addrs, &tmp_addr)) {
        /* Since real Q35 hardware has an ICH9 chip that has an
         * integrated HD audio device at 0000:00:1B.0 put any
         * unaddressed ICH9 audio device at that address if it's not
         * already taken. If there's something already there, let the
         * normal device addressing assign something later.
         */
        for (i = 0; i < def->nsounds; i++) {
            virDomainSoundDefPtr sound = def->sounds[i];

            if (sound->model != VIR_DOMAIN_SOUND_MODEL_ICH9 ||
2080
                !virDeviceInfoPCIAddressIsWanted(&sound->info)) {
2081 2082
                continue;
            }
2083
            if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags, 0) < 0)
2084 2085 2086 2087 2088 2089 2090 2091
                goto cleanup;

            sound->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
            sound->info.addr.pci = tmp_addr;
            break;
        }
    }

2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
    ret = 0;
 cleanup:
    VIR_FREE(addrStr);
    return ret;
}


static int
qemuDomainValidateDevicePCISlotsChipsets(virDomainDefPtr def,
                                         virQEMUCapsPtr qemuCaps,
                                         virDomainPCIAddressSetPtr addrs)
{
2104
    if (qemuDomainIsI440FX(def) &&
2105 2106 2107 2108
        qemuDomainValidateDevicePCISlotsPIIX3(def, qemuCaps, addrs) < 0) {
        return -1;
    }

2109
    if (qemuDomainIsQ35(def) &&
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
        qemuDomainValidateDevicePCISlotsQ35(def, qemuCaps, addrs) < 0) {
        return -1;
    }

    return 0;
}


/*
 * This assigns static PCI slots to all configured devices.
 * The ordering here is chosen to match the ordering used
 * with old QEMU < 0.12, so that if a user updates a QEMU
 * host from old QEMU to QEMU >= 0.12, their guests should
 * get PCI addresses in the same order as before.
 *
 * NB, if they previously hotplugged devices then all bets
 * are off. Hotplug for old QEMU was unfixably broken wrt
 * to stable PCI addressing.
 *
 * Order is:
 *
 *  - Host bridge (slot 0)
 *  - PIIX3 ISA bridge, IDE controller, something else unknown, USB controller (slot 1)
 *  - Video (slot 2)
 *
 *  - These integrated devices were already added by
2136
 *    qemuDomainValidateDevicePCISlotsChipsets invoked right before this function
2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
 *
 * Incrementally assign slots from 3 onwards:
 *
 *  - Net
 *  - Sound
 *  - SCSI controllers
 *  - VirtIO block
 *  - VirtIO balloon
 *  - Host device passthrough
 *  - Watchdog
 *  - pci serial devices
 *
 * Prior to this function being invoked, qemuDomainCollectPCIAddress() will have
 * added all existing PCI addresses from the 'def' to 'addrs'. Thus this
 * function must only try to reserve addresses if info.type == NONE and
 * skip over info.type == PCI
 */
static int
qemuDomainAssignDevicePCISlots(virDomainDefPtr def,
                               virQEMUCapsPtr qemuCaps,
                               virDomainPCIAddressSetPtr addrs)
{
    size_t i, j;

    /* PCI controllers */
    for (i = 0; i < def->ncontrollers; i++) {
2163 2164 2165 2166
        virDomainControllerDefPtr cont = def->controllers[i];

        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI) {
            virDomainControllerModelPCI model = cont->model;
2167

2168 2169
            if (model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT ||
                model == VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT ||
2170
                !virDeviceInfoPCIAddressIsWanted(&cont->info))
2171
                continue;
2172

2173
            if (qemuDomainPCIAddressReserveNextAddr(addrs, &cont->info) < 0)
2174 2175 2176 2177 2178
                goto error;
        }
    }

    for (i = 0; i < def->nfss; i++) {
2179
        if (!virDeviceInfoPCIAddressIsWanted(&def->fss[i]->info))
2180 2181 2182 2183
            continue;

        /* Only support VirtIO-9p-pci so far. If that changes,
         * we might need to skip devices here */
2184
        if (qemuDomainPCIAddressReserveNextAddr(addrs, &def->fss[i]->info) < 0)
2185 2186 2187 2188 2189
            goto error;
    }

    /* Network interfaces */
    for (i = 0; i < def->nnets; i++) {
2190 2191
        virDomainNetDefPtr net = def->nets[i];

2192 2193 2194 2195
        /* type='hostdev' network devices might be USB, and are also
         * in hostdevs list anyway, so handle them with other hostdevs
         * instead of here.
         */
2196
        if ((net->type == VIR_DOMAIN_NET_TYPE_HOSTDEV) ||
2197
            !virDeviceInfoPCIAddressIsWanted(&net->info)) {
2198 2199
            continue;
        }
2200

2201
        if (qemuDomainPCIAddressReserveNextAddr(addrs, &net->info) < 0)
2202 2203 2204 2205 2206
            goto error;
    }

    /* Sound cards */
    for (i = 0; i < def->nsounds; i++) {
2207 2208
        virDomainSoundDefPtr sound = def->sounds[i];

2209
        if (!virDeviceInfoPCIAddressIsWanted(&sound->info))
2210
            continue;
2211

2212
        /* Skip ISA sound card, PCSPK and usb-audio */
2213 2214 2215
        if (sound->model == VIR_DOMAIN_SOUND_MODEL_SB16 ||
            sound->model == VIR_DOMAIN_SOUND_MODEL_PCSPK ||
            sound->model == VIR_DOMAIN_SOUND_MODEL_USB) {
2216
            continue;
2217
        }
2218

2219
        if (qemuDomainPCIAddressReserveNextAddr(addrs, &sound->info) < 0)
2220 2221 2222 2223 2224
            goto error;
    }

    /* Device controllers (SCSI, USB, but not IDE, FDC or CCID) */
    for (i = 0; i < def->ncontrollers; i++) {
2225 2226
        virDomainControllerDefPtr cont = def->controllers[i];

2227
        /* PCI controllers have been dealt with earlier */
2228
        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI)
2229 2230 2231
            continue;

        /* USB controller model 'none' doesn't need a PCI address */
2232 2233
        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
            cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE)
2234 2235 2236
            continue;

        /* FDC lives behind the ISA bridge; CCID is a usb device */
2237 2238
        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_FDC ||
            cont->type == VIR_DOMAIN_CONTROLLER_TYPE_CCID)
2239 2240 2241 2242
            continue;

        /* First IDE controller lives on the PIIX3 at slot=1, function=1,
           dealt with earlier on*/
2243 2244
        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_IDE &&
            cont->idx == 0)
2245 2246
            continue;

2247
        if (!virDeviceInfoPCIAddressIsWanted(&cont->info))
2248 2249 2250
            continue;

        /* USB2 needs special handling to put all companions in the same slot */
2251
        if (IS_USB2_CONTROLLER(cont)) {
2252
            virPCIDeviceAddress addr = {0};
2253 2254 2255 2256
            bool foundAddr = false;

            for (j = 0; j < def->ncontrollers; j++) {
                if (IS_USB2_CONTROLLER(def->controllers[j]) &&
2257
                    def->controllers[j]->idx == cont->idx &&
2258
                    virDeviceInfoPCIAddressIsPresent(&def->controllers[j]->info)) {
2259 2260 2261 2262 2263 2264
                    addr = def->controllers[j]->info.addr.pci;
                    foundAddr = true;
                    break;
                }
            }

2265
            switch (cont->model) {
2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_EHCI1:
                addr.function = 7;
                addr.multi = VIR_TRISTATE_SWITCH_ABSENT;
                break;
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI1:
                addr.function = 0;
                addr.multi = VIR_TRISTATE_SWITCH_ON;
                break;
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI2:
                addr.function = 1;
                addr.multi = VIR_TRISTATE_SWITCH_ABSENT;
                break;
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI3:
                addr.function = 2;
                addr.multi = VIR_TRISTATE_SWITCH_ABSENT;
                break;
            }

2284 2285
            if (foundAddr) {
                /* Reserve this function on the slot we found */
2286
                if (virDomainPCIAddressReserveAddr(addrs, &addr,
2287 2288
                                                   cont->info.pciConnectFlags,
                                                   cont->info.isolationGroup) < 0) {
2289
                    goto error;
2290
                }
2291

2292 2293 2294 2295 2296
                cont->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
                cont->info.addr.pci = addr;
            } else {
                /* This is the first part of the controller, so need
                 * to find a free slot & then reserve this function */
2297 2298 2299
                if (virDomainPCIAddressReserveNextAddr(addrs, &cont->info,
                                                       cont->info.pciConnectFlags,
                                                       addr.function) < 0) {
2300 2301
                    goto error;
                }
2302

2303
                cont->info.addr.pci.multi = addr.multi;
2304 2305
            }
        } else {
2306
            if (qemuDomainPCIAddressReserveNextAddr(addrs, &cont->info) < 0)
2307
                 goto error;
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317
        }
    }

    /* Disks (VirtIO only for now) */
    for (i = 0; i < def->ndisks; i++) {
        /* Only VirtIO disks use PCI addrs */
        if (def->disks[i]->bus != VIR_DOMAIN_DISK_BUS_VIRTIO)
            continue;

        /* don't touch s390 devices */
2318
        if (virDeviceInfoPCIAddressIsPresent(&def->disks[i]->info) ||
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
            def->disks[i]->info.type ==
            VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390 ||
            def->disks[i]->info.type ==
            VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW)
            continue;

        /* Also ignore virtio-mmio disks if our machine allows them */
        if (def->disks[i]->info.type ==
            VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO &&
            virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIRTIO_MMIO))
            continue;

2331
        if (!virDeviceInfoPCIAddressIsWanted(&def->disks[i]->info)) {
2332 2333 2334 2335 2336 2337
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("virtio disk cannot have an address of type '%s'"),
                           virDomainDeviceAddressTypeToString(def->disks[i]->info.type));
            goto error;
        }

2338
        if (qemuDomainPCIAddressReserveNextAddr(addrs, &def->disks[i]->info) < 0)
2339 2340 2341 2342 2343
            goto error;
    }

    /* Host PCI devices */
    for (i = 0; i < def->nhostdevs; i++) {
2344
        virDomainHostdevSubsysPtr subsys = &def->hostdevs[i]->source.subsys;
2345
        if (!virDeviceInfoPCIAddressIsWanted(def->hostdevs[i]->info))
2346
            continue;
2347 2348
        if (def->hostdevs[i]->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
            continue;
2349 2350 2351 2352
        if (subsys->type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
            subsys->type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI_HOST &&
            !(subsys->type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_MDEV &&
              subsys->u.mdev.model == VIR_MDEV_MODEL_TYPE_VFIO_PCI)) {
2353
            continue;
2354
        }
2355

2356
        if (qemuDomainPCIAddressReserveNextAddr(addrs,
2357
                                                def->hostdevs[i]->info) < 0)
2358 2359 2360
            goto error;
    }

2361 2362
    /* memballoon. the qemu driver only accepts virtio memballoon devices */
    if (virDomainDefHasMemballoon(def) &&
2363
        virDeviceInfoPCIAddressIsWanted(&def->memballoon->info)) {
2364
        if (qemuDomainPCIAddressReserveNextAddr(addrs,
2365
                                                &def->memballoon->info) < 0)
2366 2367 2368
            goto error;
    }

2369
    /* the qemu driver only accepts virtio rng devices */
2370
    for (i = 0; i < def->nrngs; i++) {
2371
        if (!virDeviceInfoPCIAddressIsWanted(&def->rngs[i]->info))
2372 2373
            continue;

2374
        if (qemuDomainPCIAddressReserveNextAddr(addrs, &def->rngs[i]->info) < 0)
2375 2376 2377 2378 2379 2380
            goto error;
    }

    /* A watchdog - check if it is a PCI device */
    if (def->watchdog &&
        def->watchdog->model == VIR_DOMAIN_WATCHDOG_MODEL_I6300ESB &&
2381
        virDeviceInfoPCIAddressIsWanted(&def->watchdog->info)) {
2382
        if (qemuDomainPCIAddressReserveNextAddr(addrs, &def->watchdog->info) < 0)
2383 2384 2385
            goto error;
    }

2386 2387
    /* Video devices */
    for (i = 0; i < def->nvideos; i++) {
2388 2389
        if (def->videos[i]->type == VIR_DOMAIN_VIDEO_TYPE_NONE)
            continue;
2390

2391
        if (!virDeviceInfoPCIAddressIsWanted(&def->videos[i]->info))
2392
            continue;
2393

2394
        if (qemuDomainPCIAddressReserveNextAddr(addrs, &def->videos[i]->info) < 0)
2395 2396 2397 2398 2399
            goto error;
    }

    /* Shared Memory */
    for (i = 0; i < def->nshmems; i++) {
2400
        if (!virDeviceInfoPCIAddressIsWanted(&def->shmems[i]->info))
2401 2402
            continue;

2403
        if (qemuDomainPCIAddressReserveNextAddr(addrs, &def->shmems[i]->info) < 0)
2404 2405 2406
            goto error;
    }
    for (i = 0; i < def->ninputs; i++) {
2407
        if (def->inputs[i]->bus != VIR_DOMAIN_INPUT_BUS_VIRTIO ||
2408
            !virDeviceInfoPCIAddressIsWanted(&def->inputs[i]->info))
2409 2410
            continue;

2411
        if (qemuDomainPCIAddressReserveNextAddr(addrs, &def->inputs[i]->info) < 0)
2412 2413 2414 2415 2416 2417 2418 2419
            goto error;
    }
    for (i = 0; i < def->nparallels; i++) {
        /* Nada - none are PCI based (yet) */
    }
    for (i = 0; i < def->nserials; i++) {
        virDomainChrDefPtr chr = def->serials[i];

2420
        if (chr->targetType != VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_PCI ||
2421
            !virDeviceInfoPCIAddressIsWanted(&chr->info))
2422 2423
            continue;

2424
        if (qemuDomainPCIAddressReserveNextAddr(addrs, &chr->info) < 0)
2425 2426 2427 2428 2429 2430 2431 2432 2433
            goto error;
    }
    for (i = 0; i < def->nchannels; i++) {
        /* Nada - none are PCI based (yet) */
    }
    for (i = 0; i < def->nhubs; i++) {
        /* Nada - none are PCI based (yet) */
    }

J
Ján Tomko 已提交
2434
    if (def->vsock &&
2435
        virDeviceInfoPCIAddressIsWanted(&def->vsock->info)) {
J
Ján Tomko 已提交
2436 2437 2438 2439 2440 2441

        if (qemuDomainPCIAddressReserveNextAddr(addrs,
                                                &def->vsock->info) < 0)
            goto error;
    }

2442 2443 2444 2445 2446 2447 2448
    return 0;

 error:
    return -1;
}


2449
static void
2450
qemuDomainPCIControllerSetDefaultModelName(virDomainControllerDefPtr cont,
2451
                                           virDomainDefPtr def,
2452
                                           virQEMUCapsPtr qemuCaps)
2453 2454 2455 2456 2457 2458
{
    int *modelName = &cont->opts.pciopts.modelName;

    /* make sure it's not already set */
    if (*modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_NONE)
        return;
2459

2460 2461 2462 2463 2464 2465 2466
    switch ((virDomainControllerModelPCI)cont->model) {
    case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
        *modelName = VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PCI_BRIDGE;
        break;
    case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
        *modelName = VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_I82801B11_BRIDGE;
        break;
2467 2468 2469
    case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_TO_PCI_BRIDGE:
        *modelName = VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PCIE_PCI_BRIDGE;
        break;
2470
    case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT_PORT:
2471 2472 2473 2474 2475 2476
        /* Use generic PCIe Root Ports if available, falling back to
         * ioh3420 otherwise */
        if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_PCIE_ROOT_PORT))
            *modelName = VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PCIE_ROOT_PORT;
        else
            *modelName = VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_IOH3420;
2477 2478 2479 2480 2481 2482 2483
        break;
    case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_UPSTREAM_PORT:
        *modelName = VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_X3130_UPSTREAM;
        break;
    case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_DOWNSTREAM_PORT:
        *modelName = VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_XIO3130_DOWNSTREAM;
        break;
2484
    case VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS:
2485 2486
        *modelName = VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PXB;
        break;
2487
    case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS:
2488 2489
        *modelName = VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PXB_PCIE;
        break;
2490
    case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
2491 2492 2493
        if (qemuDomainIsPSeries(def))
            *modelName = VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_SPAPR_PCI_HOST_BRIDGE;
        break;
2494
    case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
2495
    case VIR_DOMAIN_CONTROLLER_MODEL_PCI_DEFAULT:
2496 2497 2498 2499 2500 2501
    case VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST:
        break;
    }
}


2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
/**
 * qemuDomainAddressFindNewTargetIndex:
 * @def: domain definition
 *
 * Find a target index that can be used for a PCI controller.
 *
 * Returns: an unused target index, or -1 if all available target
 *          indexes are already taken.
 */
static int
qemuDomainAddressFindNewTargetIndex(virDomainDefPtr def)
{
    int targetIndex;
    int ret = -1;

    /* Try all indexes between 1 and 31 - QEMU only supports 32
     * PHBs, and 0 is reserved for the default, implicit one */
    for (targetIndex = 1; targetIndex <= 31; targetIndex++) {
        bool found = false;
        size_t i;

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

            /* Skip everything but PHBs */
2527
            if (!virDomainControllerIsPSeriesPHB(cont))
2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549
                continue;

            /* Stop looking as soon as we find a PHB that's
             * already using this specific target index */
            if (cont->opts.pciopts.targetIndex == targetIndex) {
                found = true;
                break;
            }
        }

        /* If no existing PCI controller uses this index, great,
         * it means it's free and we can return it to the caller */
        if (!found) {
            ret = targetIndex;
            break;
        }
    }

    return ret;
}


2550 2551 2552
static int
qemuDomainAddressFindNewBusNr(virDomainDefPtr def)
{
2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595
    /* Try to find a nice default for busNr for a new pci-expander-bus.
     * This is a bit tricky, since you need to satisfy the following:
     *
     * 1) There need to be enough unused bus numbers between busNr of this
     *    bus and busNr of the next highest bus for the guest to assign a
     *    unique bus number to each PCI bus that is a child of this
     *    bus. Each PCI controller. On top of this, the pxb device (which
     *    implements the pci-expander-bus) includes a pci-bridge within
     *    it, and that bridge also uses one bus number (so each pxb device
     *    requires at least 2 bus numbers).
     *
     * 2) There need to be enough bus numbers *below* this for all the
     *    child controllers of the pci-expander-bus with the next lower
     *    busNr (or the pci-root bus if there are no lower
     *    pci-expander-buses).
     *
     * 3) If at all possible, we want to avoid needing to change the busNr
     *    of a bus in the future, as that changes the guest's device ABI,
     *    which could potentially lead to issues with a guest OS that is
     *    picky about such things.
     *
     *  Due to the impossibility of predicting what might be added to the
     *  config in the future, we can't make a foolproof choice, but since
     *  a pci-expander-bus (pxb) has slots for 32 devices, and the only
     *  practical use for it is to assign real devices on a particular
     *  NUMA node in the host, it's reasonably safe to assume it should
     *  never need any additional child buses (probably only a few of the
     *  32 will ever be used). So for pci-expander-bus we find the lowest
     *  existing busNr, and set this one to the current lowest - 2 (one
     *  for the pxb, one for the intergrated pci-bridge), thus leaving the
     *  maximum possible bus numbers available for other buses plugged
     *  into pci-root (i.e. pci-bridges and other
     *  pci-expander-buses). Anyone who needs more than 32 devices
     *  descended from one pci-expander-bus should set the busNr manually
     *  in the config.
     *
     *  There is room for more error checking here - in particular we
     *  can/should determine the ultimate parent (root-bus) of each PCI
     *  controller and determine if there is enough space for all the
     *  buses within the current range allotted to the bus just prior to
     *  this one.
     */

2596 2597 2598 2599
    size_t i;
    int lowestBusNr = 256;

    for (i = 0; i < def->ncontrollers; i++) {
2600 2601 2602 2603
        virDomainControllerDefPtr cont = def->controllers[i];

        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI) {
            int thisBusNr = cont->opts.pciopts.busNr;
2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620

            if (thisBusNr >= 0 && thisBusNr < lowestBusNr)
                lowestBusNr = thisBusNr;
        }
    }

    /* If we already have a busNR = 1, then we can't auto-assign (0 is
     * the pci[e]-root, and the others may have been assigned
     * purposefully).
     */
    if (lowestBusNr <= 2)
        return -1;

    return lowestBusNr - 2;
}


2621 2622 2623
static int
qemuDomainAssignPCIAddresses(virDomainDefPtr def,
                             virQEMUCapsPtr qemuCaps,
2624
                             virQEMUDriverPtr driver,
2625 2626 2627 2628 2629
                             virDomainObjPtr obj)
{
    int ret = -1;
    virDomainPCIAddressSetPtr addrs = NULL;
    qemuDomainObjPrivatePtr priv = NULL;
2630 2631 2632 2633
    int max_idx = -1;
    int nbuses = 0;
    size_t i;
    int rv;
2634

2635
    for (i = 0; i < def->ncontrollers; i++) {
2636 2637 2638
        virDomainControllerDefPtr cont = def->controllers[i];

        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI) {
2639
            if ((int)cont->idx > max_idx)
2640
                max_idx = cont->idx;
2641
        }
2642
    }
2643

2644
    nbuses = max_idx + 1;
2645

2646 2647 2648 2649
    /* set the connect type flags (pci vs. pcie) in the DeviceInfo
     * of all devices. This will be used to pick an appropriate
     * bus when assigning addresses.
     */
2650
    if (qemuDomainFillAllPCIConnectFlags(def, qemuCaps, driver) < 0)
2651 2652
        goto cleanup;

2653 2654 2655
    if (qemuDomainFillAllPCIExtensionFlags(def, qemuCaps) < 0)
        goto cleanup;

2656 2657 2658
    if (qemuDomainSetupIsolationGroups(def) < 0)
        goto cleanup;

2659
    if (nbuses > 0) {
2660
        /* 1st pass to figure out how many PCI bridges we need */
2661
        if (!(addrs = qemuDomainPCIAddressSetCreate(def, qemuCaps, nbuses, true)))
2662
            goto cleanup;
2663

2664 2665 2666
        if (qemuDomainValidateDevicePCISlotsChipsets(def, qemuCaps,
                                                     addrs) < 0)
            goto cleanup;
2667

2668 2669 2670 2671 2672 2673 2674 2675
        /* For domains that have pci-root, reserve 1 extra slot for a
         * (potential) bridge (for future expansion) only if buses are
         * not fully reserved yet (if all buses are fully reserved
         * with manually/previously assigned addresses, any attempt to
         * reserve an extra slot would fail anyway. But if all buses
         * are *not* fully reserved, this extra reservation might push
         * the config to add a new pci-bridge to plug into the final
         * available slot, thus preserving the ability to expand)
2676
         *
2677 2678 2679 2680
         * We only do this for those domains that have pci-root, since
         * those with pcie-root will usually want to expand using PCIe
         * controllers, which we will do after assigning addresses for
         * all *actual* devices.
2681
         */
2682

2683
        if (qemuDomainHasPCIRoot(def)) {
2684 2685 2686 2687 2688 2689 2690
            /* This is a dummy info used to reserve a slot for a
             * legacy PCI device that doesn't exist, but may in the
             * future, e.g.  if another device is hotplugged into the
             * domain.
             */
            virDomainDeviceInfo info = {
                .pciConnectFlags = (VIR_PCI_CONNECT_HOTPLUGGABLE |
2691 2692
                                    VIR_PCI_CONNECT_TYPE_PCI_DEVICE),
                .pciAddrExtFlags = VIR_PCI_ADDRESS_EXTENSION_NONE
2693 2694 2695 2696
            };
            bool buses_reserved = true;

            for (i = 0; i < addrs->nbuses; i++) {
2697
                if (!virDomainPCIAddressBusIsFullyReserved(&addrs->buses[i])) {
2698 2699 2700 2701 2702
                    buses_reserved = false;
                    break;
                }
            }
            if (!buses_reserved &&
2703
                qemuDomainPCIAddressReserveNextAddr(addrs, &info) < 0)
2704 2705
                goto cleanup;
        }
2706

2707 2708
        if (qemuDomainAssignDevicePCISlots(def, qemuCaps, addrs) < 0)
            goto cleanup;
2709

2710 2711 2712
        if (virDomainDeviceInfoIterate(def, qemuDomainAssignPCIAddressExtension, addrs) < 0)
            goto cleanup;

2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728
        /* Only for *new* domains with pcie-root (and no other
         * manually specified PCI controllers in the definition): If,
         * after assigning addresses/reserving slots for all devices,
         * we see that any extra buses have been auto-added, we
         * understand that the application has left management of PCI
         * addresses and controllers up to libvirt. In order to allow
         * such applications to easily support hotplug, we will do a
         * "one time" reservation of one extra PCIE|HOTPLUGGABLE
         * slots, which should cause us to auto-add 1 extra
         * pcie-root-port. The single slot in this root-port will be
         * available for hotplug, or may also be used when a device is
         * added to the config offline.
         */

        if (max_idx <= 0 &&
            addrs->nbuses > max_idx + 1 &&
2729
            qemuDomainHasPCIeRoot(def)) {
2730 2731
            virDomainDeviceInfo info = {
                .pciConnectFlags = (VIR_PCI_CONNECT_HOTPLUGGABLE |
2732 2733
                                    VIR_PCI_CONNECT_TYPE_PCIE_DEVICE),
                .pciAddrExtFlags = VIR_PCI_ADDRESS_EXTENSION_NONE
2734 2735 2736 2737 2738
            };

            /* if there isn't an empty pcie-root-port, this will
             * cause one to be added
             */
2739
            if (qemuDomainPCIAddressReserveNextAddr(addrs, &info) < 0)
2740 2741 2742 2743 2744 2745
               goto cleanup;
        }

        /* now reflect any controllers auto-added to addrs into the
         * domain controllers list
         */
2746
        for (i = 1; i < addrs->nbuses; i++) {
2747 2748
            virDomainDeviceDef dev;
            int contIndex;
2749
            virDomainPCIAddressBusPtr bus = &addrs->buses[i];
2750

2751 2752 2753 2754
            if ((rv = virDomainDefMaybeAddController(
                     def, VIR_DOMAIN_CONTROLLER_TYPE_PCI,
                     i, bus->model)) < 0)
                goto cleanup;
2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777

            if (rv == 0)
                continue; /* no new controller added */

            /* We did add a new controller, so we will need one more
             * address (and we need to set the new controller's
             * pciConnectFlags)
             */
            contIndex = virDomainControllerFind(def,
                                                VIR_DOMAIN_CONTROLLER_TYPE_PCI,
                                                i);
            if (contIndex < 0) {
                /* this should never happen - we just added it */
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Could not find auto-added %s controller "
                                 "with index %zu"),
                               virDomainControllerModelPCITypeToString(bus->model),
                               i);
                goto cleanup;
            }
            dev.type = VIR_DOMAIN_DEVICE_CONTROLLER;
            dev.data.controller = def->controllers[contIndex];
            /* set connect flags so it will be properly addressed */
2778
            qemuDomainFillDevicePCIConnectFlags(def, &dev, qemuCaps, driver);
2779 2780 2781 2782 2783 2784 2785

            /* Reserve an address for the controller. pci-root and pcie-root
             * controllers don't plug into any other PCI controller, hence
             * they should skip this step */
            if (bus->model != VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT &&
                bus->model != VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT &&
                qemuDomainPCIAddressReserveNextAddr(addrs,
2786
                                                    &dev.data.controller->info) < 0) {
2787
                goto cleanup;
2788
            }
2789
        }
2790

2791 2792 2793 2794
        nbuses = addrs->nbuses;
        virDomainPCIAddressSetFree(addrs);
        addrs = NULL;
    }
2795

2796
    if (!(addrs = qemuDomainPCIAddressSetCreate(def, qemuCaps, nbuses, false)))
2797
        goto cleanup;
2798

2799 2800 2801 2802
    if (qemuDomainSupportsPCI(def, qemuCaps)) {
        if (qemuDomainValidateDevicePCISlotsChipsets(def, qemuCaps,
                                                     addrs) < 0)
            goto cleanup;
2803

2804 2805
        if (qemuDomainAssignDevicePCISlots(def, qemuCaps, addrs) < 0)
            goto cleanup;
2806

2807 2808 2809
        if (virDomainDeviceInfoIterate(def, qemuDomainAssignPCIAddressExtension, addrs) < 0)
            goto cleanup;

2810 2811 2812 2813 2814
        /* set multi attribute for devices at function 0 of
         * any slot that has multiple functions in use
         */
        virDomainPCIAddressSetAllMulti(def);

2815 2816 2817 2818 2819
        for (i = 0; i < def->ncontrollers; i++) {
            virDomainControllerDefPtr cont = def->controllers[i];
            int idx = cont->idx;
            virPCIDeviceAddressPtr addr;
            virDomainPCIControllerOptsPtr options;
2820

2821 2822
            if (cont->type != VIR_DOMAIN_CONTROLLER_TYPE_PCI)
                continue;
2823

2824 2825
            addr = &cont->info.addr.pci;
            options = &cont->opts.pciopts;
2826

2827 2828 2829 2830
            /* set default model name (the actual name of the
             * device in qemu) for any controller that doesn't yet
             * have it set.
             */
2831
            qemuDomainPCIControllerSetDefaultModelName(cont, def, qemuCaps);
2832

2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858
            /* set defaults for any other auto-generated config
             * options for this controller that haven't been
             * specified in config.
             */
            switch ((virDomainControllerModelPCI)cont->model) {
            case VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE:
                if (options->chassisNr == -1)
                    options->chassisNr = cont->idx;
                break;
            case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT_PORT:
                if (options->chassis == -1)
                   options->chassis = cont->idx;
                if (options->port == -1)
                   options->port = (addr->slot << 3) + addr->function;
                break;
            case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_DOWNSTREAM_PORT:
                if (options->chassis == -1)
                   options->chassis = cont->idx;
                if (options->port == -1)
                   options->port = addr->slot;
                break;
            case VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS:
            case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS:
                if (options->busNr == -1)
                    options->busNr = qemuDomainAddressFindNewBusNr(def);
                if (options->busNr == -1) {
2859
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2860 2861 2862 2863 2864
                                   _("No free busNr lower than current "
                                     "lowest busNr is available to "
                                     "auto-assign to bus %d. Must be "
                                     "manually assigned"),
                                   addr->bus);
2865 2866
                    goto cleanup;
                }
2867
                break;
2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891
            case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
                if (!qemuDomainIsPSeries(def))
                    break;
                if (options->targetIndex == -1) {
                    if (cont->idx == 0) {
                        /* The pci-root controller with controller index 0
                         * must always be assigned target index 0, because
                         * it represents the implicit PHB which is treated
                         * differently than all other PHBs */
                        options->targetIndex = 0;
                    } else {
                        /* For all other PHBs the target index doesn't need
                         * to match the controller index or have any
                         * particular value, really */
                        options->targetIndex = qemuDomainAddressFindNewTargetIndex(def);
                    }
                }
                if (options->targetIndex == -1) {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("No usable target index found for %d"),
                                   addr->bus);
                    goto cleanup;
                }
                break;
2892
            case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
2893
            case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_TO_PCI_BRIDGE:
2894 2895
            case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_UPSTREAM_PORT:
            case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
2896
            case VIR_DOMAIN_CONTROLLER_MODEL_PCI_DEFAULT:
2897 2898 2899 2900
            case VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST:
                break;
            }

2901
            /* check if every PCI bridge controller's index is larger than
2902 2903 2904 2905 2906 2907
             * the bus it is placed onto
             */
            if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE &&
                idx <= addr->bus) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("PCI controller at index %d (0x%02x) has "
2908 2909
                                 "bus='0x%02x', but index must be "
                                 "larger than bus"),
2910 2911
                               idx, idx, addr->bus);
                goto cleanup;
2912 2913 2914 2915 2916 2917
            }
        }
    }

    if (obj && obj->privateData) {
        priv = obj->privateData;
J
John Ferlan 已提交
2918 2919 2920
        /* if this is the live domain object, we persist the PCI addresses */
        priv->pciaddrs = addrs;
        addrs = NULL;
2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931
    }

    ret = 0;

 cleanup:
    virDomainPCIAddressSetFree(addrs);

    return ret;
}


J
Ján Tomko 已提交
2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943
struct qemuAssignUSBIteratorInfo {
    virDomainUSBAddressSetPtr addrs;
    size_t count;
};


static int
qemuDomainAssignUSBPortsIterator(virDomainDeviceInfoPtr info,
                                 void *opaque)
{
    struct qemuAssignUSBIteratorInfo *data = opaque;

2944 2945 2946 2947 2948 2949
    if (info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE &&
        info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB)
        return 0;

    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB &&
        virDomainUSBAddressPortIsValid(info->addr.usb.port))
J
Ján Tomko 已提交
2950 2951 2952 2953 2954 2955 2956 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
        return 0;

    return virDomainUSBAddressAssign(data->addrs, info);
}


static int
qemuDomainAssignUSBHubs(virDomainUSBAddressSetPtr addrs,
                        virDomainDefPtr def)
{
    size_t i;

    for (i = 0; i < def->nhubs; i++) {
        virDomainHubDefPtr hub = def->hubs[i];
        if (hub->type != VIR_DOMAIN_HUB_TYPE_USB)
            continue;

        if (hub->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB &&
            virDomainUSBAddressPortIsValid(hub->info.addr.usb.port))
            continue;
        if (virDomainUSBAddressAssign(addrs, &hub->info) < 0)
            return -1;

        if (virDomainUSBAddressSetAddHub(addrs, hub) < 0)
            return -1;
    }

    return 0;
}


static int
qemuDomainAssignUSBPorts(virDomainUSBAddressSetPtr addrs,
                         virDomainDefPtr def)
{
    struct qemuAssignUSBIteratorInfo data = { .addrs = addrs };

    return virDomainUSBDeviceDefForeach(def,
                                        qemuDomainAssignUSBPortsIterator,
                                        &data,
                                        true);
}


2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010
static int
qemuDomainAssignUSBPortsCounter(virDomainDeviceInfoPtr info ATTRIBUTE_UNUSED,
                                void *opaque)
{
    struct qemuAssignUSBIteratorInfo *data = opaque;

    data->count++;
    return 0;
}


static int
qemuDomainUSBAddressAddHubs(virDomainDefPtr def)
{
    struct qemuAssignUSBIteratorInfo data = { .count = 0 };
    virDomainHubDefPtr hub = NULL;
    size_t available_ports;
3011
    size_t hubs_needed = 0;
3012
    int ret = -1;
3013
    size_t i;
3014 3015 3016 3017 3018 3019 3020

    available_ports = virDomainUSBAddressCountAllPorts(def);
    ignore_value(virDomainUSBDeviceDefForeach(def,
                                              qemuDomainAssignUSBPortsCounter,
                                              &data,
                                              false));

3021
    if (data.count > 0 && !virDomainDefHasUSB(def)) {
3022 3023 3024 3025 3026 3027
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("USB is disabled for this domain, but USB devices "
                         "are present in the domain XML"));
        return -1;
    }

3028 3029 3030 3031 3032 3033 3034 3035
    if (data.count > available_ports)
        hubs_needed = VIR_DIV_UP(data.count - available_ports + 1,
                                 VIR_DOMAIN_USB_HUB_PORTS - 1);

    VIR_DEBUG("Found %zu USB devices and %zu provided USB ports; adding %zu hubs",
              data.count, available_ports, hubs_needed);

    for (i = 0; i < hubs_needed; i++) {
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050
        if (VIR_ALLOC(hub) < 0)
            return -1;
        hub->type = VIR_DOMAIN_HUB_TYPE_USB;

        if (VIR_APPEND_ELEMENT(def->hubs, def->nhubs, hub) < 0)
            goto cleanup;
    }

    ret = 0;
 cleanup:
    VIR_FREE(hub);
    return ret;
}


3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082
static virBitmapPtr
qemuDomainGetMemorySlotMap(const virDomainDef *def)
{
    virBitmapPtr ret;
    virDomainMemoryDefPtr mem;
    size_t i;

    if (!(ret = virBitmapNew(def->mem.memory_slots)))
        return NULL;

    for (i = 0; i < def->nmems; i++) {
        mem = def->mems[i];

        if (mem->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM)
            ignore_value(virBitmapSetBit(ret, mem->info.addr.dimm.slot));
    }

    return ret;
}


static int
qemuAssignMemoryDeviceSlot(virDomainMemoryDefPtr mem,
                           virBitmapPtr slotmap)
{
    ssize_t nextslot = -1;

    if (mem->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM)
        return 0;

    if ((nextslot = virBitmapNextClearBit(slotmap, -1)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
Y
Yuri Chornoivan 已提交
3083
                       _("failed to find an empty memory slot"));
3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138
        return -1;
    }

    ignore_value(virBitmapSetBit(slotmap, nextslot));
    mem->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM;
    mem->info.addr.dimm.slot = nextslot;

    return 0;
}


int
qemuDomainAssignMemoryDeviceSlot(virDomainDefPtr def,
                                 virDomainMemoryDefPtr mem)
{
    virBitmapPtr slotmap = NULL;
    int ret;

    if (!(slotmap = qemuDomainGetMemorySlotMap(def)))
        return -1;

    ret = qemuAssignMemoryDeviceSlot(mem, slotmap);

    virBitmapFree(slotmap);
    return ret;
}


static int
qemuDomainAssignMemorySlots(virDomainDefPtr def)
{
    virBitmapPtr slotmap = NULL;
    int ret = -1;
    size_t i;

    if (!virDomainDefHasMemoryHotplug(def))
        return 0;

    if (!(slotmap = qemuDomainGetMemorySlotMap(def)))
        return -1;

    for (i = 0; i < def->nmems; i++) {
        if (qemuAssignMemoryDeviceSlot(def->mems[i], slotmap) < 0)
            goto cleanup;
    }

    ret = 0;

 cleanup:
    virBitmapFree(slotmap);
    return ret;

}


J
Ján Tomko 已提交
3139 3140
static int
qemuDomainAssignUSBAddresses(virDomainDefPtr def,
3141 3142
                             virDomainObjPtr obj,
                             bool newDomain)
J
Ján Tomko 已提交
3143 3144 3145 3146 3147
{
    int ret = -1;
    virDomainUSBAddressSetPtr addrs = NULL;
    qemuDomainObjPrivatePtr priv = NULL;

3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158
    if (!newDomain) {
        /* only create the address cache for:
         *  new domains
         *  domains that already have all the addresses specified
         * otherwise libvirt's attempt to recreate the USB topology via
         * QEMU command line might fail */
        if (virDomainUSBDeviceDefForeach(def, virDomainUSBAddressPresent, NULL,
                                         false) < 0)
            return 0;
    }

J
Ján Tomko 已提交
3159 3160 3161
    if (!(addrs = virDomainUSBAddressSetCreate()))
        goto cleanup;

3162 3163 3164
    if (qemuDomainUSBAddressAddHubs(def) < 0)
        goto cleanup;

J
Ján Tomko 已提交
3165 3166 3167 3168 3169 3170 3171 3172 3173
    if (virDomainUSBAddressSetAddControllers(addrs, def) < 0)
        goto cleanup;

    if (virDomainUSBDeviceDefForeach(def, virDomainUSBAddressReserve, addrs,
                                     true) < 0)
        goto cleanup;

    VIR_DEBUG("Existing USB addresses have been reserved");

J
Ján Tomko 已提交
3174 3175 3176 3177 3178 3179 3180 3181
    if (qemuDomainAssignUSBHubs(addrs, def) < 0)
        goto cleanup;

    if (qemuDomainAssignUSBPorts(addrs, def) < 0)
        goto cleanup;

    VIR_DEBUG("Finished assigning USB ports");

J
Ján Tomko 已提交
3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194
    if (obj && obj->privateData) {
        priv = obj->privateData;
        priv->usbaddrs = addrs;
        addrs = NULL;
    }
    ret = 0;

 cleanup:
    virDomainUSBAddressSetFree(addrs);
    return ret;
}


3195 3196 3197
int
qemuDomainAssignAddresses(virDomainDefPtr def,
                          virQEMUCapsPtr qemuCaps,
3198
                          virQEMUDriverPtr driver,
3199
                          virDomainObjPtr obj,
J
Ján Tomko 已提交
3200
                          bool newDomain)
3201
{
3202
    if (qemuDomainAssignVirtioSerialAddresses(def) < 0)
3203
        return -1;
3204

3205
    if (qemuDomainAssignSpaprVIOAddresses(def) < 0)
3206
        return -1;
3207

T
Tomasz Flendrich 已提交
3208
    if (qemuDomainAssignS390Addresses(def, qemuCaps) < 0)
3209
        return -1;
3210

3211
    qemuDomainAssignVirtioMMIOAddresses(def, qemuCaps);
3212

3213
    if (qemuDomainAssignPCIAddresses(def, qemuCaps, driver, obj) < 0)
3214 3215
        return -1;

3216
    if (qemuDomainAssignUSBAddresses(def, obj, newDomain) < 0)
J
Ján Tomko 已提交
3217 3218
        return -1;

3219 3220 3221
    if (qemuDomainAssignMemorySlots(def) < 0)
        return -1;

3222
    return 0;
3223 3224
}

3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241
/**
 * qemuDomainEnsurePCIAddress:
 *
 * @obj: the virDomainObjPtr for the domain. This will include
 *       qemuCaps and address cache (if there is one)
 *
 * @dev: the device that we need to ensure has a PCI address
 *
 * if @dev should have a PCI address but doesn't, assign an address on
 * a compatible PCI bus, and set it in @dev->...info. If there is an
 * address already, validate that it is on a compatible bus, based on
 * @dev->...info.pciConnectFlags.
 *
 * returns 0 on success -1 on failure.
 */
int
qemuDomainEnsurePCIAddress(virDomainObjPtr obj,
3242 3243
                           virDomainDeviceDefPtr dev,
                           virQEMUDriverPtr driver)
3244 3245 3246 3247 3248 3249 3250
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
    virDomainDeviceInfoPtr info = virDomainDeviceGetInfo(dev);

    if (!info)
        return 0;

3251
    qemuDomainFillDevicePCIConnectFlags(obj->def, dev, priv->qemuCaps, driver);
3252

3253 3254
    qemuDomainFillDevicePCIExtensionFlags(dev, info, priv->qemuCaps);

3255 3256 3257
    return virDomainPCIAddressEnsureAddr(priv->pciaddrs, info,
                                         info->pciConnectFlags);
}
3258 3259 3260

void
qemuDomainReleaseDeviceAddress(virDomainObjPtr vm,
3261
                               virDomainDeviceInfoPtr info)
3262 3263 3264
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

3265
    if (virDeviceInfoPCIAddressIsPresent(info)) {
3266
        virDomainPCIAddressReleaseAddr(priv->pciaddrs, &info->addr.pci);
3267 3268
        virDomainPCIAddressExtensionReleaseAddr(priv->pciaddrs, &info->addr.pci);
    }
3269

3270
    virDomainUSBAddressRelease(priv->usbaddrs, info);
3271
}
3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287


int
qemuDomainEnsureVirtioAddress(bool *releaseAddr,
                              virDomainObjPtr vm,
                              virDomainDeviceDefPtr dev,
                              const char *devicename)
{
    virDomainDeviceInfoPtr info = virDomainDeviceGetInfo(dev);
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virDomainCCWAddressSetPtr ccwaddrs = NULL;
    virQEMUDriverPtr driver = priv->driver;
    int ret = -1;

    if (!info->type) {
        if (qemuDomainIsS390CCW(vm->def) &&
3288
            virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_CCW))
3289 3290 3291 3292
            info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW;
        else if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_S390))
            info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390;
    } else {
3293
        if (!qemuDomainCheckCCWS390AddressSupport(vm->def, info, priv->qemuCaps,
3294 3295 3296 3297 3298
                                                  devicename))
            return -1;
    }

    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW) {
3299
        if (!(ccwaddrs = virDomainCCWAddressSetCreateFromDomain(vm->def)))
3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316
            goto cleanup;
        if (virDomainCCWAddressAssign(info, ccwaddrs,
                                      !info->addr.ccw.assigned) < 0)
            goto cleanup;
    } else if (!info->type ||
               info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
        if (qemuDomainEnsurePCIAddress(vm, dev, driver) < 0)
            goto cleanup;
        *releaseAddr = true;
    }

    ret = 0;

 cleanup:
    virDomainCCWAddressSetFree(ccwaddrs);
    return ret;
}