virhostdev.c 60.0 KB
Newer Older
1 2
/* virhostdev.c: hostdev management
 *
3
 * Copyright (C) 2006-2007, 2009-2016 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
struct virHostdevIsPCINodeDeviceUsedData {
58
    virHostdevManagerPtr mgr;
59
    const char *domainName;
60
    const bool usesVFIO;
61 62
};

A
Andrea Bolognani 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
/* This module makes heavy use of bookkeeping lists contained inside a
 * virHostdevManager instance to keep track of the devices' status. To make
 * it easy to spot potential ownership errors when moving devices from one
 * list to the other, variable names should comply with the following
 * conventions when it comes to virPCIDevice and virPCIDeviceList instances:
 *
 *   pci - a short-lived virPCIDevice whose purpose is usually just to look
 *         up the actual PCI device in one of the bookkeeping lists; basically
 *         little more than a fancy virPCIDeviceAddress
 *
 *   pcidevs - a list containing a bunch of the above
 *
 *   actual - a virPCIDevice instance that has either been retrieved from one
 *            of the bookkeeping lists, or is intended to be added or copied
 *            to one at some point
 *
 * Passing an 'actual' to a function that requires a 'pci' is fine, but the
 * opposite is usually not true; as a rule of thumb, functions in the virpci
 * module usually expect an 'actual'. Even with these conventions in place,
 * adding comments to highlight ownership-related issues is recommended */

84 85
static int virHostdevIsPCINodeDeviceUsed(virPCIDeviceAddressPtr devAddr, void *opaque)
{
86
    virPCIDevicePtr actual;
87
    int ret = -1;
88
    struct virHostdevIsPCINodeDeviceUsedData *helperData = opaque;
89

90 91 92 93 94 95 96
    actual = virPCIDeviceListFindByIDs(helperData->mgr->activePCIHostdevs,
                                       devAddr->domain, devAddr->bus,
                                       devAddr->slot, devAddr->function);
    if (actual) {
        const char *actual_drvname = NULL;
        const char *actual_domname = NULL;
        virPCIDeviceGetUsedBy(actual, &actual_drvname, &actual_domname);
97

98
        if (helperData->usesVFIO &&
99 100
            (actual_domname && helperData->domainName) &&
            (STREQ(actual_domname, helperData->domainName)))
101 102
            goto iommu_owner;

103
        if (actual_drvname && actual_domname)
104 105 106
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is in use by "
                             "driver %s, domain %s"),
107 108
                           virPCIDeviceGetName(actual),
                           actual_drvname, actual_domname);
109 110 111
        else
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is in use"),
112
                           virPCIDeviceGetName(actual));
113 114
        goto cleanup;
    }
115
 iommu_owner:
116 117 118 119 120
    ret = 0;
 cleanup:
    return ret;
}

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
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)
136 137

static void
138
virHostdevManagerDispose(void *obj)
139
{
140 141
    virHostdevManagerPtr hostdevMgr = obj;

142 143 144
    if (!hostdevMgr)
        return;

145 146 147 148
    virObjectUnref(hostdevMgr->activePCIHostdevs);
    virObjectUnref(hostdevMgr->inactivePCIHostdevs);
    virObjectUnref(hostdevMgr->activeUSBHostdevs);
    virObjectUnref(hostdevMgr->activeSCSIHostdevs);
149 150 151
    VIR_FREE(hostdevMgr->stateDir);
}

152 153
static virHostdevManagerPtr
virHostdevManagerNew(void)
154
{
155
    virHostdevManagerPtr hostdevMgr;
156
    bool privileged = geteuid() == 0;
157 158 159

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

161
    if (!(hostdevMgr->activePCIHostdevs = virPCIDeviceListNew()))
162 163
        goto error;

164
    if (!(hostdevMgr->activeUSBHostdevs = virUSBDeviceListNew()))
165 166
        goto error;

167
    if (!(hostdevMgr->inactivePCIHostdevs = virPCIDeviceListNew()))
168 169
        goto error;

170
    if (!(hostdevMgr->activeSCSIHostdevs = virSCSIDeviceListNew()))
171 172
        goto error;

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    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);
206 207
    }

208
    return hostdevMgr;
209

210
 error:
211 212
    virObjectUnref(hostdevMgr);
    return NULL;
213 214 215 216 217
}

virHostdevManagerPtr
virHostdevManagerGetDefault(void)
{
218
    if (virHostdevManagerInitialize() < 0)
219
        return NULL;
220 221

    return virObjectRef(manager);
222
}
223 224

static virPCIDeviceListPtr
225
virHostdevGetPCIHostDeviceList(virDomainHostdevDefPtr *hostdevs, int nhostdevs)
226
{
227
    virPCIDeviceListPtr pcidevs;
228 229
    size_t i;

230
    if (!(pcidevs = virPCIDeviceListNew()))
231 232 233 234
        return NULL;

    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
235
        virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;
236
        virPCIDevicePtr pci;
237 238 239 240 241 242

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

243
        pci = virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
244
                              pcisrc->addr.slot, pcisrc->addr.function);
245 246
        if (!pci) {
            virObjectUnref(pcidevs);
247 248
            return NULL;
        }
249 250 251
        if (virPCIDeviceListAdd(pcidevs, pci) < 0) {
            virPCIDeviceFree(pci);
            virObjectUnref(pcidevs);
252 253 254
            return NULL;
        }

