qemu_hostdev.c 46.6 KB
Newer Older
1 2 3
/*
 * qemu_hostdev.c: QEMU hostdev management
 *
4
 * Copyright (C) 2006-2007, 2009-2013 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

26 27 28 29 30
#include <dirent.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <errno.h>

31
#include "qemu_hostdev.h"
32
#include "virlog.h"
33
#include "virerror.h"
34
#include "viralloc.h"
35
#include "virpci.h"
36
#include "virusb.h"
37
#include "virscsi.h"
38
#include "virnetdev.h"
39
#include "virfile.h"
40

41 42
#define VIR_FROM_THIS VIR_FROM_QEMU

43
static virPCIDeviceListPtr
44 45
qemuGetPciHostDeviceList(virDomainHostdevDefPtr *hostdevs, int nhostdevs)
{
46
    virPCIDeviceListPtr list;
47
    size_t i;
48

49
    if (!(list = virPCIDeviceListNew()))
50 51
        return NULL;

52
    for (i = 0; i < nhostdevs; i++) {
53
        virDomainHostdevDefPtr hostdev = hostdevs[i];
54
        virPCIDevicePtr dev;
55 56 57 58 59 60

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

61 62 63 64
        dev = virPCIDeviceNew(hostdev->source.subsys.u.pci.addr.domain,
                              hostdev->source.subsys.u.pci.addr.bus,
                              hostdev->source.subsys.u.pci.addr.slot,
                              hostdev->source.subsys.u.pci.addr.function);
65
        if (!dev) {
66
            virObjectUnref(list);
67 68 69
            return NULL;
        }

70 71
        if (virPCIDeviceListAdd(list, dev) < 0) {
            virPCIDeviceFree(dev);
72
            virObjectUnref(list);
73 74 75
            return NULL;
        }

76
        virPCIDeviceSetManaged(dev, hostdev->managed);
77
        if (hostdev->source.subsys.u.pci.backend
78
            == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
79 80 81 82
            if (virPCIDeviceSetStubDriver(dev, "vfio-pci") < 0) {
                virObjectUnref(list);
                return NULL;
            }
83
        } else {
84 85 86 87
            if (virPCIDeviceSetStubDriver(dev, "pci-stub") < 0) {
                virObjectUnref(list);
                return NULL;
            }
88
        }
89 90 91 92 93
    }

    return list;
}

94

95
/*
96 97 98 99 100 101
 * qemuGetActivePciHostDeviceList - make a new list with a *copy* of
 *   every virPCIDevice object that is found on the activePciHostdevs
 *   list *and* is in the hostdev list for this domain.
 *
 * Return the new list, or NULL if there was a failure.
 *
102 103
 * Pre-condition: driver->activePciHostdevs is locked
 */
104
static virPCIDeviceListPtr
105
qemuGetActivePciHostDeviceList(virQEMUDriverPtr driver,
106 107 108
                               virDomainHostdevDefPtr *hostdevs,
                               int nhostdevs)
{
109
    virPCIDeviceListPtr list;
110
    size_t i;
111

112
    if (!(list = virPCIDeviceListNew()))
113 114
        return NULL;

115
    for (i = 0; i < nhostdevs; i++) {
116
        virDomainHostdevDefPtr hostdev = hostdevs[i];
117
        virDevicePCIAddressPtr addr;
118
        virPCIDevicePtr activeDev;
119 120 121 122 123 124

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

125 126 127 128 129
        addr = &hostdev->source.subsys.u.pci.addr;
        activeDev = virPCIDeviceListFindByIDs(driver->activePciHostdevs,
                                              addr->domain, addr->bus,
                                              addr->slot, addr->function);
        if (activeDev && virPCIDeviceListAddCopy(list, activeDev) < 0) {
130
            virObjectUnref(list);
131 132 133 134 135 136
            return NULL;
        }
    }

    return list;
}
137

138 139 140 141

int
qemuUpdateActivePciHostdevs(virQEMUDriverPtr driver,
                            virDomainDefPtr def)
142
{
143
    virDomainHostdevDefPtr hostdev = NULL;
144
    virPCIDevicePtr dev = NULL;
145
    size_t i;
146
    int ret = -1;
147 148 149 150

    if (!def->nhostdevs)
        return 0;

151 152 153
    virObjectLock(driver->activePciHostdevs);
    virObjectLock(driver->inactivePciHostdevs);

154 155 156 157 158 159 160 161
    for (i = 0; i < def->nhostdevs; i++) {
        hostdev = def->hostdevs[i];

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

162 163 164 165
        dev = virPCIDeviceNew(hostdev->source.subsys.u.pci.addr.domain,
                              hostdev->source.subsys.u.pci.addr.bus,
                              hostdev->source.subsys.u.pci.addr.slot,
                              hostdev->source.subsys.u.pci.addr.function);
166 167

        if (!dev)
168
            goto cleanup;
169

170
        virPCIDeviceSetManaged(dev, hostdev->managed);
171
        if (hostdev->source.subsys.u.pci.backend
172
            == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
173 174
            if (virPCIDeviceSetStubDriver(dev, "vfio-pci") < 0)
                goto cleanup;
175
        } else {
176 177 178
            if (virPCIDeviceSetStubDriver(dev, "pci-stub") < 0)
                goto cleanup;

179
        }
180
        virPCIDeviceSetUsedBy(dev, def->name);
181 182

        /* Setup the original states for the PCI device */
183 184 185
        virPCIDeviceSetUnbindFromStub(dev, hostdev->origstates.states.pci.unbind_from_stub);
        virPCIDeviceSetRemoveSlot(dev, hostdev->origstates.states.pci.remove_slot);
        virPCIDeviceSetReprobe(dev, hostdev->origstates.states.pci.reprobe);
186

187
        if (virPCIDeviceListAdd(driver->activePciHostdevs, dev) < 0)
188
            goto cleanup;
189
        dev = NULL;
190 191
    }

192
    ret = 0;
193
cleanup:
194
    virPCIDeviceFree(dev);
195 196 197
    virObjectUnlock(driver->activePciHostdevs);
    virObjectUnlock(driver->inactivePciHostdevs);
    return ret;
198 199
}

200

