qemu_hotplug.c 98.6 KB
Newer Older
1 2 3
/*
 * qemu_hotplug.h: QEMU device hotplug management
 *
4
 * Copyright (C) 2006-2013 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
                                   virDomainObjPtr vm,
                                   virDomainDiskDefPtr disk,
56
                                   virDomainDiskDefPtr origdisk,
57 58
                                   bool force)
{
59
    int ret = -1;
60
    char *driveAlias = NULL;
61
    qemuDomainObjPrivatePtr priv = vm->privateData;
62
    int retries = CHANGE_MEDIA_RETRIES;
63
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
64 65

    if (!origdisk->info.alias) {
66 67
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("missing disk device alias name for %s"), origdisk->dst);
68
        goto cleanup;
69 70 71 72
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
        origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
73 74
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
75
                       virDomainDiskDeviceTypeToString(disk->device));
76
        goto cleanup;
77 78
    }

79
    if (virDomainLockDiskAttach(driver->lockManager, cfg->uri,
80
                                vm, disk) < 0)
81
        goto cleanup;
82

83
    if (virSecurityManagerSetImageLabel(driver->securityManager,
84
                                        vm->def, disk) < 0) {
85 86
        if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
            VIR_WARN("Unable to release lock on %s", disk->src);
87
        goto cleanup;
88
    }
89

90
    if (!(driveAlias = qemuDeviceDriveHostAlias(origdisk, priv->qemuCaps)))
91 92
        goto error;

93
    qemuDomainObjEnterMonitor(driver, vm);
94 95 96 97 98 99 100 101 102 103 104
    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 */
    }

105
    if (disk->src) {
106 107
        /* deliberately don't depend on 'ret' as 'eject' may have failed for the
         * fist time and we are gonna check the drive state anyway */
108
        const char *format = NULL;
109 110 111 112 113 114 115 116 117 118

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

119
        if (disk->type != VIR_DOMAIN_DISK_TYPE_DIR) {
120 121 122 123
            if (disk->format > 0)
                format = virStorageFileFormatTypeToString(disk->format);
            else if (origdisk->format > 0)
                format = virStorageFileFormatTypeToString(origdisk->format);
124 125 126 127 128
        }
        ret = qemuMonitorChangeMedia(priv->mon,
                                     driveAlias,
                                     disk->src, format);
    }
129
exit_monitor:
130
    qemuDomainObjExitMonitor(driver, vm);
131

132
    virDomainAuditDisk(vm, origdisk->src, disk->src, "update", ret >= 0);
133 134 135 136

    if (ret < 0)
        goto error;

137
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
138
                                            vm->def, origdisk) < 0)
139 140
        VIR_WARN("Unable to restore security label on ejected image %s", origdisk->src);

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

144 145 146 147 148 149 150 151
    VIR_FREE(origdisk->src);
    origdisk->src = disk->src;
    disk->src = NULL;
    origdisk->type = disk->type;


    virDomainDiskDefFree(disk);

152 153 154
cleanup:
    VIR_FREE(driveAlias);
    virObjectUnref(cfg);
155 156 157
    return ret;

error:
158
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
159
                                            vm->def, disk) < 0)
160
        VIR_WARN("Unable to restore security label on new media %s", disk->src);
161 162 163 164

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

165
    goto cleanup;
166 167
}

168
int
169
qemuDomainCheckEjectableMedia(virQEMUDriverPtr driver,
170 171
                             virDomainObjPtr vm,
                             enum qemuDomainAsyncJob asyncJob)
172 173
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
174
    virHashTablePtr table = NULL;
175 176 177
    int ret = -1;
    int i;

178 179
    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) == 0) {
        table = qemuMonitorGetBlockInfo(priv->mon);
180
        qemuDomainObjExitMonitor(driver, vm);
181
    }
182 183 184 185

    if (!table)
        goto cleanup;

186 187
    for (i = 0; i < vm->def->ndisks; i++) {
        virDomainDiskDefPtr disk = vm->def->disks[i];
188
        struct qemuDomainDiskInfo *info;
189

190 191
        if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK ||
            disk->device == VIR_DOMAIN_DISK_DEVICE_LUN) {
192
                 continue;
193
        }
194

195 196
        info = qemuMonitorBlockInfoLookup(table, disk->info.alias);
        if (!info)
197 198
            goto cleanup;

199
        if (info->tray_open && disk->src)
200 201 202 203 204 205
            VIR_FREE(disk->src);
    }

    ret = 0;

cleanup:
206
    virHashFree(table);
207 208 209
    return ret;
}

210 211 212 213
int qemuDomainAttachVirtioDiskDevice(virConnectPtr conn,
                                     virQEMUDriverPtr driver,
                                     virDomainObjPtr vm,
                                     virDomainDiskDefPtr disk)
214
{
215
    int i, ret = -1;
216 217 218 219
    const char* type = virDomainDiskBusTypeToString(disk->bus);
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *devstr = NULL;
    char *drivestr = NULL;
220
    bool releaseaddr = false;
221
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
222

223 224 225 226 227 228 229 230
    if (!disk->info.type) {
        if (STREQLEN(vm->def->os.machine, "s390-ccw", 8) &&
            virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_CCW))
            disk->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW;
        else if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_S390))
            disk->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_VIRTIO_S390;
    }

231 232
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
233 234
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("target %s already exists"), disk->dst);
235
            goto cleanup;
236 237 238
        }
    }

239
    if (virDomainLockDiskAttach(driver->lockManager, cfg->uri,
240
                                vm, disk) < 0)
241
        goto cleanup;
242

243
    if (virSecurityManagerSetImageLabel(driver->securityManager,
244
                                        vm->def, disk) < 0) {
245 246
        if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
            VIR_WARN("Unable to release lock on %s", disk->src);
247
        goto cleanup;
248
    }
249

250
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
251 252 253 254
        if (disk->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW) {
            if (qemuDomainCCWAddressAssign(&disk->info, priv->ccwaddrs,
                                           !disk->info.addr.ccw.assigned) < 0)
                goto error;
255 256
        } else if (!disk->info.type ||
                    disk->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
257 258 259
            if (qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &disk->info) < 0)
                goto error;
        }
260
        releaseaddr = true;
261
        if (qemuAssignDeviceDiskAlias(vm->def, disk, priv->qemuCaps) < 0)
262 263
            goto error;

264
        if (!(drivestr = qemuBuildDriveStr(conn, disk, false, priv->qemuCaps)))
265 266
            goto error;

267
        if (!(devstr = qemuBuildDriveDevStr(NULL, disk, 0, priv->qemuCaps)))
268 269 270 271 272 273 274 275
            goto error;
    }

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

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

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

    if (ret < 0)
        goto error;

    virDomainDiskInsertPreAlloced(vm->def, disk);

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

error:
322 323 324 325 326 327 328 329 330 331
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE) && releaseaddr) {
        if (disk->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI &&
            qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
                                            &disk->info.addr.pci) < 0)
            VIR_WARN("Unable to release PCI address on %s", disk->src);
        else if (disk->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW &&
                 qemuDomainCCWAddressReleaseAddr(priv->ccwaddrs,
                                                 &disk->info) < 0)
            VIR_WARN("Unable to release CCW address on %s", disk->src);
    }
332

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

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

340
    goto cleanup;
341 342 343
}


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

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

361
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
362 363
        if (qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &controller->info) < 0)
            goto cleanup;
364
        releaseaddr = true;
365 366 367
        if (qemuAssignDeviceControllerAlias(controller) < 0)
            goto cleanup;

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

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

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

386
    qemuDomainObjEnterMonitor(driver, vm);
387
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
388 389 390 391 392 393
        ret = qemuMonitorAddDevice(priv->mon, devstr);
    } else {
        ret = qemuMonitorAttachPCIDiskController(priv->mon,
                                                 type,
                                                 &controller->info.addr.pci);
    }
394
    qemuDomainObjExitMonitor(driver, vm);
395 396 397 398 399 400 401 402

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

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

    VIR_FREE(devstr);
    return ret;
}

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

