virhostdev.c 57.7 KB
Newer Older
1 2
/* virhostdev.c: hostdev management
 *
3
 * Copyright (C) 2006-2007, 2009-2015 Red Hat, Inc.
4
 * Copyright (C) 2006 Daniel P. Berrange
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 * Copyright (C) 2014 SUSE LINUX Products GmbH, Nuernberg, Germany.
 *
 * 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/>.
 *
21
 * Author: Daniel P. Berrange <berrange@redhat.com>
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
 * Author: Chunyan Liu <cyliu@suse.com>
 */

#include <config.h>

#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

#include "virhostdev.h"
#include "viralloc.h"
#include "virstring.h"
#include "virfile.h"
#include "virerror.h"
#include "virlog.h"
#include "virutil.h"
42
#include "virnetdev.h"
43 44 45
#include "configmake.h"

#define VIR_FROM_THIS VIR_FROM_NONE
46 47 48

VIR_LOG_INIT("util.hostdev");

49 50
#define HOSTDEV_STATE_DIR LOCALSTATEDIR "/run/libvirt/hostdevmgr"

51 52 53 54 55 56
static virHostdevManagerPtr manager; /* global hostdev manager, never freed */

static virClassPtr virHostdevManagerClass;
static void virHostdevManagerDispose(void *obj);
static virHostdevManagerPtr virHostdevManagerNew(void);

57 58 59 60 61 62
struct virHostdevIsPCINodeDeviceUsedData {
    virHostdevManagerPtr hostdev_mgr;
    const char *domainName;
    const bool usesVfio;
};

63 64 65 66 67
static int virHostdevIsPCINodeDeviceUsed(virPCIDeviceAddressPtr devAddr, void *opaque)
{
    virPCIDevicePtr other;
    int ret = -1;
    virPCIDevicePtr pci = NULL;
68
    struct virHostdevIsPCINodeDeviceUsedData *helperData = opaque;
69 70 71 72 73

    if (!(pci = virPCIDeviceNew(devAddr->domain, devAddr->bus,
                                devAddr->slot, devAddr->function)))
        goto cleanup;

74 75
    other = virPCIDeviceListFind(helperData->hostdev_mgr->activePCIHostdevs,
                                 pci);
76 77 78 79 80
    if (other) {
        const char *other_drvname = NULL;
        const char *other_domname = NULL;
        virPCIDeviceGetUsedBy(other, &other_drvname, &other_domname);

81 82 83 84 85
        if (helperData->usesVfio &&
            (other_domname && helperData->domainName) &&
            (STREQ(other_domname, helperData->domainName)))
            goto iommu_owner;

86 87 88 89 90 91 92 93 94 95 96 97
        if (other_drvname && other_domname)
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is in use by "
                             "driver %s, domain %s"),
                           virPCIDeviceGetName(pci),
                           other_drvname, other_domname);
        else
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is in use"),
                           virPCIDeviceGetName(pci));
        goto cleanup;
    }
98
 iommu_owner:
99 100 101 102 103 104
    ret = 0;
 cleanup:
    virPCIDeviceFree(pci);
    return ret;
}

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
static int virHostdevManagerOnceInit(void)
{
    if (!(virHostdevManagerClass = virClassNew(virClassForObject(),
                                               "virHostdevManager",
                                               sizeof(virHostdevManager),
                                               virHostdevManagerDispose)))
        return -1;

    if (!(manager = virHostdevManagerNew()))
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(virHostdevManager)
120 121

static void
122
virHostdevManagerDispose(void *obj)
123
{
124 125
    virHostdevManagerPtr hostdevMgr = obj;

126 127 128
    if (!hostdevMgr)
        return;

129 130 131 132
    virObjectUnref(hostdevMgr->activePCIHostdevs);
    virObjectUnref(hostdevMgr->inactivePCIHostdevs);
    virObjectUnref(hostdevMgr->activeUSBHostdevs);
    virObjectUnref(hostdevMgr->activeSCSIHostdevs);
133 134 135
    VIR_FREE(hostdevMgr->stateDir);
}

136 137
static virHostdevManagerPtr
virHostdevManagerNew(void)
138
{
139
    virHostdevManagerPtr hostdevMgr;
140
    bool privileged = geteuid() == 0;
141 142 143

    if (!(hostdevMgr = virObjectNew(virHostdevManagerClass)))
        return NULL;
144

145
    if ((hostdevMgr->activePCIHostdevs = virPCIDeviceListNew()) == NULL)
146 147
        goto error;

148
    if ((hostdevMgr->activeUSBHostdevs = virUSBDeviceListNew()) == NULL)
149 150
        goto error;

151
    if ((hostdevMgr->inactivePCIHostdevs = virPCIDeviceListNew()) == NULL)
152 153
        goto error;

154
    if ((hostdevMgr->activeSCSIHostdevs = virSCSIDeviceListNew()) == NULL)
155 156
        goto error;

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
    if (privileged) {
        if (VIR_STRDUP(hostdevMgr->stateDir, HOSTDEV_STATE_DIR) < 0)
            goto error;

        if (virFileMakePath(hostdevMgr->stateDir) < 0) {
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("Failed to create state dir '%s'"),
                           hostdevMgr->stateDir);
            goto error;
        }
    } else {
        char *rundir = NULL;
        mode_t old_umask;

        if (!(rundir = virGetUserRuntimeDirectory()))
            goto error;

        if (virAsprintf(&hostdevMgr->stateDir, "%s/hostdevmgr", rundir) < 0) {
            VIR_FREE(rundir);
            goto error;
        }
        VIR_FREE(rundir);

        old_umask = umask(077);

        if (virFileMakePath(hostdevMgr->stateDir) < 0) {
            umask(old_umask);
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("Failed to create state dir '%s'"),
                           hostdevMgr->stateDir);
            goto error;
        }
        umask(old_umask);
190 191
    }

192
    return hostdevMgr;
193

194
 error:
195 196
    virObjectUnref(hostdevMgr);
    return NULL;
197 198 199 200 201
}

virHostdevManagerPtr
virHostdevManagerGetDefault(void)
{
202
    if (virHostdevManagerInitialize() < 0)
203
        return NULL;
204 205

    return virObjectRef(manager);
206
}
207 208

static virPCIDeviceListPtr
209
virHostdevGetPCIHostDeviceList(virDomainHostdevDefPtr *hostdevs, int nhostdevs)
210 211 212 213 214 215 216 217 218
{
    virPCIDeviceListPtr list;
    size_t i;

    if (!(list = virPCIDeviceListNew()))
        return NULL;

    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
219
        virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;
220 221 222 223 224 225 226
        virPCIDevicePtr dev;

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

227 228
        dev = virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                              pcisrc->addr.slot, pcisrc->addr.function);
229 230 231 232 233 234 235 236 237 238 239
        if (!dev) {
            virObjectUnref(list);
            return NULL;
        }
        if (virPCIDeviceListAdd(list, dev) < 0) {
            virPCIDeviceFree(dev);
            virObjectUnref(list);
            return NULL;
        }

        virPCIDeviceSetManaged(dev, hostdev->managed);
