virhostdev.c 75.5 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 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
 * 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/>.
 */

#include <config.h>

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

#include "virhostdev.h"
#include "viralloc.h"
#include "virstring.h"
#include "virfile.h"
#include "virerror.h"
#include "virlog.h"
#include "virutil.h"
37
#include "virnetdev.h"
38 39 40
#include "configmake.h"

#define VIR_FROM_THIS VIR_FROM_NONE
41 42 43

VIR_LOG_INIT("util.hostdev");

44 45
#define HOSTDEV_STATE_DIR LOCALSTATEDIR "/run/libvirt/hostdevmgr"

46 47 48 49 50 51
static virHostdevManagerPtr manager; /* global hostdev manager, never freed */

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

52
struct virHostdevIsPCINodeDeviceUsedData {
53
    virHostdevManagerPtr mgr;
54
    const char *domainName;
55
    const bool usesVFIO;
56 57
};

A
Andrea Bolognani 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
/* 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 */

79 80
static int virHostdevIsPCINodeDeviceUsed(virPCIDeviceAddressPtr devAddr, void *opaque)
{
81
    virPCIDevicePtr actual;
82
    int ret = -1;
83
    struct virHostdevIsPCINodeDeviceUsedData *helperData = opaque;
84

85 86 87 88 89 90 91
    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);
92

93
        if (helperData->usesVFIO &&
94 95
            (actual_domname && helperData->domainName) &&
            (STREQ(actual_domname, helperData->domainName)))
96 97
            goto iommu_owner;

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

116 117
static int virHostdevManagerOnceInit(void)
{
118
    if (!VIR_CLASS_NEW(virHostdevManager, virClassForObject()))
119 120 121 122 123 124 125 126
        return -1;

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

    return 0;
}

127
VIR_ONCE_GLOBAL_INIT(virHostdevManager);
128 129

static void
130
virHostdevManagerDispose(void *obj)
131
{
132 133
    virHostdevManagerPtr hostdevMgr = obj;

134 135 136 137
    virObjectUnref(hostdevMgr->activePCIHostdevs);
    virObjectUnref(hostdevMgr->inactivePCIHostdevs);
    virObjectUnref(hostdevMgr->activeUSBHostdevs);
    virObjectUnref(hostdevMgr->activeSCSIHostdevs);
138
    virObjectUnref(hostdevMgr->activeSCSIVHostHostdevs);
139
    virObjectUnref(hostdevMgr->activeMediatedHostdevs);
140 141 142
    VIR_FREE(hostdevMgr->stateDir);
}

143 144
static virHostdevManagerPtr
virHostdevManagerNew(void)
145
{
146
    VIR_AUTOUNREF(virHostdevManagerPtr) hostdevMgr = NULL;
147
    bool privileged = geteuid() == 0;
148 149 150

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

152
    if (!(hostdevMgr->activePCIHostdevs = virPCIDeviceListNew()))
153
        return NULL;
154

155
    if (!(hostdevMgr->activeUSBHostdevs = virUSBDeviceListNew()))
156
        return NULL;
157

158
    if (!(hostdevMgr->inactivePCIHostdevs = virPCIDeviceListNew()))
159
        return NULL;
160

161
    if (!(hostdevMgr->activeSCSIHostdevs = virSCSIDeviceListNew()))
162
        return NULL;
163

164
    if (!(hostdevMgr->activeSCSIVHostHostdevs = virSCSIVHostDeviceListNew()))
165
        return NULL;
166

167
    if (!(hostdevMgr->activeMediatedHostdevs = virMediatedDeviceListNew()))
168
        return NULL;
169

170 171
    if (privileged) {
        if (VIR_STRDUP(hostdevMgr->stateDir, HOSTDEV_STATE_DIR) < 0)
172
            return NULL;
173 174 175 176 177

        if (virFileMakePath(hostdevMgr->stateDir) < 0) {
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("Failed to create state dir '%s'"),
                           hostdevMgr->stateDir);
178
            return NULL;
179 180
        }
    } else {
181
        VIR_AUTOFREE(char *) rundir = NULL;
182 183 184
        mode_t old_umask;

        if (!(rundir = virGetUserRuntimeDirectory()))
185
            return NULL;
186

187
        if (virAsprintf(&hostdevMgr->stateDir, "%s/hostdevmgr", rundir) < 0)
188
            return NULL;
189 190 191 192 193 194 195 196

        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);
197
            return NULL;
198 199
        }
        umask(old_umask);
200 201
    }

202
    VIR_RETURN_PTR(hostdevMgr);
203 204 205 206 207
}

virHostdevManagerPtr
virHostdevManagerGetDefault(void)
{
208
    if (virHostdevManagerInitialize() < 0)
209
        return NULL;
210 211

    return virObjectRef(manager);
212
}
213 214

static virPCIDeviceListPtr
215
virHostdevGetPCIHostDeviceList(virDomainHostdevDefPtr *hostdevs, int nhostdevs)
216
{
217
    VIR_AUTOUNREF(virPCIDeviceListPtr) pcidevs = NULL;
218 219
    size_t i;

220
    if (!(pcidevs = virPCIDeviceListNew()))
221 222 223 224
        return NULL;

    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
225
        virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;
226
        VIR_AUTOPTR(virPCIDevice) pci = NULL;
227 228 229 230 231 232

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

233
        pci = virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
234
                              pcisrc->addr.slot, pcisrc->addr.function);
235
        if (!pci)
236 237
            return NULL;

238
        virPCIDeviceSetManaged(pci, hostdev->managed);
239 240

        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO)
241
            virPCIDeviceSetStubDriver(pci, VIR_PCI_STUB_DRIVER_VFIO);
242
        else if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN)
243
            virPCIDeviceSetStubDriver(pci, VIR_PCI_STUB_DRIVER_XEN);
244
        else
