virhostdev.c 75.1 KB
Newer Older
1 2
/* virhostdev.c: hostdev management
 *
3
 * Copyright (C) 2006-2007, 2009-2017 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
    virObjectUnref(hostdevMgr->activeSCSIVHostHostdevs);
150
    virObjectUnref(hostdevMgr->activeMediatedHostdevs);
151 152 153
    VIR_FREE(hostdevMgr->stateDir);
}

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

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

163
    if (!(hostdevMgr->activePCIHostdevs = virPCIDeviceListNew()))
164 165
        goto error;

166
    if (!(hostdevMgr->activeUSBHostdevs = virUSBDeviceListNew()))
167 168
        goto error;

169
    if (!(hostdevMgr->inactivePCIHostdevs = virPCIDeviceListNew()))
170 171
        goto error;

172
    if (!(hostdevMgr->activeSCSIHostdevs = virSCSIDeviceListNew()))
173 174
        goto error;

175 176 177
    if (!(hostdevMgr->activeSCSIVHostHostdevs = virSCSIVHostDeviceListNew()))
        goto error;

178 179 180
    if (!(hostdevMgr->activeMediatedHostdevs = virMediatedDeviceListNew()))
        goto error;

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
    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);
214 215
    }

216
    return hostdevMgr;
217

218
 error:
219 220
    virObjectUnref(hostdevMgr);
    return NULL;
221 222 223 224 225
}

virHostdevManagerPtr
virHostdevManagerGetDefault(void)
{
226
    if (virHostdevManagerInitialize() < 0)
227
        return NULL;
228 229

    return virObjectRef(manager);
230
}
231 232

static virPCIDeviceListPtr
233
virHostdevGetPCIHostDeviceList(virDomainHostdevDefPtr *hostdevs, int nhostdevs)
234
{
235
    virPCIDeviceListPtr pcidevs;
236 237
    size_t i;

238
    if (!(pcidevs = virPCIDeviceListNew()))
239 240 241 242
        return NULL;

    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
243
        virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;
244
        virPCIDevicePtr pci;
245 246 247 248 249 250

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

251
        pci = virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
252
                              pcisrc->addr.slot, pcisrc->addr.function);
253 254
        if (!pci) {
            virObjectUnref(pcidevs);
255 256
            return NULL;
        }
257 258 259
        if (virPCIDeviceListAdd(pcidevs, pci) < 0) {
            virPCIDeviceFree(pci);
            virObjectUnref(pcidevs);
260 261 262
            return NULL;
        }

263
        virPCIDeviceSetManaged(pci, hostdev->managed);
264 265

        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO)
266
            virPCIDeviceSetStubDriver(pci, VIR_PCI_STUB_DRIVER_VFIO);
267
        else if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN)
268
            virPCIDeviceSetStubDriver(pci, VIR_PCI_STUB_DRIVER_XEN);
269
        else
270
            virPCIDeviceSetStubDriver(pci, VIR_PCI_STUB_DRIVER_KVM);
271 272
    }

273
    return pcidevs;
274 275 276 277
}


static int
278
virHostdevPCISysfsPath(virDomainHostdevDefPtr hostdev,
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
                       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;

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

316
    if (virHostdevPCISysfsPath(hostdev, &sysfs_path) < 0)
317 318 319 320 321 322 323
        return ret;

    if (virPCIIsVirtualFunction(sysfs_path) == 1) {
        if (virPCIGetVirtualFunctionInfo(sysfs_path, linkdev,
                                         vf) < 0)
            goto cleanup;
    } else {
324 325 326 327 328
        /* In practice this should never happen, since we currently
         * only support assigning SRIOV VFs via <interface
         * type='hostdev'>, and it is only those devices that should
         * end up calling this function.
         */
329 330
        if (virPCIGetNetName(sysfs_path, linkdev) < 0)
            goto cleanup;
331 332 333 334 335 336 337 338

        if (!linkdev) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("The device at %s has no network device name"),
                             sysfs_path);
            goto cleanup;
        }

339 340 341 342 343
        *vf = -1;
    }

    ret = 0;

344
 cleanup:
345 346 347 348 349 350
    VIR_FREE(sysfs_path);

    return ret;
}


351
static bool
352 353 354 355 356 357 358 359 360
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;
}


361 362 363 364 365 366 367 368 369 370 371 372 373 374
/**
 * virHostdevIsSCSIDevice:
 * @hostdev: host device to check
 *
 * Returns true if @hostdev is a SCSI device, false otherwise.
 */
bool
virHostdevIsSCSIDevice(virDomainHostdevDefPtr hostdev)
{
    return hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
        hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI;
}


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


415 416 417 418 419 420 421 422 423 424 425 426 427
/**
 * virHostdevSaveNetConfig:
 * @hostdev: config object describing a hostdev device
 * @stateDir: directory to save device state into
 *
 * If the given hostdev device is an SRIOV network VF and *does not*
 * have a <virtualport> element (ie, it isn't being configured via
 * 802.11Qbh), determine its PF+VF#, and use that to save its current
 * "admin" MAC address and VF tag (the ones saved in the PF
 * driver).
 *
 * Returns 0 on success, -1 on failure.
 */
428
static int
429 430
virHostdevSaveNetConfig(virDomainHostdevDefPtr hostdev,
                        const char *stateDir)
431 432
{
    int ret = -1;
433
    char *linkdev = NULL;
434
    int vf = -1;
435 436 437 438

    if (!virHostdevIsPCINetDevice(hostdev) ||
        virDomainNetGetActualVirtPortProfile(hostdev->parent.data.net))
       return 0;
439

440
    if (virHostdevIsVirtualFunction(hostdev) != 1) {
441 442 443
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Interface type hostdev is currently supported on"
                         " SR-IOV Virtual Functions only"));
444
        goto cleanup;
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
    if (virHostdevNetDevice(hostdev, &linkdev, &vf) < 0)
        goto cleanup;

    if (virNetDevSaveNetConfig(linkdev, vf, stateDir, true) < 0)
        goto cleanup;

    ret = 0;
 cleanup:
    VIR_FREE(linkdev);
    return ret;
}


/**
 * virHostdevSetNetConfig:
 * @hostdev: config object describing a hostdev device
 * @uuid: uuid of the domain
 *
 * If the given hostdev device is an SRIOV network VF, determine its
 * PF+VF#, and use that to set the "admin" MAC address and VF tag (the
 * ones saved in the PF driver).xs
 *
 * Returns 0 on success, -1 on failure.
 */