240 241 242 243 244 245 246

        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO)
            virPCIDeviceSetStubDriver(dev, VIR_PCI_STUB_DRIVER_VFIO);
        else if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN)
            virPCIDeviceSetStubDriver(dev, VIR_PCI_STUB_DRIVER_XEN);
        else
            virPCIDeviceSetStubDriver(dev, VIR_PCI_STUB_DRIVER_KVM);
247 248 249 250 251 252 253
    }

    return list;
}


/*
254
 * virHostdevGetActivePCIHostDeviceList - make a new list with a *copy* of
255
 *   every virPCIDevice object that is found on the activePCIHostdevs
256 257 258 259
 *   list *and* is in the hostdev list for this domain.
 *
 * Return the new list, or NULL if there was a failure.
 *
260
 * Pre-condition: activePCIHostdevs is locked
261 262
 */
static virPCIDeviceListPtr
263
virHostdevGetActivePCIHostDeviceList(virHostdevManagerPtr mgr,
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
                                     virDomainHostdevDefPtr *hostdevs,
                                     int nhostdevs)
{
    virPCIDeviceListPtr list;
    size_t i;

    if (!(list = virPCIDeviceListNew()))
        return NULL;

    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
        virDevicePCIAddressPtr addr;
        virPCIDevicePtr activeDev;

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

        addr = &hostdev->source.subsys.u.pci.addr;
284
        activeDev = virPCIDeviceListFindByIDs(mgr->activePCIHostdevs,
285 286 287 288 289 290 291 292 293 294 295 296
                                              addr->domain, addr->bus,
                                              addr->slot, addr->function);
        if (activeDev && virPCIDeviceListAddCopy(list, activeDev) < 0) {
            virObjectUnref(list);
            return NULL;
        }
    }

    return list;
}

static int
297
virHostdevPCISysfsPath(virDomainHostdevDefPtr hostdev,
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
                       char **sysfs_path)
{
    virPCIDeviceAddress config_address;

    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;

    return virPCIDeviceAddressGetSysfsFile(&config_address, sysfs_path);
}


static int
virHostdevIsVirtualFunction(virDomainHostdevDefPtr hostdev)
{
    char *sysfs_path = NULL;
    int ret = -1;

317
    if (virHostdevPCISysfsPath(hostdev, &sysfs_path) < 0)
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
        return ret;

    ret = virPCIIsVirtualFunction(sysfs_path);

    VIR_FREE(sysfs_path);

    return ret;
}


static int
virHostdevNetDevice(virDomainHostdevDefPtr hostdev, char **linkdev,
                    int *vf)
{
    int ret = -1;
    char *sysfs_path = NULL;

335
    if (virHostdevPCISysfsPath(hostdev, &sysfs_path) < 0)
336 337 338 339 340 341 342 343 344 345 346 347 348 349
        return ret;

    if (virPCIIsVirtualFunction(sysfs_path) == 1) {
        if (virPCIGetVirtualFunctionInfo(sysfs_path, linkdev,
                                         vf) < 0)
            goto cleanup;
    } else {
        if (virPCIGetNetName(sysfs_path, linkdev) < 0)
            goto cleanup;
        *vf = -1;
    }

    ret = 0;

350
 cleanup:
351 352 353 354 355 356
    VIR_FREE(sysfs_path);

    return ret;
}


357 358 359 360 361 362 363 364 365 366
static int
virHostdevIsPCINetDevice(virDomainHostdevDefPtr hostdev)
{
    return 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;
}


367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
static int
virHostdevNetConfigVirtPortProfile(const char *linkdev, int vf,
                                   virNetDevVPortProfilePtr virtPort,
                                   const virMacAddr *macaddr,
                                   const unsigned char *uuid,
                                   bool associate)
{
    int ret = -1;

    if (!virtPort)
        return ret;

    switch (virtPort->virtPortType) {
    case VIR_NETDEV_VPORT_PROFILE_NONE:
    case VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH:
    case VIR_NETDEV_VPORT_PROFILE_8021QBG:
    case VIR_NETDEV_VPORT_PROFILE_LAST:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("virtualport type %s is "
                         "currently not supported on interfaces of type "
                         "hostdev"),
                       virNetDevVPortTypeToString(virtPort->virtPortType));
        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;
}


static int
virHostdevNetConfigReplace(virDomainHostdevDefPtr hostdev,
                           const unsigned char *uuid,
410
                           const char *stateDir)
411 412 413 414 415 416 417 418 419
{
    char *linkdev = NULL;
    virNetDevVlanPtr vlan;
    virNetDevVPortProfilePtr virtPort;
    int ret = -1;
    int vf = -1;
    int vlanid = -1;
    bool port_profile_associate = true;

420
    if (virHostdevIsVirtualFunction(hostdev) != 1) {
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Interface type hostdev is currently supported on"
                         " SR-IOV Virtual Functions only"));
        return ret;
    }

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

    vlan = virDomainNetGetActualVlan(hostdev->parent.data.net);
    virtPort = virDomainNetGetActualVirtPortProfile(
                                 hostdev->parent.data.net);
    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;
        }
        ret = virHostdevNetConfigVirtPortProfile(linkdev, vf,
                            virtPort, &hostdev->parent.data.net->mac, uuid,
                            port_profile_associate);
    } 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 */
        }

        ret = virNetDevReplaceNetConfig(linkdev, vf,
                                        &hostdev->parent.data.net->mac,
                                        vlanid, stateDir);
    }
468
 cleanup:
469 470 471 472 473 474 475 476 477 478 479 480 481
    VIR_FREE(linkdev);
    return ret;
}

/* @oldStateDir:
 * For upgrade purpose:
 * To an existing VM on QEMU, the hostdev netconfig file is originally stored
 * in cfg->stateDir (/var/run/libvirt/qemu). Switch to new version, it uses new
 * location (hostdev_mgr->stateDir) but certainly will not find it. In this
 * case, try to find in the old state dir.
 */
static int
virHostdevNetConfigRestore(virDomainHostdevDefPtr hostdev,
482 483
                           const char *stateDir,
                           const char *oldStateDir)
484 485 486 487 488 489 490 491 492 493
{
    char *linkdev = NULL;
    virNetDevVPortProfilePtr virtPort;
    int ret = -1;
    int vf = -1;
    bool port_profile_associate = false;

    /* This is only needed for PCI devices that have been defined
     * using <interface type='hostdev'>. For all others, it is a NOP.
     */
494
    if (!virHostdevIsPCINetDevice(hostdev))
495 496
       return 0;

497
    if (virHostdevIsVirtualFunction(hostdev) != 1) {
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 527
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Interface type hostdev is currently supported on"
                         " SR-IOV Virtual Functions only"));
        return ret;
    }

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

    virtPort = virDomainNetGetActualVirtPortProfile(
                                 hostdev->parent.data.net);
    if (virtPort) {
        ret = virHostdevNetConfigVirtPortProfile(linkdev, vf, virtPort,
                                                 &hostdev->parent.data.net->mac,
                                                 NULL,
                                                 port_profile_associate);
    } else {
        ret = virNetDevRestoreNetConfig(linkdev, vf, stateDir);
        if (ret < 0 && oldStateDir != NULL)
            ret = virNetDevRestoreNetConfig(linkdev, vf, oldStateDir);
    }

    VIR_FREE(linkdev);

    return ret;
}