245
            virPCIDeviceSetStubDriver(pci, VIR_PCI_STUB_DRIVER_KVM);
246

247
        if (virPCIDeviceListAdd(pcidevs, pci) < 0)
248
            return NULL;
249
        pci = NULL;
250 251
    }

252
    VIR_RETURN_PTR(pcidevs);
253 254 255 256
}


static int
257
virHostdevPCISysfsPath(virDomainHostdevDefPtr hostdev,
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
                       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)
{
274
    VIR_AUTOFREE(char *) sysfs_path = NULL;
275

276
    if (virHostdevPCISysfsPath(hostdev, &sysfs_path) < 0)
277
        return -1;
278

279
    return virPCIIsVirtualFunction(sysfs_path);
280 281 282 283
}


static int
284 285 286
virHostdevNetDevice(virDomainHostdevDefPtr hostdev,
                    int pfNetDevIdx,
                    char **linkdev,
287 288
                    int *vf)
{
289
    VIR_AUTOFREE(char *) sysfs_path = NULL;
290

291
    if (virHostdevPCISysfsPath(hostdev, &sysfs_path) < 0)
292
        return -1;
293 294

    if (virPCIIsVirtualFunction(sysfs_path) == 1) {
295
        if (virPCIGetVirtualFunctionInfo(sysfs_path, pfNetDevIdx,
296 297
                                         linkdev, vf) < 0)
            return -1;
298
    } else {
299 300 301 302 303
        /* 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.
         */
304
        if (virPCIGetNetName(sysfs_path, 0, NULL, linkdev) < 0)
305
            return -1;
306

307
        if (!(*linkdev)) {
308 309
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("The device at %s has no network device name"),
310
                           sysfs_path);
311
            return -1;
312 313
        }

314 315 316
        *vf = -1;
    }

317
    return 0;
318 319 320
}


321
static bool
322 323 324 325
virHostdevIsPCINetDevice(virDomainHostdevDefPtr hostdev)
{
    return hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
        hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
326
        hostdev->parentnet != NULL;
327 328 329
}


330 331 332 333 334 335 336 337 338 339 340 341 342 343
/**
 * 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;
}


344 345 346 347 348 349 350 351 352 353 354 355 356 357
/**
 * virHostdevIsMdevDevice:
 * @hostdev: host device to check
 *
 * Returns true if @hostdev is a Mediated device, false otherwise.
 */
bool
virHostdevIsMdevDevice(virDomainHostdevDefPtr hostdev)
{
    return hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
        hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_MDEV;
}


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 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
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;
}


398 399 400 401 402 403 404 405 406 407 408 409 410
/**
 * 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.
 */
411
static int
412 413
virHostdevSaveNetConfig(virDomainHostdevDefPtr hostdev,
                        const char *stateDir)
414
{
415
    VIR_AUTOFREE(char *) linkdev = NULL;
416
    int vf = -1;
417 418

    if (!virHostdevIsPCINetDevice(hostdev) ||
419
        virDomainNetGetActualVirtPortProfile(hostdev->parentnet))
420
       return 0;
421

422
    if (virHostdevIsVirtualFunction(hostdev) != 1) {
423 424 425
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Interface type hostdev is currently supported on"
                         " SR-IOV Virtual Functions only"));
426
        return -1;
427 428
    }

429
    if (virHostdevNetDevice(hostdev, -1, &linkdev, &vf) < 0)
430
        return -1;
431 432

    if (virNetDevSaveNetConfig(linkdev, vf, stateDir, true) < 0)
433
        return -1;
434

435
    return 0;
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
}


/**
 * 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)
{
454
    VIR_AUTOFREE(char *) linkdev = NULL;
455 456 457 458 459 460 461 462
    virNetDevVlanPtr vlan;
    virNetDevVPortProfilePtr virtPort;
    int vf = -1;
    bool port_profile_associate = true;

    if (!virHostdevIsPCINetDevice(hostdev))
        return 0;

463
    if (virHostdevNetDevice(hostdev, -1, &linkdev, &vf) < 0)
464
        return -1;
465

466 467
    vlan = virDomainNetGetActualVlan(hostdev->parentnet);
    virtPort = virDomainNetGetActualVirtPortProfile(hostdev->parentnet);
468 469 470 471 472 473
    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));
474
            return -1;
475
        }
476
        if (virHostdevNetConfigVirtPortProfile(linkdev, vf, virtPort,
477
                                               &hostdev->parentnet->mac,
478 479
                                               uuid, port_profile_associate) < 0)
            return -1;
480
    } else {
481
        if (virNetDevSetNetConfig(linkdev, vf, &hostdev->parentnet->mac,
482 483
                                  vlan, NULL, true) < 0)
            return -1;
484
    }
485

486
    return 0;
487 488
}

489

490 491 492 493
/* @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
494
 * location (mgr->stateDir) but certainly will not find it. In this
495 496 497
 * case, try to find in the old state dir.
 */
static int
498
virHostdevRestoreNetConfig(virDomainHostdevDefPtr hostdev,
499 500
                           const char *stateDir,
                           const char *oldStateDir)
501
{
502 503 504
    VIR_AUTOFREE(char *) linkdev = NULL;
    VIR_AUTOFREE(virMacAddrPtr) MAC = NULL;
    VIR_AUTOFREE(virMacAddrPtr) adminMAC = NULL;
505
    VIR_AUTOPTR(virNetDevVlan) vlan = NULL;
506 507 508
    virNetDevVPortProfilePtr virtPort;
    int vf = -1;
    bool port_profile_associate = false;
509

510 511 512 513

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

517
    if (virHostdevIsVirtualFunction(hostdev) != 1) {
518 519 520
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Interface type hostdev is currently supported on"
                         " SR-IOV Virtual Functions only"));
521
        return -1;
522 523
    }

524
    if (virHostdevNetDevice(hostdev, 0, &linkdev, &vf) < 0)