422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
    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;
439
    cont->idx = controller;
440 441
    cont->model = -1;

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

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

    return cont;
}


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

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

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

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

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

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

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

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

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

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

533
    qemuDomainObjEnterMonitor(driver, vm);
534
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
        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;
555 556
            disk->info.addr.drive.bus = driveAddr.bus;
            disk->info.addr.drive.unit = driveAddr.unit;
557 558
        }
    }
559
    qemuDomainObjExitMonitor(driver, vm);
560

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

    if (ret < 0)
        goto error;

    virDomainDiskInsertPreAlloced(vm->def, disk);

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

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

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

582
    goto cleanup;
583 584 585
}


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

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

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

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

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

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

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

637
    qemuDomainObjEnterMonitor(driver, vm);
638
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
639 640 641 642 643 644 645 646 647 648 649 650 651
        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);
    }
652
    qemuDomainObjExitMonitor(driver, vm);
653

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

    if (ret < 0)
        goto error;

    virDomainDiskInsertPreAlloced(vm->def, disk);

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

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

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

675
    goto cleanup;
676 677 678 679 680
}


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

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

707 708 709 710 711
    /* 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)
712
        goto cleanup;
713 714

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

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

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

733 734
    if (actualType == VIR_DOMAIN_NET_TYPE_BRIDGE ||
        actualType == VIR_DOMAIN_NET_TYPE_NETWORK) {
R
Richa Marwaha 已提交
735 736 737 738 739 740
        /*
         * 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 ||
741
            cfg->privileged ||
742
            (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NETDEV_BRIDGE))) {
R
Richa Marwaha 已提交
743
            if ((tapfd = qemuNetworkIfaceConnect(vm->def, conn, driver, net,
744
                                                 priv->qemuCaps)) < 0)
R
Richa Marwaha 已提交
745 746
                goto cleanup;
            iface_connected = true;
747
            if (qemuOpenVhostNet(vm->def, net, priv->qemuCaps, &vhostfd) < 0)
R
Richa Marwaha 已提交
748 749
                goto cleanup;
        }
750
    } else if (actualType == VIR_DOMAIN_NET_TYPE_DIRECT) {
751
        if ((tapfd = qemuPhysIfaceConnect(vm->def, driver, net,
752
                                          priv->qemuCaps,
753
                                          VIR_NETDEV_VPORT_PROFILE_OP_CREATE)) < 0)
754 755
            goto cleanup;
        iface_connected = true;
756
        if (qemuOpenVhostNet(vm->def, net, priv->qemuCaps, &vhostfd) < 0)
757
            goto cleanup;
758 759 760
    } else if (actualType == VIR_DOMAIN_NET_TYPE_ETHERNET) {
        if (qemuOpenVhostNet(vm->def, net, priv->qemuCaps, &vhostfd) < 0)
            goto cleanup;
761 762
    }

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

769 770 771 772 773 774 775 776 777 778 779 780
    if (STREQLEN(vm->def->os.machine, "s390-ccw", 8) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_CCW)) {
        net->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW;
        if (qemuDomainCCWAddressAssign(&net->info, priv->ccwaddrs,
                                       !net->info.addr.ccw.assigned) < 0)
            goto cleanup;
    } else if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_S390))
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("virtio-s390 net device cannot be hotplugged."));
    else if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE) &&
             qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &net->info) < 0)
             goto cleanup;
781

782 783
    releaseaddr = true;

784 785
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NETDEV) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
786 787 788 789 790
        vlan = -1;
    } else {
        vlan = qemuDomainNetVLAN(net);

        if (vlan < 0) {
791 792
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Unable to attach network devices without vlan"));
793 794 795 796 797 798 799 800 801
            goto cleanup;
        }
    }

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

802 803 804 805 806
    if (vhostfd != -1) {
        if (virAsprintf(&vhostfd_name, "vhostfd-%s", net->info.alias) < 0)
            goto no_memory;
    }

807 808 809
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NETDEV) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
        if (!(netstr = qemuBuildHostNetStr(net, driver, priv->qemuCaps,
R
Richa Marwaha 已提交
810 811
                                           ',', -1, tapfd_name,
                                           vhostfd_name)))
812
            goto cleanup;
813
    } else {
814
        if (!(netstr = qemuBuildHostNetStr(net, driver, priv->qemuCaps,
R
Richa Marwaha 已提交
815 816
                                           ' ', vlan, tapfd_name,
                                           vhostfd_name)))
817
            goto cleanup;
818 819
    }

820
    qemuDomainObjEnterMonitor(driver, vm);
821 822
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NETDEV) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
823 824
        if (qemuMonitorAddNetdev(priv->mon, netstr, tapfd, tapfd_name,
                                 vhostfd, vhostfd_name) < 0) {
825
            qemuDomainObjExitMonitor(driver, vm);
826
            virDomainAuditNet(vm, NULL, net, "attach", false);
827
            goto cleanup;
828 829
        }
    } else {
830 831
        if (qemuMonitorAddHostNetwork(priv->mon, netstr, tapfd, tapfd_name,
                                      vhostfd, vhostfd_name) < 0) {
832
            qemuDomainObjExitMonitor(driver, vm);
833
            virDomainAuditNet(vm, NULL, net, "attach", false);
834
            goto cleanup;
835 836
        }
    }
837
    qemuDomainObjExitMonitor(driver, vm);
838 839

    VIR_FORCE_CLOSE(tapfd);
840
    VIR_FORCE_CLOSE(vhostfd);
841 842

    if (!virDomainObjIsActive(vm)) {
843 844
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest unexpectedly quit"));
845 846 847
        goto cleanup;
    }

848 849
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
        if (!(nicstr = qemuBuildNicDevStr(net, vlan, 0, priv->qemuCaps)))
850 851 852 853 854 855
            goto try_remove;
    } else {
        if (!(nicstr = qemuBuildNicStr(net, NULL, vlan)))
            goto try_remove;
    }

856
    qemuDomainObjEnterMonitor(driver, vm);
857
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
858
        if (qemuMonitorAddDevice(priv->mon, nicstr) < 0) {
859
            qemuDomainObjExitMonitor(driver, vm);
860
            virDomainAuditNet(vm, NULL, net, "attach", false);
861 862 863
            goto try_remove;
        }
    } else {
864
        guestAddr = net->info.addr.pci;
865 866
        if (qemuMonitorAddPCINetwork(priv->mon, nicstr,
                                     &guestAddr) < 0) {
867
            qemuDomainObjExitMonitor(driver, vm);
868
            virDomainAuditNet(vm, NULL, net, "attach", false);
869 870 871 872 873
            goto try_remove;
        }
        net->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
        memcpy(&net->info.addr.pci, &guestAddr, sizeof(guestAddr));
    }
874
    qemuDomainObjExitMonitor(driver, vm);
875

876 877 878
    /* set link state */
    if (net->linkstate == VIR_DOMAIN_NET_INTERFACE_LINK_STATE_DOWN) {
        if (!net->info.alias) {
879 880
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("device alias not found: cannot set link state to down"));
881
        } else {
882
            qemuDomainObjEnterMonitor(driver, vm);
883

884
            if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NETDEV)) {
885
                if (qemuMonitorSetLink(priv->mon, net->info.alias, VIR_DOMAIN_NET_INTERFACE_LINK_STATE_DOWN) < 0) {
886
                    qemuDomainObjExitMonitor(driver, vm);
887 888 889 890
                    virDomainAuditNet(vm, NULL, net, "attach", false);
                    goto try_remove;
                }
            } else {
891
                virReportError(VIR_ERR_OPERATION_FAILED, "%s",
892
                               _("setting of link state not supported: Link is up"));
893 894
            }

895
            qemuDomainObjExitMonitor(driver, vm);
896 897 898 899
        }
        /* link set to down */
    }

900
    virDomainAuditNet(vm, NULL, net, "attach", true);
901 902 903 904

    ret = 0;

