qemu_hotplug.c 82.6 KB
Newer Older
1 2 3
/*
 * qemu_hotplug.h: QEMU device hotplug management
 *
4
 * Copyright (C) 2006-2012 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25 26 27 28 29 30 31 32
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */


#include <config.h>

#include "qemu_hotplug.h"
#include "qemu_capabilities.h"
#include "qemu_domain.h"
#include "qemu_command.h"
#include "qemu_bridge_filter.h"
#include "qemu_hostdev.h"
33
#include "domain_audit.h"
34 35 36 37 38
#include "domain_nwfilter.h"
#include "logging.h"
#include "virterror_internal.h"
#include "memory.h"
#include "pci.h"
E
Eric Blake 已提交
39
#include "virfile.h"
40
#include "qemu_cgroup.h"
41
#include "locking/domain_lock.h"
42
#include "network/bridge_driver.h"
43 44
#include "virnetdev.h"
#include "virnetdevbridge.h"
A
Ansis Atteka 已提交
45
#include "virnetdevtap.h"
46
#include "device_conf.h"
47 48

#define VIR_FROM_THIS VIR_FROM_QEMU
49
#define CHANGE_MEDIA_RETRIES 10
50 51 52 53 54 55 56 57 58 59

int qemuDomainChangeEjectableMedia(struct qemud_driver *driver,
                                   virDomainObjPtr vm,
                                   virDomainDiskDefPtr disk,
                                   bool force)
{
    virDomainDiskDefPtr origdisk = NULL;
    int i;
    int ret;
    char *driveAlias = NULL;
60
    qemuDomainObjPrivatePtr priv = vm->privateData;
61
    int retries = CHANGE_MEDIA_RETRIES;
62 63 64 65 66 67 68 69 70 71

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->bus == disk->bus &&
            STREQ(vm->def->disks[i]->dst, disk->dst)) {
            origdisk = vm->def->disks[i];
            break;
        }
    }

    if (!origdisk) {
72 73 74 75
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No device with bus '%s' and target '%s'"),
                       virDomainDiskBusTypeToString(disk->bus),
                       disk->dst);
76 77 78 79
        return -1;
    }

    if (!origdisk->info.alias) {
80 81
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("missing disk device alias name for %s"), origdisk->dst);
82 83 84 85 86
        return -1;
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
        origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
87 88
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
89
                       virDomainDiskDeviceTypeToString(disk->device));
90 91 92
        return -1;
    }

93 94 95
    if (virDomainLockDiskAttach(driver->lockManager, vm, disk) < 0)
        return -1;

96
    if (virSecurityManagerSetImageLabel(driver->securityManager,
97
                                        vm->def, disk) < 0) {
98 99
        if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
            VIR_WARN("Unable to release lock on %s", disk->src);
100
        return -1;
101
    }
102

103
    if (!(driveAlias = qemuDeviceDriveHostAlias(origdisk, priv->caps)))
104 105
        goto error;

106
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
107
    ret = qemuMonitorEjectMedia(priv->mon, driveAlias, force);
108
    qemuDomainObjExitMonitor(driver, vm);
109

110
    virObjectRef(vm);
111
    /* we don't want to report errors from media tray_open polling */
112
    while (retries) {
113 114 115
        if (origdisk->tray_status == VIR_DOMAIN_DISK_TRAY_OPEN)
            break;

116
        retries--;
117
        virDomainObjUnlock(vm);
118 119
        VIR_DEBUG("Waiting 500ms for tray to open. Retries left %d", retries);
        usleep(500 * 1000); /* sleep 500ms */
120
        virDomainObjLock(vm);
121
    }
122
    virObjectUnref(vm);
123

124 125 126
    if (retries <= 0) {
        if (ret == 0) {
            /* If ret == -1, EjectMedia already set an error message */
127
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
128
                           _("Unable to eject media"));
129
        }
130 131 132 133 134 135 136 137
        goto audit;
    }
    ret = 0;

    if (disk->src) {
        /* deliberately don't depend on 'ret' as 'eject' may have failed the
         * first time and we are going to check the drive state anyway */
        const char *format = NULL;
138

139 140 141 142 143 144
        if (disk->type != VIR_DOMAIN_DISK_TYPE_DIR) {
            if (disk->driverType)
                format = disk->driverType;
            else if (origdisk->driverType)
                format = origdisk->driverType;
        }
145
        qemuDomainObjEnterMonitor(driver, vm);
146 147 148
        ret = qemuMonitorChangeMedia(priv->mon,
                                     driveAlias,
                                     disk->src, format);
149
        qemuDomainObjExitMonitor(driver, vm);
150 151
    }

152
audit:
153
    virDomainAuditDisk(vm, origdisk->src, disk->src, "update", ret >= 0);
154 155 156 157

    if (ret < 0)
        goto error;

158
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
159
                                            vm->def, origdisk) < 0)
160 161
        VIR_WARN("Unable to restore security label on ejected image %s", origdisk->src);

162 163 164
    if (virDomainLockDiskDetach(driver->lockManager, vm, origdisk) < 0)
        VIR_WARN("Unable to release lock on disk %s", origdisk->src);

165 166 167 168 169 170 171 172 173 174 175 176 177
    VIR_FREE(origdisk->src);
    origdisk->src = disk->src;
    disk->src = NULL;
    origdisk->type = disk->type;

    VIR_FREE(driveAlias);

    virDomainDiskDefFree(disk);

    return ret;

error:
    VIR_FREE(driveAlias);
178

179
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
180
                                            vm->def, disk) < 0)
181
        VIR_WARN("Unable to restore security label on new media %s", disk->src);
182 183 184 185

    if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
        VIR_WARN("Unable to release lock on %s", disk->src);

186 187 188
    return -1;
}

189 190
int
qemuDomainCheckEjectableMedia(struct qemud_driver *driver,
191 192
                             virDomainObjPtr vm,
                             enum qemuDomainAsyncJob asyncJob)
193 194
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
195
    virHashTablePtr table = NULL;
196 197 198
    int ret = -1;
    int i;

199 200 201 202
    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) == 0) {
        table = qemuMonitorGetBlockInfo(priv->mon);
        qemuDomainObjExitMonitorWithDriver(driver, vm);
    }
203 204 205 206

    if (!table)
        goto cleanup;

207 208
    for (i = 0; i < vm->def->ndisks; i++) {
        virDomainDiskDefPtr disk = vm->def->disks[i];
209
        struct qemuDomainDiskInfo *info;
210

211 212
        if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK ||
            disk->device == VIR_DOMAIN_DISK_DEVICE_LUN) {
213
                 continue;
214
        }
215

216 217
        info = qemuMonitorBlockInfoLookup(table, disk->info.alias);
        if (!info)
218 219
            goto cleanup;

220
        if (info->tray_open && disk->src)
221 222 223 224 225 226
            VIR_FREE(disk->src);
    }

    ret = 0;

cleanup:
227
    virHashFree(table);
228 229 230
    return ret;
}

231

232 233
int qemuDomainAttachPciDiskDevice(virConnectPtr conn,
                                  struct qemud_driver *driver,
234
                                  virDomainObjPtr vm,
235
                                  virDomainDiskDefPtr disk)
236 237 238 239 240 241
{
    int i, ret;
    const char* type = virDomainDiskBusTypeToString(disk->bus);
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *devstr = NULL;
    char *drivestr = NULL;
242
    bool releaseaddr = false;
243 244 245

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
246 247
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("target %s already exists"), disk->dst);
248 249 250 251
            return -1;
        }
    }

252 253 254
    if (virDomainLockDiskAttach(driver->lockManager, vm, disk) < 0)
        return -1;

255
    if (virSecurityManagerSetImageLabel(driver->securityManager,
256
                                        vm->def, disk) < 0) {
257 258
        if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
            VIR_WARN("Unable to release lock on %s", disk->src);
259
        return -1;
260
    }
261

262
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
263 264
        if (qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &disk->info) < 0)
            goto error;
265
        releaseaddr = true;
266
        if (qemuAssignDeviceDiskAlias(vm->def, disk, priv->caps) < 0)
267 268
            goto error;

269
        if (!(drivestr = qemuBuildDriveStr(conn, disk, false, priv->caps)))
270 271
            goto error;

272
        if (!(devstr = qemuBuildDriveDevStr(NULL, disk, 0, priv->caps)))
273 274 275 276 277 278 279 280
            goto error;
    }

    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
        virReportOOMError();
        goto error;
    }

281
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
282
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
283 284 285 286
        ret = qemuMonitorAddDrive(priv->mon, drivestr);
        if (ret == 0) {
            ret = qemuMonitorAddDevice(priv->mon, devstr);
            if (ret < 0) {
287 288 289 290 291 292 293 294 295 296
                virErrorPtr orig_err = virSaveLastError();
                if (qemuMonitorDriveDel(priv->mon, drivestr) < 0) {
                    VIR_WARN("Unable to remove drive %s (%s) after failed "
                             "qemuMonitorAddDevice",
                             drivestr, devstr);
                }
                if (orig_err) {
                    virSetError(orig_err);
                    virFreeError(orig_err);
                }
297 298 299
            }
        }
    } else {
300
        virDevicePCIAddress guestAddr = disk->info.addr.pci;
301 302 303 304 305 306 307 308 309 310 311
        ret = qemuMonitorAddPCIDisk(priv->mon,
                                    disk->src,
                                    type,
                                    &guestAddr);
        if (ret == 0) {
            disk->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
            memcpy(&disk->info.addr.pci, &guestAddr, sizeof(guestAddr));
        }
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);

312
    virDomainAuditDisk(vm, NULL, disk->src, "attach", ret >= 0);
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327

    if (ret < 0)
        goto error;

    virDomainDiskInsertPreAlloced(vm->def, disk);

    VIR_FREE(devstr);
    VIR_FREE(drivestr);

    return 0;

error:
    VIR_FREE(devstr);
    VIR_FREE(drivestr);

328
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
329
        (disk->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) &&
330
        releaseaddr &&
331 332
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
                                        disk->info.addr.pci.slot) < 0)
333 334
        VIR_WARN("Unable to release PCI address on %s", disk->src);

335
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
336
                                            vm->def, disk) < 0)
337 338
        VIR_WARN("Unable to restore security label on %s", disk->src);

339 340 341
    if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
        VIR_WARN("Unable to release lock on %s", disk->src);

342 343 344 345 346 347
    return -1;
}