201
int
202
qemuUpdateActiveUsbHostdevs(virQEMUDriverPtr driver,
203 204 205
                            virDomainDefPtr def)
{
    virDomainHostdevDefPtr hostdev = NULL;
206
    size_t i;
207
    int ret = -1;
208 209 210 211

    if (!def->nhostdevs)
        return 0;

212
    virObjectLock(driver->activeUsbHostdevs);
213
    for (i = 0; i < def->nhostdevs; i++) {
214
        virUSBDevicePtr usb = NULL;
215 216 217 218 219 220 221
        hostdev = def->hostdevs[i];

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

222 223 224
        usb = virUSBDeviceNew(hostdev->source.subsys.u.usb.bus,
                              hostdev->source.subsys.u.usb.device,
                              NULL);
225 226 227 228 229 230 231 232
        if (!usb) {
            VIR_WARN("Unable to reattach USB device %03d.%03d on domain %s",
                     hostdev->source.subsys.u.usb.bus,
                     hostdev->source.subsys.u.usb.device,
                     def->name);
            continue;
        }

233
        virUSBDeviceSetUsedBy(usb, def->name);
234

235 236
        if (virUSBDeviceListAdd(driver->activeUsbHostdevs, usb) < 0) {
            virUSBDeviceFree(usb);
237
            goto cleanup;
238 239
        }
    }
240 241 242 243
    ret = 0;
cleanup:
    virObjectUnlock(driver->activeUsbHostdevs);
    return ret;
244 245
}

246 247 248 249 250
int
qemuUpdateActiveScsiHostdevs(virQEMUDriverPtr driver,
                             virDomainDefPtr def)
{
    virDomainHostdevDefPtr hostdev = NULL;
251
    size_t i;
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    int ret = -1;

    if (!def->nhostdevs)
        return 0;

    virObjectLock(driver->activeScsiHostdevs);
    for (i = 0; i < def->nhostdevs; i++) {
        virSCSIDevicePtr scsi = NULL;
        hostdev = def->hostdevs[i];

        if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
            hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI)
            continue;

        if (!(scsi = virSCSIDeviceNew(hostdev->source.subsys.u.scsi.adapter,
                                      hostdev->source.subsys.u.scsi.bus,
                                      hostdev->source.subsys.u.scsi.target,
                                      hostdev->source.subsys.u.scsi.unit,
270 271
                                      hostdev->readonly,
                                      hostdev->shareable)))
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
            goto cleanup;

        virSCSIDeviceSetUsedBy(scsi, def->name);

        if (virSCSIDeviceListAdd(driver->activeScsiHostdevs, scsi) < 0) {
            virSCSIDeviceFree(scsi);
            goto cleanup;
        }
    }
    ret = 0;

cleanup:
    virObjectUnlock(driver->activeScsiHostdevs);
    return ret;
}

288

289
static int
290 291
qemuDomainHostdevPciSysfsPath(virDomainHostdevDefPtr hostdev,
                              char **sysfs_path)
292
{
293
    virPCIDeviceAddress config_address;
294

295 296 297 298
    config_address.domain = hostdev->source.subsys.u.pci.addr.domain;
    config_address.bus = hostdev->source.subsys.u.pci.addr.bus;
    config_address.slot = hostdev->source.subsys.u.pci.addr.slot;
    config_address.function = hostdev->source.subsys.u.pci.addr.function;
299

300
    return virPCIDeviceAddressGetSysfsFile(&config_address, sysfs_path);
301 302
}

303

304 305 306 307 308 309 310 311 312
int
qemuDomainHostdevIsVirtualFunction(virDomainHostdevDefPtr hostdev)
{
    char *sysfs_path = NULL;
    int ret = -1;

    if (qemuDomainHostdevPciSysfsPath(hostdev, &sysfs_path) < 0)
        return ret;

313
    ret = virPCIIsVirtualFunction(sysfs_path);
314 315 316 317 318 319

    VIR_FREE(sysfs_path);

    return ret;
}

320

321 322 323 324 325 326 327 328 329 330
static int
qemuDomainHostdevNetDevice(virDomainHostdevDefPtr hostdev, char **linkdev,
                           int *vf)
{
    int ret = -1;
    char *sysfs_path = NULL;

    if (qemuDomainHostdevPciSysfsPath(hostdev, &sysfs_path) < 0)
        return ret;

331 332 333
    if (virPCIIsVirtualFunction(sysfs_path) == 1) {
        if (virPCIGetVirtualFunctionInfo(sysfs_path, linkdev,
                                         vf) < 0)
334 335
            goto cleanup;
    } else {
336
        if (virPCIGetNetName(sysfs_path, linkdev) < 0)
337 338 339 340 341 342 343 344 345 346 347 348
            goto cleanup;
        *vf = -1;
    }

    ret = 0;

cleanup:
    VIR_FREE(sysfs_path);

    return ret;
}

349

350 351 352
static int
qemuDomainHostdevNetConfigVirtPortProfile(const char *linkdev, int vf,
                                          virNetDevVPortProfilePtr virtPort,
E
Eric Blake 已提交
353
                                          const virMacAddr *macaddr,
354
                                          const unsigned char *uuid,
355
                                          bool associate)
356 357 358 359 360 361
{
    int ret = -1;

    if (!virtPort)
        return ret;

362
    switch (virtPort->virtPortType) {
363 364 365 366
    case VIR_NETDEV_VPORT_PROFILE_NONE:
    case VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH:
    case VIR_NETDEV_VPORT_PROFILE_8021QBG:
    case VIR_NETDEV_VPORT_PROFILE_LAST:
367 368 369 370 371
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("virtualport type %s is "
                         "currently not supported on interfaces of type "
                         "hostdev"),
                       virNetDevVPortTypeToString(virtPort->virtPortType));
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
        break;

    case VIR_NETDEV_VPORT_PROFILE_8021QBH:
        if (associate)
            ret = virNetDevVPortProfileAssociate(NULL, virtPort, macaddr,
                                                 linkdev, vf, uuid,
                                                 VIR_NETDEV_VPORT_PROFILE_OP_CREATE, false);
        else
            ret = virNetDevVPortProfileDisassociate(NULL, virtPort,
                                                    macaddr, linkdev, vf,
                                                    VIR_NETDEV_VPORT_PROFILE_OP_DESTROY);
        break;
    }

    return ret;
}

389

