qemu_hotplug.c 96.0 KB
Newer Older
1 2 3
/*
 * qemu_hotplug.h: QEMU device hotplug management
 *
4
 * Copyright (C) 2006-2012 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25 26 27 28 29 30 31 32
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */


#include <config.h>

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

#define VIR_FROM_THIS VIR_FROM_QEMU
51
#define CHANGE_MEDIA_RETRIES 10
52

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

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

    if (!origdisk) {
75 76 77 78
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No device with bus '%s' and target '%s'"),
                       virDomainDiskBusTypeToString(disk->bus),
                       disk->dst);
79
        goto cleanup;
80 81 82
    }

    if (!origdisk->info.alias) {
83 84
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("missing disk device alias name for %s"), origdisk->dst);
85
        goto cleanup;
86 87 88 89
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
        origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
90 91
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
92
                       virDomainDiskDeviceTypeToString(disk->device));
93
        goto cleanup;
94 95
    }

96
    if (virDomainLockDiskAttach(driver->lockManager, cfg->uri,
97
                                vm, disk) < 0)
98
        goto cleanup;
99

100
    if (virSecurityManagerSetImageLabel(driver->securityManager,
101
                                        vm->def, disk) < 0) {
102 103
        if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
            VIR_WARN("Unable to release lock on %s", disk->src);
104
        goto cleanup;
105
    }
106

107
    if (!(driveAlias = qemuDeviceDriveHostAlias(origdisk, priv->caps)))
108 109
        goto error;

110
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
111 112 113 114 115 116 117 118 119 120 121
    ret = qemuMonitorEjectMedia(priv->mon, driveAlias, force);

    /* we don't want to report errors from media tray_open polling */
    while (retries--) {
        if (origdisk->tray_status == VIR_DOMAIN_DISK_TRAY_OPEN)
            break;

        VIR_DEBUG("Waiting 500ms for tray to open. Retries left %d", retries);
        usleep(500 * 1000); /* sleep 500ms */
    }

122
    if (disk->src) {
123 124
        /* deliberately don't depend on 'ret' as 'eject' may have failed for the
         * fist time and we are gonna check the drive state anyway */
125
        const char *format = NULL;
126 127 128 129 130 131 132 133 134 135

        /* We haven't succeeded yet */
        ret = -1;

        if (retries <= 0) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("Unable to eject media before changing it"));
            goto exit_monitor;
        }

136
        if (disk->type != VIR_DOMAIN_DISK_TYPE_DIR) {
137 138 139 140
            if (disk->format > 0)
                format = virStorageFileFormatTypeToString(disk->format);
            else if (origdisk->format > 0)
                format = virStorageFileFormatTypeToString(origdisk->format);
141 142 143 144 145
        }
        ret = qemuMonitorChangeMedia(priv->mon,
                                     driveAlias,
                                     disk->src, format);
    }
146
exit_monitor:
147 148
    qemuDomainObjExitMonitorWithDriver(driver, vm);

149
    virDomainAuditDisk(vm, origdisk->src, disk->src, "update", ret >= 0);
150 151 152 153

    if (ret < 0)
        goto error;

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

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

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


    virDomainDiskDefFree(disk);

169 170 171
cleanup:
    VIR_FREE(driveAlias);
    virObjectUnref(cfg);
172 173 174
    return ret;

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

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

182
    goto cleanup;
183 184
}

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

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

    if (!table)
        goto cleanup;

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

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

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

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

    ret = 0;

cleanup:
223
    virHashFree(table);
224 225 226
    return ret;
}

227

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

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
243 244
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("target %s already exists"), disk->dst);
245
            goto cleanup;
246 247 248
        }
    }

249
    if (virDomainLockDiskAttach(driver->lockManager, cfg->uri,
250
                                vm, disk) < 0)
251
        goto cleanup;
252

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

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

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

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

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

279
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
280
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
281 282 283 284
        ret = qemuMonitorAddDrive(priv->mon, drivestr);
        if (ret == 0) {
            ret = qemuMonitorAddDevice(priv->mon, devstr);
            if (ret < 0) {
285 286 287 288 289 290 291 292 293 294
                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);
                }
295 296 297
            }
        }
    } else {
298
        virDevicePCIAddress guestAddr = disk->info.addr.pci;
299 300 301 302 303 304 305 306 307 308 309
        ret = qemuMonitorAddPCIDisk(priv->mon,
                                    disk->src,
                                    type,
                                    &guestAddr);
        if (ret == 0) {
            disk->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
            memcpy(&disk->info.addr.pci, &guestAddr, sizeof(guestAddr));
        }
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);

310
    virDomainAuditDisk(vm, NULL, disk->src, "attach", ret >= 0);
311 312 313 314 315 316

    if (ret < 0)
        goto error;

    virDomainDiskInsertPreAlloced(vm->def, disk);

317
cleanup:
318 319
    VIR_FREE(devstr);
    VIR_FREE(drivestr);
320 321
    virObjectUnref(cfg);
    return ret;
322 323

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

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

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

338
    goto cleanup;
339 340 341
}


342
int qemuDomainAttachPciControllerDevice(virQEMUDriverPtr driver,
343
                                        virDomainObjPtr vm,
344
                                        virDomainControllerDefPtr controller)
345 346 347 348 349
{
    int ret = -1;
    const char* type = virDomainControllerTypeToString(controller->type);
    char *devstr = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
350
    bool releaseaddr = false;
351

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

359
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
360 361
        if (qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &controller->info) < 0)
            goto cleanup;
362
        releaseaddr = true;
363 364 365
        if (qemuAssignDeviceControllerAlias(controller) < 0)
            goto cleanup;

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

374
        if (!(devstr = qemuBuildControllerDevStr(vm->def, controller, priv->caps, NULL))) {
375 376 377 378 379 380 381 382 383
            goto cleanup;
        }
    }

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

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

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

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

    VIR_FREE(devstr);
    return ret;
}


static virDomainControllerDefPtr
414
qemuDomainFindOrCreateSCSIDiskController(virQEMUDriverPtr driver,
415
                                         virDomainObjPtr vm,
416
                                         int controller)
417 418 419
{
    int i;
    virDomainControllerDefPtr cont;
420

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

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

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

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

441
    VIR_INFO("No SCSI controller present, hotplugging one");
442
    if (qemuDomainAttachPciControllerDevice(driver,
443
                                            vm, cont) < 0) {
444 445 446 447 448
        VIR_FREE(cont);
        return NULL;
    }

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

    return cont;
}


460
int qemuDomainAttachSCSIDisk(virConnectPtr conn,
461
                             virQEMUDriverPtr driver,
462
                             virDomainObjPtr vm,
463
                             virDomainDiskDefPtr disk)
