qemu_domain_address.c 64.1 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 40 41 42
/*
 * 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/>.
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#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


int
43
qemuDomainSetSCSIControllerModel(const virDomainDef *def,
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
                                 virQEMUCapsPtr qemuCaps,
                                 int *model)
{
    if (*model > 0) {
        switch (*model) {
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC:
            if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_LSI)) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("This QEMU doesn't support "
                                 "the LSI 53C895A SCSI controller"));
                return -1;
            }
            break;
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI:
            if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_SCSI)) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("This QEMU doesn't support "
                                 "virtio scsi controller"));
                return -1;
            }
            break;
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_IBMVSCSI:
            /*TODO: need checking work here if necessary */
            break;
68 69 70 71 72 73 74 75
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068:
            if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_MPTSAS1068)) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("This QEMU doesn't support "
                                 "the LSI SAS1068 (MPT Fusion) controller"));
                return -1;
            }
            break;
76 77 78 79
        case VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1078:
            if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_MEGASAS)) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("This QEMU doesn't support "
80
                                 "the LSI SAS1078 (MegaRAID) controller"));
81 82 83 84 85 86 87 88 89 90
                return -1;
            }
            break;
        default:
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Unsupported controller model: %s"),
                           virDomainControllerModelSCSITypeToString(*model));
            return -1;
        }
    } else {
91
        if (qemuDomainMachineIsPSeries(def)) {
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
            *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_IBMVSCSI;
        } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_SCSI_LSI)) {
            *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC;
        } else if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_SCSI)) {
            *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VIRTIO_SCSI;
        } else {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to determine model for scsi controller"));
            return -1;
        }
    }

    return 0;
}


static int
109
qemuDomainAssignVirtioSerialAddresses(virDomainDefPtr def)
110 111 112 113 114
{
    int ret = -1;
    size_t i;
    virDomainVirtioSerialAddrSetPtr addrs = NULL;

115
    if (!(addrs = virDomainVirtioSerialAddrSetCreateFromDomain(def)))
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
        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) &&
            virDomainVirtioSerialAddrAutoAssign(def, addrs, &chr->info, true) < 0)
            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) &&
            virDomainVirtioSerialAddrAutoAssign(def, addrs, &chr->info, false) < 0)
            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
qemuDomainAssignSpaprVIOAddresses(virDomainDefPtr def,
                                  virQEMUCapsPtr qemuCaps)
{
    size_t i;
    int ret = -1;
    int model;

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

    for (i = 0; i < def->nnets; i++) {
214 215 216 217 218 219 220 221
        virDomainNetDefPtr net = def->nets[i];

        if (net->model &&
            STREQ(net->model, "spapr-vlan")) {
            net->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO;
        }

        if (qemuDomainAssignSpaprVIOAddress(def, &net->info, VIO_ADDR_NET) < 0)
222 223 224 225
            goto cleanup;
    }

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

        model = cont->model;
        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI) {
230 231 232 233 234
            if (qemuDomainSetSCSIControllerModel(def, qemuCaps, &model) < 0)
                goto cleanup;
        }

        if (model == VIR_DOMAIN_CONTROLLER_MODEL_SCSI_IBMVSCSI &&
235 236 237 238 239
            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) {
240
            goto cleanup;
241
        }
242 243 244 245
    }

    for (i = 0; i < def->nserials; i++) {
        if (def->serials[i]->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL &&
246
            qemuDomainMachineIsPSeries(def))
247 248 249 250 251 252 253
            def->serials[i]->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_SPAPRVIO;
        if (qemuDomainAssignSpaprVIOAddress(def, &def->serials[i]->info,
                                            VIO_ADDR_SERIAL) < 0)
            goto cleanup;
    }

    if (def->nvram) {
254
        if (qemuDomainMachineIsPSeries(def))
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
            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;
}


static void
qemuDomainPrimeVirtioDeviceAddresses(virDomainDefPtr def,
                                     virDomainDeviceAddressType type)
{
    /*
       declare address-less virtio devices to be of address type 'type'
       disks, networks, consoles, controllers, memballoon and rng in this
       order
       if type is ccw filesystem devices are declared to be of address type ccw
    */
    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++) {
289 290 291 292 293
        virDomainNetDefPtr net = def->nets[i];

        if (STREQ(net->model, "virtio") &&
            net->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
            net->info.type = type;
294 295 296 297 298 299 300 301 302 303
        }
    }

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

    for (i = 0; i < def->ncontrollers; i++) {
304 305 306 307 308 309 310
        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;
        }
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
    }

    if (def->memballoon &&
        def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO &&
        def->memballoon->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
        def->memballoon->info.type = type;

    for (i = 0; i < def->nrngs; i++) {
        if (def->rngs[i]->model == VIR_DOMAIN_RNG_MODEL_VIRTIO &&
            def->rngs[i]->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
            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;
        }
    }
}

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
virDomainCCWAddressSetPtr
qemuDomainCCWAddrSetCreateFromDomain(virDomainDefPtr def)
{
    virDomainCCWAddressSetPtr addrs = NULL;

    if (!(addrs = virDomainCCWAddressSetCreate()))
        goto error;

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

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

    return addrs;

 error:
    virDomainCCWAddressSetFree(addrs);
    return NULL;
}
354 355 356 357 358 359 360 361 362