255
        virPCIDeviceSetManaged(pci, hostdev->managed);
256 257

        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO)
258
            virPCIDeviceSetStubDriver(pci, VIR_PCI_STUB_DRIVER_VFIO);
259
        else if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN)
260
            virPCIDeviceSetStubDriver(pci, VIR_PCI_STUB_DRIVER_XEN);
261
        else
262
            virPCIDeviceSetStubDriver(pci, VIR_PCI_STUB_DRIVER_KVM);
263 264
    }

265
    return pcidevs;
266 267 268 269
}


static int
270
virHostdevPCISysfsPath(virDomainHostdevDefPtr hostdev,
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
                       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;

290
    if (virHostdevPCISysfsPath(hostdev, &sysfs_path) < 0)
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
        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;

308
    if (virHostdevPCISysfsPath(hostdev, &sysfs_path) < 0)
309 310 311 312 313 314 315 316 317 318 319 320 321 322
        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;

323
 cleanup:
324 325 326 327 328 329
    VIR_FREE(sysfs_path);

    return ret;
}


330
static bool
331 332 333 334 335 336 337 338 339
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;
}


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 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
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,
383
                           const char *stateDir)
384 385 386 387 388 389 390 391
{
    char *linkdev = NULL;
    virNetDevVlanPtr vlan;
    virNetDevVPortProfilePtr virtPort;
    int ret = -1;
    int vf = -1;
    bool port_profile_associate = true;

392
    if (virHostdevIsVirtualFunction(hostdev) != 1) {
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
        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 */
        ret = virNetDevReplaceNetConfig(linkdev, vf,
                                        &hostdev->parent.data.net->mac,
420
                                        vlan, stateDir);
421
    }
422
 cleanup:
423 424 425 426 427 428 429 430
    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
431
 * location (mgr->stateDir) but certainly will not find it. In this
432 433 434 435
 * case, try to find in the old state dir.
 */
static int
virHostdevNetConfigRestore(virDomainHostdevDefPtr hostdev,
436 437
                           const char *stateDir,
                           const char *oldStateDir)
438 439 440 441 442 443 444 445 446 447
{
    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.
     */
448
    if (!virHostdevIsPCINetDevice(hostdev))
449 450
       return 0;

451
    if (virHostdevIsVirtualFunction(hostdev) != 1) {
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
        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
480
virHostdevPreparePCIDevices(virHostdevManagerPtr mgr,
481
                            const char *drv_name,
482
                            const char *dom_name,
483 484 485 486 487 488 489 490 491
                            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;
492
    virPCIDeviceAddressPtr devAddr = NULL;
493

494 495 496
    if (!nhostdevs)
        return 0;

497 498
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
499

500
    if (!(pcidevs = virHostdevGetPCIHostDeviceList(hostdevs, nhostdevs)))
501 502
        goto cleanup;

503 504 505 506 507 508 509 510
    /* 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 */

511
    /* Step 1: Perform some initial checks on the devices */
512
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
513
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
514
        bool strict_acs_check = !!(flags & VIR_HOSTDEV_STRICT_ACS_CHECK);
515
        bool usesVFIO = (virPCIDeviceGetStubDriver(pci) == VIR_PCI_STUB_DRIVER_VFIO);
516
        struct virHostdevIsPCINodeDeviceUsedData data = { mgr, dom_name, usesVFIO };
517

518
        if (!usesVFIO && !virPCIDeviceIsAssignable(pci, strict_acs_check)) {
519 520
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is not assignable"),
521
                           virPCIDeviceGetName(pci));
522 523
            goto cleanup;
        }
524

525
        /* The device is in use by other active domain if
526
         * the dev is in list activePCIHostdevs. VFIO devices
M
Martin Kletzander 已提交
527
         * belonging to same iommu group can't be shared
528
         * across guests.
529
         */
530
        devAddr = virPCIDeviceGetAddress(pci);
531
        if (usesVFIO) {
532 533
            if (virPCIDeviceAddressIOMMUGroupIterate(devAddr,
                                                     virHostdevIsPCINodeDeviceUsed,
534
                                                     &data) < 0)
535
                goto cleanup;
536
        } else if (virHostdevIsPCINodeDeviceUsed(devAddr, &data)) {
537 538 539 540
            goto cleanup;
        }
    }

541 542
    /* Step 2: detach managed devices and make sure unmanaged devices
     *         have already been taken care of */
543
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
544
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
545

546
        if (virPCIDeviceGetManaged(pci)) {
A
Andrea Bolognani 已提交
547 548 549 550 551

            /* We can't look up the actual device because it has not been
             * created yet: virPCIDeviceDetach() will insert a copy of 'pci'
             * into the list of inactive devices, and that copy will be the
             * actual device going forward */
552
            VIR_DEBUG("Detaching managed PCI device %s",
553 554
                      virPCIDeviceGetName(pci));
            if (virPCIDeviceDetach(pci,
555 556
                                   mgr->activePCIHostdevs,
                                   mgr->inactivePCIHostdevs) < 0)
557
                goto reattachdevs;
558
        } else {
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
            char *driverPath;
            char *driverName;
            int stub;

            /* Unmanaged devices should already have been marked as
             * inactive: if that's the case, we can simply move on */
            if (virPCIDeviceListFind(mgr->inactivePCIHostdevs, pci)) {
                VIR_DEBUG("Not detaching unmanaged PCI device %s",
                          virPCIDeviceGetName(pci));
                continue;
            }

            /* If that's not the case, though, it might be because the
             * daemon has been restarted, causing us to lose track of the
             * device. Try and recover by marking the device as inactive
             * if it happens to be bound to a known stub driver.
             *
             * FIXME Get rid of this once a proper way to keep track of
             *       information about active / inactive device across
             *       daemon restarts has been implemented */

            if (virPCIDeviceGetDriverPathAndName(pci,
                                                 &driverPath, &driverName) < 0)
                goto reattachdevs;

            stub = virPCIStubDriverTypeFromString(driverName);

            VIR_FREE(driverPath);
            VIR_FREE(driverName);

            if (stub > VIR_PCI_STUB_DRIVER_NONE &&
                stub < VIR_PCI_STUB_DRIVER_LAST) {

                /* The device is bound to a known stub driver: store this
                 * information and add a copy to the inactive list */
                virPCIDeviceSetStubDriver(pci, stub);

                VIR_DEBUG("Adding PCI device %s to inactive list",
                          virPCIDeviceGetName(pci));
                if (virPCIDeviceListAddCopy(mgr->inactivePCIHostdevs, pci) < 0)
                    goto reattachdevs;
600 601 602 603 604 605
            } else {
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("Unmanaged PCI device %s must be manually "
                               "detached from the host"),
                               virPCIDeviceGetName(pci));
                goto reattachdevs;
606
            }
607
        }
608 609
    }

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

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

