virhostdev.c 53.5 KB
Newer Older
1 2
/* virhostdev.c: hostdev management
 *
3 4
 * Copyright (C) 2006-2007, 2009-2013 Red Hat, Inc.
 * 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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
static virHostdevManagerPtr manager; /* global hostdev manager, never freed */

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

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)
72 73

static void
74
virHostdevManagerDispose(void *obj)
75
{
76 77
    virHostdevManagerPtr hostdevMgr = obj;

78 79 80
    if (!hostdevMgr)
        return;

81 82 83 84
    virObjectUnref(hostdevMgr->activePCIHostdevs);
    virObjectUnref(hostdevMgr->inactivePCIHostdevs);
    virObjectUnref(hostdevMgr->activeUSBHostdevs);
    virObjectUnref(hostdevMgr->activeSCSIHostdevs);
85 86 87
    VIR_FREE(hostdevMgr->stateDir);
}

88 89
static virHostdevManagerPtr
virHostdevManagerNew(void)
90
{
91
    virHostdevManagerPtr hostdevMgr;
92
    bool privileged = geteuid() == 0;
93 94 95

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

97
    if ((hostdevMgr->activePCIHostdevs = virPCIDeviceListNew()) == NULL)
98 99
        goto error;

100
    if ((hostdevMgr->activeUSBHostdevs = virUSBDeviceListNew()) == NULL)
101 102
        goto error;

103
    if ((hostdevMgr->inactivePCIHostdevs = virPCIDeviceListNew()) == NULL)
104 105
        goto error;

106
    if ((hostdevMgr->activeSCSIHostdevs = virSCSIDeviceListNew()) == NULL)
107 108
        goto error;

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    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);
142 143
    }

144
    return hostdevMgr;
145

146
 error:
147 148
    virObjectUnref(hostdevMgr);
    return NULL;
149 150 151 152 153
}

virHostdevManagerPtr
virHostdevManagerGetDefault(void)
{
154
    if (virHostdevManagerInitialize() < 0)
155
        return NULL;
156 157

    return virObjectRef(manager);
158
}
159 160

static virPCIDeviceListPtr
161
virHostdevGetPCIHostDeviceList(virDomainHostdevDefPtr *hostdevs, int nhostdevs)
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
{
    virPCIDeviceListPtr list;
    size_t i;

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

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

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

        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);
        if (!dev) {
            virObjectUnref(list);
            return NULL;
        }

        if (virPCIDeviceListAdd(list, dev) < 0) {
            virPCIDeviceFree(dev);
            virObjectUnref(list);
            return NULL;
        }

        virPCIDeviceSetManaged(dev, hostdev->managed);
        if (hostdev->source.subsys.u.pci.backend
            == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
            if (virPCIDeviceSetStubDriver(dev, "vfio-pci") < 0) {
                virObjectUnref(list);
                return NULL;
            }
200 201 202 203 204 205
        } else if (hostdev->source.subsys.u.pci.backend
                   == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN) {
            if (virPCIDeviceSetStubDriver(dev, "pciback") < 0) {
                virObjectUnref(list);
                return NULL;
            }
206 207 208 209 210 211 212 213 214 215 216 217 218
        } else {
            if (virPCIDeviceSetStubDriver(dev, "pci-stub") < 0) {
                virObjectUnref(list);
                return NULL;
            }
        }
    }

    return list;
}


/*
219
 * virHostdevGetActivePCIHostDeviceList - make a new list with a *copy* of
220
 *   every virPCIDevice object that is found on the activePCIHostdevs
221 222 223 224
 *   list *and* is in the hostdev list for this domain.
 *
 * Return the new list, or NULL if there was a failure.
 *
225
 * Pre-condition: activePCIHostdevs is locked
226 227
 */
static virPCIDeviceListPtr
228
virHostdevGetActivePCIHostDeviceList(virHostdevManagerPtr mgr,
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
                                     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;
249
        activeDev = virPCIDeviceListFindByIDs(mgr->activePCIHostdevs,
250 251 252 253 254 255 256 257 258 259 260 261
                                              addr->domain, addr->bus,
                                              addr->slot, addr->function);
        if (activeDev && virPCIDeviceListAddCopy(list, activeDev) < 0) {
            virObjectUnref(list);
            return NULL;
        }
    }

    return list;
}