/*
 * 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 已提交
363
                              virQEMUCapsPtr qemuCaps)
364 365 366 367 368 369 370 371 372
{
    int ret = -1;
    virDomainCCWAddressSetPtr addrs = NULL;

    if (qemuDomainMachineIsS390CCW(def) &&
        virQEMUCapsGet(qemuCaps, QEMU_CAPS_VIRTIO_CCW)) {
        qemuDomainPrimeVirtioDeviceAddresses(
            def, VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW);

373
        if (!(addrs = qemuDomainCCWAddrSetCreateFromDomain(def)))
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
            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;
}


391
static void
392 393 394
qemuDomainAssignARMVirtioMMIOAddresses(virDomainDefPtr def,
                                       virQEMUCapsPtr qemuCaps)
{
395 396 397 398 399
    if (def->os.arch != VIR_ARCH_ARMV7L &&
        def->os.arch != VIR_ARCH_AARCH64)
        return;

    if (!(STRPREFIX(def->os.machine, "vexpress-") ||
J
Ján Tomko 已提交
400
          qemuDomainMachineIsVirt(def)))
401 402 403
        return;

    if (virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIRTIO_MMIO)) {
404 405 406 407 408 409 410 411 412 413 414 415 416 417
        qemuDomainPrimeVirtioDeviceAddresses(
            def, VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_MMIO);
    }
}


static int
qemuDomainCollectPCIAddress(virDomainDefPtr def ATTRIBUTE_UNUSED,
                            virDomainDeviceDefPtr device,
                            virDomainDeviceInfoPtr info,
                            void *opaque)
{
    virDomainPCIAddressSetPtr addrs = opaque;
    int ret = -1;
418
    virPCIDeviceAddressPtr addr = &info->addr.pci;
419 420 421
    bool entireSlot;
    /* flags may be changed from default below */
    virDomainPCIConnectFlags flags = (VIR_PCI_CONNECT_HOTPLUGGABLE |
422
                                      VIR_PCI_CONNECT_TYPE_PCI_DEVICE);
423

424 425 426
    if (!virDeviceInfoPCIAddressPresent(info) ||
        ((device->type == VIR_DOMAIN_DEVICE_HOSTDEV) &&
         (device->data.hostdev->parent.type != VIR_DOMAIN_DEVICE_NONE))) {
427 428 429 430 431 432 433 434 435 436 437 438 439 440
        /* 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;
    }

    /* Change flags according to differing requirements of different
     * devices.
     */
    switch (device->type) {
    case VIR_DOMAIN_DEVICE_CONTROLLER:
        switch (device->data.controller->type) {
        case  VIR_DOMAIN_CONTROLLER_TYPE_PCI:
441
           flags = virDomainPCIControllerModelToConnectType(device->data.controller->model);
442 443 444 445 446 447
            break;

        case VIR_DOMAIN_CONTROLLER_TYPE_SATA:
            /* SATA controllers aren't hot-plugged, and can be put in
             * either a PCI or PCIe slot
             */
448 449
            flags = (VIR_PCI_CONNECT_TYPE_PCI_DEVICE
                     | VIR_PCI_CONNECT_TYPE_PCIE_DEVICE);
450 451 452
            break;

        case VIR_DOMAIN_CONTROLLER_TYPE_USB:
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
            /* allow UHCI and EHCI controllers to be manually placed on
             * the PCIe bus (but don't put them there automatically)
             */
            switch (device->data.controller->model) {
            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:
                flags = VIR_PCI_CONNECT_TYPE_PCI_DEVICE;
                break;
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_NEC_XHCI:
                /* should this be PCIE-only? Or do we need to allow PCI
                 * for backward compatibility?
                 */
                flags = (VIR_PCI_CONNECT_TYPE_PCI_DEVICE
                         | VIR_PCI_CONNECT_TYPE_PCIE_DEVICE);
                break;
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_PCI_OHCI:
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX3_UHCI:
            case VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX4_UHCI:
                /* Allow these for PCI only */
                break;
            }
478 479 480 481 482 483 484
        }
        break;

    case VIR_DOMAIN_DEVICE_SOUND:
        switch (device->data.sound->model) {
        case VIR_DOMAIN_SOUND_MODEL_ICH6:
        case VIR_DOMAIN_SOUND_MODEL_ICH9:
485
            flags = VIR_PCI_CONNECT_TYPE_PCI_DEVICE;
486 487 488 489 490 491 492 493
            break;
        }
        break;

    case VIR_DOMAIN_DEVICE_VIDEO:
        /* video cards aren't hot-plugged, and can be put in either a
         * PCI or PCIe slot
         */
494 495
       flags = (VIR_PCI_CONNECT_TYPE_PCI_DEVICE
                | VIR_PCI_CONNECT_TYPE_PCIE_DEVICE);
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
        break;
    }

    /* 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 ||
              cont->model == -1) && addr->function == 2)) {
            /* 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 &&
527
                !(addrs->buses[0].flags & VIR_PCI_CONNECT_TYPE_PCI_DEVICE)) {
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 574 575 576 577 578
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Bus 0 must be PCI for integrated PIIX3 "
                                 "USB or IDE controllers"));
                return -1;
            } else {
                return 0;
            }
        }
    }

    entireSlot = (addr->function == 0 &&
                  addr->multi != VIR_TRISTATE_SWITCH_ON);

    if (virDomainPCIAddressReserveAddr(addrs, addr, flags,
                                       entireSlot, true) < 0)
        goto cleanup;

    ret = 0;
 cleanup:
    return ret;
}

static virDomainPCIAddressSetPtr
qemuDomainPCIAddressSetCreate(virDomainDefPtr def,
                              unsigned int nbuses,
                              bool dryRun)
{
    virDomainPCIAddressSetPtr addrs;
    size_t i;

    if ((addrs = virDomainPCIAddressSetAlloc(nbuses)) == NULL)
        return NULL;

    addrs->dryRun = dryRun;

    /* As a safety measure, set default model='pci-root' for first pci
     * controller and 'pci-bridge' for all subsequent. After setting
     * those defaults, then scan the config and set the actual model
     * for all addrs[idx]->bus that already have a corresponding
     * controller in the config.
     *
     */
    if (nbuses > 0)
        virDomainPCIAddressBusSetModel(&addrs->buses[0],
                                       VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT);
    for (i = 1; i < nbuses; i++) {
        virDomainPCIAddressBusSetModel(&addrs->buses[i],
                                       VIR_DOMAIN_CONTROLLER_MODEL_PCI_BRIDGE);
    }

    for (i = 0; i < def->ncontrollers; i++) {
579 580
        virDomainControllerDefPtr cont = def->controllers[i];
        size_t idx = cont->idx;
581

582
        if (cont->type != VIR_DOMAIN_CONTROLLER_TYPE_PCI)
583 584 585 586 587 588 589 590 591
            continue;

        if (idx >= addrs->nbuses) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Inappropriate new pci controller index %zu "
                             "not found in addrs"), idx);
            goto error;
        }