int qemuDomainAttachPciControllerDevice(struct qemud_driver *driver,
                                        virDomainObjPtr vm,
348
                                        virDomainControllerDefPtr controller)
349 350 351 352 353
{
    int ret = -1;
    const char* type = virDomainControllerTypeToString(controller->type);
    char *devstr = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
354
    bool releaseaddr = false;
355

356 357 358 359 360
    if (virDomainControllerFind(vm->def, controller->type, controller->idx) > 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("target %s:%d already exists"),
                       type, controller->idx);
        return -1;
361 362
    }

363
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
364 365
        if (qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &controller->info) < 0)
            goto cleanup;
366
        releaseaddr = true;
367 368 369
        if (qemuAssignDeviceControllerAlias(controller) < 0)
            goto cleanup;

370 371
        if (controller->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
            controller->model == -1 &&
372
            !qemuCapsGet(priv->caps, QEMU_CAPS_PIIX3_USB_UHCI)) {
373 374
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("USB controller hotplug unsupported in this QEMU binary"));
375 376 377
            goto cleanup;
        }

378
        if (!(devstr = qemuBuildControllerDevStr(vm->def, controller, priv->caps, NULL))) {
379 380 381 382 383 384 385 386 387
            goto cleanup;
        }
    }

    if (VIR_REALLOC_N(vm->def->controllers, vm->def->ncontrollers+1) < 0) {
        virReportOOMError();
        goto cleanup;
    }

388
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
389
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
        ret = qemuMonitorAddDevice(priv->mon, devstr);
    } else {
        ret = qemuMonitorAttachPCIDiskController(priv->mon,
                                                 type,
                                                 &controller->info.addr.pci);
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);

    if (ret == 0) {
        controller->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
        virDomainControllerInsertPreAlloced(vm->def, controller);
    }

cleanup:
    if ((ret != 0) &&
405
        qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
406
        (controller->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) &&
407
        releaseaddr &&
408 409
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
                                        controller->info.addr.pci.slot) < 0)
410
        VIR_WARN("Unable to release PCI address on controller");
411 412 413 414 415 416 417 418 419

    VIR_FREE(devstr);
    return ret;
}


static virDomainControllerDefPtr
qemuDomainFindOrCreateSCSIDiskController(struct qemud_driver *driver,
                                         virDomainObjPtr vm,
420
                                         int controller)
421 422 423
{
    int i;
    virDomainControllerDefPtr cont;
424

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    for (i = 0 ; i < vm->def->ncontrollers ; i++) {
        cont = vm->def->controllers[i];

        if (cont->type != VIR_DOMAIN_CONTROLLER_TYPE_SCSI)
            continue;

        if (cont->idx == controller)
            return cont;
    }

    /* No SCSI controller present, for backward compatibility we
     * now hotplug a controller */
    if (VIR_ALLOC(cont) < 0) {
        virReportOOMError();
        return NULL;
    }
    cont->type = VIR_DOMAIN_CONTROLLER_TYPE_SCSI;
442
    cont->idx = controller;
443 444
    cont->model = -1;

445
    VIR_INFO("No SCSI controller present, hotplugging one");
446
    if (qemuDomainAttachPciControllerDevice(driver,
447
                                            vm, cont) < 0) {
448 449 450 451 452
        VIR_FREE(cont);
        return NULL;
    }

    if (!virDomainObjIsActive(vm)) {
453 454
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest unexpectedly quit"));
455 456 457 458 459 460 461 462 463
        /* cont doesn't need freeing here, since the reference
         * now held in def->controllers */
        return NULL;
    }

    return cont;
}


464 465
int qemuDomainAttachSCSIDisk(virConnectPtr conn,
                             struct qemud_driver *driver,
466
                             virDomainObjPtr vm,
467
                             virDomainDiskDefPtr disk)
468 469 470 471 472 473 474 475 476 477
{
    int i;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virDomainControllerDefPtr cont = NULL;
    char *drivestr = NULL;
    char *devstr = NULL;
    int ret = -1;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
478 479
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("target %s already exists"), disk->dst);
480 481 482 483
            return -1;
        }
    }

484 485
    if (virDomainLockDiskAttach(driver->lockManager, vm, disk) < 0)
        return -1;
486

487
    if (virSecurityManagerSetImageLabel(driver->securityManager,
488
                                        vm->def, disk) < 0) {
489 490
        if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
            VIR_WARN("Unable to release lock on %s", disk->src);
491
        return -1;
492
    }
493 494 495

    /* We should have an address already, so make sure */
    if (disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE) {
496 497 498
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected disk address type %s"),
                       virDomainDeviceAddressTypeToString(disk->info.type));
499 500 501
        goto error;
    }

502 503
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
        if (qemuAssignDeviceDiskAlias(vm->def, disk, priv->caps) < 0)
504
            goto error;
505
        if (!(devstr = qemuBuildDriveDevStr(vm->def, disk, 0, priv->caps)))
506 507 508
            goto error;
    }

509
    if (!(drivestr = qemuBuildDriveStr(conn, disk, false, priv->caps)))
510 511 512
        goto error;

    for (i = 0 ; i <= disk->info.addr.drive.controller ; i++) {
513
        cont = qemuDomainFindOrCreateSCSIDiskController(driver, vm, i);
514 515 516 517 518 519 520 521 522 523
        if (!cont)
            goto error;
    }

    /* Tell clang that "cont" is non-NULL.
       This is because disk->info.addr.driver.controller is unsigned,
       and hence the above loop must iterate at least once.  */
    sa_assert (cont);

    if (cont->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
524 525
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("SCSI controller %d was missing its PCI address"), cont->idx);
526 527 528 529 530 531 532 533
        goto error;
    }

    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
        virReportOOMError();
        goto error;
    }

534
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
535
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
        ret = qemuMonitorAddDrive(priv->mon, drivestr);
        if (ret == 0) {
            ret = qemuMonitorAddDevice(priv->mon, devstr);
            if (ret < 0) {
                VIR_WARN("qemuMonitorAddDevice failed on %s (%s)",
                         drivestr, devstr);
                /* XXX should call 'drive_del' on error but this does not
                   exist yet */
            }
        }
    } else {
        virDomainDeviceDriveAddress driveAddr;
        ret = qemuMonitorAttachDrive(priv->mon,
                                     drivestr,
                                     &cont->info.addr.pci,
                                     &driveAddr);
        if (ret == 0) {
            /* XXX we should probably validate that the addr matches
             * our existing defined addr instead of overwriting */
            disk->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE;
556 557
            disk->info.addr.drive.bus = driveAddr.bus;
            disk->info.addr.drive.unit = driveAddr.unit;
558 559 560 561
        }
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);

562
    virDomainAuditDisk(vm, NULL, disk->src, "attach", ret >= 0);
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577

    if (ret < 0)
        goto error;

    virDomainDiskInsertPreAlloced(vm->def, disk);

    VIR_FREE(devstr);
    VIR_FREE(drivestr);

    return 0;

error:
    VIR_FREE(devstr);
    VIR_FREE(drivestr);

578
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
579
                                            vm->def, disk) < 0)
580 581
        VIR_WARN("Unable to restore security label on %s", disk->src);

582 583 584
    if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
        VIR_WARN("Unable to release lock on %s", disk->src);

585 586 587 588
    return -1;
}


589 590
int qemuDomainAttachUsbMassstorageDevice(virConnectPtr conn,
                                         struct qemud_driver *driver,
591
                                         virDomainObjPtr vm,
592
                                         virDomainDiskDefPtr disk)
593 594 595 596 597 598 599 600
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int i, ret;
    char *drivestr = NULL;
    char *devstr = NULL;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
601 602
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("target %s already exists"), disk->dst);
603 604 605 606
            return -1;
        }
    }

607 608 609
    if (virDomainLockDiskAttach(driver->lockManager, vm, disk) < 0)
        return -1;

610
    if (virSecurityManagerSetImageLabel(driver->securityManager,
611
                                        vm->def, disk) < 0) {
612 613
        if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
            VIR_WARN("Unable to release lock on %s", disk->src);
614
        return -1;
615
    }
616

617
    /* XXX not correct once we allow attaching a USB CDROM */
618
    if (!disk->src) {
619 620
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("disk source path is missing"));
621 622 623
        goto error;
    }

624 625
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
        if (qemuAssignDeviceDiskAlias(vm->def, disk, priv->caps) < 0)
626
            goto error;
627
        if (!(drivestr = qemuBuildDriveStr(conn, disk, false, priv->caps)))
628
            goto error;
629
        if (!(devstr = qemuBuildDriveDevStr(NULL, disk, 0, priv->caps)))
630 631 632 633 634 635 636 637
            goto error;
    }

    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
        virReportOOMError();
        goto error;
    }

638
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
639
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
        ret = qemuMonitorAddDrive(priv->mon, drivestr);
        if (ret == 0) {
            ret = qemuMonitorAddDevice(priv->mon, devstr);
            if (ret < 0) {
                VIR_WARN("qemuMonitorAddDevice failed on %s (%s)",
                         drivestr, devstr);
                /* XXX should call 'drive_del' on error but this does not
                   exist yet */
            }
        }
    } else {
        ret = qemuMonitorAddUSBDisk(priv->mon, disk->src);
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);

655
    virDomainAuditDisk(vm, NULL, disk->src, "attach", ret >= 0);
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670

    if (ret < 0)
        goto error;

    virDomainDiskInsertPreAlloced(vm->def, disk);

    VIR_FREE(devstr);
    VIR_FREE(drivestr);

    return 0;

error:
    VIR_FREE(devstr);
    VIR_FREE(drivestr);

671
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
672
                                            vm->def, disk) < 0)
673 674
        VIR_WARN("Unable to restore security label on %s", disk->src);

675 676 677
    if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
        VIR_WARN("Unable to release lock on %s", disk->src);

678 679 680 681 682 683 684 685
    return -1;
}


/* XXX conn required for network -> bridge resolution */
int qemuDomainAttachNetDevice(virConnectPtr conn,
                              struct qemud_driver *driver,
                              virDomainObjPtr vm,
686
                              virDomainNetDefPtr net)
687 688 689 690
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *tapfd_name = NULL;
    int tapfd = -1;
691 692
    char *vhostfd_name = NULL;
    int vhostfd = -1;
693 694
    char *nicstr = NULL;
    char *netstr = NULL;
A
Ansis Atteka 已提交
695
    virNetDevVPortProfilePtr vport = NULL;
696
    int ret = -1;
697
    virDevicePCIAddress guestAddr;
698
    int vlan;
