qemu_hotplug.c 125.4 KB
Newer Older
1 2 3
/*
 * qemu_hotplug.h: QEMU device hotplug management
 *
4
 * Copyright (C) 2006-2014 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
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */


#include <config.h>

#include "qemu_hotplug.h"
28
#include "qemu_hotplugpriv.h"
29 30 31 32 33
#include "qemu_capabilities.h"
#include "qemu_domain.h"
#include "qemu_command.h"
#include "qemu_bridge_filter.h"
#include "qemu_hostdev.h"
34
#include "domain_audit.h"
35
#include "domain_nwfilter.h"
36
#include "virlog.h"
37
#include "datatypes.h"
38
#include "virerror.h"
39
#include "viralloc.h"
40
#include "virpci.h"
E
Eric Blake 已提交
41
#include "virfile.h"
42
#include "virprocess.h"
43
#include "qemu_cgroup.h"
44
#include "locking/domain_lock.h"
45
#include "network/bridge_driver.h"
46 47
#include "virnetdev.h"
#include "virnetdevbridge.h"
A
Ansis Atteka 已提交
48
#include "virnetdevtap.h"
49
#include "device_conf.h"
50
#include "virstoragefile.h"
51
#include "virstring.h"
52
#include "virtime.h"
53 54

#define VIR_FROM_THIS VIR_FROM_QEMU
55
#define CHANGE_MEDIA_RETRIES 10
56

57 58 59 60
/* Wait up to 5 seconds for device removal to finish. */
unsigned long long qemuDomainRemoveDeviceWaitTime = 1000ull * 5;


61
int qemuDomainChangeEjectableMedia(virQEMUDriverPtr driver,
62 63
                                   virDomainObjPtr vm,
                                   virDomainDiskDefPtr disk,
64
                                   virDomainDiskDefPtr origdisk,
65 66
                                   bool force)
{
67
    int ret = -1;
68
    char *driveAlias = NULL;
69
    qemuDomainObjPrivatePtr priv = vm->privateData;
70
    int retries = CHANGE_MEDIA_RETRIES;
71
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
72 73

    if (!origdisk->info.alias) {
74 75
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("missing disk device alias name for %s"), origdisk->dst);
76
        goto cleanup;
77 78 79 80
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
        origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
81 82
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
83
                       virDomainDiskDeviceTypeToString(disk->device));
84
        goto cleanup;
85 86
    }

87
    if (virDomainLockDiskAttach(driver->lockManager, cfg->uri,
88
                                vm, disk) < 0)
89
        goto cleanup;
90

91
    if (virSecurityManagerSetImageLabel(driver->securityManager,
92
                                        vm->def, disk) < 0) {
93 94
        if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
            VIR_WARN("Unable to release lock on %s", disk->src);
95
        goto cleanup;
96
    }
97

98
    if (!(driveAlias = qemuDeviceDriveHostAlias(origdisk, priv->qemuCaps)))
99 100
        goto error;

101
    qemuDomainObjEnterMonitor(driver, vm);
102
    ret = qemuMonitorEjectMedia(priv->mon, driveAlias, force);
103
    qemuDomainObjExitMonitor(driver, vm);
104

105
    virObjectRef(vm);
106
    /* we don't want to report errors from media tray_open polling */
107
    while (retries) {
108 109 110
        if (origdisk->tray_status == VIR_DOMAIN_DISK_TRAY_OPEN)
            break;

111
        retries--;
112
        virObjectUnlock(vm);
113 114
        VIR_DEBUG("Waiting 500ms for tray to open. Retries left %d", retries);
        usleep(500 * 1000); /* sleep 500ms */
115
        virObjectLock(vm);
116
    }
117
    virObjectUnref(vm);
118

119 120 121
    if (retries <= 0) {
        if (ret == 0) {
            /* If ret == -1, EjectMedia already set an error message */
122
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
123
                           _("Unable to eject media"));
124
        }
125 126 127 128 129 130 131 132
        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;
133

134
        if (disk->type != VIR_DOMAIN_DISK_TYPE_DIR) {
135 136 137 138
            if (disk->format > 0)
                format = virStorageFileFormatTypeToString(disk->format);
            else if (origdisk->format > 0)
                format = virStorageFileFormatTypeToString(origdisk->format);
139
        }
140
        qemuDomainObjEnterMonitor(driver, vm);
141 142 143
        ret = qemuMonitorChangeMedia(priv->mon,
                                     driveAlias,
                                     disk->src, format);
144
        qemuDomainObjExitMonitor(driver, vm);
145
    }
146
audit:
147
    virDomainAuditDisk(vm, origdisk->src, disk->src, "update", ret >= 0);
148 149 150 151

    if (ret < 0)
        goto error;

152
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
153
                                            vm->def, origdisk) < 0)
154 155
        VIR_WARN("Unable to restore security label on ejected image %s", origdisk->src);

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

159 160 161 162 163 164 165 166
    VIR_FREE(origdisk->src);
    origdisk->src = disk->src;
    disk->src = NULL;
    origdisk->type = disk->type;


    virDomainDiskDefFree(disk);

167 168 169
cleanup:
    VIR_FREE(driveAlias);
    virObjectUnref(cfg);
170 171 172
    return ret;

error:
173
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
174
                                            vm->def, disk) < 0)
175
        VIR_WARN("Unable to restore security label on new media %s", disk->src);
176 177 178 179

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

180
    goto cleanup;
181 182
}

183
int
184
qemuDomainCheckEjectableMedia(virQEMUDriverPtr driver,
185 186
                             virDomainObjPtr vm,
                             enum qemuDomainAsyncJob asyncJob)
187 188
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
189
    virHashTablePtr table = NULL;
190
    int ret = -1;
191
    size_t i;
192

193 194
    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) == 0) {
        table = qemuMonitorGetBlockInfo(priv->mon);
195
        qemuDomainObjExitMonitor(driver, vm);
196
    }
197 198 199 200

    if (!table)
        goto cleanup;

201 202
    for (i = 0; i < vm->def->ndisks; i++) {
        virDomainDiskDefPtr disk = vm->def->disks[i];
203
        struct qemuDomainDiskInfo *info;
204

205 206
        if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK ||
            disk->device == VIR_DOMAIN_DISK_DEVICE_LUN) {
207
                 continue;
208
        }
209

210 211
        info = qemuMonitorBlockInfoLookup(table, disk->info.alias);
        if (!info)
212 213
            goto cleanup;

214
        if (info->tray_open && disk->src)
215 216 217 218 219 220
            VIR_FREE(disk->src);
    }

    ret = 0;

cleanup:
221
    virHashFree(table);
222 223 224
    return ret;
}

225 226 227 228 229
static int
qemuDomainAttachVirtioDiskDevice(virConnectPtr conn,
                                 virQEMUDriverPtr driver,
                                 virDomainObjPtr vm,
                                 virDomainDiskDefPtr disk)
230
{
231 232
    size_t i;
    int ret = -1;
233 234 235 236
    const char* type = virDomainDiskBusTypeToString(disk->bus);
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *devstr = NULL;
    char *drivestr = NULL;
237
    bool releaseaddr = false;
238
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
239

240 241 242 243 244 245 246 247
    if (!disk->info.type) {
        if (STREQLEN(vm->def->os.machine, "s390-ccw", 8) &&
            virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_CCW))
            disk->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW;
        else if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_S390))
            disk->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390;
    }

248
    for (i = 0; i < vm->def->ndisks; i++) {
249
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
250 251
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("target %s already exists"), disk->dst);
252
            goto cleanup;
253 254 255
        }
    }

256
    if (virDomainLockDiskAttach(driver->lockManager, cfg->uri,
257
                                vm, disk) < 0)
258
        goto cleanup;
259

260
    if (virSecurityManagerSetImageLabel(driver->securityManager,
261
                                        vm->def, disk) < 0) {
262 263
        if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
            VIR_WARN("Unable to release lock on %s", disk->src);
264
        goto cleanup;
265
    }
266

267
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
268 269 270 271
        if (disk->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW) {
            if (qemuDomainCCWAddressAssign(&disk->info, priv->ccwaddrs,
                                           !disk->info.addr.ccw.assigned) < 0)
                goto error;
272 273
        } else if (!disk->info.type ||
                    disk->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
274 275 276
            if (qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &disk->info) < 0)
                goto error;
        }
277
        releaseaddr = true;
278
        if (qemuAssignDeviceDiskAlias(vm->def, disk, priv->qemuCaps) < 0)
279 280
            goto error;

281
        if (!(drivestr = qemuBuildDriveStr(conn, disk, false, priv->qemuCaps)))
282 283
            goto error;

284
        if (!(devstr = qemuBuildDriveDevStr(vm->def, disk, 0, priv->qemuCaps)))
285 286 287
            goto error;
    }

288
    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0)
289 290
        goto error;

291
    qemuDomainObjEnterMonitor(driver, vm);
292
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
293 294 295 296
        ret = qemuMonitorAddDrive(priv->mon, drivestr);
        if (ret == 0) {
            ret = qemuMonitorAddDevice(priv->mon, devstr);
            if (ret < 0) {
297 298 299 300 301 302 303 304 305 306
                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);
                }
307 308
            }
        }
309 310
    } else if (!disk->info.type ||
                disk->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
311
        virDevicePCIAddress guestAddr = disk->info.addr.pci;
312 313 314 315
        ret = qemuMonitorAddPCIDisk(priv->mon,
                                    disk->src,
                                    type,
                                    &guestAddr);
316 317
        if (ret == 0) {
            disk->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
318
            memcpy(&disk->info.addr.pci, &guestAddr, sizeof(guestAddr));
319
        }
320
    }
321
    qemuDomainObjExitMonitor(driver, vm);
322

323
    virDomainAuditDisk(vm, NULL, disk->src, "attach", ret >= 0);
324 325 326 327 328 329

    if (ret < 0)
        goto error;

    virDomainDiskInsertPreAlloced(vm->def, disk);

330
cleanup:
331 332
    VIR_FREE(devstr);
    VIR_FREE(drivestr);
333 334
    virObjectUnref(cfg);
    return ret;
335 336

error:
337 338
    if (releaseaddr)
        qemuDomainReleaseDeviceAddress(vm, &disk->info, disk->src);
339

340
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
341
                                            vm->def, disk) < 0)
342 343
        VIR_WARN("Unable to restore security label on %s", disk->src);

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

347
    goto cleanup;
348 349 350
}


351 352 353
int qemuDomainAttachControllerDevice(virQEMUDriverPtr driver,
                                     virDomainObjPtr vm,
                                     virDomainControllerDefPtr controller)
354 355 356 357 358
{
    int ret = -1;
    const char* type = virDomainControllerTypeToString(controller->type);
    char *devstr = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
359
    bool releaseaddr = false;
360

361
    if (virDomainControllerFind(vm->def, controller->type, controller->idx) >= 0) {
362 363 364 365
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("target %s:%d already exists"),
                       type, controller->idx);
        return -1;
366 367
    }

368
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
        if (controller->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
            if (STRPREFIX(vm->def->os.machine, "s390-ccw") &&
                virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_CCW))
                controller->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW;
            else if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_S390))
                controller->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390;
        }

        if (controller->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE ||
            controller->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
            if (qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &controller->info) < 0)
                goto cleanup;
        } else if (controller->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW) {
            if (qemuDomainCCWAddressAssign(&controller->info, priv->ccwaddrs,
                                           !controller->info.addr.ccw.assigned) < 0)
                goto cleanup;
        }
386
        releaseaddr = true;
387 388 389
        if (qemuAssignDeviceControllerAlias(controller) < 0)
            goto cleanup;

390 391
        if (controller->type == VIR_DOMAIN_CONTROLLER_TYPE_USB &&
            controller->model == -1 &&
392
            !virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_PIIX3_USB_UHCI)) {
393 394
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("USB controller hotplug unsupported in this QEMU binary"));
395 396 397
            goto cleanup;
        }

398
        if (!(devstr = qemuBuildControllerDevStr(vm->def, controller, priv->qemuCaps, NULL))) {
399 400 401 402
            goto cleanup;
        }
    }

403
    if (VIR_REALLOC_N(vm->def->controllers, vm->def->ncontrollers+1) < 0)
404 405
        goto cleanup;

406
    qemuDomainObjEnterMonitor(driver, vm);
407
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
408 409 410 411 412 413
        ret = qemuMonitorAddDevice(priv->mon, devstr);
    } else {
        ret = qemuMonitorAttachPCIDiskController(priv->mon,
                                                 type,
                                                 &controller->info.addr.pci);
    }
414
    qemuDomainObjExitMonitor(driver, vm);
415 416

    if (ret == 0) {
417 418
        if (controller->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
            controller->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
419 420 421 422
        virDomainControllerInsertPreAlloced(vm->def, controller);
    }

cleanup:
423 424
    if (ret != 0 && releaseaddr)
        qemuDomainReleaseDeviceAddress(vm, &controller->info, NULL);
425 426 427 428 429 430

    VIR_FREE(devstr);
    return ret;
}

static virDomainControllerDefPtr
431
qemuDomainFindOrCreateSCSIDiskController(virQEMUDriverPtr driver,
432
                                         virDomainObjPtr vm,
433
                                         int controller)
434
{
435
    size_t i;
436
    virDomainControllerDefPtr cont;
437

438
    for (i = 0; i < vm->def->ncontrollers; i++) {
439 440 441 442 443 444 445 446 447 448 449
        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 */
450
    if (VIR_ALLOC(cont) < 0)
451 452
        return NULL;
    cont->type = VIR_DOMAIN_CONTROLLER_TYPE_SCSI;
453
    cont->idx = controller;
454 455
    cont->model = -1;

456
    VIR_INFO("No SCSI controller present, hotplugging one");
457 458
    if (qemuDomainAttachControllerDevice(driver,
                                         vm, cont) < 0) {
459 460 461 462 463
        VIR_FREE(cont);
        return NULL;
    }

    if (!virDomainObjIsActive(vm)) {
464 465
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest unexpectedly quit"));
466 467 468 469 470 471 472 473 474
        /* cont doesn't need freeing here, since the reference
         * now held in def->controllers */
        return NULL;
    }

    return cont;
}


475 476 477 478 479
static int
qemuDomainAttachSCSIDisk(virConnectPtr conn,
                         virQEMUDriverPtr driver,
                         virDomainObjPtr vm,
                         virDomainDiskDefPtr disk)
480
{
481
    size_t i;
482 483 484 485 486
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virDomainControllerDefPtr cont = NULL;
    char *drivestr = NULL;
    char *devstr = NULL;
    int ret = -1;
487
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
488

489
    for (i = 0; i < vm->def->ndisks; i++) {
490
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
491 492
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("target %s already exists"), disk->dst);
493
            goto cleanup;
494 495 496
        }
    }

497
    if (virDomainLockDiskAttach(driver->lockManager, cfg->uri,
498
                                vm, disk) < 0)
499
        goto cleanup;
500

501
    if (virSecurityManagerSetImageLabel(driver->securityManager,
502
                                        vm->def, disk) < 0) {
503 504
        if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
            VIR_WARN("Unable to release lock on %s", disk->src);
505
        goto cleanup;
506
    }