cleanup:
905 906 907
    if (!ret) {
        vm->def->nets[vm->def->nnets++] = net;
    } else {
908
        if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE) &&
909
            net->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI &&
910 911
            releaseaddr &&
            qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
912
                                            &net->info.addr.pci) < 0)
913
            VIR_WARN("Unable to release PCI address on NIC");
914 915 916 917 918 919 920
        else if (STREQLEN(vm->def->os.machine, "s390-ccw", 8) &&
                 virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_CCW) &&
                 net->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW &&
                 releaseaddr &&
                 qemuDomainCCWAddressReleaseAddr(priv->ccwaddrs,
                                                 &net->info) < 0)
            VIR_WARN("Unable to release CCW address on NIC");
921

922
        if (iface_connected) {
923
            virDomainConfNWFilterTeardown(net);
924

925 926 927 928 929
            vport = virDomainNetGetActualVirtPortProfile(net);
            if (vport && vport->virtPortType == VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH)
               ignore_value(virNetDevOpenvswitchRemovePort(
                               virDomainNetGetActualBridgeName(net), net->ifname));
        }
A
Ansis Atteka 已提交
930

931 932
        networkReleaseActualDevice(net);
    }
933 934 935 936 937

    VIR_FREE(nicstr);
    VIR_FREE(netstr);
    VIR_FREE(tapfd_name);
    VIR_FORCE_CLOSE(tapfd);
938 939
    VIR_FREE(vhostfd_name);
    VIR_FORCE_CLOSE(vhostfd);
940
    virObjectUnref(cfg);
941 942 943 944 945 946 947 948

    return ret;

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

    if (vlan < 0) {
949 950
        if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NETDEV) &&
            virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
951 952 953
            char *netdev_name;
            if (virAsprintf(&netdev_name, "host%s", net->info.alias) < 0)
                goto no_memory;
954
            qemuDomainObjEnterMonitor(driver, vm);
955 956 957
            if (qemuMonitorRemoveNetdev(priv->mon, netdev_name) < 0)
                VIR_WARN("Failed to remove network backend for netdev %s",
                         netdev_name);
958
            qemuDomainObjExitMonitor(driver, vm);
959 960
            VIR_FREE(netdev_name);
        } else {
961
            VIR_WARN("Unable to remove network backend");
962 963 964 965 966
        }
    } else {
        char *hostnet_name;
        if (virAsprintf(&hostnet_name, "host%s", net->info.alias) < 0)
            goto no_memory;
967
        qemuDomainObjEnterMonitor(driver, vm);
968 969 970
        if (qemuMonitorRemoveHostNetwork(priv->mon, vlan, hostnet_name) < 0)
            VIR_WARN("Failed to remove network backend for vlan %d, net %s",
                     vlan, hostnet_name);
971
        qemuDomainObjExitMonitor(driver, vm);
972 973 974 975 976 977 978 979 980 981
        VIR_FREE(hostnet_name);
    }
    goto cleanup;

no_memory:
    virReportOOMError();
    goto cleanup;
}


982
int qemuDomainAttachHostPciDevice(virQEMUDriverPtr driver,
983
                                  virDomainObjPtr vm,
984
                                  virDomainHostdevDefPtr hostdev)
985 986 987 988 989 990
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret;
    char *devstr = NULL;
    int configfd = -1;
    char *configfd_name = NULL;
991
    bool releaseaddr = false;
992 993 994 995 996 997

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

998 999
    if (qemuPrepareHostdevPCIDevices(driver, vm->def->name, vm->def->uuid,
                                     &hostdev, 1) < 0)
1000 1001
        return -1;

1002
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
1003 1004
        if (qemuAssignDeviceHostdevAlias(vm->def, hostdev, -1) < 0)
            goto error;
1005
        if (qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, hostdev->info) < 0)
1006
            goto error;
1007
        releaseaddr = true;
1008
        if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_PCI_CONFIGFD)) {
1009 1010 1011
            configfd = qemuOpenPCIConfig(hostdev);
            if (configfd >= 0) {
                if (virAsprintf(&configfd_name, "fd-%s",
1012
                                hostdev->info->alias) < 0) {
1013 1014 1015 1016 1017 1018 1019
                    virReportOOMError();
                    goto error;
                }
            }
        }

        if (!virDomainObjIsActive(vm)) {
1020 1021
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("guest unexpectedly quit during hotplug"));
1022 1023 1024
            goto error;
        }

1025
        if (!(devstr = qemuBuildPCIHostdevDevStr(hostdev, configfd_name,
1026
                                                 priv->qemuCaps)))
1027 1028
            goto error;

1029
        qemuDomainObjEnterMonitor(driver, vm);
1030 1031
        ret = qemuMonitorAddDeviceWithFd(priv->mon, devstr,
                                         configfd, configfd_name);
1032
        qemuDomainObjExitMonitor(driver, vm);
1033
    } else {
1034
        virDevicePCIAddress guestAddr = hostdev->info->addr.pci;
1035

1036
        qemuDomainObjEnterMonitor(driver, vm);
1037 1038 1039
        ret = qemuMonitorAddPCIHostDevice(priv->mon,
                                          &hostdev->source.subsys.u.pci,
                                          &guestAddr);
1040
        qemuDomainObjExitMonitor(driver, vm);
1041

1042 1043
        hostdev->info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
        memcpy(&hostdev->info->addr.pci, &guestAddr, sizeof(guestAddr));
1044
    }
1045
    virDomainAuditHostdev(vm, hostdev, "attach", ret == 0);
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
    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:
1058
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE) &&
1059
        (hostdev->info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) &&
1060
        releaseaddr &&
1061
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
1062
                                        &hostdev->info->addr.pci) < 0)
1063
        VIR_WARN("Unable to release PCI address on host device");
1064

1065
    qemuDomainReAttachHostdevDevices(driver, vm->def->name, &hostdev, 1);
1066 1067 1068 1069 1070 1071 1072 1073 1074

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

    return -1;
}


1075
int qemuDomainAttachRedirdevDevice(virQEMUDriverPtr driver,
1076 1077 1078 1079 1080
                                   virDomainObjPtr vm,
                                   virDomainRedirdevDefPtr redirdev)
{
    int ret;
    qemuDomainObjPrivatePtr priv = vm->privateData;
1081
    virDomainDefPtr def = vm->def;
1082 1083
    char *devstr = NULL;

1084
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
1085 1086
        if (qemuAssignDeviceRedirdevAlias(vm->def, redirdev, -1) < 0)
            goto error;
1087
        if (!(devstr = qemuBuildRedirdevDevStr(def, redirdev, priv->qemuCaps)))
1088 1089 1090 1091 1092 1093 1094 1095
            goto error;
    }

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

1096
    qemuDomainObjEnterMonitor(driver, vm);
1097
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE))
1098 1099 1100 1101
        ret = qemuMonitorAddDevice(priv->mon, devstr);
    else
        goto error;

1102
    qemuDomainObjExitMonitor(driver, vm);
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
    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;

}

1119
int qemuDomainAttachHostUsbDevice(virQEMUDriverPtr driver,
1120
                                  virDomainObjPtr vm,
1121
                                  virDomainHostdevDefPtr hostdev)
1122 1123 1124 1125 1126
{
    int ret;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *devstr = NULL;

1127
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
1128 1129
        if (qemuAssignDeviceHostdevAlias(vm->def, hostdev, -1) < 0)
            goto error;
1130
        if (!(devstr = qemuBuildUSBHostdevDevStr(hostdev, priv->qemuCaps)))
1131 1132 1133 1134 1135 1136 1137 1138
            goto error;
    }

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

1139
    if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_DEVICES)) {
1140
        virUSBDevicePtr usb;
1141

1142
        if ((usb = virUSBDeviceNew(hostdev->source.subsys.u.usb.bus,
1143 1144
                                hostdev->source.subsys.u.usb.device,
                                NULL)) == NULL)
1145 1146
            goto error;

1147
        if (virUSBDeviceFileIterate(usb, qemuSetupHostUsbDeviceCgroup,
1148
                                    vm) < 0) {
1149
            virUSBDeviceFree(usb);
1150
            goto error;
1151 1152
        }
        virUSBDeviceFree(usb);
1153 1154
    }