int
virHostdevPreparePCIDevices(virHostdevManagerPtr hostdev_mgr,
                            const char *drv_name,
528
                            const char *dom_name,
529 530 531 532 533 534 535 536 537
                            const unsigned char *uuid,
                            virDomainHostdevDefPtr *hostdevs,
                            int nhostdevs,
                            unsigned int flags)
{
    virPCIDeviceListPtr pcidevs = NULL;
    int last_processed_hostdev_vf = -1;
    size_t i;
    int ret = -1;
538
    virPCIDeviceAddressPtr devAddr = NULL;
539

540 541 542
    if (!nhostdevs)
        return 0;

543 544
    virObjectLock(hostdev_mgr->activePCIHostdevs);
    virObjectLock(hostdev_mgr->inactivePCIHostdevs);
545

546
    if (!(pcidevs = virHostdevGetPCIHostDeviceList(hostdevs, nhostdevs)))
547 548
        goto cleanup;

549 550 551 552 553 554 555 556 557
    /* Detaching devices from the host involves several steps; each
     * of them is described at length below.
     *
     * All devices must 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 */

    /* Step 1: validate that non-managed device isn't in use, eg
558 559 560 561 562 563
     * by checking that device is either un-bound, or bound
     * to pci-stub.ko
     */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
        bool strict_acs_check = !!(flags & VIR_HOSTDEV_STRICT_ACS_CHECK);
564
        bool usesVfio = (virPCIDeviceGetStubDriver(dev) == VIR_PCI_STUB_DRIVER_VFIO);
565 566
        struct virHostdevIsPCINodeDeviceUsedData data = {hostdev_mgr, dom_name,
                                                         usesVfio};
567

568
        if (!usesVfio && !virPCIDeviceIsAssignable(dev, strict_acs_check)) {
569 570 571 572 573
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is not assignable"),
                           virPCIDeviceGetName(dev));
            goto cleanup;
        }
574

575
        /* The device is in use by other active domain if
576
         * the dev is in list activePCIHostdevs. VFIO devices
M
Martin Kletzander 已提交
577
         * belonging to same iommu group can't be shared
578
         * across guests.
579
         */
580
        devAddr = virPCIDeviceGetAddress(dev);
581
        if (usesVfio) {
582 583
            if (virPCIDeviceAddressIOMMUGroupIterate(devAddr,
                                                     virHostdevIsPCINodeDeviceUsed,
584
                                                     &data) < 0)
585
                goto cleanup;
586
        } else if (virHostdevIsPCINodeDeviceUsed(devAddr, &data)) {
587 588 589 590
            goto cleanup;
        }
    }

591
    /* Step 2: detach managed devices (i.e. bind to appropriate stub driver) */
592 593
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
594

595 596 597 598 599 600
        if (virPCIDeviceGetManaged(dev)) {
            VIR_DEBUG("Detaching managed PCI device %s",
                      virPCIDeviceGetName(dev));
            if (virPCIDeviceDetach(dev,
                                   hostdev_mgr->activePCIHostdevs,
                                   hostdev_mgr->inactivePCIHostdevs) < 0)
601
                goto reattachdevs;
602 603 604 605
        } else {
            VIR_DEBUG("Not detaching unmanaged PCI device %s",
                      virPCIDeviceGetName(dev));
        }
606 607
    }

608 609 610
    /* At this point, all devices are attached to the stub driver and have
     * been marked as inactive */

611
    /* Step 3: Now that all the PCI hostdevs have been detached, we
612 613 614 615
     * can safely reset them */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);

616
        VIR_DEBUG("Resetting PCI device %s", virPCIDeviceGetName(dev));
617 618
        if (virPCIDeviceReset(dev, hostdev_mgr->activePCIHostdevs,
                              hostdev_mgr->inactivePCIHostdevs) < 0)
619 620 621
            goto reattachdevs;
    }

622
    /* Step 4: For SRIOV network devices, Now that we have detached the
623 624 625
     * the network device, set the netdev config */
    for (i = 0; i < nhostdevs; i++) {
         virDomainHostdevDefPtr hostdev = hostdevs[i];
626
         if (!virHostdevIsPCINetDevice(hostdev))
627
             continue;
628 629 630
         if (virHostdevNetConfigReplace(hostdev, uuid,
                                        hostdev_mgr->stateDir) < 0) {
             goto resetvfnetconfig;
631 632 633 634
         }
         last_processed_hostdev_vf = i;
    }

635
    /* Step 5: Now mark all the devices as active */
636 637
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
638 639 640

        VIR_DEBUG("Adding PCI device %s to active list",
                  virPCIDeviceGetName(dev));
641
        if (virPCIDeviceListAdd(hostdev_mgr->activePCIHostdevs, dev) < 0)
642 643 644
            goto inactivedevs;
    }

645
    /* Step 6: Now remove the devices from inactive list. */
646
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
647 648 649 650 651
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);

        VIR_DEBUG("Removing PCI device %s from inactive list",
                  virPCIDeviceGetName(dev));
        virPCIDeviceListDel(hostdev_mgr->inactivePCIHostdevs, dev);
652 653
    }

654
    /* Step 7: Now set the used_by_domain of the device in
655
     * activePCIHostdevs as domain name.
656 657 658 659 660
     */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev, activeDev;

        dev = virPCIDeviceListGet(pcidevs, i);
661
        activeDev = virPCIDeviceListFind(hostdev_mgr->activePCIHostdevs, dev);
662

663 664
        VIR_DEBUG("Setting driver and domain information for PCI device %s",
                  virPCIDeviceGetName(dev));
665
        if (activeDev)
666
            virPCIDeviceSetUsedBy(activeDev, drv_name, dom_name);
667 668
    }

669
    /* Step 8: Now set the original states for hostdev def */
670 671 672 673
    for (i = 0; i < nhostdevs; i++) {
        virPCIDevicePtr dev;
        virPCIDevicePtr pcidev;
        virDomainHostdevDefPtr hostdev = hostdevs[i];
674
        virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;
675 676 677 678 679 680

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

681 682
        dev = virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                              pcisrc->addr.slot, pcisrc->addr.function);
683

684 685 686
        /* Appropriate values for the unbind_from_stub, remove_slot
         * and reprobe properties of the device were set earlier
         * by virPCIDeviceDetach() */
687 688
        VIR_DEBUG("Saving network configuration of PCI device %s",
                  virPCIDeviceGetName(dev));
689 690 691 692 693 694 695 696 697 698 699 700
        if ((pcidev = virPCIDeviceListFind(pcidevs, dev))) {
            hostdev->origstates.states.pci.unbind_from_stub =
                virPCIDeviceGetUnbindFromStub(pcidev);
            hostdev->origstates.states.pci.remove_slot =
                virPCIDeviceGetRemoveSlot(pcidev);
            hostdev->origstates.states.pci.reprobe =
                virPCIDeviceGetReprobe(pcidev);
        }

        virPCIDeviceFree(dev);
    }

701
    /* Step 9: Now steal all the devices from pcidevs */
702 703 704 705 706 707
    while (virPCIDeviceListCount(pcidevs) > 0)
        virPCIDeviceListStealIndex(pcidevs, 0);

    ret = 0;
    goto cleanup;

708
 inactivedevs:
709
    /* Only steal all the devices from activePCIHostdevs. We will
710 711 712 713
     * free them in virObjectUnref().
     */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