525
        return -1;
526

527
    virtPort = virDomainNetGetActualVirtPortProfile(hostdev->parentnet);
528
    if (virtPort) {
529
        return virHostdevNetConfigVirtPortProfile(linkdev, vf, virtPort,
530
                                                  &hostdev->parentnet->mac,
531 532
                                                  NULL,
                                                  port_profile_associate);
533
    } else {
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
        /* we need to try 3 different places for the config file:
         * 1) ${stateDir}/${PF}_vf${vf}
         *    This is almost always where the saved config is
         *
         * 2) ${oldStateDir/${PF}_vf${vf}
         *    saved config is only here if this machine was running a
         *    (by now *very*) old version of libvirt that saved the
         *    file in a different directory
         *
         * 3) ${stateDir}${PF[1]}_vf${VF}
         *    PF[1] means "the netdev for port 2 of the PF device", and
         *    is only valid when the PF is a Mellanox dual port NIC with
         *    a VF that was created in "single port" mode.
         *
         *  NB: if virNetDevReadNetConfig() returns < 0, then it found
         *  the file, but there was a problem, so we should
         *  immediately return an error to our caller. If it returns
         *  0, but all of the interesting stuff is NULL, that means
         *  the file wasn't found, so we can/should check other
         *  locations for it.
         */
555

556 557 558
        /* 1) standard location */
        if (virNetDevReadNetConfig(linkdev, vf, stateDir,
                                   &adminMAC, &vlan, &MAC) < 0) {
559
            return -1;
560 561 562 563 564 565 566 567 568 569
        }

        /* 2) "old" (pre-1.2.3 circa 2014) location - whenever we get
        *  to the point that nobody will ever upgrade directly from
        *  1.2.3 (or older) directly to current libvirt, we can
        *  eliminate this clause
        **/
        if (!(adminMAC || vlan || MAC) && oldStateDir &&
            virNetDevReadNetConfig(linkdev, vf, oldStateDir,
                                   &adminMAC, &vlan, &MAC) < 0) {
570
            return -1;
571 572
        }

573 574 575 576 577 578 579 580 581
        /* 3) try using the PF's "port 2" netdev as the name of the
         * config file
         */
        if (!(adminMAC || vlan || MAC)) {
            VIR_FREE(linkdev);

            if (virHostdevNetDevice(hostdev, 1, &linkdev, &vf) < 0 ||
                virNetDevReadNetConfig(linkdev, vf, stateDir,
                                       &adminMAC, &vlan, &MAC) < 0) {
582
                return -1;
583
            }
584
        }
585

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
        /* 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;
608 609
        }

610 611
        ignore_value(virNetDevSetNetConfig(linkdev, vf,
                                           adminMAC, vlan, MAC, true));
612
        return 0;
613 614 615 616
    }
}

int
617
virHostdevPreparePCIDevices(virHostdevManagerPtr mgr,
618
                            const char *drv_name,
619
                            const char *dom_name,
620 621 622 623 624
                            const unsigned char *uuid,
                            virDomainHostdevDefPtr *hostdevs,
                            int nhostdevs,
                            unsigned int flags)
{
625
    VIR_AUTOUNREF(virPCIDeviceListPtr) pcidevs = NULL;
626 627 628
    int last_processed_hostdev_vf = -1;
    size_t i;
    int ret = -1;
629
    virPCIDeviceAddressPtr devAddr = NULL;
630

631 632 633
    if (!nhostdevs)
        return 0;

634 635 636
    if (!(pcidevs = virHostdevGetPCIHostDeviceList(hostdevs, nhostdevs)))
        return -1;

637 638
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
639

640 641 642 643 644 645 646 647
    /* 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 */

648
    /* Step 1: Perform some initial checks on the devices */
649
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
650
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
651
        bool strict_acs_check = !!(flags & VIR_HOSTDEV_STRICT_ACS_CHECK);
652
        bool usesVFIO = (virPCIDeviceGetStubDriver(pci) == VIR_PCI_STUB_DRIVER_VFIO);
653
        struct virHostdevIsPCINodeDeviceUsedData data = { mgr, dom_name, usesVFIO };
654 655 656 657 658 659 660 661 662 663 664
        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;
        }
665

666
        if (!usesVFIO && !virPCIDeviceIsAssignable(pci, strict_acs_check)) {
667 668
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is not assignable"),
669
                           virPCIDeviceGetName(pci));
670 671
            goto cleanup;
        }
672

673
        /* The device is in use by other active domain if
674
         * the dev is in list activePCIHostdevs. VFIO devices
M
Martin Kletzander 已提交
675
         * belonging to same iommu group can't be shared
676
         * across guests.
677
         */
678
        devAddr = virPCIDeviceGetAddress(pci);
679
        if (usesVFIO) {
680 681
            if (virPCIDeviceAddressIOMMUGroupIterate(devAddr,
                                                     virHostdevIsPCINodeDeviceUsed,
682
                                                     &data) < 0)
683
                goto cleanup;
684
        } else if (virHostdevIsPCINodeDeviceUsed(devAddr, &data)) {
685 686 687 688
            goto cleanup;
        }
    }

689 690 691 692 693 694 695 696
    /* 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;
    }

697 698
    /* Step 2: detach managed devices and make sure unmanaged devices
     *         have already been taken care of */
699
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
700
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
701

702
        if (virPCIDeviceGetManaged(pci)) {
A
Andrea Bolognani 已提交
703 704 705 706 707

            /* 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 */
708
            VIR_DEBUG("Detaching managed PCI device %s",
709 710
                      virPCIDeviceGetName(pci));
            if (virPCIDeviceDetach(pci,
711 712
                                   mgr->activePCIHostdevs,
                                   mgr->inactivePCIHostdevs) < 0)
713
                goto reattachdevs;
714
        } else {
715 716
            VIR_AUTOFREE(char *) driverPath = NULL;
            VIR_AUTOFREE(char *) driverName = NULL;
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 747 748 749 750 751 752
            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);

            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;