592
        if (virDomainPCIAddressBusSetModel(&addrs->buses[idx], cont->model) < 0)
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
            goto error;
        }

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

    return addrs;

 error:
    virDomainPCIAddressSetFree(addrs);
    return NULL;
}


static int
qemuDomainValidateDevicePCISlotsPIIX3(virDomainDefPtr def,
                                      virQEMUCapsPtr qemuCaps,
                                      virDomainPCIAddressSetPtr addrs)
{
    int ret = -1;
    size_t i;
614
    virPCIDeviceAddress tmp_addr;
615 616
    bool qemuDeviceVideoUsable = virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIDEO_PRIMARY);
    char *addrStr = NULL;
617 618
    virDomainPCIConnectFlags flags = (VIR_PCI_CONNECT_HOTPLUGGABLE
                                      | VIR_PCI_CONNECT_TYPE_PCI_DEVICE);
619 620 621

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

624
        /* First IDE controller lives on the PIIX3 at slot=1, function=1 */
625 626 627 628 629 630 631
        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_IDE &&
            cont->idx == 0) {
            if (virDeviceInfoPCIAddressPresent(&cont->info)) {
                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) {
632 633 634 635 636
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("Primary IDE controller must have PCI address 0:0:1.1"));
                    goto cleanup;
                }
            } else {
637 638 639 640 641
                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;
642
            }
643 644 645 646 647 648 649 650 651
        } else if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
                   cont->idx == 0 &&
                   (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_PIIX3_UHCI ||
                    cont->model == -1)) {
            if (virDeviceInfoPCIAddressPresent(&cont->info)) {
                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) {
652 653 654 655 656
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("PIIX3 USB controller must have PCI address 0:0:1.2"));
                    goto cleanup;
                }
            } else {
657 658 659 660 661
                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;
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
            }
        }
    }

    /* PIIX3 (ISA bridge, IDE controller, something else unknown, USB controller)
     * hardcoded slot=1, multifunction device
     */
    if (addrs->nbuses) {
        memset(&tmp_addr, 0, sizeof(tmp_addr));
        tmp_addr.slot = 1;
        if (virDomainPCIAddressReserveSlot(addrs, &tmp_addr, flags) < 0)
            goto cleanup;
    }

    if (def->nvideos > 0) {
        /* 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];
684
        if (virDeviceInfoPCIAddressWanted(&primaryVideo->info)) {
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
            memset(&tmp_addr, 0, sizeof(tmp_addr));
            tmp_addr.slot = 2;

            if (!(addrStr = virDomainPCIAddressAsString(&tmp_addr)))
                goto cleanup;
            if (!virDomainPCIAddressValidate(addrs, &tmp_addr,
                                             addrStr, flags, false))
                goto cleanup;

            if (virDomainPCIAddressSlotInUse(addrs, &tmp_addr)) {
                if (qemuDeviceVideoUsable) {
                    if (virDomainPCIAddressReserveNextSlot(addrs,
                                                           &primaryVideo->info,
                                                           flags) < 0)
                        goto cleanup;
                } 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 {
                if (virDomainPCIAddressReserveSlot(addrs, &tmp_addr, flags) < 0)
                    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");
        } else if (virDomainPCIAddressReserveSlot(addrs, &tmp_addr, flags) < 0) {
            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;
750
    virPCIDeviceAddress tmp_addr;
751 752
    bool qemuDeviceVideoUsable = virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VIDEO_PRIMARY);
    char *addrStr = NULL;
753
    virDomainPCIConnectFlags flags = VIR_PCI_CONNECT_TYPE_PCIE_DEVICE;
754 755

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

        switch (cont->type) {
759 760 761 762 763
        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.
             */
764 765 766 767 768 769
            if (cont->idx == 0) {
                if (virDeviceInfoPCIAddressPresent(&cont->info)) {
                    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) {
770 771 772 773 774
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("Primary SATA controller must have PCI address 0:0:1f.2"));
                        goto cleanup;
                    }
                } else {
775 776 777 778 779
                    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;
780 781 782 783 784
                }
            }
            break;

        case VIR_DOMAIN_CONTROLLER_TYPE_USB:
785 786
            if ((cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_ICH9_UHCI1) &&
                (cont->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)) {
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
                /* 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) {
                    if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr,
                                                       flags, false, true) < 0)
                        goto cleanup;
811 812 813 814 815 816
                    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;
817 818 819 820 821
                }
            }
            break;

        case VIR_DOMAIN_CONTROLLER_TYPE_PCI:
822 823
            if (cont->model == VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE &&
                cont->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
824 825 826 827 828 829 830 831 832 833
                /* 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)) {
                    if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr,
                                                       flags, true, false) < 0)
                        goto cleanup;
834 835 836 837 838
                    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;
839 840 841 842 843 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
                }
            }
            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;
        if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags,
                                           false, false) < 0)
           goto cleanup;
        tmp_addr.function = 3;
        tmp_addr.multi = VIR_TRISTATE_SWITCH_ABSENT;
        if (virDomainPCIAddressReserveAddr(addrs, &tmp_addr, flags,
                                           false, false) < 0)
           goto cleanup;
    }

    if (def->nvideos > 0) {
        /* NB: unlike the pc machinetypes, on q35 machinetypes the
         * integrated devices are at slot 0x1f, so when qemu looks for
         * the first free lot for the first VGA, it will always be at
         * slot 1 (which was used up by the integrated PIIX3 devices
         * on pc machinetypes).
         */
        virDomainVideoDefPtr primaryVideo = def->videos[0];
873
        if (virDeviceInfoPCIAddressWanted(&primaryVideo->info)) {
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
            memset(&tmp_addr, 0, sizeof(tmp_addr));
            tmp_addr.slot = 1;

            if (!(addrStr = virDomainPCIAddressAsString(&tmp_addr)))
                goto cleanup;
            if (!virDomainPCIAddressValidate(addrs, &tmp_addr,
                                             addrStr, flags, false))
                goto cleanup;

            if (virDomainPCIAddressSlotInUse(addrs, &tmp_addr)) {
                if (qemuDeviceVideoUsable) {
                    if (virDomainPCIAddressReserveNextSlot(addrs,
                                                           &primaryVideo->info,
                                                           flags) < 0)
                        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 {
                if (virDomainPCIAddressReserveSlot(addrs, &tmp_addr, flags) < 0)
                    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();
        } else if (virDomainPCIAddressReserveSlot(addrs, &tmp_addr, flags) < 0) {
            goto cleanup;
        }
    }
    ret = 0;
 cleanup:
    VIR_FREE(addrStr);
    return ret;
}


static int
qemuDomainValidateDevicePCISlotsChipsets(virDomainDefPtr def,
                                         virQEMUCapsPtr qemuCaps,
                                         virDomainPCIAddressSetPtr addrs)
{
    if (qemuDomainMachineIsI440FX(def) &&
        qemuDomainValidateDevicePCISlotsPIIX3(def, qemuCaps, addrs) < 0) {
        return -1;
    }

    if (qemuDomainMachineIsQ35(def) &&
        qemuDomainValidateDevicePCISlotsQ35(def, qemuCaps, addrs) < 0) {
        return -1;
    }

    return 0;
}


static bool
qemuDomainPCIBusFullyReserved(virDomainPCIAddressBusPtr bus)
{
    size_t i;

    for (i = bus->minSlot; i <= bus->maxSlot; i++)
        if (!bus->slots[i])
            return false;

    return true;
}


/*
 * 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
 *    qemuValidateDevicePCISlotsChipsets invoked right before this function
 *
 * 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;
1007
    virDomainPCIConnectFlags flags = 0; /* initialize to quiet gcc warning */
1008
    virPCIDeviceAddress tmp_addr;
1009 1010 1011

    /* PCI controllers */
    for (i = 0; i < def->ncontrollers; i++) {
1012 1013 1014 1015
        virDomainControllerDefPtr cont = def->controllers[i];

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

1017 1018
            if (model == VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT ||
                model == VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT ||
1019
                !virDeviceInfoPCIAddressWanted(&cont->info))
1020
                continue;
1021 1022 1023 1024 1025

            /* convert the type of controller into a "CONNECT_TYPE"
             * flag to use when searching for the proper
             * controller/bus to connect it to on the upstream side.
             */
1026
            flags = virDomainPCIControllerModelToConnectType(model);
1027
            if (virDomainPCIAddressReserveNextSlot(addrs,
1028
                                                   &cont->info, flags) < 0) {
1029
                goto error;
1030
            }
1031 1032 1033
        }
    }

1034 1035 1036 1037 1038 1039
    /* all other devices that plug into a PCI slot are treated as a
     * PCI endpoint devices that require a hotplug-capable slot
     * (except for some special cases which have specific handling
     * below)
     */
    flags = VIR_PCI_CONNECT_HOTPLUGGABLE | VIR_PCI_CONNECT_TYPE_PCI_DEVICE;
1040 1041

    for (i = 0; i < def->nfss; i++) {
1042
        if (!virDeviceInfoPCIAddressWanted(&def->fss[i]->info))
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
            continue;

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

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

1056 1057 1058 1059
        /* type='hostdev' network devices might be USB, and are also
         * in hostdevs list anyway, so handle them with other hostdevs
         * instead of here.
         */
1060 1061
        if ((net->type == VIR_DOMAIN_NET_TYPE_HOSTDEV) ||
            !virDeviceInfoPCIAddressWanted(&net->info)) {
1062 1063
            continue;
        }
1064
        if (virDomainPCIAddressReserveNextSlot(addrs, &net->info, flags) < 0)
1065 1066 1067 1068 1069
            goto error;
    }

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

        if (!virDeviceInfoPCIAddressWanted(&sound->info))
1073
            continue;
1074

1075
        /* Skip ISA sound card, PCSPK and usb-audio */
1076 1077 1078
        if (sound->model == VIR_DOMAIN_SOUND_MODEL_SB16 ||
            sound->model == VIR_DOMAIN_SOUND_MODEL_PCSPK ||
            sound->model == VIR_DOMAIN_SOUND_MODEL_USB) {
1079
            continue;
1080
        }
1081

1082
        if (virDomainPCIAddressReserveNextSlot(addrs, &sound->info, flags) < 0)
1083 1084 1085 1086 1087
            goto error;
    }

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