1155
    qemuDomainObjEnterMonitor(driver, vm);
1156
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE))
1157 1158 1159 1160 1161
        ret = qemuMonitorAddDevice(priv->mon, devstr);
    else
        ret = qemuMonitorAddUSBDeviceExact(priv->mon,
                                           hostdev->source.subsys.u.usb.bus,
                                           hostdev->source.subsys.u.usb.device);
1162
    qemuDomainObjExitMonitor(driver, vm);
1163
    virDomainAuditHostdev(vm, hostdev, "attach", ret == 0);
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
    if (ret < 0)
        goto error;

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

    VIR_FREE(devstr);

    return 0;

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

1178
int qemuDomainAttachHostDevice(virQEMUDriverPtr driver,
1179
                               virDomainObjPtr vm,
1180
                               virDomainHostdevDefPtr hostdev)
1181
{
1182 1183
    virUSBDeviceList *list;
    virUSBDevicePtr usb = NULL;
1184

1185
    if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
1186 1187 1188
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev mode '%s' not supported"),
                       virDomainHostdevModeTypeToString(hostdev->mode));
1189 1190 1191
        return -1;
    }

1192
    if (!(list = virUSBDeviceListNew()))
1193
        goto cleanup;
1194

1195
    if (hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
1196
        if (qemuFindHostdevUSBDevice(hostdev, true, &usb) < 0)
1197 1198
            goto cleanup;

1199 1200
        if (virUSBDeviceListAdd(list, usb) < 0) {
            virUSBDeviceFree(usb);
M
Marc-André Lureau 已提交
1201
            usb = NULL;
1202 1203 1204
            goto cleanup;
        }

1205 1206
        if (qemuPrepareHostdevUSBDevices(driver, vm->def->name, list) < 0) {
            usb = NULL;
1207
            goto cleanup;
1208
        }
1209

1210
        virUSBDeviceListSteal(list, usb);
1211
    }
1212

1213
    if (virSecurityManagerSetHostdevLabel(driver->securityManager,
1214
                                          vm->def, hostdev, NULL) < 0)
1215
        goto cleanup;
1216 1217 1218 1219

    switch (hostdev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
        if (qemuDomainAttachHostPciDevice(driver, vm,
1220
                                          hostdev) < 0)
1221 1222 1223 1224 1225
            goto error;
        break;

    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
        if (qemuDomainAttachHostUsbDevice(driver, vm,
1226
                                          hostdev) < 0)
1227 1228 1229 1230
            goto error;
        break;

    default:
1231 1232 1233
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(hostdev->source.subsys.type));
1234 1235 1236
        goto error;
    }

1237
    virObjectUnref(list);
1238 1239 1240
    return 0;

error:
1241
    if (virSecurityManagerRestoreHostdevLabel(driver->securityManager,
1242
                                              vm->def, hostdev, NULL) < 0)
1243
        VIR_WARN("Unable to restore host device labelling on hotplug fail");
1244

1245
cleanup:
1246
    virObjectUnref(list);
1247
    if (usb)
1248
        virUSBDeviceListSteal(driver->activeUsbHostdevs, usb);
1249 1250 1251
    return -1;
}

1252 1253
static virDomainNetDefPtr *qemuDomainFindNet(virDomainObjPtr vm,
                                             virDomainNetDefPtr dev)
1254 1255 1256 1257
{
    int i;

    for (i = 0; i < vm->def->nnets; i++) {
1258
        if (virMacAddrCmp(&vm->def->nets[i]->mac, &dev->mac) == 0)
1259
            return &vm->def->nets[i];
1260 1261 1262 1263 1264
    }

    return NULL;
}

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

1310 1311 1312 1313
    } else {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Interface type %d has no bridge name"),
                       virDomainNetGetActualType(net));
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
    }

cleanup:
    return brname;
}

static int
qemuDomainChangeNetBridge(virConnectPtr conn,
                          virDomainObjPtr vm,
                          virDomainNetDefPtr olddev,
                          virDomainNetDefPtr newdev)
1325 1326
{
    int ret = -1;
1327 1328 1329 1330 1331 1332 1333
    char *oldbridge = NULL, *newbridge = NULL;

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

    if (!(newbridge = qemuDomainNetGetBridgeName(conn, newdev)))
        goto cleanup;
1334 1335 1336 1337 1338

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

    if (virNetDevExists(newbridge) != 1) {
1339 1340
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("bridge %s doesn't exist"), newbridge);
1341
        goto cleanup;
1342 1343 1344 1345 1346
    }

    if (oldbridge) {
        ret = virNetDevBridgeRemovePort(oldbridge, olddev->ifname);
        virDomainAuditNet(vm, olddev, NULL, "detach", ret == 0);
1347 1348 1349 1350 1351 1352 1353 1354
        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);
        }
1355 1356 1357
    }

    ret = virNetDevBridgeAddPort(newbridge, olddev->ifname);
1358
    virDomainAuditNet(vm, NULL, newdev, "attach", ret == 0);
1359 1360 1361 1362
    if (ret < 0) {
        ret = virNetDevBridgeAddPort(oldbridge, olddev->ifname);
        virDomainAuditNet(vm, NULL, olddev, "attach", ret == 0);
        if (ret < 0) {
1363
            virReportError(VIR_ERR_OPERATION_FAILED,
1364
                           _("unable to recover former state by adding port "
1365
                             "to bridge %s"), oldbridge);
1366
        }
1367
        goto cleanup;
1368
    }
1369 1370 1371
    /* caller will replace entire olddev with newdev in domain nets list */
    ret = 0;
cleanup:
1372
    VIR_FREE(oldbridge);
1373 1374
    VIR_FREE(newbridge);
    return ret;
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 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
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;
}

1414
int qemuDomainChangeNetLinkState(virQEMUDriverPtr driver,
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
                                 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) {
1425 1426
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("can't change link state: device alias not found"));
1427 1428 1429
        return -1;
    }

1430
    qemuDomainObjEnterMonitor(driver, vm);
1431 1432 1433 1434 1435 1436 1437 1438 1439

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

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

cleanup:
1440
    qemuDomainObjExitMonitor(driver, vm);
1441 1442 1443 1444

    return ret;
}

1445
int
1446
qemuDomainChangeNet(virQEMUDriverPtr driver,
1447 1448 1449
                    virDomainObjPtr vm,
                    virDomainPtr dom,
                    virDomainDeviceDefPtr dev)
1450
{
1451 1452 1453 1454 1455 1456
    virDomainNetDefPtr newdev = dev->data.net;
    virDomainNetDefPtr *devslot = qemuDomainFindNet(vm, newdev);
    virDomainNetDefPtr olddev;
    int oldType, newType;
    bool needReconnect = false;
    bool needBridgeChange = false;
1457
    bool needFilterChange = false;
1458 1459 1460
    bool needLinkStateChange = false;
    bool needReplaceDevDef = false;
    int ret = -1;
1461

1462
    if (!devslot || !(olddev = *devslot)) {
1463
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
1464
                       _("cannot find existing network device to modify"));
1465 1466 1467 1468 1469 1470
        goto cleanup;
    }

    oldType = virDomainNetGetActualType(olddev);
    if (oldType == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
        /* no changes are possible to a type='hostdev' interface */
1471
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
                       _("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];

1494
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
1495 1496 1497 1498 1499 1500 1501 1502
                       _("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)) {
1503
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
1504 1505 1506 1507
                       _("cannot modify network device model from %s to %s"),
                       olddev->model ? olddev->model : "(default)",
                       newdev->model ? newdev->model : "(default)");
        goto cleanup;
1508 1509
    }

1510 1511 1512 1513 1514
    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)) {
1515
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
                       _("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;
1526 1527
    }

1528
    if (STRNEQ_NULLABLE(olddev->script, newdev->script)) {
1529
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1530 1531
                       _("cannot modify network device script attribute"));
        goto cleanup;
1532 1533
    }