A
Andrea Bolognani 已提交
618 619 620
        /* We can avoid looking up the actual device here, because performing
         * a PCI reset on a device doesn't require any information other than
         * the address, which 'pci' already contains */
621 622
        VIR_DEBUG("Resetting PCI device %s", virPCIDeviceGetName(pci));
        if (virPCIDeviceReset(pci, mgr->activePCIHostdevs,
623
                              mgr->inactivePCIHostdevs) < 0)
624 625 626
            goto reattachdevs;
    }

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

640
    /* Step 5: Move devices from the inactive list to the active list */
641
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
642
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
643
        virPCIDevicePtr actual;
644

645
        VIR_DEBUG("Removing PCI device %s from inactive list",
646
                  virPCIDeviceGetName(pci));
647
        actual = virPCIDeviceListSteal(mgr->inactivePCIHostdevs, pci);
648

649
        VIR_DEBUG("Adding PCI device %s to active list",
650
                  virPCIDeviceGetName(pci));
651 652
        if (!actual || virPCIDeviceListAdd(mgr->activePCIHostdevs, actual) < 0)
            goto inactivedevs;
653 654
    }

655
    /* Step 6: Set driver and domain information */
656
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
657
        virPCIDevicePtr pci, actual;
658

A
Andrea Bolognani 已提交
659 660 661
        /* We need to look up the actual device and set the information
         * there because 'pci' only contain address information and will
         * be released at the end of the function */
662 663
        pci = virPCIDeviceListGet(pcidevs, i);
        actual = virPCIDeviceListFind(mgr->activePCIHostdevs, pci);
664

665
        VIR_DEBUG("Setting driver and domain information for PCI device %s",
666 667 668
                  virPCIDeviceGetName(pci));
        if (actual)
            virPCIDeviceSetUsedBy(actual, drv_name, dom_name);
669 670
    }

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

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

682 683 684 685 686 687 688 689
        /* We need to look up the actual device because it's the one
         * that contains the information we care about (unbind_from_stub,
         * remove_slot, reprobe) */
        actual = virPCIDeviceListFindByIDs(mgr->activePCIHostdevs,
                                           pcisrc->addr.domain,
                                           pcisrc->addr.bus,
                                           pcisrc->addr.slot,
                                           pcisrc->addr.function);
690

691 692 693
        /* Appropriate values for the unbind_from_stub, remove_slot
         * and reprobe properties of the device were set earlier
         * by virPCIDeviceDetach() */
694
        if (actual) {
695
            VIR_DEBUG("Saving network configuration of PCI device %s",
696
                      virPCIDeviceGetName(actual));
697
            hostdev->origstates.states.pci.unbind_from_stub =
698
                virPCIDeviceGetUnbindFromStub(actual);
699
            hostdev->origstates.states.pci.remove_slot =
700
                virPCIDeviceGetRemoveSlot(actual);
701
            hostdev->origstates.states.pci.reprobe =
702
                virPCIDeviceGetReprobe(actual);
703 704 705 706 707 708
        }
    }

    ret = 0;
    goto cleanup;

709
 inactivedevs:
710 711
    /* Move devices back to the inactive list so that they can be
     * processed properly below (reattachdevs label) */
712
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
713
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
714
        virPCIDevicePtr actual;
715 716

        VIR_DEBUG("Removing PCI device %s from active list",
717
                  virPCIDeviceGetName(pci));
718 719 720 721 722 723 724 725
        if (!(actual = virPCIDeviceListSteal(mgr->activePCIHostdevs, pci)))
            continue;

        VIR_DEBUG("Adding PCI device %s to inactive list",
                  virPCIDeviceGetName(pci));
        if (virPCIDeviceListAdd(mgr->inactivePCIHostdevs, actual) < 0)
            VIR_WARN("Failed to add PCI device %s to the inactive list",
                     virPCIDeviceGetName(pci));