699
    bool releaseaddr = false;
700 701
    bool iface_connected = false;
    int actualType;
702

703 704 705
    /* preallocate new slot for device */
    if (VIR_REALLOC_N(vm->def->nets, vm->def->nnets+1) < 0) {
        virReportOOMError();
706 707 708
        return -1;
    }

709 710 711 712 713
    /* If appropriate, grab a physical device from the configured
     * network's pool of devices, or resolve bridge device name
     * to the one defined in the network definition.
     */
    if (networkAllocateActualDevice(net) < 0)
714
        return -1;
715 716

    actualType = virDomainNetGetActualType(net);
717 718 719 720 721 722 723 724 725 726 727 728

    if (actualType == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
        /* This is really a "smart hostdev", so it should be attached
         * as a hostdev (the hostdev code will reach over into the
         * netdev-specific code as appropriate), then also added to
         * the nets list (see cleanup:) if successful.
         */
        ret = qemuDomainAttachHostDevice(driver, vm,
                                         virDomainNetGetActualHostdev(net));
        goto cleanup;
    }

729
    if (!qemuCapsGet(priv->caps, QEMU_CAPS_HOST_NET_ADD)) {
730 731
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("installed qemu version does not support host_net_add"));
732 733 734
        goto cleanup;
    }

735 736
    if (actualType == VIR_DOMAIN_NET_TYPE_BRIDGE ||
        actualType == VIR_DOMAIN_NET_TYPE_NETWORK) {
R
Richa Marwaha 已提交
737 738 739 740 741 742 743
        /*
         * If type=bridge then we attempt to allocate the tap fd here only if
         * running under a privilged user or -netdev bridge option is not
         * supported.
         */
        if (actualType == VIR_DOMAIN_NET_TYPE_NETWORK ||
            driver->privileged ||
744
            (!qemuCapsGet (priv->caps, QEMU_CAPS_NETDEV_BRIDGE))) {
R
Richa Marwaha 已提交
745
            if ((tapfd = qemuNetworkIfaceConnect(vm->def, conn, driver, net,
746
                                                 priv->caps)) < 0)
R
Richa Marwaha 已提交
747 748
                goto cleanup;
            iface_connected = true;
749
            if (qemuOpenVhostNet(vm->def, net, priv->caps, &vhostfd) < 0)
R
Richa Marwaha 已提交
750 751
                goto cleanup;
        }
752
    } else if (actualType == VIR_DOMAIN_NET_TYPE_DIRECT) {
753
        if ((tapfd = qemuPhysIfaceConnect(vm->def, driver, net,
754
                                          priv->caps,
755
                                          VIR_NETDEV_VPORT_PROFILE_OP_CREATE)) < 0)
756 757
            goto cleanup;
        iface_connected = true;
758
        if (qemuOpenVhostNet(vm->def, net, priv->caps, &vhostfd) < 0)
759
            goto cleanup;
760 761
    }

762 763
    if (qemuCapsGet(priv->caps, QEMU_CAPS_NET_NAME) ||
        qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
764 765 766 767
        if (qemuAssignDeviceNetAlias(vm->def, net, -1) < 0)
            goto cleanup;
    }

768
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
769 770 771
        qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &net->info) < 0)
        goto cleanup;

772 773
    releaseaddr = true;

774 775
    if (qemuCapsGet(priv->caps, QEMU_CAPS_NETDEV) &&
        qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
776 777 778 779 780
        vlan = -1;
    } else {
        vlan = qemuDomainNetVLAN(net);

        if (vlan < 0) {
781 782
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Unable to attach network devices without vlan"));
783 784 785 786 787 788 789 790 791
            goto cleanup;
        }
    }

    if (tapfd != -1) {
        if (virAsprintf(&tapfd_name, "fd-%s", net->info.alias) < 0)
            goto no_memory;
    }

792 793 794 795 796
    if (vhostfd != -1) {
        if (virAsprintf(&vhostfd_name, "vhostfd-%s", net->info.alias) < 0)
            goto no_memory;
    }

797 798 799
    if (qemuCapsGet(priv->caps, QEMU_CAPS_NETDEV) &&
        qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
        if (!(netstr = qemuBuildHostNetStr(net, driver, priv->caps,
R
Richa Marwaha 已提交
800 801
                                           ',', -1, tapfd_name,
                                           vhostfd_name)))
802
            goto cleanup;
803
    } else {
804
        if (!(netstr = qemuBuildHostNetStr(net, driver, priv->caps,
R
Richa Marwaha 已提交
805 806
                                           ' ', vlan, tapfd_name,
                                           vhostfd_name)))
807
            goto cleanup;
808 809
    }

810
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
811 812
    if (qemuCapsGet(priv->caps, QEMU_CAPS_NETDEV) &&
        qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
813 814
        if (qemuMonitorAddNetdev(priv->mon, netstr, tapfd, tapfd_name,
                                 vhostfd, vhostfd_name) < 0) {
815
            qemuDomainObjExitMonitorWithDriver(driver, vm);
816
            virDomainAuditNet(vm, NULL, net, "attach", false);
817
            goto cleanup;
818 819
        }
    } else {
820 821
        if (qemuMonitorAddHostNetwork(priv->mon, netstr, tapfd, tapfd_name,
                                      vhostfd, vhostfd_name) < 0) {
822
            qemuDomainObjExitMonitorWithDriver(driver, vm);
823
            virDomainAuditNet(vm, NULL, net, "attach", false);
824
            goto cleanup;
825 826 827 828 829
        }
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);

    VIR_FORCE_CLOSE(tapfd);
830
    VIR_FORCE_CLOSE(vhostfd);
831 832

    if (!virDomainObjIsActive(vm)) {
833 834
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest unexpectedly quit"));
835 836 837
        goto cleanup;
    }

838 839
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
        if (!(nicstr = qemuBuildNicDevStr(net, vlan, 0, priv->caps)))
840 841 842 843 844 845
            goto try_remove;
    } else {
        if (!(nicstr = qemuBuildNicStr(net, NULL, vlan)))
            goto try_remove;
    }

846
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
847
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
848 849
        if (qemuMonitorAddDevice(priv->mon, nicstr) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
850
            virDomainAuditNet(vm, NULL, net, "attach", false);
851 852 853
            goto try_remove;
        }
    } else {
854
        guestAddr = net->info.addr.pci;
855 856 857
        if (qemuMonitorAddPCINetwork(priv->mon, nicstr,
                                     &guestAddr) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
858
            virDomainAuditNet(vm, NULL, net, "attach", false);
859 860 861 862 863 864 865
            goto try_remove;
        }
        net->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
        memcpy(&net->info.addr.pci, &guestAddr, sizeof(guestAddr));
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);

866 867 868
    /* set link state */
    if (net->linkstate == VIR_DOMAIN_NET_INTERFACE_LINK_STATE_DOWN) {
        if (!net->info.alias) {
869 870
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("device alias not found: cannot set link state to down"));
871 872 873
        } else {
            qemuDomainObjEnterMonitorWithDriver(driver, vm);

874
            if (qemuCapsGet(priv->caps, QEMU_CAPS_NETDEV)) {
875 876 877 878 879 880
                if (qemuMonitorSetLink(priv->mon, net->info.alias, VIR_DOMAIN_NET_INTERFACE_LINK_STATE_DOWN) < 0) {
                    qemuDomainObjExitMonitorWithDriver(driver, vm);
                    virDomainAuditNet(vm, NULL, net, "attach", false);
                    goto try_remove;
                }
            } else {
881
                virReportError(VIR_ERR_OPERATION_FAILED, "%s",
882
                               _("setting of link state not supported: Link is up"));
883 884 885 886 887 888 889
            }

            qemuDomainObjExitMonitorWithDriver(driver, vm);
        }
        /* link set to down */
    }

890
    virDomainAuditNet(vm, NULL, net, "attach", true);
891 892 893 894

    ret = 0;

cleanup:
895 896 897
    if (!ret) {
        vm->def->nets[vm->def->nnets++] = net;
    } else {
898
        if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
899 900 901 902 903 904
            (net->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) &&
            releaseaddr &&
            qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
                                            net->info.addr.pci.slot) < 0)
            VIR_WARN("Unable to release PCI address on NIC");

905
        if (iface_connected) {
906
            virDomainConfNWFilterTeardown(net);
907

908 909 910 911 912
            vport = virDomainNetGetActualVirtPortProfile(net);
            if (vport && vport->virtPortType == VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH)
               ignore_value(virNetDevOpenvswitchRemovePort(
                               virDomainNetGetActualBridgeName(net), net->ifname));
        }
A
Ansis Atteka 已提交
913

914 915
        networkReleaseActualDevice(net);
    }
916 917 918 919 920

    VIR_FREE(nicstr);
    VIR_FREE(netstr);
    VIR_FREE(tapfd_name);
    VIR_FORCE_CLOSE(tapfd);
921 922
    VIR_FREE(vhostfd_name);
    VIR_FORCE_CLOSE(vhostfd);
923 924 925 926 927 928 929 930

    return ret;

try_remove:
    if (!virDomainObjIsActive(vm))
        goto cleanup;

    if (vlan < 0) {
931 932
        if (qemuCapsGet(priv->caps, QEMU_CAPS_NETDEV) &&
            qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
933 934 935
            char *netdev_name;
            if (virAsprintf(&netdev_name, "host%s", net->info.alias) < 0)
                goto no_memory;
936
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
937 938 939 940 941 942
            if (qemuMonitorRemoveNetdev(priv->mon, netdev_name) < 0)
                VIR_WARN("Failed to remove network backend for netdev %s",
                         netdev_name);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            VIR_FREE(netdev_name);
        } else {
943
            VIR_WARN("Unable to remove network backend");
944 945 946 947 948
        }
    } else {
        char *hostnet_name;
        if (virAsprintf(&hostnet_name, "host%s", net->info.alias) < 0)
            goto no_memory;
949
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
        if (qemuMonitorRemoveHostNetwork(priv->mon, vlan, hostnet_name) < 0)
            VIR_WARN("Failed to remove network backend for vlan %d, net %s",
                     vlan, hostnet_name);
        qemuDomainObjExitMonitorWithDriver(driver, vm);
        VIR_FREE(hostnet_name);
    }
    goto cleanup;

no_memory:
    virReportOOMError();
    goto cleanup;
}


int qemuDomainAttachHostPciDevice(struct qemud_driver *driver,
                                  virDomainObjPtr vm,
966
                                  virDomainHostdevDefPtr hostdev)