1534 1535 1536 1537 1538 1539 1540
    /* 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)) {
1541
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1542 1543 1544
                       _("cannot modify network device tap name"));
        goto cleanup;
    }
1545

1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
    /* 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)) {
1559
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
                       _("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)) {
1570
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1571 1572 1573 1574
                       _("cannot modify network device alias"));
        goto cleanup;
    }
    if (olddev->info.rombar != newdev->info.rombar) {
1575
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1576 1577 1578 1579
                       _("cannot modify network device rom bar setting"));
        goto cleanup;
    }
    if (STRNEQ_NULLABLE(olddev->info.romfile, newdev->info.romfile)) {
1580
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1581 1582 1583 1584
                       _("cannot modify network rom file"));
        goto cleanup;
    }
    if (olddev->info.bootIndex != newdev->info.bootIndex) {
1585
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1586 1587 1588 1589
                       _("cannot modify network device boot index setting"));
        goto cleanup;
    }
    /* (end of device info checks) */
1590

1591 1592 1593 1594
    if (STRNEQ_NULLABLE(olddev->filter, newdev->filter) ||
        !virNWFilterHashTableEqual(olddev->filterparams, newdev->filterparams)) {
        needFilterChange = true;
    }
1595

1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
    /* 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 */
1612
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
1613 1614 1615 1616 1617 1618
                       _("cannot change network interface type to '%s'"),
                       virDomainNetTypeToString(newType));
        goto cleanup;
    }

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

1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
        /* 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;
            }
1632 1633
        break;

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 1661 1662 1663 1664 1665 1666 1667 1668 1669
        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:
1670
            virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
1671 1672 1673
                           _("unable to change config on '%s' network type"),
                           virDomainNetTypeToString(newdev->type));
            break;
1674

1675
        }
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
    } 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;
1707 1708

        }
1709
    }
1710

1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
    /* 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;
    }
1722

1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
    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;
1733 1734
    }

1735 1736 1737 1738 1739 1740
    if (olddev->linkstate != newdev->linkstate)
        needLinkStateChange = true;

    /* FINALLY - actually perform the required actions */

    if (needReconnect) {
1741
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
1742 1743 1744
                       _("unable to change config on '%s' network type"),
                       virDomainNetTypeToString(newdev->type));
        goto cleanup;
1745 1746
    }

1747 1748 1749 1750 1751
    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,
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
         * 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 */
1762
        needReplaceDevDef = true;
1763 1764
    }

1765 1766 1767
    if (needLinkStateChange &&
        qemuDomainChangeNetLinkState(driver, vm, olddev, newdev->linkstate) < 0) {
        goto cleanup;
1768 1769
    }

1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
    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;
1783 1784
    }

1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
    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);

1808 1809 1810 1811
    return ret;
}


1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827

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
1828
qemuDomainChangeGraphics(virQEMUDriverPtr driver,
1829 1830 1831 1832
                         virDomainObjPtr vm,
                         virDomainGraphicsDefPtr dev)
{
    virDomainGraphicsDefPtr olddev = qemuDomainFindGraphics(vm, dev);
1833
    const char *oldListenAddr, *newListenAddr;
1834
    const char *oldListenNetwork, *newListenNetwork;
1835
    int ret = -1;
1836
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
1837 1838

    if (!olddev) {
1839 1840
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot find existing graphics device to modify"));
1841
        goto cleanup;
1842 1843
    }

1844 1845
    oldListenAddr = virDomainGraphicsListenGetAddress(olddev, 0);
    newListenAddr = virDomainGraphicsListenGetAddress(dev, 0);
1846 1847
    oldListenNetwork = virDomainGraphicsListenGetNetwork(olddev, 0);
    newListenNetwork = virDomainGraphicsListenGetNetwork(dev, 0);
1848

1849 1850 1851
    switch (dev->type) {
    case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
        if ((olddev->data.vnc.autoport != dev->data.vnc.autoport) ||
E
Eric Blake 已提交
1852 1853
            (!dev->data.vnc.autoport &&
             (olddev->data.vnc.port != dev->data.vnc.port))) {
1854 1855
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change port settings on vnc graphics"));
1856
            goto cleanup;
1857
        }
1858
        if (STRNEQ_NULLABLE(oldListenAddr,newListenAddr)) {
1859 1860
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change listen address setting on vnc graphics"));
1861
            goto cleanup;
1862
        }
1863
        if (STRNEQ_NULLABLE(oldListenNetwork,newListenNetwork)) {
1864 1865
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change listen network setting on vnc graphics"));
1866
            goto cleanup;
1867
        }
1868
        if (STRNEQ_NULLABLE(olddev->data.vnc.keymap, dev->data.vnc.keymap)) {
1869 1870
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change keymap setting on vnc graphics"));
1871
            goto cleanup;
1872 1873
        }

1874 1875 1876
        /* 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 */
1877 1878
        if (olddev->data.vnc.auth.expires ||
            dev->data.vnc.auth.expires ||
1879
            olddev->data.vnc.auth.connected != dev->data.vnc.auth.connected ||
E
Eric Blake 已提交
1880 1881 1882
            STRNEQ_NULLABLE(olddev->data.vnc.auth.passwd,
                            dev->data.vnc.auth.passwd)) {
            VIR_DEBUG("Updating password on VNC server %p %p",
1883
                      dev->data.vnc.auth.passwd, cfg->vncPassword);
E
Eric Blake 已提交
1884 1885 1886
            ret = qemuDomainChangeGraphicsPasswords(driver, vm,
                                                    VIR_DOMAIN_GRAPHICS_TYPE_VNC,
                                                    &dev->data.vnc.auth,
1887
                                                    cfg->vncPassword);
1888
            if (ret < 0)
1889
                goto cleanup;
1890 1891 1892 1893 1894

            /* 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;
1895 1896
            olddev->data.vnc.auth.validTo = dev->data.vnc.auth.validTo;
            olddev->data.vnc.auth.expires = dev->data.vnc.auth.expires;
1897
            olddev->data.vnc.auth.connected = dev->data.vnc.auth.connected;
1898 1899 1900 1901 1902
        } else {
            ret = 0;
        }
        break;

1903 1904
    case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
        if ((olddev->data.spice.autoport != dev->data.spice.autoport) ||
E
Eric Blake 已提交
1905 1906 1907 1908
            (!dev->data.spice.autoport &&
             (olddev->data.spice.port != dev->data.spice.port)) ||
            (!dev->data.spice.autoport &&
             (olddev->data.spice.tlsPort != dev->data.spice.tlsPort))) {
1909 1910
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change port settings on spice graphics"));
1911
            goto cleanup;
1912
        }
1913
        if (STRNEQ_NULLABLE(oldListenAddr, newListenAddr)) {
1914 1915
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change listen address setting on spice graphics"));
1916
            goto cleanup;
1917
        }
1918
        if (STRNEQ_NULLABLE(oldListenNetwork, newListenNetwork)) {
1919 1920
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change listen network setting on spice graphics"));
1921
            goto cleanup;
1922
        }
E
Eric Blake 已提交
1923 1924
        if (STRNEQ_NULLABLE(olddev->data.spice.keymap,
                            dev->data.spice.keymap)) {
1925
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1926
                            _("cannot change keymap setting on spice graphics"));
1927
            goto cleanup;
1928 1929
        }

1930 1931 1932 1933 1934
        /* 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"
         */
1935 1936
        if (olddev->data.spice.auth.expires ||
            dev->data.spice.auth.expires ||
1937
            olddev->data.spice.auth.connected != dev->data.spice.auth.connected ||
1938 1939
            dev->data.spice.auth.connected ==
            VIR_DOMAIN_GRAPHICS_AUTH_CONNECTED_DISCONNECT ||
E
Eric Blake 已提交
1940 1941 1942
            STRNEQ_NULLABLE(olddev->data.spice.auth.passwd,
                            dev->data.spice.auth.passwd)) {
            VIR_DEBUG("Updating password on SPICE server %p %p",
1943
                      dev->data.spice.auth.passwd, cfg->spicePassword);
E
Eric Blake 已提交
1944 1945 1946
            ret = qemuDomainChangeGraphicsPasswords(driver, vm,
                                                    VIR_DOMAIN_GRAPHICS_TYPE_SPICE,
                                                    &dev->data.spice.auth,
1947
                                                    cfg->spicePassword);
E
Eric Blake 已提交
1948

1949
            if (ret < 0)
1950
                goto cleanup;
1951

E
Eric Blake 已提交
1952
            /* Steal the new dev's char * reference */
1953 1954 1955 1956 1957
            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;
1958
            olddev->data.spice.auth.connected = dev->data.spice.auth.connected;
1959
        } else {
1960
            VIR_DEBUG("Not updating since password didn't change");
1961 1962
            ret = 0;
        }
E
Eric Blake 已提交
1963
        break;
1964

1965
    default:
1966 1967 1968
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unable to change config on '%s' graphics type"),
                       virDomainGraphicsTypeToString(dev->type));
1969 1970 1971
        break;
    }

1972 1973
cleanup:
    virObjectUnref(cfg);
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
    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;
}