464 465 466 467 468 469 470
{
    int i;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virDomainControllerDefPtr cont = NULL;
    char *drivestr = NULL;
    char *devstr = NULL;
    int ret = -1;
471
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
472 473 474

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
475 476
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("target %s already exists"), disk->dst);
477
            goto cleanup;
478 479 480
        }
    }

481
    if (virDomainLockDiskAttach(driver->lockManager, cfg->uri,
482
                                vm, disk) < 0)
483
        goto cleanup;
484

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

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

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

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

    for (i = 0 ; i <= disk->info.addr.drive.controller ; i++) {
511
        cont = qemuDomainFindOrCreateSCSIDiskController(driver, vm, i);
512 513 514 515 516 517 518
        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.  */
519
    sa_assert(cont);
520 521

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

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

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

560
    virDomainAuditDisk(vm, NULL, disk->src, "attach", ret >= 0);
561 562 563 564 565 566

    if (ret < 0)
        goto error;

    virDomainDiskInsertPreAlloced(vm->def, disk);

567
cleanup:
568 569
    VIR_FREE(devstr);
    VIR_FREE(drivestr);
570 571
    virObjectUnref(cfg);
    return ret;
572 573

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

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

581
    goto cleanup;
582 583 584
}


585
int qemuDomainAttachUsbMassstorageDevice(virConnectPtr conn,
586
                                         virQEMUDriverPtr driver,
587
                                         virDomainObjPtr vm,
588
                                         virDomainDiskDefPtr disk)
589 590
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
591
    int i, ret = -1;
592 593
    char *drivestr = NULL;
    char *devstr = NULL;
594
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
595 596 597

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
598 599
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("target %s already exists"), disk->dst);
600
            goto cleanup;
601 602 603
        }
    }

604
    if (virDomainLockDiskAttach(driver->lockManager, cfg->uri,
605
                                vm, disk) < 0)
606
        goto cleanup;
607

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

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

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

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

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

653
    virDomainAuditDisk(vm, NULL, disk->src, "attach", ret >= 0);
654 655 656 657 658 659

    if (ret < 0)
        goto error;

    virDomainDiskInsertPreAlloced(vm->def, disk);

660
cleanup:
661 662
    VIR_FREE(devstr);
    VIR_FREE(drivestr);
663 664
    virObjectUnref(cfg);
    return ret;
665 666

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

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

674
    goto cleanup;
675 676 677 678 679
}


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

700 701 702
    /* preallocate new slot for device */
    if (VIR_REALLOC_N(vm->def->nets, vm->def->nnets+1) < 0) {
        virReportOOMError();
703
        goto cleanup;
704 705
    }

706 707 708 709 710
    /* If appropriate, grab a physical device from the configured
     * network's pool of devices, or resolve bridge device name
     * to the one defined in the network definition.
     */
    if (networkAllocateActualDevice(net) < 0)
711
        goto cleanup;
712 713

    actualType = virDomainNetGetActualType(net);
714 715 716 717 718 719 720 721 722 723 724 725

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

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

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

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

765
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
766 767 768
        qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &net->info) < 0)
        goto cleanup;

769 770
    releaseaddr = true;

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

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

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

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

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

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

    VIR_FORCE_CLOSE(tapfd);
827
    VIR_FORCE_CLOSE(vhostfd);
828 829

    if (!virDomainObjIsActive(vm)) {
830 831
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest unexpectedly quit"));
832 833 834
        goto cleanup;
    }

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

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

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

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

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

887
    virDomainAuditNet(vm, NULL, net, "attach", true);
888 889 890 891

    ret = 0;

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

902
        if (iface_connected) {
903
            virDomainConfNWFilterTeardown(net);
904

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

911 912
        networkReleaseActualDevice(net);
    }
913 914 915 916 917

    VIR_FREE(nicstr);
    VIR_FREE(netstr);
    VIR_FREE(tapfd_name);
    VIR_FORCE_CLOSE(tapfd);
918 919
    VIR_FREE(vhostfd_name);
    VIR_FORCE_CLOSE(vhostfd);
920
    virObjectUnref(cfg);
921 922 923 924 925 926 927 928

    return ret;

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

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

no_memory:
    virReportOOMError();
    goto cleanup;
}


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

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

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

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

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

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

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

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

1022 1023
        hostdev->info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
        memcpy(&hostdev->info->addr.pci, &guestAddr, sizeof(guestAddr));
1024
    }
1025
    virDomainAuditHostdev(vm, hostdev, "attach", ret == 0);
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
    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:
1038
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
1039
        (hostdev->info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) &&
1040
        releaseaddr &&
1041
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
1042
                                        hostdev->info->addr.pci.slot) < 0)
1043
        VIR_WARN("Unable to release PCI address on host device");
1044

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

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

    return -1;
}


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

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

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

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

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

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

    VIR_FREE(devstr);

    return 0;

error:
    VIR_FREE(devstr);
    return -1;

}

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

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

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

    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        virCgroupPtr cgroup = NULL;
        usbDevice *usb;
1122
        qemuCgroupData data;
1123

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

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

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

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

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

    VIR_FREE(devstr);

    return 0;

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

1165
int qemuDomainAttachHostDevice(virQEMUDriverPtr driver,
1166
                               virDomainObjPtr vm,
1167
                               virDomainHostdevDefPtr hostdev)
1168
{
1169 1170 1171
    usbDeviceList *list;
    usbDevice *usb = NULL;

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

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

1182
    if (hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
1183
        if (qemuFindHostdevUSBDevice(hostdev, true, &usb) < 0)
1184 1185 1186 1187
            goto cleanup;

        if (usbDeviceListAdd(list, usb) < 0) {
            usbFreeDevice(usb);
M
Marc-André Lureau 已提交
1188
            usb = NULL;
1189 1190 1191
            goto cleanup;
        }

1192 1193
        if (qemuPrepareHostdevUSBDevices(driver, vm->def->name, list) < 0) {
            usb = NULL;
1194
            goto cleanup;
1195
        }
1196 1197 1198

        usbDeviceListSteal(list, usb);
    }
1199

1200
    if (virSecurityManagerSetHostdevLabel(driver->securityManager,
1201
                                          vm->def, hostdev, NULL) < 0)
1202
        goto cleanup;
1203 1204 1205 1206

    switch (hostdev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
        if (qemuDomainAttachHostPciDevice(driver, vm,
1207
                                          hostdev) < 0)
1208 1209 1210 1211 1212
            goto error;
        break;

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
        if (qemuDomainAttachHostUsbDevice(driver, vm,
1213
                                          hostdev) < 0)
1214 1215 1216 1217
            goto error;
        break;

    default:
1218 1219 1220
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(hostdev->source.subsys.type));
1221 1222 1223
        goto error;
    }