390 391 392 393 394 395
int
qemuDomainHostdevNetConfigReplace(virDomainHostdevDefPtr hostdev,
                                  const unsigned char *uuid,
                                  char *stateDir)
{
    char *linkdev = NULL;
396
    virNetDevVlanPtr vlan;
397 398 399 400
    virNetDevVPortProfilePtr virtPort;
    int ret = -1;
    int vf = -1;
    int vlanid = -1;
401
    bool port_profile_associate = true;
402 403 404 405
    int isvf;

    isvf = qemuDomainHostdevIsVirtualFunction(hostdev);
    if (isvf <= 0) {
406 407 408
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Interface type hostdev is currently supported on"
                         " SR-IOV Virtual Functions only"));
409 410 411 412 413 414
        return ret;
    }

    if (qemuDomainHostdevNetDevice(hostdev, &linkdev, &vf) < 0)
        return ret;

415
    vlan = virDomainNetGetActualVlan(hostdev->parent.data.net);
416 417
    virtPort = virDomainNetGetActualVirtPortProfile(
                                 hostdev->parent.data.net);
418 419 420 421 422 423 424 425
    if (virtPort) {
        if (vlan) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("direct setting of the vlan tag is not allowed "
                             "for hostdev devices using %s mode"),
                           virNetDevVPortTypeToString(virtPort->virtPortType));
            goto cleanup;
        }
426
        ret = qemuDomainHostdevNetConfigVirtPortProfile(linkdev, vf,
427
                            virtPort, &hostdev->parent.data.net->mac, uuid,
428
                            port_profile_associate);
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
    } else {
        /* Set only mac and vlan */
        if (vlan) {
            if (vlan->nTags != 1 || vlan->trunk) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("vlan trunking is not supported "
                                 "by SR-IOV network devices"));
                goto cleanup;
            }
            if (vf == -1) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("vlan can only be set for SR-IOV VFs, but "
                                 "%s is not a VF"), linkdev);
                goto cleanup;
            }
            vlanid = vlan->tag[0];
        } else  if (vf >= 0) {
            vlanid = 0; /* assure any current vlan tag is reset */
        }

449
        ret = virNetDevReplaceNetConfig(linkdev, vf,
450 451 452 453
                                        &hostdev->parent.data.net->mac,
                                        vlanid, stateDir);
    }
cleanup:
454 455 456 457
    VIR_FREE(linkdev);
    return ret;
}

458

459 460 461 462 463 464 465 466
int
qemuDomainHostdevNetConfigRestore(virDomainHostdevDefPtr hostdev,
                                  char *stateDir)
{
    char *linkdev = NULL;
    virNetDevVPortProfilePtr virtPort;
    int ret = -1;
    int vf = -1;
467
    bool port_profile_associate = false;
468 469
    int isvf;

470 471 472 473 474 475 476 477 478
    /* This is only needed for PCI devices that have been defined
     * using <interface type='hostdev'>. For all others, it is a NOP.
     */
    if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
        hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI ||
        hostdev->parent.type != VIR_DOMAIN_DEVICE_NET ||
        !hostdev->parent.data.net)
       return 0;

479 480
    isvf = qemuDomainHostdevIsVirtualFunction(hostdev);
    if (isvf <= 0) {
481 482 483
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Interface type hostdev is currently supported on"
                         " SR-IOV Virtual Functions only"));
484 485 486 487 488 489 490 491 492 493
        return ret;
    }

    if (qemuDomainHostdevNetDevice(hostdev, &linkdev, &vf) < 0)
        return ret;

    virtPort = virDomainNetGetActualVirtPortProfile(
                                 hostdev->parent.data.net);
    if (virtPort)
        ret = qemuDomainHostdevNetConfigVirtPortProfile(linkdev, vf, virtPort,
494
                                          &hostdev->parent.data.net->mac, NULL,
495 496 497 498 499 500 501 502 503
                                          port_profile_associate);
    else
        ret = virNetDevRestoreNetConfig(linkdev, vf, stateDir);

    VIR_FREE(linkdev);

    return ret;
}

504

505
bool
506 507 508 509 510 511 512 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
qemuHostdevHostSupportsPassthroughVFIO(void)
{
    DIR *iommuDir = NULL;
    struct dirent *iommuGroup = NULL;
    bool ret = false;

    /* condition 1 - /sys/kernel/iommu_groups/ contains entries */
    if (!(iommuDir = opendir("/sys/kernel/iommu_groups/")))
        goto cleanup;

    while ((iommuGroup = readdir(iommuDir))) {
        /* skip ./ ../ */
        if (STRPREFIX(iommuGroup->d_name, "."))
            continue;

        /* assume we found a group */
        break;
    }

    if (!iommuGroup)
        goto cleanup;
    /* okay, iommu is on and recognizes groups */

    /* condition 2 - /dev/vfio/vfio exists */
    if (!virFileExists("/dev/vfio/vfio"))
        goto cleanup;

    ret = true;

cleanup:
    if (iommuDir)
        closedir(iommuDir);

    return ret;
}


#if HAVE_LINUX_KVM_H
# include <linux/kvm.h>
545
bool
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
qemuHostdevHostSupportsPassthroughLegacy(void)
{
    int kvmfd = -1;
    bool ret = false;

    if ((kvmfd = open("/dev/kvm", O_RDONLY)) < 0)
        goto cleanup;

# ifdef KVM_CAP_IOMMU
    if ((ioctl(kvmfd, KVM_CHECK_EXTENSION, KVM_CAP_IOMMU)) <= 0)
        goto cleanup;

    ret = true;
# endif

cleanup:
    VIR_FORCE_CLOSE(kvmfd);

    return ret;
}
#else
567
bool
568 569 570 571 572 573 574 575 576
qemuHostdevHostSupportsPassthroughLegacy(void)
{
    return false;
}
#endif