1991
static int qemuComparePCIDevice(virDomainDefPtr def ATTRIBUTE_UNUSED,
1992
                                virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
1993
                                virDomainDeviceInfoPtr info1,
1994 1995
                                void *opaque)
{
1996
    virDomainDeviceInfoPtr info2 = opaque;
1997

1998 1999
    if (info1->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI ||
        info2->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)
2000 2001
        return 0;

2002 2003
    if (info1->addr.pci.slot == info2->addr.pci.slot &&
        info1->addr.pci.function != info2->addr.pci.function)
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015
        return -1;
    return 0;
}

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

2016

2017 2018 2019
int qemuDomainDetachVirtioDiskDevice(virQEMUDriverPtr driver,
                                     virDomainObjPtr vm,
                                     virDomainDeviceDefPtr dev)
2020 2021 2022 2023 2024 2025 2026 2027 2028
{
    int i, ret = -1;
    virDomainDiskDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *drivestr = NULL;

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

    if (i < 0) {
2029 2030
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("disk %s not found"), dev->data.disk->dst);
2031 2032 2033 2034 2035
        goto cleanup;
    }

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

2036
    if (qemuIsMultiFunctionDevice(vm->def, &detach->info)) {
2037 2038 2039
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %s"),
                       dev->data.disk->dst);
2040 2041 2042
        goto cleanup;
    }

2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
    if (STREQLEN(vm->def->os.machine, "s390-ccw", 8) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_CCW)) {
        if (!virDomainDeviceAddressIsValid(&detach->info,
                                           VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW)) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("device cannot be detached without a valid CCW address"));
            goto cleanup;
        }
    } else {
        if (!virDomainDeviceAddressIsValid(&detach->info,
                                           VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("device cannot be detached without a valid PCI address"));
            goto cleanup;
        }
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
    }

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

2068
    qemuDomainObjEnterMonitor(driver, vm);
2069
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
2070
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
2071
            qemuDomainObjExitMonitor(driver, vm);
2072
            virDomainAuditDisk(vm, detach->src, NULL, "detach", false);
2073 2074 2075 2076 2077
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
2078
            qemuDomainObjExitMonitor(driver, vm);
2079
            virDomainAuditDisk(vm, detach->src, NULL, "detach", false);
2080 2081 2082 2083 2084 2085 2086
            goto cleanup;
        }
    }

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

2087
    qemuDomainObjExitMonitor(driver, vm);
2088

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

2091 2092 2093 2094 2095 2096 2097 2098 2099
    if (detach->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW &&
        STREQLEN(vm->def->os.machine, "s390-ccw", 8) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_CCW) &&
        qemuDomainCCWAddressReleaseAddr(priv->ccwaddrs, &detach->info) < 0) {
        VIR_WARN("Unable to release CCW address on %s", dev->data.disk->src);
    } else if (detach->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI &&
               virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE) &&
               qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
                                               &detach->info.addr.pci) < 0)
2100 2101 2102 2103
        VIR_WARN("Unable to release PCI address on %s", dev->data.disk->src);

    virDomainDiskRemove(vm->def, i);

2104 2105
    dev->data.disk->backingChain = detach->backingChain;
    detach->backingChain = NULL;
2106 2107
    virDomainDiskDefFree(detach);

2108
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
2109
                                            vm->def, dev->data.disk) < 0)
2110 2111
        VIR_WARN("Unable to restore security label on %s", dev->data.disk->src);

2112 2113 2114
    if (qemuTeardownDiskCgroup(vm, dev->data.disk) < 0)
        VIR_WARN("Failed to teardown cgroup for disk path %s",
                 NULLSTR(dev->data.disk->src));
2115

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

2119 2120 2121 2122 2123 2124 2125
    ret = 0;

cleanup:
    VIR_FREE(drivestr);
    return ret;
}

2126
int qemuDomainDetachDiskDevice(virQEMUDriverPtr driver,
2127
                               virDomainObjPtr vm,
2128
                               virDomainDeviceDefPtr dev)
2129 2130 2131 2132 2133 2134 2135 2136 2137
{
    int i, ret = -1;
    virDomainDiskDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *drivestr = NULL;

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

    if (i < 0) {
2138 2139
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("disk %s not found"), dev->data.disk->dst);
2140 2141 2142
        goto cleanup;
    }

2143
    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
2144 2145 2146
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Underlying qemu does not support %s disk removal"),
                       virDomainDiskBusTypeToString(dev->data.disk->bus));
2147 2148 2149 2150 2151
        goto cleanup;
    }

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

E
Eric Blake 已提交
2152 2153 2154 2155 2156 2157 2158
    if (detach->mirror) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE,
                       _("disk '%s' is in an active block copy job"),
                       detach->dst);
        goto cleanup;
    }

2159 2160 2161 2162 2163 2164 2165 2166
    /* 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;
    }

2167
    qemuDomainObjEnterMonitor(driver, vm);
2168
    if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
2169
        qemuDomainObjExitMonitor(driver, vm);
2170
        virDomainAuditDisk(vm, detach->src, NULL, "detach", false);
2171 2172 2173 2174 2175 2176
        goto cleanup;
    }

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

2177
    qemuDomainObjExitMonitor(driver, vm);
2178

2179
    virDomainAuditDisk(vm, detach->src, NULL, "detach", true);
2180 2181 2182

    virDomainDiskRemove(vm->def, i);

2183 2184
    dev->data.disk->backingChain = detach->backingChain;
    detach->backingChain = NULL;
2185 2186
    virDomainDiskDefFree(detach);

2187
    if (virSecurityManagerRestoreImageLabel(driver->securityManager,
2188
                                            vm->def, dev->data.disk) < 0)
2189 2190
        VIR_WARN("Unable to restore security label on %s", dev->data.disk->src);

2191 2192 2193
    if (qemuTeardownDiskCgroup(vm, dev->data.disk) < 0)
        VIR_WARN("Failed to teardown cgroup for disk path %s",
                 NULLSTR(dev->data.disk->src));
2194

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

2198 2199 2200 2201 2202 2203 2204
    ret = 0;

cleanup:
    VIR_FREE(drivestr);
    return ret;
}

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 2252 2253 2254
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;
    }
}

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

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

2273 2274
    detach = vm->def->controllers[idx];

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

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

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

2295
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
2296 2297 2298 2299
        if (qemuAssignDeviceControllerAlias(detach) < 0)
            goto cleanup;
    }

2300
    qemuDomainObjEnterMonitor(driver, vm);
2301
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
2302
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias)) {
2303
            qemuDomainObjExitMonitor(driver, vm);
2304 2305 2306 2307 2308
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
2309
            qemuDomainObjExitMonitor(driver, vm);
2310 2311 2312
            goto cleanup;
        }
    }
2313
    qemuDomainObjExitMonitor(driver, vm);
2314

2315 2316
    virDomainControllerRemove(vm->def, idx);
    virDomainControllerDefFree(detach);
2317

2318
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE) &&
2319
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
2320
                                        &detach->info.addr.pci) < 0)
2321
        VIR_WARN("Unable to release PCI address on controller");
2322 2323 2324 2325 2326 2327 2328

    ret = 0;

cleanup:
    return ret;
}

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

2341
    if (qemuIsMultiFunctionDevice(vm->def, detach->info)) {
2342 2343 2344 2345
        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);
2346
        goto cleanup;
2347 2348
    }

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

2356
    qemuDomainObjEnterMonitor(driver, vm);
2357
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
2358
        rv = qemuMonitorDelDevice(priv->mon, detach->info->alias);
2359
    } else {
2360
        rv = qemuMonitorRemovePCIDevice(priv->mon, &detach->info->addr.pci);
2361
    }
2362
    qemuDomainObjExitMonitor(driver, vm);
2363 2364 2365
    virDomainAuditHostdev(vm, detach, "detach", rv == 0);
    if (rv < 0)
        goto cleanup;
2366

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

2374 2375
    virObjectLock(driver->activePciHostdevs);
    virObjectLock(driver->inactivePciHostdevs);
2376 2377
    pci = virPCIDeviceNew(subsys->u.pci.domain, subsys->u.pci.bus,
                          subsys->u.pci.slot,   subsys->u.pci.function);
2378
    if (pci) {
2379
        activePci = virPCIDeviceListSteal(driver->activePciHostdevs, pci);
2380
        if (activePci &&
2381 2382
            virPCIDeviceReset(activePci, driver->activePciHostdevs,
                              driver->inactivePciHostdevs) == 0) {
2383
            qemuReattachPciDevice(activePci, driver);
2384
            ret = 0;
2385 2386
        } else {
            /* reset of the device failed, treat it as if it was returned */