726 727
    }

728
 resetvfnetconfig:
729 730
    if (last_processed_hostdev_vf >= 0) {
        for (i = 0; i <= last_processed_hostdev_vf; i++)
731
            virHostdevNetConfigRestore(hostdevs[i], mgr->stateDir, NULL);
732
    }
733

734
 reattachdevs:
735
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
736
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
737
        virPCIDevicePtr actual;
738

739 740 741 742 743 744
        /* We need to look up the actual device because that's what
         * virPCIDeviceReattach() exepects as its argument */
        if (!(actual = virPCIDeviceListFind(mgr->inactivePCIHostdevs, pci)))
            continue;

        if (virPCIDeviceGetManaged(actual)) {
745
            VIR_DEBUG("Reattaching managed PCI device %s",
746
                      virPCIDeviceGetName(pci));
747
            ignore_value(virPCIDeviceReattach(actual,
748 749
                                              mgr->activePCIHostdevs,
                                              mgr->inactivePCIHostdevs));
750 751
        } else {
            VIR_DEBUG("Not reattaching unmanaged PCI device %s",
752
                      virPCIDeviceGetName(pci));
753
        }
754 755
    }

756
 cleanup:
757
    virObjectUnref(pcidevs);
758 759
    virObjectUnlock(mgr->activePCIHostdevs);
    virObjectUnlock(mgr->inactivePCIHostdevs);
760

761 762 763 764
    return ret;
}

/*
765
 * Pre-condition: inactivePCIHostdevs & activePCIHostdevs
766 767 768
 * are locked
 */
static void
769
virHostdevReattachPCIDevice(virHostdevManagerPtr mgr,
770
                            virPCIDevicePtr actual)
771 772
{
    /* Wait for device cleanup if it is qemu/kvm */
773
    if (virPCIDeviceGetStubDriver(actual) == VIR_PCI_STUB_DRIVER_KVM) {
774
        int retries = 100;
775
        while (virPCIDeviceWaitForCleanup(actual, "kvm_assigned_device")
776 777 778 779 780 781
               && retries) {
            usleep(100*1000);
            retries--;
        }
    }

782 783
    VIR_DEBUG("Reattaching PCI device %s", virPCIDeviceGetName(actual));
    if (virPCIDeviceReattach(actual, mgr->activePCIHostdevs,
784
                             mgr->inactivePCIHostdevs) < 0) {
785
        VIR_ERROR(_("Failed to re-attach PCI device: %s"),
786 787
                  virGetLastErrorMessage());
        virResetLastError();
788 789 790 791 792 793 794
    }
}

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

805 806 807
    if (!nhostdevs)
        return;

808 809
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
810

811
    if (!(pcidevs = virHostdevGetPCIHostDeviceList(hostdevs, nhostdevs))) {
812
        VIR_ERROR(_("Failed to allocate PCI device list: %s"),
813 814
                  virGetLastErrorMessage());
        virResetLastError();
815 816 817
        goto cleanup;
    }

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

821 822
    /* Step 1: Filter out all devices that are either not active or not
     *         used by the current domain and driver */
823 824
    i = 0;
    while (i < virPCIDeviceListCount(pcidevs)) {
825 826 827
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
        virPCIDevicePtr actual = NULL;

A
Andrea Bolognani 已提交
828 829 830 831
        /* We need to look up the actual device, which is the one containing
         * information such as by which domain and driver it is used. As a
         * side effect, by looking it up we can also tell whether it was
         * really active in the first place */
832 833 834 835 836 837 838 839 840
        actual = virPCIDeviceListFind(mgr->activePCIHostdevs, pci);
        if (actual) {
            const char *actual_drvname;
            const char *actual_domname;
            virPCIDeviceGetUsedBy(actual, &actual_drvname, &actual_domname);
            if (STRNEQ_NULLABLE(drv_name, actual_drvname) ||
                STRNEQ_NULLABLE(dom_name, actual_domname)) {

                virPCIDeviceListDel(pcidevs, pci);
A
Andrea Bolognani 已提交
841 842
                continue;
            }
843
        } else {
844
            virPCIDeviceListDel(pcidevs, pci);
845
            continue;
846 847
        }

848 849 850 851 852 853 854 855
        i++;
    }

    /* Step 2: Move devices from the active list to the inactive list */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
        virPCIDevicePtr actual;

856
        VIR_DEBUG("Removing PCI device %s from active list",
857
                  virPCIDeviceGetName(pci));
858 859 860 861 862 863 864 865
        actual = virPCIDeviceListSteal(mgr->activePCIHostdevs, pci);

        VIR_DEBUG("Adding PCI device %s to inactive list",
                  virPCIDeviceGetName(pci));
        if (!actual ||
            virPCIDeviceListAdd(mgr->inactivePCIHostdevs, actual) < 0) {

            VIR_ERROR(_("Failed to add PCI device %s to the inactive list"),
866 867
                      virGetLastErrorMessage());
            virResetLastError();
868
        }
869 870
    }

871 872
    /* At this point, any device that had been used by the guest has been
     * moved to the inactive list */
873

874
    /* Step 3: restore original network config of hostdevs that used
875
     * <interface type='hostdev'>
876
     */