static int
virHostdevSetNetConfig(virDomainHostdevDefPtr hostdev,
                       const unsigned char *uuid)
{
    char *linkdev = NULL;
    virNetDevVlanPtr vlan;
    virNetDevVPortProfilePtr virtPort;
    int ret = -1;
    int vf = -1;
    bool port_profile_associate = true;

    if (!virHostdevIsPCINetDevice(hostdev))
        return 0;

485
    if (virHostdevNetDevice(hostdev, &linkdev, &vf) < 0)
486
        goto cleanup;
487 488

    vlan = virDomainNetGetActualVlan(hostdev->parent.data.net);
489
    virtPort = virDomainNetGetActualVirtPortProfile(hostdev->parent.data.net);
490 491 492 493 494 495 496 497
    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;
        }
498 499 500 501 502
        if (virHostdevNetConfigVirtPortProfile(linkdev, vf, virtPort,
                                               &hostdev->parent.data.net->mac,
                                               uuid, port_profile_associate) < 0) {
            goto cleanup;
        }
503
    } else {
504 505
        if (virNetDevSetNetConfig(linkdev, vf, &hostdev->parent.data.net->mac,
                                  vlan, NULL, true) < 0) {
506 507
            goto cleanup;
        }
508
    }
509 510

    ret = 0;
511
 cleanup:
512 513 514 515
    VIR_FREE(linkdev);
    return ret;
}

516

517 518 519 520
/* @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
521
 * location (mgr->stateDir) but certainly will not find it. In this
522 523 524 525
 * case, try to find in the old state dir.
 */
static int
virHostdevNetConfigRestore(virDomainHostdevDefPtr hostdev,
526 527
                           const char *stateDir,
                           const char *oldStateDir)
528 529 530 531 532 533 534 535 536 537
{
    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.
     */
538
    if (!virHostdevIsPCINetDevice(hostdev))
539 540
       return 0;

541
    if (virHostdevIsVirtualFunction(hostdev) != 1) {
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
        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 {
559 560 561 562 563 564 565 566 567 568
        virMacAddrPtr MAC = NULL;
        virMacAddrPtr adminMAC = NULL;
        virNetDevVlanPtr vlan = NULL;

        ret = virNetDevReadNetConfig(linkdev, vf, stateDir, &adminMAC, &vlan, &MAC);
        if (ret < 0 && oldStateDir)
            ret = virNetDevReadNetConfig(linkdev, vf, oldStateDir,
                                         &adminMAC, &vlan, &MAC);

        if (ret == 0) {
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
            /* if a MAC was stored for the VF, we should now restore
             * that as the adminMAC. We have to do it this way because
             * the VF is still not bound to the host's net driver, so
             * we can't directly set its MAC (and even after it is
             * re-bound to the host net driver, it will still have its
             * "administratively set" flag on, and that prohibits the
             * VF's net driver from directly setting the MAC
             * anyway). But it we set the desired VF MAC as the "admin
             * MAC" *now*, then when the VF is re-bound to the host
             * net driver (which will happen soon after returning from
             * this function), that adminMAC will be set (by the PF)
             * as the VF's new initial MAC.
             *
             * If no MAC was stored for the VF, that means it wasn't
             * bound to a net driver before we used it anyway, so the
             * adminMAC is all we have, and we can just restore it
             * directly.
             */
            if (MAC) {
                VIR_FREE(adminMAC);
                adminMAC = MAC;
                MAC = NULL;
            }

593 594 595 596 597 598 599
            ignore_value(virNetDevSetNetConfig(linkdev, vf,
                                               adminMAC, vlan, MAC, true));
        }

        VIR_FREE(MAC);
        VIR_FREE(adminMAC);
        virNetDevVlanFree(vlan);
600 601 602 603 604 605 606 607
    }

    VIR_FREE(linkdev);

    return ret;
}

int
608
virHostdevPreparePCIDevices(virHostdevManagerPtr mgr,
609
                            const char *drv_name,
610
                            const char *dom_name,
611 612 613 614 615 616 617 618 619
                            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;
620
    virPCIDeviceAddressPtr devAddr = NULL;
621

622 623 624
    if (!nhostdevs)
        return 0;

625 626
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
627

628
    if (!(pcidevs = virHostdevGetPCIHostDeviceList(hostdevs, nhostdevs)))
629 630
        goto cleanup;

631 632 633 634 635 636 637 638
    /* 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 */

639
    /* Step 1: Perform some initial checks on the devices */
640
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
641
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
642
        bool strict_acs_check = !!(flags & VIR_HOSTDEV_STRICT_ACS_CHECK);
643
        bool usesVFIO = (virPCIDeviceGetStubDriver(pci) == VIR_PCI_STUB_DRIVER_VFIO);
644
        struct virHostdevIsPCINodeDeviceUsedData data = { mgr, dom_name, usesVFIO };
645 646 647 648 649 650 651 652 653 654 655
        int hdrType = -1;

        if (virPCIGetHeaderType(pci, &hdrType) < 0)
            goto cleanup;

        if (hdrType != VIR_PCI_HEADER_ENDPOINT) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Non-endpoint PCI devices cannot be assigned "
                             "to guests"));
            goto cleanup;
        }
656

657
        if (!usesVFIO && !virPCIDeviceIsAssignable(pci, strict_acs_check)) {
658 659
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is not assignable"),
660
                           virPCIDeviceGetName(pci));
661 662
            goto cleanup;
        }
663

664
        /* The device is in use by other active domain if
665
         * the dev is in list activePCIHostdevs. VFIO devices
M
Martin Kletzander 已提交
666
         * belonging to same iommu group can't be shared
667
         * across guests.
668
         */
669
        devAddr = virPCIDeviceGetAddress(pci);
670
        if (usesVFIO) {
671 672
            if (virPCIDeviceAddressIOMMUGroupIterate(devAddr,
                                                     virHostdevIsPCINodeDeviceUsed,
673
                                                     &data) < 0)
674
                goto cleanup;
675
        } else if (virHostdevIsPCINodeDeviceUsed(devAddr, &data)) {
676 677 678 679
            goto cleanup;
        }
    }

680 681 682 683 684 685 686 687
    /* Step 1.5: For non-802.11Qbh SRIOV network devices, save the
     * current device config
     */
    for (i = 0; i < nhostdevs; i++) {
        if (virHostdevSaveNetConfig(hostdevs[i], mgr->stateDir) < 0)
            goto cleanup;
    }

688 689
    /* Step 2: detach managed devices and make sure unmanaged devices
     *         have already been taken care of */