static bool
qemuPrepareHostdevPCICheckSupport(virDomainHostdevDefPtr *hostdevs,
577 578
                                  size_t nhostdevs,
                                  virQEMUCapsPtr qemuCaps)
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
{
    bool supportsPassthroughKVM = qemuHostdevHostSupportsPassthroughLegacy();
    bool supportsPassthroughVFIO = qemuHostdevHostSupportsPassthroughVFIO();
    size_t i;

    /* assign defaults for hostdev passthrough */
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
        int *backend = &hostdev->source.subsys.u.pci.backend;

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

        switch ((virDomainHostdevSubsysPciBackendType) *backend) {
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
        case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_DEFAULT:
            if (supportsPassthroughVFIO &&
                virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE_VFIO_PCI)) {
                *backend = VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO;
            } else if (supportsPassthroughKVM &&
                       (virQEMUCapsGet(qemuCaps, QEMU_CAPS_PCIDEVICE) ||
                        virQEMUCapsGet(qemuCaps, QEMU_CAPS_DEVICE))) {
                *backend = VIR_DOMAIN_HOSTDEV_PCI_BACKEND_KVM;
            } else {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("host doesn't support passthrough of "
                                 "host PCI devices"));
                return false;
            }

            break;

612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
        case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO:
            if (!supportsPassthroughVFIO) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("host doesn't support VFIO PCI passthrough"));
                return false;
            }
            break;

        case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_KVM:
            if (!supportsPassthroughKVM) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("host doesn't support legacy PCI passthrough"));
                return false;
            }

            break;

        case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_TYPE_LAST:
            break;
        }
    }

    return true;
}


638 639 640 641 642
int
qemuPrepareHostdevPCIDevices(virQEMUDriverPtr driver,
                             const char *name,
                             const unsigned char *uuid,
                             virDomainHostdevDefPtr *hostdevs,
643 644
                             int nhostdevs,
                             virQEMUCapsPtr qemuCaps)
645
{
646
    virPCIDeviceListPtr pcidevs = NULL;
647
    int last_processed_hostdev_vf = -1;
648
    size_t i;
649
    int ret = -1;
650
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
651

652
    if (!qemuPrepareHostdevPCICheckSupport(hostdevs, nhostdevs, qemuCaps))
653 654
        goto cleanup;

655 656 657
    virObjectLock(driver->activePciHostdevs);
    virObjectLock(driver->inactivePciHostdevs);

658
    if (!(pcidevs = qemuGetPciHostDeviceList(hostdevs, nhostdevs)))
659
        goto cleanup;
660

661
    /* We have to use 9 loops here. *All* devices must
662 663 664 665 666 667
     * be detached before we reset any of them, because
     * in some cases you have to reset the whole PCI,
     * which impacts all devices on it. Also, all devices
     * must be reset before being marked as active.
     */

668
    /* Loop 1: validate that non-managed device isn't in use, eg
669 670 671 672
     * by checking that device is either un-bound, or bound
     * to pci-stub.ko
     */

673 674 675
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
        virPCIDevicePtr other;
676

677
        if (!virPCIDeviceIsAssignable(dev, !cfg->relaxedACS)) {
678 679
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is not assignable"),
680
                           virPCIDeviceGetName(dev));
681 682 683 684 685
            goto cleanup;
        }
        /* The device is in use by other active domain if
         * the dev is in list driver->activePciHostdevs.
         */
686 687
        if ((other = virPCIDeviceListFind(driver->activePciHostdevs, dev))) {
            const char *other_name = virPCIDeviceGetUsedBy(other);
688 689

            if (other_name)
690 691
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("PCI device %s is in use by domain %s"),
692
                               virPCIDeviceGetName(dev), other_name);
693
            else
694 695
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("PCI device %s is already in use"),
696
                               virPCIDeviceGetName(dev));
697 698 699 700
            goto cleanup;
        }
    }

701
    /* Loop 2: detach managed devices (i.e. bind to appropriate stub driver) */
702 703 704
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
        if (virPCIDeviceGetManaged(dev) &&
705
            virPCIDeviceDetach(dev, driver->activePciHostdevs, NULL) < 0)
706
            goto reattachdevs;
707 708
    }

709 710
    /* Loop 3: Now that all the PCI hostdevs have been detached, we
     * can safely reset them */
711 712
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
713

714 715
        if (virPCIDeviceReset(dev, driver->activePciHostdevs,
                              driver->inactivePciHostdevs) < 0)
716
            goto reattachdevs;
717 718
    }

719 720 721 722 723 724 725 726 727 728 729
    /* Loop 4: For SRIOV network devices, Now that we have detached the
     * the network device, set the netdev config */
    for (i = 0; i < nhostdevs; i++) {
         virDomainHostdevDefPtr hostdev = hostdevs[i];
         if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
             continue;
         if (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI)
             continue;
         if (hostdev->parent.type == VIR_DOMAIN_DEVICE_NET &&
             hostdev->parent.data.net) {
             if (qemuDomainHostdevNetConfigReplace(hostdev, uuid,
730
                                                   cfg->stateDir) < 0) {
731 732 733 734 735 736 737
                 goto resetvfnetconfig;
             }
         }
         last_processed_hostdev_vf = i;
    }

    /* Loop 5: Now mark all the devices as active */
738 739 740
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
        if (virPCIDeviceListAdd(driver->activePciHostdevs, dev) < 0)
741
            goto inactivedevs;
742 743
    }

744
    /* Loop 6: Now remove the devices from inactive list. */
745 746 747
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
         virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
         virPCIDeviceListDel(driver->inactivePciHostdevs, dev);
748 749
    }

750
    /* Loop 7: Now set the used_by_domain of the device in
751 752
     * driver->activePciHostdevs as domain name.
     */
753 754
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev, activeDev;
755

756 757
        dev = virPCIDeviceListGet(pcidevs, i);
        activeDev = virPCIDeviceListFind(driver->activePciHostdevs, dev);
758

759
        if (activeDev)
760
            virPCIDeviceSetUsedBy(activeDev, name);
761 762
    }

763
    /* Loop 8: Now set the original states for hostdev def */
764
    for (i = 0; i < nhostdevs; i++) {
765 766
        virPCIDevicePtr dev;
        virPCIDevicePtr pcidev;
767 768 769 770 771 772 773
        virDomainHostdevDefPtr hostdev = hostdevs[i];

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

774 775 776 777
        dev = virPCIDeviceNew(hostdev->source.subsys.u.pci.addr.domain,
                              hostdev->source.subsys.u.pci.addr.bus,
                              hostdev->source.subsys.u.pci.addr.slot,
                              hostdev->source.subsys.u.pci.addr.function);
778 779 780 781 782

        /* original states "unbind_from_stub", "remove_slot",
         * "reprobe" were already set by pciDettachDevice in
         * loop 2.
         */
783
        if ((pcidev = virPCIDeviceListFind(pcidevs, dev))) {
784
            hostdev->origstates.states.pci.unbind_from_stub =
785
                virPCIDeviceGetUnbindFromStub(pcidev);
786
            hostdev->origstates.states.pci.remove_slot =
787
                virPCIDeviceGetRemoveSlot(pcidev);
788
            hostdev->origstates.states.pci.reprobe =
789
                virPCIDeviceGetReprobe(pcidev);
790 791
        }

792
        virPCIDeviceFree(dev);
793 794
    }