877 878 879 880 881
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];

        if (virHostdevIsPCINetDevice(hostdev)) {
            virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;
882
            virPCIDevicePtr actual;
883

884 885 886 887 888
            actual = virPCIDeviceListFindByIDs(mgr->inactivePCIHostdevs,
                                               pcisrc->addr.domain,
                                               pcisrc->addr.bus,
                                               pcisrc->addr.slot,
                                               pcisrc->addr.function);
889

890
            if (actual) {
891
                VIR_DEBUG("Restoring network configuration of PCI device %s",
892
                          virPCIDeviceGetName(actual));
893
                virHostdevNetConfigRestore(hostdev, mgr->stateDir,
894
                                           oldStateDir);
895 896 897
            }
        }
    }
898

899
    /* Step 4: perform a PCI Reset on all devices */
900
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
901
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
902

A
Andrea Bolognani 已提交
903 904 905
        /* We can avoid looking up the actual device here, because performing
         * a PCI reset on a device doesn't require any information other than
         * the address, which 'pci' already contains */
906 907
        VIR_DEBUG("Resetting PCI device %s", virPCIDeviceGetName(pci));
        if (virPCIDeviceReset(pci, mgr->activePCIHostdevs,
908
                              mgr->inactivePCIHostdevs) < 0) {
909
            VIR_ERROR(_("Failed to reset PCI device: %s"),
910 911
                      virGetLastErrorMessage());
            virResetLastError();
912 913 914
        }
    }

915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
    /* Step 5: Reattach managed devices to their host drivers; unmanaged
     *         devices don't need to be processed further */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
        virPCIDevicePtr actual;

        /* We need to look up the actual device because that's what
         * virHostdevReattachPCIDevice() expects as its argument */
        if (!(actual = virPCIDeviceListFind(mgr->inactivePCIHostdevs, pci)))
            continue;

        if (virPCIDeviceGetManaged(actual))
            virHostdevReattachPCIDevice(mgr, actual);
        else
            VIR_DEBUG("Not reattaching unmanaged PCI device %s",
                      virPCIDeviceGetName(actual));
931 932
    }

933
 cleanup:
934
    virObjectUnref(pcidevs);
935 936
    virObjectUnlock(mgr->activePCIHostdevs);
    virObjectUnlock(mgr->inactivePCIHostdevs);
937
}
938 939

int
940
virHostdevUpdateActivePCIDevices(virHostdevManagerPtr mgr,
941 942
                                 virDomainHostdevDefPtr *hostdevs,
                                 int nhostdevs,
943
                                 const char *drv_name,
944
                                 const char *dom_name)
945 946
{
    virDomainHostdevDefPtr hostdev = NULL;
947
    virPCIDevicePtr actual = NULL;
948 949 950
    size_t i;
    int ret = -1;

951 952 953
    if (!nhostdevs)
        return 0;

954 955
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
956

957
    for (i = 0; i < nhostdevs; i++) {
958
        virDomainHostdevSubsysPCIPtr pcisrc;
959
        hostdev = hostdevs[i];
960
        pcisrc = &hostdev->source.subsys.u.pci;
961 962 963 964 965 966

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

967 968
        actual = virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                                 pcisrc->addr.slot, pcisrc->addr.function);
969

970
        if (!actual)
971 972
            goto cleanup;

973 974
        virPCIDeviceSetManaged(actual, hostdev->managed);
        virPCIDeviceSetUsedBy(actual, drv_name, dom_name);
975

976
        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO)
977
            virPCIDeviceSetStubDriver(actual, VIR_PCI_STUB_DRIVER_VFIO);
978
        else if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN)
979
            virPCIDeviceSetStubDriver(actual, VIR_PCI_STUB_DRIVER_XEN);
980
        else
981
            virPCIDeviceSetStubDriver(actual, VIR_PCI_STUB_DRIVER_KVM);
982

983
        /* Setup the original states for the PCI device */
984 985 986
        virPCIDeviceSetUnbindFromStub(actual, hostdev->origstates.states.pci.unbind_from_stub);
        virPCIDeviceSetRemoveSlot(actual, hostdev->origstates.states.pci.remove_slot);
        virPCIDeviceSetReprobe(actual, hostdev->origstates.states.pci.reprobe);
987

988
        if (virPCIDeviceListAdd(mgr->activePCIHostdevs, actual) < 0)
989
            goto cleanup;
990
        actual = NULL;
991 992 993
    }

    ret = 0;
994
 cleanup:
995
    virPCIDeviceFree(actual);
996 997
    virObjectUnlock(mgr->activePCIHostdevs);
    virObjectUnlock(mgr->inactivePCIHostdevs);
998 999 1000 1001
    return ret;
}

int
1002
virHostdevUpdateActiveUSBDevices(virHostdevManagerPtr mgr,
1003 1004
                                 virDomainHostdevDefPtr *hostdevs,
                                 int nhostdevs,
1005
                                 const char *drv_name,
1006
                                 const char *dom_name)