static int
262
virHostdevPCISysfsPath(virDomainHostdevDefPtr hostdev,
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
                       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;

282
    if (virHostdevPCISysfsPath(hostdev, &sysfs_path) < 0)
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
        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;

300
    if (virHostdevPCISysfsPath(hostdev, &sysfs_path) < 0)
301 302 303 304 305 306 307 308 309 310 311 312 313 314
        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;

315
 cleanup:
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
    VIR_FREE(sysfs_path);

    return ret;
}


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,
365
                           const char *stateDir)
366 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 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
{
    char *linkdev = NULL;
    virNetDevVlanPtr vlan;
    virNetDevVPortProfilePtr virtPort;
    int ret = -1;
    int vf = -1;
    int vlanid = -1;
    bool port_profile_associate = true;
    int isvf;

    isvf = virHostdevIsVirtualFunction(hostdev);
    if (isvf <= 0) {
        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);
    }
425
 cleanup:
426 427 428 429 430 431 432 433 434 435 436 437 438
    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,
439 440
                           const char *stateDir,
                           const char *oldStateDir)
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 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
{
    char *linkdev = NULL;
    virNetDevVPortProfilePtr virtPort;
    int ret = -1;
    int vf = -1;
    bool port_profile_associate = false;
    int isvf;

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

    isvf = virHostdevIsVirtualFunction(hostdev);
    if (isvf <= 0) {
        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,
490
                            const char *dom_name,
491 492 493 494 495 496 497 498 499 500
                            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;

501 502 503
    if (!nhostdevs)
        return 0;

504 505
    virObjectLock(hostdev_mgr->activePCIHostdevs);
    virObjectLock(hostdev_mgr->inactivePCIHostdevs);
506

507
    if (!(pcidevs = virHostdevGetPCIHostDeviceList(hostdevs, nhostdevs)))
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
        goto cleanup;

    /* We have to use 9 loops here. *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.
     */

    /* Loop 1: validate that non-managed device isn't in use, eg
     * 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);
        virPCIDevicePtr other;
        bool strict_acs_check = !!(flags & VIR_HOSTDEV_STRICT_ACS_CHECK);

        if (!virPCIDeviceIsAssignable(dev, strict_acs_check)) {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is not assignable"),
                           virPCIDeviceGetName(dev));
            goto cleanup;
        }
        /* The device is in use by other active domain if
534
         * the dev is in list activePCIHostdevs.
535
         */
536
        if ((other = virPCIDeviceListFind(hostdev_mgr->activePCIHostdevs, dev))) {
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
            const char *other_drvname;
            const char *other_domname;

            virPCIDeviceGetUsedBy(other, &other_drvname, &other_domname);
            if (other_drvname && other_domname)
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("PCI device %s is in use by "
                                 "driver %s, domain %s"),
                               virPCIDeviceGetName(dev),
                               other_drvname, other_domname);
            else
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("PCI device %s is already in use"),
                               virPCIDeviceGetName(dev));
            goto cleanup;
        }
    }

    /* Loop 2: detach managed devices (i.e. bind to appropriate stub driver) */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
        if (virPCIDeviceGetManaged(dev) &&
559
            virPCIDeviceDetach(dev, hostdev_mgr->activePCIHostdevs, NULL) < 0)
560 561 562 563 564 565 566 567
            goto reattachdevs;
    }

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

568 569
        if (virPCIDeviceReset(dev, hostdev_mgr->activePCIHostdevs,
                              hostdev_mgr->inactivePCIHostdevs) < 0)
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
            goto reattachdevs;
    }

    /* 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 (virHostdevNetConfigReplace(hostdev, uuid,
                                            hostdev_mgr->stateDir) < 0) {
                 goto resetvfnetconfig;
             }
         }
         last_processed_hostdev_vf = i;
    }

    /* Loop 5: Now mark all the devices as active */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
594
        if (virPCIDeviceListAdd(hostdev_mgr->activePCIHostdevs, dev) < 0)
595 596 597 598 599 600
            goto inactivedevs;
    }

    /* Loop 6: Now remove the devices from inactive list. */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
         virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