753 754 755
            } else {
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("Unmanaged PCI device %s must be manually "
756
                                 "detached from the host"),
757 758
                               virPCIDeviceGetName(pci));
                goto reattachdevs;
759
            }
760
        }
761 762
    }

763 764 765
    /* At this point, all devices are attached to the stub driver and have
     * been marked as inactive */

766
    /* Step 3: Now that all the PCI hostdevs have been detached, we
767 768
     * can safely reset them */
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
769
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
770

A
Andrea Bolognani 已提交
771 772 773
        /* 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 */
774 775
        VIR_DEBUG("Resetting PCI device %s", virPCIDeviceGetName(pci));
        if (virPCIDeviceReset(pci, mgr->activePCIHostdevs,
776
                              mgr->inactivePCIHostdevs) < 0)
777 778 779
            goto reattachdevs;
    }

780
    /* Step 4: For SRIOV network devices, Now that we have detached the
781
     * the network device, set the new netdev config */
782
    for (i = 0; i < nhostdevs; i++) {
783 784 785 786 787

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

        last_processed_hostdev_vf = i;
788 789
    }

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

795
        VIR_DEBUG("Removing PCI device %s from inactive list",
796
                  virPCIDeviceGetName(pci));
797
        actual = virPCIDeviceListSteal(mgr->inactivePCIHostdevs, pci);
798

799
        VIR_DEBUG("Adding PCI device %s to active list",
800
                  virPCIDeviceGetName(pci));
801 802
        if (!actual || virPCIDeviceListAdd(mgr->activePCIHostdevs, actual) < 0)
            goto inactivedevs;
803 804
    }

805
    /* Step 6: Set driver and domain information */
806
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
807
        virPCIDevicePtr pci, actual;
808

A
Andrea Bolognani 已提交
809 810 811
        /* 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 */
812 813
        pci = virPCIDeviceListGet(pcidevs, i);
        actual = virPCIDeviceListFind(mgr->activePCIHostdevs, pci);
814

815
        VIR_DEBUG("Setting driver and domain information for PCI device %s",
816 817 818
                  virPCIDeviceGetName(pci));
        if (actual)
            virPCIDeviceSetUsedBy(actual, drv_name, dom_name);
819 820
    }

821
    /* Step 7: Now set the original states for hostdev def */
822
    for (i = 0; i < nhostdevs; i++) {
823
        virPCIDevicePtr actual;
824
        virDomainHostdevDefPtr hostdev = hostdevs[i];
825
        virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;
826 827 828 829 830 831

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

832 833 834 835 836 837 838 839
        /* 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);
840

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

    ret = 0;
    goto cleanup;

859
 inactivedevs:
860 861
    /* Move devices back to the inactive list so that they can be
     * processed properly below (reattachdevs label) */
862
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
863
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
864
        virPCIDevicePtr actual;
865 866

        VIR_DEBUG("Removing PCI device %s from active list",
867
                  virPCIDeviceGetName(pci));
868 869 870 871 872 873 874 875
        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));
876 877
    }

878
 resetvfnetconfig:
879 880
    if (last_processed_hostdev_vf >= 0) {
        for (i = 0; i <= last_processed_hostdev_vf; i++)
881
            virHostdevRestoreNetConfig(hostdevs[i], mgr->stateDir, NULL);
882
    }
883

884
 reattachdevs:
885
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
886
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
887
        virPCIDevicePtr actual;
888

889
        /* We need to look up the actual device because that's what
N
Nitesh Konkar 已提交
890
         * virPCIDeviceReattach() expects as its argument */
891 892 893 894
        if (!(actual = virPCIDeviceListFind(mgr->inactivePCIHostdevs, pci)))
            continue;

        if (virPCIDeviceGetManaged(actual)) {
895
            VIR_DEBUG("Reattaching managed PCI device %s",
896
                      virPCIDeviceGetName(pci));
897
            ignore_value(virPCIDeviceReattach(actual,
898 899
                                              mgr->activePCIHostdevs,
                                              mgr->inactivePCIHostdevs));
900 901
        } else {
            VIR_DEBUG("Not reattaching unmanaged PCI device %s",
902
                      virPCIDeviceGetName(pci));
903
        }
904 905
    }

906
 cleanup:
907 908
    virObjectUnlock(mgr->activePCIHostdevs);
    virObjectUnlock(mgr->inactivePCIHostdevs);
909

910 911 912 913
    return ret;
}

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

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

/* @oldStateDir:
941
 * For upgrade purpose: see virHostdevRestoreNetConfig
942 943
 */
void
944
virHostdevReAttachPCIDevices(virHostdevManagerPtr mgr,
945
                             const char *drv_name,
946
                             const char *dom_name,
947 948
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs,
949
                             const char *oldStateDir)
950
{
951
    VIR_AUTOUNREF(virPCIDeviceListPtr) pcidevs = NULL;
952 953
    size_t i;

954 955 956
    if (!nhostdevs)
        return;

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

964 965 966
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);

967 968
    /* Reattaching devices to the host involves several steps; each
     * of them is described at length below */
969

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

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

997 998 999 1000 1001 1002 1003 1004
        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;

1005
        VIR_DEBUG("Removing PCI device %s from active list",
1006
                  virPCIDeviceGetName(pci));
1007 1008 1009 1010 1011 1012 1013 1014
        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"),
1015 1016
                      virGetLastErrorMessage());
            virResetLastError();
1017
        }
1018 1019
    }

1020 1021
    /* At this point, any device that had been used by the guest has been
     * moved to the inactive list */
1022

1023
    /* Step 3: restore original network config of hostdevs that used
1024
     * <interface type='hostdev'>
1025
     */
1026 1027 1028 1029 1030
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];

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