967 968 969 970 971 972
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret;
    char *devstr = NULL;
    int configfd = -1;
    char *configfd_name = NULL;
973
    bool releaseaddr = false;
974 975 976 977 978 979

    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs+1) < 0) {
        virReportOOMError();
        return -1;
    }

980 981
    if (qemuPrepareHostdevPCIDevices(driver, vm->def->name, vm->def->uuid,
                                     &hostdev, 1) < 0)
982 983
        return -1;

984
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
985 986
        if (qemuAssignDeviceHostdevAlias(vm->def, hostdev, -1) < 0)
            goto error;
987
        if (qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, hostdev->info) < 0)
988
            goto error;
989
        releaseaddr = true;
990
        if (qemuCapsGet(priv->caps, QEMU_CAPS_PCI_CONFIGFD)) {
991 992 993
            configfd = qemuOpenPCIConfig(hostdev);
            if (configfd >= 0) {
                if (virAsprintf(&configfd_name, "fd-%s",
994
                                hostdev->info->alias) < 0) {
995 996 997 998 999 1000 1001
                    virReportOOMError();
                    goto error;
                }
            }
        }

        if (!virDomainObjIsActive(vm)) {
1002 1003
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("guest unexpectedly quit during hotplug"));
1004 1005 1006
            goto error;
        }

1007
        if (!(devstr = qemuBuildPCIHostdevDevStr(hostdev, configfd_name,
1008
                                                 priv->caps)))
1009 1010
            goto error;

1011
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
1012 1013
        ret = qemuMonitorAddDeviceWithFd(priv->mon, devstr,
                                         configfd, configfd_name);
1014 1015
        qemuDomainObjExitMonitorWithDriver(driver, vm);
    } else {
1016
        virDevicePCIAddress guestAddr = hostdev->info->addr.pci;
1017

1018
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
1019 1020 1021 1022 1023
        ret = qemuMonitorAddPCIHostDevice(priv->mon,
                                          &hostdev->source.subsys.u.pci,
                                          &guestAddr);
        qemuDomainObjExitMonitorWithDriver(driver, vm);

1024 1025
        hostdev->info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
        memcpy(&hostdev->info->addr.pci, &guestAddr, sizeof(guestAddr));
1026
    }
1027
    virDomainAuditHostdev(vm, hostdev, "attach", ret == 0);
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    if (ret < 0)
        goto error;

    vm->def->hostdevs[vm->def->nhostdevs++] = hostdev;

    VIR_FREE(devstr);
    VIR_FREE(configfd_name);
    VIR_FORCE_CLOSE(configfd);

    return 0;

error:
1040
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
1041
        (hostdev->info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) &&
1042
        releaseaddr &&
1043
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
1044
                                        hostdev->info->addr.pci.slot) < 0)
1045
        VIR_WARN("Unable to release PCI address on host device");
1046

1047
    qemuDomainReAttachHostdevDevices(driver, vm->def->name, &hostdev, 1);
1048 1049 1050 1051 1052 1053 1054 1055 1056

    VIR_FREE(devstr);
    VIR_FREE(configfd_name);
    VIR_FORCE_CLOSE(configfd);

    return -1;
}


1057 1058 1059 1060 1061 1062
int qemuDomainAttachRedirdevDevice(struct qemud_driver *driver,
                                   virDomainObjPtr vm,
                                   virDomainRedirdevDefPtr redirdev)
{
    int ret;
    qemuDomainObjPrivatePtr priv = vm->privateData;
1063
    virDomainDefPtr def = vm->def;
1064 1065
    char *devstr = NULL;

1066
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
1067 1068
        if (qemuAssignDeviceRedirdevAlias(vm->def, redirdev, -1) < 0)
            goto error;
1069
        if (!(devstr = qemuBuildRedirdevDevStr(def, redirdev, priv->caps)))
1070 1071 1072 1073 1074 1075 1076 1077 1078
            goto error;
    }

    if (VIR_REALLOC_N(vm->def->redirdevs, vm->def->nredirdevs+1) < 0) {
        virReportOOMError();
        goto error;
    }

    qemuDomainObjEnterMonitorWithDriver(driver, vm);
1079
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE))
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
        ret = qemuMonitorAddDevice(priv->mon, devstr);
    else
        goto error;

    qemuDomainObjExitMonitorWithDriver(driver, vm);
    virDomainAuditRedirdev(vm, redirdev, "attach", ret == 0);
    if (ret < 0)
        goto error;

    vm->def->redirdevs[vm->def->nredirdevs++] = redirdev;

    VIR_FREE(devstr);

    return 0;

error:
    VIR_FREE(devstr);
    return -1;

}

1101 1102
int qemuDomainAttachHostUsbDevice(struct qemud_driver *driver,
                                  virDomainObjPtr vm,
1103
                                  virDomainHostdevDefPtr hostdev)
1104 1105 1106 1107 1108
{
    int ret;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *devstr = NULL;

1109
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
1110 1111
        if (qemuAssignDeviceHostdevAlias(vm->def, hostdev, -1) < 0)
            goto error;
1112
        if (!(devstr = qemuBuildUSBHostdevDevStr(hostdev, priv->caps)))
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
            goto error;
    }

    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs+1) < 0) {
        virReportOOMError();
        goto error;
    }

    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        virCgroupPtr cgroup = NULL;
        usbDevice *usb;
1124
        qemuCgroupData data;
1125 1126

        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) !=0 ) {
1127 1128 1129
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to find cgroup for %s"),
                           vm->def->name);
1130 1131 1132 1133 1134 1135 1136
            goto error;
        }

        if ((usb = usbGetDevice(hostdev->source.subsys.u.usb.bus,
                                hostdev->source.subsys.u.usb.device)) == NULL)
            goto error;

1137 1138
        data.vm = vm;
        data.cgroup = cgroup;
1139
        if (usbDeviceFileIterate(usb, qemuSetupHostUsbDeviceCgroup, &data) < 0)
1140 1141 1142
            goto error;
    }

1143
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
1144
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE))
1145 1146 1147 1148 1149 1150
        ret = qemuMonitorAddDevice(priv->mon, devstr);
    else
        ret = qemuMonitorAddUSBDeviceExact(priv->mon,
                                           hostdev->source.subsys.u.usb.bus,
                                           hostdev->source.subsys.u.usb.device);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
1151
    virDomainAuditHostdev(vm, hostdev, "attach", ret == 0);
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
    if (ret < 0)
        goto error;

    vm->def->hostdevs[vm->def->nhostdevs++] = hostdev;

    VIR_FREE(devstr);

    return 0;

error:
    VIR_FREE(devstr);
    return -1;
}

int qemuDomainAttachHostDevice(struct qemud_driver *driver,
                               virDomainObjPtr vm,
1168
                               virDomainHostdevDefPtr hostdev)
1169
{
1170 1171 1172
    usbDeviceList *list;
    usbDevice *usb = NULL;

1173
    if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
1174 1175 1176
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev mode '%s' not supported"),
                       virDomainHostdevModeTypeToString(hostdev->mode));
1177 1178 1179
        return -1;
    }

1180 1181
    if (!(list = usbDeviceListNew()))
        goto cleanup;
1182

1183 1184 1185 1186 1187
    if (hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
        unsigned vendor = hostdev->source.subsys.u.usb.vendor;
        unsigned product = hostdev->source.subsys.u.usb.product;
        unsigned bus = hostdev->source.subsys.u.usb.bus;
        unsigned device = hostdev->source.subsys.u.usb.device;
1188

1189 1190
        if (vendor && bus) {
            usb = usbFindDevice(vendor, product, bus, device);
1191

1192 1193 1194 1195
        } else if (vendor && !bus) {
            usbDeviceList *devs = usbFindDeviceByVendor(vendor, product);
            if (!devs)
                goto cleanup;
1196

1197
            if (usbDeviceListCount(devs) > 1) {
1198 1199 1200
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("multiple USB devices for %x:%x, "
                                 "use <address> to specify one"), vendor, product);
1201 1202 1203 1204 1205 1206
                usbDeviceListFree(devs);
                goto cleanup;
            }
            usb = usbDeviceListGet(devs, 0);
            usbDeviceListSteal(devs, usb);
            usbDeviceListFree(devs);
1207

1208 1209
            hostdev->source.subsys.u.usb.bus = usbDeviceGetBus(usb);
            hostdev->source.subsys.u.usb.device = usbDeviceGetDevno(usb);
1210

1211 1212 1213
        } else if (!vendor && bus) {
            usb = usbFindDeviceByBus(bus, device);
        }
1214

1215 1216 1217 1218 1219
        if (!usb)
            goto cleanup;

        if (usbDeviceListAdd(list, usb) < 0) {
            usbFreeDevice(usb);
M
Marc-André Lureau 已提交
1220
            usb = NULL;
1221 1222 1223
            goto cleanup;
        }

1224 1225
        if (qemuPrepareHostdevUSBDevices(driver, vm->def->name, list) < 0) {
            usb = NULL;
1226
            goto cleanup;
1227
        }
1228 1229 1230

        usbDeviceListSteal(list, usb);
    }
1231

1232
    if (virSecurityManagerSetHostdevLabel(driver->securityManager,
1233
                                          vm->def, hostdev) < 0)
1234
        goto cleanup;
1235 1236 1237 1238

    switch (hostdev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
        if (qemuDomainAttachHostPciDevice(driver, vm,
1239
                                          hostdev) < 0)
1240 1241 1242 1243 1244
            goto error;
        break;

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
        if (qemuDomainAttachHostUsbDevice(driver, vm,
1245
                                          hostdev) < 0)
1246 1247 1248 1249
            goto error;
        break;

    default:
1250 1251 1252
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(hostdev->source.subsys.type));
1253 1254 1255
        goto error;
    }

1256
    usbDeviceListFree(list);
1257 1258 1259
    return 0;

error:
1260
    if (virSecurityManagerRestoreHostdevLabel(driver->securityManager,
1261
                                              vm->def, hostdev) < 0)
1262
        VIR_WARN("Unable to restore host device labelling on hotplug fail");
1263

1264 1265
cleanup:
    usbDeviceListFree(list);
1266 1267
    if (usb)
        usbDeviceListSteal(driver->activeUsbHostdevs, usb);
1268 1269 1270
    return -1;
}