1224
    usbDeviceListFree(list);
1225 1226 1227
    return 0;

error:
1228
    if (virSecurityManagerRestoreHostdevLabel(driver->securityManager,
1229
                                              vm->def, hostdev, NULL) < 0)
1230
        VIR_WARN("Unable to restore host device labelling on hotplug fail");
1231

1232 1233
cleanup:
    usbDeviceListFree(list);
1234 1235
    if (usb)
        usbDeviceListSteal(driver->activeUsbHostdevs, usb);
1236 1237 1238
    return -1;
}

1239 1240
static virDomainNetDefPtr *qemuDomainFindNet(virDomainObjPtr vm,
                                             virDomainNetDefPtr dev)
1241 1242 1243 1244
{
    int i;

    for (i = 0; i < vm->def->nnets; i++) {
1245
        if (virMacAddrCmp(&vm->def->nets[i]->mac, &dev->mac) == 0)
1246
            return &vm->def->nets[i];
1247 1248 1249 1250 1251
    }

    return NULL;
}

1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
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 */
        if (!(brname = strdup(tmpbr))) {
            virReportOOMError();
            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);

1297 1298 1299 1300
    } else {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Interface type %d has no bridge name"),
                       virDomainNetGetActualType(net));
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
    }

cleanup:
    return brname;
}

static int
qemuDomainChangeNetBridge(virConnectPtr conn,
                          virDomainObjPtr vm,
                          virDomainNetDefPtr olddev,
                          virDomainNetDefPtr newdev)
1312 1313
{
    int ret = -1;
1314 1315 1316 1317 1318 1319 1320
    char *oldbridge = NULL, *newbridge = NULL;

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

    if (!(newbridge = qemuDomainNetGetBridgeName(conn, newdev)))
        goto cleanup;
1321 1322 1323 1324 1325

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

    if (virNetDevExists(newbridge) != 1) {
1326 1327
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("bridge %s doesn't exist"), newbridge);
1328
        goto cleanup;
1329 1330 1331 1332 1333
    }

    if (oldbridge) {
        ret = virNetDevBridgeRemovePort(oldbridge, olddev->ifname);
        virDomainAuditNet(vm, olddev, NULL, "detach", ret == 0);
1334 1335 1336 1337 1338 1339 1340 1341
        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);
        }
1342 1343 1344
    }

    ret = virNetDevBridgeAddPort(newbridge, olddev->ifname);
1345
    virDomainAuditNet(vm, NULL, newdev, "attach", ret == 0);
1346 1347 1348 1349
    if (ret < 0) {
        ret = virNetDevBridgeAddPort(oldbridge, olddev->ifname);
        virDomainAuditNet(vm, NULL, olddev, "attach", ret == 0);
        if (ret < 0) {
1350
            virReportError(VIR_ERR_OPERATION_FAILED,
1351
                           _("unable to recover former state by adding port "
1352
                             "to bridge %s"), oldbridge);
1353
        }
1354
        goto cleanup;
1355
    }
1356 1357 1358
    /* caller will replace entire olddev with newdev in domain nets list */
    ret = 0;
cleanup:
1359
    VIR_FREE(oldbridge);
1360 1361
    VIR_FREE(newbridge);
    return ret;
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 1395 1396 1397 1398 1399 1400
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;
}

1401
int qemuDomainChangeNetLinkState(virQEMUDriverPtr driver,
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
                                 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) {
1412 1413
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("can't change link state: device alias not found"));
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
        return -1;
    }

    qemuDomainObjEnterMonitorWithDriver(driver, vm);

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

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

cleanup:
    qemuDomainObjExitMonitorWithDriver(driver, vm);

    return ret;
}

1432
int
1433
qemuDomainChangeNet(virQEMUDriverPtr driver,
1434 1435 1436
                    virDomainObjPtr vm,
                    virDomainPtr dom,
                    virDomainDeviceDefPtr dev)
1437
{
1438 1439 1440 1441 1442 1443
    virDomainNetDefPtr newdev = dev->data.net;
    virDomainNetDefPtr *devslot = qemuDomainFindNet(vm, newdev);
    virDomainNetDefPtr olddev;
    int oldType, newType;
    bool needReconnect = false;
    bool needBridgeChange = false;
1444
    bool needFilterChange = false;
1445 1446 1447
    bool needLinkStateChange = false;
    bool needReplaceDevDef = false;
    int ret = -1;
1448

1449
    if (!devslot || !(olddev = *devslot)) {
1450 1451
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("cannot find existing network device to modify"));
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
        goto cleanup;
    }

    oldType = virDomainNetGetActualType(olddev);
    if (oldType == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
        /* no changes are possible to a type='hostdev' interface */
        virReportError(VIR_ERR_NO_SUPPORT,
                       _("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];

        virReportError(VIR_ERR_NO_SUPPORT,
                       _("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)) {
        virReportError(VIR_ERR_NO_SUPPORT,
                       _("cannot modify network device model from %s to %s"),
                       olddev->model ? olddev->model : "(default)",
                       newdev->model ? newdev->model : "(default)");
        goto cleanup;
1495 1496
    }

1497 1498 1499 1500 1501
    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 ||
         olddev->driver.virtio.event_idx != newdev->driver.virtio.event_idx)) {
1502
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
                       _("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;
1513 1514
    }

1515
    if (STRNEQ_NULLABLE(olddev->script, newdev->script)) {
1516
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
1517 1518
                       _("cannot modify network device script attribute"));
        goto cleanup;
1519 1520
    }

1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
    /* ifname: check if it's set in newdev. If not, retain the autogenerated one */
    if (!(newdev->ifname ||
          (newdev->ifname = strdup(olddev->ifname)))) {
        virReportOOMError();
        goto cleanup;
    }
    if (STRNEQ_NULLABLE(olddev->ifname, newdev->ifname)) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("cannot modify network device tap name"));
        goto cleanup;
    }
1532

1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
    /* 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)) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("cannot modify network device guest PCI address"));
        goto cleanup;
    }
    /* grab alias from olddev if not set in newdev */
    if (!(newdev->info.alias ||
          (newdev->info.alias = strdup(olddev->info.alias)))) {
        virReportOOMError();
        goto cleanup;
    }
    if (STRNEQ_NULLABLE(olddev->info.alias, newdev->info.alias)) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("cannot modify network device alias"));
        goto cleanup;
    }
    if (olddev->info.rombar != newdev->info.rombar) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("cannot modify network device rom bar setting"));
        goto cleanup;
    }
    if (STRNEQ_NULLABLE(olddev->info.romfile, newdev->info.romfile)) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("cannot modify network rom file"));
        goto cleanup;
    }
    if (olddev->info.bootIndex != newdev->info.bootIndex) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("cannot modify network device boot index setting"));
        goto cleanup;
    }
    /* (end of device info checks) */