795
    /* Loop 9: Now steal all the devices from pcidevs */
796 797
    while (virPCIDeviceListCount(pcidevs) > 0)
        virPCIDeviceListStealIndex(pcidevs, 0);
798

799
    ret = 0;
800 801 802 803
    goto cleanup;

inactivedevs:
    /* Only steal all the devices from driver->activePciHostdevs. We will
804
     * free them in virObjectUnref().
805
     */
806 807
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
808
        virPCIDeviceListSteal(driver->activePciHostdevs, dev);
809
    }
810

811
resetvfnetconfig:
812 813 814
    for (i = 0;
         last_processed_hostdev_vf != -1 && i < last_processed_hostdev_vf; i++)
        qemuDomainHostdevNetConfigRestore(hostdevs[i], cfg->stateDir);
815

816
reattachdevs:
817 818
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
819 820 821 822

        /* NB: This doesn't actually re-bind to original driver, just
         * unbinds from the stub driver
         */
823 824
        ignore_value(virPCIDeviceReattach(dev, driver->activePciHostdevs,
                                          NULL));
825 826
    }

827
cleanup:
828 829
    virObjectUnlock(driver->activePciHostdevs);
    virObjectUnlock(driver->inactivePciHostdevs);
830
    virObjectUnref(pcidevs);
831
    virObjectUnref(cfg);
832 833 834
    return ret;
}

835

836
int
837
qemuPrepareHostdevUSBDevices(virQEMUDriverPtr driver,
838
                             const char *name,
839
                             virUSBDeviceListPtr list)
840
{
841
    size_t i, j;
842
    unsigned int count;
843
    virUSBDevicePtr tmp;
844

845
    virObjectLock(driver->activeUsbHostdevs);
846
    count = virUSBDeviceListCount(list);
847 848

    for (i = 0; i < count; i++) {
849 850 851
        virUSBDevicePtr usb = virUSBDeviceListGet(list, i);
        if ((tmp = virUSBDeviceListFind(driver->activeUsbHostdevs, usb))) {
            const char *other_name = virUSBDeviceGetUsedBy(tmp);
852 853

            if (other_name)
854 855
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("USB device %s is in use by domain %s"),
856
                               virUSBDeviceGetName(tmp), other_name);
857
            else
858 859
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("USB device %s is already in use"),
860
                               virUSBDeviceGetName(tmp));
861
            goto error;
862 863
        }

864
        virUSBDeviceSetUsedBy(usb, name);
865
        VIR_DEBUG("Adding %03d.%03d dom=%s to activeUsbHostdevs",
866
                  virUSBDeviceGetBus(usb), virUSBDeviceGetDevno(usb), name);
867 868
        /*
         * The caller is responsible to steal these usb devices
869
         * from the virUSBDeviceList that passed in on success,
870 871
         * perform rollback on failure.
         */
872
        if (virUSBDeviceListAdd(driver->activeUsbHostdevs, usb) < 0)
873
            goto error;
874
    }
875 876

    virObjectUnlock(driver->activeUsbHostdevs);
877
    return 0;
878 879 880

error:
    for (j = 0; j < i; j++) {
881 882
        tmp = virUSBDeviceListGet(list, i);
        virUSBDeviceListSteal(driver->activeUsbHostdevs, tmp);
883
    }
884
    virObjectUnlock(driver->activeUsbHostdevs);
885
    return -1;
886 887
}

888

889 890 891
int
qemuFindHostdevUSBDevice(virDomainHostdevDefPtr hostdev,
                         bool mandatory,
892
                         virUSBDevicePtr *usb)
893 894 895 896 897
{
    unsigned vendor = hostdev->source.subsys.u.usb.vendor;
    unsigned product = hostdev->source.subsys.u.usb.product;
    unsigned bus = hostdev->source.subsys.u.usb.bus;
    unsigned device = hostdev->source.subsys.u.usb.device;
898
    bool autoAddress = hostdev->source.subsys.u.usb.autoAddress;
899
    int rc;
900

901
    *usb = NULL;
902

903
    if (vendor && bus) {
904 905 906 907
        rc = virUSBDeviceFind(vendor, product, bus, device,
                              NULL,
                              autoAddress ? false : mandatory,
                              usb);
908
        if (rc < 0) {
909
            return -1;
910 911 912 913 914 915 916 917 918 919 920 921 922 923
        } else if (!autoAddress) {
            goto out;
        } else {
            VIR_INFO("USB device %x:%x could not be found at previous"
                     " address (bus:%u device:%u)",
                     vendor, product, bus, device);
        }
    }

    /* When vendor is specified, its USB address is either unspecified or the
     * device could not be found at the USB device where it had been
     * automatically found before.
     */
    if (vendor) {
924
        virUSBDeviceListPtr devs;
925

926
        rc = virUSBDeviceFindByVendor(vendor, product, NULL, mandatory, &devs);
927 928 929 930
        if (rc < 0)
            return -1;

        if (rc == 1) {
931 932
            *usb = virUSBDeviceListGet(devs, 0);
            virUSBDeviceListSteal(devs, *usb);
933
        }
934
        virObjectUnref(devs);
935

936 937 938
        if (rc == 0) {
            goto out;
        } else if (rc > 1) {
939 940 941 942 943 944 945 946 947 948 949
            if (autoAddress) {
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("Multiple USB devices for %x:%x were found,"
                                 " but none of them is at bus:%u device:%u"),
                               vendor, product, bus, device);
            } else {
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("Multiple USB devices for %x:%x, "
                                 "use <address> to specify one"),
                               vendor, product);
            }
950 951
            return -1;
        }
952