1090
        /* PCI controllers have been dealt with earlier */
1091
        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI)
1092 1093 1094
            continue;

        /* USB controller model 'none' doesn't need a PCI address */
1095 1096
        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
            cont->model == VIR_DOMAIN_CONTROLLER_MODEL_USB_NONE)
1097 1098 1099
            continue;

        /* FDC lives behind the ISA bridge; CCID is a usb device */
1100 1101
        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_FDC ||
            cont->type == VIR_DOMAIN_CONTROLLER_TYPE_CCID)
1102 1103 1104 1105
            continue;

        /* First IDE controller lives on the PIIX3 at slot=1, function=1,
           dealt with earlier on*/
1106 1107
        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_IDE &&
            cont->idx == 0)
1108 1109
            continue;

1110
        if (!virDeviceInfoPCIAddressWanted(&cont->info))
1111 1112 1113
            continue;

        /* USB2 needs special handling to put all companions in the same slot */
1114
        if (IS_USB2_CONTROLLER(cont)) {
1115
            virPCIDeviceAddress addr = {0};
1116 1117 1118 1119 1120
            bool foundAddr = false;

            memset(&tmp_addr, 0, sizeof(tmp_addr));
            for (j = 0; j < def->ncontrollers; j++) {
                if (IS_USB2_CONTROLLER(def->controllers[j]) &&
1121
                    def->controllers[j]->idx == cont->idx &&
1122
                    virDeviceInfoPCIAddressPresent(&def->controllers[j]->info)) {
1123 1124 1125 1126 1127 1128
                    addr = def->controllers[j]->info.addr.pci;
                    foundAddr = true;
                    break;
                }
            }

1129
            switch (cont->model) {
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
            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;
            }

            if (!foundAddr) {
                /* This is the first part of the controller, so need
                 * to find a free slot & then reserve a function */
                if (virDomainPCIAddressGetNextSlot(addrs, &tmp_addr, flags) < 0)
                    goto error;

                addr.bus = tmp_addr.bus;
                addr.slot = tmp_addr.slot;

                addrs->lastaddr = addr;
                addrs->lastaddr.function = 0;
                addrs->lastaddr.multi = VIR_TRISTATE_SWITCH_ABSENT;
            }
            /* Finally we can reserve the slot+function */
            if (virDomainPCIAddressReserveAddr(addrs, &addr, flags,
                                               false, foundAddr) < 0)
                goto error;

1166 1167
            cont->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
            cont->info.addr.pci = addr;
1168 1169
        } else {
            if (virDomainPCIAddressReserveNextSlot(addrs,
1170
                                                   &cont->info, flags) < 0) {
1171
                goto error;
1172
            }
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
        }
    }

    /* 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 */