2387
            virPCIDeviceFree(activePci);
2388
        }
2389
        virPCIDeviceFree(pci);
2390
    }
2391 2392
    virObjectUnlock(driver->activePciHostdevs);
    virObjectUnlock(driver->inactivePciHostdevs);
2393

2394
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE) &&
2395
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
2396
                                        &detach->info->addr.pci) < 0)
2397
        VIR_WARN("Unable to release PCI address on host device");
2398

2399 2400
cleanup:
    virObjectUnref(cfg);
2401 2402 2403
    return ret;
}

2404
static int
2405
qemuDomainDetachHostUsbDevice(virQEMUDriverPtr driver,
2406
                              virDomainObjPtr vm,
2407
                              virDomainHostdevDefPtr detach)
2408 2409
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2410
    virDomainHostdevSubsysPtr subsys = &detach->source.subsys;
2411
    virUSBDevicePtr usb;
2412
    int ret;
2413

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

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

2426
    qemuDomainObjEnterMonitor(driver, vm);
2427
    ret = qemuMonitorDelDevice(priv->mon, detach->info->alias);
2428
    qemuDomainObjExitMonitor(driver, vm);
2429
    virDomainAuditHostdev(vm, detach, "detach", ret == 0);
2430 2431
    if (ret < 0)
        return -1;
2432

2433
    usb = virUSBDeviceNew(subsys->u.usb.bus, subsys->u.usb.device, NULL);
2434
    if (usb) {
2435
        virObjectLock(driver->activeUsbHostdevs);
2436
        virUSBDeviceListDel(driver->activeUsbHostdevs, usb);
2437
        virObjectUnlock(driver->activeUsbHostdevs);
2438
        virUSBDeviceFree(usb);
2439 2440
    } else {
        VIR_WARN("Unable to find device %03d.%03d in list of used USB devices",
2441
                 subsys->u.usb.bus, subsys->u.usb.device);
2442 2443 2444 2445
    }
    return ret;
}

2446
static
2447
int qemuDomainDetachThisHostDevice(virQEMUDriverPtr driver,
2448 2449 2450
                                   virDomainObjPtr vm,
                                   virDomainHostdevDefPtr detach,
                                   int idx)
2451
{
2452
    int ret = -1;
2453

2454 2455 2456 2457 2458 2459 2460 2461 2462
    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) {
2463
            virReportError(VIR_ERR_INTERNAL_ERROR,
2464
                           _("device not found in hostdevs list (%zu entries)"),
2465
                           vm->def->nhostdevs);
2466 2467
            return ret;
        }
2468 2469
    }

2470
    switch (detach->source.subsys.type) {
2471
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
2472 2473
        ret = qemuDomainDetachHostPciDevice(driver, vm, detach);
        break;
2474
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
2475
        ret = qemuDomainDetachHostUsbDevice(driver, vm, detach);
2476 2477
        break;
    default:
2478 2479 2480
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(detach->source.subsys.type));
2481 2482 2483
        return -1;
    }

2484 2485
    if (!ret) {
        if (virSecurityManagerRestoreHostdevLabel(driver->securityManager,
2486
                                                  vm->def, detach, NULL) < 0) {
2487 2488 2489 2490
            VIR_WARN("Failed to restore host device labelling");
        }
        virDomainHostdevRemove(vm->def, idx);
        virDomainHostdevDefFree(detach);
2491
    }
2492 2493
    return ret;
}
2494

2495
/* search for a hostdev matching dev and detach it */
2496
int qemuDomainDetachHostDevice(virQEMUDriverPtr driver,
2497 2498 2499 2500 2501 2502 2503 2504 2505
                               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) {
2506 2507 2508
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev mode '%s' not supported"),
                       virDomainHostdevModeTypeToString(hostdev->mode));
2509 2510 2511 2512 2513 2514
        return -1;
    }

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

    if (idx < 0) {
2515
        switch (subsys->type) {
2516
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
2517 2518 2519 2520
            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);
2521 2522 2523
            break;
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
            if (subsys->u.usb.bus && subsys->u.usb.device) {
2524 2525 2526
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("host usb device %03d.%03d not found"),
                               subsys->u.usb.bus, subsys->u.usb.device);
2527
            } else {
2528 2529 2530
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("host usb device vendor=0x%.4x product=0x%.4x not found"),
                               subsys->u.usb.vendor, subsys->u.usb.product);
2531 2532 2533
            }
            break;
        default:
2534 2535
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected hostdev type %d"), subsys->type);
2536 2537 2538 2539 2540
            break;
        }
        return -1;
    }

2541 2542 2543 2544 2545 2546 2547
    /* 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);
2548 2549
}

2550
int
2551
qemuDomainDetachNetDevice(virQEMUDriverPtr driver,
2552 2553 2554
                          virDomainObjPtr vm,
                          virDomainDeviceDefPtr dev)
{
2555
    int detachidx, ret = -1;
2556 2557 2558 2559
    virDomainNetDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int vlan;
    char *hostnet_name = NULL;
2560
    char mac[VIR_MAC_STRING_BUFLEN];
2561
    virNetDevVPortProfilePtr vport = NULL;
2562
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2563

2564 2565 2566 2567 2568 2569
    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;
2570
    }
2571
    else if (detachidx < 0) {
2572
        virReportError(VIR_ERR_OPERATION_FAILED,
2573 2574
                       _("network device %s not found"),
                       virMacAddrFormat(&dev->data.net->mac, mac));
2575 2576
        goto cleanup;
    }
2577
    detach = vm->def->nets[detachidx];
2578

2579
    if (virDomainNetGetActualType(detach) == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
2580
        /* coverity[negative_returns] */