601
         virPCIDeviceListDel(hostdev_mgr->inactivePCIHostdevs, dev);
602 603 604
    }

    /* Loop 7: Now set the used_by_domain of the device in
605
     * activePCIHostdevs as domain name.
606 607 608 609 610
     */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev, activeDev;

        dev = virPCIDeviceListGet(pcidevs, i);
611
        activeDev = virPCIDeviceListFind(hostdev_mgr->activePCIHostdevs, dev);
612 613

        if (activeDev)
614
            virPCIDeviceSetUsedBy(activeDev, drv_name, dom_name);
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
    }

    /* Loop 8: Now set the original states for hostdev def */
    for (i = 0; i < nhostdevs; i++) {
        virPCIDevicePtr dev;
        virPCIDevicePtr pcidev;
        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;

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

        /* original states "unbind_from_stub", "remove_slot",
         * "reprobe" were already set by pciDettachDevice in
         * loop 2.
         */
        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);
    }

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

    ret = 0;
    goto cleanup;

656
 inactivedevs:
657
    /* Only steal all the devices from activePCIHostdevs. We will
658 659 660 661
     * free them in virObjectUnref().
     */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
662
        virPCIDeviceListSteal(hostdev_mgr->activePCIHostdevs, dev);
663 664
    }

665
 resetvfnetconfig:
666 667 668 669
    for (i = 0;
         last_processed_hostdev_vf != -1 && i < last_processed_hostdev_vf; i++)
        virHostdevNetConfigRestore(hostdevs[i], hostdev_mgr->stateDir, NULL);

670
 reattachdevs:
671 672 673 674 675 676
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);

        /* NB: This doesn't actually re-bind to original driver, just
         * unbinds from the stub driver
         */
677
        ignore_value(virPCIDeviceReattach(dev, hostdev_mgr->activePCIHostdevs,
678 679 680
                                          NULL));
    }

681
 cleanup:
682 683
    virObjectUnlock(hostdev_mgr->activePCIHostdevs);
    virObjectUnlock(hostdev_mgr->inactivePCIHostdevs);
684 685 686 687 688
    virObjectUnref(pcidevs);
    return ret;
}

/*
689
 * Pre-condition: inactivePCIHostdevs & activePCIHostdevs
690 691 692
 * are locked
 */