1183
        if (virDeviceInfoPCIAddressPresent(&def->disks[i]->info) ||
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
            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;

1196
        if (!virDeviceInfoPCIAddressWanted(&def->disks[i]->info)) {
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("virtio disk cannot have an address of type '%s'"),
                           virDomainDeviceAddressTypeToString(def->disks[i]->info.type));
            goto error;
        }

        if (virDomainPCIAddressReserveNextSlot(addrs, &def->disks[i]->info,
                                               flags) < 0)
            goto error;
    }

    /* Host PCI devices */
    for (i = 0; i < def->nhostdevs; i++) {
1210
        if (!virDeviceInfoPCIAddressWanted(def->hostdevs[i]->info))
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
            continue;
        if (def->hostdevs[i]->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
            def->hostdevs[i]->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI)
            continue;

        if (virDomainPCIAddressReserveNextSlot(addrs,
                                               def->hostdevs[i]->info,
                                               flags) < 0)
            goto error;
    }

    /* VirtIO balloon */
    if (def->memballoon &&
        def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO &&
1225
        virDeviceInfoPCIAddressWanted(&def->memballoon->info)) {
1226 1227 1228 1229 1230 1231 1232 1233 1234
        if (virDomainPCIAddressReserveNextSlot(addrs,
                                               &def->memballoon->info,
                                               flags) < 0)
            goto error;
    }

    /* VirtIO RNG */
    for (i = 0; i < def->nrngs; i++) {
        if (def->rngs[i]->model != VIR_DOMAIN_RNG_MODEL_VIRTIO ||
1235
            !virDeviceInfoPCIAddressWanted(&def->rngs[i]->info))
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
            continue;

        if (virDomainPCIAddressReserveNextSlot(addrs,
                                               &def->rngs[i]->info, flags) < 0)
            goto error;
    }

    /* A watchdog - check if it is a PCI device */
    if (def->watchdog &&
        def->watchdog->model == VIR_DOMAIN_WATCHDOG_MODEL_I6300ESB &&
1246
        virDeviceInfoPCIAddressWanted(&def->watchdog->info)) {
1247 1248 1249 1250 1251 1252 1253 1254
        if (virDomainPCIAddressReserveNextSlot(addrs, &def->watchdog->info,
                                               flags) < 0)
            goto error;
    }

    /* Assign a PCI slot to the primary video card if there is not an
     * assigned address. */
    if (def->nvideos > 0 &&
1255
        virDeviceInfoPCIAddressWanted(&def->videos[0]->info)) {
1256 1257 1258 1259 1260 1261
        if (virDomainPCIAddressReserveNextSlot(addrs, &def->videos[0]->info,
                                               flags) < 0)
            goto error;
    }

    for (i = 1; i < def->nvideos; i++) {
1262
        if (!virDeviceInfoPCIAddressWanted(&def->videos[i]->info))
1263 1264 1265 1266 1267 1268 1269 1270
            continue;
        if (virDomainPCIAddressReserveNextSlot(addrs, &def->videos[i]->info,
                                               flags) < 0)
            goto error;
    }

    /* Shared Memory */
    for (i = 0; i < def->nshmems; i++) {
1271
        if (!virDeviceInfoPCIAddressWanted(&def->shmems[i]->info))
1272 1273 1274 1275 1276 1277 1278
            continue;

        if (virDomainPCIAddressReserveNextSlot(addrs,
                                               &def->shmems[i]->info, flags) < 0)
            goto error;
    }
    for (i = 0; i < def->ninputs; i++) {
1279 1280
        if (def->inputs[i]->bus != VIR_DOMAIN_INPUT_BUS_VIRTIO ||
            !virDeviceInfoPCIAddressWanted(&def->inputs[i]->info))
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
            continue;

        if (virDomainPCIAddressReserveNextSlot(addrs,
                                               &def->inputs[i]->info, flags) < 0)
            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];

1293 1294
        if (chr->targetType != VIR_DOMAIN_CHR_SERIAL_TARGET_TYPE_PCI ||
            !virDeviceInfoPCIAddressWanted(&chr->info))
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
            continue;

        if (virDomainPCIAddressReserveNextSlot(addrs, &chr->info, flags) < 0)
            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) */
    }

    return 0;

 error:
    return -1;
}


static bool
qemuDomainSupportsPCI(virDomainDefPtr def,
                      virQEMUCapsPtr qemuCaps)
{
    if ((def->os.arch != VIR_ARCH_ARMV7L) && (def->os.arch != VIR_ARCH_AARCH64))
        return true;

    if (STREQ(def->os.machine, "versatilepb"))
        return true;

J
Ján Tomko 已提交
1324
    if (qemuDomainMachineIsVirt(def) &&
1325 1326 1327 1328 1329 1330 1331
        virQEMUCapsGet(qemuCaps, QEMU_CAPS_OBJECT_GPEX))
        return true;

    return false;
}


1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
static void
qemuDomainPCIControllerSetDefaultModelName(virDomainControllerDefPtr cont)
{
    int *modelName = &cont->opts.pciopts.modelName;

    /* make sure it's not already set */
    if (*modelName != VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_NONE)
        return;
    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;
    case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT_PORT:
        *modelName = VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_IOH3420;
        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;
1356
    case VIR_DOMAIN_CONTROLLER_MODEL_PCI_EXPANDER_BUS:
1357 1358
        *modelName = VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PXB;
        break;
1359
    case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_EXPANDER_BUS:
1360 1361
        *modelName = VIR_DOMAIN_CONTROLLER_PCI_MODEL_NAME_PXB_PCIE;
        break;
1362 1363 1364 1365 1366 1367 1368 1369
    case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
    case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
    case VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST:
        break;
    }
}