1007 1008 1009 1010 1011
{
    virDomainHostdevDefPtr hostdev = NULL;
    size_t i;
    int ret = -1;

1012 1013 1014
    if (!nhostdevs)
        return 0;

1015
    virObjectLock(mgr->activeUSBHostdevs);
1016
    for (i = 0; i < nhostdevs; i++) {
1017
        virDomainHostdevSubsysUSBPtr usbsrc;
1018
        virUSBDevicePtr usb = NULL;
1019
        hostdev = hostdevs[i];
1020
        usbsrc = &hostdev->source.subsys.u.usb;
1021 1022 1023 1024 1025 1026

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

1027
        if (!(usb = virUSBDeviceNew(usbsrc->bus, usbsrc->device, NULL))) {
1028
            VIR_WARN("Unable to reattach USB device %03d.%03d on domain %s",
1029
                     usbsrc->bus, usbsrc->device, dom_name);
1030 1031 1032
            continue;
        }

1033
        virUSBDeviceSetUsedBy(usb, drv_name, dom_name);
1034

1035
        if (virUSBDeviceListAdd(mgr->activeUSBHostdevs, usb) < 0) {
1036 1037 1038 1039 1040
            virUSBDeviceFree(usb);
            goto cleanup;
        }
    }
    ret = 0;
1041
 cleanup:
1042
    virObjectUnlock(mgr->activeUSBHostdevs);
1043 1044 1045
    return ret;
}

1046 1047 1048 1049 1050 1051 1052 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
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;
}

1083
int
1084
virHostdevUpdateActiveSCSIDevices(virHostdevManagerPtr mgr,
1085 1086
                                  virDomainHostdevDefPtr *hostdevs,
                                  int nhostdevs,
1087
                                  const char *drv_name,
1088
                                  const char *dom_name)
1089 1090 1091 1092 1093
{
    virDomainHostdevDefPtr hostdev = NULL;
    size_t i;
    int ret = -1;

1094 1095 1096
    if (!nhostdevs)
        return 0;

1097
    virObjectLock(mgr->activeSCSIHostdevs);
1098
    for (i = 0; i < nhostdevs; i++) {
1099
        virDomainHostdevSubsysSCSIPtr scsisrc;
1100
        hostdev = hostdevs[i];
1101
        scsisrc = &hostdev->source.subsys.u.scsi;
1102 1103 1104 1105 1106

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

1107 1108
        if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
            continue;  /* Not supported for iSCSI */
1109
        } else {
1110 1111
            if (virHostdevUpdateActiveSCSIHostDevices(mgr, hostdev, scsisrc,
                                                      drv_name, dom_name) < 0)
1112 1113 1114 1115 1116
                goto cleanup;
        }
    }
    ret = 0;

1117
 cleanup:
1118
    virObjectUnlock(mgr->activeSCSIHostdevs);
1119 1120
    return ret;
}
1121 1122

static int
1123 1124 1125 1126
virHostdevMarkUSBDevices(virHostdevManagerPtr mgr,
                         const char *drv_name,
                         const char *dom_name,
                         virUSBDeviceListPtr list)
1127 1128 1129 1130 1131
{
    size_t i, j;
    unsigned int count;
    virUSBDevicePtr tmp;

1132
    virObjectLock(mgr->activeUSBHostdevs);
1133 1134 1135 1136
    count = virUSBDeviceListCount(list);

    for (i = 0; i < count; i++) {
        virUSBDevicePtr usb = virUSBDeviceListGet(list, i);
1137
        if ((tmp = virUSBDeviceListFind(mgr->activeUSBHostdevs, usb))) {
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
            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;
        }

1155
        virUSBDeviceSetUsedBy(usb, drv_name, dom_name);
1156
        VIR_DEBUG("Adding %03d.%03d dom=%s to activeUSBHostdevs",
1157 1158
                  virUSBDeviceGetBus(usb), virUSBDeviceGetDevno(usb),
                  dom_name);
1159 1160 1161 1162 1163
        /*
         * The caller is responsible to steal these usb devices
         * from the virUSBDeviceList that passed in on success,
         * perform rollback on failure.
         */
1164
        if (virUSBDeviceListAdd(mgr->activeUSBHostdevs, usb) < 0)
1165 1166 1167
            goto error;
    }

1168
    virObjectUnlock(mgr->activeUSBHostdevs);
1169 1170
    return 0;

1171
 error:
1172 1173
    for (j = 0; j < i; j++) {
        tmp = virUSBDeviceListGet(list, i);
1174
        virUSBDeviceListSteal(mgr->activeUSBHostdevs, tmp);
1175
    }
1176
    virObjectUnlock(mgr->activeUSBHostdevs);
1177 1178 1179 1180 1181 1182 1183 1184 1185
    return -1;
}


static int
virHostdevFindUSBDevice(virDomainHostdevDefPtr hostdev,
                        bool mandatory,
                        virUSBDevicePtr *usb)
{
1186 1187 1188 1189 1190 1191
    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;
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
    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;
        }

1246 1247 1248
        usbsrc->bus = virUSBDeviceGetBus(*usb);
        usbsrc->device = virUSBDeviceGetDevno(*usb);
        usbsrc->autoAddress = true;
1249 1250 1251 1252 1253

        if (autoAddress) {
            VIR_INFO("USB device %x:%x found at bus:%u device:%u (moved"
                     " from bus:%u device:%u)",
                     vendor, product,
1254
                     usbsrc->bus, usbsrc->device,
1255 1256 1257 1258 1259 1260 1261
                     bus, device);
        }
    } else if (!vendor && bus) {
        if (virUSBDeviceFindByBus(bus, device, NULL, mandatory, usb) < 0)
            return -1;
    }

1262
 out:
1263 1264 1265 1266 1267 1268
    if (!*usb)
        hostdev->missing = true;
    return 0;
}