690
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
691
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
692

693
        if (virPCIDeviceGetManaged(pci)) {
A
Andrea Bolognani 已提交
694 695 696 697 698

            /* 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 */
699
            VIR_DEBUG("Detaching managed PCI device %s",
700 701
                      virPCIDeviceGetName(pci));
            if (virPCIDeviceDetach(pci,
702 703
                                   mgr->activePCIHostdevs,
                                   mgr->inactivePCIHostdevs) < 0)
704
                goto reattachdevs;
705
        } else {
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
            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;
747 748 749 750 751 752
            } else {
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("Unmanaged PCI device %s must be manually "
                               "detached from the host"),
                               virPCIDeviceGetName(pci));
                goto reattachdevs;
753
            }
754
        }
755 756
    }

757 758 759
    /* At this point, all devices are attached to the stub driver and have
     * been marked as inactive */

760
    /* Step 3: Now that all the PCI hostdevs have been detached, we
761 762
     * can safely reset them */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
763
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
764

A
Andrea Bolognani 已提交
765 766 767
        /* 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 */
768 769
        VIR_DEBUG("Resetting PCI device %s", virPCIDeviceGetName(pci));
        if (virPCIDeviceReset(pci, mgr->activePCIHostdevs,
770
                              mgr->inactivePCIHostdevs) < 0)
771 772 773
            goto reattachdevs;
    }

774
    /* Step 4: For SRIOV network devices, Now that we have detached the
775
     * the network device, set the new netdev config */
776
    for (i = 0; i < nhostdevs; i++) {
777 778 779 780 781

        if (virHostdevSetNetConfig(hostdevs[i], uuid) < 0)
            goto resetvfnetconfig;

        last_processed_hostdev_vf = i;
782 783
    }

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

789
        VIR_DEBUG("Removing PCI device %s from inactive list",
790
                  virPCIDeviceGetName(pci));
791
        actual = virPCIDeviceListSteal(mgr->inactivePCIHostdevs, pci);
792

793
        VIR_DEBUG("Adding PCI device %s to active list",
794
                  virPCIDeviceGetName(pci));
795 796
        if (!actual || virPCIDeviceListAdd(mgr->activePCIHostdevs, actual) < 0)
            goto inactivedevs;
797 798
    }

799
    /* Step 6: Set driver and domain information */
800
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
801
        virPCIDevicePtr pci, actual;
802

A
Andrea Bolognani 已提交
803 804 805
        /* 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 */
806 807
        pci = virPCIDeviceListGet(pcidevs, i);
        actual = virPCIDeviceListFind(mgr->activePCIHostdevs, pci);
808

809
        VIR_DEBUG("Setting driver and domain information for PCI device %s",
810 811 812
                  virPCIDeviceGetName(pci));
        if (actual)
            virPCIDeviceSetUsedBy(actual, drv_name, dom_name);
813 814
    }

815
    /* Step 7: Now set the original states for hostdev def */
816
    for (i = 0; i < nhostdevs; i++) {
817
        virPCIDevicePtr actual;
818
        virDomainHostdevDefPtr hostdev = hostdevs[i];
819
        virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;
820 821 822 823 824 825

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

826 827 828 829 830 831 832 833
        /* 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);
834

835 836 837
        /* Appropriate values for the unbind_from_stub, remove_slot
         * and reprobe properties of the device were set earlier
         * by virPCIDeviceDetach() */
838
        if (actual) {
839
            VIR_DEBUG("Saving network configuration of PCI device %s",
840
                      virPCIDeviceGetName(actual));
841
            hostdev->origstates.states.pci.unbind_from_stub =
842
                virPCIDeviceGetUnbindFromStub(actual);
843
            hostdev->origstates.states.pci.remove_slot =
844
                virPCIDeviceGetRemoveSlot(actual);
845
            hostdev->origstates.states.pci.reprobe =
846
                virPCIDeviceGetReprobe(actual);
847 848 849 850 851 852
        }
    }

    ret = 0;
    goto cleanup;

853
 inactivedevs:
854 855
    /* Move devices back to the inactive list so that they can be
     * processed properly below (reattachdevs label) */
856
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
857
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
858
        virPCIDevicePtr actual;
859 860

        VIR_DEBUG("Removing PCI device %s from active list",
861
                  virPCIDeviceGetName(pci));
862 863 864 865 866 867 868 869
        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));
870 871
    }

872
 resetvfnetconfig:
873 874
    if (last_processed_hostdev_vf >= 0) {
        for (i = 0; i <= last_processed_hostdev_vf; i++)
875
            virHostdevNetConfigRestore(hostdevs[i], mgr->stateDir, NULL);
876
    }
877

878
 reattachdevs:
879
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
880
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
881
        virPCIDevicePtr actual;
882

883
        /* We need to look up the actual device because that's what
N
Nitesh Konkar 已提交
884
         * virPCIDeviceReattach() expects as its argument */
885 886 887 888
        if (!(actual = virPCIDeviceListFind(mgr->inactivePCIHostdevs, pci)))
            continue;

        if (virPCIDeviceGetManaged(actual)) {
889
            VIR_DEBUG("Reattaching managed PCI device %s",
890
                      virPCIDeviceGetName(pci));
891
            ignore_value(virPCIDeviceReattach(actual,
892 893
                                              mgr->activePCIHostdevs,
                                              mgr->inactivePCIHostdevs));
894 895
        } else {
            VIR_DEBUG("Not reattaching unmanaged PCI device %s",
896
                      virPCIDeviceGetName(pci));
897
        }
898 899
    }

900
 cleanup:
901
    virObjectUnref(pcidevs);
902 903
    virObjectUnlock(mgr->activePCIHostdevs);
    virObjectUnlock(mgr->inactivePCIHostdevs);
904

905 906 907 908
    return ret;
}

/*
909
 * Pre-condition: inactivePCIHostdevs & activePCIHostdevs
910 911 912
 * are locked
 */
static void
913
virHostdevReattachPCIDevice(virHostdevManagerPtr mgr,
914
                            virPCIDevicePtr actual)
915 916
{
    /* Wait for device cleanup if it is qemu/kvm */
917
    if (virPCIDeviceGetStubDriver(actual) == VIR_PCI_STUB_DRIVER_KVM) {
918
        int retries = 100;
919
        while (virPCIDeviceWaitForCleanup(actual, "kvm_assigned_device")
920 921 922 923 924 925
               && retries) {
            usleep(100*1000);
            retries--;
        }
    }

926 927
    VIR_DEBUG("Reattaching PCI device %s", virPCIDeviceGetName(actual));
    if (virPCIDeviceReattach(actual, mgr->activePCIHostdevs,
928
                             mgr->inactivePCIHostdevs) < 0) {
929
        VIR_ERROR(_("Failed to re-attach PCI device: %s"),
930 931
                  virGetLastErrorMessage());
        virResetLastError();
932 933 934 935 936 937 938
    }
}