507 508 509

    /* We should have an address already, so make sure */
    if (disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE) {
510 511 512
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected disk address type %s"),
                       virDomainDeviceAddressTypeToString(disk->info.type));
513 514 515
        goto error;
    }

516 517
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
        if (qemuAssignDeviceDiskAlias(vm->def, disk, priv->qemuCaps) < 0)
518
            goto error;
519
        if (!(devstr = qemuBuildDriveDevStr(vm->def, disk, 0, priv->qemuCaps)))
520 521 522
            goto error;
    }

523
    if (!(drivestr = qemuBuildDriveStr(conn, disk, false, priv->qemuCaps)))
524 525
        goto error;

526
    for (i = 0; i <= disk->info.addr.drive.controller; i++) {
527
        cont = qemuDomainFindOrCreateSCSIDiskController(driver, vm, i);
528 529 530 531 532 533 534
        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.  */
535
    sa_assert(cont);
536

537
    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0)
538 539
        goto error;

540
    qemuDomainObjEnterMonitor(driver, vm);
541
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
542 543 544 545 546 547 548 549 550 551 552
        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 {
553 554 555 556 557 558 559
        if (cont->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("SCSI controller %d was missing its PCI address"),
                           cont->idx);
            goto error;
        }

560 561 562 563 564 565 566 567 568
        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;
569 570
            disk->info.addr.drive.bus = driveAddr.bus;
            disk->info.addr.drive.unit = driveAddr.unit;
571 572
        }
    }
573
    qemuDomainObjExitMonitor(driver, vm);
574

575
    virDomainAuditDisk(vm, NULL, disk->src, "attach", ret >= 0);
576 577 578 579 580 581

    if (ret < 0)
        goto error;

    virDomainDiskInsertPreAlloced(vm->def, disk);

582
cleanup:
583 584
    VIR_FREE(devstr);
    VIR_FREE(drivestr);
585 586
    virObjectUnref(cfg);
    return ret;
587 588

error:
589
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
590
                                            vm->def, disk) < 0)
591 592
        VIR_WARN("Unable to restore security label on %s", disk->src);

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

596
    goto cleanup;
597 598 599
}


600 601 602 603 604
static int
qemuDomainAttachUsbMassstorageDevice(virConnectPtr conn,
                                     virQEMUDriverPtr driver,
                                     virDomainObjPtr vm,
                                     virDomainDiskDefPtr disk)
605 606
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
607 608
    size_t i;
    int ret = -1;
609 610
    char *drivestr = NULL;
    char *devstr = NULL;
611
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
612

613
    for (i = 0; i < vm->def->ndisks; i++) {
614
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
615 616
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("target %s already exists"), disk->dst);
617
            goto cleanup;
618 619 620
        }
    }

621
    if (virDomainLockDiskAttach(driver->lockManager, cfg->uri,
622
                                vm, disk) < 0)
623
        goto cleanup;
624

625
    if (virSecurityManagerSetImageLabel(driver->securityManager,
626
                                        vm->def, disk) < 0) {
627 628
        if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
            VIR_WARN("Unable to release lock on %s", disk->src);
629
        goto cleanup;
630
    }
631

632
    /* XXX not correct once we allow attaching a USB CDROM */
633
    if (!disk->src) {
634 635
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("disk source path is missing"));
636 637 638
        goto error;
    }

639 640
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
        if (qemuAssignDeviceDiskAlias(vm->def, disk, priv->qemuCaps) < 0)
641
            goto error;
642
        if (!(drivestr = qemuBuildDriveStr(conn, disk, false, priv->qemuCaps)))
643
            goto error;
644
        if (!(devstr = qemuBuildDriveDevStr(vm->def, disk, 0, priv->qemuCaps)))
645 646 647
            goto error;
    }

648
    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0)
649 650
        goto error;

651
    qemuDomainObjEnterMonitor(driver, vm);
652
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
653 654 655 656 657 658 659 660 661 662 663 664 665
        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);
    }
666
    qemuDomainObjExitMonitor(driver, vm);
667

668
    virDomainAuditDisk(vm, NULL, disk->src, "attach", ret >= 0);
669 670 671 672 673 674

    if (ret < 0)
        goto error;

    virDomainDiskInsertPreAlloced(vm->def, disk);

675
cleanup:
676 677
    VIR_FREE(devstr);
    VIR_FREE(drivestr);
678 679
    virObjectUnref(cfg);
    return ret;
680 681

error:
682
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
683
                                            vm->def, disk) < 0)
684 685
        VIR_WARN("Unable to restore security label on %s", disk->src);

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

689
    goto cleanup;
690 691 692
}


693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
int
qemuDomainAttachDeviceDiskLive(virConnectPtr conn,
                               virQEMUDriverPtr driver,
                               virDomainObjPtr vm,
                               virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virDomainDiskDefPtr orig_disk = NULL;
    virDomainDeviceDefPtr dev_copy = NULL;
    virDomainDiskDefPtr tmp = NULL;
    virCapsPtr caps = NULL;
    int ret = -1;

    if (disk->driverName != NULL && !STREQ(disk->driverName, "qemu")) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("unsupported driver name '%s' for disk '%s'"),
                       disk->driverName, disk->src);
        goto end;
    }

    if (qemuTranslateDiskSourcePool(conn, disk) < 0)
        goto end;

    if (qemuAddSharedDevice(driver, dev, vm->def->name) < 0)
        goto end;

    if (qemuSetUnprivSGIO(dev) < 0)
        goto end;

722
    if (qemuDomainDetermineDiskChain(driver, vm, disk, false) < 0)
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
        goto end;

    if (qemuSetupDiskCgroup(vm, disk) < 0)
        goto end;

    switch (disk->device)  {
    case VIR_DOMAIN_DISK_DEVICE_CDROM:
    case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
        if (!(orig_disk = virDomainDiskFindByBusAndDst(vm->def,
                                                       disk->bus, disk->dst))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("No device with bus '%s' and target '%s'"),
                           virDomainDiskBusTypeToString(disk->bus),
                           disk->dst);
            goto end;
        }

        if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
            goto end;

        tmp = dev->data.disk;
        dev->data.disk = orig_disk;

        if (!(dev_copy = virDomainDeviceDefCopy(dev, vm->def,
                                                caps, driver->xmlopt))) {
            dev->data.disk = tmp;
            goto end;
        }
        dev->data.disk = tmp;

        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, orig_disk, false);
        /* 'disk' must not be accessed now - it has been free'd.
         * 'orig_disk' now points to the new disk, while 'dev_copy'
         * now points to the old disk */

        /* Need to remove the shared disk entry for the original disk src
         * if the operation is either ejecting or updating.
         */
        if (ret == 0)
            ignore_value(qemuRemoveSharedDevice(driver, dev_copy,
                                                vm->def->name));
        break;
    case VIR_DOMAIN_DISK_DEVICE_DISK:
    case VIR_DOMAIN_DISK_DEVICE_LUN:
        if (disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
            if (disk->device == VIR_DOMAIN_DISK_DEVICE_LUN) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("disk device='lun' is not supported for usb bus"));
                break;
            }
            ret = qemuDomainAttachUsbMassstorageDevice(conn, driver, vm,
                                                       disk);
        } else if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
            ret = qemuDomainAttachVirtioDiskDevice(conn, driver, vm, disk);
        } else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI) {
            ret = qemuDomainAttachSCSIDisk(conn, driver, vm, disk);
        } else {
            virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                           _("disk bus '%s' cannot be hotplugged."),
                           virDomainDiskBusTypeToString(disk->bus));
        }
        break;
    default:
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("disk device type '%s' cannot be hotplugged"),
                       virDomainDiskDeviceTypeToString(disk->device));
        break;
    }

792 793 794 795
    if (ret != 0 &&
        qemuTeardownDiskCgroup(vm, disk) < 0) {
        VIR_WARN("Failed to teardown cgroup for disk path %s",
                 NULLSTR(disk->src));
796 797 798 799 800 801 802 803 804 805 806
    }

end:
    if (ret != 0)
        ignore_value(qemuRemoveSharedDevice(driver, dev, vm->def->name));
    virObjectUnref(caps);
    virDomainDeviceDefFree(dev_copy);
    return ret;
}


807 808
/* XXX conn required for network -> bridge resolution */
int qemuDomainAttachNetDevice(virConnectPtr conn,
809
                              virQEMUDriverPtr driver,
810
                              virDomainObjPtr vm,
811
                              virDomainNetDefPtr net)
812 813
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
814 815 816 817 818 819
    char **tapfdName = NULL;
    int *tapfd = NULL;
    int tapfdSize = 0;
    char **vhostfdName = NULL;
    int *vhostfd = NULL;
    int vhostfdSize = 0;
820 821
    char *nicstr = NULL;
    char *netstr = NULL;
A
Ansis Atteka 已提交
822
    virNetDevVPortProfilePtr vport = NULL;
823
    int ret = -1;
824
    virDevicePCIAddress guestAddr;
825
    int vlan;
826
    bool releaseaddr = false;
827 828
    bool iface_connected = false;
    int actualType;
829
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
830
    size_t i;
831

832
    /* preallocate new slot for device */
833
    if (VIR_REALLOC_N(vm->def->nets, vm->def->nnets + 1) < 0)
834
        goto cleanup;
835

836 837 838 839
    /* 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.
     */
840
    if (networkAllocateActualDevice(vm->def, net) < 0)
841
        goto cleanup;
842 843

    actualType = virDomainNetGetActualType(net);
844 845 846 847 848 849 850 851 852 853 854 855

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

856
    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_HOST_NET_ADD)) {
857 858
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("installed qemu version does not support host_net_add"));
859 860 861
        goto cleanup;
    }

862 863 864 865 866 867 868 869 870 871
    /* Currently nothing besides TAP devices supports multiqueue. */
    if (net->driver.virtio.queues > 0 &&
        !(actualType == VIR_DOMAIN_NET_TYPE_NETWORK ||
          actualType == VIR_DOMAIN_NET_TYPE_BRIDGE)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Multiqueue network is not supported for: %s"),
                       virDomainNetTypeToString(actualType));
        return -1;
    }

872 873
    if (actualType == VIR_DOMAIN_NET_TYPE_BRIDGE ||
        actualType == VIR_DOMAIN_NET_TYPE_NETWORK) {
874 875 876 877
        tapfdSize = vhostfdSize = net->driver.virtio.queues;
        if (!tapfdSize)
            tapfdSize = vhostfdSize = 1;
        if (VIR_ALLOC_N(tapfd, tapfdSize) < 0 ||
878
            VIR_ALLOC_N(vhostfd, vhostfdSize) < 0)
879 880 881
            goto cleanup;
        if (qemuNetworkIfaceConnect(vm->def, conn, driver, net,
                                    priv->qemuCaps, tapfd, &tapfdSize) < 0)
882 883
            goto cleanup;
        iface_connected = true;
884
        if (qemuOpenVhostNet(vm->def, net, priv->qemuCaps, vhostfd, &vhostfdSize) < 0)
885
            goto cleanup;
886
    } else if (actualType == VIR_DOMAIN_NET_TYPE_DIRECT) {
887
        tapfdSize = vhostfdSize = 1;
888
        if (VIR_ALLOC(tapfd) < 0 || VIR_ALLOC(vhostfd) < 0)
889 890 891 892
            goto cleanup;
        if ((tapfd[0] = qemuPhysIfaceConnect(vm->def, driver, net,
                                             priv->qemuCaps,
                                             VIR_NETDEV_VPORT_PROFILE_OP_CREATE)) < 0)
893 894
            goto cleanup;
        iface_connected = true;
895
        if (qemuOpenVhostNet(vm->def, net, priv->qemuCaps, vhostfd, &vhostfdSize) < 0)
896
            goto cleanup;
897
    } else if (actualType == VIR_DOMAIN_NET_TYPE_ETHERNET) {
898
        vhostfdSize = 1;
899
        if (VIR_ALLOC(vhostfd) < 0)
900 901
            goto cleanup;
        if (qemuOpenVhostNet(vm->def, net, priv->qemuCaps, vhostfd, &vhostfdSize) < 0)
902
            goto cleanup;
903 904
    }

905 906
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NET_NAME) ||
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
907 908 909 910
        if (qemuAssignDeviceNetAlias(vm->def, net, -1) < 0)
            goto cleanup;
    }

911 912 913 914 915 916 917 918 919 920 921 922
    if (STREQLEN(vm->def->os.machine, "s390-ccw", 8) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_CCW)) {
        net->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW;
        if (qemuDomainCCWAddressAssign(&net->info, priv->ccwaddrs,
                                       !net->info.addr.ccw.assigned) < 0)
            goto cleanup;
    } else if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_S390))
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("virtio-s390 net device cannot be hotplugged."));
    else if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE) &&
             qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &net->info) < 0)
             goto cleanup;
923

924 925
    releaseaddr = true;

926 927
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NETDEV) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
928 929 930 931 932
        vlan = -1;
    } else {
        vlan = qemuDomainNetVLAN(net);

        if (vlan < 0) {
933 934
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Unable to attach network devices without vlan"));
935 936 937 938
            goto cleanup;
        }
    }

939
    if (VIR_ALLOC_N(tapfdName, tapfdSize) < 0 ||
940
        VIR_ALLOC_N(vhostfdName, vhostfdSize) < 0)
941 942 943
        goto cleanup;

    for (i = 0; i < tapfdSize; i++) {
944
        if (virAsprintf(&tapfdName[i], "fd-%s%zu", net->info.alias, i) < 0)
945
            goto cleanup;
946 947
    }

948
    for (i = 0; i < vhostfdSize; i++) {
949
        if (virAsprintf(&vhostfdName[i], "vhostfd-%s%zu", net->info.alias, i) < 0)
950
            goto cleanup;
951 952
    }

953 954
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NETDEV) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
955
        if (!(netstr = qemuBuildHostNetStr(net, driver,
956 957 958
                                           ',', -1,
                                           tapfdName, tapfdSize,
                                           vhostfdName, vhostfdSize)))
959
            goto cleanup;
960
    } else {
961
        if (!(netstr = qemuBuildHostNetStr(net, driver,
962 963 964
                                           ' ', vlan,
                                           tapfdName, tapfdSize,
                                           vhostfdName, vhostfdSize)))
965
            goto cleanup;
966 967
    }

968
    qemuDomainObjEnterMonitor(driver, vm);
969 970
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NETDEV) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
971 972 973
        if (qemuMonitorAddNetdev(priv->mon, netstr,
                                 tapfd, tapfdName, tapfdSize,
                                 vhostfd, vhostfdName, vhostfdSize) < 0) {
974
            qemuDomainObjExitMonitor(driver, vm);
975
            virDomainAuditNet(vm, NULL, net, "attach", false);
976
            goto cleanup;
977 978
        }
    } else {
979 980 981
        if (qemuMonitorAddHostNetwork(priv->mon, netstr,
                                      tapfd, tapfdName, tapfdSize,
                                      vhostfd, vhostfdName, vhostfdSize) < 0) {
982
            qemuDomainObjExitMonitor(driver, vm);
983
            virDomainAuditNet(vm, NULL, net, "attach", false);
984
            goto cleanup;
985 986
        }
    }