1033 1034 1035 1036 1037
            actual = virPCIDeviceListFindByIDs(mgr->inactivePCIHostdevs,
                                               pcisrc->addr.domain,
                                               pcisrc->addr.bus,
                                               pcisrc->addr.slot,
                                               pcisrc->addr.function);
1038

1039
            if (actual) {
1040
                VIR_DEBUG("Restoring network configuration of PCI device %s",
1041
                          virPCIDeviceGetName(actual));
1042
                virHostdevRestoreNetConfig(hostdev, mgr->stateDir,
1043
                                           oldStateDir);
1044 1045 1046
            }
        }
    }
1047

1048
    /* Step 4: perform a PCI Reset on all devices */
1049
    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
1050
        virPCIDevicePtr pci = virPCIDeviceListGet(pcidevs, i);
1051

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

1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    /* 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));
1080 1081
    }

1082 1083
    virObjectUnlock(mgr->activePCIHostdevs);
    virObjectUnlock(mgr->inactivePCIHostdevs);
1084
    virObjectUnref(pcidevs);
1085
}
1086 1087

int
1088
virHostdevUpdateActivePCIDevices(virHostdevManagerPtr mgr,
1089 1090
                                 virDomainHostdevDefPtr *hostdevs,
                                 int nhostdevs,
1091
                                 const char *drv_name,
1092
                                 const char *dom_name)
1093 1094 1095 1096 1097
{
    virDomainHostdevDefPtr hostdev = NULL;
    size_t i;
    int ret = -1;

1098 1099 1100
    if (!nhostdevs)
        return 0;

1101 1102
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
1103

1104
    for (i = 0; i < nhostdevs; i++) {
1105
        VIR_AUTOPTR(virPCIDevice) actual = NULL;
1106
        virDomainHostdevSubsysPCIPtr pcisrc;
1107
        hostdev = hostdevs[i];
1108
        pcisrc = &hostdev->source.subsys.u.pci;
1109 1110 1111 1112 1113 1114

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

1115 1116
        actual = virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
                                 pcisrc->addr.slot, pcisrc->addr.function);
1117

1118
        if (!actual)
1119 1120
            goto cleanup;

1121 1122
        virPCIDeviceSetManaged(actual, hostdev->managed);
        virPCIDeviceSetUsedBy(actual, drv_name, dom_name);
1123

1124
        if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO)
1125
            virPCIDeviceSetStubDriver(actual, VIR_PCI_STUB_DRIVER_VFIO);
1126
        else if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN)
1127
            virPCIDeviceSetStubDriver(actual, VIR_PCI_STUB_DRIVER_XEN);
1128
        else
1129
            virPCIDeviceSetStubDriver(actual, VIR_PCI_STUB_DRIVER_KVM);
1130

1131
        /* Setup the original states for the PCI device */
1132 1133 1134
        virPCIDeviceSetUnbindFromStub(actual, hostdev->origstates.states.pci.unbind_from_stub);
        virPCIDeviceSetRemoveSlot(actual, hostdev->origstates.states.pci.remove_slot);
        virPCIDeviceSetReprobe(actual, hostdev->origstates.states.pci.reprobe);
1135

1136
        if (virPCIDeviceListAdd(mgr->activePCIHostdevs, actual) < 0)
1137
            goto cleanup;
1138
        actual = NULL;
1139 1140 1141
    }

    ret = 0;
1142
 cleanup:
1143 1144
    virObjectUnlock(mgr->activePCIHostdevs);
    virObjectUnlock(mgr->inactivePCIHostdevs);
1145 1146 1147 1148
    return ret;
}

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

1159 1160 1161
    if (!nhostdevs)
        return 0;

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

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

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

1180
        virUSBDeviceSetUsedBy(usb, drv_name, dom_name);
1181

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

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
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;

    if (!(scsi = virSCSIDeviceNew(NULL,
                                  scsihostsrc->adapter, scsihostsrc->bus,
                                  scsihostsrc->target, scsihostsrc->unit,
                                  hostdev->readonly, hostdev->shareable)))
1208
        return -1;
1209 1210 1211 1212

    if ((tmp = virSCSIDeviceListFind(mgr->activeSCSIHostdevs, scsi))) {
        if (virSCSIDeviceSetUsedBy(tmp, drv_name, dom_name) < 0) {
            virSCSIDeviceFree(scsi);
1213
            return -1;
1214 1215 1216 1217 1218 1219
        }
        virSCSIDeviceFree(scsi);
    } else {
        if (virSCSIDeviceSetUsedBy(scsi, drv_name, dom_name) < 0 ||
            virSCSIDeviceListAdd(mgr->activeSCSIHostdevs, scsi) < 0) {
            virSCSIDeviceFree(scsi);
1220
            return -1;
1221 1222
        }
    }
1223
    return 0;
1224 1225
}

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

1237 1238 1239
    if (!nhostdevs)
        return 0;

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

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

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

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

1264 1265 1266 1267 1268 1269 1270 1271 1272 1273

int
virHostdevUpdateActiveMediatedDevices(virHostdevManagerPtr mgr,
                                      virDomainHostdevDefPtr *hostdevs,
                                      int nhostdevs,
                                      const char *drv_name,
                                      const char *dom_name)
{
    int ret = -1;
    size_t i;
1274
    VIR_AUTOPTR(virMediatedDevice) mdev = NULL;
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285

    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;

1286
        if (!virHostdevIsMdevDevice(hostdev))
1287 1288 1289 1290 1291 1292 1293
            continue;

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

        virMediatedDeviceSetUsedBy(mdev, drv_name, dom_name);

1294
        if (virMediatedDeviceListAdd(mgr->activeMediatedHostdevs, &mdev) < 0)
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
            goto cleanup;
    }

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