1577

1578 1579 1580 1581
    if (STRNEQ_NULLABLE(olddev->filter, newdev->filter) ||
        !virNWFilterHashTableEqual(olddev->filterparams, newdev->filterparams)) {
        needFilterChange = true;
    }
1582

1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
    /* 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 &&
        networkAllocateActualDevice(newdev) < 0) {
        goto cleanup;
    }

    newType = virDomainNetGetActualType(newdev);

    if (newType == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
        /* can't turn it into a type='hostdev' interface */
        virReportError(VIR_ERR_NO_SUPPORT,
                       _("cannot change network interface type to '%s'"),
                       virDomainNetTypeToString(newType));
        goto cleanup;
    }

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

1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
        /* 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;
            }
1619 1620
        break;

1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
        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:
            virReportError(VIR_ERR_NO_SUPPORT,
                           _("unable to change config on '%s' network type"),
                           virDomainNetTypeToString(newdev->type));
            break;
1661

1662
        }
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
    } 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;
1694 1695

        }
1696
    }
1697

1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
    /* 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;
    }
1709

1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
    if (STRNEQ_NULLABLE(virDomainNetGetActualDirectDev(olddev),
                        virDomainNetGetActualDirectDev(newdev)) ||
        virDomainNetGetActualDirectMode(olddev) != virDomainNetGetActualDirectMode(olddev) ||
        !virNetDevVPortProfileEqual(virDomainNetGetActualVirtPortProfile(olddev),
                                    virDomainNetGetActualVirtPortProfile(newdev)) ||
        !virNetDevBandwidthEqual(virDomainNetGetActualBandwidth(olddev),
                                 virDomainNetGetActualBandwidth(newdev)) ||
        !virNetDevVlanEqual(virDomainNetGetActualVlan(olddev),
                            virDomainNetGetActualVlan(newdev))) {
        needReconnect = true;
1720 1721
    }

1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
    if (olddev->linkstate != newdev->linkstate)
        needLinkStateChange = true;

    /* FINALLY - actually perform the required actions */

    if (needReconnect) {
        virReportError(VIR_ERR_NO_SUPPORT,
                       _("unable to change config on '%s' network type"),
                       virDomainNetTypeToString(newdev->type));
        goto cleanup;
1732 1733
    }

1734 1735 1736 1737 1738
    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,
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
         * 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 */
1749
        needReplaceDevDef = true;
1750 1751
    }

1752 1753 1754
    if (needLinkStateChange &&
        qemuDomainChangeNetLinkState(driver, vm, olddev, newdev->linkstate) < 0) {
        goto cleanup;
1755 1756
    }

1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
    if (needReplaceDevDef) {
        /* the changes above warrant replacing olddev with newdev in
         * the domain's nets list.
         */
        networkReleaseActualDevice(olddev);
        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;
1770 1771
    }

1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
    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)
        networkReleaseActualDevice(newdev);

1795 1796 1797 1798
    return ret;
}


1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814

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

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

    return NULL;
}


int
1815
qemuDomainChangeGraphics(virQEMUDriverPtr driver,
1816 1817 1818 1819
                         virDomainObjPtr vm,
                         virDomainGraphicsDefPtr dev)
{
    virDomainGraphicsDefPtr olddev = qemuDomainFindGraphics(vm, dev);
1820
    const char *oldListenAddr, *newListenAddr;
1821
    const char *oldListenNetwork, *newListenNetwork;
1822
    int ret = -1;
1823
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
1824 1825

    if (!olddev) {
1826 1827
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot find existing graphics device to modify"));
1828
        goto cleanup;
1829 1830
    }

1831 1832
    oldListenAddr = virDomainGraphicsListenGetAddress(olddev, 0);
    newListenAddr = virDomainGraphicsListenGetAddress(dev, 0);
1833 1834
    oldListenNetwork = virDomainGraphicsListenGetNetwork(olddev, 0);
    newListenNetwork = virDomainGraphicsListenGetNetwork(dev, 0);
1835

1836 1837 1838
    switch (dev->type) {
    case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
        if ((olddev->data.vnc.autoport != dev->data.vnc.autoport) ||
E
Eric Blake 已提交
1839 1840
            (!dev->data.vnc.autoport &&
             (olddev->data.vnc.port != dev->data.vnc.port))) {
1841 1842
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change port settings on vnc graphics"));
1843
            goto cleanup;
1844
        }
1845
        if (STRNEQ_NULLABLE(oldListenAddr,newListenAddr)) {
1846 1847
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change listen address setting on vnc graphics"));
1848
            goto cleanup;
1849
        }
1850
        if (STRNEQ_NULLABLE(oldListenNetwork,newListenNetwork)) {
1851 1852
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change listen network setting on vnc graphics"));
1853
            goto cleanup;
1854
        }
1855
        if (STRNEQ_NULLABLE(olddev->data.vnc.keymap, dev->data.vnc.keymap)) {
1856 1857
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change keymap setting on vnc graphics"));
1858
            goto cleanup;
1859 1860
        }

1861 1862 1863
        /* 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 */
1864 1865
        if (olddev->data.vnc.auth.expires ||
            dev->data.vnc.auth.expires ||
1866
            olddev->data.vnc.auth.connected != dev->data.vnc.auth.connected ||
E
Eric Blake 已提交
1867 1868 1869
            STRNEQ_NULLABLE(olddev->data.vnc.auth.passwd,
                            dev->data.vnc.auth.passwd)) {
            VIR_DEBUG("Updating password on VNC server %p %p",
1870
                      dev->data.vnc.auth.passwd, cfg->vncPassword);
E
Eric Blake 已提交
1871 1872 1873
            ret = qemuDomainChangeGraphicsPasswords(driver, vm,
                                                    VIR_DOMAIN_GRAPHICS_TYPE_VNC,
                                                    &dev->data.vnc.auth,
1874
                                                    cfg->vncPassword);
1875
            if (ret < 0)
1876
                goto cleanup;
1877 1878 1879 1880 1881

            /* 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;
1882 1883
            olddev->data.vnc.auth.validTo = dev->data.vnc.auth.validTo;
            olddev->data.vnc.auth.expires = dev->data.vnc.auth.expires;
1884
            olddev->data.vnc.auth.connected = dev->data.vnc.auth.connected;
1885 1886 1887 1888 1889
        } else {
            ret = 0;
        }
        break;

1890 1891
    case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
        if ((olddev->data.spice.autoport != dev->data.spice.autoport) ||
E
Eric Blake 已提交
1892 1893 1894 1895
            (!dev->data.spice.autoport &&
             (olddev->data.spice.port != dev->data.spice.port)) ||
            (!dev->data.spice.autoport &&
             (olddev->data.spice.tlsPort != dev->data.spice.tlsPort))) {
1896 1897
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change port settings on spice graphics"));
1898
            goto cleanup;
1899
        }
1900
        if (STRNEQ_NULLABLE(oldListenAddr, newListenAddr)) {
1901 1902
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change listen address setting on spice graphics"));
1903
            goto cleanup;
1904
        }
1905
        if (STRNEQ_NULLABLE(oldListenNetwork, newListenNetwork)) {
1906 1907
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change listen network setting on spice graphics"));
1908
            goto cleanup;
1909
        }
E
Eric Blake 已提交
1910 1911
        if (STRNEQ_NULLABLE(olddev->data.spice.keymap,
                            dev->data.spice.keymap)) {
1912
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1913
                            _("cannot change keymap setting on spice graphics"));
1914
            goto cleanup;
1915 1916
        }

1917 1918 1919 1920 1921
        /* 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"
         */
1922 1923
        if (olddev->data.spice.auth.expires ||
            dev->data.spice.auth.expires ||
1924
            olddev->data.spice.auth.connected != dev->data.spice.auth.connected ||
1925 1926
            dev->data.spice.auth.connected ==
            VIR_DOMAIN_GRAPHICS_AUTH_CONNECTED_DISCONNECT ||
E
Eric Blake 已提交
1927 1928 1929
            STRNEQ_NULLABLE(olddev->data.spice.auth.passwd,
                            dev->data.spice.auth.passwd)) {
            VIR_DEBUG("Updating password on SPICE server %p %p",
1930
                      dev->data.spice.auth.passwd, cfg->spicePassword);
E
Eric Blake 已提交
1931 1932 1933
            ret = qemuDomainChangeGraphicsPasswords(driver, vm,
                                                    VIR_DOMAIN_GRAPHICS_TYPE_SPICE,
                                                    &dev->data.spice.auth,
1934
                                                    cfg->spicePassword);
E
Eric Blake 已提交
1935

1936
            if (ret < 0)
1937
                goto cleanup;
1938

E
Eric Blake 已提交
1939
            /* Steal the new dev's char * reference */
1940 1941 1942 1943 1944
            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;
1945
            olddev->data.spice.auth.connected = dev->data.spice.auth.connected;
1946
        } else {
1947
            VIR_DEBUG("Not updating since password didn't change");
1948 1949
            ret = 0;
        }
E
Eric Blake 已提交
1950
        break;
1951

1952
    default:
1953 1954 1955
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unable to change config on '%s' graphics type"),
                       virDomainGraphicsTypeToString(dev->type));
1956 1957 1958
        break;
    }

1959 1960
cleanup:
    virObjectUnref(cfg);
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
    return ret;
}


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

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

    return -1;
}