987
    qemuDomainObjExitMonitor(driver, vm);
988

989 990 991 992
    for (i = 0; i < tapfdSize; i++)
        VIR_FORCE_CLOSE(tapfd[i]);
    for (i = 0; i < vhostfdSize; i++)
        VIR_FORCE_CLOSE(vhostfd[i]);
993 994

    if (!virDomainObjIsActive(vm)) {
995 996
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest unexpectedly quit"));
997 998 999
        goto cleanup;
    }

1000
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
1001
        if (!(nicstr = qemuBuildNicDevStr(vm->def, net, vlan, 0,
1002
                                          vhostfdSize, priv->qemuCaps)))
1003 1004 1005 1006 1007 1008
            goto try_remove;
    } else {
        if (!(nicstr = qemuBuildNicStr(net, NULL, vlan)))
            goto try_remove;
    }

1009
    qemuDomainObjEnterMonitor(driver, vm);
1010
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
1011
        if (qemuMonitorAddDevice(priv->mon, nicstr) < 0) {
1012
            qemuDomainObjExitMonitor(driver, vm);
1013
            virDomainAuditNet(vm, NULL, net, "attach", false);
1014 1015 1016
            goto try_remove;
        }
    } else {
1017
        guestAddr = net->info.addr.pci;
1018 1019
        if (qemuMonitorAddPCINetwork(priv->mon, nicstr,
                                     &guestAddr) < 0) {
1020
            qemuDomainObjExitMonitor(driver, vm);
1021
            virDomainAuditNet(vm, NULL, net, "attach", false);
1022 1023 1024 1025 1026
            goto try_remove;
        }
        net->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
        memcpy(&net->info.addr.pci, &guestAddr, sizeof(guestAddr));
    }
1027
    qemuDomainObjExitMonitor(driver, vm);
1028

1029 1030 1031
    /* set link state */
    if (net->linkstate == VIR_DOMAIN_NET_INTERFACE_LINK_STATE_DOWN) {
        if (!net->info.alias) {
1032 1033
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("device alias not found: cannot set link state to down"));
1034
        } else {
1035
            qemuDomainObjEnterMonitor(driver, vm);
1036

1037
            if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NETDEV)) {
1038
                if (qemuMonitorSetLink(priv->mon, net->info.alias, VIR_DOMAIN_NET_INTERFACE_LINK_STATE_DOWN) < 0) {
1039
                    qemuDomainObjExitMonitor(driver, vm);
1040 1041 1042 1043
                    virDomainAuditNet(vm, NULL, net, "attach", false);
                    goto try_remove;
                }
            } else {
1044
                virReportError(VIR_ERR_OPERATION_FAILED, "%s",
1045
                               _("setting of link state not supported: Link is up"));
1046 1047
            }

1048
            qemuDomainObjExitMonitor(driver, vm);
1049 1050 1051 1052
        }
        /* link set to down */
    }

1053
    virDomainAuditNet(vm, NULL, net, "attach", true);
1054 1055 1056 1057

    ret = 0;

cleanup:
1058 1059 1060
    if (!ret) {
        vm->def->nets[vm->def->nnets++] = net;
    } else {
1061 1062
        if (releaseaddr)
            qemuDomainReleaseDeviceAddress(vm, &net->info, NULL);
1063

1064
        if (iface_connected) {
1065
            virDomainConfNWFilterTeardown(net);
1066

1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
            if (virDomainNetGetActualType(net) == VIR_DOMAIN_NET_TYPE_DIRECT) {
                ignore_value(virNetDevMacVLanDeleteWithVPortProfile(
                                 net->ifname, &net->mac,
                                 virDomainNetGetActualDirectDev(net),
                                 virDomainNetGetActualDirectMode(net),
                                 virDomainNetGetActualVirtPortProfile(net),
                                 cfg->stateDir));
                VIR_FREE(net->ifname);
            }

1077 1078 1079 1080 1081
            vport = virDomainNetGetActualVirtPortProfile(net);
            if (vport && vport->virtPortType == VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH)
               ignore_value(virNetDevOpenvswitchRemovePort(
                               virDomainNetGetActualBridgeName(net), net->ifname));
        }
A
Ansis Atteka 已提交
1082

1083 1084
        virDomainNetRemoveHostdev(vm->def, net);

1085
        networkReleaseActualDevice(vm->def, net);
1086
    }
1087 1088 1089

    VIR_FREE(nicstr);
    VIR_FREE(netstr);
1090
    for (i = 0; tapfd && i < tapfdSize; i++) {
1091
        VIR_FORCE_CLOSE(tapfd[i]);
1092 1093
        if (tapfdName)
            VIR_FREE(tapfdName[i]);
1094 1095 1096
    }
    VIR_FREE(tapfd);
    VIR_FREE(tapfdName);
1097
    for (i = 0; vhostfd && i < vhostfdSize; i++) {
1098
        VIR_FORCE_CLOSE(vhostfd[i]);
1099 1100
        if (vhostfdName)
            VIR_FREE(vhostfdName[i]);
1101 1102 1103
    }
    VIR_FREE(vhostfd);
    VIR_FREE(vhostfdName);
1104
    virObjectUnref(cfg);
1105 1106 1107 1108 1109 1110 1111 1112

    return ret;

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

    if (vlan < 0) {
1113 1114
        if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NETDEV) &&
            virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
1115 1116
            char *netdev_name;
            if (virAsprintf(&netdev_name, "host%s", net->info.alias) < 0)
1117
                goto cleanup;
1118
            qemuDomainObjEnterMonitor(driver, vm);
1119 1120 1121
            if (qemuMonitorRemoveNetdev(priv->mon, netdev_name) < 0)
                VIR_WARN("Failed to remove network backend for netdev %s",
                         netdev_name);
1122
            qemuDomainObjExitMonitor(driver, vm);
1123 1124
            VIR_FREE(netdev_name);
        } else {
1125
            VIR_WARN("Unable to remove network backend");
1126 1127 1128 1129
        }
    } else {
        char *hostnet_name;
        if (virAsprintf(&hostnet_name, "host%s", net->info.alias) < 0)
1130
            goto cleanup;
1131
        qemuDomainObjEnterMonitor(driver, vm);
1132 1133 1134
        if (qemuMonitorRemoveHostNetwork(priv->mon, vlan, hostnet_name) < 0)
            VIR_WARN("Failed to remove network backend for vlan %d, net %s",
                     vlan, hostnet_name);
1135
        qemuDomainObjExitMonitor(driver, vm);
1136 1137 1138 1139 1140 1141
        VIR_FREE(hostnet_name);
    }
    goto cleanup;
}


1142 1143 1144 1145
static int
qemuDomainAttachHostPciDevice(virQEMUDriverPtr driver,
                              virDomainObjPtr vm,
                              virDomainHostdevDefPtr hostdev)
1146 1147 1148 1149 1150 1151
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret;
    char *devstr = NULL;
    int configfd = -1;
    char *configfd_name = NULL;
1152
    bool releaseaddr = false;
1153
    bool teardowncgroup = false;
1154
    bool teardownlabel = false;
1155
    int backend;
1156
    unsigned long long memKB;
1157

1158
    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs + 1) < 0)
1159 1160
        return -1;

1161
    if (qemuPrepareHostdevPCIDevices(driver, vm->def->name, vm->def->uuid,
1162
                                     &hostdev, 1, priv->qemuCaps) < 0)
1163 1164
        return -1;

1165 1166 1167
    /* this could have been changed by qemuPrepareHostdevPCIDevices */
    backend = hostdev->source.subsys.u.pci.backend;

1168 1169
    switch ((virDomainHostdevSubsysPciBackendType) backend) {
    case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO:
1170 1171 1172 1173 1174 1175
        if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE_VFIO_PCI)) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("VFIO PCI device assignment is not "
                             "supported by this version of qemu"));
            goto error;
        }
1176

1177 1178 1179
        /* VFIO requires all of the guest's memory to be locked
         * resident (plus an additional 1GiB to cover IO space). During
         * hotplug, the guest's memory may already be locked, but it
1180
         * doesn't hurt to "change" the limit to the same value.
1181 1182 1183
         * NB: the domain's memory tuning parameters are stored as
         * Kibibytes, but virProcessSetMaxMemLock expects the value in
         * bytes.
1184
         */
1185 1186 1187 1188
        memKB = vm->def->mem.hard_limit
            ? vm->def->mem.hard_limit
            : vm->def->mem.max_balloon + (1024 * 1024);
        virProcessSetMaxMemLock(vm->pid, memKB * 1024);
1189 1190 1191 1192 1193 1194
        break;

    case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_DEFAULT:
    case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_KVM:
    case VIR_DOMAIN_HOSTDEV_PCI_BACKEND_TYPE_LAST:
        break;
1195 1196
    }

1197 1198 1199 1200
    if (qemuSetupHostdevCGroup(vm, hostdev) < 0)
        goto error;
    teardowncgroup = true;

1201 1202 1203 1204 1205
    if (virSecurityManagerSetHostdevLabel(driver->securityManager,
                                          vm->def, hostdev, NULL) < 0)
        goto error;
    teardownlabel = true;

1206
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
1207 1208
        if (qemuAssignDeviceHostdevAlias(vm->def, hostdev, -1) < 0)
            goto error;
1209
        if (qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, hostdev->info) < 0)
1210
            goto error;
1211
        releaseaddr = true;
1212
        if (backend != VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO &&
1213
            virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_PCI_CONFIGFD)) {
1214 1215 1216
            configfd = qemuOpenPCIConfig(hostdev);
            if (configfd >= 0) {
                if (virAsprintf(&configfd_name, "fd-%s",
1217
                                hostdev->info->alias) < 0)
1218 1219 1220 1221 1222
                    goto error;
            }
        }

        if (!virDomainObjIsActive(vm)) {
1223 1224
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("guest unexpectedly quit during hotplug"));
1225 1226 1227
            goto error;
        }

1228
        if (!(devstr = qemuBuildPCIHostdevDevStr(vm->def, hostdev, configfd_name,
1229
                                                 priv->qemuCaps)))
1230 1231
            goto error;

1232
        qemuDomainObjEnterMonitor(driver, vm);
1233 1234
        ret = qemuMonitorAddDeviceWithFd(priv->mon, devstr,
                                         configfd, configfd_name);
1235
        qemuDomainObjExitMonitor(driver, vm);
1236
    } else {
1237
        virDevicePCIAddress guestAddr = hostdev->info->addr.pci;
1238

1239
        qemuDomainObjEnterMonitor(driver, vm);
1240
        ret = qemuMonitorAddPCIHostDevice(priv->mon,
1241
                                          &hostdev->source.subsys.u.pci.addr,
1242
                                          &guestAddr);
1243
        qemuDomainObjExitMonitor(driver, vm);
1244

1245 1246
        hostdev->info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
        memcpy(&hostdev->info->addr.pci, &guestAddr, sizeof(guestAddr));
1247
    }
1248
    virDomainAuditHostdev(vm, hostdev, "attach", ret == 0);
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
    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:
1261 1262
    if (teardowncgroup && qemuTeardownHostdevCgroup(vm, hostdev) < 0)
        VIR_WARN("Unable to remove host device cgroup ACL on hotplug fail");
1263 1264 1265 1266
    if (teardownlabel &&
        virSecurityManagerRestoreHostdevLabel(driver->securityManager,
                                              vm->def, hostdev, NULL) < 0)
        VIR_WARN("Unable to restore host device labelling on hotplug fail");
1267

1268 1269
    if (releaseaddr)
        qemuDomainReleaseDeviceAddress(vm, hostdev->info, NULL);
1270

1271
    qemuDomainReAttachHostdevDevices(driver, vm->def->name, &hostdev, 1);
1272 1273 1274 1275 1276 1277 1278 1279 1280

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

    return -1;
}


1281
int qemuDomainAttachRedirdevDevice(virQEMUDriverPtr driver,
1282 1283 1284 1285 1286
                                   virDomainObjPtr vm,
                                   virDomainRedirdevDefPtr redirdev)
{
    int ret;
    qemuDomainObjPrivatePtr priv = vm->privateData;
1287
    virDomainDefPtr def = vm->def;
1288 1289
    char *devstr = NULL;

1290
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
1291 1292
        if (qemuAssignDeviceRedirdevAlias(vm->def, redirdev, -1) < 0)
            goto error;
1293
        if (!(devstr = qemuBuildRedirdevDevStr(def, redirdev, priv->qemuCaps)))
1294 1295 1296
            goto error;
    }

1297
    if (VIR_REALLOC_N(vm->def->redirdevs, vm->def->nredirdevs+1) < 0)
1298 1299
        goto error;

1300
    qemuDomainObjEnterMonitor(driver, vm);
1301
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE))
1302 1303 1304 1305
        ret = qemuMonitorAddDevice(priv->mon, devstr);
    else
        goto error;

1306
    qemuDomainObjExitMonitor(driver, vm);
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
    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;

}

1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
int
qemuDomainChrInsert(virDomainDefPtr vmdef,
                    virDomainChrDefPtr chr)
{
    if (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE &&
        chr->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("attaching serial console is not supported"));
        return -1;
    }

    if (virDomainChrFind(vmdef, chr)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("chardev already exists"));
        return -1;
    }

    if (virDomainChrInsert(vmdef, chr) < 0)
        return -1;

    /* Due to some crazy backcompat stuff, the first serial device is an alias
     * to the first console too. If this is the case, the definition must be
     * duplicated as first console device. */
    if (vmdef->nserials == 1 && vmdef->nconsoles == 0) {
        if ((!vmdef->consoles && VIR_ALLOC(vmdef->consoles) < 0) ||
            VIR_ALLOC(vmdef->consoles[0]) < 0) {
            virDomainChrRemove(vmdef, chr);
            return -1;
        }
        vmdef->nconsoles = 1;

        /* Create an console alias for the serial port */
        vmdef->consoles[0]->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE;
        vmdef->consoles[0]->targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL;
    }

    return 0;
}

virDomainChrDefPtr
qemuDomainChrRemove(virDomainDefPtr vmdef,
                    virDomainChrDefPtr chr)
{
    virDomainChrDefPtr ret;
    bool removeCompat;

    if (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE &&
        chr->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("detaching serial console is not supported"));
        return NULL;
    }

    /* Due to some crazy backcompat stuff, the first serial device is an alias
     * to the first console too. If this is the case, the definition must be
     * duplicated as first console device. */
    removeCompat = vmdef->nserials && vmdef->nconsoles &&
        vmdef->consoles[0]->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE &&
        vmdef->consoles[0]->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL &&
        virDomainChrEquals(vmdef->serials[0], chr);

    if (!(ret = virDomainChrRemove(vmdef, chr))) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("device not present in domain configuration"));
            return NULL;
    }

    if (removeCompat)
        VIR_DELETE_ELEMENT(vmdef->consoles, 0, vmdef->nconsoles);

    return ret;
}
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404