/* @oldStateDir:
 * For upgrade purpose: see virHostdevNetConfigRestore
 */
void
939
virHostdevReAttachPCIDevices(virHostdevManagerPtr mgr,
940
                             const char *drv_name,
941
                             const char *dom_name,
942 943
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs,
944
                             const char *oldStateDir)
945 946 947 948
{
    virPCIDeviceListPtr pcidevs;
    size_t i;

949 950 951
    if (!nhostdevs)
        return;

952 953
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
954

955
    if (!(pcidevs = virHostdevGetPCIHostDeviceList(hostdevs, nhostdevs))) {
956
        VIR_ERROR(_("Failed to allocate PCI device list: %s"),
957 958
                  virGetLastErrorMessage());
        virResetLastError();
959 960 961
        goto cleanup;
    }

962 963
    /* Reattaching devices to the host involves several steps; each
     * of them is described at length below */
964

965 966
    /* Step 1: Filter out all devices that are either not active or not
     *         used by the current domain and driver */
967 968
    i = 0;
    while (i < virPCIDeviceListCount(pcidevs)) {
969 970 971
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
        virPCIDevicePtr actual = NULL;

A
Andrea Bolognani 已提交
972 973 974 975
        /* 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 */
976 977 978 979 980 981 982 983 984
        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 已提交
985 986
                continue;
            }
987
        } else {
988
            virPCIDeviceListDel(pcidevs, pci);
989
            continue;
990 991
        }

992 993 994 995 996 997 998 999
        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;

1000
        VIR_DEBUG("Removing PCI device %s from active list",
1001
                  virPCIDeviceGetName(pci));
1002 1003 1004 1005 1006 1007 1008 1009
        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"),
1010 1011
                      virGetLastErrorMessage());
            virResetLastError();
1012
        }
1013 1014
    }

1015 1016
    /* At this point, any device that had been used by the guest has been
     * moved to the inactive list */
1017

1018
    /* Step 3: restore original network config of hostdevs that used
1019
     * <interface type='hostdev'>
1020
     */
1021 1022 1023 1024 1025
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];

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

1028 1029 1030 1031 1032
            actual = virPCIDeviceListFindByIDs(mgr->inactivePCIHostdevs,
                                               pcisrc->addr.domain,
                                               pcisrc->addr.bus,
                                               pcisrc->addr.slot,
                                               pcisrc->addr.function);
1033

1034
            if (actual) {
1035
                VIR_DEBUG("Restoring network configuration of PCI device %s",
1036
                          virPCIDeviceGetName(actual));
1037
                virHostdevNetConfigRestore(hostdev, mgr->stateDir,
1038
                                           oldStateDir);
1039 1040 1041
            }
        }
    }
1042

1043
    /* Step 4: perform a PCI Reset on all devices */
1044
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
1045
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
1046

A
Andrea Bolognani 已提交
1047 1048 1049
        /* 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 */
1050 1051
        VIR_DEBUG("Resetting PCI device %s", virPCIDeviceGetName(pci));
        if (virPCIDeviceReset(pci, mgr->activePCIHostdevs,
1052
                              mgr->inactivePCIHostdevs) < 0) {
1053
            VIR_ERROR(_("Failed to reset PCI device: %s"),
1054 1055
                      virGetLastErrorMessage());
            virResetLastError();
1056 1057 1058
        }
    }

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
    /* 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));
1075 1076
    }

1077
 cleanup:
1078
    virObjectUnref(pcidevs);
1079 1080
    virObjectUnlock(mgr->activePCIHostdevs);
    virObjectUnlock(mgr->inactivePCIHostdevs);
1081
}
1082 1083

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

1095 1096 1097
    if (!nhostdevs)
        return 0;

1098 1099
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
1100

1101
    for (i = 0; i < nhostdevs; i++) {
1102
        virDomainHostdevSubsysPCIPtr pcisrc;
1103
        hostdev = hostdevs[i];
1104
        pcisrc = &hostdev->source.subsys.u.pci;
1105 1106 1107 1108 1109 1110

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

1111 1112
        actual = virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                                 pcisrc->addr.slot, pcisrc->addr.function);
1113

1114
        if (!actual)
1115 1116
            goto cleanup;

1117 1118
        virPCIDeviceSetManaged(actual, hostdev->managed);
        virPCIDeviceSetUsedBy(actual, drv_name, dom_name);
1119

1120
        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO)
1121
            virPCIDeviceSetStubDriver(actual, VIR_PCI_STUB_DRIVER_VFIO);
1122
        else if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN)
1123
            virPCIDeviceSetStubDriver(actual, VIR_PCI_STUB_DRIVER_XEN);
1124
        else
1125
            virPCIDeviceSetStubDriver(actual, VIR_PCI_STUB_DRIVER_KVM);
1126

1127
        /* Setup the original states for the PCI device */
1128 1129 1130
        virPCIDeviceSetUnbindFromStub(actual, hostdev->origstates.states.pci.unbind_from_stub);
        virPCIDeviceSetRemoveSlot(actual, hostdev->origstates.states.pci.remove_slot);
        virPCIDeviceSetReprobe(actual, hostdev->origstates.states.pci.reprobe);
1131

1132
        if (virPCIDeviceListAdd(mgr->activePCIHostdevs, actual) < 0)
1133
            goto cleanup;
1134
        actual = NULL;
1135 1136 1137
    }

    ret = 0;
1138
 cleanup:
1139
    virPCIDeviceFree(actual);
1140 1141
    virObjectUnlock(mgr->activePCIHostdevs);
    virObjectUnlock(mgr->inactivePCIHostdevs);
1142 1143 1144 1145
    return ret;
}

int
1146
virHostdevUpdateActiveUSBDevices(virHostdevManagerPtr mgr,
1147 1148
                                 virDomainHostdevDefPtr *hostdevs,
                                 int nhostdevs,
1149
                                 const char *drv_name,
1150
                                 const char *dom_name)