static void
693
virHostdevReattachPCIDevice(virPCIDevicePtr dev, virHostdevManagerPtr mgr)
694 695 696 697 698
{
    /* If the device is not managed and was attached to guest
     * successfully, it must have been inactive.
     */
    if (!virPCIDeviceGetManaged(dev)) {
699
        if (virPCIDeviceListAdd(mgr->inactivePCIHostdevs, dev) < 0)
700 701 702 703 704 705 706 707 708 709 710 711 712 713
            virPCIDeviceFree(dev);
        return;
    }

    /* Wait for device cleanup if it is qemu/kvm */
    if (STREQ(virPCIDeviceGetStubDriver(dev), "pci-stub")) {
        int retries = 100;
        while (virPCIDeviceWaitForCleanup(dev, "kvm_assigned_device")
               && retries) {
            usleep(100*1000);
            retries--;
        }
    }

714 715
    if (virPCIDeviceReattach(dev, mgr->activePCIHostdevs,
                             mgr->inactivePCIHostdevs) < 0) {
716 717 718 719 720 721 722 723 724 725 726 727 728 729
        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,
730
                             const char *dom_name,
731 732
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs,
733
                             const char *oldStateDir)
734 735 736 737
{
    virPCIDeviceListPtr pcidevs;
    size_t i;

738 739 740
    if (!nhostdevs)
        return;

741 742
    virObjectLock(hostdev_mgr->activePCIHostdevs);
    virObjectLock(hostdev_mgr->inactivePCIHostdevs);
743

744
    if (!(pcidevs = virHostdevGetActivePCIHostDeviceList(hostdev_mgr,
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
                                                         hostdevs,
                                                         nhostdevs))) {
        virErrorPtr err = virGetLastError();
        VIR_ERROR(_("Failed to allocate PCI device list: %s"),
                  err ? err->message : _("unknown error"));
        virResetError(err);
        goto cleanup;
    }

    /* 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
     */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
        virPCIDevicePtr activeDev = NULL;

        /* delete the copy of the dev from pcidevs if it's used by
763
         * other domain. Or delete it from activePCIHostDevs if it had
764 765
         * been used by this domain.
         */
766
        activeDev = virPCIDeviceListFind(hostdev_mgr->activePCIHostdevs, dev);
767 768 769 770 771
        if (activeDev) {
            const char *usedby_drvname;
            const char *usedby_domname;
            virPCIDeviceGetUsedBy(activeDev, &usedby_drvname, &usedby_domname);
            if (STRNEQ_NULLABLE(drv_name, usedby_drvname) ||
772
                STRNEQ_NULLABLE(dom_name, usedby_domname)) {
773 774 775 776 777
                    virPCIDeviceListDel(pcidevs, dev);
                    continue;
                }
        }

778
        virPCIDeviceListDel(hostdev_mgr->activePCIHostdevs, dev);
779 780 781
    }

    /* At this point, any device that had been used by the guest is in
782
     * pcidevs, but has been removed from activePCIHostdevs.
783 784 785 786 787 788 789 790 791 792 793 794 795
     */

    /*
     * For SRIOV net host devices, unset mac and port profile before
     * reset and reattach device
     */
    for (i = 0; i < nhostdevs; i++)
        virHostdevNetConfigRestore(hostdevs[i], hostdev_mgr->stateDir,
                                   oldStateDir);

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

796 797
        if (virPCIDeviceReset(dev, hostdev_mgr->activePCIHostdevs,
                              hostdev_mgr->inactivePCIHostdevs) < 0) {
798 799 800 801 802 803 804 805 806
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to reset PCI device: %s"),
                      err ? err->message : _("unknown error"));
            virResetError(err);
        }
    }

    while (virPCIDeviceListCount(pcidevs) > 0) {
        virPCIDevicePtr dev = virPCIDeviceListStealIndex(pcidevs, 0);
807
        virHostdevReattachPCIDevice(dev, hostdev_mgr);
808 809 810
    }

    virObjectUnref(pcidevs);
811
 cleanup:
812 813
    virObjectUnlock(hostdev_mgr->activePCIHostdevs);
    virObjectUnlock(hostdev_mgr->inactivePCIHostdevs);
814
}
815 816

int
817
virHostdevUpdateActivePCIDevices(virHostdevManagerPtr mgr,
818 819
                                 virDomainHostdevDefPtr *hostdevs,
                                 int nhostdevs,
820
                                 const char *drv_name,
821
                                 const char *dom_name)
822 823 824 825 826 827
{
    virDomainHostdevDefPtr hostdev = NULL;
    virPCIDevicePtr dev = NULL;
    size_t i;
    int ret = -1;

828 829 830
    if (!nhostdevs)
        return 0;

831 832
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
833

834 835
    for (i = 0; i < nhostdevs; i++) {
        hostdev = hostdevs[i];
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854

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

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

        if (!dev)
            goto cleanup;

        virPCIDeviceSetManaged(dev, hostdev->managed);
        if (hostdev->source.subsys.u.pci.backend
            == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
            if (virPCIDeviceSetStubDriver(dev, "vfio-pci") < 0)
                goto cleanup;
855 856 857 858
        } else if (hostdev->source.subsys.u.pci.backend
                   == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN) {
            if (virPCIDeviceSetStubDriver(dev, "pciback") < 0)
                goto cleanup;
859 860 861 862 863
        } else {
            if (virPCIDeviceSetStubDriver(dev, "pci-stub") < 0)
                goto cleanup;

        }
864
        virPCIDeviceSetUsedBy(dev, drv_name, dom_name);
865 866 867 868 869 870

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

871
        if (virPCIDeviceListAdd(mgr->activePCIHostdevs, dev) < 0)
872 873 874 875 876
            goto cleanup;
        dev = NULL;
    }

    ret = 0;
877
 cleanup:
878
    virPCIDeviceFree(dev);
879 880
    virObjectUnlock(mgr->activePCIHostdevs);
    virObjectUnlock(mgr->inactivePCIHostdevs);
881 882 883 884
    return ret;
}