int qemuDomainAttachChrDevice(virQEMUDriverPtr driver,
                              virDomainObjPtr vm,
                              virDomainChrDefPtr chr)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virDomainDefPtr vmdef = vm->def;
    char *devstr = NULL;
    char *charAlias = NULL;
1405
    bool need_remove = false;
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425

    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("qemu does not support -device"));
        return ret;
    }

    if (qemuAssignDeviceChrAlias(vmdef, chr, -1) < 0)
        return ret;

    if (qemuBuildChrDeviceStr(&devstr, vm->def, chr, priv->qemuCaps) < 0)
        return ret;

    if (virAsprintf(&charAlias, "char%s", chr->info.alias) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (qemuDomainChrInsert(vmdef, chr) < 0)
        goto cleanup;
1426
    need_remove = true;
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443

    qemuDomainObjEnterMonitor(driver, vm);
    if (qemuMonitorAttachCharDev(priv->mon, charAlias, &chr->source) < 0) {
        qemuDomainObjExitMonitor(driver, vm);
        goto cleanup;
    }

    if (devstr && qemuMonitorAddDevice(priv->mon, devstr) < 0) {
        /* detach associated chardev on error */
        qemuMonitorDetachCharDev(priv->mon, charAlias);
        qemuDomainObjExitMonitor(driver, vm);
        goto cleanup;
    }
    qemuDomainObjExitMonitor(driver, vm);

    ret = 0;
cleanup:
1444
    if (ret < 0 && need_remove)
1445 1446 1447 1448 1449 1450
        qemuDomainChrRemove(vmdef, chr);
    VIR_FREE(charAlias);
    VIR_FREE(devstr);
    return ret;
}

1451 1452 1453 1454
static int
qemuDomainAttachHostUsbDevice(virQEMUDriverPtr driver,
                              virDomainObjPtr vm,
                              virDomainHostdevDefPtr hostdev)
1455 1456
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
1457 1458
    virUSBDeviceList *list = NULL;
    virUSBDevicePtr usb = NULL;
1459
    char *devstr = NULL;
1460
    bool added = false;
1461
    bool teardowncgroup = false;
1462
    bool teardownlabel = false;
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
    int ret = -1;

    if (qemuFindHostdevUSBDevice(hostdev, true, &usb) < 0)
        return -1;

    if (!(list = virUSBDeviceListNew()))
        goto cleanup;

    if (virUSBDeviceListAdd(list, usb) < 0)
        goto cleanup;

    if (qemuPrepareHostdevUSBDevices(driver, vm->def->name, list) < 0)
        goto cleanup;

    added = true;
    virUSBDeviceListSteal(list, usb);
1479

1480 1481 1482 1483
    if (qemuSetupHostdevCGroup(vm, hostdev) < 0)
        goto cleanup;
    teardowncgroup = true;

1484 1485 1486 1487 1488
    if (virSecurityManagerSetHostdevLabel(driver->securityManager,
                                          vm->def, hostdev, NULL) < 0)
        goto cleanup;
    teardownlabel = true;

1489
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
1490
        if (qemuAssignDeviceHostdevAlias(vm->def, hostdev, -1) < 0)
1491
            goto cleanup;
1492
        if (!(devstr = qemuBuildUSBHostdevDevStr(vm->def, hostdev, priv->qemuCaps)))
1493
            goto cleanup;
1494 1495
    }

1496
    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs+1) < 0)
1497
        goto cleanup;
1498

1499
    qemuDomainObjEnterMonitor(driver, vm);
1500
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE))
1501 1502 1503 1504 1505
        ret = qemuMonitorAddDevice(priv->mon, devstr);
    else
        ret = qemuMonitorAddUSBDeviceExact(priv->mon,
                                           hostdev->source.subsys.u.usb.bus,
                                           hostdev->source.subsys.u.usb.device);
1506
    qemuDomainObjExitMonitor(driver, vm);
1507
    virDomainAuditHostdev(vm, hostdev, "attach", ret == 0);
1508
    if (ret < 0)
1509
        goto cleanup;
1510 1511 1512

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

1513 1514
    ret = 0;
cleanup:
1515 1516 1517 1518 1519 1520 1521
    if (ret < 0) {
        if (teardowncgroup && qemuTeardownHostdevCgroup(vm, hostdev) < 0)
            VIR_WARN("Unable to remove host device cgroup ACL on hotplug fail");
        if (teardownlabel &&
            virSecurityManagerRestoreHostdevLabel(driver->securityManager,
                                                  vm->def, hostdev, NULL) < 0)
            VIR_WARN("Unable to restore host device labelling on hotplug fail");
1522 1523
        if (added)
            virUSBDeviceListSteal(driver->activeUsbHostdevs, usb);
1524
    }
1525 1526 1527 1528
    if (list && usb &&
        !virUSBDeviceListFind(list, usb) &&
        !virUSBDeviceListFind(driver->activeUsbHostdevs, usb))
        virUSBDeviceFree(usb);
1529
    virObjectUnref(list);
1530
    VIR_FREE(devstr);
1531
    return ret;
1532 1533
}

1534 1535 1536 1537 1538 1539 1540
static int
qemuDomainAttachHostScsiDevice(virQEMUDriverPtr driver,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
1541
    virDomainControllerDefPtr cont = NULL;
1542 1543
    char *devstr = NULL;
    char *drvstr = NULL;
1544
    bool teardowncgroup = false;
1545
    bool teardownlabel = false;
1546 1547 1548 1549 1550 1551 1552 1553 1554

    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DRIVE) ||
        !virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE) ||
        !virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE_SCSI_GENERIC)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("SCSI passthrough is not supported by this version of qemu"));
        return -1;
    }

1555 1556 1557 1558
    cont = qemuDomainFindOrCreateSCSIDiskController(driver, vm, hostdev->info->addr.drive.controller);
    if (!cont)
        return -1;

1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
    if (qemuPrepareHostdevSCSIDevices(driver, vm->def->name,
                                      &hostdev, 1)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to prepare scsi hostdev: %s:%d:%d:%d"),
                       hostdev->source.subsys.u.scsi.adapter,
                       hostdev->source.subsys.u.scsi.bus,
                       hostdev->source.subsys.u.scsi.target,
                       hostdev->source.subsys.u.scsi.unit);
        return -1;
    }

1570 1571 1572 1573
    if (qemuSetupHostdevCGroup(vm, hostdev) < 0)
        goto cleanup;
    teardowncgroup = true;

1574 1575 1576 1577 1578
    if (virSecurityManagerSetHostdevLabel(driver->securityManager,
                                          vm->def, hostdev, NULL) < 0)
        goto cleanup;
    teardownlabel = true;

1579
    if (qemuAssignDeviceHostdevAlias(vm->def, hostdev, -1) < 0)
1580 1581
        goto cleanup;

1582 1583
    if (!(drvstr = qemuBuildSCSIHostdevDrvStr(hostdev, priv->qemuCaps,
                                              &buildCommandLineCallbacks)))
1584 1585 1586 1587 1588
        goto cleanup;

    if (!(devstr = qemuBuildSCSIHostdevDevStr(vm->def, hostdev, priv->qemuCaps)))
        goto cleanup;

1589
    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs + 1) < 0)
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
        goto cleanup;

    qemuDomainObjEnterMonitor(driver, vm);
    if ((ret = qemuMonitorAddDrive(priv->mon, drvstr)) == 0) {
        if ((ret = qemuMonitorAddDevice(priv->mon, devstr)) < 0) {
            virErrorPtr orig_err = virSaveLastError();
            if (qemuMonitorDriveDel(priv->mon, drvstr) < 0)
                VIR_WARN("Unable to remove drive %s (%s) after failed "
                         "qemuMonitorAddDevice",
                         drvstr, devstr);
            if (orig_err) {
                virSetError(orig_err);
                virFreeError(orig_err);
            }
        }
    }
    qemuDomainObjExitMonitor(driver, vm);

    virDomainAuditHostdev(vm, hostdev, "attach", ret == 0);
    if (ret < 0)
        goto cleanup;

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

    ret = 0;
cleanup:
1616
    if (ret < 0) {
1617
        qemuDomainReAttachHostScsiDevices(driver, vm->def->name, &hostdev, 1);
1618 1619
        if (teardowncgroup && qemuTeardownHostdevCgroup(vm, hostdev) < 0)
            VIR_WARN("Unable to remove host device cgroup ACL on hotplug fail");
1620 1621 1622 1623
        if (teardownlabel &&
            virSecurityManagerRestoreHostdevLabel(driver->securityManager,
                                                  vm->def, hostdev, NULL) < 0)
            VIR_WARN("Unable to restore host device labelling on hotplug fail");
1624
    }
1625 1626 1627 1628 1629
    VIR_FREE(drvstr);
    VIR_FREE(devstr);
    return ret;
}

1630
int qemuDomainAttachHostDevice(virQEMUDriverPtr driver,
1631
                               virDomainObjPtr vm,
1632
                               virDomainHostdevDefPtr hostdev)
1633 1634
{
    if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
1635 1636 1637
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev mode '%s' not supported"),
                       virDomainHostdevModeTypeToString(hostdev->mode));
1638 1639 1640 1641 1642 1643
        return -1;
    }

    switch (hostdev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
        if (qemuDomainAttachHostPciDevice(driver, vm,
1644
                                          hostdev) < 0)
1645 1646 1647 1648 1649
            goto error;
        break;

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
        if (qemuDomainAttachHostUsbDevice(driver, vm,
1650
                                          hostdev) < 0)
1651 1652 1653
            goto error;
        break;

1654 1655 1656 1657 1658 1659
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
        if (qemuDomainAttachHostScsiDevice(driver, vm,
                                           hostdev) < 0)
            goto error;
        break;

1660
    default:
1661 1662 1663
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(hostdev->source.subsys.type));
1664 1665 1666 1667 1668 1669 1670 1671 1672
        goto error;
    }

    return 0;

error:
    return -1;
}

1673 1674
static virDomainNetDefPtr *qemuDomainFindNet(virDomainObjPtr vm,
                                             virDomainNetDefPtr dev)
1675
{
1676
    size_t i;
1677 1678

    for (i = 0; i < vm->def->nnets; i++) {
1679
        if (virMacAddrCmp(&vm->def->nets[i]->mac, &dev->mac) == 0)
1680
            return &vm->def->nets[i];
1681 1682 1683 1684 1685
    }

    return NULL;
}

1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
static char *
qemuDomainNetGetBridgeName(virConnectPtr conn, virDomainNetDefPtr net)
{
    char *brname = NULL;
    int actualType = virDomainNetGetActualType(net);

    if (actualType == VIR_DOMAIN_NET_TYPE_BRIDGE) {
        const char *tmpbr = virDomainNetGetActualBridgeName(net);
        if (!tmpbr) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("interface is missing bridge name"));
            goto cleanup;
        }
        /* we need a copy, not just a pointer to the original */
1700
        if (VIR_STRDUP(brname, tmpbr) < 0)
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
            goto cleanup;
    } else if (actualType == VIR_DOMAIN_NET_TYPE_NETWORK) {
        int active;
        virErrorPtr errobj;
        virNetworkPtr network;

        if (!(network = virNetworkLookupByName(conn, net->data.network.name))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Couldn't find network '%s'"),
                           net->data.network.name);
            goto cleanup;
        }

        active = virNetworkIsActive(network);
        if (active == 1) {
            brname = virNetworkGetBridgeName(network);
        } else if (active == 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Network '%s' is not active."),
                           net->data.network.name);
        }

        /* Make sure any above failure is preserved */
        errobj = virSaveLastError();
        virNetworkFree(network);
        virSetError(errobj);
        virFreeError(errobj);

1729 1730 1731 1732
    } else {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Interface type %d has no bridge name"),
                       virDomainNetGetActualType(net));
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
    }

cleanup:
    return brname;
}

static int
qemuDomainChangeNetBridge(virConnectPtr conn,
                          virDomainObjPtr vm,
                          virDomainNetDefPtr olddev,
                          virDomainNetDefPtr newdev)
1744 1745
{
    int ret = -1;
1746 1747 1748 1749 1750 1751 1752
    char *oldbridge = NULL, *newbridge = NULL;

    if (!(oldbridge = qemuDomainNetGetBridgeName(conn, olddev)))
        goto cleanup;

    if (!(newbridge = qemuDomainNetGetBridgeName(conn, newdev)))
        goto cleanup;
1753 1754 1755 1756 1757

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

    if (virNetDevExists(newbridge) != 1) {
1758 1759
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("bridge %s doesn't exist"), newbridge);
1760
        goto cleanup;
1761 1762 1763 1764 1765
    }

    if (oldbridge) {
        ret = virNetDevBridgeRemovePort(oldbridge, olddev->ifname);
        virDomainAuditNet(vm, olddev, NULL, "detach", ret == 0);
1766 1767 1768 1769 1770 1771 1772 1773
        if (ret < 0) {
            /* warn but continue - possibly the old network
             * had been destroyed and reconstructed, leaving the
             * tap device orphaned.
             */
            VIR_WARN("Unable to detach device %s from bridge %s",
                     olddev->ifname, oldbridge);
        }
1774 1775 1776
    }

    ret = virNetDevBridgeAddPort(newbridge, olddev->ifname);
1777
    virDomainAuditNet(vm, NULL, newdev, "attach", ret == 0);
1778 1779 1780 1781
    if (ret < 0) {
        ret = virNetDevBridgeAddPort(oldbridge, olddev->ifname);
        virDomainAuditNet(vm, NULL, olddev, "attach", ret == 0);
        if (ret < 0) {
1782
            virReportError(VIR_ERR_OPERATION_FAILED,
1783
                           _("unable to recover former state by adding port "
1784
                             "to bridge %s"), oldbridge);
1785
        }
1786
        goto cleanup;
1787
    }
1788 1789 1790
    /* caller will replace entire olddev with newdev in domain nets list */
    ret = 0;
cleanup:
1791
    VIR_FREE(oldbridge);
1792 1793
    VIR_FREE(newbridge);
    return ret;
1794 1795
}

1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
static int
qemuDomainChangeNetFilter(virConnectPtr conn,
                          virDomainObjPtr vm,
                          virDomainNetDefPtr olddev,
                          virDomainNetDefPtr newdev)
{
    /* make sure this type of device supports filters. */
    switch (virDomainNetGetActualType(newdev)) {
    case VIR_DOMAIN_NET_TYPE_ETHERNET:
    case VIR_DOMAIN_NET_TYPE_BRIDGE:
    case VIR_DOMAIN_NET_TYPE_NETWORK:
        break;
    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("filters not supported on interfaces of type %s"),
                       virDomainNetTypeToString(virDomainNetGetActualType(newdev)));
        return -1;
    }

    virDomainConfNWFilterTeardown(olddev);

    if (virDomainConfNWFilterInstantiate(conn, vm->def->uuid, newdev) < 0) {
        virErrorPtr errobj;

        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("failed to add new filter rules to '%s' "
                         "- attempting to restore old rules"),
                       olddev->ifname);
        errobj = virSaveLastError();
        ignore_value(virDomainConfNWFilterInstantiate(conn, vm->def->uuid, olddev));
        virSetError(errobj);
        virFreeError(errobj);
        return -1;
    }
    return 0;
}