1151 1152 1153 1154 1155
{
    virDomainHostdevDefPtr hostdev = NULL;
    size_t i;
    int ret = -1;

1156 1157 1158
    if (!nhostdevs)
        return 0;

1159
    virObjectLock(mgr->activeUSBHostdevs);
1160
    for (i = 0; i < nhostdevs; i++) {
1161
        virDomainHostdevSubsysUSBPtr usbsrc;
1162
        virUSBDevicePtr usb = NULL;
1163
        hostdev = hostdevs[i];
1164
        usbsrc = &hostdev->source.subsys.u.usb;
1165 1166 1167 1168 1169 1170

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

1171
        if (!(usb = virUSBDeviceNew(usbsrc->bus, usbsrc->device, NULL))) {
1172
            VIR_WARN("Unable to reattach USB device %03d.%03d on domain %s",
1173
                     usbsrc->bus, usbsrc->device, dom_name);
1174 1175 1176
            continue;
        }

1177
        virUSBDeviceSetUsedBy(usb, drv_name, dom_name);
1178

1179
        if (virUSBDeviceListAdd(mgr->activeUSBHostdevs, usb) < 0) {
1180 1181 1182 1183 1184
            virUSBDeviceFree(usb);
            goto cleanup;
        }
    }
    ret = 0;
1185
 cleanup:
1186
    virObjectUnlock(mgr->activeUSBHostdevs);
1187 1188 1189
    return ret;
}

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

1227
int
1228
virHostdevUpdateActiveSCSIDevices(virHostdevManagerPtr mgr,
1229 1230
                                  virDomainHostdevDefPtr *hostdevs,
                                  int nhostdevs,
1231
                                  const char *drv_name,
1232
                                  const char *dom_name)
1233 1234 1235 1236 1237
{
    virDomainHostdevDefPtr hostdev = NULL;
    size_t i;
    int ret = -1;

1238 1239 1240
    if (!nhostdevs)
        return 0;

1241
    virObjectLock(mgr->activeSCSIHostdevs);
1242
    for (i = 0; i < nhostdevs; i++) {
1243
        virDomainHostdevSubsysSCSIPtr scsisrc;
1244
        hostdev = hostdevs[i];
1245
        scsisrc = &hostdev->source.subsys.u.scsi;
1246

1247
        if (!virHostdevIsSCSIDevice(hostdev))
1248 1249
            continue;

1250 1251
        if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
            continue;  /* Not supported for iSCSI */
1252
        } else {
1253 1254
            if (virHostdevUpdateActiveSCSIHostDevices(mgr, hostdev, scsisrc,
                                                      drv_name, dom_name) < 0)
1255 1256 1257 1258 1259
                goto cleanup;
        }
    }
    ret = 0;

1260
 cleanup:
1261
    virObjectUnlock(mgr->activeSCSIHostdevs);
1262 1263
    return ret;
}
1264

1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308

int
virHostdevUpdateActiveMediatedDevices(virHostdevManagerPtr mgr,
                                      virDomainHostdevDefPtr *hostdevs,
                                      int nhostdevs,
                                      const char *drv_name,
                                      const char *dom_name)
{
    int ret = -1;
    size_t i;
    virMediatedDevicePtr mdev = NULL;

    if (nhostdevs == 0)
        return 0;

    virObjectLock(mgr->activeMediatedHostdevs);
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
        virDomainHostdevSubsysMediatedDevPtr mdevsrc;

        mdevsrc = &hostdev->source.subsys.u.mdev;

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

        if (!(mdev = virMediatedDeviceNew(mdevsrc->uuidstr, mdevsrc->model)))
            goto cleanup;

        virMediatedDeviceSetUsedBy(mdev, drv_name, dom_name);

        if (virMediatedDeviceListAdd(mgr->activeMediatedHostdevs, mdev) < 0)
            goto cleanup;
    }

    ret = 0;
 cleanup:
    virMediatedDeviceFree(mdev);
    virObjectUnlock(mgr->activeMediatedHostdevs);
    return ret;
}


1309
static int
1310 1311 1312 1313
virHostdevMarkUSBDevices(virHostdevManagerPtr mgr,
                         const char *drv_name,
                         const char *dom_name,
                         virUSBDeviceListPtr list)
1314 1315 1316 1317 1318
{
    size_t i, j;
    unsigned int count;
    virUSBDevicePtr tmp;

1319
    virObjectLock(mgr->activeUSBHostdevs);
1320 1321 1322 1323
    count = virUSBDeviceListCount(list);

    for (i = 0; i < count; i++) {
        virUSBDevicePtr usb = virUSBDeviceListGet(list, i);
1324
        if ((tmp = virUSBDeviceListFind(mgr->activeUSBHostdevs, usb))) {
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
            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;
        }

1342
        virUSBDeviceSetUsedBy(usb, drv_name, dom_name);
1343
        VIR_DEBUG("Adding %03d.%03d dom=%s to activeUSBHostdevs",
1344 1345
                  virUSBDeviceGetBus(usb), virUSBDeviceGetDevno(usb),
                  dom_name);
1346 1347 1348 1349 1350
        /*
         * The caller is responsible to steal these usb devices
         * from the virUSBDeviceList that passed in on success,
         * perform rollback on failure.
         */
1351
        if (virUSBDeviceListAdd(mgr->activeUSBHostdevs, usb) < 0)
1352 1353 1354
            goto error;
    }

1355
    virObjectUnlock(mgr->activeUSBHostdevs);
1356 1357
    return 0;

1358
 error:
1359 1360
    for (j = 0; j < i; j++) {
        tmp = virUSBDeviceListGet(list, i);
1361
        virUSBDeviceListSteal(mgr->activeUSBHostdevs, tmp);
1362
    }
1363
    virObjectUnlock(mgr->activeUSBHostdevs);
1364 1365 1366 1367
    return -1;
}


1368
int
1369 1370 1371 1372
virHostdevFindUSBDevice(virDomainHostdevDefPtr hostdev,
                        bool mandatory,
                        virUSBDevicePtr *usb)
{
1373 1374 1375 1376 1377 1378
    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;
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
    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;
        }

1433 1434 1435
        usbsrc->bus = virUSBDeviceGetBus(*usb);
        usbsrc->device = virUSBDeviceGetDevno(*usb);
        usbsrc->autoAddress = true;
1436 1437 1438 1439 1440

        if (autoAddress) {
            VIR_INFO("USB device %x:%x found at bus:%u device:%u (moved"
                     " from bus:%u device:%u)",
                     vendor, product,
1441
                     usbsrc->bus, usbsrc->device,
1442 1443 1444 1445 1446 1447 1448
                     bus, device);
        }
    } else if (!vendor && bus) {
        if (virUSBDeviceFindByBus(bus, device, NULL, mandatory, usb) < 0)
            return -1;
    }