1305
static int
1306 1307 1308 1309
virHostdevMarkUSBDevices(virHostdevManagerPtr mgr,
                         const char *drv_name,
                         const char *dom_name,
                         virUSBDeviceListPtr list)
1310 1311 1312 1313 1314
{
    size_t i, j;
    unsigned int count;
    virUSBDevicePtr tmp;

1315
    virObjectLock(mgr->activeUSBHostdevs);
1316 1317 1318 1319
    count = virUSBDeviceListCount(list);

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

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

1351
    virObjectUnlock(mgr->activeUSBHostdevs);
1352 1353
    return 0;

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


1364
int
1365 1366 1367 1368
virHostdevFindUSBDevice(virDomainHostdevDefPtr hostdev,
                        bool mandatory,
                        virUSBDevicePtr *usb)
{
1369 1370 1371 1372 1373 1374
    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;
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
    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) {
1400
        VIR_AUTOUNREF(virUSBDeviceListPtr) devs = NULL;
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

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

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

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

1428 1429 1430
        usbsrc->bus = virUSBDeviceGetBus(*usb);
        usbsrc->device = virUSBDeviceGetDevno(*usb);
        usbsrc->autoAddress = true;
1431 1432 1433 1434 1435

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

1444
 out:
1445 1446 1447 1448 1449 1450
    if (!*usb)
        hostdev->missing = true;
    return 0;
}

int
1451
virHostdevPrepareUSBDevices(virHostdevManagerPtr mgr,
1452
                            const char *drv_name,
1453
                            const char *dom_name,
1454 1455 1456 1457 1458
                            virDomainHostdevDefPtr *hostdevs,
                            int nhostdevs,
                            unsigned int flags)
{
    size_t i;
1459
    VIR_AUTOUNREF(virUSBDeviceListPtr) list = NULL;
1460 1461 1462
    virUSBDevicePtr tmp;
    bool coldBoot = !!(flags & VIR_HOSTDEV_COLD_BOOT);

1463 1464 1465
    if (!nhostdevs)
        return 0;

1466 1467 1468 1469 1470 1471
    /* 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()))
1472
        return -1;
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491

    /* 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)
1492
            return -1;
1493

1494
        if (usb && virUSBDeviceListAdd(list, &usb) < 0) {
1495
            virUSBDeviceFree(usb);
1496
            return -1;
1497 1498 1499
        }
    }

1500
    /* Mark devices in temporary list as used by @dom_name
1501 1502 1503
     * and add them do driver list. However, if something goes
     * wrong, perform rollback.
     */
1504
    if (virHostdevMarkUSBDevices(mgr, drv_name, dom_name, list) < 0)
1505
        return -1;
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515

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

1516
    return 0;
1517
}
1518

1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
static int
virHostdevPrepareSCSIHostDevices(virDomainHostdevDefPtr hostdev,
                                 virDomainHostdevSubsysSCSIPtr scsisrc,
                                 virSCSIDeviceListPtr list)
{
    virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
    virSCSIDevicePtr scsi;

    if (hostdev->managed) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("SCSI host device doesn't support managed mode"));
1530
        return -1;
1531 1532 1533 1534 1535 1536
    }

    if (!(scsi = virSCSIDeviceNew(NULL,
                                  scsihostsrc->adapter, scsihostsrc->bus,
                                  scsihostsrc->target, scsihostsrc->unit,
                                  hostdev->readonly, hostdev->shareable)))
1537
        return -1;
1538 1539 1540

    if (virSCSIDeviceListAdd(list, scsi) < 0) {
        virSCSIDeviceFree(scsi);
1541
        return -1;
1542 1543
    }

1544
    return 0;
1545 1546
}

1547
int
1548
virHostdevPrepareSCSIDevices(virHostdevManagerPtr mgr,
1549
                             const char *drv_name,
1550
                             const char *dom_name,
1551 1552 1553 1554 1555
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs)
{
    size_t i, j;
    int count;
1556
    VIR_AUTOUNREF(virSCSIDeviceListPtr) list = NULL;
1557 1558
    virSCSIDevicePtr tmp;

1559 1560 1561
    if (!nhostdevs)
        return 0;

1562 1563 1564 1565 1566 1567
    /* 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()))
1568
        return -1;
1569 1570 1571 1572

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

1575
        if (!virHostdevIsSCSIDevice(hostdev))
1576 1577
            continue;

1578 1579 1580 1581
        if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
            continue;  /* Not supported for iSCSI */
        } else {
            if (virHostdevPrepareSCSIHostDevices(hostdev, scsisrc, list) < 0)
1582
                return -1;
1583 1584 1585 1586 1587 1588 1589
        }
    }

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

    for (i = 0; i < count; i++) {
        virSCSIDevicePtr scsi = virSCSIDeviceListGet(list, i);
1595
        if ((tmp = virSCSIDeviceListFind(mgr->activeSCSIHostdevs,
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
                                         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;
            }

1609
            if (virSCSIDeviceSetUsedBy(tmp, drv_name, dom_name) < 0)
1610 1611
                goto error;
        } else {
1612
            if (virSCSIDeviceSetUsedBy(scsi, drv_name, dom_name) < 0)
1613 1614
                goto error;

1615
            VIR_DEBUG("Adding %s to activeSCSIHostdevs", virSCSIDeviceGetName(scsi));
1616

1617
            if (virSCSIDeviceListAdd(mgr->activeSCSIHostdevs, scsi) < 0)
1618 1619 1620 1621
                goto error;
        }
    }

1622
    virObjectUnlock(mgr->activeSCSIHostdevs);
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634

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

    return 0;

1635
 error:
1636 1637
    for (j = 0; j < i; j++) {
        tmp = virSCSIDeviceListGet(list, i);
1638
        virSCSIDeviceListSteal(mgr->activeSCSIHostdevs, tmp);
1639
    }
1640
    virObjectUnlock(mgr->activeSCSIHostdevs);
1641 1642
    return -1;
}
1643