int
1269
virHostdevPrepareUSBDevices(virHostdevManagerPtr mgr,
1270
                            const char *drv_name,
1271
                            const char *dom_name,
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
                            virDomainHostdevDefPtr *hostdevs,
                            int nhostdevs,
                            unsigned int flags)
{
    size_t i;
    int ret = -1;
    virUSBDeviceListPtr list;
    virUSBDevicePtr tmp;
    bool coldBoot = !!(flags & VIR_HOSTDEV_COLD_BOOT);

1282 1283 1284
    if (!nhostdevs)
        return 0;

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
    /* 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;
        }
    }

1319
    /* Mark devices in temporary list as used by @dom_name
1320 1321 1322
     * and add them do driver list. However, if something goes
     * wrong, perform rollback.
     */
1323
    if (virHostdevMarkUSBDevices(mgr, drv_name, dom_name, list) < 0)
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
        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;

1337
 cleanup:
1338 1339 1340
    virObjectUnref(list);
    return ret;
}
1341

1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
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;
}

1374
int
1375
virHostdevPrepareSCSIDevices(virHostdevManagerPtr mgr,
1376
                             const char *drv_name,
1377
                             const char *dom_name,
1378 1379 1380 1381 1382 1383 1384 1385
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs)
{
    size_t i, j;
    int count;
    virSCSIDeviceListPtr list;
    virSCSIDevicePtr tmp;

1386 1387 1388
    if (!nhostdevs)
        return 0;

1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
    /* 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];
1400
        virDomainHostdevSubsysSCSIPtr scsisrc = &hostdev->source.subsys.u.scsi;
1401 1402 1403 1404 1405

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

1406 1407 1408 1409 1410
        if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
            continue;  /* Not supported for iSCSI */
        } else {
            if (virHostdevPrepareSCSIHostDevices(hostdev, scsisrc, list) < 0)
                goto cleanup;
1411 1412 1413 1414 1415 1416 1417
        }
    }

    /* Loop 2: Mark devices in temporary list as used by @name
     * and add them to driver list. However, if something goes
     * wrong, perform rollback.
     */
1418
    virObjectLock(mgr->activeSCSIHostdevs);
1419 1420 1421 1422
    count = virSCSIDeviceListCount(list);

    for (i = 0; i < count; i++) {
        virSCSIDevicePtr scsi = virSCSIDeviceListGet(list, i);
1423
        if ((tmp = virSCSIDeviceListFind(mgr->activeSCSIHostdevs,
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
                                         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;
            }

1437
            if (virSCSIDeviceSetUsedBy(tmp, drv_name, dom_name) < 0)
1438 1439
                goto error;
        } else {
1440
            if (virSCSIDeviceSetUsedBy(scsi, drv_name, dom_name) < 0)
1441 1442
                goto error;

1443
            VIR_DEBUG("Adding %s to activeSCSIHostdevs", virSCSIDeviceGetName(scsi));
1444

1445
            if (virSCSIDeviceListAdd(mgr->activeSCSIHostdevs, scsi) < 0)
1446 1447 1448 1449
                goto error;
        }
    }

1450
    virObjectUnlock(mgr->activeSCSIHostdevs);
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463

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

1464
 error:
1465 1466
    for (j = 0; j < i; j++) {
        tmp = virSCSIDeviceListGet(list, i);
1467
        virSCSIDeviceListSteal(mgr->activeSCSIHostdevs, tmp);
1468
    }
1469
    virObjectUnlock(mgr->activeSCSIHostdevs);
1470
 cleanup:
1471 1472 1473
    virObjectUnref(list);
    return -1;
}
1474 1475

void
1476
virHostdevReAttachUSBDevices(virHostdevManagerPtr mgr,
1477 1478 1479 1480
                             const char *drv_name,
                             const char *dom_name,
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs)
1481 1482 1483
{
    size_t i;

1484 1485 1486
    if (!nhostdevs)
        return;

1487
    virObjectLock(mgr->activeUSBHostdevs);
1488 1489
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
1490
        virDomainHostdevSubsysUSBPtr usbsrc = &hostdev->source.subsys.u.usb;
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
        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;

1502
        if (!(usb = virUSBDeviceNew(usbsrc->bus, usbsrc->device, NULL))) {
1503
            VIR_WARN("Unable to reattach USB device %03d.%03d on domain %s",
1504
                     usbsrc->bus, usbsrc->device, dom_name);
1505 1506 1507 1508 1509 1510 1511 1512 1513
            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 */

1514
        tmp = virUSBDeviceListFind(mgr->activeUSBHostdevs, usb);
1515 1516 1517 1518 1519
        virUSBDeviceFree(usb);

        if (!tmp) {
            VIR_WARN("Unable to find device %03d.%03d "
                     "in list of active USB devices",
1520
                     usbsrc->bus, usbsrc->device);
1521 1522 1523 1524 1525
            continue;
        }

        virUSBDeviceGetUsedBy(tmp, &usedby_drvname, &usedby_domname);
        if (STREQ_NULLABLE(drv_name, usedby_drvname) &&
1526
            STREQ_NULLABLE(dom_name, usedby_domname)) {
1527
            VIR_DEBUG("Removing %03d.%03d dom=%s from activeUSBHostdevs",
1528
                      usbsrc->bus, usbsrc->device, dom_name);
1529
            virUSBDeviceListDel(mgr->activeUSBHostdevs, tmp);
1530 1531
        }
    }
1532
    virObjectUnlock(mgr->activeUSBHostdevs);
1533
}
1534