953 954
        hostdev->source.subsys.u.usb.bus = virUSBDeviceGetBus(*usb);
        hostdev->source.subsys.u.usb.device = virUSBDeviceGetDevno(*usb);
955 956 957 958 959 960 961 962 963 964
        hostdev->source.subsys.u.usb.autoAddress = true;

        if (autoAddress) {
            VIR_INFO("USB device %x:%x found at bus:%u device:%u (moved"
                     " from bus:%u device:%u)",
                     vendor, product,
                     hostdev->source.subsys.u.usb.bus,
                     hostdev->source.subsys.u.usb.device,
                     bus, device);
        }
965
    } else if (!vendor && bus) {
966
        if (virUSBDeviceFindByBus(bus, device, NULL, mandatory, usb) < 0)
967
            return -1;
968 969
    }

970 971
out:
    if (!*usb)
972
        hostdev->missing = true;
973
    return 0;
974 975
}

976

977
static int
978
qemuPrepareHostUSBDevices(virQEMUDriverPtr driver,
979 980
                          virDomainDefPtr def,
                          bool coldBoot)
981
{
982 983
    size_t i;
    int ret = -1;
984 985
    virUSBDeviceListPtr list;
    virUSBDevicePtr tmp;
986 987
    virDomainHostdevDefPtr *hostdevs = def->hostdevs;
    int nhostdevs = def->nhostdevs;
988 989 990 991 992 993

    /* To prevent situation where USB device is assigned to two domains
     * we need to keep a list of currently assigned USB devices.
     * This is done in several loops which cannot be joined into one big
     * loop. See qemuPrepareHostdevPCIDevices()
     */
994
    if (!(list = virUSBDeviceListNew()))
995 996
        goto cleanup;

997
    /* Loop 1: build temporary list
998
     */
999
    for (i = 0; i < nhostdevs; i++) {
1000
        virDomainHostdevDefPtr hostdev = hostdevs[i];
1001
        bool required = true;
1002
        virUSBDevicePtr usb;
1003 1004 1005 1006 1007 1008

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

1009 1010 1011 1012 1013 1014
        if (hostdev->startupPolicy == VIR_DOMAIN_STARTUP_POLICY_OPTIONAL ||
            (hostdev->startupPolicy == VIR_DOMAIN_STARTUP_POLICY_REQUISITE &&
             !coldBoot))
            required = false;

        if (qemuFindHostdevUSBDevice(hostdev, required, &usb) < 0)
1015
            goto cleanup;
1016

1017 1018
        if (usb && virUSBDeviceListAdd(list, usb) < 0) {
            virUSBDeviceFree(usb);
1019
            goto cleanup;
1020 1021 1022
        }
    }

1023
    /* Mark devices in temporary list as used by @name
1024 1025 1026
     * and add them do driver list. However, if something goes
     * wrong, perform rollback.
     */
1027
    if (qemuPrepareHostdevUSBDevices(driver, def->name, list) < 0)
1028
        goto cleanup;
1029

1030
    /* Loop 2: Temporary list was successfully merged with
1031 1032 1033
     * driver list, so steal all items to avoid freeing them
     * in cleanup label.
     */
1034 1035 1036
    while (virUSBDeviceListCount(list) > 0) {
        tmp = virUSBDeviceListGet(list, 0);
        virUSBDeviceListSteal(list, tmp);
1037 1038 1039 1040 1041
    }

    ret = 0;

cleanup:
1042
    virObjectUnref(list);
1043
    return ret;
1044 1045
}

1046

1047 1048 1049 1050 1051 1052
int
qemuPrepareHostdevSCSIDevices(virQEMUDriverPtr driver,
                              const char *name,
                              virDomainHostdevDefPtr *hostdevs,
                              int nhostdevs)
{
1053 1054
    size_t i, j;
    int count;
1055 1056 1057
    virSCSIDeviceListPtr list;
    virSCSIDevicePtr tmp;

1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
    /* Loop 1: Add the shared scsi host device to shared device
     * table.
     */
    for (i = 0; i < nhostdevs; i++) {
        virDomainDeviceDef dev;

        dev.type = VIR_DOMAIN_DEVICE_HOSTDEV;
        dev.data.hostdev = hostdevs[i];

        if (qemuAddSharedDevice(driver, &dev, name) < 0)
            return -1;
1069 1070 1071

        if (qemuSetUnprivSGIO(&dev) < 0)
            return -1;
1072 1073
    }

1074 1075 1076 1077 1078 1079 1080 1081
    /* To prevent situation where SCSI device is assigned to two domains
     * we need to keep a list of currently assigned SCSI devices.
     * This is done in several loops which cannot be joined into one big
     * loop. See qemuPrepareHostdevPCIDevices()
     */
    if (!(list = virSCSIDeviceListNew()))
        goto cleanup;

1082
    /* Loop 2: build temporary list */
1083
    for (i = 0; i < nhostdevs; i++) {
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
        virDomainHostdevDefPtr hostdev = hostdevs[i];
        virSCSIDevicePtr scsi;

        if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
            hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI)
            continue;

        if (hostdev->managed) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("SCSI host device doesn't support managed mode"));
            goto cleanup;
        }

        if (!(scsi = virSCSIDeviceNew(hostdev->source.subsys.u.scsi.adapter,
                                      hostdev->source.subsys.u.scsi.bus,
                                      hostdev->source.subsys.u.scsi.target,
                                      hostdev->source.subsys.u.scsi.unit,
1101 1102
                                      hostdev->readonly,
                                      hostdev->shareable)))
1103 1104 1105 1106 1107 1108 1109 1110
            goto cleanup;

        if (scsi && virSCSIDeviceListAdd(list, scsi) < 0) {
            virSCSIDeviceFree(scsi);
            goto cleanup;
        }
    }