1644 1645 1646 1647 1648 1649 1650 1651 1652
int
virHostdevPrepareSCSIVHostDevices(virHostdevManagerPtr mgr,
                                  const char *drv_name,
                                  const char *dom_name,
                                  virDomainHostdevDefPtr *hostdevs,
                                  int nhostdevs)
{
    size_t i, j;
    int count;
1653
    VIR_AUTOUNREF(virSCSIVHostDeviceListPtr) list = NULL;
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
    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()))
1665
        return -1;
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679

    /* 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)))
1680
            return -1;
1681 1682 1683

        if (virSCSIVHostDeviceListAdd(list, host) < 0) {
            virSCSIVHostDeviceFree(host);
1684
            return -1;
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
        }
    }

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

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

1737 1738 1739 1740 1741 1742 1743 1744 1745

int
virHostdevPrepareMediatedDevices(virHostdevManagerPtr mgr,
                                 const char *drv_name,
                                 const char *dom_name,
                                 virDomainHostdevDefPtr *hostdevs,
                                 int nhostdevs)
{
    size_t i;
1746
    VIR_AUTOUNREF(virMediatedDeviceListPtr) list = NULL;
1747 1748 1749 1750 1751 1752 1753 1754 1755

    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()))
1756
        return -1;
1757 1758 1759 1760 1761 1762 1763

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

1764
        if (!virHostdevIsMdevDevice(hostdev))
1765 1766 1767
            continue;

        if (!(mdev = virMediatedDeviceNew(src->uuidstr, src->model)))
1768
            return -1;
1769

1770
        if (virMediatedDeviceListAdd(list, &mdev) < 0) {
1771
            virMediatedDeviceFree(mdev);
1772
            return -1;
1773 1774 1775 1776 1777 1778 1779 1780
        }
    }

    /* 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)
1781
        return -1;
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791

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

1792
    return 0;
1793 1794
}

1795
void
1796
virHostdevReAttachUSBDevices(virHostdevManagerPtr mgr,
1797 1798 1799 1800
                             const char *drv_name,
                             const char *dom_name,
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs)
1801 1802 1803
{
    size_t i;

1804 1805 1806
    if (!nhostdevs)
        return;

1807
    virObjectLock(mgr->activeUSBHostdevs);
1808 1809
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
1810
        virDomainHostdevSubsysUSBPtr usbsrc = &hostdev->source.subsys.u.usb;
1811 1812
        VIR_AUTOPTR(virUSBDevice) usb = NULL;
        virUSBDevicePtr tmp;
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
        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;

1823
        if (!(usb = virUSBDeviceNew(usbsrc->bus, usbsrc->device, NULL))) {
1824
            VIR_WARN("Unable to reattach USB device %03d.%03d on domain %s",
1825
                     usbsrc->bus, usbsrc->device, NULLSTR(dom_name));
1826 1827 1828 1829 1830 1831 1832 1833 1834
            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 */

1835
        tmp = virUSBDeviceListFind(mgr->activeUSBHostdevs, usb);
1836 1837 1838 1839

        if (!tmp) {
            VIR_WARN("Unable to find device %03d.%03d "
                     "in list of active USB devices",
1840
                     usbsrc->bus, usbsrc->device);
1841 1842 1843 1844 1845
            continue;
        }

        virUSBDeviceGetUsedBy(tmp, &usedby_drvname, &usedby_domname);
        if (STREQ_NULLABLE(drv_name, usedby_drvname) &&
1846
            STREQ_NULLABLE(dom_name, usedby_domname)) {
1847
            VIR_DEBUG("Removing %03d.%03d dom=%s from activeUSBHostdevs",
1848
                      usbsrc->bus, usbsrc->device, dom_name);
1849
            virUSBDeviceListDel(mgr->activeUSBHostdevs, tmp);
1850 1851
        }
    }
1852
    virObjectUnlock(mgr->activeUSBHostdevs);
1853
}
1854