1833
int qemuDomainChangeNetLinkState(virQEMUDriverPtr driver,
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
                                 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) {
1844 1845
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("can't change link state: device alias not found"));
1846 1847 1848
        return -1;
    }

1849
    qemuDomainObjEnterMonitor(driver, vm);
1850 1851 1852 1853 1854 1855 1856 1857 1858

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

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

cleanup:
1859
    qemuDomainObjExitMonitor(driver, vm);
1860 1861 1862 1863

    return ret;
}

1864
int
1865
qemuDomainChangeNet(virQEMUDriverPtr driver,
1866 1867 1868
                    virDomainObjPtr vm,
                    virDomainPtr dom,
                    virDomainDeviceDefPtr dev)
1869
{
1870 1871 1872 1873 1874 1875
    virDomainNetDefPtr newdev = dev->data.net;
    virDomainNetDefPtr *devslot = qemuDomainFindNet(vm, newdev);
    virDomainNetDefPtr olddev;
    int oldType, newType;
    bool needReconnect = false;
    bool needBridgeChange = false;
1876
    bool needFilterChange = false;
1877 1878
    bool needLinkStateChange = false;
    bool needReplaceDevDef = false;
1879
    bool needBandwidthSet = false;
1880
    int ret = -1;
1881

1882
    if (!devslot || !(olddev = *devslot)) {
1883
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
1884
                       _("cannot find existing network device to modify"));
1885 1886 1887 1888 1889 1890
        goto cleanup;
    }

    oldType = virDomainNetGetActualType(olddev);
    if (oldType == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
        /* no changes are possible to a type='hostdev' interface */
1891
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
                       _("cannot change config of '%s' network type"),
                       virDomainNetTypeToString(oldType));
        goto cleanup;
    }

    /* Check individual attributes for changes that can't be done to a
     * live netdev. These checks *mostly* go in order of the
     * declarations in virDomainNetDef in order to assure nothing is
     * omitted. (exceptiong where noted in comments - in particular,
     * some things require that a new "actual device" be allocated
     * from the network driver first, but we delay doing that until
     * after we've made as many other checks as possible)
     */

    /* type: this can change (with some restrictions), but the actual
     * type of the new device connection isn't known until after we
     * allocate the "actual" device.
     */

    if (virMacAddrCmp(&olddev->mac, &newdev->mac)) {
        char oldmac[VIR_MAC_STRING_BUFLEN], newmac[VIR_MAC_STRING_BUFLEN];

1914
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
1915 1916 1917 1918 1919 1920 1921 1922
                       _("cannot change network interface mac address "
                         "from %s to %s"),
                       virMacAddrFormat(&olddev->mac, oldmac),
                       virMacAddrFormat(&newdev->mac, newmac));
        goto cleanup;
    }

    if (STRNEQ_NULLABLE(olddev->model, newdev->model)) {
1923
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
1924 1925 1926 1927
                       _("cannot modify network device model from %s to %s"),
                       olddev->model ? olddev->model : "(default)",
                       newdev->model ? newdev->model : "(default)");
        goto cleanup;
1928 1929
    }

1930 1931 1932 1933
    if (olddev->model && STREQ(olddev->model, "virtio") &&
        (olddev->driver.virtio.name != newdev->driver.virtio.name ||
         olddev->driver.virtio.txmode != newdev->driver.virtio.txmode ||
         olddev->driver.virtio.ioeventfd != newdev->driver.virtio.ioeventfd ||
1934 1935
         olddev->driver.virtio.event_idx != newdev->driver.virtio.event_idx ||
         olddev->driver.virtio.queues != newdev->driver.virtio.queues)) {
1936
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
                       _("cannot modify virtio network device driver attributes"));
        goto cleanup;
    }

    /* data: this union will be examined later, after allocating new actualdev */
    /* virtPortProfile: will be examined later, after allocating new actualdev */

    if (olddev->tune.sndbuf_specified != newdev->tune.sndbuf_specified ||
        olddev->tune.sndbuf != newdev->tune.sndbuf) {
        needReconnect = true;
1947 1948
    }

1949
    if (STRNEQ_NULLABLE(olddev->script, newdev->script)) {
1950
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1951 1952
                       _("cannot modify network device script attribute"));
        goto cleanup;
1953 1954
    }

1955
    /* ifname: check if it's set in newdev. If not, retain the autogenerated one */
1956
    if (!newdev->ifname && VIR_STRDUP(newdev->ifname, olddev->ifname) < 0)
1957 1958
        goto cleanup;
    if (STRNEQ_NULLABLE(olddev->ifname, newdev->ifname)) {
1959
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1960 1961 1962
                       _("cannot modify network device tap name"));
        goto cleanup;
    }
1963

1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
    /* info: if newdev->info is empty, fill it in from olddev,
     * otherwise verify that it matches - nothing is allowed to
     * change. (There is no helper function to do this, so
     * individually check the few feidls of virDomainDeviceInfo that
     * are relevant in this case).
     */
    if (!virDomainDeviceAddressIsValid(&newdev->info,
                                       VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) &&
        virDomainDeviceInfoCopy(&newdev->info, &olddev->info) < 0) {
        goto cleanup;
    }
    if (!virDevicePCIAddressEqual(&olddev->info.addr.pci,
                                  &newdev->info.addr.pci)) {
1977
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1978 1979 1980 1981
                       _("cannot modify network device guest PCI address"));
        goto cleanup;
    }
    /* grab alias from olddev if not set in newdev */
1982 1983
    if (!newdev->info.alias &&
        VIR_STRDUP(newdev->info.alias, olddev->info.alias) < 0)
1984 1985
        goto cleanup;
    if (STRNEQ_NULLABLE(olddev->info.alias, newdev->info.alias)) {
1986
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1987 1988 1989 1990
                       _("cannot modify network device alias"));
        goto cleanup;
    }
    if (olddev->info.rombar != newdev->info.rombar) {
1991
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1992 1993 1994 1995
                       _("cannot modify network device rom bar setting"));
        goto cleanup;
    }
    if (STRNEQ_NULLABLE(olddev->info.romfile, newdev->info.romfile)) {
1996
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1997 1998 1999 2000
                       _("cannot modify network rom file"));
        goto cleanup;
    }
    if (olddev->info.bootIndex != newdev->info.bootIndex) {
2001
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
2002 2003 2004 2005
                       _("cannot modify network device boot index setting"));
        goto cleanup;
    }
    /* (end of device info checks) */
2006

2007 2008 2009 2010
    if (STRNEQ_NULLABLE(olddev->filter, newdev->filter) ||
        !virNWFilterHashTableEqual(olddev->filterparams, newdev->filterparams)) {
        needFilterChange = true;
    }
2011

2012 2013 2014 2015 2016 2017 2018 2019
    /* bandwidth can be modified, and will be checked later */
    /* vlan can be modified, and will be checked later */
    /* linkstate can be modified */

    /* allocate new actual device to compare to old - we will need to
     * free it if we fail for any reason
     */
    if (newdev->type == VIR_DOMAIN_NET_TYPE_NETWORK &&
2020
        networkAllocateActualDevice(vm->def, newdev) < 0) {
2021 2022 2023 2024 2025 2026 2027
        goto cleanup;
    }

    newType = virDomainNetGetActualType(newdev);

    if (newType == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
        /* can't turn it into a type='hostdev' interface */
2028
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
2029 2030 2031 2032 2033 2034
                       _("cannot change network interface type to '%s'"),
                       virDomainNetTypeToString(newType));
        goto cleanup;
    }

    if (olddev->type == newdev->type && oldType == newType) {
2035

2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
        /* if type hasn't changed, check the relevant fields for the type */
        switch (newdev->type) {
        case VIR_DOMAIN_NET_TYPE_USER:
            break;

        case VIR_DOMAIN_NET_TYPE_ETHERNET:
            if (STRNEQ_NULLABLE(olddev->data.ethernet.dev,
                                newdev->data.ethernet.dev) ||
                STRNEQ_NULLABLE(olddev->data.ethernet.ipaddr,
                                newdev->data.ethernet.ipaddr)) {
                needReconnect = true;
            }
2048 2049
        break;

2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
        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,
                                newdev->data.socket.address) ||
                olddev->data.socket.port != newdev->data.socket.port) {
                needReconnect = true;
            }
            break;

        case VIR_DOMAIN_NET_TYPE_NETWORK:
            if (STRNEQ(olddev->data.network.name, newdev->data.network.name)) {
                if (virDomainNetGetActualVirtPortProfile(newdev))
                    needReconnect = true;
                else
                    needBridgeChange = true;
            }
            /* other things handled in common code directly below this switch */
            break;

        case VIR_DOMAIN_NET_TYPE_BRIDGE:
            /* all handled in bridge name checked in common code below */
            break;

        case VIR_DOMAIN_NET_TYPE_INTERNAL:
            if (STRNEQ_NULLABLE(olddev->data.internal.name,
                                newdev->data.internal.name)) {
                needReconnect = true;
            }
            break;

        case VIR_DOMAIN_NET_TYPE_DIRECT:
            /* all handled in common code directly below this switch */
            break;

        default:
2086
            virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
2087 2088 2089
                           _("unable to change config on '%s' network type"),
                           virDomainNetTypeToString(newdev->type));
            break;
2090

2091
        }
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
    } else {
        /* interface type has changed. There are a few special cases
         * where this can only require a minor (or even no) change,
         * but in most cases we need to do a full reconnection.
         *
         * If we switch (in either direction) between type='bridge'
         * and type='network' (for a traditional managed virtual
         * network that uses a host bridge, i.e. forward
         * mode='route|nat'), we just need to change the bridge.
         */
        if ((oldType == VIR_DOMAIN_NET_TYPE_NETWORK &&
             newType == VIR_DOMAIN_NET_TYPE_BRIDGE) ||
            (oldType == VIR_DOMAIN_NET_TYPE_BRIDGE &&
             newType == VIR_DOMAIN_NET_TYPE_NETWORK)) {

            needBridgeChange = true;

        } else if (oldType == VIR_DOMAIN_NET_TYPE_DIRECT &&
                   newType == VIR_DOMAIN_NET_TYPE_DIRECT) {

            /* this is the case of switching from type='direct' to
             * type='network' for a network that itself uses direct
             * (macvtap) devices. If the physical device and mode are
             * the same, this doesn't require any actual setup
             * change. If the physical device or mode *does* change,
             * that will be caught in the common section below */

        } else {

            /* for all other combinations, we'll need a full reconnect */
            needReconnect = true;
2123 2124

        }
2125
    }
2126

2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137
    /* now several things that are in multiple (but not all)
     * different types, and can be safely compared even for those
     * cases where they don't apply to a particular type.
     */
    if (STRNEQ_NULLABLE(virDomainNetGetActualBridgeName(olddev),
                        virDomainNetGetActualBridgeName(newdev))) {
        if (virDomainNetGetActualVirtPortProfile(newdev))
            needReconnect = true;
        else
            needBridgeChange = true;
    }
2138

2139 2140 2141 2142 2143 2144 2145 2146
    if (STRNEQ_NULLABLE(virDomainNetGetActualDirectDev(olddev),
                        virDomainNetGetActualDirectDev(newdev)) ||
        virDomainNetGetActualDirectMode(olddev) != virDomainNetGetActualDirectMode(olddev) ||
        !virNetDevVPortProfileEqual(virDomainNetGetActualVirtPortProfile(olddev),
                                    virDomainNetGetActualVirtPortProfile(newdev)) ||
        !virNetDevVlanEqual(virDomainNetGetActualVlan(olddev),
                            virDomainNetGetActualVlan(newdev))) {
        needReconnect = true;
2147 2148
    }

2149 2150 2151
    if (olddev->linkstate != newdev->linkstate)
        needLinkStateChange = true;

2152 2153 2154 2155
    if (!virNetDevBandwidthEqual(virDomainNetGetActualBandwidth(olddev),
                                 virDomainNetGetActualBandwidth(newdev)))
        needBandwidthSet = true;

2156 2157 2158
    /* FINALLY - actually perform the required actions */

    if (needReconnect) {
2159
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
2160 2161 2162
                       _("unable to change config on '%s' network type"),
                       virDomainNetTypeToString(newdev->type));
        goto cleanup;
2163 2164
    }

2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
    if (needBandwidthSet) {
        if (virNetDevBandwidthSet(newdev->ifname,
                                  virDomainNetGetActualBandwidth(newdev),
                                  false) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot set bandwidth limits on %s"),
                           newdev->ifname);
            goto cleanup;
        }
        needReplaceDevDef = true;
    }

2177 2178 2179 2180 2181
    if (needBridgeChange) {
        if (qemuDomainChangeNetBridge(dom->conn, vm, olddev, newdev) < 0)
            goto cleanup;
        /* we successfully switched to the new bridge, and we've
         * determined that the rest of newdev is equivalent to olddev,
2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
         * so move newdev into place */
        needReplaceDevDef = true;
    }

    if (needFilterChange) {
        if (qemuDomainChangeNetFilter(dom->conn, vm, olddev, newdev) < 0)
            goto cleanup;
        /* we successfully switched to the new filter, and we've
         * determined that the rest of newdev is equivalent to olddev,
         * so move newdev into place */
2192
        needReplaceDevDef = true;
2193 2194
    }

2195 2196 2197
    if (needLinkStateChange &&
        qemuDomainChangeNetLinkState(driver, vm, olddev, newdev->linkstate) < 0) {
        goto cleanup;
2198 2199
    }

2200 2201 2202 2203
    if (needReplaceDevDef) {
        /* the changes above warrant replacing olddev with newdev in
         * the domain's nets list.
         */
2204 2205 2206

        /* this function doesn't work with HOSTDEV networks yet, thus
         * no need to change the pointer in the hostdev structure */
2207
        networkReleaseActualDevice(vm->def, olddev);
2208 2209 2210 2211 2212 2213 2214 2215
        virDomainNetDefFree(olddev);
        /* move newdev into the nets list, and NULL it out from the
         * virDomainDeviceDef that we were given so that the caller
         * won't delete it on return.
         */
        *devslot = newdev;
        newdev = dev->data.net = NULL;
        dev->type = VIR_DOMAIN_DEVICE_NONE;
2216 2217
    }

2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
    ret = 0;
cleanup:
    /* When we get here, we will be in one of these two states:
     *
     * 1) newdev has been moved into the domain's list of nets and
     *    newdev set to NULL, and dev->data.net will be NULL (and
     *    dev->type is NONE). olddev will have been completely
     *    released and freed. (aka success) In this case no extra
     *    cleanup is needed.
     *
     * 2) newdev has *not* been moved into the domain's list of nets,
     *    and dev->data.net == newdev (and dev->type == NET). In this *
     *    case, we need to at least release the "actual device" from *
     *    newdev (the caller will free dev->data.net a.k.a. newdev, and
     *    the original olddev is still in used)
     *
     * Note that case (2) isn't necessarily a failure. It may just be
     * that the changes were minor enough that we didn't need to
     * replace the entire device object.
     */
    if (newdev)