714 715 716

        VIR_DEBUG("Removing PCI device %s from active list",
                  virPCIDeviceGetName(dev));
717
        virPCIDeviceListSteal(hostdev_mgr->activePCIHostdevs, dev);
718 719
    }

720
 resetvfnetconfig:
721
    for (i = 0;
722
         last_processed_hostdev_vf != -1 && i <= last_processed_hostdev_vf; i++)
723 724
        virHostdevNetConfigRestore(hostdevs[i], hostdev_mgr->stateDir, NULL);

725
 reattachdevs:
726 727 728
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);

729
        if (virPCIDeviceGetManaged(dev)) {
730 731
            VIR_DEBUG("Reattaching managed PCI device %s",
                      virPCIDeviceGetName(dev));
732 733 734
            ignore_value(virPCIDeviceReattach(dev,
                                              hostdev_mgr->activePCIHostdevs,
                                              hostdev_mgr->inactivePCIHostdevs));
735 736 737
        } else {
            VIR_DEBUG("Not reattaching unmanaged PCI device %s",
                      virPCIDeviceGetName(dev));
738
        }
739 740
    }

741
 cleanup:
742
    virObjectUnref(pcidevs);
743 744
    virObjectUnlock(hostdev_mgr->activePCIHostdevs);
    virObjectUnlock(hostdev_mgr->inactivePCIHostdevs);
745

746 747 748 749
    return ret;
}

/*
750
 * Pre-condition: inactivePCIHostdevs & activePCIHostdevs
751 752 753
 * are locked
 */
static void
754
virHostdevReattachPCIDevice(virPCIDevicePtr dev, virHostdevManagerPtr mgr)
755 756 757 758 759
{
    /* If the device is not managed and was attached to guest
     * successfully, it must have been inactive.
     */
    if (!virPCIDeviceGetManaged(dev)) {
760 761
        VIR_DEBUG("Adding unmanaged PCI device %s to inactive list",
                  virPCIDeviceGetName(dev));
762
        if (virPCIDeviceListAdd(mgr->inactivePCIHostdevs, dev) < 0)
763 764 765 766 767
            virPCIDeviceFree(dev);
        return;
    }

    /* Wait for device cleanup if it is qemu/kvm */
768
    if (virPCIDeviceGetStubDriver(dev) == VIR_PCI_STUB_DRIVER_KVM) {
769 770 771 772 773 774 775 776
        int retries = 100;
        while (virPCIDeviceWaitForCleanup(dev, "kvm_assigned_device")
               && retries) {
            usleep(100*1000);
            retries--;
        }
    }

777
    VIR_DEBUG("Reattaching PCI device %s", virPCIDeviceGetName(dev));
778 779
    if (virPCIDeviceReattach(dev, mgr->activePCIHostdevs,
                             mgr->inactivePCIHostdevs) < 0) {
780 781 782 783 784 785 786 787 788 789 790 791 792 793
        virErrorPtr err = virGetLastError();
        VIR_ERROR(_("Failed to re-attach PCI device: %s"),
                  err ? err->message : _("unknown error"));
        virResetError(err);
    }
    virPCIDeviceFree(dev);
}

/* @oldStateDir:
 * For upgrade purpose: see virHostdevNetConfigRestore
 */
void
virHostdevReAttachPCIDevices(virHostdevManagerPtr hostdev_mgr,
                             const char *drv_name,
794
                             const char *dom_name,
795 796
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs,
797
                             const char *oldStateDir)
798 799 800 801
{
    virPCIDeviceListPtr pcidevs;
    size_t i;

802 803 804
    if (!nhostdevs)
        return;

805 806
    virObjectLock(hostdev_mgr->activePCIHostdevs);
    virObjectLock(hostdev_mgr->inactivePCIHostdevs);
807

808
    if (!(pcidevs = virHostdevGetActivePCIHostDeviceList(hostdev_mgr,
809 810 811 812 813 814 815 816 817
                                                         hostdevs,
                                                         nhostdevs))) {
        virErrorPtr err = virGetLastError();
        VIR_ERROR(_("Failed to allocate PCI device list: %s"),
                  err ? err->message : _("unknown error"));
        virResetError(err);
        goto cleanup;
    }

818 819
    /* Reattaching devices to the host involves several steps; each
     * of them is described at length below */
820

821
    /* Step 1: verify that each device in the hostdevs list really was in use
822
     * by this domain, and remove them all from the activePCIHostdevs list.
823
     */
824 825
    i = 0;
    while (i < virPCIDeviceListCount(pcidevs)) {
826 827 828
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
        virPCIDevicePtr activeDev = NULL;

829
        activeDev = virPCIDeviceListFind(hostdev_mgr->activePCIHostdevs, dev);
830 831 832 833 834
        if (activeDev) {
            const char *usedby_drvname;
            const char *usedby_domname;
            virPCIDeviceGetUsedBy(activeDev, &usedby_drvname, &usedby_domname);
            if (STRNEQ_NULLABLE(drv_name, usedby_drvname) ||
835
                STRNEQ_NULLABLE(dom_name, usedby_domname)) {
836 837 838 839 840
                    virPCIDeviceListDel(pcidevs, dev);
                    continue;
                }
        }

841 842
        VIR_DEBUG("Removing PCI device %s from active list",
                  virPCIDeviceGetName(dev));
843
        virPCIDeviceListDel(hostdev_mgr->activePCIHostdevs, dev);
844
        i++;
845 846 847
    }

    /* At this point, any device that had been used by the guest is in
848
     * pcidevs, but has been removed from activePCIHostdevs.
849 850
     */

851
    /* Step 2: restore original network config of hostdevs that used
852
     * <interface type='hostdev'>
853
     */
854 855 856 857 858 859 860 861 862 863
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];

        if (virHostdevIsPCINetDevice(hostdev)) {
            virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;
            virPCIDevicePtr dev = NULL;
            dev = virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                                  pcisrc->addr.slot, pcisrc->addr.function);
            if (dev) {
                if (virPCIDeviceListFind(pcidevs, dev)) {
864 865
                    VIR_DEBUG("Restoring network configuration of PCI device %s",
                              virPCIDeviceGetName(dev));
866 867 868 869 870 871 872
                    virHostdevNetConfigRestore(hostdev, hostdev_mgr->stateDir,
                                               oldStateDir);
                }
            }
            virPCIDeviceFree(dev);
        }
    }
873

874
    /* Step 3: perform a PCI Reset on all devices */
875 876 877
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);

878
        VIR_DEBUG("Resetting PCI device %s", virPCIDeviceGetName(dev));
879 880
        if (virPCIDeviceReset(dev, hostdev_mgr->activePCIHostdevs,
                              hostdev_mgr->inactivePCIHostdevs) < 0) {
881 882 883 884 885 886 887
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to reset PCI device: %s"),
                      err ? err->message : _("unknown error"));
            virResetError(err);
        }
    }

888
    /* Step 4: reattach devices to their host drivers (if managed) or place
889
     * them on the inactive list (if not managed)
890
     */
891 892
    while (virPCIDeviceListCount(pcidevs) > 0) {
        virPCIDevicePtr dev = virPCIDeviceListStealIndex(pcidevs, 0);
893
        virHostdevReattachPCIDevice(dev, hostdev_mgr);
894 895 896
    }

    virObjectUnref(pcidevs);