1449
 out:
1450 1451 1452 1453 1454 1455
    if (!*usb)
        hostdev->missing = true;
    return 0;
}

int
1456
virHostdevPrepareUSBDevices(virHostdevManagerPtr mgr,
1457
                            const char *drv_name,
1458
                            const char *dom_name,
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
                            virDomainHostdevDefPtr *hostdevs,
                            int nhostdevs,
                            unsigned int flags)
{
    size_t i;
    int ret = -1;
    virUSBDeviceListPtr list;
    virUSBDevicePtr tmp;
    bool coldBoot = !!(flags & VIR_HOSTDEV_COLD_BOOT);

1469 1470 1471
    if (!nhostdevs)
        return 0;

1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
    /* 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;
        }
    }

1506
    /* Mark devices in temporary list as used by @dom_name
1507 1508 1509
     * and add them do driver list. However, if something goes
     * wrong, perform rollback.
     */
1510
    if (virHostdevMarkUSBDevices(mgr, drv_name, dom_name, list) < 0)
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
        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;

1524
 cleanup:
1525 1526 1527
    virObjectUnref(list);
    return ret;
}
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
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;
}

1561
int
1562
virHostdevPrepareSCSIDevices(virHostdevManagerPtr mgr,
1563
                             const char *drv_name,
1564
                             const char *dom_name,
1565 1566 1567 1568 1569 1570 1571 1572
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs)
{
    size_t i, j;
    int count;
    virSCSIDeviceListPtr list;
    virSCSIDevicePtr tmp;

1573 1574 1575
    if (!nhostdevs)
        return 0;

1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
    /* 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];
1587
        virDomainHostdevSubsysSCSIPtr scsisrc = &hostdev->source.subsys.u.scsi;
1588

1589
        if (!virHostdevIsSCSIDevice(hostdev))
1590 1591
            continue;

1592 1593 1594 1595 1596
        if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
            continue;  /* Not supported for iSCSI */
        } else {
            if (virHostdevPrepareSCSIHostDevices(hostdev, scsisrc, list) < 0)
                goto cleanup;
1597 1598 1599 1600 1601 1602 1603
        }
    }

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

    for (i = 0; i < count; i++) {
        virSCSIDevicePtr scsi = virSCSIDeviceListGet(list, i);
1609
        if ((tmp = virSCSIDeviceListFind(mgr->activeSCSIHostdevs,
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
                                         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;
            }

1623
            if (virSCSIDeviceSetUsedBy(tmp, drv_name, dom_name) < 0)
1624 1625
                goto error;
        } else {
1626
            if (virSCSIDeviceSetUsedBy(scsi, drv_name, dom_name) < 0)
1627 1628
                goto error;

1629
            VIR_DEBUG("Adding %s to activeSCSIHostdevs", virSCSIDeviceGetName(scsi));
1630

1631
            if (virSCSIDeviceListAdd(mgr->activeSCSIHostdevs, scsi) < 0)
1632 1633 1634 1635
                goto error;
        }
    }

1636
    virObjectUnlock(mgr->activeSCSIHostdevs);
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649

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

1650
 error:
1651 1652
    for (j = 0; j < i; j++) {
        tmp = virSCSIDeviceListGet(list, i);
1653
        virSCSIDeviceListSteal(mgr->activeSCSIHostdevs, tmp);
1654
    }
1655
    virObjectUnlock(mgr->activeSCSIHostdevs);
1656
 cleanup:
1657 1658 1659
    virObjectUnref(list);
    return -1;
}
1660

1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
int
virHostdevPrepareSCSIVHostDevices(virHostdevManagerPtr mgr,
                                  const char *drv_name,
                                  const char *dom_name,
                                  virDomainHostdevDefPtr *hostdevs,
                                  int nhostdevs)
{
    size_t i, j;
    int count;
    virSCSIVHostDeviceListPtr list;
    virSCSIVHostDevicePtr host, tmp;

    if (!nhostdevs)
        return 0;

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

    /* Loop 1: build temporary list */
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
        virDomainHostdevSubsysSCSIVHostPtr hostsrc = &hostdev->source.subsys.u.scsi_host;

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

        if (hostsrc->protocol != VIR_DOMAIN_HOSTDEV_SUBSYS_SCSI_HOST_PROTOCOL_TYPE_VHOST)
            continue;  /* Not supported */

        if (!(host = virSCSIVHostDeviceNew(hostsrc->wwpn)))
            goto cleanup;

        if (virSCSIVHostDeviceListAdd(list, host) < 0) {
            virSCSIVHostDeviceFree(host);
            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.
     */
    virObjectLock(mgr->activeSCSIVHostHostdevs);
    count = virSCSIVHostDeviceListCount(list);

    for (i = 0; i < count; i++) {
        host = virSCSIVHostDeviceListGet(list, i);
        if ((tmp = virSCSIVHostDeviceListFind(mgr->activeSCSIVHostHostdevs,
                                              host))) {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("SCSI_host device %s is already in use by "
                             "another domain"),
                           virSCSIVHostDeviceGetName(tmp));
            goto error;
        } else {
            if (virSCSIVHostDeviceSetUsedBy(host, drv_name, dom_name) < 0)
                goto error;

            VIR_DEBUG("Adding %s to activeSCSIVHostHostdevs",
                      virSCSIVHostDeviceGetName(host));

            if (virSCSIVHostDeviceListAdd(mgr->activeSCSIVHostHostdevs, host) < 0)
                goto error;
        }
    }

    virObjectUnlock(mgr->activeSCSIVHostHostdevs);

    /* Loop 3: Temporary list was successfully merged with
     * driver list, so steal all items to avoid freeing them
     * when freeing temporary list.
     */
    while (virSCSIVHostDeviceListCount(list) > 0) {
        tmp = virSCSIVHostDeviceListGet(list, 0);
        virSCSIVHostDeviceListSteal(list, tmp);
    }

    virObjectUnref(list);
    return 0;
 error:
    for (j = 0; j < i; j++) {
        tmp = virSCSIVHostDeviceListGet(list, i);
        virSCSIVHostDeviceListSteal(mgr->activeSCSIVHostHostdevs, tmp);
    }
    virObjectUnlock(mgr->activeSCSIVHostHostdevs);
 cleanup:
    virObjectUnref(list);
    return -1;
}

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 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820