2581 2582 2583 2584 2585
        ret = qemuDomainDetachThisHostDevice(driver, vm,
                                             virDomainNetGetActualHostdev(detach),
                                             -1);
        goto cleanup;
    }
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600
    if (STREQLEN(vm->def->os.machine, "s390-ccw", 8) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_CCW)) {
        if (!virDomainDeviceAddressIsValid(&detach->info,
                                           VIR_DOMAIN_DEVICE_ADDRESS_TYPE_CCW)) {
            virReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("device cannot be detached without a CCW address"));
            goto cleanup;
        }
    } else {
        if (!virDomainDeviceAddressIsValid(&detach->info,
                                           VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
            virReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("device cannot be detached without a PCI address"));
            goto cleanup;
        }
2601

2602 2603 2604 2605 2606 2607
        if (qemuIsMultiFunctionDevice(vm->def, &detach->info)) {
            virReportError(VIR_ERR_OPERATION_FAILED,
                            _("cannot hot unplug multifunction PCI device :%s"),
                            dev->data.disk->dst);
            goto cleanup;
        }
2608 2609 2610
    }

    if ((vlan = qemuDomainNetVLAN(detach)) < 0) {
2611 2612
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("unable to determine original VLAN"));
2613 2614 2615 2616 2617 2618 2619 2620
        goto cleanup;
    }

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

2621
    qemuDomainObjEnterMonitor(driver, vm);
2622
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
2623
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
2624
            qemuDomainObjExitMonitor(driver, vm);
2625 2626 2627 2628 2629 2630
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
2631
            qemuDomainObjExitMonitor(driver, vm);
2632 2633 2634 2635 2636
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    }

2637 2638
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NETDEV) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE)) {
2639
        if (qemuMonitorRemoveNetdev(priv->mon, hostnet_name) < 0) {
2640
            qemuDomainObjExitMonitor(driver, vm);
2641 2642 2643 2644 2645
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemoveHostNetwork(priv->mon, vlan, hostnet_name) < 0) {
2646
            qemuDomainObjExitMonitor(driver, vm);
2647 2648 2649 2650
            virDomainAuditNet(vm, detach, NULL, "detach", false);
            goto cleanup;
        }
    }
2651
    qemuDomainObjExitMonitor(driver, vm);
2652 2653 2654

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

2655 2656 2657 2658 2659
    if (STREQLEN(vm->def->os.machine, "s390-ccw", 8) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VIRTIO_CCW)) {
        if (qemuDomainCCWAddressReleaseAddr(priv->ccwaddrs, &detach->info) < 0)
            VIR_WARN("Unable to release CCW address on NIC");
    } else if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DEVICE) &&
2660
        qemuDomainPCIAddressReleaseSlot(priv->pciaddrs,
2661
                                        &detach->info.addr.pci) < 0)
2662 2663 2664 2665 2666 2667
        VIR_WARN("Unable to release PCI address on NIC");

    virDomainConfNWFilterTeardown(detach);

    if (virDomainNetGetActualType(detach) == VIR_DOMAIN_NET_TYPE_DIRECT) {
        ignore_value(virNetDevMacVLanDeleteWithVPortProfile(
2668
                         detach->ifname, &detach->mac,
2669 2670 2671
                         virDomainNetGetActualDirectDev(detach),
                         virDomainNetGetActualDirectMode(detach),
                         virDomainNetGetActualVirtPortProfile(detach),
2672
                         cfg->stateDir));
2673 2674 2675
        VIR_FREE(detach->ifname);
    }

2676
    if (cfg->macFilter && (detach->ifname != NULL)) {
2677 2678
        if ((errno = networkDisallowMacOnPort(driver,
                                              detach->ifname,
2679
                                              &detach->mac))) {
2680
            virReportSystemError(errno,
2681
             _("failed to remove ebtables rule on '%s'"),
2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
                                 detach->ifname);
        }
    }

    vport = virDomainNetGetActualVirtPortProfile(detach);
    if (vport && vport->virtPortType == VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH)
        ignore_value(virNetDevOpenvswitchRemovePort(
                        virDomainNetGetActualBridgeName(detach),
                        detach->ifname));
    ret = 0;
cleanup:
2693 2694
    if (!ret) {
        networkReleaseActualDevice(detach);
2695
        virDomainNetRemove(vm->def, detachidx);
2696 2697
        virDomainNetDefFree(detach);
    }
2698
    VIR_FREE(hostnet_name);
2699
    virObjectUnref(cfg);
2700 2701 2702
    return ret;
}

2703
int
2704
qemuDomainChangeGraphicsPasswords(virQEMUDriverPtr driver,
2705 2706 2707 2708 2709 2710 2711 2712
                                  virDomainObjPtr vm,
                                  int type,
                                  virDomainGraphicsAuthDefPtr auth,
                                  const char *defaultPasswd)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    time_t now = time(NULL);
    char expire_time [64];
2713
    const char *connected = NULL;
2714 2715
    int ret = -1;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2716

2717 2718 2719 2720
    if (!auth->passwd && !cfg->vncPassword) {
        ret = 0;
        goto cleanup;
    }
2721

2722 2723 2724
    if (auth->connected)
        connected = virDomainGraphicsAuthConnectedTypeToString(auth->connected);

2725
    qemuDomainObjEnterMonitor(driver, vm);
2726 2727 2728
    ret = qemuMonitorSetPassword(priv->mon,
                                 type,
                                 auth->passwd ? auth->passwd : defaultPasswd,
2729
                                 connected);
2730 2731 2732

    if (ret == -2) {
        if (type != VIR_DOMAIN_GRAPHICS_TYPE_VNC) {
2733 2734
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Graphics password only supported for VNC"));
2735 2736 2737 2738 2739 2740
            ret = -1;
        } else {
            ret = qemuMonitorSetVNCPassword(priv->mon,
                                            auth->passwd ? auth->passwd : defaultPasswd);
        }
    }
2741
    if (ret != 0)
2742
        goto end_job;
2743

2744 2745 2746
    if (auth->expires) {
        time_t lifetime = auth->validTo - now;
        if (lifetime <= 0)
2747
            snprintf(expire_time, sizeof(expire_time), "now");
2748
        else
2749
            snprintf(expire_time, sizeof(expire_time), "%lu", (long unsigned)auth->validTo);
2750
    } else {
2751
        snprintf(expire_time, sizeof(expire_time), "never");
2752 2753 2754 2755 2756 2757 2758
    }

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

    if (ret == -2) {
        /* XXX we could fake this with a timer */
        if (auth->expires) {
2759 2760
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Expiry of passwords is not supported"));
2761
            ret = -1;
2762 2763
        } else {
            ret = 0;
2764 2765 2766
        }
    }

2767
end_job:
2768
    qemuDomainObjExitMonitor(driver, vm);
2769 2770
cleanup:
    virObjectUnref(cfg);
2771 2772
    return ret;
}
2773

2774
int qemuDomainAttachLease(virQEMUDriverPtr driver,
2775 2776 2777
                          virDomainObjPtr vm,
                          virDomainLeaseDefPtr lease)
{
2778 2779 2780
    int ret = -1;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);

2781
    if (virDomainLeaseInsertPreAlloc(vm->def) < 0)
2782
        goto cleanup;
2783

2784
    if (virDomainLockLeaseAttach(driver->lockManager, cfg->uri,
2785
                                 vm, lease) < 0) {
2786
        virDomainLeaseInsertPreAlloced(vm->def, NULL);
2787
        goto cleanup;
2788 2789 2790
    }

    virDomainLeaseInsertPreAlloced(vm->def, lease);
2791 2792 2793 2794 2795
    ret = 0;

cleanup:
    virObjectUnref(cfg);
    return ret;
2796 2797
}

2798
int qemuDomainDetachLease(virQEMUDriverPtr driver,
2799 2800 2801
                          virDomainObjPtr vm,
                          virDomainLeaseDefPtr lease)
{
2802
    virDomainLeaseDefPtr det_lease;
2803 2804 2805
    int i;

    if ((i = virDomainLeaseIndex(vm->def, lease)) < 0) {
2806 2807 2808
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Lease %s in lockspace %s does not exist"),
                       lease->key, NULLSTR(lease->lockspace));
2809 2810 2811 2812 2813 2814
        return -1;
    }

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

2815 2816
    det_lease = virDomainLeaseRemoveAt(vm->def, i);
    virDomainLeaseDefFree(det_lease);
2817 2818
    return 0;
}