897
 cleanup:
898 899
    virObjectUnlock(hostdev_mgr->activePCIHostdevs);
    virObjectUnlock(hostdev_mgr->inactivePCIHostdevs);
900
}
901 902

int
903
virHostdevUpdateActivePCIDevices(virHostdevManagerPtr mgr,
904 905
                                 virDomainHostdevDefPtr *hostdevs,
                                 int nhostdevs,
906
                                 const char *drv_name,
907
                                 const char *dom_name)
908 909 910 911 912 913
{
    virDomainHostdevDefPtr hostdev = NULL;
    virPCIDevicePtr dev = NULL;
    size_t i;
    int ret = -1;

914 915 916
    if (!nhostdevs)
        return 0;

917 918
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
919

920
    for (i = 0; i < nhostdevs; i++) {
921
        virDomainHostdevSubsysPCIPtr pcisrc;
922
        hostdev = hostdevs[i];
923
        pcisrc = &hostdev->source.subsys.u.pci;
924 925 926 927 928 929

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

930 931
        dev = virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                              pcisrc->addr.slot, pcisrc->addr.function);
932 933 934 935 936

        if (!dev)
            goto cleanup;

        virPCIDeviceSetManaged(dev, hostdev->managed);
937
        virPCIDeviceSetUsedBy(dev, drv_name, dom_name);
938

939 940 941 942 943 944 945
        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO)
            virPCIDeviceSetStubDriver(dev, VIR_PCI_STUB_DRIVER_VFIO);
        else if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN)
            virPCIDeviceSetStubDriver(dev, VIR_PCI_STUB_DRIVER_XEN);
        else
            virPCIDeviceSetStubDriver(dev, VIR_PCI_STUB_DRIVER_KVM);

946 947 948 949 950
        /* Setup the original states for the PCI device */
        virPCIDeviceSetUnbindFromStub(dev, hostdev->origstates.states.pci.unbind_from_stub);
        virPCIDeviceSetRemoveSlot(dev, hostdev->origstates.states.pci.remove_slot);
        virPCIDeviceSetReprobe(dev, hostdev->origstates.states.pci.reprobe);

951
        if (virPCIDeviceListAdd(mgr->activePCIHostdevs, dev) < 0)
952 953 954 955 956
            goto cleanup;
        dev = NULL;
    }

    ret = 0;
957
 cleanup:
958
    virPCIDeviceFree(dev);
959 960
    virObjectUnlock(mgr->activePCIHostdevs);
    virObjectUnlock(mgr->inactivePCIHostdevs);
961 962 963 964
    return ret;
}

int
965
virHostdevUpdateActiveUSBDevices(virHostdevManagerPtr mgr,
966 967
                                 virDomainHostdevDefPtr *hostdevs,
                                 int nhostdevs,
968
                                 const char *drv_name,
969
                                 const char *dom_name)
970 971 972 973 974
{
    virDomainHostdevDefPtr hostdev = NULL;
    size_t i;
    int ret = -1;

975 976 977
    if (!nhostdevs)
        return 0;

978
    virObjectLock(mgr->activeUSBHostdevs);
979
    for (i = 0; i < nhostdevs; i++) {
980
        virDomainHostdevSubsysUSBPtr usbsrc;
981
        virUSBDevicePtr usb = NULL;
982
        hostdev = hostdevs[i];
983
        usbsrc = &hostdev->source.subsys.u.usb;
984 985 986 987 988 989

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

990
        if (!(usb = virUSBDeviceNew(usbsrc->bus, usbsrc->device, NULL))) {
991
            VIR_WARN("Unable to reattach USB device %03d.%03d on domain %s",
992
                     usbsrc->bus, usbsrc->device, dom_name);
993 994 995
            continue;
        }

996
        virUSBDeviceSetUsedBy(usb, drv_name, dom_name);
997

998
        if (virUSBDeviceListAdd(mgr->activeUSBHostdevs, usb) < 0) {
999 1000 1001 1002 1003
            virUSBDeviceFree(usb);
            goto cleanup;
        }
    }
    ret = 0;
1004
 cleanup:
1005
    virObjectUnlock(mgr->activeUSBHostdevs);
1006 1007 1008
    return ret;
}

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
static int
virHostdevUpdateActiveSCSIHostDevices(virHostdevManagerPtr mgr,
                                      virDomainHostdevDefPtr hostdev,
                                      virDomainHostdevSubsysSCSIPtr scsisrc,
                                      const char *drv_name,
                                      const char *dom_name)
{
    virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
    virSCSIDevicePtr scsi = NULL;
    virSCSIDevicePtr tmp = NULL;
    int ret = -1;

    if (!(scsi = virSCSIDeviceNew(NULL,
                                  scsihostsrc->adapter, scsihostsrc->bus,
                                  scsihostsrc->target, scsihostsrc->unit,
                                  hostdev->readonly, hostdev->shareable)))
        goto cleanup;

    if ((tmp = virSCSIDeviceListFind(mgr->activeSCSIHostdevs, scsi))) {
        if (virSCSIDeviceSetUsedBy(tmp, drv_name, dom_name) < 0) {
            virSCSIDeviceFree(scsi);
            goto cleanup;
        }
        virSCSIDeviceFree(scsi);
    } else {
        if (virSCSIDeviceSetUsedBy(scsi, drv_name, dom_name) < 0 ||
            virSCSIDeviceListAdd(mgr->activeSCSIHostdevs, scsi) < 0) {
            virSCSIDeviceFree(scsi);
            goto cleanup;
        }
    }
    ret = 0;

 cleanup:
    return ret;
}

1046
int
1047
virHostdevUpdateActiveSCSIDevices(virHostdevManagerPtr mgr,
1048 1049
                                  virDomainHostdevDefPtr *hostdevs,
                                  int nhostdevs,
1050
                                  const char *drv_name,
1051
                                  const char *dom_name)
1052 1053 1054 1055 1056
{
    virDomainHostdevDefPtr hostdev = NULL;
    size_t i;
    int ret = -1;

1057 1058 1059
    if (!nhostdevs)
        return 0;

1060
    virObjectLock(mgr->activeSCSIHostdevs);
1061
    for (i = 0; i < nhostdevs; i++) {
1062
        virDomainHostdevSubsysSCSIPtr scsisrc;
1063
        hostdev = hostdevs[i];
1064
        scsisrc = &hostdev->source.subsys.u.scsi;
1065 1066 1067 1068 1069

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

1070 1071
        if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
            continue;  /* Not supported for iSCSI */
1072
        } else {
1073 1074
            if (virHostdevUpdateActiveSCSIHostDevices(mgr, hostdev, scsisrc,
                                                      drv_name, dom_name) < 0)
1075 1076 1077 1078 1079
                goto cleanup;
        }
    }
    ret = 0;

1080
 cleanup:
1081
    virObjectUnlock(mgr->activeSCSIHostdevs);
1082 1083
    return ret;
}
1084 1085

static int
1086 1087 1088 1089
virHostdevMarkUSBDevices(virHostdevManagerPtr mgr,
                         const char *drv_name,
                         const char *dom_name,
                         virUSBDeviceListPtr list)