int
virHostdevPrepareMediatedDevices(virHostdevManagerPtr mgr,
                                 const char *drv_name,
                                 const char *dom_name,
                                 virDomainHostdevDefPtr *hostdevs,
                                 int nhostdevs)
{
    size_t i;
    int ret = -1;
    virMediatedDeviceListPtr list;

    if (!nhostdevs)
        return 0;

    /* To prevent situation where mediated device is assigned to multiple
     * domains we maintain a driver list of currently assigned mediated devices.
     * A device is appended to the driver list after a series of preparations.
     */
    if (!(list = virMediatedDeviceListNew()))
        goto cleanup;

    /* Loop 1: Build a temporary list of ALL mediated devices. */
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
        virDomainHostdevSubsysMediatedDevPtr src = &hostdev->source.subsys.u.mdev;
        virMediatedDevicePtr mdev;

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

        if (!(mdev = virMediatedDeviceNew(src->uuidstr, src->model)))
            goto cleanup;

        if (virMediatedDeviceListAdd(list, mdev) < 0) {
            virMediatedDeviceFree(mdev);
            goto cleanup;
        }
    }

    /* Mark the devices in the list as used by @drv_name-@dom_name and copy the
     * references to the driver list
     */
    if (virMediatedDeviceListMarkDevices(mgr->activeMediatedHostdevs,
                                         list, drv_name, dom_name) < 0)
        goto cleanup;

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

    ret = 0;
 cleanup:
    virObjectUnref(list);
    return ret;
}

1821
void
1822
virHostdevReAttachUSBDevices(virHostdevManagerPtr mgr,
1823 1824 1825 1826
                             const char *drv_name,
                             const char *dom_name,
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs)
1827 1828 1829
{
    size_t i;

1830 1831 1832
    if (!nhostdevs)
        return;

1833
    virObjectLock(mgr->activeUSBHostdevs);
1834 1835
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
1836
        virDomainHostdevSubsysUSBPtr usbsrc = &hostdev->source.subsys.u.usb;
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
        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;

1848
        if (!(usb = virUSBDeviceNew(usbsrc->bus, usbsrc->device, NULL))) {
1849
            VIR_WARN("Unable to reattach USB device %03d.%03d on domain %s",
1850
                     usbsrc->bus, usbsrc->device, NULLSTR(dom_name));
1851 1852 1853 1854 1855 1856 1857 1858 1859
            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 */

1860
        tmp = virUSBDeviceListFind(mgr->activeUSBHostdevs, usb);
1861 1862 1863 1864 1865
        virUSBDeviceFree(usb);

        if (!tmp) {
            VIR_WARN("Unable to find device %03d.%03d "
                     "in list of active USB devices",
1866
                     usbsrc->bus, usbsrc->device);
1867 1868 1869 1870 1871
            continue;
        }

        virUSBDeviceGetUsedBy(tmp, &usedby_drvname, &usedby_domname);
        if (STREQ_NULLABLE(drv_name, usedby_drvname) &&
1872
            STREQ_NULLABLE(dom_name, usedby_domname)) {
1873
            VIR_DEBUG("Removing %03d.%03d dom=%s from activeUSBHostdevs",
1874
                      usbsrc->bus, usbsrc->device, dom_name);
1875
            virUSBDeviceListDel(mgr->activeUSBHostdevs, tmp);
1876 1877
        }
    }
1878
    virObjectUnlock(mgr->activeUSBHostdevs);
1879
}
1880

1881
static void
1882
virHostdevReAttachSCSIHostDevices(virHostdevManagerPtr mgr,
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
                                  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))) {
1896
        VIR_WARN("Unable to reattach SCSI device %s:%u:%u:%llu on domain %s",
1897 1898 1899 1900 1901 1902 1903 1904
                 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. */

1905
    if (!(tmp = virSCSIDeviceListFind(mgr->activeSCSIHostdevs, scsi))) {
1906
        VIR_WARN("Unable to find device %s:%u:%u:%llu "
1907 1908 1909 1910 1911 1912 1913
                 "in list of active SCSI devices",
                 scsihostsrc->adapter, scsihostsrc->bus,
                 scsihostsrc->target, scsihostsrc->unit);
        virSCSIDeviceFree(scsi);
        return;
    }

1914
    VIR_DEBUG("Removing %s:%u:%u:%llu dom=%s from activeSCSIHostdevs",
1915 1916 1917
               scsihostsrc->adapter, scsihostsrc->bus, scsihostsrc->target,
               scsihostsrc->unit, dom_name);

1918
    virSCSIDeviceListDel(mgr->activeSCSIHostdevs, tmp,
1919 1920 1921 1922
                         drv_name, dom_name);
    virSCSIDeviceFree(scsi);
}

1923
void
1924
virHostdevReAttachSCSIDevices(virHostdevManagerPtr mgr,
1925 1926 1927 1928
                              const char *drv_name,
                              const char *dom_name,
                              virDomainHostdevDefPtr *hostdevs,
                              int nhostdevs)
1929 1930 1931
{
    size_t i;

1932 1933 1934
    if (!nhostdevs)
        return;

1935
    virObjectLock(mgr->activeSCSIHostdevs);
1936 1937
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
1938
        virDomainHostdevSubsysSCSIPtr scsisrc = &hostdev->source.subsys.u.scsi;
1939

1940
        if (!virHostdevIsSCSIDevice(hostdev))
1941 1942
            continue;

1943 1944 1945
        if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI)
            continue; /* Not supported for iSCSI */
        else
1946
            virHostdevReAttachSCSIHostDevices(mgr, hostdev, scsisrc,
1947
                                              drv_name, dom_name);
1948
    }
1949
    virObjectUnlock(mgr->activeSCSIHostdevs);
1950
}
1951