1978
static int qemuComparePCIDevice(virDomainDefPtr def ATTRIBUTE_UNUSED,
1979
                                virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
1980
                                virDomainDeviceInfoPtr info1,
1981 1982
                                void *opaque)
{
1983
    virDomainDeviceInfoPtr info2 = opaque;
1984

1985 1986
    if (info1->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI ||
        info2->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)
1987 1988
        return 0;

1989 1990
    if (info1->addr.pci.slot == info2->addr.pci.slot &&
        info1->addr.pci.function != info2->addr.pci.function)
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
        return -1;
    return 0;
}

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

2003

2004
int qemuDomainDetachPciDiskDevice(virQEMUDriverPtr driver,
2005
                                  virDomainObjPtr vm,
2006
                                  virDomainDeviceDefPtr dev)
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
{
    int i, ret = -1;
    virDomainDiskDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virCgroupPtr cgroup = NULL;
    char *drivestr = NULL;

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

    if (i < 0) {
2017 2018
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("disk %s not found"), dev->data.disk->dst);
2019 2020 2021 2022 2023
        goto cleanup;
    }

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

2024
    if (qemuIsMultiFunctionDevice(vm->def, &detach->info)) {
2025 2026 2027
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %s"),
                       dev->data.disk->dst);
2028 2029 2030
        goto cleanup;
    }

2031 2032
    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) != 0) {
2033 2034 2035
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to find cgroup for %s"),
                           vm->def->name);
2036 2037 2038 2039 2040 2041
            goto cleanup;
        }
    }

    if (!virDomainDeviceAddressIsValid(&detach->info,
                                       VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
2042 2043
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("device cannot be detached without a PCI address"));
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
        goto cleanup;
    }

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

2055
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2056
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
2057
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
2058
            qemuDomainObjExitMonitorWithDriver(driver, vm);
2059
            virDomainAuditDisk(vm, detach->src, NULL, "detach", false);
2060 2061 2062 2063 2064
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
2065
            qemuDomainObjExitMonitorWithDriver(driver, vm);
2066
            virDomainAuditDisk(vm, detach->src, NULL, "detach", false);
2067 2068 2069 2070 2071 2072 2073 2074 2075
            goto cleanup;
        }
    }

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

    qemuDomainObjExitMonitorWithDriver(driver, vm);

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

2078
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
2079 2080
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
                                        detach->info.addr.pci.slot) < 0)
2081 2082 2083 2084
        VIR_WARN("Unable to release PCI address on %s", dev->data.disk->src);

    virDomainDiskRemove(vm->def, i);

2085 2086
    dev->data.disk->backingChain = detach->backingChain;
    detach->backingChain = NULL;
2087 2088
    virDomainDiskDefFree(detach);

2089
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
2090
                                            vm->def, dev->data.disk) < 0)
2091 2092 2093
        VIR_WARN("Unable to restore security label on %s", dev->data.disk->src);

    if (cgroup != NULL) {
2094
        if (qemuTeardownDiskCgroup(vm, cgroup, dev->data.disk) < 0)
2095 2096 2097 2098
            VIR_WARN("Failed to teardown cgroup for disk path %s",
                     NULLSTR(dev->data.disk->src));
    }

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

2102 2103 2104
    ret = 0;

cleanup:
2105
    virCgroupFree(&cgroup);
2106 2107 2108 2109
    VIR_FREE(drivestr);
    return ret;
}

2110
int qemuDomainDetachDiskDevice(virQEMUDriverPtr driver,
2111
                               virDomainObjPtr vm,
2112
                               virDomainDeviceDefPtr dev)
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
{
    int i, ret = -1;
    virDomainDiskDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virCgroupPtr cgroup = NULL;
    char *drivestr = NULL;

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

    if (i < 0) {
2123 2124
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("disk %s not found"), dev->data.disk->dst);
2125 2126 2127
        goto cleanup;
    }