1535
static void
1536
virHostdevReAttachSCSIHostDevices(virHostdevManagerPtr mgr,
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
                                  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))) {
1550
        VIR_WARN("Unable to reattach SCSI device %s:%u:%u:%llu on domain %s",
1551 1552 1553 1554 1555 1556 1557 1558
                 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. */

1559
    if (!(tmp = virSCSIDeviceListFind(mgr->activeSCSIHostdevs, scsi))) {
1560
        VIR_WARN("Unable to find device %s:%u:%u:%llu "
1561 1562 1563 1564 1565 1566 1567
                 "in list of active SCSI devices",
                 scsihostsrc->adapter, scsihostsrc->bus,
                 scsihostsrc->target, scsihostsrc->unit);
        virSCSIDeviceFree(scsi);
        return;
    }

1568
    VIR_DEBUG("Removing %s:%u:%u:%llu dom=%s from activeSCSIHostdevs",
1569 1570 1571
               scsihostsrc->adapter, scsihostsrc->bus, scsihostsrc->target,
               scsihostsrc->unit, dom_name);

1572
    virSCSIDeviceListDel(mgr->activeSCSIHostdevs, tmp,
1573 1574 1575 1576
                         drv_name, dom_name);
    virSCSIDeviceFree(scsi);
}

1577
void
1578
virHostdevReAttachSCSIDevices(virHostdevManagerPtr mgr,
1579 1580 1581 1582
                              const char *drv_name,
                              const char *dom_name,
                              virDomainHostdevDefPtr *hostdevs,
                              int nhostdevs)
1583 1584 1585
{
    size_t i;

1586 1587 1588
    if (!nhostdevs)
        return;

1589
    virObjectLock(mgr->activeSCSIHostdevs);
1590 1591
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
1592
        virDomainHostdevSubsysSCSIPtr scsisrc = &hostdev->source.subsys.u.scsi;
1593 1594 1595 1596 1597

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

1598 1599 1600
        if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI)
            continue; /* Not supported for iSCSI */
        else
1601
            virHostdevReAttachSCSIHostDevices(mgr, hostdev, scsisrc,
1602
                                              drv_name, dom_name);
1603
    }
1604
    virObjectUnlock(mgr->activeSCSIHostdevs);
1605
}
1606 1607

int
1608
virHostdevPCINodeDeviceDetach(virHostdevManagerPtr mgr,
1609 1610
                              virPCIDevicePtr pci)
{
1611
    struct virHostdevIsPCINodeDeviceUsedData data = { mgr, NULL, false };
1612 1613
    int ret = -1;

1614 1615
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
1616

1617
    if (virHostdevIsPCINodeDeviceUsed(virPCIDeviceGetAddress(pci), &data))
1618
        goto cleanup;
1619

1620 1621
    if (virPCIDeviceDetach(pci, mgr->activePCIHostdevs,
                           mgr->inactivePCIHostdevs) < 0)
1622
        goto cleanup;
1623 1624

    ret = 0;
1625 1626

 cleanup:
1627 1628
    virObjectUnlock(mgr->inactivePCIHostdevs);
    virObjectUnlock(mgr->activePCIHostdevs);
1629

1630 1631 1632 1633
    return ret;
}

int
1634
virHostdevPCINodeDeviceReAttach(virHostdevManagerPtr mgr,
1635 1636
                                virPCIDevicePtr pci)
{
1637
    struct virHostdevIsPCINodeDeviceUsedData data = { mgr, NULL, false };
1638 1639
    int ret = -1;

1640 1641
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
1642

1643
    if (virHostdevIsPCINodeDeviceUsed(virPCIDeviceGetAddress(pci), &data))
1644
        goto cleanup;
1645

1646 1647 1648
    virPCIDeviceSetUnbindFromStub(pci, true);
    virPCIDeviceSetRemoveSlot(pci, true);
    virPCIDeviceSetReprobe(pci, true);
1649

1650
    if (virPCIDeviceReattach(pci, mgr->activePCIHostdevs,
1651
                             mgr->inactivePCIHostdevs) < 0)
1652
        goto cleanup;
1653 1654

    ret = 0;
1655 1656

 cleanup:
1657 1658
    virObjectUnlock(mgr->inactivePCIHostdevs);
    virObjectUnlock(mgr->activePCIHostdevs);
1659

1660 1661 1662 1663
    return ret;
}

int
1664
virHostdevPCINodeDeviceReset(virHostdevManagerPtr mgr,
1665 1666 1667 1668
                             virPCIDevicePtr pci)
{
    int ret = -1;

1669 1670 1671 1672
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
    if (virPCIDeviceReset(pci, mgr->activePCIHostdevs,
                          mgr->inactivePCIHostdevs) < 0)
1673 1674 1675
        goto out;

    ret = 0;
1676
 out:
1677 1678
    virObjectUnlock(mgr->inactivePCIHostdevs);
    virObjectUnlock(mgr->activePCIHostdevs);
1679 1680
    return ret;
}
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719

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
1720
 * For upgrade purpose: see virHostdevReAttachPCIHostdevs
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 1749
 */
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
1750
virHostdevUpdateActiveDomainDevices(virHostdevManagerPtr mgr,
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
                                    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;
}