1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
void
virHostdevReAttachSCSIVHostDevices(virHostdevManagerPtr mgr,
                                   const char *drv_name,
                                   const char *dom_name,
                                   virDomainHostdevDefPtr *hostdevs,
                                   int nhostdevs)
{
    size_t i;
    virSCSIVHostDevicePtr host, tmp;


    if (!nhostdevs)
        return;

    virObjectLock(mgr->activeSCSIVHostHostdevs);
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
        virDomainHostdevSubsysSCSIVHostPtr hostsrc = &hostdev->source.subsys.u.scsi_host;
        const char *usedby_drvname;
        const char *usedby_domname;

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

        if (hostsrc->protocol != VIR_DOMAIN_HOSTDEV_SUBSYS_SCSI_HOST_PROTOCOL_TYPE_VHOST)
            continue; /* Not supported */

        if (!(host = virSCSIVHostDeviceNew(hostsrc->wwpn))) {
            VIR_WARN("Unable to reattach SCSI_host device %s on domain %s",
1982
                     hostsrc->wwpn, NULLSTR(dom_name));
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
            virObjectUnlock(mgr->activeSCSIVHostHostdevs);
            return;
        }

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

        if (!(tmp = virSCSIVHostDeviceListFind(mgr->activeSCSIVHostHostdevs,
                                               host))) {
            VIR_WARN("Unable to find device %s "
                     "in list of active SCSI_host devices",
                     hostsrc->wwpn);
            virSCSIVHostDeviceFree(host);
            virObjectUnlock(mgr->activeSCSIVHostHostdevs);
            return;
        }

        virSCSIVHostDeviceGetUsedBy(tmp, &usedby_drvname, &usedby_domname);

        if (STREQ_NULLABLE(drv_name, usedby_drvname) &&
            STREQ_NULLABLE(dom_name, usedby_domname)) {
            VIR_DEBUG("Removing %s dom=%s from activeSCSIVHostHostdevs",
                       hostsrc->wwpn, dom_name);

            virSCSIVHostDeviceListDel(mgr->activeSCSIVHostHostdevs, tmp);
        }

        virSCSIVHostDeviceFree(host);
    }
    virObjectUnlock(mgr->activeSCSIVHostHostdevs);
}

2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
/* TODO: Rename this function along with all virHostdevReAttach* functions that
 * have nothing to do with an explicit re-attachment of a device back to the
 * host driver (like PCI).
 * Despite what the function name suggests, there's nothing to be re-attached
 * for mediated devices, the function merely removes a mediated device from the
 * list of active host devices.
 */
void
virHostdevReAttachMediatedDevices(virHostdevManagerPtr mgr,
                                  const char *drv_name,
                                  const char *dom_name,
                                  virDomainHostdevDefPtr *hostdevs,
                                  int nhostdevs)
{
    const char *used_by_drvname = NULL;
    const char *used_by_domname = NULL;
    size_t i;

    if (nhostdevs == 0)
        return;

    virObjectLock(mgr->activeMediatedHostdevs);
    for (i = 0; i < nhostdevs; i++) {
        virMediatedDevicePtr mdev, tmp;
        virDomainHostdevSubsysMediatedDevPtr mdevsrc;
        virDomainHostdevDefPtr hostdev = hostdevs[i];

        mdevsrc = &hostdev->source.subsys.u.mdev;

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

        if (!(mdev = virMediatedDeviceNew(mdevsrc->uuidstr,
                                          mdevsrc->model)))
            continue;

        /* Remove from the list only mdevs assigned to @drv_name/@dom_name */

        tmp = virMediatedDeviceListFind(mgr->activeMediatedHostdevs, mdev);
        virMediatedDeviceFree(mdev);

        /* skip inactive devices */
        if (!tmp)
            continue;

        virMediatedDeviceGetUsedBy(tmp, &used_by_drvname, &used_by_domname);
        if (STREQ_NULLABLE(drv_name, used_by_drvname) &&
            STREQ_NULLABLE(dom_name, used_by_domname)) {
            VIR_DEBUG("Removing %s dom=%s from activeMediatedHostdevs",
                      mdevsrc->uuidstr, dom_name);
            virMediatedDeviceListDel(mgr->activeMediatedHostdevs, tmp);
        }
    }
    virObjectUnlock(mgr->activeMediatedHostdevs);
}

2073
int
2074
virHostdevPCINodeDeviceDetach(virHostdevManagerPtr mgr,
2075 2076
                              virPCIDevicePtr pci)
{
2077
    struct virHostdevIsPCINodeDeviceUsedData data = { mgr, NULL, false };
2078 2079
    int ret = -1;

2080 2081
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
2082

2083
    if (virHostdevIsPCINodeDeviceUsed(virPCIDeviceGetAddress(pci), &data))
2084
        goto cleanup;
2085

2086 2087
    if (virPCIDeviceDetach(pci, mgr->activePCIHostdevs,
                           mgr->inactivePCIHostdevs) < 0)
2088
        goto cleanup;
2089 2090

    ret = 0;
2091 2092

 cleanup:
2093 2094
    virObjectUnlock(mgr->inactivePCIHostdevs);
    virObjectUnlock(mgr->activePCIHostdevs);
2095

2096 2097 2098 2099
    return ret;
}

int
2100
virHostdevPCINodeDeviceReAttach(virHostdevManagerPtr mgr,
2101 2102
                                virPCIDevicePtr pci)
{
2103
    struct virHostdevIsPCINodeDeviceUsedData data = { mgr, NULL, false };
2104 2105
    int ret = -1;

2106 2107
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
2108

2109
    if (virHostdevIsPCINodeDeviceUsed(virPCIDeviceGetAddress(pci), &data))
2110
        goto cleanup;
2111

2112 2113 2114
    virPCIDeviceSetUnbindFromStub(pci, true);
    virPCIDeviceSetRemoveSlot(pci, true);
    virPCIDeviceSetReprobe(pci, true);
2115

2116
    if (virPCIDeviceReattach(pci, mgr->activePCIHostdevs,
2117
                             mgr->inactivePCIHostdevs) < 0)
2118
        goto cleanup;
2119 2120

    ret = 0;
2121 2122

 cleanup:
2123 2124
    virObjectUnlock(mgr->inactivePCIHostdevs);
    virObjectUnlock(mgr->activePCIHostdevs);
2125

2126 2127 2128 2129
    return ret;
}

int
2130
virHostdevPCINodeDeviceReset(virHostdevManagerPtr mgr,
2131 2132 2133 2134
                             virPCIDevicePtr pci)
{
    int ret = -1;

2135 2136 2137 2138
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
    if (virPCIDeviceReset(pci, mgr->activePCIHostdevs,
                          mgr->inactivePCIHostdevs) < 0)
2139 2140 2141
        goto out;

    ret = 0;
2142
 out:
2143 2144
    virObjectUnlock(mgr->inactivePCIHostdevs);
    virObjectUnlock(mgr->activePCIHostdevs);
2145 2146
    return ret;
}
2147 2148 2149 2150 2151 2152 2153 2154 2155 2156

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

2157 2158 2159
    if (!mgr) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no host device manager defined"));
2160
        return -1;
2161
    }
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188

    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
2189
 * For upgrade purpose: see virHostdevReAttachPCIHostdevs
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
 */
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
2219
virHostdevUpdateActiveDomainDevices(virHostdevManagerPtr mgr,
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
                                    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;
}