1111
    /* Loop 3: Mark devices in temporary list as used by @name
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
     * and add them to driver list. However, if something goes
     * wrong, perform rollback.
     */
    virObjectLock(driver->activeScsiHostdevs);
    count = virSCSIDeviceListCount(list);

    for (i = 0; i < count; i++) {
        virSCSIDevicePtr scsi = virSCSIDeviceListGet(list, i);
        if ((tmp = virSCSIDeviceListFind(driver->activeScsiHostdevs, scsi))) {
            const char *other_name = virSCSIDeviceGetUsedBy(tmp);

            if (other_name)
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("SCSI device %s is in use by domain %s"),
                               virSCSIDeviceGetName(tmp), other_name);
            else
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("SCSI device %s is already in use"),
                               virSCSIDeviceGetName(tmp));
            goto error;
        }

        virSCSIDeviceSetUsedBy(scsi, name);
        VIR_DEBUG("Adding %s to activeScsiHostdevs", virSCSIDeviceGetName(scsi));

        if (virSCSIDeviceListAdd(driver->activeScsiHostdevs, scsi) < 0)
            goto error;
    }

    virObjectUnlock(driver->activeScsiHostdevs);

1143
    /* Loop 4: Temporary list was successfully merged with
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
     * driver list, so steal all items to avoid freeing them
     * when freeing temporary list.
     */
    while (virSCSIDeviceListCount(list) > 0) {
        tmp = virSCSIDeviceListGet(list, 0);
        virSCSIDeviceListSteal(list, tmp);
    }

    virObjectUnref(list);
    return 0;

error:
    for (j = 0; j < i; j++) {
        tmp = virSCSIDeviceListGet(list, i);
        virSCSIDeviceListSteal(driver->activeScsiHostdevs, tmp);
    }
    virObjectUnlock(driver->activeScsiHostdevs);
cleanup:
    virObjectUnref(list);
    return -1;
}

1166 1167 1168 1169

int
qemuPrepareHostDevices(virQEMUDriverPtr driver,
                       virDomainDefPtr def,
1170
                       virQEMUCapsPtr qemuCaps,
1171
                       bool coldBoot)
1172 1173 1174 1175
{
    if (!def->nhostdevs)
        return 0;

1176
    if (qemuPrepareHostdevPCIDevices(driver, def->name, def->uuid,
1177 1178
                                     def->hostdevs, def->nhostdevs,
                                     qemuCaps) < 0)
1179 1180
        return -1;

1181
    if (qemuPrepareHostUSBDevices(driver, def, coldBoot) < 0)
1182 1183
        return -1;

1184 1185 1186 1187
    if (qemuPrepareHostdevSCSIDevices(driver, def->name,
                                      def->hostdevs, def->nhostdevs) < 0)
        return -1;

1188 1189 1190 1191
    return 0;
}


1192 1193 1194 1195
/*
 * Pre-condition: driver->inactivePciHostdevs & driver->activePciHostdevs
 * are locked
 */
1196 1197
void
qemuReattachPciDevice(virPCIDevicePtr dev, virQEMUDriverPtr driver)
1198 1199 1200
{
    int retries = 100;

1201 1202 1203
    /* If the device is not managed and was attached to guest
     * successfully, it must have been inactive.
     */
1204 1205 1206
    if (!virPCIDeviceGetManaged(dev)) {
        if (virPCIDeviceListAdd(driver->inactivePciHostdevs, dev) < 0)
            virPCIDeviceFree(dev);
1207
        return;
1208
    }
1209

1210
    while (virPCIDeviceWaitForCleanup(dev, "kvm_assigned_device")
1211 1212 1213 1214 1215
           && retries) {
        usleep(100*1000);
        retries--;
    }

1216
    if (virPCIDeviceReattach(dev, driver->activePciHostdevs,
1217
                             driver->inactivePciHostdevs) < 0) {
1218 1219 1220 1221
        virErrorPtr err = virGetLastError();
        VIR_ERROR(_("Failed to re-attach PCI device: %s"),
                  err ? err->message : _("unknown error"));
        virResetError(err);
1222
    }
1223
    virPCIDeviceFree(dev);
1224 1225 1226
}


1227 1228 1229 1230 1231
void
qemuDomainReAttachHostdevDevices(virQEMUDriverPtr driver,
                                 const char *name,
                                 virDomainHostdevDefPtr *hostdevs,
                                 int nhostdevs)
1232
{
1233
    virPCIDeviceListPtr pcidevs;
1234
    size_t i;
1235
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
1236

1237 1238 1239
    virObjectLock(driver->activePciHostdevs);
    virObjectLock(driver->inactivePciHostdevs);

1240 1241 1242
    if (!(pcidevs = qemuGetActivePciHostDeviceList(driver,
                                                   hostdevs,
                                                   nhostdevs))) {
1243
        virErrorPtr err = virGetLastError();
1244
        VIR_ERROR(_("Failed to allocate PCI device list: %s"),
1245 1246
                  err ? err->message : _("unknown error"));
        virResetError(err);
1247
        goto cleanup;
1248 1249
    }

1250 1251 1252 1253
    /* Again 4 loops; mark all devices as inactive before reset
     * them and reset all the devices before re-attach.
     * Attach mac and port profile parameters to devices
     */
1254 1255 1256
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
        virPCIDevicePtr activeDev = NULL;
1257

1258 1259 1260
        /* delete the copy of the dev from pcidevs if it's used by
         * other domain. Or delete it from activePciHostDevs if it had
         * been used by this domain.
1261
         */
1262
        activeDev = virPCIDeviceListFind(driver->activePciHostdevs, dev);
1263
        if (activeDev &&
1264
            STRNEQ_NULLABLE(name, virPCIDeviceGetUsedBy(activeDev))) {
1265
            virPCIDeviceListDel(pcidevs, dev);
1266
            continue;
1267
        }
1268

1269
        virPCIDeviceListDel(driver->activePciHostdevs, dev);
1270 1271
    }

1272 1273 1274 1275
    /* At this point, any device that had been used by the guest is in
     * pcidevs, but has been removed from activePciHostdevs.
     */

1276 1277 1278 1279
    /*
     * For SRIOV net host devices, unset mac and port profile before
     * reset and reattach device
     */
1280 1281
    for (i = 0; i < nhostdevs; i++)
        qemuDomainHostdevNetConfigRestore(hostdevs[i], cfg->stateDir);
1282

1283 1284
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
1285

1286 1287
        if (virPCIDeviceReset(dev, driver->activePciHostdevs,
                              driver->inactivePciHostdevs) < 0) {
1288 1289 1290 1291 1292 1293 1294
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to reset PCI device: %s"),
                      err ? err->message : _("unknown error"));
            virResetError(err);
        }
    }