1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
static int
qemuDomainAddressFindNewBusNr(virDomainDefPtr def)
{
/* 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
1380
 *    implements the pci-expander-bus) includes a pci-bridge within
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
 *    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.
 */
    size_t i;
    int lowestBusNr = 256;

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

        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI) {
            int thisBusNr = cont->opts.pciopts.busNr;
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439

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


1440 1441 1442 1443 1444 1445 1446 1447
static int
qemuDomainAssignPCIAddresses(virDomainDefPtr def,
                             virQEMUCapsPtr qemuCaps,
                             virDomainObjPtr obj)
{
    int ret = -1;
    virDomainPCIAddressSetPtr addrs = NULL;
    qemuDomainObjPrivatePtr priv = NULL;
1448 1449 1450 1451 1452
    int max_idx = -1;
    int nbuses = 0;
    size_t i;
    int rv;
    bool buses_reserved = true;
1453

1454
    virDomainPCIConnectFlags flags = VIR_PCI_CONNECT_TYPE_PCI_DEVICE;
1455

1456
    for (i = 0; i < def->ncontrollers; i++) {
1457 1458 1459 1460 1461
        virDomainControllerDefPtr cont = def->controllers[i];

        if (cont->type == VIR_DOMAIN_CONTROLLER_TYPE_PCI) {
            if ((int) cont->idx > max_idx)
                max_idx = cont->idx;
1462
        }
1463
    }
1464

1465
    nbuses = max_idx + 1;
1466

1467 1468 1469
    if (nbuses > 0 &&
        virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_PCI_BRIDGE)) {
        virDomainDeviceInfo info;
1470

1471 1472 1473
        /* 1st pass to figure out how many PCI bridges we need */
        if (!(addrs = qemuDomainPCIAddressSetCreate(def, nbuses, true)))
            goto cleanup;
1474

1475 1476 1477
        if (qemuDomainValidateDevicePCISlotsChipsets(def, qemuCaps,
                                                     addrs) < 0)
            goto cleanup;
1478

1479 1480 1481 1482
        for (i = 0; i < addrs->nbuses; i++) {
            if (!qemuDomainPCIBusFullyReserved(&addrs->buses[i]))
                buses_reserved = false;
        }
1483

1484
        /* Reserve 1 extra slot for a (potential) bridge only if buses
1485 1486 1487 1488 1489 1490
         * are not fully reserved yet.
         *
         * We don't reserve the extra slot for aarch64 mach-virt guests
         * either because we want to be able to have pure virtio-mmio
         * guests, and reserving this slot would force us to add at least
         * a dmi-to-pci-bridge to an otherwise PCI-free topology
1491 1492
         */
        if (!buses_reserved &&
1493
            !qemuDomainMachineIsVirt(def) &&
1494 1495
            virDomainPCIAddressReserveNextSlot(addrs, &info, flags) < 0)
            goto cleanup;
1496

1497 1498
        if (qemuDomainAssignDevicePCISlots(def, qemuCaps, addrs) < 0)
            goto cleanup;
1499

1500 1501
        for (i = 1; i < addrs->nbuses; i++) {
            virDomainPCIAddressBusPtr bus = &addrs->buses[i];
1502

1503 1504 1505 1506 1507 1508 1509 1510
            if ((rv = virDomainDefMaybeAddController(
                     def, VIR_DOMAIN_CONTROLLER_TYPE_PCI,
                     i, bus->model)) < 0)
                goto cleanup;
            /* If we added a new bridge, we will need one more address */
            if (rv > 0 &&
                virDomainPCIAddressReserveNextSlot(addrs, &info, flags) < 0)
                goto cleanup;
1511
        }
1512 1513 1514
        nbuses = addrs->nbuses;
        virDomainPCIAddressSetFree(addrs);
        addrs = NULL;
1515

1516 1517 1518 1519 1520 1521
    } else if (max_idx > 0) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("PCI bridges are not supported "
                         "by this QEMU binary"));
        goto cleanup;
    }
1522

1523 1524
    if (!(addrs = qemuDomainPCIAddressSetCreate(def, nbuses, false)))
        goto cleanup;
1525