int
885
virHostdevUpdateActiveUSBDevices(virHostdevManagerPtr mgr,
886 887
                                 virDomainHostdevDefPtr *hostdevs,
                                 int nhostdevs,
888
                                 const char *drv_name,
889
                                 const char *dom_name)
890 891 892 893 894
{
    virDomainHostdevDefPtr hostdev = NULL;
    size_t i;
    int ret = -1;

895 896 897
    if (!nhostdevs)
        return 0;

898
    virObjectLock(mgr->activeUSBHostdevs);
899
    for (i = 0; i < nhostdevs; i++) {
900
        virDomainHostdevSubsysUSBPtr usbsrc;
901
        virUSBDevicePtr usb = NULL;
902
        hostdev = hostdevs[i];
903
        usbsrc = &hostdev->source.subsys.u.usb;
904 905 906 907 908 909

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

910
        if (!(usb = virUSBDeviceNew(usbsrc->bus, usbsrc->device, NULL))) {
911
            VIR_WARN("Unable to reattach USB device %03d.%03d on domain %s",
912
                     usbsrc->bus, usbsrc->device, dom_name);
913 914 915
            continue;
        }

916
        virUSBDeviceSetUsedBy(usb, drv_name, dom_name);
917

918
        if (virUSBDeviceListAdd(mgr->activeUSBHostdevs, usb) < 0) {
919 920 921 922 923
            virUSBDeviceFree(usb);
            goto cleanup;
        }
    }
    ret = 0;
924
 cleanup:
925
    virObjectUnlock(mgr->activeUSBHostdevs);
926 927 928 929
    return ret;
}

int
930
virHostdevUpdateActiveSCSIDevices(virHostdevManagerPtr mgr,
931 932
                                  virDomainHostdevDefPtr *hostdevs,
                                  int nhostdevs,
933
                                  const char *drv_name,
934
                                  const char *dom_name)
935 936 937 938 939 940 941
{
    virDomainHostdevDefPtr hostdev = NULL;
    size_t i;
    int ret = -1;
    virSCSIDevicePtr scsi = NULL;
    virSCSIDevicePtr tmp = NULL;

942 943 944
    if (!nhostdevs)
        return 0;

945
    virObjectLock(mgr->activeSCSIHostdevs);
946 947
    for (i = 0; i < nhostdevs; i++) {
        hostdev = hostdevs[i];
948 949 950 951 952 953 954 955 956 957 958 959 960 961

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

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

962
        if ((tmp = virSCSIDeviceListFind(mgr->activeSCSIHostdevs, scsi))) {
963
            if (virSCSIDeviceSetUsedBy(tmp, drv_name, dom_name) < 0) {
964 965 966 967 968
                virSCSIDeviceFree(scsi);
                goto cleanup;
            }
            virSCSIDeviceFree(scsi);
        } else {
969
            if (virSCSIDeviceSetUsedBy(scsi, drv_name, dom_name) < 0 ||
970
                virSCSIDeviceListAdd(mgr->activeSCSIHostdevs, scsi) < 0) {
971 972 973 974 975 976 977
                virSCSIDeviceFree(scsi);
                goto cleanup;
            }
        }
    }
    ret = 0;

978
 cleanup:
979
    virObjectUnlock(mgr->activeSCSIHostdevs);
980 981
    return ret;
}
982 983

static int
984 985 986 987
virHostdevMarkUSBDevices(virHostdevManagerPtr mgr,
                         const char *drv_name,
                         const char *dom_name,
                         virUSBDeviceListPtr list)