2239
        networkReleaseActualDevice(vm->def, newdev);
2240

2241 2242 2243 2244
    return ret;
}


2245 2246 2247 2248

static virDomainGraphicsDefPtr qemuDomainFindGraphics(virDomainObjPtr vm,
                                                      virDomainGraphicsDefPtr dev)
{
2249
    size_t i;
2250

2251
    for (i = 0; i < vm->def->ngraphics; i++) {
2252 2253 2254 2255 2256 2257 2258 2259 2260
        if (vm->def->graphics[i]->type == dev->type)
            return vm->def->graphics[i];
    }

    return NULL;
}


int
2261
qemuDomainChangeGraphics(virQEMUDriverPtr driver,
2262 2263 2264 2265 2266
                         virDomainObjPtr vm,
                         virDomainGraphicsDefPtr dev)
{
    virDomainGraphicsDefPtr olddev = qemuDomainFindGraphics(vm, dev);
    int ret = -1;
2267
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2268
    size_t i;
2269 2270

    if (!olddev) {
2271 2272
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot find existing graphics device to modify"));
2273
        goto cleanup;
2274 2275
    }

2276 2277 2278 2279 2280 2281 2282
    if (dev->nListens != olddev->nListens) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("cannot change the number of listen addresses"));
        goto cleanup;
    }

    for (i = 0; i < dev->nListens; i++) {
J
Jim Fehlig 已提交
2283
        virDomainGraphicsListenDefPtr newlisten = &dev->listens[i];
2284 2285
        virDomainGraphicsListenDefPtr oldlisten = &olddev->listens[i];

J
Jim Fehlig 已提交
2286
        if (newlisten->type != oldlisten->type) {
2287 2288 2289 2290 2291
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("cannot change the type of listen address"));
            goto cleanup;
        }

J
Jim Fehlig 已提交
2292
        switch ((enum virDomainGraphicsListenType) newlisten->type) {
2293
        case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS:
J
Jim Fehlig 已提交
2294
            if (STRNEQ_NULLABLE(newlisten->address, oldlisten->address)) {
2295 2296 2297 2298 2299 2300 2301 2302 2303
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               dev->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC ?
                               _("cannot change listen address setting on vnc graphics") :
                               _("cannot change listen address setting on spice graphics"));
                goto cleanup;
            }
            break;

        case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK:
J
Jim Fehlig 已提交
2304
            if (STRNEQ_NULLABLE(newlisten->network, oldlisten->network)) {
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               dev->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC ?
                           _("cannot change listen network setting on vnc graphics") :
                           _("cannot change listen network setting on spice graphics"));
                goto cleanup;
            }
            break;

        case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NONE:
        case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_LAST:
            /* nada */
            break;
        }
    }
2319

2320 2321 2322
    switch (dev->type) {
    case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
        if ((olddev->data.vnc.autoport != dev->data.vnc.autoport) ||
E
Eric Blake 已提交
2323 2324
            (!dev->data.vnc.autoport &&
             (olddev->data.vnc.port != dev->data.vnc.port))) {
2325 2326
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change port settings on vnc graphics"));
2327
            goto cleanup;
2328 2329
        }
        if (STRNEQ_NULLABLE(olddev->data.vnc.keymap, dev->data.vnc.keymap)) {
2330 2331
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change keymap setting on vnc graphics"));
2332
            goto cleanup;
2333 2334
        }

2335 2336 2337
        /* 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 */
2338 2339
        if (olddev->data.vnc.auth.expires ||
            dev->data.vnc.auth.expires ||
2340
            olddev->data.vnc.auth.connected != dev->data.vnc.auth.connected ||
E
Eric Blake 已提交
2341 2342 2343
            STRNEQ_NULLABLE(olddev->data.vnc.auth.passwd,
                            dev->data.vnc.auth.passwd)) {
            VIR_DEBUG("Updating password on VNC server %p %p",
2344
                      dev->data.vnc.auth.passwd, cfg->vncPassword);
E
Eric Blake 已提交
2345 2346 2347
            ret = qemuDomainChangeGraphicsPasswords(driver, vm,
                                                    VIR_DOMAIN_GRAPHICS_TYPE_VNC,
                                                    &dev->data.vnc.auth,
2348
                                                    cfg->vncPassword);
2349
            if (ret < 0)
2350
                goto cleanup;
2351 2352 2353 2354 2355

            /* 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;
2356 2357
            olddev->data.vnc.auth.validTo = dev->data.vnc.auth.validTo;
            olddev->data.vnc.auth.expires = dev->data.vnc.auth.expires;
2358
            olddev->data.vnc.auth.connected = dev->data.vnc.auth.connected;
2359 2360 2361 2362 2363
        } else {
            ret = 0;
        }
        break;

2364 2365
    case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
        if ((olddev->data.spice.autoport != dev->data.spice.autoport) ||
E
Eric Blake 已提交
2366 2367 2368 2369
            (!dev->data.spice.autoport &&
             (olddev->data.spice.port != dev->data.spice.port)) ||
            (!dev->data.spice.autoport &&
             (olddev->data.spice.tlsPort != dev->data.spice.tlsPort))) {
2370 2371
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change port settings on spice graphics"));
2372
            goto cleanup;
2373
        }
E
Eric Blake 已提交
2374 2375
        if (STRNEQ_NULLABLE(olddev->data.spice.keymap,
                            dev->data.spice.keymap)) {
2376
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2377
                            _("cannot change keymap setting on spice graphics"));
2378
            goto cleanup;
2379 2380
        }

2381 2382 2383 2384 2385
        /* 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"
         */
2386 2387
        if (olddev->data.spice.auth.expires ||
            dev->data.spice.auth.expires ||
2388
            olddev->data.spice.auth.connected != dev->data.spice.auth.connected ||
2389 2390
            dev->data.spice.auth.connected ==
            VIR_DOMAIN_GRAPHICS_AUTH_CONNECTED_DISCONNECT ||
E
Eric Blake 已提交
2391 2392 2393
            STRNEQ_NULLABLE(olddev->data.spice.auth.passwd,
                            dev->data.spice.auth.passwd)) {
            VIR_DEBUG("Updating password on SPICE server %p %p",
2394
                      dev->data.spice.auth.passwd, cfg->spicePassword);
E
Eric Blake 已提交
2395 2396 2397
            ret = qemuDomainChangeGraphicsPasswords(driver, vm,
                                                    VIR_DOMAIN_GRAPHICS_TYPE_SPICE,
                                                    &dev->data.spice.auth,
2398
                                                    cfg->spicePassword);
E
Eric Blake 已提交
2399

2400
            if (ret < 0)
2401
                goto cleanup;
2402

E
Eric Blake 已提交
2403
            /* Steal the new dev's char * reference */
2404 2405 2406 2407 2408
            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;
2409
            olddev->data.spice.auth.connected = dev->data.spice.auth.connected;
2410
        } else {
2411
            VIR_DEBUG("Not updating since password didn't change");
2412 2413
            ret = 0;
        }
E
Eric Blake 已提交
2414
        break;
2415

2416
    default:
2417 2418 2419
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unable to change config on '%s' graphics type"),
                       virDomainGraphicsTypeToString(dev->type));
2420 2421 2422
        break;
    }

2423 2424
cleanup:
    virObjectUnref(cfg);
2425 2426 2427 2428
    return ret;
}


2429
static int qemuComparePCIDevice(virDomainDefPtr def ATTRIBUTE_UNUSED,
2430
                                virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
2431
                                virDomainDeviceInfoPtr info1,
2432 2433
                                void *opaque)
{
2434
    virDomainDeviceInfoPtr info2 = opaque;
2435

2436 2437
    if (info1->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI ||
        info2->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)
2438 2439
        return 0;

2440 2441 2442
    if (info1->addr.pci.domain == info2->addr.pci.domain &&
        info1->addr.pci.bus == info2->addr.pci.bus &&
        info1->addr.pci.slot == info2->addr.pci.slot &&
2443
        info1->addr.pci.function != info2->addr.pci.function)
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
        return -1;
    return 0;
}

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

2456

2457 2458 2459 2460 2461 2462
static void
qemuDomainRemoveDiskDevice(virQEMUDriverPtr driver,
                           virDomainObjPtr vm,
                           virDomainDiskDefPtr disk)
{
    virDomainDeviceDef dev;
2463
    virObjectEventPtr event;
2464 2465 2466 2467 2468 2469 2470
    size_t i;

    VIR_DEBUG("Removing disk %s from domain %p %s",
              disk->info.alias, vm, vm->def->name);

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

2471 2472 2473 2474
    event = virDomainEventDeviceRemovedNewFromObj(vm, disk->info.alias);
    if (event)
        qemuDomainEventQueue(driver, event);

2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501
    for (i = 0; i < vm->def->ndisks; i++) {
        if (vm->def->disks[i] == disk) {
            virDomainDiskRemove(vm->def, i);
            break;
        }
    }

    qemuDomainReleaseDeviceAddress(vm, &disk->info, disk->src);

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

    if (qemuTeardownDiskCgroup(vm, disk) < 0)
        VIR_WARN("Failed to tear down cgroup for disk path %s", disk->src);

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

    dev.type = VIR_DOMAIN_DEVICE_DISK;
    dev.data.disk = disk;
    ignore_value(qemuRemoveSharedDevice(driver, &dev, vm->def->name));

    virDomainDiskDefFree(disk);
}


2502
static void
2503
qemuDomainRemoveControllerDevice(virQEMUDriverPtr driver,
2504 2505 2506
                                 virDomainObjPtr vm,
                                 virDomainControllerDefPtr controller)
{
2507
    virObjectEventPtr event;
2508 2509 2510 2511 2512
    size_t i;

    VIR_DEBUG("Removing controller %s from domain %p %s",
              controller->info.alias, vm, vm->def->name);

2513 2514 2515 2516
    event = virDomainEventDeviceRemovedNewFromObj(vm, controller->info.alias);
    if (event)
        qemuDomainEventQueue(driver, event);

2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
    for (i = 0; i < vm->def->ncontrollers; i++) {
        if (vm->def->controllers[i] == controller) {
            virDomainControllerRemove(vm->def, i);
            break;
        }
    }

    qemuDomainReleaseDeviceAddress(vm, &controller->info, NULL);
    virDomainControllerDefFree(controller);
}


2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
static void
qemuDomainRemovePCIHostDevice(virQEMUDriverPtr driver,
                              virDomainObjPtr vm,
                              virDomainHostdevDefPtr hostdev)
{
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
    virPCIDevicePtr pci;
    virPCIDevicePtr activePci;

    virObjectLock(driver->activePciHostdevs);
    virObjectLock(driver->inactivePciHostdevs);
    pci = virPCIDeviceNew(subsys->u.pci.addr.domain, subsys->u.pci.addr.bus,
                          subsys->u.pci.addr.slot, subsys->u.pci.addr.function);
    if (pci) {
        activePci = virPCIDeviceListSteal(driver->activePciHostdevs, pci);
        if (activePci &&
            virPCIDeviceReset(activePci, driver->activePciHostdevs,
                              driver->inactivePciHostdevs) == 0) {
            qemuReattachPciDevice(activePci, driver);
        } else {
            /* reset of the device failed, treat it as if it was returned */
            virPCIDeviceFree(activePci);
        }
        virPCIDeviceFree(pci);
    }
    virObjectUnlock(driver->activePciHostdevs);
    virObjectUnlock(driver->inactivePciHostdevs);

    qemuDomainReleaseDeviceAddress(vm, hostdev->info, NULL);
}

static void
qemuDomainRemoveUSBHostDevice(virQEMUDriverPtr driver,
                              virDomainObjPtr vm ATTRIBUTE_UNUSED,
                              virDomainHostdevDefPtr hostdev)
{
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
    virUSBDevicePtr usb;

    usb = virUSBDeviceNew(subsys->u.usb.bus, subsys->u.usb.device, NULL);
    if (usb) {
        virObjectLock(driver->activeUsbHostdevs);
        virUSBDeviceListDel(driver->activeUsbHostdevs, usb);
        virObjectUnlock(driver->activeUsbHostdevs);
        virUSBDeviceFree(usb);
    } else {
        VIR_WARN("Unable to find device %03d.%03d in list of used USB devices",
                 subsys->u.usb.bus, subsys->u.usb.device);
    }
}

static void
qemuDomainRemoveSCSIHostDevice(virQEMUDriverPtr driver,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
    qemuDomainReAttachHostScsiDevices(driver, vm->def->name, &hostdev, 1);
}

static void
qemuDomainRemoveHostDevice(virQEMUDriverPtr driver,
                           virDomainObjPtr vm,
                           virDomainHostdevDefPtr hostdev)
{
2593
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2594
    virDomainNetDefPtr net = NULL;
2595
    virObjectEventPtr event;
2596 2597 2598 2599 2600
    size_t i;

    VIR_DEBUG("Removing host device %s from domain %p %s",
              hostdev->info->alias, vm, vm->def->name);

2601 2602 2603 2604
    event = virDomainEventDeviceRemovedNewFromObj(vm, hostdev->info->alias);
    if (event)
        qemuDomainEventQueue(driver, event);

2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624
    if (hostdev->parent.type == VIR_DOMAIN_DEVICE_NET) {
        net = hostdev->parent.data.net;

        for (i = 0; i < vm->def->nnets; i++) {
            if (vm->def->nets[i] == net) {
                virDomainNetRemove(vm->def, i);
                break;
            }
        }
    }

    for (i = 0; i < vm->def->nhostdevs; i++) {
        if (vm->def->hostdevs[i] == hostdev) {
            virDomainHostdevRemove(vm->def, i);
            break;
        }
    }

    virDomainAuditHostdev(vm, hostdev, "detach", true);

2625 2626
    qemuDomainHostdevNetConfigRestore(hostdev, cfg->stateDir);

2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
    switch ((enum virDomainHostdevSubsysType) hostdev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
        qemuDomainRemovePCIHostDevice(driver, vm, hostdev);
        break;
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
        qemuDomainRemoveUSBHostDevice(driver, vm, hostdev);
        break;
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
        qemuDomainRemoveSCSIHostDevice(driver, vm, hostdev);
        break;
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_LAST:
        break;
    }

    if (qemuTeardownHostdevCgroup(vm, hostdev) < 0)
        VIR_WARN("Failed to remove host device cgroup ACL");

    if (virSecurityManagerRestoreHostdevLabel(driver->securityManager,
                                              vm->def, hostdev, NULL) < 0) {
        VIR_WARN("Failed to restore host device labelling");
    }

    virDomainHostdevDefFree(hostdev);

    if (net) {
2652
        networkReleaseActualDevice(vm->def, net);
2653 2654
        virDomainNetDefFree(net);
    }
2655
    virObjectUnref(cfg);
2656 2657 2658
}