1090 1091 1092 1093 1094
{
    size_t i, j;
    unsigned int count;
    virUSBDevicePtr tmp;

1095
    virObjectLock(mgr->activeUSBHostdevs);
1096 1097 1098 1099
    count = virUSBDeviceListCount(list);

    for (i = 0; i < count; i++) {
        virUSBDevicePtr usb = virUSBDeviceListGet(list, i);
1100
        if ((tmp = virUSBDeviceListFind(mgr->activeUSBHostdevs, usb))) {
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
            const char *other_drvname;
            const char *other_domname;

            virUSBDeviceGetUsedBy(tmp, &other_drvname, &other_domname);
            if (other_drvname && other_domname)
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("USB device %s is in use by "
                                 "driver %s, domain %s"),
                               virUSBDeviceGetName(tmp),
                               other_drvname, other_domname);
            else
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("USB device %s is already in use"),
                               virUSBDeviceGetName(tmp));
            goto error;
        }

1118
        virUSBDeviceSetUsedBy(usb, drv_name, dom_name);
1119
        VIR_DEBUG("Adding %03d.%03d dom=%s to activeUSBHostdevs",
1120 1121
                  virUSBDeviceGetBus(usb), virUSBDeviceGetDevno(usb),
                  dom_name);
1122 1123 1124 1125 1126
        /*
         * The caller is responsible to steal these usb devices
         * from the virUSBDeviceList that passed in on success,
         * perform rollback on failure.
         */
1127
        if (virUSBDeviceListAdd(mgr->activeUSBHostdevs, usb) < 0)
1128 1129 1130
            goto error;
    }

1131
    virObjectUnlock(mgr->activeUSBHostdevs);
1132 1133
    return 0;

1134
 error:
1135 1136
    for (j = 0; j < i; j++) {
        tmp = virUSBDeviceListGet(list, i);
1137
        virUSBDeviceListSteal(mgr->activeUSBHostdevs, tmp);
1138
    }
1139
    virObjectUnlock(mgr->activeUSBHostdevs);
1140 1141 1142 1143 1144 1145 1146 1147 1148
    return -1;
}


static int
virHostdevFindUSBDevice(virDomainHostdevDefPtr hostdev,
                        bool mandatory,
                        virUSBDevicePtr *usb)
{
1149 1150 1151 1152 1153 1154
    virDomainHostdevSubsysUSBPtr usbsrc = &hostdev->source.subsys.u.usb;
    unsigned vendor = usbsrc->vendor;
    unsigned product = usbsrc->product;
    unsigned bus = usbsrc->bus;
    unsigned device = usbsrc->device;
    bool autoAddress = usbsrc->autoAddress;
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
    int rc;

    *usb = NULL;

    if (vendor && bus) {
        rc = virUSBDeviceFind(vendor, product, bus, device,
                              NULL,
                              autoAddress ? false : mandatory,
                              usb);
        if (rc < 0) {
            return -1;
        } 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) {
        virUSBDeviceListPtr devs;

        rc = virUSBDeviceFindByVendor(vendor, product, NULL, mandatory, &devs);
        if (rc < 0)
            return -1;

        if (rc == 1) {
            *usb = virUSBDeviceListGet(devs, 0);
            virUSBDeviceListSteal(devs, *usb);
        }
        virObjectUnref(devs);

        if (rc == 0) {
            goto out;
        } else if (rc > 1) {
            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);
            }
            return -1;
        }

1209 1210 1211
        usbsrc->bus = virUSBDeviceGetBus(*usb);
        usbsrc->device = virUSBDeviceGetDevno(*usb);
        usbsrc->autoAddress = true;
1212 1213 1214 1215 1216

        if (autoAddress) {
            VIR_INFO("USB device %x:%x found at bus:%u device:%u (moved"
                     " from bus:%u device:%u)",
                     vendor, product,
1217
                     usbsrc->bus, usbsrc->device,
1218 1219 1220 1221 1222 1223 1224
                     bus, device);
        }
    } else if (!vendor && bus) {
        if (virUSBDeviceFindByBus(bus, device, NULL, mandatory, usb) < 0)
            return -1;
    }

1225
 out:
1226 1227 1228 1229 1230 1231 1232 1233
    if (!*usb)
        hostdev->missing = true;
    return 0;
}

int
virHostdevPrepareUSBDevices(virHostdevManagerPtr hostdev_mgr,
                            const char *drv_name,
1234
                            const char *dom_name,
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
                            virDomainHostdevDefPtr *hostdevs,
                            int nhostdevs,
                            unsigned int flags)
{
    size_t i;
    int ret = -1;
    virUSBDeviceListPtr list;
    virUSBDevicePtr tmp;
    bool coldBoot = !!(flags & VIR_HOSTDEV_COLD_BOOT);

1245 1246 1247
    if (!nhostdevs)
        return 0;

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    /* 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 virHostdevPreparePCIDevices()
     */
    if (!(list = virUSBDeviceListNew()))
        goto cleanup;

    /* Loop 1: build temporary list
     */
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
        bool required = true;
        virUSBDevicePtr usb;

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

        if (hostdev->startupPolicy == VIR_DOMAIN_STARTUP_POLICY_OPTIONAL ||
            (hostdev->startupPolicy == VIR_DOMAIN_STARTUP_POLICY_REQUISITE &&
             !coldBoot))
            required = false;

        if (virHostdevFindUSBDevice(hostdev, required, &usb) < 0)
            goto cleanup;

        if (usb && virUSBDeviceListAdd(list, usb) < 0) {
            virUSBDeviceFree(usb);
            goto cleanup;
        }
    }

1282
    /* Mark devices in temporary list as used by @dom_name
1283 1284 1285
     * and add them do driver list. However, if something goes
     * wrong, perform rollback.
     */
1286
    if (virHostdevMarkUSBDevices(hostdev_mgr, drv_name, dom_name, list) < 0)
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
        goto cleanup;

    /* Loop 2: Temporary list was successfully merged with
     * driver list, so steal all items to avoid freeing them
     * in cleanup label.
     */
    while (virUSBDeviceListCount(list) > 0) {
        tmp = virUSBDeviceListGet(list, 0);
        virUSBDeviceListSteal(list, tmp);
    }

    ret = 0;

1300
 cleanup:
1301 1302 1303
    virObjectUnref(list);
    return ret;
}
1304

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
static int
virHostdevPrepareSCSIHostDevices(virDomainHostdevDefPtr hostdev,
                                 virDomainHostdevSubsysSCSIPtr scsisrc,
                                 virSCSIDeviceListPtr list)
{
    virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
    virSCSIDevicePtr scsi;
    int ret = -1;

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

    if (!(scsi = virSCSIDeviceNew(NULL,
                                  scsihostsrc->adapter, scsihostsrc->bus,
                                  scsihostsrc->target, scsihostsrc->unit,
                                  hostdev->readonly, hostdev->shareable)))
        goto cleanup;

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

    ret = 0;

 cleanup:
    return ret;
}