1271 1272 1273 1274 1275 1276
static virDomainNetDefPtr qemuDomainFindNet(virDomainObjPtr vm,
                                            virDomainNetDefPtr dev)
{
    int i;

    for (i = 0; i < vm->def->nnets; i++) {
1277
        if (virMacAddrCmp(&vm->def->nets[i]->mac, &dev->mac) == 0)
1278 1279 1280 1281 1282 1283
            return vm->def->nets[i];
    }

    return NULL;
}

1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
static
int qemuDomainChangeNetBridge(virDomainObjPtr vm,
                              virDomainNetDefPtr olddev,
                              virDomainNetDefPtr newdev)
{
    int ret = -1;
    char *oldbridge = olddev->data.bridge.brname;
    char *newbridge = newdev->data.bridge.brname;

    VIR_DEBUG("Change bridge for interface %s: %s -> %s",
              olddev->ifname, oldbridge, newbridge);

    if (virNetDevExists(newbridge) != 1) {
1297 1298
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("bridge %s doesn't exist"), newbridge);
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
        return -1;
    }

    if (oldbridge) {
        ret = virNetDevBridgeRemovePort(oldbridge, olddev->ifname);
        virDomainAuditNet(vm, olddev, NULL, "detach", ret == 0);
        if (ret < 0)
            return -1;
    }

    /* move newbridge into olddev now so Audit log is correct */
    olddev->data.bridge.brname = newbridge;
    ret = virNetDevBridgeAddPort(newbridge, olddev->ifname);
    virDomainAuditNet(vm, NULL, olddev, "attach", ret == 0);
    if (ret < 0) {
        /* restore oldbridge to olddev */
        olddev->data.bridge.brname = oldbridge;
        ret = virNetDevBridgeAddPort(oldbridge, olddev->ifname);
        virDomainAuditNet(vm, NULL, olddev, "attach", ret == 0);
        if (ret < 0) {
1319
            virReportError(VIR_ERR_OPERATION_FAILED,
1320
                           _("unable to recover former state by adding port "
1321
                             "to bridge %s"), oldbridge);
1322 1323 1324 1325 1326 1327 1328 1329 1330
        }
        return -1;
    }
    /* oldbridge no longer needed, and newbridge moved to olddev */
    VIR_FREE(oldbridge);
    newdev->data.bridge.brname = NULL;
    return 0;
}

1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
int qemuDomainChangeNetLinkState(struct qemud_driver *driver,
                                 virDomainObjPtr vm,
                                 virDomainNetDefPtr dev,
                                 int linkstate)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;

    VIR_DEBUG("dev: %s, state: %d", dev->info.alias, linkstate);

    if (!dev->info.alias) {
1342 1343
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("can't change link state: device alias not found"));
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
        return -1;
    }

    qemuDomainObjEnterMonitorWithDriver(driver, vm);

    ret = qemuMonitorSetLink(priv->mon, dev->info.alias, linkstate);
    if (ret < 0)
        goto cleanup;

    /* modify the device configuration */
    dev->linkstate = linkstate;

cleanup:
    qemuDomainObjExitMonitorWithDriver(driver, vm);

    return ret;
}

int qemuDomainChangeNet(struct qemud_driver *driver,
                        virDomainObjPtr vm,
                        virDomainPtr dom ATTRIBUTE_UNUSED,
                        virDomainNetDefPtr dev)

{
    virDomainNetDefPtr olddev = qemuDomainFindNet(vm, dev);
    int ret = 0;

    if (!olddev) {
1372 1373
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("cannot find existing network device to modify"));
1374 1375 1376 1377
        return -1;
    }

    if (olddev->type != dev->type) {
1378 1379
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("cannot change network interface type"));
1380 1381 1382
        return -1;
    }

1383 1384 1385 1386 1387
    if (!virNetDevVPortProfileEqual(olddev->virtPortProfile, dev->virtPortProfile)) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("cannot change <virtualport> settings"));
    }

1388 1389 1390 1391 1392 1393
    switch (olddev->type) {
    case VIR_DOMAIN_NET_TYPE_USER:
        break;

    case VIR_DOMAIN_NET_TYPE_ETHERNET:
        if (STRNEQ_NULLABLE(olddev->data.ethernet.dev, dev->data.ethernet.dev) ||
1394
            STRNEQ_NULLABLE(olddev->script, dev->script) ||
1395
            STRNEQ_NULLABLE(olddev->data.ethernet.ipaddr, dev->data.ethernet.ipaddr)) {
1396 1397
            virReportError(VIR_ERR_NO_SUPPORT, "%s",
                           _("cannot modify ethernet network device configuration"));
1398 1399 1400 1401 1402 1403 1404 1405 1406
            return -1;
        }
        break;

    case VIR_DOMAIN_NET_TYPE_SERVER:
    case VIR_DOMAIN_NET_TYPE_CLIENT:
    case VIR_DOMAIN_NET_TYPE_MCAST:
        if (STRNEQ_NULLABLE(olddev->data.socket.address, dev->data.socket.address) ||
            olddev->data.socket.port != dev->data.socket.port) {
1407 1408
            virReportError(VIR_ERR_NO_SUPPORT, "%s",
                           _("cannot modify network socket device configuration"));
1409 1410 1411 1412 1413 1414
            return -1;
        }
        break;

    case VIR_DOMAIN_NET_TYPE_NETWORK:
        if (STRNEQ_NULLABLE(olddev->data.network.name, dev->data.network.name) ||
1415
            STRNEQ_NULLABLE(olddev->data.network.portgroup, dev->data.network.portgroup)) {
1416 1417
            virReportError(VIR_ERR_NO_SUPPORT, "%s",
                           _("cannot modify network device configuration"));
1418 1419 1420 1421 1422
            return -1;
        }

        break;

1423
    case VIR_DOMAIN_NET_TYPE_BRIDGE:
1424
       /* allow changing brname */
1425 1426
       break;

1427 1428
    case VIR_DOMAIN_NET_TYPE_INTERNAL:
        if (STRNEQ_NULLABLE(olddev->data.internal.name, dev->data.internal.name)) {
1429 1430
            virReportError(VIR_ERR_NO_SUPPORT, "%s",
                           _("cannot modify internal network device configuration"));
1431 1432 1433 1434 1435 1436
            return -1;
        }
        break;

    case VIR_DOMAIN_NET_TYPE_DIRECT:
        if (STRNEQ_NULLABLE(olddev->data.direct.linkdev, dev->data.direct.linkdev) ||
1437
            olddev->data.direct.mode != dev->data.direct.mode) {
1438 1439
            virReportError(VIR_ERR_NO_SUPPORT, "%s",
                           _("cannot modify direct network device configuration"));
1440 1441 1442 1443 1444
            return -1;
        }
        break;

    default:
1445 1446 1447
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unable to change config on '%s' network type"),
                       virDomainNetTypeToString(dev->type));
1448 1449 1450 1451 1452 1453 1454
        break;

    }

    /* all other unmodifiable parameters */
    if (STRNEQ_NULLABLE(olddev->model, dev->model) ||
        STRNEQ_NULLABLE(olddev->filter, dev->filter)) {
1455 1456
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("cannot modify network device configuration"));
1457 1458 1459 1460 1461 1462
        return -1;
    }

    /* check if device name has been set, if no, retain the autogenerated one */
    if (dev->ifname &&
        STRNEQ_NULLABLE(olddev->ifname, dev->ifname)) {
1463 1464
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("cannot modify network device configuration"));
1465 1466 1467
        return -1;
    }

1468 1469 1470 1471 1472 1473 1474
    if (olddev->type == VIR_DOMAIN_NET_TYPE_BRIDGE
        && STRNEQ_NULLABLE(olddev->data.bridge.brname,
                           dev->data.bridge.brname)) {
        if ((ret = qemuDomainChangeNetBridge(vm, olddev, dev)) < 0)
            return ret;
    }

1475 1476 1477 1478 1479 1480 1481 1482 1483
    if (olddev->linkstate != dev->linkstate) {
        if ((ret = qemuDomainChangeNetLinkState(driver, vm, olddev, dev->linkstate)) < 0)
            return ret;
    }

    return ret;
}


1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504

static virDomainGraphicsDefPtr qemuDomainFindGraphics(virDomainObjPtr vm,
                                                      virDomainGraphicsDefPtr dev)
{
    int i;

    for (i = 0 ; i < vm->def->ngraphics ; i++) {
        if (vm->def->graphics[i]->type == dev->type)
            return vm->def->graphics[i];
    }

    return NULL;
}