1526 1527 1528 1529
    if (qemuDomainSupportsPCI(def, qemuCaps)) {
        if (qemuDomainValidateDevicePCISlotsChipsets(def, qemuCaps,
                                                     addrs) < 0)
            goto cleanup;
1530

1531 1532
        if (qemuDomainAssignDevicePCISlots(def, qemuCaps, addrs) < 0)
            goto cleanup;
1533

1534 1535 1536 1537 1538
        for (i = 0; i < def->ncontrollers; i++) {
            virDomainControllerDefPtr cont = def->controllers[i];
            int idx = cont->idx;
            virPCIDeviceAddressPtr addr;
            virDomainPCIControllerOptsPtr options;
1539

1540 1541
            if (cont->type != VIR_DOMAIN_CONTROLLER_TYPE_PCI)
                continue;
1542

1543 1544
            addr = &cont->info.addr.pci;
            options = &cont->opts.pciopts;
1545

1546 1547 1548 1549 1550
            /* set default model name (the actual name of the
             * device in qemu) for any controller that doesn't yet
             * have it set.
             */
            qemuDomainPCIControllerSetDefaultModelName(cont);
1551

1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
            /* 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) {
1578
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1579 1580 1581 1582 1583
                                   _("No free busNr lower than current "
                                     "lowest busNr is available to "
                                     "auto-assign to bus %d. Must be "
                                     "manually assigned"),
                                   addr->bus);
1584 1585
                    goto cleanup;
                }
1586 1587 1588 1589 1590 1591 1592 1593 1594
                break;
            case VIR_DOMAIN_CONTROLLER_MODEL_DMI_TO_PCI_BRIDGE:
            case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_SWITCH_UPSTREAM_PORT:
            case VIR_DOMAIN_CONTROLLER_MODEL_PCI_ROOT:
            case VIR_DOMAIN_CONTROLLER_MODEL_PCIE_ROOT:
            case VIR_DOMAIN_CONTROLLER_MODEL_PCI_LAST:
                break;
            }

1595
            /* check if every PCI bridge controller's index is larger than
1596 1597 1598 1599 1600 1601
             * 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 "
1602 1603
                                 "bus='0x%02x', but index must be "
                                 "larger than bus"),
1604 1605
                               idx, idx, addr->bus);
                goto cleanup;
1606 1607 1608 1609 1610 1611
            }
        }
    }

    if (obj && obj->privateData) {
        priv = obj->privateData;
J
John Ferlan 已提交
1612 1613 1614 1615
        /* if this is the live domain object, we persist the PCI addresses */
        virDomainPCIAddressSetFree(priv->pciaddrs);
        priv->pciaddrs = addrs;
        addrs = NULL;
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
    }

    ret = 0;

 cleanup:
    virDomainPCIAddressSetFree(addrs);

    return ret;
}


J
Ján Tomko 已提交
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
struct qemuAssignUSBIteratorInfo {
    virDomainUSBAddressSetPtr addrs;
    size_t count;
};


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

    if (info->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
        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);
}


1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
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;
    int ret = -1;

    available_ports = virDomainUSBAddressCountAllPorts(def);
    ignore_value(virDomainUSBDeviceDefForeach(def,
                                              qemuDomainAssignUSBPortsCounter,
                                              &data,
                                              false));
    VIR_DEBUG("Found %zu USB devices and %zu provided USB ports",
              data.count, available_ports);

    /* Add one hub if there are more devices than ports
     * otherwise it's up to the user to specify more hubs/controllers */
    if (data.count > available_ports) {
        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;
}


J
Ján Tomko 已提交
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
static int
qemuDomainAssignUSBAddresses(virDomainDefPtr def,
                             virDomainObjPtr obj)
{
    int ret = -1;
    virDomainUSBAddressSetPtr addrs = NULL;
    qemuDomainObjPrivatePtr priv = NULL;

    if (!(addrs = virDomainUSBAddressSetCreate()))
        goto cleanup;

1740 1741 1742
    if (qemuDomainUSBAddressAddHubs(def) < 0)
        goto cleanup;

J
Ján Tomko 已提交
1743 1744 1745 1746 1747 1748 1749 1750 1751
    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 已提交
1752 1753 1754 1755 1756 1757 1758 1759
    if (qemuDomainAssignUSBHubs(addrs, def) < 0)
        goto cleanup;

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

    VIR_DEBUG("Finished assigning USB ports");

J
Ján Tomko 已提交
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
    if (obj && obj->privateData) {
        priv = obj->privateData;
        priv->usbaddrs = addrs;
        addrs = NULL;
    }
    ret = 0;

 cleanup:
    virDomainUSBAddressSetFree(addrs);
    return ret;
}


1773 1774 1775
int
qemuDomainAssignAddresses(virDomainDefPtr def,
                          virQEMUCapsPtr qemuCaps,
1776
                          virDomainObjPtr obj,
J
Ján Tomko 已提交
1777
                          bool newDomain)
1778
{
1779
    if (qemuDomainAssignVirtioSerialAddresses(def) < 0)
1780
        return -1;
1781

1782 1783
    if (qemuDomainAssignSpaprVIOAddresses(def, qemuCaps) < 0)
        return -1;
1784

T
Tomasz Flendrich 已提交
1785
    if (qemuDomainAssignS390Addresses(def, qemuCaps) < 0)
1786
        return -1;
1787

1788
    qemuDomainAssignARMVirtioMMIOAddresses(def, qemuCaps);
1789

1790 1791 1792
    if (qemuDomainAssignPCIAddresses(def, qemuCaps, obj) < 0)
        return -1;

J
Ján Tomko 已提交
1793 1794 1795
    if (newDomain && qemuDomainAssignUSBAddresses(def, obj) < 0)
        return -1;

1796
    return 0;
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
}


void
qemuDomainReleaseDeviceAddress(virDomainObjPtr vm,
                               virDomainDeviceInfoPtr info,
                               const char *devstr)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (!devstr)
        devstr = info->alias;

T
Tomasz Flendrich 已提交
1810 1811 1812
    if (virDeviceInfoPCIAddressPresent(info) &&
        virDomainPCIAddressReleaseSlot(priv->pciaddrs,
                                       &info->addr.pci) < 0)
1813 1814
        VIR_WARN("Unable to release PCI address on %s",
                 NULLSTR(devstr));
1815

1816 1817 1818 1819 1820
    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_USB &&
        priv->usbaddrs &&
        virDomainUSBAddressRelease(priv->usbaddrs, info) < 0)
        VIR_WARN("Unable to release USB address on %s",
                 NULLSTR(devstr));
1821
}