988 989 990 991 992
{
    size_t i, j;
    unsigned int count;
    virUSBDevicePtr tmp;

993
    virObjectLock(mgr->activeUSBHostdevs);
994 995 996 997
    count = virUSBDeviceListCount(list);

    for (i = 0; i < count; i++) {
        virUSBDevicePtr usb = virUSBDeviceListGet(list, i);
998
        if ((tmp = virUSBDeviceListFind(mgr->activeUSBHostdevs, usb))) {
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
            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;
        }

1016
        virUSBDeviceSetUsedBy(usb, drv_name, dom_name);
1017
        VIR_DEBUG("Adding %03d.%03d dom=%s to activeUSBHostdevs",
1018 1019
                  virUSBDeviceGetBus(usb), virUSBDeviceGetDevno(usb),
                  dom_name);
1020 1021 1022 1023 1024
        /*
         * The caller is responsible to steal these usb devices
         * from the virUSBDeviceList that passed in on success,
         * perform rollback on failure.
         */
1025
        if (virUSBDeviceListAdd(mgr->activeUSBHostdevs, usb) < 0)
1026 1027 1028
            goto error;
    }

1029
    virObjectUnlock(mgr->activeUSBHostdevs);
1030 1031
    return 0;

1032
 error:
1033 1034
    for (j = 0; j < i; j++) {
        tmp = virUSBDeviceListGet(list, i);
1035
        virUSBDeviceListSteal(mgr->activeUSBHostdevs, tmp);
1036
    }
1037
    virObjectUnlock(mgr->activeUSBHostdevs);
1038 1039 1040 1041 1042 1043 1044 1045 1046
    return -1;
}


static int
virHostdevFindUSBDevice(virDomainHostdevDefPtr hostdev,
                        bool mandatory,
                        virUSBDevicePtr *usb)
{
1047 1048 1049 1050 1051 1052
    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;
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
    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;
        }

1107 1108 1109
        usbsrc->bus = virUSBDeviceGetBus(*usb);
        usbsrc->device = virUSBDeviceGetDevno(*usb);
        usbsrc->autoAddress = true;
1110 1111 1112 1113 1114

        if (autoAddress) {
            VIR_INFO("USB device %x:%x found at bus:%u device:%u (moved"
                     " from bus:%u device:%u)",
                     vendor, product,
1115
                     usbsrc->bus, usbsrc->device,
1116 1117 1118 1119 1120 1121 1122
                     bus, device);
        }
    } else if (!vendor && bus) {
        if (virUSBDeviceFindByBus(bus, device, NULL, mandatory, usb) < 0)
            return -1;
    }

1123
 out:
1124 1125 1126 1127 1128 1129 1130 1131
    if (!*usb)
        hostdev->missing = true;
    return 0;
}

int
virHostdevPrepareUSBDevices(virHostdevManagerPtr hostdev_mgr,
                            const char *drv_name,
1132
                            const char *dom_name,
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
                            virDomainHostdevDefPtr *hostdevs,
                            int nhostdevs,
                            unsigned int flags)
{
    size_t i;
    int ret = -1;
    virUSBDeviceListPtr list;
    virUSBDevicePtr tmp;
    bool coldBoot = !!(flags & VIR_HOSTDEV_COLD_BOOT);

1143 1144 1145
    if (!nhostdevs)
        return 0;

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    /* 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;
        }
    }

1180
    /* Mark devices in temporary list as used by @dom_name
1181 1182 1183
     * and add them do driver list. However, if something goes
     * wrong, perform rollback.
     */
1184
    if (virHostdevMarkUSBDevices(hostdev_mgr, drv_name, dom_name, list) < 0)
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
        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;

1198
 cleanup:
1199 1200 1201
    virObjectUnref(list);
    return ret;
}
1202 1203 1204 1205