int
qemuDomainChangeGraphics(struct qemud_driver *driver,
                         virDomainObjPtr vm,
                         virDomainGraphicsDefPtr dev)
{
    virDomainGraphicsDefPtr olddev = qemuDomainFindGraphics(vm, dev);
1505
    const char *oldListenAddr, *newListenAddr;
1506
    const char *oldListenNetwork, *newListenNetwork;
1507 1508 1509
    int ret = -1;

    if (!olddev) {
1510 1511
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot find existing graphics device to modify"));
1512 1513 1514
        return -1;
    }

1515 1516
    oldListenAddr = virDomainGraphicsListenGetAddress(olddev, 0);
    newListenAddr = virDomainGraphicsListenGetAddress(dev, 0);
1517 1518
    oldListenNetwork = virDomainGraphicsListenGetNetwork(olddev, 0);
    newListenNetwork = virDomainGraphicsListenGetNetwork(dev, 0);
1519

1520 1521 1522
    switch (dev->type) {
    case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
        if ((olddev->data.vnc.autoport != dev->data.vnc.autoport) ||
E
Eric Blake 已提交
1523 1524
            (!dev->data.vnc.autoport &&
             (olddev->data.vnc.port != dev->data.vnc.port))) {
1525 1526
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change port settings on vnc graphics"));
1527 1528
            return -1;
        }
1529
        if (STRNEQ_NULLABLE(oldListenAddr,newListenAddr)) {
1530 1531
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change listen address setting on vnc graphics"));
1532 1533
            return -1;
        }
1534
        if (STRNEQ_NULLABLE(oldListenNetwork,newListenNetwork)) {
1535 1536
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change listen network setting on vnc graphics"));
1537 1538
            return -1;
        }
1539
        if (STRNEQ_NULLABLE(olddev->data.vnc.keymap, dev->data.vnc.keymap)) {
1540 1541
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change keymap setting on vnc graphics"));
1542 1543 1544
            return -1;
        }

1545 1546 1547
        /* If a password lifetime was, or is set, or action if connected has
         * changed, then we must always run, even if new password matches
         * old password */
1548 1549
        if (olddev->data.vnc.auth.expires ||
            dev->data.vnc.auth.expires ||
1550
            olddev->data.vnc.auth.connected != dev->data.vnc.auth.connected ||
E
Eric Blake 已提交
1551 1552 1553 1554 1555 1556 1557 1558
            STRNEQ_NULLABLE(olddev->data.vnc.auth.passwd,
                            dev->data.vnc.auth.passwd)) {
            VIR_DEBUG("Updating password on VNC server %p %p",
                      dev->data.vnc.auth.passwd, driver->vncPassword);
            ret = qemuDomainChangeGraphicsPasswords(driver, vm,
                                                    VIR_DOMAIN_GRAPHICS_TYPE_VNC,
                                                    &dev->data.vnc.auth,
                                                    driver->vncPassword);
1559 1560
            if (ret < 0)
                return ret;
1561 1562 1563 1564 1565

            /* Steal the new dev's  char * reference */
            VIR_FREE(olddev->data.vnc.auth.passwd);
            olddev->data.vnc.auth.passwd = dev->data.vnc.auth.passwd;
            dev->data.vnc.auth.passwd = NULL;
1566 1567
            olddev->data.vnc.auth.validTo = dev->data.vnc.auth.validTo;
            olddev->data.vnc.auth.expires = dev->data.vnc.auth.expires;
1568
            olddev->data.vnc.auth.connected = dev->data.vnc.auth.connected;
1569 1570 1571 1572 1573
        } else {
            ret = 0;
        }
        break;

1574 1575
    case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
        if ((olddev->data.spice.autoport != dev->data.spice.autoport) ||
E
Eric Blake 已提交
1576 1577 1578 1579
            (!dev->data.spice.autoport &&
             (olddev->data.spice.port != dev->data.spice.port)) ||
            (!dev->data.spice.autoport &&
             (olddev->data.spice.tlsPort != dev->data.spice.tlsPort))) {
1580 1581
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change port settings on spice graphics"));
1582 1583
            return -1;
        }
1584
        if (STRNEQ_NULLABLE(oldListenAddr, newListenAddr)) {
1585 1586
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change listen address setting on spice graphics"));
1587 1588
            return -1;
        }
1589
        if (STRNEQ_NULLABLE(oldListenNetwork, newListenNetwork)) {
1590 1591
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change listen network setting on spice graphics"));
1592 1593
            return -1;
        }
E
Eric Blake 已提交
1594 1595
        if (STRNEQ_NULLABLE(olddev->data.spice.keymap,
                            dev->data.spice.keymap)) {
1596
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1597 1598 1599 1600
                            _("cannot change keymap setting on spice graphics"));
            return -1;
        }

1601 1602 1603 1604 1605
        /* We must reset the password if it has changed but also if:
         * - password lifetime is or was set
         * - the requested action has changed
         * - the action is "disconnect"
         */
1606 1607
        if (olddev->data.spice.auth.expires ||
            dev->data.spice.auth.expires ||
1608
            olddev->data.spice.auth.connected != dev->data.spice.auth.connected ||
1609 1610
            dev->data.spice.auth.connected ==
            VIR_DOMAIN_GRAPHICS_AUTH_CONNECTED_DISCONNECT ||
E
Eric Blake 已提交
1611 1612 1613 1614 1615 1616 1617 1618 1619
            STRNEQ_NULLABLE(olddev->data.spice.auth.passwd,
                            dev->data.spice.auth.passwd)) {
            VIR_DEBUG("Updating password on SPICE server %p %p",
                      dev->data.spice.auth.passwd, driver->spicePassword);
            ret = qemuDomainChangeGraphicsPasswords(driver, vm,
                                                    VIR_DOMAIN_GRAPHICS_TYPE_SPICE,
                                                    &dev->data.spice.auth,
                                                    driver->spicePassword);

1620 1621 1622
            if (ret < 0)
                return ret;

E
Eric Blake 已提交
1623
            /* Steal the new dev's char * reference */
1624 1625 1626 1627 1628
            VIR_FREE(olddev->data.spice.auth.passwd);
            olddev->data.spice.auth.passwd = dev->data.spice.auth.passwd;
            dev->data.spice.auth.passwd = NULL;
            olddev->data.spice.auth.validTo = dev->data.spice.auth.validTo;
            olddev->data.spice.auth.expires = dev->data.spice.auth.expires;
1629
            olddev->data.spice.auth.connected = dev->data.spice.auth.connected;
1630
        } else {
1631
            VIR_DEBUG("Not updating since password didn't change");
1632 1633
            ret = 0;
        }
E
Eric Blake 已提交
1634
        break;
1635

1636
    default:
1637 1638 1639
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unable to change config on '%s' graphics type"),
                       virDomainGraphicsTypeToString(dev->type));
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
        break;
    }

    return ret;
}


static inline int qemuFindDisk(virDomainDefPtr def, const char *dst)
{
    int i;

    for (i = 0 ; i < def->ndisks ; i++) {
        if (STREQ(def->disks[i]->dst, dst)) {
            return i;
        }
    }

    return -1;
}

1660
static int qemuComparePCIDevice(virDomainDefPtr def ATTRIBUTE_UNUSED,
1661
                                virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
1662
                                virDomainDeviceInfoPtr info1,
1663 1664
                                void *opaque)
{
1665
    virDomainDeviceInfoPtr info2 = opaque;
1666

1667 1668
    if (info1->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI ||
        info2->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)
1669 1670
        return 0;

1671 1672
    if (info1->addr.pci.slot == info2->addr.pci.slot &&
        info1->addr.pci.function != info2->addr.pci.function)
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
        return -1;
    return 0;
}

static bool qemuIsMultiFunctionDevice(virDomainDefPtr def,
                                      virDomainDeviceInfoPtr dev)
{
    if (virDomainDeviceInfoIterate(def, qemuComparePCIDevice, dev) < 0)
        return true;
    return false;
}

1685 1686 1687

int qemuDomainDetachPciDiskDevice(struct qemud_driver *driver,
                                  virDomainObjPtr vm,
1688
                                  virDomainDeviceDefPtr dev)
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
{
    int i, ret = -1;
    virDomainDiskDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virCgroupPtr cgroup = NULL;
    char *drivestr = NULL;

    i = qemuFindDisk(vm->def, dev->data.disk->dst);

    if (i < 0) {
1699 1700
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("disk %s not found"), dev->data.disk->dst);
1701 1702 1703 1704 1705
        goto cleanup;
    }

    detach = vm->def->disks[i];

1706
    if (qemuIsMultiFunctionDevice(vm->def, &detach->info)) {
1707 1708 1709
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %s"),
                       dev->data.disk->dst);
1710 1711 1712
        goto cleanup;
    }

1713 1714
    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) != 0) {
1715 1716 1717
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to find cgroup for %s"),
                           vm->def->name);
1718 1719 1720 1721 1722 1723
            goto cleanup;
        }
    }

    if (!virDomainDeviceAddressIsValid(&detach->info,
                                       VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
1724 1725
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("device cannot be detached without a PCI address"));
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
        goto cleanup;
    }

    /* build the actual drive id string as the disk->info.alias doesn't
     * contain the QEMU_DRIVE_HOST_PREFIX that is passed to qemu */
    if (virAsprintf(&drivestr, "%s%s",
                    QEMU_DRIVE_HOST_PREFIX, detach->info.alias) < 0) {
        virReportOOMError();
        goto cleanup;
    }

1737
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
1738
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
1739
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
1740
            qemuDomainObjExitMonitorWithDriver(driver, vm);
1741
            virDomainAuditDisk(vm, detach->src, NULL, "detach", false);
1742 1743 1744 1745 1746
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
1747
            qemuDomainObjExitMonitorWithDriver(driver, vm);
1748
            virDomainAuditDisk(vm, detach->src, NULL, "detach", false);
1749 1750 1751 1752 1753 1754 1755 1756 1757
            goto cleanup;
        }
    }

    /* disconnect guest from host device */
    qemuMonitorDriveDel(priv->mon, drivestr);

    qemuDomainObjExitMonitorWithDriver(driver, vm);

1758
    virDomainAuditDisk(vm, detach->src, NULL, "detach", true);
1759

1760
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
1761 1762
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
                                        detach->info.addr.pci.slot) < 0)
1763 1764 1765 1766 1767 1768
        VIR_WARN("Unable to release PCI address on %s", dev->data.disk->src);

    virDomainDiskRemove(vm->def, i);

    virDomainDiskDefFree(detach);

1769
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
1770
                                            vm->def, dev->data.disk) < 0)
1771 1772 1773
        VIR_WARN("Unable to restore security label on %s", dev->data.disk->src);

    if (cgroup != NULL) {
1774
        if (qemuTeardownDiskCgroup(driver, vm, cgroup, dev->data.disk) < 0)
1775 1776 1777 1778
            VIR_WARN("Failed to teardown cgroup for disk path %s",
                     NULLSTR(dev->data.disk->src));
    }

1779 1780 1781
    if (virDomainLockDiskDetach(driver->lockManager, vm, dev->data.disk) < 0)
        VIR_WARN("Unable to release lock on %s", dev->data.disk->src);

1782 1783 1784
    ret = 0;

cleanup:
1785
    virCgroupFree(&cgroup);
1786 1787 1788 1789
    VIR_FREE(drivestr);
    return ret;
}

1790 1791
int qemuDomainDetachDiskDevice(struct qemud_driver *driver,
                               virDomainObjPtr vm,
1792
                               virDomainDeviceDefPtr dev)
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
{
    int i, ret = -1;
    virDomainDiskDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virCgroupPtr cgroup = NULL;
    char *drivestr = NULL;

    i = qemuFindDisk(vm->def, dev->data.disk->dst);

    if (i < 0) {
1803 1804
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("disk %s not found"), dev->data.disk->dst);
1805 1806 1807
        goto cleanup;
    }

1808
    if (!qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
1809 1810 1811
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Underlying qemu does not support %s disk removal"),
                       virDomainDiskBusTypeToString(dev->data.disk->bus));
1812 1813 1814 1815 1816 1817 1818
        goto cleanup;
    }

    detach = vm->def->disks[i];

    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) != 0) {
1819 1820 1821
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to find cgroup for %s"),
                           vm->def->name);
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
            goto cleanup;
        }
    }

    /* build the actual drive id string as the disk->info.alias doesn't
     * contain the QEMU_DRIVE_HOST_PREFIX that is passed to qemu */
    if (virAsprintf(&drivestr, "%s%s",
                    QEMU_DRIVE_HOST_PREFIX, detach->info.alias) < 0) {
        virReportOOMError();
        goto cleanup;
    }