2659 2660 2661 2662 2663 2664 2665
static void
qemuDomainRemoveNetDevice(virQEMUDriverPtr driver,
                          virDomainObjPtr vm,
                          virDomainNetDefPtr net)
{
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
    virNetDevVPortProfilePtr vport;
2666
    virObjectEventPtr event;
2667 2668
    size_t i;

2669 2670 2671 2672 2673 2674
    if (virDomainNetGetActualType(net) == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
        /* this function handles all hostdev and netdev cleanup */
        qemuDomainRemoveHostDevice(driver, vm, virDomainNetGetActualHostdev(net));
        return;
    }

2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719
    VIR_DEBUG("Removing network interface %s from domain %p %s",
              net->info.alias, vm, vm->def->name);

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

    event = virDomainEventDeviceRemovedNewFromObj(vm, net->info.alias);
    if (event)
        qemuDomainEventQueue(driver, event);

    for (i = 0; i < vm->def->nnets; i++) {
        if (vm->def->nets[i] == net) {
            virDomainNetRemove(vm->def, i);
            break;
        }
    }

    qemuDomainReleaseDeviceAddress(vm, &net->info, NULL);
    virDomainConfNWFilterTeardown(net);

    if (virDomainNetGetActualType(net) == VIR_DOMAIN_NET_TYPE_DIRECT) {
        ignore_value(virNetDevMacVLanDeleteWithVPortProfile(
                         net->ifname, &net->mac,
                         virDomainNetGetActualDirectDev(net),
                         virDomainNetGetActualDirectMode(net),
                         virDomainNetGetActualVirtPortProfile(net),
                         cfg->stateDir));
        VIR_FREE(net->ifname);
    }

    if (cfg->macFilter && (net->ifname != NULL)) {
        if ((errno = networkDisallowMacOnPort(driver,
                                              net->ifname,
                                              &net->mac))) {
            virReportSystemError(errno,
             _("failed to remove ebtables rule on '%s'"),
                                 net->ifname);
        }
    }

    vport = virDomainNetGetActualVirtPortProfile(net);
    if (vport && vport->virtPortType == VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH)
        ignore_value(virNetDevOpenvswitchRemovePort(
                        virDomainNetGetActualBridgeName(net),
                        net->ifname));

2720
    networkReleaseActualDevice(vm->def, net);
2721 2722 2723 2724 2725
    virDomainNetDefFree(net);
    virObjectUnref(cfg);
}


2726
static void
2727
qemuDomainRemoveChrDevice(virQEMUDriverPtr driver,
2728 2729 2730
                          virDomainObjPtr vm,
                          virDomainChrDefPtr chr)
{
2731
    virObjectEventPtr event;
2732

2733 2734 2735
    VIR_DEBUG("Removing character device %s from domain %p %s",
              chr->info.alias, vm, vm->def->name);

2736 2737 2738 2739
    event = virDomainEventDeviceRemovedNewFromObj(vm, chr->info.alias);
    if (event)
        qemuDomainEventQueue(driver, event);

2740 2741 2742 2743 2744
    qemuDomainChrRemove(vm->def, chr);
    virDomainChrDefFree(chr);
}


2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826
void
qemuDomainRemoveDevice(virQEMUDriverPtr driver,
                       virDomainObjPtr vm,
                       virDomainDeviceDefPtr dev)
{
    switch ((virDomainDeviceType) dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
        qemuDomainRemoveDiskDevice(driver, vm, dev->data.disk);
        break;
    case VIR_DOMAIN_DEVICE_CONTROLLER:
        qemuDomainRemoveControllerDevice(driver, vm, dev->data.controller);
        break;
    case VIR_DOMAIN_DEVICE_NET:
        qemuDomainRemoveNetDevice(driver, vm, dev->data.net);
        break;
    case VIR_DOMAIN_DEVICE_HOSTDEV:
        qemuDomainRemoveHostDevice(driver, vm, dev->data.hostdev);
        break;

    case VIR_DOMAIN_DEVICE_CHR:
        qemuDomainRemoveChrDevice(driver, vm, dev->data.chr);
        break;

    case VIR_DOMAIN_DEVICE_NONE:
    case VIR_DOMAIN_DEVICE_LEASE:
    case VIR_DOMAIN_DEVICE_FS:
    case VIR_DOMAIN_DEVICE_INPUT:
    case VIR_DOMAIN_DEVICE_SOUND:
    case VIR_DOMAIN_DEVICE_VIDEO:
    case VIR_DOMAIN_DEVICE_WATCHDOG:
    case VIR_DOMAIN_DEVICE_GRAPHICS:
    case VIR_DOMAIN_DEVICE_HUB:
    case VIR_DOMAIN_DEVICE_REDIRDEV:
    case VIR_DOMAIN_DEVICE_SMARTCARD:
    case VIR_DOMAIN_DEVICE_MEMBALLOON:
    case VIR_DOMAIN_DEVICE_NVRAM:
    case VIR_DOMAIN_DEVICE_RNG:
    case VIR_DOMAIN_DEVICE_LAST:
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("don't know how to remove a %s device"),
                       virDomainDeviceTypeToString(dev->type));
        break;
    }
}


static void
qemuDomainMarkDeviceForRemoval(virDomainObjPtr vm,
                               virDomainDeviceInfoPtr info)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE_DEL_EVENT))
        priv->unpluggingDevice = info->alias;
    else
        priv->unpluggingDevice = NULL;
}

static void
qemuDomainResetDeviceRemoval(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    priv->unpluggingDevice = NULL;
}

/* Returns:
 *  -1 on error
 *   0 when DEVICE_DELETED event is unsupported
 *   1 when device removal finished
 *   2 device removal did not finish in QEMU_REMOVAL_WAIT_TIME
 */
static int
qemuDomainWaitForDeviceRemoval(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    unsigned long long until;

    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE_DEL_EVENT))
        return 0;

    if (virTimeMillisNow(&until) < 0)
        return -1;
2827
    until += qemuDomainRemoveDeviceWaitTime;
2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857

    while (priv->unpluggingDevice) {
        if (virCondWaitUntil(&priv->unplugFinished,
                             &vm->parent.lock, until) < 0) {
            if (errno == ETIMEDOUT) {
                return 2;
            } else {
                virReportSystemError(errno, "%s",
                                     _("Unable to wait on unplug condition"));
                return -1;
            }
        }
    }

    return 1;
}

void
qemuDomainSignalDeviceRemoval(virDomainObjPtr vm,
                              const char *devAlias)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (STREQ_NULLABLE(priv->unpluggingDevice, devAlias)) {
        qemuDomainResetDeviceRemoval(vm);
        virCondSignal(&priv->unplugFinished);
    }
}


2858 2859 2860 2861
static int
qemuDomainDetachVirtioDiskDevice(virQEMUDriverPtr driver,
                                 virDomainObjPtr vm,
                                 virDomainDiskDefPtr detach)
2862
{
2863
    int ret = -1;
2864 2865 2866
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *drivestr = NULL;

2867
    if (qemuIsMultiFunctionDevice(vm->def, &detach->info)) {
2868 2869
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %s"),
2870
                       detach->dst);
2871 2872 2873
        goto cleanup;
    }

2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888
    if (STREQLEN(vm->def->os.machine, "s390-ccw", 8) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_CCW)) {
        if (!virDomainDeviceAddressIsValid(&detach->info,
                                           VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW)) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("device cannot be detached without a valid CCW address"));
            goto cleanup;
        }
    } else {
        if (!virDomainDeviceAddressIsValid(&detach->info,
                                           VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("device cannot be detached without a valid PCI address"));
            goto cleanup;
        }
2889 2890 2891 2892 2893
    }

    /* 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",
2894
                    QEMU_DRIVE_HOST_PREFIX, detach->info.alias) < 0)
2895 2896
        goto cleanup;

2897 2898
    qemuDomainMarkDeviceForRemoval(vm, &detach->info);

2899
    qemuDomainObjEnterMonitor(driver, vm);
2900
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
2901
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
2902
            qemuDomainObjExitMonitor(driver, vm);
2903
            virDomainAuditDisk(vm, detach->src, NULL, "detach", false);
2904 2905 2906 2907 2908
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
2909
            qemuDomainObjExitMonitor(driver, vm);
2910
            virDomainAuditDisk(vm, detach->src, NULL, "detach", false);
2911 2912 2913 2914 2915 2916 2917
            goto cleanup;
        }
    }

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

2918
    qemuDomainObjExitMonitor(driver, vm);
2919

2920 2921
    if (!qemuDomainWaitForDeviceRemoval(vm))
        qemuDomainRemoveDiskDevice(driver, vm, detach);
2922 2923 2924
    ret = 0;

cleanup:
2925
    qemuDomainResetDeviceRemoval(vm);
2926 2927 2928 2929
    VIR_FREE(drivestr);
    return ret;
}

2930 2931 2932 2933
static int
qemuDomainDetachDiskDevice(virQEMUDriverPtr driver,
                           virDomainObjPtr vm,
                           virDomainDiskDefPtr detach)
2934
{
2935
    int ret = -1;
2936 2937 2938
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *drivestr = NULL;

2939
    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
2940 2941
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Underlying qemu does not support %s disk removal"),
2942
                       virDomainDiskBusTypeToString(detach->bus));
2943 2944 2945
        goto cleanup;
    }

E
Eric Blake 已提交
2946 2947 2948 2949 2950 2951 2952
    if (detach->mirror) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE,
                       _("disk '%s' is in an active block copy job"),
                       detach->dst);
        goto cleanup;
    }

2953 2954 2955
    /* 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",
2956
                    QEMU_DRIVE_HOST_PREFIX, detach->info.alias) < 0)
2957 2958
        goto cleanup;

2959 2960
    qemuDomainMarkDeviceForRemoval(vm, &detach->info);

2961
    qemuDomainObjEnterMonitor(driver, vm);
2962
    if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
2963
        qemuDomainObjExitMonitor(driver, vm);
2964
        virDomainAuditDisk(vm, detach->src, NULL, "detach", false);
2965 2966 2967 2968 2969 2970
        goto cleanup;
    }

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

2971
    qemuDomainObjExitMonitor(driver, vm);
2972

2973 2974
    if (!qemuDomainWaitForDeviceRemoval(vm))
        qemuDomainRemoveDiskDevice(driver, vm, detach);
2975 2976 2977
    ret = 0;

cleanup:
2978
    qemuDomainResetDeviceRemoval(vm);
2979 2980 2981 2982
    VIR_FREE(drivestr);
    return ret;
}

2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035
static int
qemuFindDisk(virDomainDefPtr def, const char *dst)
{
    size_t i;

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

    return -1;
}

int
qemuDomainDetachDeviceDiskLive(virQEMUDriverPtr driver,
                               virDomainObjPtr vm,
                               virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr disk;
    int ret = -1;
    int idx;

    if ((idx = qemuFindDisk(vm->def, dev->data.disk->dst)) < 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("disk %s not found"), dev->data.disk->dst);
        return -1;
    }
    disk = vm->def->disks[idx];

    switch (disk->device) {
    case VIR_DOMAIN_DISK_DEVICE_DISK:
    case VIR_DOMAIN_DISK_DEVICE_LUN:
        if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
            ret = qemuDomainDetachVirtioDiskDevice(driver, vm, disk);
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
                 disk->bus == VIR_DOMAIN_DISK_BUS_USB)
            ret = qemuDomainDetachDiskDevice(driver, vm, disk);
        else
            virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                           _("This type of disk cannot be hot unplugged"));
        break;
    default:
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("disk device type '%s' cannot be detached"),
                       virDomainDiskDeviceTypeToString(disk->device));
        break;
    }

    return ret;
}


3036 3037 3038
static bool qemuDomainDiskControllerIsBusy(virDomainObjPtr vm,
                                           virDomainControllerDefPtr detach)
{
3039
    size_t i;
3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
    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;
    }
}

3086 3087 3088
int qemuDomainDetachControllerDevice(virQEMUDriverPtr driver,
                                     virDomainObjPtr vm,
                                     virDomainDeviceDefPtr dev)
3089
{
3090
    int idx, ret = -1;
3091 3092 3093
    virDomainControllerDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;

3094 3095 3096
    if ((idx = virDomainControllerFind(vm->def,
                                       dev->data.controller->type,
                                       dev->data.controller->idx)) < 0) {
3097
        virReportError(VIR_ERR_OPERATION_FAILED,
3098
                       _("controller %s:%d not found"),
3099 3100
                       virDomainControllerTypeToString(dev->data.controller->type),
                       dev->data.controller->idx);
3101 3102 3103
        goto cleanup;
    }

3104 3105
    detach = vm->def->controllers[idx];

3106 3107 3108 3109 3110 3111
    if (detach->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI &&
        detach->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW &&
        detach->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("device with '%s' address cannot be detached"),
                       virDomainDeviceAddressTypeToString(detach->info.type));
3112 3113 3114
        goto cleanup;
    }

3115 3116 3117 3118 3119 3120 3121 3122 3123
    if (!virDomainDeviceAddressIsValid(&detach->info, detach->info.type)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("device with invalid '%s' address cannot be detached"),
                       virDomainDeviceAddressTypeToString(detach->info.type));
        goto cleanup;
    }

    if (detach->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI &&
        qemuIsMultiFunctionDevice(vm->def, &detach->info)) {
3124 3125 3126
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %s"),
                       dev->data.disk->dst);
3127 3128 3129
        goto cleanup;
    }

3130
    if (qemuDomainControllerIsBusy(vm, detach)) {
3131 3132
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("device cannot be detached: device is busy"));
3133 3134 3135
        goto cleanup;
    }

3136
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
3137 3138 3139 3140
        if (qemuAssignDeviceControllerAlias(detach) < 0)
            goto cleanup;
    }

3141 3142
    qemuDomainMarkDeviceForRemoval(vm, &detach->info);

3143
    qemuDomainObjEnterMonitor(driver, vm);
3144
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
3145
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias)) {
3146
            qemuDomainObjExitMonitor(driver, vm);
3147 3148 3149 3150 3151
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
3152
            qemuDomainObjExitMonitor(driver, vm);
3153 3154 3155
            goto cleanup;
        }
    }
3156
    qemuDomainObjExitMonitor(driver, vm);
3157

3158 3159
    if (!qemuDomainWaitForDeviceRemoval(vm))
        qemuDomainRemoveControllerDevice(driver, vm, detach);
3160 3161 3162 3163

    ret = 0;

cleanup:
3164
    qemuDomainResetDeviceRemoval(vm);
3165 3166 3167
    return ret;
}

3168
static int
3169
qemuDomainDetachHostPciDevice(virQEMUDriverPtr driver,
3170
                              virDomainObjPtr vm,
3171
                              virDomainHostdevDefPtr detach)
3172 3173
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
3174
    virDomainHostdevSubsysPtr subsys = &detach->source.subsys;
3175
    int ret;
3176

3177
    if (qemuIsMultiFunctionDevice(vm->def, detach->info)) {
3178 3179
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %.4x:%.2x:%.2x.%.1x"),
3180 3181
                       subsys->u.pci.addr.domain, subsys->u.pci.addr.bus,
                       subsys->u.pci.addr.slot, subsys->u.pci.addr.function);
3182
        return -1;
3183 3184
    }

3185
    if (!virDomainDeviceAddressIsValid(detach->info,
3186
                                       VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
3187 3188
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("device cannot be detached without a PCI address"));
3189
        return -1;
3190 3191
    }

3192 3193
    qemuDomainMarkDeviceForRemoval(vm, detach->info);

3194
    qemuDomainObjEnterMonitor(driver, vm);
3195
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
3196
        ret = qemuMonitorDelDevice(priv->mon, detach->info->alias);
3197
    } else {
3198
        ret = qemuMonitorRemovePCIDevice(priv->mon, &detach->info->addr.pci);
3199
    }
3200
    qemuDomainObjExitMonitor(driver, vm);
3201 3202 3203 3204

    return ret;
}

3205
static int
3206
qemuDomainDetachHostUsbDevice(virQEMUDriverPtr driver,
3207
                              virDomainObjPtr vm,
3208
                              virDomainHostdevDefPtr detach)
3209 3210
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
3211
    int ret;
3212

3213
    if (!detach->info->alias) {
3214 3215
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("device cannot be detached without a device alias"));
3216 3217 3218
        return -1;
    }

3219
    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
3220 3221
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("device cannot be detached with this QEMU version"));
3222 3223 3224
        return -1;
    }

3225 3226
    qemuDomainMarkDeviceForRemoval(vm, detach->info);

3227
    qemuDomainObjEnterMonitor(driver, vm);
3228
    ret = qemuMonitorDelDevice(priv->mon, detach->info->alias);
3229
    qemuDomainObjExitMonitor(driver, vm);
3230 3231 3232 3233

    return ret;
}

3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255
static int
qemuDomainDetachHostScsiDevice(virQEMUDriverPtr driver,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr detach)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *drvstr = NULL;
    char *devstr = NULL;
    int ret = -1;

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

    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("device cannot be detached with this QEMU version"));
        return -1;
    }

3256 3257
    if (!(drvstr = qemuBuildSCSIHostdevDrvStr(detach, priv->qemuCaps,
                                              &buildCommandLineCallbacks)))
3258 3259 3260 3261
        goto cleanup;
    if (!(devstr = qemuBuildSCSIHostdevDevStr(vm->def, detach, priv->qemuCaps)))
        goto cleanup;

3262 3263
    qemuDomainMarkDeviceForRemoval(vm, detach->info);

3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288
    qemuDomainObjEnterMonitor(driver, vm);
    if ((ret = qemuMonitorDelDevice(priv->mon, detach->info->alias)) == 0) {
        if ((ret = qemuMonitorDriveDel(priv->mon, drvstr)) < 0) {
            virErrorPtr orig_err = virSaveLastError();
            if (qemuMonitorAddDevice(priv->mon, devstr) < 0)
                VIR_WARN("Unable to add device %s (%s) after failed "
                         "qemuMonitorDriveDel",
                         drvstr, devstr);
            if (orig_err) {
                virSetError(orig_err);
                virFreeError(orig_err);
            }
        }
    }
    qemuDomainObjExitMonitor(driver, vm);

cleanup:
    VIR_FREE(drvstr);
    VIR_FREE(devstr);
    return ret;
}

static int
qemuDomainDetachThisHostDevice(virQEMUDriverPtr driver,
                               virDomainObjPtr vm,
3289
                               virDomainHostdevDefPtr detach)
3290
{
3291
    int ret = -1;
3292

3293
    switch (detach->source.subsys.type) {
3294
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
3295 3296
        ret = qemuDomainDetachHostPciDevice(driver, vm, detach);
        break;
3297
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
3298
        ret = qemuDomainDetachHostUsbDevice(driver, vm, detach);
3299
        break;
3300 3301 3302
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
        ret = qemuDomainDetachHostScsiDevice(driver, vm, detach);
        break;
3303
    default:
3304 3305 3306
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(detach->source.subsys.type));
3307 3308 3309
        return -1;
    }

3310 3311
    if (ret < 0)
        virDomainAuditHostdev(vm, detach, "detach", false);
3312
    else if (!qemuDomainWaitForDeviceRemoval(vm))
3313
        qemuDomainRemoveHostDevice(driver, vm, detach);
3314

3315 3316
    qemuDomainResetDeviceRemoval(vm);

3317 3318
    return ret;
}
3319

3320
/* search for a hostdev matching dev and detach it */
3321
int qemuDomainDetachHostDevice(virQEMUDriverPtr driver,
3322 3323 3324 3325 3326 3327 3328 3329 3330
                               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) {
3331 3332 3333
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev mode '%s' not supported"),
                       virDomainHostdevModeTypeToString(hostdev->mode));