2128
    if (!qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
2129 2130 2131
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Underlying qemu does not support %s disk removal"),
                       virDomainDiskBusTypeToString(dev->data.disk->bus));
2132 2133 2134 2135 2136
        goto cleanup;
    }

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

E
Eric Blake 已提交
2137 2138 2139 2140 2141 2142 2143
    if (detach->mirror) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE,
                       _("disk '%s' is in an active block copy job"),
                       detach->dst);
        goto cleanup;
    }

2144 2145
    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) != 0) {
2146 2147 2148
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to find cgroup for %s"),
                           vm->def->name);
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
            goto cleanup;
        }
    }

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

2161
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2162
    if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
2163
        qemuDomainObjExitMonitorWithDriver(driver, vm);
2164
        virDomainAuditDisk(vm, detach->src, NULL, "detach", false);
2165 2166 2167 2168 2169 2170 2171 2172
        goto cleanup;
    }

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

    qemuDomainObjExitMonitorWithDriver(driver, vm);

2173
    virDomainAuditDisk(vm, detach->src, NULL, "detach", true);
2174 2175 2176

    virDomainDiskRemove(vm->def, i);

2177 2178
    dev->data.disk->backingChain = detach->backingChain;
    detach->backingChain = NULL;
2179 2180
    virDomainDiskDefFree(detach);

2181
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
2182
                                            vm->def, dev->data.disk) < 0)
2183 2184 2185
        VIR_WARN("Unable to restore security label on %s", dev->data.disk->src);

    if (cgroup != NULL) {
2186
        if (qemuTeardownDiskCgroup(vm, cgroup, dev->data.disk) < 0)
2187 2188 2189 2190
            VIR_WARN("Failed to teardown cgroup for disk path %s",
                     NULLSTR(dev->data.disk->src));
    }

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

2194 2195 2196 2197 2198 2199 2200 2201
    ret = 0;

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

2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
static bool qemuDomainDiskControllerIsBusy(virDomainObjPtr vm,
                                           virDomainControllerDefPtr detach)
{
    int i;
    virDomainDiskDefPtr disk;

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

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

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

    return false;
}

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

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

2252
int qemuDomainDetachPciControllerDevice(virQEMUDriverPtr driver,
2253
                                        virDomainObjPtr vm,
2254
                                        virDomainDeviceDefPtr dev)
2255
{
2256
    int idx, ret = -1;
2257 2258 2259
    virDomainControllerDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;

2260 2261 2262
    if ((idx = virDomainControllerFind(vm->def,
                                       dev->data.controller->type,
                                       dev->data.controller->idx)) < 0) {
2263 2264 2265 2266
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("disk controller %s:%d not found"),
                       virDomainControllerTypeToString(dev->data.controller->type),
                       dev->data.controller->idx);
2267 2268 2269
        goto cleanup;
    }

2270 2271
    detach = vm->def->controllers[idx];

2272 2273
    if (!virDomainDeviceAddressIsValid(&detach->info,
                                       VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
2274 2275
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("device cannot be detached without a PCI address"));
2276 2277 2278
        goto cleanup;
    }

2279
    if (qemuIsMultiFunctionDevice(vm->def, &detach->info)) {
2280 2281 2282
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %s"),
                       dev->data.disk->dst);
2283 2284 2285
        goto cleanup;
    }

2286
    if (qemuDomainControllerIsBusy(vm, detach)) {
2287 2288
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("device cannot be detached: device is busy"));
2289 2290 2291
        goto cleanup;
    }

2292
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
2293 2294 2295 2296
        if (qemuAssignDeviceControllerAlias(detach) < 0)
            goto cleanup;
    }

2297
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2298
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
2299
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias)) {
2300
            qemuDomainObjExitMonitorWithDriver(driver, vm);
2301 2302 2303 2304 2305
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
2306
            qemuDomainObjExitMonitorWithDriver(driver, vm);
2307 2308 2309 2310 2311
            goto cleanup;
        }
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);

2312 2313
    virDomainControllerRemove(vm->def, idx);
    virDomainControllerDefFree(detach);
2314

2315
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
2316 2317
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
                                        detach->info.addr.pci.slot) < 0)
2318
        VIR_WARN("Unable to release PCI address on controller");
2319 2320 2321 2322 2323 2324 2325

    ret = 0;

cleanup:
    return ret;
}

2326
static int
2327
qemuDomainDetachHostPciDevice(virQEMUDriverPtr driver,
2328
                              virDomainObjPtr vm,
2329
                              virDomainHostdevDefPtr detach)
2330 2331
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2332
    virDomainHostdevSubsysPtr subsys = &detach->source.subsys;
2333
    int ret = -1, rv;
2334
    pciDevice *pci;
2335
    pciDevice *activePci;
2336
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2337

2338
    if (qemuIsMultiFunctionDevice(vm->def, detach->info)) {
2339 2340 2341 2342
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %.4x:%.2x:%.2x.%.1x"),
                       subsys->u.pci.domain, subsys->u.pci.bus,
                       subsys->u.pci.slot,   subsys->u.pci.function);
2343
        goto cleanup;
2344 2345
    }

2346
    if (!virDomainDeviceAddressIsValid(detach->info,
2347
                                       VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
2348 2349
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("device cannot be detached without a PCI address"));
2350
        goto cleanup;
2351 2352
    }

2353
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2354
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
2355
        rv = qemuMonitorDelDevice(priv->mon, detach->info->alias);
2356
    } else {
2357
        rv = qemuMonitorRemovePCIDevice(priv->mon, &detach->info->addr.pci);
2358 2359
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);
2360 2361 2362
    virDomainAuditHostdev(vm, detach, "detach", rv == 0);
    if (rv < 0)
        goto cleanup;
2363

2364 2365 2366 2367 2368
    /*
     * For SRIOV net host devices, unset mac and port profile before
     * reset and reattach device
     */
     if (detach->parent.data.net)
2369
         qemuDomainHostdevNetConfigRestore(detach, cfg->stateDir);
2370

2371 2372
    pci = pciGetDevice(subsys->u.pci.domain, subsys->u.pci.bus,
                       subsys->u.pci.slot,   subsys->u.pci.function);
2373 2374
    if (pci) {
        activePci = pciDeviceListSteal(driver->activePciHostdevs, pci);
2375 2376 2377
        if (activePci &&
            pciResetDevice(activePci, driver->activePciHostdevs,
                           driver->inactivePciHostdevs) == 0) {
2378
            qemuReattachPciDevice(activePci, driver);
2379
            ret = 0;
2380 2381 2382 2383
        } else {
            /* reset of the device failed, treat it as if it was returned */
            pciFreeDevice(activePci);
        }
2384 2385 2386
        pciFreeDevice(pci);
    }