int
virHostdevPrepareSCSIDevices(virHostdevManagerPtr hostdev_mgr,
                             const char *drv_name,
1206
                             const char *dom_name,
1207 1208 1209 1210 1211 1212 1213 1214
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs)
{
    size_t i, j;
    int count;
    virSCSIDeviceListPtr list;
    virSCSIDevicePtr tmp;

1215 1216 1217
    if (!nhostdevs)
        return 0;

1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
    /* 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];
        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(NULL,
                                      hostdev->source.subsys.u.scsi.adapter,
                                      hostdev->source.subsys.u.scsi.bus,
                                      hostdev->source.subsys.u.scsi.target,
                                      hostdev->source.subsys.u.scsi.unit,
                                      hostdev->readonly,
                                      hostdev->shareable)))
            goto cleanup;

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

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

    for (i = 0; i < count; i++) {
        virSCSIDevicePtr scsi = virSCSIDeviceListGet(list, i);
1265
        if ((tmp = virSCSIDeviceListFind(hostdev_mgr->activeSCSIHostdevs,
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
                                         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;
            }

1279
            if (virSCSIDeviceSetUsedBy(tmp, drv_name, dom_name) < 0)
1280 1281
                goto error;
        } else {
1282
            if (virSCSIDeviceSetUsedBy(scsi, drv_name, dom_name) < 0)
1283 1284
                goto error;

1285
            VIR_DEBUG("Adding %s to activeSCSIHostdevs", virSCSIDeviceGetName(scsi));
1286

1287
            if (virSCSIDeviceListAdd(hostdev_mgr->activeSCSIHostdevs, scsi) < 0)
1288 1289 1290 1291
                goto error;
        }
    }

1292
    virObjectUnlock(hostdev_mgr->activeSCSIHostdevs);
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305

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

1306
 error:
1307 1308
    for (j = 0; j < i; j++) {
        tmp = virSCSIDeviceListGet(list, i);
1309
        virSCSIDeviceListSteal(hostdev_mgr->activeSCSIHostdevs, tmp);
1310
    }
1311
    virObjectUnlock(hostdev_mgr->activeSCSIHostdevs);
1312
 cleanup:
1313 1314 1315
    virObjectUnref(list);
    return -1;
}
1316 1317

void
1318 1319 1320 1321 1322
virHostdevReAttachUSBDevices(virHostdevManagerPtr hostdev_mgr,
                             const char *drv_name,
                             const char *dom_name,
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs)
1323 1324 1325
{
    size_t i;

1326 1327 1328
    if (!nhostdevs)
        return;

1329
    virObjectLock(hostdev_mgr->activeUSBHostdevs);
1330 1331
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
1332
        virDomainHostdevSubsysUSBPtr usbsrc = &hostdev->source.subsys.u.usb;
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
        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;

1344
        if (!(usb = virUSBDeviceNew(usbsrc->bus, usbsrc->device, NULL))) {
1345
            VIR_WARN("Unable to reattach USB device %03d.%03d on domain %s",
1346
                     usbsrc->bus, usbsrc->device, dom_name);
1347 1348 1349 1350 1351 1352 1353 1354 1355
            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 */

1356
        tmp = virUSBDeviceListFind(hostdev_mgr->activeUSBHostdevs, usb);
1357 1358 1359 1360 1361
        virUSBDeviceFree(usb);

        if (!tmp) {
            VIR_WARN("Unable to find device %03d.%03d "
                     "in list of active USB devices",
1362
                     usbsrc->bus, usbsrc->device);
1363 1364 1365 1366 1367
            continue;
        }

        virUSBDeviceGetUsedBy(tmp, &usedby_drvname, &usedby_domname);
        if (STREQ_NULLABLE(drv_name, usedby_drvname) &&
1368
            STREQ_NULLABLE(dom_name, usedby_domname)) {
1369
            VIR_DEBUG("Removing %03d.%03d dom=%s from activeUSBHostdevs",
1370
                      usbsrc->bus, usbsrc->device, dom_name);
1371
            virUSBDeviceListDel(hostdev_mgr->activeUSBHostdevs, tmp);
1372 1373
        }
    }
1374
    virObjectUnlock(hostdev_mgr->activeUSBHostdevs);
1375
}
1376 1377

void
1378 1379 1380 1381 1382
virHostdevReAttachSCSIDevices(virHostdevManagerPtr hostdev_mgr,
                              const char *drv_name,
                              const char *dom_name,
                              virDomainHostdevDefPtr *hostdevs,
                              int nhostdevs)
1383 1384 1385
{
    size_t i;

1386 1387 1388
    if (!nhostdevs)
        return;

1389
    virObjectLock(hostdev_mgr->activeSCSIHostdevs);
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
        virSCSIDevicePtr scsi;
        virSCSIDevicePtr tmp;

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

        if (!(scsi = virSCSIDeviceNew(NULL,
                                      hostdev->source.subsys.u.scsi.adapter,
                                      hostdev->source.subsys.u.scsi.bus,
                                      hostdev->source.subsys.u.scsi.target,
                                      hostdev->source.subsys.u.scsi.unit,
                                      hostdev->readonly,
                                      hostdev->shareable))) {
            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,
1411
                     dom_name);
1412 1413 1414 1415 1416 1417
            continue;
        }

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

1418
        if (!(tmp = virSCSIDeviceListFind(hostdev_mgr->activeSCSIHostdevs, scsi))) {
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
            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);
            virSCSIDeviceFree(scsi);
            continue;
        }