1855
static void
1856
virHostdevReAttachSCSIHostDevices(virHostdevManagerPtr mgr,
1857 1858 1859 1860 1861 1862
                                  virDomainHostdevDefPtr hostdev,
                                  virDomainHostdevSubsysSCSIPtr scsisrc,
                                  const char *drv_name,
                                  const char *dom_name)
{
    virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;
1863
    VIR_AUTOPTR(virSCSIDevice) scsi = NULL;
1864 1865 1866 1867 1868 1869
    virSCSIDevicePtr tmp;

    if (!(scsi = virSCSIDeviceNew(NULL,
                                  scsihostsrc->adapter, scsihostsrc->bus,
                                  scsihostsrc->target, scsihostsrc->unit,
                                  hostdev->readonly, hostdev->shareable))) {
1870
        VIR_WARN("Unable to reattach SCSI device %s:%u:%u:%llu on domain %s",
1871 1872 1873 1874 1875 1876 1877 1878
                 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. */

1879
    if (!(tmp = virSCSIDeviceListFind(mgr->activeSCSIHostdevs, scsi))) {
1880
        VIR_WARN("Unable to find device %s:%u:%u:%llu "
1881 1882 1883 1884 1885 1886
                 "in list of active SCSI devices",
                 scsihostsrc->adapter, scsihostsrc->bus,
                 scsihostsrc->target, scsihostsrc->unit);
        return;
    }

1887
    VIR_DEBUG("Removing %s:%u:%u:%llu dom=%s from activeSCSIHostdevs",
1888 1889
              scsihostsrc->adapter, scsihostsrc->bus, scsihostsrc->target,
              scsihostsrc->unit, dom_name);
1890

1891
    virSCSIDeviceListDel(mgr->activeSCSIHostdevs, tmp,
1892 1893 1894
                         drv_name, dom_name);
}

1895
void
1896
virHostdevReAttachSCSIDevices(virHostdevManagerPtr mgr,
1897 1898 1899 1900
                              const char *drv_name,
                              const char *dom_name,
                              virDomainHostdevDefPtr *hostdevs,
                              int nhostdevs)
1901 1902 1903
{
    size_t i;

1904 1905 1906
    if (!nhostdevs)
        return;

1907
    virObjectLock(mgr->activeSCSIHostdevs);
1908 1909
    for (i = 0; i < nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
1910
        virDomainHostdevSubsysSCSIPtr scsisrc = &hostdev->source.subsys.u.scsi;
1911

1912
        if (!virHostdevIsSCSIDevice(hostdev))
1913 1914
            continue;

1915 1916 1917
        if (scsisrc->protocol == VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI)
            continue; /* Not supported for iSCSI */
        else
1918
            virHostdevReAttachSCSIHostDevices(mgr, hostdev, scsisrc,
1919
                                              drv_name, dom_name);
1920
    }
1921
    virObjectUnlock(mgr->activeSCSIHostdevs);
1922
}
1923

1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
void
virHostdevReAttachSCSIVHostDevices(virHostdevManagerPtr mgr,
                                   const char *drv_name,
                                   const char *dom_name,
                                   virDomainHostdevDefPtr *hostdevs,
                                   int nhostdevs)
{
    size_t i;

    if (!nhostdevs)
        return;

    virObjectLock(mgr->activeSCSIVHostHostdevs);
    for (i = 0; i < nhostdevs; i++) {
1938 1939
        VIR_AUTOPTR(virSCSIVHostDevice) host = NULL;
        virSCSIVHostDevicePtr tmp;
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
        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",
1954
                     hostsrc->wwpn, NULLSTR(dom_name));
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
            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);
            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",
1976
                      hostsrc->wwpn, dom_name);
1977 1978 1979 1980 1981 1982 1983

            virSCSIVHostDeviceListDel(mgr->activeSCSIVHostHostdevs, tmp);
        }
    }
    virObjectUnlock(mgr->activeSCSIVHostHostdevs);
}

1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
/* 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++) {
2007 2008
        VIR_AUTOPTR(virMediatedDevice) mdev = NULL;
        virMediatedDevicePtr tmp;
2009 2010 2011 2012 2013
        virDomainHostdevSubsysMediatedDevPtr mdevsrc;
        virDomainHostdevDefPtr hostdev = hostdevs[i];

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

2014
        if (!virHostdevIsMdevDevice(hostdev))
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
            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);

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

2040
int
2041
virHostdevPCINodeDeviceDetach(virHostdevManagerPtr mgr,
2042 2043
                              virPCIDevicePtr pci)
{
2044
    struct virHostdevIsPCINodeDeviceUsedData data = { mgr, NULL, false };
2045 2046
    int ret = -1;

2047 2048
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
2049

2050
    if (virHostdevIsPCINodeDeviceUsed(virPCIDeviceGetAddress(pci), &data))
2051
        goto cleanup;
2052

2053 2054
    if (virPCIDeviceDetach(pci, mgr->activePCIHostdevs,
                           mgr->inactivePCIHostdevs) < 0)
2055
        goto cleanup;
2056 2057

    ret = 0;
2058 2059

 cleanup:
2060 2061
    virObjectUnlock(mgr->inactivePCIHostdevs);
    virObjectUnlock(mgr->activePCIHostdevs);
2062

2063 2064 2065 2066
    return ret;
}

int
2067
virHostdevPCINodeDeviceReAttach(virHostdevManagerPtr mgr,
2068 2069
                                virPCIDevicePtr pci)
{
2070
    struct virHostdevIsPCINodeDeviceUsedData data = { mgr, NULL, false };
2071 2072
    int ret = -1;

2073 2074
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
2075

2076
    if (virHostdevIsPCINodeDeviceUsed(virPCIDeviceGetAddress(pci), &data))
2077
        goto cleanup;
2078

2079 2080 2081
    virPCIDeviceSetUnbindFromStub(pci, true);
    virPCIDeviceSetRemoveSlot(pci, true);
    virPCIDeviceSetReprobe(pci, true);
2082

2083
    if (virPCIDeviceReattach(pci, mgr->activePCIHostdevs,
2084
                             mgr->inactivePCIHostdevs) < 0)
2085
        goto cleanup;
2086 2087

    ret = 0;
2088 2089

 cleanup:
2090 2091
    virObjectUnlock(mgr->inactivePCIHostdevs);
    virObjectUnlock(mgr->activePCIHostdevs);
2092

2093 2094 2095 2096
    return ret;
}

int
2097
virHostdevPCINodeDeviceReset(virHostdevManagerPtr mgr,
2098 2099 2100 2101
                             virPCIDevicePtr pci)
{
    int ret = -1;

2102 2103 2104 2105
    virObjectLock(mgr->activePCIHostdevs);
    virObjectLock(mgr->inactivePCIHostdevs);
    if (virPCIDeviceReset(pci, mgr->activePCIHostdevs,
                          mgr->inactivePCIHostdevs) < 0)
2106 2107 2108
        goto out;

    ret = 0;
2109
 out:
2110 2111
    virObjectUnlock(mgr->inactivePCIHostdevs);
    virObjectUnlock(mgr->activePCIHostdevs);
2112 2113
    return ret;
}
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123

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

2124 2125 2126
    if (!mgr) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no host device manager defined"));
2127
        return -1;
2128
    }
2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140

    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,
2141 2142
                                        def->hostdevs, def->nhostdevs,
                                        flags) < 0)
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
            return -1;
    }

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

    return 0;
}

/* @oldStateDir
2156
 * For upgrade purpose: see virHostdevReAttachPCIHostdevs
2157 2158 2159 2160 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
 */
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
2186
virHostdevUpdateActiveDomainDevices(virHostdevManagerPtr mgr,
2187 2188 2189 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 2219
                                    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;
}