2387
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
2388
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
2389
                                        detach->info->addr.pci.slot) < 0)
2390
        VIR_WARN("Unable to release PCI address on host device");
2391

2392 2393
cleanup:
    virObjectUnref(cfg);
2394 2395 2396
    return ret;
}

2397
static int
2398
qemuDomainDetachHostUsbDevice(virQEMUDriverPtr driver,
2399
                              virDomainObjPtr vm,
2400
                              virDomainHostdevDefPtr detach)
2401 2402
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2403
    virDomainHostdevSubsysPtr subsys = &detach->source.subsys;
2404
    usbDevice *usb;
2405
    int ret;
2406

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

2413
    if (!qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
2414 2415
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("device cannot be detached with this QEMU version"));
2416 2417 2418
        return -1;
    }

2419
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2420
    ret = qemuMonitorDelDevice(priv->mon, detach->info->alias);
2421
    qemuDomainObjExitMonitorWithDriver(driver, vm);
2422
    virDomainAuditHostdev(vm, detach, "detach", ret == 0);
2423 2424
    if (ret < 0)
        return -1;
2425

2426
    usb = usbGetDevice(subsys->u.usb.bus, subsys->u.usb.device, NULL);
2427 2428 2429 2430 2431
    if (usb) {
        usbDeviceListDel(driver->activeUsbHostdevs, usb);
        usbFreeDevice(usb);
    } else {
        VIR_WARN("Unable to find device %03d.%03d in list of used USB devices",
2432
                 subsys->u.usb.bus, subsys->u.usb.device);
2433 2434 2435 2436
    }
    return ret;
}

2437
static
2438
int qemuDomainDetachThisHostDevice(virQEMUDriverPtr driver,
2439 2440 2441
                                   virDomainObjPtr vm,
                                   virDomainHostdevDefPtr detach,
                                   int idx)
2442
{
2443
    int ret = -1;
2444

2445 2446 2447 2448 2449 2450 2451 2452 2453
    if (idx < 0) {
        /* caller didn't know index of hostdev in hostdevs list, so we
         * need to find it.
         */
        for (idx = 0; idx < vm->def->nhostdevs; idx++) {
            if (vm->def->hostdevs[idx] == detach)
                break;
        }
        if (idx >= vm->def->nhostdevs) {
2454
            virReportError(VIR_ERR_INTERNAL_ERROR,
2455
                           _("device not found in hostdevs list (%zu entries)"),
2456
                           vm->def->nhostdevs);
2457 2458
            return ret;
        }
2459 2460
    }

2461
    switch (detach->source.subsys.type) {
2462
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
2463 2464
        ret = qemuDomainDetachHostPciDevice(driver, vm, detach);
        break;
2465
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
2466
        ret = qemuDomainDetachHostUsbDevice(driver, vm, detach);
2467 2468
        break;
    default:
2469 2470 2471
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(detach->source.subsys.type));
2472 2473 2474
        return -1;
    }

2475 2476
    if (!ret) {
        if (virSecurityManagerRestoreHostdevLabel(driver->securityManager,
2477
                                                  vm->def, detach, NULL) < 0) {
2478 2479 2480 2481
            VIR_WARN("Failed to restore host device labelling");
        }
        virDomainHostdevRemove(vm->def, idx);
        virDomainHostdevDefFree(detach);
2482
    }
2483 2484
    return ret;
}
2485

2486
/* search for a hostdev matching dev and detach it */
2487
int qemuDomainDetachHostDevice(virQEMUDriverPtr driver,
2488 2489 2490 2491 2492 2493 2494 2495 2496
                               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) {
2497 2498 2499
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev mode '%s' not supported"),
                       virDomainHostdevModeTypeToString(hostdev->mode));
2500 2501 2502 2503 2504 2505
        return -1;
    }

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

    if (idx < 0) {
2506
        switch (subsys->type) {
2507
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
2508 2509 2510 2511
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("host pci device %.4x:%.2x:%.2x.%.1x not found"),
                           subsys->u.pci.domain, subsys->u.pci.bus,
                           subsys->u.pci.slot, subsys->u.pci.function);
2512 2513 2514
            break;
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
            if (subsys->u.usb.bus && subsys->u.usb.device) {
2515 2516 2517
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("host usb device %03d.%03d not found"),
                               subsys->u.usb.bus, subsys->u.usb.device);
2518
            } else {
2519 2520 2521
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("host usb device vendor=0x%.4x product=0x%.4x not found"),
                               subsys->u.usb.vendor, subsys->u.usb.product);
2522 2523 2524
            }
            break;
        default:
2525 2526
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected hostdev type %d"), subsys->type);
2527 2528 2529 2530 2531
            break;
        }
        return -1;
    }

2532 2533 2534 2535 2536 2537 2538
    /* If this is a network hostdev, we need to use the higher-level detach
     * function so that mac address / virtualport are reset
     */
    if (detach->parent.type == VIR_DOMAIN_DEVICE_NET)
        return qemuDomainDetachNetDevice(driver, vm, &detach->parent);
    else
        return qemuDomainDetachThisHostDevice(driver, vm, detach, idx);
2539 2540
}

2541
int
2542
qemuDomainDetachNetDevice(virQEMUDriverPtr driver,
2543 2544 2545
                          virDomainObjPtr vm,
                          virDomainDeviceDefPtr dev)
{
2546
    int detachidx, ret = -1;
2547 2548 2549 2550
    virDomainNetDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int vlan;
    char *hostnet_name = NULL;
2551
    char mac[VIR_MAC_STRING_BUFLEN];
2552
    virNetDevVPortProfilePtr vport = NULL;
2553
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2554

2555 2556 2557 2558 2559 2560
    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;
2561
    }
2562
    else if (detachidx < 0) {
2563
        virReportError(VIR_ERR_OPERATION_FAILED,
2564 2565
                       _("network device %s not found"),
                       virMacAddrFormat(&dev->data.net->mac, mac));
2566 2567
        goto cleanup;
    }
2568
    detach = vm->def->nets[detachidx];
2569

2570
    if (virDomainNetGetActualType(detach) == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
2571
        /* coverity[negative_returns] */
2572 2573 2574 2575 2576 2577
        ret = qemuDomainDetachThisHostDevice(driver, vm,
                                             virDomainNetGetActualHostdev(detach),
                                             -1);
        goto cleanup;
    }