1834
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
1835
    if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
1836
        qemuDomainObjExitMonitorWithDriver(driver, vm);
1837
        virDomainAuditDisk(vm, detach->src, NULL, "detach", false);
1838 1839 1840 1841 1842 1843 1844 1845
        goto cleanup;
    }

    /* disconnect guest from host device */
    qemuMonitorDriveDel(priv->mon, drivestr);

    qemuDomainObjExitMonitorWithDriver(driver, vm);

1846
    virDomainAuditDisk(vm, detach->src, NULL, "detach", true);
1847 1848 1849 1850 1851

    virDomainDiskRemove(vm->def, i);

    virDomainDiskDefFree(detach);

1852
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
1853
                                            vm->def, dev->data.disk) < 0)
1854 1855 1856
        VIR_WARN("Unable to restore security label on %s", dev->data.disk->src);

    if (cgroup != NULL) {
1857
        if (qemuTeardownDiskCgroup(driver, vm, cgroup, dev->data.disk) < 0)
1858 1859 1860 1861
            VIR_WARN("Failed to teardown cgroup for disk path %s",
                     NULLSTR(dev->data.disk->src));
    }

1862 1863 1864
    if (virDomainLockDiskDetach(driver->lockManager, vm, dev->data.disk) < 0)
        VIR_WARN("Unable to release lock on disk %s", dev->data.disk->src);

1865 1866 1867 1868 1869 1870 1871 1872
    ret = 0;

cleanup:
    VIR_FREE(drivestr);
    virCgroupFree(&cgroup);
    return ret;
}

1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922
static bool qemuDomainDiskControllerIsBusy(virDomainObjPtr vm,
                                           virDomainControllerDefPtr detach)
{
    int i;
    virDomainDiskDefPtr disk;

    for (i = 0; i < vm->def->ndisks; i++) {
        disk = vm->def->disks[i];
        if (disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE)
            /* the disk does not use disk controller */
            continue;

        /* check whether the disk uses this type controller */
        if (disk->bus == VIR_DOMAIN_DISK_BUS_IDE &&
            detach->type != VIR_DOMAIN_CONTROLLER_TYPE_IDE)
            continue;
        if (disk->bus == VIR_DOMAIN_DISK_BUS_FDC &&
            detach->type != VIR_DOMAIN_CONTROLLER_TYPE_FDC)
            continue;
        if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI &&
            detach->type != VIR_DOMAIN_CONTROLLER_TYPE_SCSI)
            continue;

        if (disk->info.addr.drive.controller == detach->idx)
            return true;
    }

    return false;
}

static bool qemuDomainControllerIsBusy(virDomainObjPtr vm,
                                       virDomainControllerDefPtr detach)
{
    switch (detach->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_IDE:
    case VIR_DOMAIN_CONTROLLER_TYPE_FDC:
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
        return qemuDomainDiskControllerIsBusy(vm, detach);

    case VIR_DOMAIN_CONTROLLER_TYPE_SATA:
    case VIR_DOMAIN_CONTROLLER_TYPE_VIRTIO_SERIAL:
    case VIR_DOMAIN_CONTROLLER_TYPE_CCID:
    default:
        /* libvirt does not support sata controller, and does not support to
         * detach virtio and smart card controller.
         */
        return true;
    }
}

1923 1924
int qemuDomainDetachPciControllerDevice(struct qemud_driver *driver,
                                        virDomainObjPtr vm,
1925
                                        virDomainDeviceDefPtr dev)
1926
{
1927
    int idx, ret = -1;
1928 1929 1930
    virDomainControllerDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;

1931 1932 1933
    if ((idx = virDomainControllerFind(vm->def,
                                       dev->data.controller->type,
                                       dev->data.controller->idx)) < 0) {
1934 1935 1936 1937
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("disk controller %s:%d not found"),
                       virDomainControllerTypeToString(dev->data.controller->type),
                       dev->data.controller->idx);
1938 1939 1940
        goto cleanup;
    }

1941 1942
    detach = vm->def->controllers[idx];

1943 1944
    if (!virDomainDeviceAddressIsValid(&detach->info,
                                       VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
1945 1946
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("device cannot be detached without a PCI address"));
1947 1948 1949
        goto cleanup;
    }

1950
    if (qemuIsMultiFunctionDevice(vm->def, &detach->info)) {
1951 1952 1953
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %s"),
                       dev->data.disk->dst);
1954 1955 1956
        goto cleanup;
    }

1957
    if (qemuDomainControllerIsBusy(vm, detach)) {
1958 1959
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("device cannot be detached: device is busy"));
1960 1961 1962
        goto cleanup;
    }

1963
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
1964 1965 1966 1967
        if (qemuAssignDeviceControllerAlias(detach) < 0)
            goto cleanup;
    }

1968
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
1969
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
1970
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias)) {
1971
            qemuDomainObjExitMonitorWithDriver(driver, vm);
1972 1973 1974 1975 1976
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
1977
            qemuDomainObjExitMonitorWithDriver(driver, vm);
1978 1979 1980 1981 1982
            goto cleanup;
        }
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);

1983 1984
    virDomainControllerRemove(vm->def, idx);
    virDomainControllerDefFree(detach);
1985

1986
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
1987 1988
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
                                        detach->info.addr.pci.slot) < 0)
1989
        VIR_WARN("Unable to release PCI address on controller");
1990 1991 1992 1993 1994 1995 1996

    ret = 0;

cleanup:
    return ret;
}

1997 1998 1999
static int
qemuDomainDetachHostPciDevice(struct qemud_driver *driver,
                              virDomainObjPtr vm,
2000
                              virDomainHostdevDefPtr detach)
2001 2002
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2003 2004
    virDomainHostdevSubsysPtr subsys = &detach->source.subsys;
    int ret;
2005
    pciDevice *pci;
2006
    pciDevice *activePci;
2007

2008
    if (qemuIsMultiFunctionDevice(vm->def, detach->info)) {
2009 2010 2011 2012
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %.4x:%.2x:%.2x.%.1x"),
                       subsys->u.pci.domain, subsys->u.pci.bus,
                       subsys->u.pci.slot,   subsys->u.pci.function);
2013
        return -1;
2014 2015
    }

2016
    if (!virDomainDeviceAddressIsValid(detach->info,
2017
                                       VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
2018 2019
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("device cannot be detached without a PCI address"));
2020 2021 2022
        return -1;
    }

2023
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2024
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
2025
        ret = qemuMonitorDelDevice(priv->mon, detach->info->alias);
2026
    } else {
2027
        ret = qemuMonitorRemovePCIDevice(priv->mon, &detach->info->addr.pci);
2028 2029
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);
2030
    virDomainAuditHostdev(vm, detach, "detach", ret == 0);
2031 2032
    if (ret < 0)
        return -1;
2033

2034 2035 2036 2037 2038 2039 2040
    /*
     * For SRIOV net host devices, unset mac and port profile before
     * reset and reattach device
     */
     if (detach->parent.data.net)
         qemuDomainHostdevNetConfigRestore(detach, driver->stateDir);

2041 2042
    pci = pciGetDevice(subsys->u.pci.domain, subsys->u.pci.bus,
                       subsys->u.pci.slot,   subsys->u.pci.function);
2043 2044
    if (pci) {
        activePci = pciDeviceListSteal(driver->activePciHostdevs, pci);
2045 2046 2047
        if (activePci &&
            pciResetDevice(activePci, driver->activePciHostdevs,
                           driver->inactivePciHostdevs) == 0) {
2048
            qemuReattachPciDevice(activePci, driver);
2049 2050 2051
        } else {
            /* reset of the device failed, treat it as if it was returned */
            pciFreeDevice(activePci);
2052
            ret = -1;
2053
        }
2054
        pciFreeDevice(pci);
2055 2056
    } else {
        ret = -1;
2057 2058
    }

2059
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
2060
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
2061
                                        detach->info->addr.pci.slot) < 0)
2062
        VIR_WARN("Unable to release PCI address on host device");
2063 2064 2065 2066

    return ret;
}

2067 2068 2069
static int
qemuDomainDetachHostUsbDevice(struct qemud_driver *driver,
                              virDomainObjPtr vm,
2070
                              virDomainHostdevDefPtr detach)
2071 2072
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2073
    virDomainHostdevSubsysPtr subsys = &detach->source.subsys;
2074
    usbDevice *usb;
2075
    int ret;
2076

2077
    if (!detach->info->alias) {
2078 2079
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("device cannot be detached without a device alias"));
2080 2081 2082
        return -1;
    }

2083
    if (!qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
2084 2085
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("device cannot be detached with this QEMU version"));
2086 2087 2088
        return -1;
    }

2089
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2090
    ret = qemuMonitorDelDevice(priv->mon, detach->info->alias);
2091
    qemuDomainObjExitMonitorWithDriver(driver, vm);
2092
    virDomainAuditHostdev(vm, detach, "detach", ret == 0);
2093 2094
    if (ret < 0)
        return -1;
2095

2096
    usb = usbGetDevice(subsys->u.usb.bus, subsys->u.usb.device);
2097 2098 2099 2100 2101
    if (usb) {
        usbDeviceListDel(driver->activeUsbHostdevs, usb);
        usbFreeDevice(usb);
    } else {
        VIR_WARN("Unable to find device %03d.%03d in list of used USB devices",
2102
                 subsys->u.usb.bus, subsys->u.usb.device);
2103 2104 2105 2106
    }
    return ret;
}

2107 2108 2109 2110 2111
static
int qemuDomainDetachThisHostDevice(struct qemud_driver *driver,
                                   virDomainObjPtr vm,
                                   virDomainHostdevDefPtr detach,
                                   int idx)
2112
{
2113
    int ret = -1;
2114

2115 2116 2117 2118 2119 2120 2121 2122 2123
    if (idx < 0) {
        /* caller didn't know index of hostdev in hostdevs list, so we
         * need to find it.
         */
        for (idx = 0; idx < vm->def->nhostdevs; idx++) {
            if (vm->def->hostdevs[idx] == detach)
                break;
        }
        if (idx >= vm->def->nhostdevs) {
2124 2125 2126
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("device not found in hostdevs list (%d entries)"),
                           vm->def->nhostdevs);
2127 2128
            return ret;
        }
2129 2130
    }