1337 1338 1339
int
virHostdevPrepareSCSIDevices(virHostdevManagerPtr hostdev_mgr,
                             const char *drv_name,
1340
                             const char *dom_name,
1341 1342 1343 1344 1345 1346 1347 1348
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs)
{
    size_t i, j;
    int count;
    virSCSIDeviceListPtr list;
    virSCSIDevicePtr tmp;

1349 1350 1351
    if (!nhostdevs)
        return 0;

1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
    /* 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 virHostdevPreparePCIDevices()
     */
    if (!(list = virSCSIDeviceListNew()))
        goto cleanup;

    /* Loop 1: build temporary list */
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
1363
        virDomainHostdevSubsysSCSIPtr scsisrc = &hostdev->source.subsys.u.scsi;
1364 1365 1366 1367 1368

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

1369 1370 1371 1372 1373
        if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
            continue;  /* Not supported for iSCSI */
        } else {
            if (virHostdevPrepareSCSIHostDevices(hostdev, scsisrc, list) < 0)
                goto cleanup;
1374 1375 1376 1377 1378 1379 1380
        }
    }

    /* Loop 2: Mark devices in temporary list as used by @name
     * and add them to driver list. However, if something goes
     * wrong, perform rollback.
     */
1381
    virObjectLock(hostdev_mgr->activeSCSIHostdevs);
1382 1383 1384 1385
    count = virSCSIDeviceListCount(list);

    for (i = 0; i < count; i++) {
        virSCSIDevicePtr scsi = virSCSIDeviceListGet(list, i);
1386
        if ((tmp = virSCSIDeviceListFind(hostdev_mgr->activeSCSIHostdevs,
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
                                         scsi))) {
            bool scsi_shareable = virSCSIDeviceGetShareable(scsi);
            bool tmp_shareable = virSCSIDeviceGetShareable(tmp);

            if (!(scsi_shareable && tmp_shareable)) {
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("SCSI device %s is already in use by "
                                 "other domain(s) as '%s'"),
                               virSCSIDeviceGetName(tmp),
                               tmp_shareable ? "shareable" : "non-shareable");
                goto error;
            }

1400
            if (virSCSIDeviceSetUsedBy(tmp, drv_name, dom_name) < 0)
1401 1402
                goto error;
        } else {
1403
            if (virSCSIDeviceSetUsedBy(scsi, drv_name, dom_name) < 0)
1404 1405
                goto error;

1406
            VIR_DEBUG("Adding %s to activeSCSIHostdevs", virSCSIDeviceGetName(scsi));
1407

1408
            if (virSCSIDeviceListAdd(hostdev_mgr->activeSCSIHostdevs, scsi) < 0)
1409 1410 1411 1412
                goto error;
        }
    }

1413
    virObjectUnlock(hostdev_mgr->activeSCSIHostdevs);
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426

    /* Loop 3: Temporary list was successfully merged with
     * 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;

1427
 error:
1428 1429
    for (j = 0; j < i; j++) {
        tmp = virSCSIDeviceListGet(list, i);
1430
        virSCSIDeviceListSteal(hostdev_mgr->activeSCSIHostdevs, tmp);
1431
    }
1432
    virObjectUnlock(hostdev_mgr->activeSCSIHostdevs);
1433
 cleanup:
1434 1435 1436
    virObjectUnref(list);
    return -1;
}
1437 1438

void
1439 1440 1441 1442 1443
virHostdevReAttachUSBDevices(virHostdevManagerPtr hostdev_mgr,
                             const char *drv_name,
                             const char *dom_name,
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs)
1444 1445 1446
{
    size_t i;

1447 1448 1449
    if (!nhostdevs)
        return;

1450
    virObjectLock(hostdev_mgr->activeUSBHostdevs);
1451 1452
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
1453
        virDomainHostdevSubsysUSBPtr usbsrc = &hostdev->source.subsys.u.usb;
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
        virUSBDevicePtr usb, tmp;
        const char *usedby_drvname;
        const char *usedby_domname;

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

1465
        if (!(usb = virUSBDeviceNew(usbsrc->bus, usbsrc->device, NULL))) {
1466
            VIR_WARN("Unable to reattach USB device %03d.%03d on domain %s",
1467
                     usbsrc->bus, usbsrc->device, dom_name);
1468 1469 1470 1471 1472 1473 1474 1475 1476
            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 */

1477
        tmp = virUSBDeviceListFind(hostdev_mgr->activeUSBHostdevs, usb);
1478 1479 1480 1481 1482
        virUSBDeviceFree(usb);

        if (!tmp) {
            VIR_WARN("Unable to find device %03d.%03d "
                     "in list of active USB devices",
1483
                     usbsrc->bus, usbsrc->device);
1484 1485 1486 1487 1488
            continue;
        }

        virUSBDeviceGetUsedBy(tmp, &usedby_drvname, &usedby_domname);
        if (STREQ_NULLABLE(drv_name, usedby_drvname) &&
1489
            STREQ_NULLABLE(dom_name, usedby_domname)) {
1490
            VIR_DEBUG("Removing %03d.%03d dom=%s from activeUSBHostdevs",
1491
                      usbsrc->bus, usbsrc->device, dom_name);
1492
            virUSBDeviceListDel(hostdev_mgr->activeUSBHostdevs, tmp);
1493 1494
        }
    }
1495
    virObjectUnlock(hostdev_mgr->activeUSBHostdevs);
1496
}
1497

1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
static void
virHostdevReAttachSCSIHostDevices(virHostdevManagerPtr hostdev_mgr,
                                  virDomainHostdevDefPtr hostdev,
                                  virDomainHostdevSubsysSCSIPtr scsisrc,
                                  const char *drv_name,
                                  const char *dom_name)
{
    virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
    virSCSIDevicePtr scsi;
    virSCSIDevicePtr tmp;

    if (!(scsi = virSCSIDeviceNew(NULL,
                                  scsihostsrc->adapter, scsihostsrc->bus,
                                  scsihostsrc->target, scsihostsrc->unit,
                                  hostdev->readonly, hostdev->shareable))) {
1513
        VIR_WARN("Unable to reattach SCSI device %s:%u:%u:%llu on domain %s",
1514 1515 1516 1517 1518 1519 1520 1521 1522
                 scsihostsrc->adapter, scsihostsrc->bus, scsihostsrc->target,
                 scsihostsrc->unit, dom_name);
        return;
    }

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

    if (!(tmp = virSCSIDeviceListFind(hostdev_mgr->activeSCSIHostdevs, scsi))) {
1523
        VIR_WARN("Unable to find device %s:%u:%u:%llu "
1524 1525 1526 1527 1528 1529 1530
                 "in list of active SCSI devices",
                 scsihostsrc->adapter, scsihostsrc->bus,
                 scsihostsrc->target, scsihostsrc->unit);
        virSCSIDeviceFree(scsi);
        return;
    }

1531
    VIR_DEBUG("Removing %s:%u:%u:%llu dom=%s from activeSCSIHostdevs",
1532 1533 1534 1535 1536 1537 1538 1539
               scsihostsrc->adapter, scsihostsrc->bus, scsihostsrc->target,
               scsihostsrc->unit, dom_name);

    virSCSIDeviceListDel(hostdev_mgr->activeSCSIHostdevs, tmp,
                         drv_name, dom_name);
    virSCSIDeviceFree(scsi);
}

1540
void
1541 1542 1543 1544 1545
virHostdevReAttachSCSIDevices(virHostdevManagerPtr hostdev_mgr,
                              const char *drv_name,
                              const char *dom_name,
                              virDomainHostdevDefPtr *hostdevs,
                              int nhostdevs)