3334 3335 3336 3337 3338 3339
        return -1;
    }

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

    if (idx < 0) {
3340
        switch (subsys->type) {
3341
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
3342 3343
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("host pci device %.4x:%.2x:%.2x.%.1x not found"),
3344 3345
                           subsys->u.pci.addr.domain, subsys->u.pci.addr.bus,
                           subsys->u.pci.addr.slot, subsys->u.pci.addr.function);
3346 3347 3348
            break;
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
            if (subsys->u.usb.bus && subsys->u.usb.device) {
3349 3350 3351
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("host usb device %03d.%03d not found"),
                               subsys->u.usb.bus, subsys->u.usb.device);
3352
            } else {
3353 3354 3355
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("host usb device vendor=0x%.4x product=0x%.4x not found"),
                               subsys->u.usb.vendor, subsys->u.usb.product);
3356 3357
            }
            break;
3358 3359 3360 3361 3362 3363
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("host scsi device %s:%d:%d.%d not found"),
                           subsys->u.scsi.adapter, subsys->u.scsi.bus,
                           subsys->u.scsi.target, subsys->u.scsi.unit);
            break;
3364
        default:
3365 3366
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected hostdev type %d"), subsys->type);
3367 3368 3369 3370 3371
            break;
        }
        return -1;
    }

3372 3373 3374 3375 3376 3377
    /* 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
3378
        return qemuDomainDetachThisHostDevice(driver, vm, detach);
3379 3380
}

3381
int
3382
qemuDomainDetachNetDevice(virQEMUDriverPtr driver,
3383 3384 3385
                          virDomainObjPtr vm,
                          virDomainDeviceDefPtr dev)
{
3386
    int detachidx, ret = -1;
3387 3388 3389 3390
    virDomainNetDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int vlan;
    char *hostnet_name = NULL;
3391
    char mac[VIR_MAC_STRING_BUFLEN];
3392

3393 3394 3395 3396 3397 3398
    detachidx = virDomainNetFindIdx(vm->def, dev->data.net);
    if (detachidx == -2) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("multiple devices matching mac address %s found"),
                       virMacAddrFormat(&dev->data.net->mac, mac));
        goto cleanup;
3399
    }
3400
    else if (detachidx < 0) {
3401
        virReportError(VIR_ERR_OPERATION_FAILED,
3402 3403
                       _("network device %s not found"),
                       virMacAddrFormat(&dev->data.net->mac, mac));
3404 3405
        goto cleanup;
    }
3406
    detach = vm->def->nets[detachidx];
3407

3408
    if (virDomainNetGetActualType(detach) == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
3409
        /* coverity[negative_returns] */
3410
        ret = qemuDomainDetachThisHostDevice(driver, vm,
3411
                                             virDomainNetGetActualHostdev(detach));
3412 3413
        goto cleanup;
    }
3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428
    if (STREQLEN(vm->def->os.machine, "s390-ccw", 8) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_CCW)) {
        if (!virDomainDeviceAddressIsValid(&detach->info,
                                           VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW)) {
            virReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("device cannot be detached without a CCW address"));
            goto cleanup;
        }
    } else {
        if (!virDomainDeviceAddressIsValid(&detach->info,
                                           VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
            virReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("device cannot be detached without a PCI address"));
            goto cleanup;
        }
3429

3430 3431 3432 3433 3434 3435
        if (qemuIsMultiFunctionDevice(vm->def, &detach->info)) {
            virReportError(VIR_ERR_OPERATION_FAILED,
                            _("cannot hot unplug multifunction PCI device :%s"),
                            dev->data.disk->dst);
            goto cleanup;
        }
3436 3437 3438
    }

    if ((vlan = qemuDomainNetVLAN(detach)) < 0) {
3439 3440
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("unable to determine original VLAN"));
3441 3442 3443
        goto cleanup;
    }

3444
    if (virAsprintf(&hostnet_name, "host%s", detach->info.alias) < 0)
3445 3446
        goto cleanup;

3447 3448
    qemuDomainMarkDeviceForRemoval(vm, &detach->info);

3449
    qemuDomainObjEnterMonitor(driver, vm);
3450
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
3451
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
3452
            qemuDomainObjExitMonitor(driver, vm);
3453 3454 3455 3456 3457 3458
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
3459
            qemuDomainObjExitMonitor(driver, vm);
3460 3461 3462 3463 3464
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    }

3465 3466
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NETDEV) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
3467
        if (qemuMonitorRemoveNetdev(priv->mon, hostnet_name) < 0) {
3468
            qemuDomainObjExitMonitor(driver, vm);
3469 3470 3471 3472 3473
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemoveHostNetwork(priv->mon, vlan, hostnet_name) < 0) {
3474
            qemuDomainObjExitMonitor(driver, vm);
3475 3476 3477 3478
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    }
3479
    qemuDomainObjExitMonitor(driver, vm);
3480

3481 3482 3483
    if (!qemuDomainWaitForDeviceRemoval(vm))
        qemuDomainRemoveNetDevice(driver, vm, detach);

3484
    ret = 0;
3485

3486
cleanup:
3487
    qemuDomainResetDeviceRemoval(vm);
3488 3489 3490 3491
    VIR_FREE(hostnet_name);
    return ret;
}

3492
int
3493
qemuDomainChangeGraphicsPasswords(virQEMUDriverPtr driver,
3494 3495 3496 3497 3498 3499 3500 3501
                                  virDomainObjPtr vm,
                                  int type,
                                  virDomainGraphicsAuthDefPtr auth,
                                  const char *defaultPasswd)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    time_t now = time(NULL);
    char expire_time [64];
3502
    const char *connected = NULL;
3503 3504
    int ret = -1;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
3505

3506
    if (!auth->passwd && !defaultPasswd) {
3507 3508 3509
        ret = 0;
        goto cleanup;
    }
3510

3511 3512 3513
    if (auth->connected)
        connected = virDomainGraphicsAuthConnectedTypeToString(auth->connected);

3514
    qemuDomainObjEnterMonitor(driver, vm);
3515 3516 3517
    ret = qemuMonitorSetPassword(priv->mon,
                                 type,
                                 auth->passwd ? auth->passwd : defaultPasswd,
3518
                                 connected);
3519 3520 3521

    if (ret == -2) {
        if (type != VIR_DOMAIN_GRAPHICS_TYPE_VNC) {
3522 3523
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Graphics password only supported for VNC"));
3524 3525 3526 3527 3528 3529
            ret = -1;
        } else {
            ret = qemuMonitorSetVNCPassword(priv->mon,
                                            auth->passwd ? auth->passwd : defaultPasswd);
        }
    }
3530
    if (ret != 0)
3531
        goto end_job;
3532

3533 3534 3535
    if (auth->expires) {
        time_t lifetime = auth->validTo - now;
        if (lifetime <= 0)
3536
            snprintf(expire_time, sizeof(expire_time), "now");
3537
        else
3538
            snprintf(expire_time, sizeof(expire_time), "%lu", (long unsigned)auth->validTo);
3539
    } else {
3540
        snprintf(expire_time, sizeof(expire_time), "never");
3541 3542 3543 3544 3545 3546 3547
    }

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

    if (ret == -2) {
        /* XXX we could fake this with a timer */
        if (auth->expires) {
3548 3549
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Expiry of passwords is not supported"));
3550
            ret = -1;
3551 3552
        } else {
            ret = 0;
3553 3554 3555
        }
    }

3556
end_job:
3557
    qemuDomainObjExitMonitor(driver, vm);
3558 3559
cleanup:
    virObjectUnref(cfg);
3560 3561
    return ret;
}
3562

3563
int qemuDomainAttachLease(virQEMUDriverPtr driver,
3564 3565 3566
                          virDomainObjPtr vm,
                          virDomainLeaseDefPtr lease)
{
3567 3568 3569
    int ret = -1;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);

3570
    if (virDomainLeaseInsertPreAlloc(vm->def) < 0)
3571
        goto cleanup;
3572

3573
    if (virDomainLockLeaseAttach(driver->lockManager, cfg->uri,
3574
                                 vm, lease) < 0) {
3575
        virDomainLeaseInsertPreAlloced(vm->def, NULL);
3576
        goto cleanup;
3577 3578 3579
    }

    virDomainLeaseInsertPreAlloced(vm->def, lease);
3580 3581 3582 3583 3584
    ret = 0;

cleanup:
    virObjectUnref(cfg);
    return ret;
3585 3586
}

3587
int qemuDomainDetachLease(virQEMUDriverPtr driver,
3588 3589 3590
                          virDomainObjPtr vm,
                          virDomainLeaseDefPtr lease)
{
3591
    virDomainLeaseDefPtr det_lease;
3592
    int idx;
3593

3594
    if ((idx = virDomainLeaseIndex(vm->def, lease)) < 0) {
3595 3596 3597
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Lease %s in lockspace %s does not exist"),
                       lease->key, NULLSTR(lease->lockspace));
3598 3599 3600 3601 3602 3603
        return -1;
    }

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

3604
    det_lease = virDomainLeaseRemoveAt(vm->def, idx);
3605
    virDomainLeaseDefFree(det_lease);
3606 3607
    return 0;
}
3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628

int qemuDomainDetachChrDevice(virQEMUDriverPtr driver,
                              virDomainObjPtr vm,
                              virDomainChrDefPtr chr)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virDomainDefPtr vmdef = vm->def;
    virDomainChrDefPtr tmpChr;
    char *charAlias = NULL;
    char *devstr = NULL;

    if (!(tmpChr = virDomainChrFind(vmdef, chr))) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("device not present in domain configuration"));
        return ret;
    }

    if (qemuBuildChrDeviceStr(&devstr, vm->def, chr, priv->qemuCaps) < 0)
        return ret;

3629 3630
    if (virAsprintf(&charAlias, "char%s", tmpChr->info.alias) < 0)
        goto cleanup;
3631

3632 3633
    qemuDomainMarkDeviceForRemoval(vm, &tmpChr->info);

3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645
    qemuDomainObjEnterMonitor(driver, vm);
    if (devstr && qemuMonitorDelDevice(priv->mon, tmpChr->info.alias) < 0) {
        qemuDomainObjExitMonitor(driver, vm);
        goto cleanup;
    }

    if (qemuMonitorDetachCharDev(priv->mon, charAlias) < 0) {
        qemuDomainObjExitMonitor(driver, vm);
        goto cleanup;
    }
    qemuDomainObjExitMonitor(driver, vm);

3646 3647
    if (!qemuDomainWaitForDeviceRemoval(vm))
        qemuDomainRemoveChrDevice(driver, vm, tmpChr);
3648 3649 3650
    ret = 0;

cleanup:
3651
    qemuDomainResetDeviceRemoval(vm);
3652 3653 3654 3655
    VIR_FREE(devstr);
    VIR_FREE(charAlias);
    return ret;
}