2131
    switch (detach->source.subsys.type) {
2132
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
2133 2134
        ret = qemuDomainDetachHostPciDevice(driver, vm, detach);
        break;
2135
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
2136
        ret = qemuDomainDetachHostUsbDevice(driver, vm, detach);
2137 2138
        break;
    default:
2139 2140 2141
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(detach->source.subsys.type));
2142 2143 2144
        return -1;
    }

2145 2146 2147 2148 2149 2150 2151
    if (!ret) {
        if (virSecurityManagerRestoreHostdevLabel(driver->securityManager,
                                                  vm->def, detach) < 0) {
            VIR_WARN("Failed to restore host device labelling");
        }
        virDomainHostdevRemove(vm->def, idx);
        virDomainHostdevDefFree(detach);
2152
    }
2153 2154
    return ret;
}
2155

2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166
/* search for a hostdev matching dev and detach it */
int qemuDomainDetachHostDevice(struct qemud_driver *driver,
                               virDomainObjPtr vm,
                               virDomainDeviceDefPtr dev)
{
    virDomainHostdevDefPtr hostdev = dev->data.hostdev;
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
    virDomainHostdevDefPtr detach = NULL;
    int idx;

    if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
2167 2168 2169
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev mode '%s' not supported"),
                       virDomainHostdevModeTypeToString(hostdev->mode));
2170 2171 2172 2173 2174 2175 2176 2177
        return -1;
    }

    idx = virDomainHostdevFind(vm->def, hostdev, &detach);

    if (idx < 0) {
        switch(subsys->type) {
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
2178 2179 2180 2181
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("host pci device %.4x:%.2x:%.2x.%.1x not found"),
                           subsys->u.pci.domain, subsys->u.pci.bus,
                           subsys->u.pci.slot, subsys->u.pci.function);
2182 2183 2184
            break;
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
            if (subsys->u.usb.bus && subsys->u.usb.device) {
2185 2186 2187
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("host usb device %03d.%03d not found"),
                               subsys->u.usb.bus, subsys->u.usb.device);
2188
            } else {
2189 2190 2191
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("host usb device vendor=0x%.4x product=0x%.4x not found"),
                               subsys->u.usb.vendor, subsys->u.usb.product);
2192 2193 2194
            }
            break;
        default:
2195 2196
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected hostdev type %d"), subsys->type);
2197 2198 2199 2200 2201
            break;
        }
        return -1;
    }

2202 2203 2204 2205 2206 2207 2208
    /* If this is a network hostdev, we need to use the higher-level detach
     * function so that mac address / virtualport are reset
     */
    if (detach->parent.type == VIR_DOMAIN_DEVICE_NET)
        return qemuDomainDetachNetDevice(driver, vm, &detach->parent);
    else
        return qemuDomainDetachThisHostDevice(driver, vm, detach, idx);
2209 2210
}

2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
int
qemuDomainDetachNetDevice(struct qemud_driver *driver,
                          virDomainObjPtr vm,
                          virDomainDeviceDefPtr dev)
{
    int i, ret = -1;
    virDomainNetDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int vlan;
    char *hostnet_name = NULL;
    virNetDevVPortProfilePtr vport = NULL;

    for (i = 0 ; i < vm->def->nnets ; i++) {
        virDomainNetDefPtr net = vm->def->nets[i];

2226
        if (!virMacAddrCmp(&net->mac, &dev->data.net->mac)) {
2227 2228 2229 2230 2231 2232
            detach = net;
            break;
        }
    }

    if (!detach) {
2233 2234 2235 2236 2237
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("network device %02x:%02x:%02x:%02x:%02x:%02x not found"),
                       dev->data.net->mac.addr[0], dev->data.net->mac.addr[1],
                       dev->data.net->mac.addr[2], dev->data.net->mac.addr[3],
                       dev->data.net->mac.addr[4], dev->data.net->mac.addr[5]);
2238 2239 2240
        goto cleanup;
    }

2241 2242 2243 2244 2245 2246 2247
    if (virDomainNetGetActualType(detach) == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
        ret = qemuDomainDetachThisHostDevice(driver, vm,
                                             virDomainNetGetActualHostdev(detach),
                                             -1);
        goto cleanup;
    }

2248 2249
    if (!virDomainDeviceAddressIsValid(&detach->info,
                                       VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
2250 2251
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("device cannot be detached without a PCI address"));
2252 2253 2254 2255
        goto cleanup;
    }

    if (qemuIsMultiFunctionDevice(vm->def, &detach->info)) {
2256 2257 2258
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device :%s"),
                       dev->data.disk->dst);
2259 2260 2261 2262
        goto cleanup;
    }

    if ((vlan = qemuDomainNetVLAN(detach)) < 0) {
2263 2264
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("unable to determine original VLAN"));
2265 2266 2267 2268 2269 2270 2271 2272 2273
        goto cleanup;
    }

    if (virAsprintf(&hostnet_name, "host%s", detach->info.alias) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2274
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    }

2289 2290
    if (qemuCapsGet(priv->caps, QEMU_CAPS_NETDEV) &&
        qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306
        if (qemuMonitorRemoveNetdev(priv->mon, hostnet_name) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemoveHostNetwork(priv->mon, vlan, hostnet_name) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);

    virDomainAuditNet(vm, detach, NULL, "detach", true);

2307
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
2308 2309 2310 2311 2312 2313 2314 2315
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
                                        detach->info.addr.pci.slot) < 0)
        VIR_WARN("Unable to release PCI address on NIC");

    virDomainConfNWFilterTeardown(detach);

    if (virDomainNetGetActualType(detach) == VIR_DOMAIN_NET_TYPE_DIRECT) {
        ignore_value(virNetDevMacVLanDeleteWithVPortProfile(
2316
                         detach->ifname, &detach->mac,
2317 2318 2319 2320 2321 2322 2323 2324 2325 2326
                         virDomainNetGetActualDirectDev(detach),
                         virDomainNetGetActualDirectMode(detach),
                         virDomainNetGetActualVirtPortProfile(detach),
                         driver->stateDir));
        VIR_FREE(detach->ifname);
    }

    if ((driver->macFilter) && (detach->ifname != NULL)) {
        if ((errno = networkDisallowMacOnPort(driver,
                                              detach->ifname,
2327
                                              &detach->mac))) {
2328
            virReportSystemError(errno,
2329
             _("failed to remove ebtables rule on '%s'"),
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340
                                 detach->ifname);
        }
    }

    vport = virDomainNetGetActualVirtPortProfile(detach);
    if (vport && vport->virtPortType == VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH)
        ignore_value(virNetDevOpenvswitchRemovePort(
                        virDomainNetGetActualBridgeName(detach),
                        detach->ifname));
    ret = 0;
cleanup:
2341 2342 2343 2344 2345
    if (!ret) {
        networkReleaseActualDevice(detach);
        virDomainNetRemove(vm->def, i);
        virDomainNetDefFree(detach);
    }
2346 2347 2348 2349
    VIR_FREE(hostnet_name);
    return ret;
}

2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
int
qemuDomainChangeGraphicsPasswords(struct qemud_driver *driver,
                                  virDomainObjPtr vm,
                                  int type,
                                  virDomainGraphicsAuthDefPtr auth,
                                  const char *defaultPasswd)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    time_t now = time(NULL);
    char expire_time [64];
2360
    const char *connected = NULL;
2361
    const char *password;
2362 2363 2364 2365 2366
    int ret;

    if (!auth->passwd && !driver->vncPassword)
        return 0;

2367 2368
    password = auth->passwd ? auth->passwd : defaultPasswd;

2369 2370 2371
    if (auth->connected)
        connected = virDomainGraphicsAuthConnectedTypeToString(auth->connected);

2372
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2373
    ret = qemuMonitorSetPassword(priv->mon, type, password, connected);
2374 2375 2376

    if (ret == -2) {
        if (type != VIR_DOMAIN_GRAPHICS_TYPE_VNC) {
2377 2378
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Graphics password only supported for VNC"));
2379 2380
            ret = -1;
        } else {
2381
            ret = qemuMonitorSetVNCPassword(priv->mon, password);
2382 2383
        }
    }
2384 2385 2386
    if (ret != 0)
        goto cleanup;

2387 2388 2389
    if (password[0] == '\0') {
        snprintf(expire_time, sizeof(expire_time), "now");
    } else if (auth->expires) {
2390 2391
        time_t lifetime = auth->validTo - now;
        if (lifetime <= 0)
2392
            snprintf(expire_time, sizeof(expire_time), "now");
2393
        else
2394
            snprintf(expire_time, sizeof(expire_time), "%lu", (long unsigned)auth->validTo);
2395
    } else {
2396
        snprintf(expire_time, sizeof(expire_time), "never");
2397 2398 2399 2400 2401 2402 2403
    }

    ret = qemuMonitorExpirePassword(priv->mon, type, expire_time);

    if (ret == -2) {
        /* XXX we could fake this with a timer */
        if (auth->expires) {
2404 2405
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Expiry of passwords is not supported"));
2406
            ret = -1;
2407 2408
        } else {
            ret = 0;
2409 2410 2411
        }
    }

2412
cleanup:
2413 2414 2415 2416
    qemuDomainObjExitMonitorWithDriver(driver, vm);

    return ret;
}
2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437

int qemuDomainAttachLease(struct qemud_driver *driver,
                          virDomainObjPtr vm,
                          virDomainLeaseDefPtr lease)
{
    if (virDomainLeaseInsertPreAlloc(vm->def) < 0)
        return -1;

    if (virDomainLockLeaseAttach(driver->lockManager, vm, lease) < 0) {
        virDomainLeaseInsertPreAlloced(vm->def, NULL);
        return -1;
    }

    virDomainLeaseInsertPreAlloced(vm->def, lease);
    return 0;
}

int qemuDomainDetachLease(struct qemud_driver *driver,
                          virDomainObjPtr vm,
                          virDomainLeaseDefPtr lease)
{
2438
    virDomainLeaseDefPtr det_lease;
2439 2440 2441
    int i;

    if ((i = virDomainLeaseIndex(vm->def, lease)) < 0) {
2442 2443 2444
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Lease %s in lockspace %s does not exist"),
                       lease->key, NULLSTR(lease->lockspace));
2445 2446 2447 2448 2449 2450
        return -1;
    }

    if (virDomainLockLeaseDetach(driver->lockManager, vm, lease) < 0)
        return -1;

2451 2452
    det_lease = virDomainLeaseRemoveAt(vm->def, i);
    virDomainLeaseDefFree(det_lease);
2453 2454
    return 0;
}