1429
        VIR_DEBUG("Removing %s:%d:%d:%d dom=%s from activeSCSIHostdevs",
1430 1431 1432 1433
                   hostdev->source.subsys.u.scsi.adapter,
                   hostdev->source.subsys.u.scsi.bus,
                   hostdev->source.subsys.u.scsi.target,
                   hostdev->source.subsys.u.scsi.unit,
1434
                   dom_name);
1435

1436
        virSCSIDeviceListDel(hostdev_mgr->activeSCSIHostdevs, tmp,
1437
                             drv_name, dom_name);
1438 1439
        virSCSIDeviceFree(scsi);
    }
1440
    virObjectUnlock(hostdev_mgr->activeSCSIHostdevs);
1441
}
1442 1443

int
1444
virHostdevPCINodeDeviceDetach(virHostdevManagerPtr hostdev_mgr,
1445 1446 1447 1448
                              virPCIDevicePtr pci)
{
    int ret = -1;

1449 1450
    virObjectLock(hostdev_mgr->activePCIHostdevs);
    virObjectLock(hostdev_mgr->inactivePCIHostdevs);
1451

1452 1453
    if (virPCIDeviceDetach(pci, hostdev_mgr->activePCIHostdevs,
                           hostdev_mgr->inactivePCIHostdevs) < 0) {
1454 1455 1456 1457
        goto out;
    }

    ret = 0;
1458
 out:
1459 1460
    virObjectUnlock(hostdev_mgr->inactivePCIHostdevs);
    virObjectUnlock(hostdev_mgr->activePCIHostdevs);
1461 1462 1463 1464
    return ret;
}

int
1465
virHostdevPCINodeDeviceReAttach(virHostdevManagerPtr hostdev_mgr,
1466 1467 1468 1469 1470
                                virPCIDevicePtr pci)
{
    virPCIDevicePtr other;
    int ret = -1;

1471 1472 1473
    virObjectLock(hostdev_mgr->activePCIHostdevs);
    virObjectLock(hostdev_mgr->inactivePCIHostdevs);
    other = virPCIDeviceListFind(hostdev_mgr->activePCIHostdevs, pci);
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
    if (other) {
        const char *other_drvname = NULL;
        const char *other_domname = NULL;
        virPCIDeviceGetUsedBy(other, &other_drvname, &other_domname);

        if (other_drvname && other_domname)
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is still in use by "
                             "driver %s, domain %s"),
                           virPCIDeviceGetName(pci),
                           other_drvname, other_domname);
        else
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is still in use"),
                           virPCIDeviceGetName(pci));
        goto out;
    }

    virPCIDeviceReattachInit(pci);

1494 1495
    if (virPCIDeviceReattach(pci, hostdev_mgr->activePCIHostdevs,
                             hostdev_mgr->inactivePCIHostdevs) < 0)
1496 1497 1498
        goto out;

    ret = 0;
1499
 out:
1500 1501
    virObjectUnlock(hostdev_mgr->inactivePCIHostdevs);
    virObjectUnlock(hostdev_mgr->activePCIHostdevs);
1502 1503 1504 1505
    return ret;
}

int
1506
virHostdevPCINodeDeviceReset(virHostdevManagerPtr hostdev_mgr,
1507 1508 1509 1510
                             virPCIDevicePtr pci)
{
    int ret = -1;

1511 1512 1513 1514
    virObjectLock(hostdev_mgr->activePCIHostdevs);
    virObjectLock(hostdev_mgr->inactivePCIHostdevs);
    if (virPCIDeviceReset(pci, hostdev_mgr->activePCIHostdevs,
                          hostdev_mgr->inactivePCIHostdevs) < 0)
1515 1516 1517
        goto out;

    ret = 0;
1518
 out:
1519 1520
    virObjectUnlock(hostdev_mgr->inactivePCIHostdevs);
    virObjectUnlock(hostdev_mgr->activePCIHostdevs);
1521 1522
    return ret;
}
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561

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
1562
 * For upgrade purpose: see virHostdevReAttachPCIHostdevs
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
 */
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
virHostdevUpdateDomainActiveDevices(virHostdevManagerPtr mgr,
                                    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;
}