1546 1547 1548
{
    size_t i;

1549 1550 1551
    if (!nhostdevs)
        return;

1552
    virObjectLock(hostdev_mgr->activeSCSIHostdevs);
1553 1554
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
1555
        virDomainHostdevSubsysSCSIPtr scsisrc = &hostdev->source.subsys.u.scsi;
1556 1557 1558 1559 1560

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

1561 1562 1563 1564 1565
        if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI)
            continue; /* Not supported for iSCSI */
        else
            virHostdevReAttachSCSIHostDevices(hostdev_mgr, hostdev, scsisrc,
                                              drv_name, dom_name);
1566
    }
1567
    virObjectUnlock(hostdev_mgr->activeSCSIHostdevs);
1568
}
1569 1570

int
1571
virHostdevPCINodeDeviceDetach(virHostdevManagerPtr hostdev_mgr,
1572 1573
                              virPCIDevicePtr pci)
{
1574 1575
    struct virHostdevIsPCINodeDeviceUsedData data = { hostdev_mgr, NULL,
                                                     false };
1576 1577
    int ret = -1;

1578 1579
    virObjectLock(hostdev_mgr->activePCIHostdevs);
    virObjectLock(hostdev_mgr->inactivePCIHostdevs);
1580

1581
    if (virHostdevIsPCINodeDeviceUsed(virPCIDeviceGetAddress(pci), &data))
1582
        goto cleanup;
1583

1584
    if (virPCIDeviceDetach(pci, hostdev_mgr->activePCIHostdevs,
1585 1586
                           hostdev_mgr->inactivePCIHostdevs) < 0)
        goto cleanup;
1587 1588

    ret = 0;
1589 1590

 cleanup:
1591 1592
    virObjectUnlock(hostdev_mgr->inactivePCIHostdevs);
    virObjectUnlock(hostdev_mgr->activePCIHostdevs);
1593

1594 1595 1596 1597
    return ret;
}

int
1598
virHostdevPCINodeDeviceReAttach(virHostdevManagerPtr hostdev_mgr,
1599 1600
                                virPCIDevicePtr pci)
{
1601 1602
    struct virHostdevIsPCINodeDeviceUsedData data = {hostdev_mgr, NULL,
                                                     false};
1603 1604
    int ret = -1;

1605 1606
    virObjectLock(hostdev_mgr->activePCIHostdevs);
    virObjectLock(hostdev_mgr->inactivePCIHostdevs);
1607

1608
    if (virHostdevIsPCINodeDeviceUsed(virPCIDeviceGetAddress(pci), &data))
1609
        goto cleanup;
1610

1611 1612 1613
    virPCIDeviceSetUnbindFromStub(pci, true);
    virPCIDeviceSetRemoveSlot(pci, true);
    virPCIDeviceSetReprobe(pci, true);
1614

1615 1616
    if (virPCIDeviceReattach(pci, hostdev_mgr->activePCIHostdevs,
                             hostdev_mgr->inactivePCIHostdevs) < 0)
1617
        goto cleanup;
1618 1619

    ret = 0;
1620 1621

 cleanup:
1622 1623
    virObjectUnlock(hostdev_mgr->inactivePCIHostdevs);
    virObjectUnlock(hostdev_mgr->activePCIHostdevs);
1624

1625 1626 1627 1628
    return ret;
}

int
1629
virHostdevPCINodeDeviceReset(virHostdevManagerPtr hostdev_mgr,
1630 1631 1632 1633
                             virPCIDevicePtr pci)
{
    int ret = -1;

1634 1635 1636 1637
    virObjectLock(hostdev_mgr->activePCIHostdevs);
    virObjectLock(hostdev_mgr->inactivePCIHostdevs);
    if (virPCIDeviceReset(pci, hostdev_mgr->activePCIHostdevs,
                          hostdev_mgr->inactivePCIHostdevs) < 0)
1638 1639 1640
        goto out;

    ret = 0;
1641
 out:
1642 1643
    virObjectUnlock(hostdev_mgr->inactivePCIHostdevs);
    virObjectUnlock(hostdev_mgr->activePCIHostdevs);
1644 1645
    return ret;
}
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 1684

int
virHostdevPrepareDomainDevices(virHostdevManagerPtr mgr,
                               const char *driver,
                               virDomainDefPtr def,
                               unsigned int flags)
{
    if (!def->nhostdevs)
        return 0;

    if (mgr == NULL)
        return -1;

    if (flags & VIR_HOSTDEV_SP_PCI) {
        if (virHostdevPreparePCIDevices(mgr, driver,
                                        def->name, def->uuid,
                                        def->hostdevs,
                                        def->nhostdevs,
                                        flags) < 0)
            return -1;
    }

    if (flags & VIR_HOSTDEV_SP_USB) {
        if (virHostdevPrepareUSBDevices(mgr, driver, def->name,
                                         def->hostdevs, def->nhostdevs,
                                         flags) < 0)
            return -1;
    }

    if (flags & VIR_HOSTDEV_SP_SCSI) {
        if (virHostdevPrepareSCSIDevices(mgr, driver, def->name,
                                         def->hostdevs, def->nhostdevs) < 0)
        return -1;
    }

    return 0;
}

/* @oldStateDir
1685
 * For upgrade purpose: see virHostdevReAttachPCIHostdevs
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
 */
void
virHostdevReAttachDomainDevices(virHostdevManagerPtr mgr,
                                const char *driver,
                                virDomainDefPtr def,
                                unsigned int flags,
                                const char *oldStateDir)
{
    if (!def->nhostdevs || !mgr)
        return;

    if (flags & VIR_HOSTDEV_SP_PCI) {
        virHostdevReAttachPCIDevices(mgr, driver, def->name,
                                     def->hostdevs, def->nhostdevs,
                                     oldStateDir);
    }

    if (flags & VIR_HOSTDEV_SP_USB) {
        virHostdevReAttachUSBDevices(mgr, driver, def->name,
                                     def->hostdevs, def->nhostdevs);
    }

    if (flags & VIR_HOSTDEV_SP_SCSI) {
        virHostdevReAttachSCSIDevices(mgr, driver, def->name,
                                      def->hostdevs, def->nhostdevs);
    }
}

int
1715
virHostdevUpdateActiveDomainDevices(virHostdevManagerPtr mgr,
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
                                    const char *driver,
                                    virDomainDefPtr def,
                                    unsigned int flags)
{
    if (!def->nhostdevs)
        return 0;

    if (flags & VIR_HOSTDEV_SP_PCI) {
        if (virHostdevUpdateActivePCIDevices(mgr,
                                             def->hostdevs,
                                             def->nhostdevs,
                                             driver, def->name) < 0)
            return -1;
    }

    if (flags & VIR_HOSTDEV_SP_USB) {
        if (virHostdevUpdateActiveUSBDevices(mgr,
                                             def->hostdevs,
                                             def->nhostdevs,
                                             driver, def->name) < 0)
            return -1;
    }

    if (flags & VIR_HOSTDEV_SP_SCSI) {
        if (virHostdevUpdateActiveSCSIDevices(mgr,
                                              def->hostdevs,
                                              def->nhostdevs,
                                              driver, def->name) < 0)
            return -1;
    }

    return 0;
}