1295 1296
    while (virPCIDeviceListCount(pcidevs) > 0) {
        virPCIDevicePtr dev = virPCIDeviceListStealIndex(pcidevs, 0);
1297 1298 1299
        qemuReattachPciDevice(dev, driver);
    }

1300
    virObjectUnref(pcidevs);
1301
cleanup:
1302 1303
    virObjectUnlock(driver->activePciHostdevs);
    virObjectUnlock(driver->inactivePciHostdevs);
1304
    virObjectUnref(cfg);
1305 1306
}

1307

1308
static void
1309
qemuDomainReAttachHostUsbDevices(virQEMUDriverPtr driver,
1310 1311 1312 1313
                                 const char *name,
                                 virDomainHostdevDefPtr *hostdevs,
                                 int nhostdevs)
{
1314
    size_t i;
1315

1316
    virObjectLock(driver->activeUsbHostdevs);
1317 1318
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
1319
        virUSBDevicePtr usb, tmp;
1320 1321 1322 1323 1324 1325
        const char *used_by = NULL;

        if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
            continue;
        if (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB)
            continue;
1326 1327
        if (hostdev->missing)
            continue;
1328

1329 1330 1331
        usb = virUSBDeviceNew(hostdev->source.subsys.u.usb.bus,
                              hostdev->source.subsys.u.usb.device,
                              NULL);
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346

        if (!usb) {
            VIR_WARN("Unable to reattach USB device %03d.%03d on domain %s",
                     hostdev->source.subsys.u.usb.bus,
                     hostdev->source.subsys.u.usb.device,
                     name);
            continue;
        }

        /* Delete only those USB devices which belongs
         * to domain @name because qemuProcessStart() might
         * have failed because USB device is already taken.
         * Therefore we want to steal only those devices from
         * the list which were taken by @name */

1347 1348
        tmp = virUSBDeviceListFind(driver->activeUsbHostdevs, usb);
        virUSBDeviceFree(usb);
1349 1350 1351 1352 1353 1354 1355 1356 1357

        if (!tmp) {
            VIR_WARN("Unable to find device %03d.%03d "
                     "in list of active USB devices",
                     hostdev->source.subsys.u.usb.bus,
                     hostdev->source.subsys.u.usb.device);
            continue;
        }

1358
        used_by = virUSBDeviceGetUsedBy(tmp);
1359 1360 1361 1362 1363 1364
        if (STREQ_NULLABLE(used_by, name)) {
            VIR_DEBUG("Removing %03d.%03d dom=%s from activeUsbHostdevs",
                      hostdev->source.subsys.u.usb.bus,
                      hostdev->source.subsys.u.usb.device,
                      name);

1365
            virUSBDeviceListDel(driver->activeUsbHostdevs, tmp);
1366 1367
        }
    }
1368
    virObjectUnlock(driver->activeUsbHostdevs);
1369
}
1370

1371

1372 1373 1374 1375 1376 1377
void
qemuDomainReAttachHostScsiDevices(virQEMUDriverPtr driver,
                                  const char *name,
                                  virDomainHostdevDefPtr *hostdevs,
                                  int nhostdevs)
{
1378
    size_t i;
1379 1380 1381 1382 1383 1384

    virObjectLock(driver->activeScsiHostdevs);
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
        virSCSIDevicePtr scsi, tmp;
        const char *used_by = NULL;
1385 1386 1387 1388 1389 1390
        virDomainDeviceDef dev;

        dev.type = VIR_DOMAIN_DEVICE_HOSTDEV;
        dev.data.hostdev = hostdev;

        ignore_value(qemuRemoveSharedDevice(driver, &dev, name));
1391 1392 1393 1394 1395 1396 1397 1398 1399

        if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
            hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI)
            continue;

        if (!(scsi = virSCSIDeviceNew(hostdev->source.subsys.u.scsi.adapter,
                                      hostdev->source.subsys.u.scsi.bus,
                                      hostdev->source.subsys.u.scsi.target,
                                      hostdev->source.subsys.u.scsi.unit,
1400 1401
                                      hostdev->readonly,
                                      hostdev->shareable))) {
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
            VIR_WARN("Unable to reattach SCSI device %s:%d:%d:%d on domain %s",
                     hostdev->source.subsys.u.scsi.adapter,
                     hostdev->source.subsys.u.scsi.bus,
                     hostdev->source.subsys.u.scsi.target,
                     hostdev->source.subsys.u.scsi.unit,
                     name);
            continue;
        }

        /* Only delete the devices which are marked as being used by @name,
         * because qemuProcessStart could fail on the half way. */

        tmp = virSCSIDeviceListFind(driver->activeScsiHostdevs, scsi);
        virSCSIDeviceFree(scsi);

        if (!tmp) {
            VIR_WARN("Unable to find device %s:%d:%d:%d "
                     "in list of active SCSI devices",
                     hostdev->source.subsys.u.scsi.adapter,
                     hostdev->source.subsys.u.scsi.bus,
                     hostdev->source.subsys.u.scsi.target,
                     hostdev->source.subsys.u.scsi.unit);
            continue;
        }

        used_by = virSCSIDeviceGetUsedBy(tmp);
        if (STREQ_NULLABLE(used_by, name)) {
            VIR_DEBUG("Removing %s:%d:%d:%d dom=%s from activeScsiHostdevs",
                      hostdev->source.subsys.u.scsi.adapter,
                      hostdev->source.subsys.u.scsi.bus,
                      hostdev->source.subsys.u.scsi.target,
                      hostdev->source.subsys.u.scsi.unit,
                      name);

            virSCSIDeviceListDel(driver->activeScsiHostdevs, tmp);
        }
    }
    virObjectUnlock(driver->activeScsiHostdevs);
}

1442 1443 1444
void
qemuDomainReAttachHostDevices(virQEMUDriverPtr driver,
                              virDomainDefPtr def)
1445 1446 1447 1448
{
    if (!def->nhostdevs)
        return;

1449 1450
    qemuDomainReAttachHostdevDevices(driver, def->name, def->hostdevs,
                                     def->nhostdevs);
1451 1452 1453

    qemuDomainReAttachHostUsbDevices(driver, def->name, def->hostdevs,
                                     def->nhostdevs);
1454 1455 1456

    qemuDomainReAttachHostScsiDevices(driver, def->name, def->hostdevs,
                                      def->nhostdevs);
1457
}