2578 2579
    if (!virDomainDeviceAddressIsValid(&detach->info,
                                       VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
2580 2581
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("device cannot be detached without a PCI address"));
2582 2583 2584 2585
        goto cleanup;
    }

    if (qemuIsMultiFunctionDevice(vm->def, &detach->info)) {
2586 2587 2588
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device :%s"),
                       dev->data.disk->dst);
2589 2590 2591 2592
        goto cleanup;
    }

    if ((vlan = qemuDomainNetVLAN(detach)) < 0) {
2593 2594
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("unable to determine original VLAN"));
2595 2596 2597 2598 2599 2600 2601 2602 2603
        goto cleanup;
    }

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

    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2604
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    }

2619 2620
    if (qemuCapsGet(priv->caps, QEMU_CAPS_NETDEV) &&
        qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE)) {
2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
        if (qemuMonitorRemoveNetdev(priv->mon, hostnet_name) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemoveHostNetwork(priv->mon, vlan, hostnet_name) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);

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

2637
    if (qemuCapsGet(priv->caps, QEMU_CAPS_DEVICE) &&
2638 2639 2640 2641 2642 2643 2644 2645
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
                                        detach->info.addr.pci.slot) < 0)
        VIR_WARN("Unable to release PCI address on NIC");

    virDomainConfNWFilterTeardown(detach);

    if (virDomainNetGetActualType(detach) == VIR_DOMAIN_NET_TYPE_DIRECT) {
        ignore_value(virNetDevMacVLanDeleteWithVPortProfile(
2646
                         detach->ifname, &detach->mac,
2647 2648 2649
                         virDomainNetGetActualDirectDev(detach),
                         virDomainNetGetActualDirectMode(detach),
                         virDomainNetGetActualVirtPortProfile(detach),
2650
                         cfg->stateDir));
2651 2652 2653
        VIR_FREE(detach->ifname);
    }

2654
    if (cfg->macFilter && (detach->ifname != NULL)) {
2655 2656
        if ((errno = networkDisallowMacOnPort(driver,
                                              detach->ifname,
2657
                                              &detach->mac))) {
2658
            virReportSystemError(errno,
2659
             _("failed to remove ebtables rule on '%s'"),
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670
                                 detach->ifname);
        }
    }

    vport = virDomainNetGetActualVirtPortProfile(detach);
    if (vport && vport->virtPortType == VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH)
        ignore_value(virNetDevOpenvswitchRemovePort(
                        virDomainNetGetActualBridgeName(detach),
                        detach->ifname));
    ret = 0;
cleanup:
2671 2672
    if (!ret) {
        networkReleaseActualDevice(detach);
2673
        virDomainNetRemove(vm->def, detachidx);
2674 2675
        virDomainNetDefFree(detach);
    }
2676
    VIR_FREE(hostnet_name);
2677
    virObjectUnref(cfg);
2678 2679 2680
    return ret;
}

2681
int
2682
qemuDomainChangeGraphicsPasswords(virQEMUDriverPtr driver,
2683 2684 2685 2686 2687 2688 2689 2690
                                  virDomainObjPtr vm,
                                  int type,
                                  virDomainGraphicsAuthDefPtr auth,
                                  const char *defaultPasswd)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    time_t now = time(NULL);
    char expire_time [64];
2691
    const char *connected = NULL;
2692 2693
    int ret = -1;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2694

2695 2696 2697 2698
    if (!auth->passwd && !cfg->vncPassword) {
        ret = 0;
        goto cleanup;
    }
2699

2700 2701 2702
    if (auth->connected)
        connected = virDomainGraphicsAuthConnectedTypeToString(auth->connected);

2703
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2704 2705 2706
    ret = qemuMonitorSetPassword(priv->mon,
                                 type,
                                 auth->passwd ? auth->passwd : defaultPasswd,
2707
                                 connected);
2708 2709 2710

    if (ret == -2) {
        if (type != VIR_DOMAIN_GRAPHICS_TYPE_VNC) {
2711 2712
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Graphics password only supported for VNC"));
2713 2714 2715 2716 2717 2718
            ret = -1;
        } else {
            ret = qemuMonitorSetVNCPassword(priv->mon,
                                            auth->passwd ? auth->passwd : defaultPasswd);
        }
    }
2719
    if (ret != 0)
2720
        goto end_job;
2721

2722 2723 2724
    if (auth->expires) {
        time_t lifetime = auth->validTo - now;
        if (lifetime <= 0)
2725
            snprintf(expire_time, sizeof(expire_time), "now");
2726
        else
2727
            snprintf(expire_time, sizeof(expire_time), "%lu", (long unsigned)auth->validTo);
2728
    } else {
2729
        snprintf(expire_time, sizeof(expire_time), "never");
2730 2731 2732 2733 2734 2735 2736
    }

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

    if (ret == -2) {
        /* XXX we could fake this with a timer */
        if (auth->expires) {
2737 2738
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Expiry of passwords is not supported"));
2739
            ret = -1;
2740 2741
        } else {
            ret = 0;
2742 2743 2744
        }
    }

2745
end_job:
2746
    qemuDomainObjExitMonitorWithDriver(driver, vm);
2747 2748
cleanup:
    virObjectUnref(cfg);
2749 2750
    return ret;
}
2751

2752
int qemuDomainAttachLease(virQEMUDriverPtr driver,
2753 2754 2755
                          virDomainObjPtr vm,
                          virDomainLeaseDefPtr lease)
{
2756 2757 2758
    int ret = -1;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);

2759
    if (virDomainLeaseInsertPreAlloc(vm->def) < 0)
2760
        goto cleanup;
2761

2762
    if (virDomainLockLeaseAttach(driver->lockManager, cfg->uri,
2763
                                 vm, lease) < 0) {
2764
        virDomainLeaseInsertPreAlloced(vm->def, NULL);
2765
        goto cleanup;
2766 2767 2768
    }

    virDomainLeaseInsertPreAlloced(vm->def, lease);
2769 2770 2771 2772 2773
    ret = 0;

cleanup:
    virObjectUnref(cfg);
    return ret;
2774 2775
}

2776
int qemuDomainDetachLease(virQEMUDriverPtr driver,
2777 2778 2779
                          virDomainObjPtr vm,
                          virDomainLeaseDefPtr lease)
{
2780
    virDomainLeaseDefPtr det_lease;
2781 2782 2783
    int i;

    if ((i = virDomainLeaseIndex(vm->def, lease)) < 0) {
2784 2785 2786
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Lease %s in lockspace %s does not exist"),
                       lease->key, NULLSTR(lease->lockspace));
2787 2788 2789 2790 2791 2792
        return -1;
    }

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

2793 2794
    det_lease = virDomainLeaseRemoveAt(vm->def, i);
    virDomainLeaseDefFree(det_lease);
2795 2796
    return 0;
}