qemu_driver.c 383.6 KB
Newer Older
D
Daniel P. Berrange 已提交
1
/*
2
 * qemu_driver.c: core driver methods for managing qemu guests
D
Daniel P. Berrange 已提交
3
 *
4
 * Copyright (C) 2006-2012 Red Hat, Inc.
D
Daniel P. Berrange 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * 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
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

24
#include <config.h>
25

D
Daniel P. Berrange 已提交
26 27
#include <sys/types.h>
#include <sys/poll.h>
28
#include <sys/time.h>
D
Daniel P. Berrange 已提交
29 30 31 32 33 34 35 36
#include <dirent.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
37
#include <sys/utsname.h>
38 39 40 41
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <paths.h>
42
#include <stdio.h>
43
#include <sys/wait.h>
44
#include <sys/ioctl.h>
45
#include <sys/un.h>
46
#include <byteswap.h>
D
Daniel P. Berrange 已提交
47

48

49
#include "qemu_driver.h"
50
#include "qemu_agent.h"
51
#include "qemu_conf.h"
52
#include "qemu_capabilities.h"
53
#include "qemu_command.h"
54
#include "qemu_cgroup.h"
55
#include "qemu_hostdev.h"
56
#include "qemu_hotplug.h"
57
#include "qemu_monitor.h"
58
#include "qemu_bridge_filter.h"
59
#include "qemu_process.h"
60
#include "qemu_migration.h"
61 62 63 64

#include "virterror_internal.h"
#include "logging.h"
#include "datatypes.h"
65
#include "buf.h"
66
#include "util.h"
67
#include "nodeinfo.h"
68
#include "stats_linux.h"
69
#include "capabilities.h"
70
#include "memory.h"
71
#include "uuid.h"
72
#include "domain_conf.h"
73
#include "domain_audit.h"
74 75
#include "node_device_conf.h"
#include "pci.h"
76
#include "hostusb.h"
77
#include "processinfo.h"
C
Chris Lalancette 已提交
78
#include "libvirt_internal.h"
79
#include "xml.h"
80
#include "cpu/cpu.h"
81
#include "sysinfo.h"
82
#include "domain_nwfilter.h"
83
#include "hooks.h"
84
#include "storage_file.h"
E
Eric Blake 已提交
85
#include "virfile.h"
86
#include "fdstream.h"
87
#include "configmake.h"
H
Hu Tao 已提交
88
#include "threadpool.h"
89
#include "locking/lock_manager.h"
90
#include "locking/domain_lock.h"
91
#include "virkeycode.h"
92
#include "virnodesuspend.h"
93
#include "virtime.h"
94
#include "virtypedparam.h"
95

96 97
#define VIR_FROM_THIS VIR_FROM_QEMU

98 99
#define QEMU_NB_MEM_PARAM  3

100 101
#define QEMU_NB_BLOCK_IO_TUNE_PARAM  6

102 103
#define QEMU_NB_NUMA_PARAM 2

104 105 106
#if HAVE_LINUX_KVM_H
# include <linux/kvm.h>
#endif
107

108 109
/* device for kvm ioctls */
#define KVM_DEVICE "/dev/kvm"
110

111 112 113 114 115 116 117 118 119 120 121
/* add definitions missing in older linux/kvm.h */
#ifndef KVMIO
# define KVMIO 0xAE
#endif
#ifndef KVM_CHECK_EXTENSION
# define KVM_CHECK_EXTENSION       _IO(KVMIO,   0x03)
#endif
#ifndef KVM_CAP_NR_VCPUS
# define KVM_CAP_NR_VCPUS 9       /* returns max vcpus per vm */
#endif

122
#define QEMU_NB_BLKIO_PARAM  2
123

124 125
#define QEMU_NB_BANDWIDTH_PARAM 6

H
Hu Tao 已提交
126 127
static void processWatchdogEvent(void *data, void *opaque);

128 129
static int qemudShutdown(void);

130 131 132
static int qemuDomainObjStart(virConnectPtr conn,
                              struct qemud_driver *driver,
                              virDomainObjPtr vm,
133
                              unsigned int flags);
J
Jiri Denemark 已提交
134

135
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
136

137
struct qemud_driver *qemu_driver = NULL;
138 139


140 141 142 143
struct qemuAutostartData {
    struct qemud_driver *driver;
    virConnectPtr conn;
};
144

145
static void
146 147
qemuAutostartDomain(void *payload, const void *name ATTRIBUTE_UNUSED,
                    void *opaque)
148 149 150
{
    virDomainObjPtr vm = payload;
    struct qemuAutostartData *data = opaque;
151
    virErrorPtr err;
152 153 154 155
    int flags = 0;

    if (data->driver->autoStartBypassCache)
        flags |= VIR_DOMAIN_START_BYPASS_CACHE;
156 157

    virDomainObjLock(vm);
158
    virResetLastError();
159 160 161 162 163 164 165 166 167 168 169 170
    if (vm->autostart &&
        !virDomainObjIsActive(vm)) {
        if (qemuDomainObjBeginJobWithDriver(data->driver, vm,
                                            QEMU_JOB_MODIFY) < 0) {
            err = virGetLastError();
            VIR_ERROR(_("Failed to start job on VM '%s': %s"),
                      vm->def->name,
                      err ? err->message : _("unknown error"));
            goto cleanup;
        }

        if (qemuDomainObjStart(data->conn, data->driver, vm, flags) < 0) {
171
            err = virGetLastError();
172
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
173
                      vm->def->name,
174
                      err ? err->message : _("unknown error"));
175
        }
176

177
        if (qemuDomainObjEndJob(data->driver, vm) == 0)
178
            vm = NULL;
179
    }
180

181
cleanup:
182 183
    if (vm)
        virDomainObjUnlock(vm);
184 185
}

186

187
static void
188 189
qemuAutostartDomains(struct qemud_driver *driver)
{
190 191 192 193 194
    /* XXX: Figure out a better way todo this. The domain
     * startup code needs a connection handle in order
     * to lookup the bridge associated with a virtual
     * network
     */
195 196 197
    virConnectPtr conn = virConnectOpen(driver->privileged ?
                                        "qemu:///system" :
                                        "qemu:///session");
198
    /* Ignoring NULL conn which is mostly harmless here */
199
    struct qemuAutostartData data = { driver, conn };
200

201
    qemuDriverLock(driver);
202
    virHashForEach(driver->domains.objs, qemuAutostartDomain, &data);
203
    qemuDriverUnlock(driver);
204

205 206
    if (conn)
        virConnectClose(conn);
207 208
}

209
static int
210
qemuSecurityInit(struct qemud_driver *driver)
211
{
212 213 214 215
    virSecurityManagerPtr mgr = virSecurityManagerNew(driver->securityDriverName,
                                                      driver->allowDiskFormatProbing);
    if (!mgr)
        goto error;
D
Daniel Veillard 已提交
216

217 218 219 220 221 222 223
    if (driver->privileged) {
        virSecurityManagerPtr dac = virSecurityManagerNewDAC(driver->user,
                                                             driver->group,
                                                             driver->allowDiskFormatProbing,
                                                             driver->dynamicOwnership);
        if (!dac)
            goto error;
224

225
        if (!(driver->securityManager = virSecurityManagerNewStack(mgr,
E
Eric Blake 已提交
226 227 228
                                                                   dac))) {

            virSecurityManagerFree(dac);
229
            goto error;
E
Eric Blake 已提交
230
        }
231 232 233
    } else {
        driver->securityManager = mgr;
    }
D
Daniel Veillard 已提交
234

235
    return 0;
236

237
error:
238
    VIR_ERROR(_("Failed to initialize security drivers"));
239 240 241
    virSecurityManagerFree(mgr);
    return -1;
}
242

243

244 245 246 247 248
static virCapsPtr
qemuCreateCapabilities(virCapsPtr oldcaps,
                       struct qemud_driver *driver)
{
    virCapsPtr caps;
249

250 251 252 253
    /* Basic host arch / guest machine capabilities */
    if (!(caps = qemuCapsInit(oldcaps))) {
        virReportOOMError();
        return NULL;
254 255
    }

256 257 258 259 260 261
    if (driver->allowDiskFormatProbing) {
        caps->defaultDiskDriverName = NULL;
        caps->defaultDiskDriverType = NULL;
    } else {
        caps->defaultDiskDriverName = "qemu";
        caps->defaultDiskDriverType = "raw";
262 263
    }

264 265
    qemuDomainSetPrivateDataHooks(caps);
    qemuDomainSetNamespaceHooks(caps);
266

267 268 269 270
    if (virGetHostUUID(caps->host.host_uuid)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot get the host uuid"));
        goto err_exit;
271
    }
272

273 274
    /* Security driver data */
    const char *doi, *model;
275

276 277 278 279 280 281 282
    doi = virSecurityManagerGetDOI(driver->securityManager);
    model = virSecurityManagerGetModel(driver->securityManager);
    if (STRNEQ(model, "none")) {
        if (!(caps->host.secModel.model = strdup(model)))
            goto no_memory;
        if (!(caps->host.secModel.doi = strdup(doi)))
            goto no_memory;
283
    }
284

285 286
    VIR_DEBUG("Initialized caps for security driver \"%s\" with "
              "DOI \"%s\"", model, doi);
287

288
    return caps;
289

290 291 292 293
no_memory:
    virReportOOMError();
err_exit:
    virCapabilitiesFree(caps);
294 295 296
    return NULL;
}

297
static void qemuDomainSnapshotLoad(void *payload,
298
                                   const void *name ATTRIBUTE_UNUSED,
299
                                   void *data)
300
{
301 302 303 304 305 306 307 308 309
    virDomainObjPtr vm = (virDomainObjPtr)payload;
    char *baseDir = (char *)data;
    char *snapDir = NULL;
    DIR *dir = NULL;
    struct dirent *entry;
    char *xmlStr;
    int ret;
    char *fullpath;
    virDomainSnapshotDefPtr def = NULL;
310
    virDomainSnapshotObjPtr snap = NULL;
311
    virDomainSnapshotObjPtr current = NULL;
312
    char ebuf[1024];
313
    unsigned int flags = (VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE |
314
                          VIR_DOMAIN_SNAPSHOT_PARSE_DISKS |
315
                          VIR_DOMAIN_SNAPSHOT_PARSE_INTERNAL);
316

317 318 319 320
    virDomainObjLock(vm);
    if (virAsprintf(&snapDir, "%s/%s", baseDir, vm->def->name) < 0) {
        VIR_ERROR(_("Failed to allocate memory for snapshot directory for domain %s"),
                   vm->def->name);
321
        goto cleanup;
322 323
    }

324 325
    VIR_INFO("Scanning for snapshots for domain %s in %s", vm->def->name,
             snapDir);
326

327 328 329 330 331
    if (!(dir = opendir(snapDir))) {
        if (errno != ENOENT)
            VIR_ERROR(_("Failed to open snapshot directory %s for domain %s: %s"),
                      snapDir, vm->def->name,
                      virStrerror(errno, ebuf, sizeof(ebuf)));
332
        goto cleanup;
333 334
    }

335 336 337
    while ((entry = readdir(dir))) {
        if (entry->d_name[0] == '.')
            continue;
338

339 340 341
        /* NB: ignoring errors, so one malformed config doesn't
           kill the whole process */
        VIR_INFO("Loading snapshot file '%s'", entry->d_name);
342

343
        if (virAsprintf(&fullpath, "%s/%s", snapDir, entry->d_name) < 0) {
344
            VIR_ERROR(_("Failed to allocate memory for path"));
345 346
            continue;
        }
347

348 349 350 351 352 353 354 355
        ret = virFileReadAll(fullpath, 1024*1024*1, &xmlStr);
        if (ret < 0) {
            /* Nothing we can do here, skip this one */
            VIR_ERROR(_("Failed to read snapshot file %s: %s"), fullpath,
                      virStrerror(errno, ebuf, sizeof(ebuf)));
            VIR_FREE(fullpath);
            continue;
        }
356

357 358 359
        def = virDomainSnapshotDefParseString(xmlStr, qemu_driver->caps,
                                              QEMU_EXPECTED_VIRT_TYPES,
                                              flags);
360 361
        if (def == NULL) {
            /* Nothing we can do here, skip this one */
362 363
            VIR_ERROR(_("Failed to parse snapshot XML from file '%s'"),
                      fullpath);
364 365 366 367
            VIR_FREE(fullpath);
            VIR_FREE(xmlStr);
            continue;
        }
368

369 370 371
        snap = virDomainSnapshotAssignDef(&vm->snapshots, def);
        if (snap == NULL) {
            virDomainSnapshotDefFree(def);
372 373 374 375
        } else if (snap->def->current) {
            current = snap;
            if (!vm->current_snapshot)
                vm->current_snapshot = snap;
376
        }
377

378 379
        VIR_FREE(fullpath);
        VIR_FREE(xmlStr);
380 381
    }

382 383 384 385 386 387
    if (vm->current_snapshot != current) {
        VIR_ERROR(_("Too many snapshots claiming to be current for domain %s"),
                  vm->def->name);
        vm->current_snapshot = NULL;
    }

388 389 390 391
    if (virDomainSnapshotUpdateRelations(&vm->snapshots) < 0)
        VIR_ERROR(_("Snapshots have inconsistent relations for domain %s"),
                  vm->def->name);

392 393 394 395 396 397 398 399
    /* FIXME: qemu keeps internal track of snapshots.  We can get access
     * to this info via the "info snapshots" monitor command for running
     * domains, or via "qemu-img snapshot -l" for shutoff domains.  It would
     * be nice to update our internal state based on that, but there is a
     * a problem.  qemu doesn't track all of the same metadata that we do.
     * In particular we wouldn't be able to fill in the <parent>, which is
     * pretty important in our metadata.
     */
400

401
    virResetLastError();
402

403 404 405 406
cleanup:
    if (dir)
        closedir(dir);
    VIR_FREE(snapDir);
407 408 409
    virDomainObjUnlock(vm);
}

410 411 412 413 414
/**
 * qemudStartup:
 *
 * Initialization function for the QEmu daemon
 */
415
static int
416 417 418 419 420
qemudStartup(int privileged) {
    char *base = NULL;
    char *driverConf = NULL;
    int rc;
    virConnectPtr conn = NULL;
421

422 423
    if (VIR_ALLOC(qemu_driver) < 0)
        return -1;
424

425
    if (virMutexInit(&qemu_driver->lock) < 0) {
426
        VIR_ERROR(_("cannot initialize mutex"));
427 428
        VIR_FREE(qemu_driver);
        return -1;
429
    }
430 431
    qemuDriverLock(qemu_driver);
    qemu_driver->privileged = privileged;
432

433 434
    /* Don't have a dom0 so start from 1 */
    qemu_driver->nextvmid = 1;
435

436 437
    if (virDomainObjListInit(&qemu_driver->domains) < 0)
        goto out_of_memory;
438

439
    /* Init domain events */
440
    qemu_driver->domainEventState = virDomainEventStateNew();
441
    if (!qemu_driver->domainEventState)
442
        goto error;
443

444 445 446 447
    /* Allocate bitmap for vnc port reservation */
    if ((qemu_driver->reservedVNCPorts =
         virBitmapAlloc(QEMU_VNC_PORT_MAX - QEMU_VNC_PORT_MIN)) == NULL)
        goto out_of_memory;
448

449 450 451
    /* read the host sysinfo */
    if (privileged)
        qemu_driver->hostsysinfo = virSysinfoRead();
452

453 454 455 456
    if (privileged) {
        if (virAsprintf(&qemu_driver->logDir,
                        "%s/log/libvirt/qemu", LOCALSTATEDIR) == -1)
            goto out_of_memory;
457

458 459
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
            goto out_of_memory;
460

461 462 463
        if (virAsprintf(&qemu_driver->stateDir,
                      "%s/run/libvirt/qemu", LOCALSTATEDIR) == -1)
            goto out_of_memory;
464

465 466 467
        if (virAsprintf(&qemu_driver->libDir,
                      "%s/lib/libvirt/qemu", LOCALSTATEDIR) == -1)
            goto out_of_memory;
468

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
        if (virAsprintf(&qemu_driver->cacheDir,
                      "%s/cache/libvirt/qemu", LOCALSTATEDIR) == -1)
            goto out_of_memory;
        if (virAsprintf(&qemu_driver->saveDir,
                      "%s/lib/libvirt/qemu/save", LOCALSTATEDIR) == -1)
            goto out_of_memory;
        if (virAsprintf(&qemu_driver->snapshotDir,
                        "%s/lib/libvirt/qemu/snapshot", LOCALSTATEDIR) == -1)
            goto out_of_memory;
        if (virAsprintf(&qemu_driver->autoDumpPath,
                        "%s/lib/libvirt/qemu/dump", LOCALSTATEDIR) == -1)
            goto out_of_memory;
    } else {
        uid_t uid = geteuid();
        char *userdir = virGetUserDirectory(uid);
        if (!userdir)
            goto error;
486

487 488 489 490 491
        if (virAsprintf(&qemu_driver->logDir,
                        "%s/.libvirt/qemu/log", userdir) == -1) {
            VIR_FREE(userdir);
            goto out_of_memory;
        }
492

493 494 495 496 497
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1) {
            VIR_FREE(userdir);
            goto out_of_memory;
        }
        VIR_FREE(userdir);
498

499 500 501 502 503 504 505 506 507 508 509 510
        if (virAsprintf(&qemu_driver->stateDir, "%s/qemu/run", base) == -1)
            goto out_of_memory;
        if (virAsprintf(&qemu_driver->libDir, "%s/qemu/lib", base) == -1)
            goto out_of_memory;
        if (virAsprintf(&qemu_driver->cacheDir, "%s/qemu/cache", base) == -1)
            goto out_of_memory;
        if (virAsprintf(&qemu_driver->saveDir, "%s/qemu/save", base) == -1)
            goto out_of_memory;
        if (virAsprintf(&qemu_driver->snapshotDir, "%s/qemu/snapshot", base) == -1)
            goto out_of_memory;
        if (virAsprintf(&qemu_driver->autoDumpPath, "%s/qemu/dump", base) == -1)
            goto out_of_memory;
511
    }
H
Hu Tao 已提交
512

513
    if (virFileMakePath(qemu_driver->stateDir) < 0) {
514 515 516 517
        char ebuf[1024];
        VIR_ERROR(_("Failed to create state dir '%s': %s"),
                  qemu_driver->stateDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
H
Hu Tao 已提交
518
    }
519
    if (virFileMakePath(qemu_driver->libDir) < 0) {
520 521 522 523 524
        char ebuf[1024];
        VIR_ERROR(_("Failed to create lib dir '%s': %s"),
                  qemu_driver->libDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
525
    if (virFileMakePath(qemu_driver->cacheDir) < 0) {
526 527 528 529 530
        char ebuf[1024];
        VIR_ERROR(_("Failed to create cache dir '%s': %s"),
                  qemu_driver->cacheDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
531
    if (virFileMakePath(qemu_driver->saveDir) < 0) {
532 533 534 535 536
        char ebuf[1024];
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
                  qemu_driver->saveDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
537
    if (virFileMakePath(qemu_driver->snapshotDir) < 0) {
538 539 540 541 542
        char ebuf[1024];
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
                  qemu_driver->snapshotDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
543
    if (virFileMakePath(qemu_driver->autoDumpPath) < 0) {
544 545 546 547
        char ebuf[1024];
        VIR_ERROR(_("Failed to create dump dir '%s': %s"),
                  qemu_driver->autoDumpPath, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
548 549
    }

550 551 552 553 554 555 556
    /* Configuration paths are either ~/.libvirt/qemu/... (session) or
     * /etc/libvirt/qemu/... (system).
     */
    if (virAsprintf(&driverConf, "%s/qemu.conf", base) < 0 ||
        virAsprintf(&qemu_driver->configDir, "%s/qemu", base) < 0 ||
        virAsprintf(&qemu_driver->autostartDir, "%s/qemu/autostart", base) < 0)
        goto out_of_memory;
557

558
    VIR_FREE(base);
559

560 561 562 563 564
    rc = virCgroupForDriver("qemu", &qemu_driver->cgroup, privileged, 1);
    if (rc < 0) {
        char buf[1024];
        VIR_INFO("Unable to create cgroup for driver: %s",
                 virStrerror(-rc, buf, sizeof(buf)));
565 566
    }

567 568 569 570
    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
        goto error;
    }
    VIR_FREE(driverConf);
571

572 573 574 575 576 577 578 579
    /* We should always at least have the 'nop' manager, so
     * NULLs here are a fatal error
     */
    if (!qemu_driver->lockManager) {
        VIR_ERROR(_("Missing lock manager implementation"));
        goto error;
    }

580 581
    if (qemuSecurityInit(qemu_driver) < 0)
        goto error;
582

583 584 585
    if ((qemu_driver->caps = qemuCreateCapabilities(NULL,
                                                    qemu_driver)) == NULL)
        goto error;
586

587
    if ((qemu_driver->activePciHostdevs = pciDeviceListNew()) == NULL)
588
        goto error;
589

590 591 592
    if ((qemu_driver->activeUsbHostdevs = usbDeviceListNew()) == NULL)
        goto error;

593 594 595
    if ((qemu_driver->inactivePciHostdevs = pciDeviceListNew()) == NULL)
        goto error;

596 597 598 599 600 601
    if (privileged) {
        if (chown(qemu_driver->libDir, qemu_driver->user, qemu_driver->group) < 0) {
            virReportSystemError(errno,
                                 _("unable to set ownership of '%s' to user %d:%d"),
                                 qemu_driver->libDir, qemu_driver->user, qemu_driver->group);
            goto error;
602
        }
603
        if (chown(qemu_driver->cacheDir, qemu_driver->user, qemu_driver->group) < 0) {
604
            virReportSystemError(errno,
605 606 607
                                 _("unable to set ownership of '%s' to %d:%d"),
                                 qemu_driver->cacheDir, qemu_driver->user, qemu_driver->group);
            goto error;
608
        }
609 610 611 612 613 614 615 616 617 618 619
        if (chown(qemu_driver->saveDir, qemu_driver->user, qemu_driver->group) < 0) {
            virReportSystemError(errno,
                                 _("unable to set ownership of '%s' to %d:%d"),
                                 qemu_driver->saveDir, qemu_driver->user, qemu_driver->group);
            goto error;
        }
        if (chown(qemu_driver->snapshotDir, qemu_driver->user, qemu_driver->group) < 0) {
            virReportSystemError(errno,
                                 _("unable to set ownership of '%s' to %d:%d"),
                                 qemu_driver->snapshotDir, qemu_driver->user, qemu_driver->group);
            goto error;
620
        }
621
    }
622

623 624 625 626 627 628
    /* If hugetlbfs is present, then we need to create a sub-directory within
     * it, since we can't assume the root mount point has permissions that
     * will let our spawned QEMU instances use it.
     *
     * NB the check for '/', since user may config "" to disable hugepages
     * even when mounted
629
     */
630 631 632 633 634
    if (qemu_driver->hugetlbfs_mount &&
        qemu_driver->hugetlbfs_mount[0] == '/') {
        char *mempath = NULL;
        if (virAsprintf(&mempath, "%s/libvirt/qemu", qemu_driver->hugetlbfs_mount) < 0)
            goto out_of_memory;
635

636 637
        if (virFileMakePath(mempath) < 0) {
            virReportSystemError(errno,
638 639 640
                                 _("unable to create hugepage path %s"), mempath);
            VIR_FREE(mempath);
            goto error;
641
        }
642 643 644 645 646 647 648
        if (qemu_driver->privileged &&
            chown(mempath, qemu_driver->user, qemu_driver->group) < 0) {
            virReportSystemError(errno,
                                 _("unable to set ownership on %s to %d:%d"),
                                 mempath, qemu_driver->user, qemu_driver->group);
            VIR_FREE(mempath);
            goto error;
G
Guido Günther 已提交
649
        }
E
Eric Blake 已提交
650

651
        qemu_driver->hugepage_path = mempath;
652
    }
653

654 655 656
    if (qemuProcessAutoDestroyInit(qemu_driver) < 0)
        goto error;

657 658 659 660 661
    /* Get all the running persistent or transient configs first */
    if (virDomainLoadAllConfigs(qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->stateDir,
                                NULL,
M
Matthias Bolte 已提交
662 663
                                1, QEMU_EXPECTED_VIRT_TYPES,
                                NULL, NULL) < 0)
664
        goto error;
665

666 667 668
    conn = virConnectOpen(qemu_driver->privileged ?
                          "qemu:///system" :
                          "qemu:///session");
669

670
    qemuProcessReconnectAll(conn, qemu_driver);
671

672 673 674 675 676
    /* Then inactive persistent configs */
    if (virDomainLoadAllConfigs(qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->configDir,
                                qemu_driver->autostartDir,
M
Matthias Bolte 已提交
677 678
                                0, QEMU_EXPECTED_VIRT_TYPES,
                                NULL, NULL) < 0)
679
        goto error;
680

681

682 683
    virHashForEach(qemu_driver->domains.objs, qemuDomainSnapshotLoad,
                   qemu_driver->snapshotDir);
684

685
    qemu_driver->workerPool = virThreadPoolNew(0, 1, 0, processWatchdogEvent, qemu_driver);
686 687
    if (!qemu_driver->workerPool)
        goto error;
688

689 690 691 692
    qemuDriverUnlock(qemu_driver);

    qemuAutostartDomains(qemu_driver);

693 694
    if (conn)
        virConnectClose(conn);
695

696
    return 0;
697

698 699 700 701 702 703 704 705 706 707
out_of_memory:
    virReportOOMError();
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
    if (conn)
        virConnectClose(conn);
    VIR_FREE(base);
    VIR_FREE(driverConf);
    qemudShutdown();
708
    return -1;
709 710
}

711 712 713
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;
714

715 716 717 718 719 720 721
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
E
Eric Blake 已提交
722
    }
723
}
E
Eric Blake 已提交
724

725 726 727 728 729 730 731 732 733 734
/**
 * qemudReload:
 *
 * Function to restart the QEmu daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
qemudReload(void) {
    if (!qemu_driver)
        return 0;
735

736 737 738 739 740
    qemuDriverLock(qemu_driver);
    virDomainLoadAllConfigs(qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
                            qemu_driver->autostartDir,
M
Matthias Bolte 已提交
741 742
                            0, QEMU_EXPECTED_VIRT_TYPES,
                            qemudNotifyLoadDomain, qemu_driver);
743
    qemuDriverUnlock(qemu_driver);
744

745
    qemuAutostartDomains(qemu_driver);
746

747 748
    return 0;
}
S
Stefan Berger 已提交
749

750 751 752 753 754 755 756 757 758 759 760
/**
 * qemudActive:
 *
 * Checks if the QEmu daemon is active, i.e. has an active domain or
 * an active network
 *
 * Returns 1 if active, 0 otherwise
 */
static int
qemudActive(void) {
    int active = 0;
761

762 763
    if (!qemu_driver)
        return 0;
764

765 766 767 768 769 770
    /* XXX having to iterate here is not great because it requires many locks */
    qemuDriverLock(qemu_driver);
    active = virDomainObjListNumOfDomains(&qemu_driver->domains, 1);
    qemuDriverUnlock(qemu_driver);
    return active;
}
771

772 773 774 775 776 777 778 779
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
    int i;
780

781 782
    if (!qemu_driver)
        return -1;
783

784 785
    qemuDriverLock(qemu_driver);
    pciDeviceListFree(qemu_driver->activePciHostdevs);
786
    pciDeviceListFree(qemu_driver->inactivePciHostdevs);
787
    usbDeviceListFree(qemu_driver->activeUsbHostdevs);
788
    virCapabilitiesFree(qemu_driver->caps);
789

790 791
    virDomainObjListDeinit(&qemu_driver->domains);
    virBitmapFree(qemu_driver->reservedVNCPorts);
792

793
    virSysinfoDefFree(qemu_driver->hostsysinfo);
794

795 796
    qemuProcessAutoDestroyShutdown(qemu_driver);

797 798 799 800 801 802 803 804
    VIR_FREE(qemu_driver->configDir);
    VIR_FREE(qemu_driver->autostartDir);
    VIR_FREE(qemu_driver->logDir);
    VIR_FREE(qemu_driver->stateDir);
    VIR_FREE(qemu_driver->libDir);
    VIR_FREE(qemu_driver->cacheDir);
    VIR_FREE(qemu_driver->saveDir);
    VIR_FREE(qemu_driver->snapshotDir);
E
Eric Blake 已提交
805
    VIR_FREE(qemu_driver->qemuImgBinary);
806 807 808 809 810 811 812 813 814 815 816 817
    VIR_FREE(qemu_driver->autoDumpPath);
    VIR_FREE(qemu_driver->vncTLSx509certdir);
    VIR_FREE(qemu_driver->vncListen);
    VIR_FREE(qemu_driver->vncPassword);
    VIR_FREE(qemu_driver->vncSASLdir);
    VIR_FREE(qemu_driver->spiceTLSx509certdir);
    VIR_FREE(qemu_driver->spiceListen);
    VIR_FREE(qemu_driver->spicePassword);
    VIR_FREE(qemu_driver->hugetlbfs_mount);
    VIR_FREE(qemu_driver->hugepage_path);
    VIR_FREE(qemu_driver->saveImageFormat);
    VIR_FREE(qemu_driver->dumpImageFormat);
818

819
    virSecurityManagerFree(qemu_driver->securityManager);
820

821
    ebtablesContextFree(qemu_driver->ebtables);
822

823 824 825 826
    if (qemu_driver->cgroupDeviceACL) {
        for (i = 0 ; qemu_driver->cgroupDeviceACL[i] != NULL ; i++)
            VIR_FREE(qemu_driver->cgroupDeviceACL[i]);
        VIR_FREE(qemu_driver->cgroupDeviceACL);
S
Stefan Berger 已提交
827 828
    }

829
    /* Free domain callback list */
830
    virDomainEventStateFree(qemu_driver->domainEventState);
D
Daniel P. Berrange 已提交
831

832
    virCgroupFree(&qemu_driver->cgroup);
833

834 835
    virLockManagerPluginUnref(qemu_driver->lockManager);

836 837 838 839
    qemuDriverUnlock(qemu_driver);
    virMutexDestroy(&qemu_driver->lock);
    virThreadPoolFree(qemu_driver->workerPool);
    VIR_FREE(qemu_driver);
840

841
    return 0;
842 843
}

844

845
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
846
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
847
                                  unsigned int flags)
848
{
E
Eric Blake 已提交
849 850
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

851
    if (conn->uri == NULL) {
852 853 854
        if (qemu_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

855
        conn->uri = xmlParseURI(qemu_driver->privileged ?
856 857
                                "qemu:///system" :
                                "qemu:///session");
858
        if (!conn->uri) {
859
            virReportOOMError();
860 861
            return VIR_DRV_OPEN_ERROR;
        }
862 863 864 865 866 867 868 869 870 871
    } else {
        /* If URI isn't 'qemu' its definitely not for us */
        if (conn->uri->scheme == NULL ||
            STRNEQ(conn->uri->scheme, "qemu"))
            return VIR_DRV_OPEN_DECLINED;

        /* Allow remote driver to deal with URIs with hostname server */
        if (conn->uri->server != NULL)
            return VIR_DRV_OPEN_DECLINED;

872
        if (qemu_driver == NULL) {
873 874
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("qemu state driver is not active"));
875 876 877
            return VIR_DRV_OPEN_ERROR;
        }

878
        if (conn->uri->path == NULL) {
879 880 881 882 883
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("no QEMU URI path given, try %s"),
                            qemu_driver->privileged
                            ? "qemu:///system"
                            : "qemu:///session");
884 885 886
                return VIR_DRV_OPEN_ERROR;
        }

887
        if (qemu_driver->privileged) {
888 889
            if (STRNEQ (conn->uri->path, "/system") &&
                STRNEQ (conn->uri->path, "/session")) {
890 891 892
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("unexpected QEMU URI path '%s', try qemu:///system"),
                                conn->uri->path);
893 894 895 896
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
897 898 899
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("unexpected QEMU URI path '%s', try qemu:///session"),
                                conn->uri->path);
900 901 902
                return VIR_DRV_OPEN_ERROR;
            }
        }
903 904 905 906 907 908 909
    }
    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int qemudClose(virConnectPtr conn) {
910
    struct qemud_driver *driver = conn->privateData;
911 912

    /* Get rid of callbacks registered for this conn */
913
    qemuDriverLock(driver);
914 915
    virDomainEventStateDeregisterConn(conn,
                                      driver->domainEventState);
916
    qemuProcessAutoDestroyRun(driver, conn);
917
    qemuDriverUnlock(driver);
918 919 920 921 922 923

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
924 925 926 927 928
/* Which features are supported by this driver? */
static int
qemudSupportsFeature (virConnectPtr conn ATTRIBUTE_UNUSED, int feature)
{
    switch (feature) {
929
    case VIR_DRV_FEATURE_MIGRATION_V2:
930
    case VIR_DRV_FEATURE_MIGRATION_V3:
931
    case VIR_DRV_FEATURE_MIGRATION_P2P:
932
    case VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION:
933
    case VIR_DRV_FEATURE_FD_PASSING:
934
    case VIR_DRV_FEATURE_TYPED_PARAM_STRING:
935 936 937
        return 1;
    default:
        return 0;
D
Daniel Veillard 已提交
938 939 940
    }
}

941
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
942
    return "QEMU";
943 944
}

945

946 947 948 949 950 951 952 953 954 955 956 957
static int qemuIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Trivially secure, since always inside the daemon */
    return 1;
}

static int qemuIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Not encrypted, but remote driver takes care of that */
    return 0;
}

958 959 960 961 962
static int qemuIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    return 1;
}

963

964 965 966 967
static int kvmGetMaxVCPUs(void) {
    int maxvcpus = 1;

    int r, fd;
968

969 970
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
971
        virReportSystemError(errno, _("Unable to open %s"), KVM_DEVICE);
972
        return -1;
973 974 975 976 977 978
    }

    r = ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_NR_VCPUS);
    if (r > 0)
        maxvcpus = r;

979
    VIR_FORCE_CLOSE(fd);
980 981 982 983
    return maxvcpus;
}


E
Eric Blake 已提交
984 985 986 987
static char *
qemuGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    struct qemud_driver *driver = conn->privateData;
988
    virBuffer buf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
989 990 991 992 993 994 995 996 997

    virCheckFlags(0, NULL);

    if (!driver->hostsysinfo) {
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("Host SMBIOS information is not available"));
        return NULL;
    }

998 999 1000 1001 1002 1003 1004
    if (virSysinfoFormat(&buf, driver->hostsysinfo) < 0)
        return NULL;
    if (virBufferError(&buf)) {
        virReportOOMError();
        return NULL;
    }
    return virBufferContentAndReset(&buf);
E
Eric Blake 已提交
1005 1006
}

1007
static int qemudGetMaxVCPUs(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
1008 1009 1010
    if (!type)
        return 16;

1011
    if (STRCASEEQ(type, "qemu"))
1012 1013
        return 16;

1014
    if (STRCASEEQ(type, "kvm"))
1015
        return kvmGetMaxVCPUs();
1016

1017
    if (STRCASEEQ(type, "kqemu"))
1018
        return 1;
1019

1020 1021
    qemuReportError(VIR_ERR_INVALID_ARG,
                    _("unknown type '%s'"), type);
1022 1023 1024
    return -1;
}

1025

1026
static char *qemudGetCapabilities(virConnectPtr conn) {
1027
    struct qemud_driver *driver = conn->privateData;
1028
    virCapsPtr caps = NULL;
1029
    char *xml = NULL;
1030

1031
    qemuDriverLock(driver);
1032

1033
    if ((caps = qemuCreateCapabilities(qemu_driver->caps,
1034
                                       qemu_driver)) == NULL) {
1035 1036 1037
        virCapabilitiesFree(caps);
        goto cleanup;
    }
1038

1039
    virCapabilitiesFree(qemu_driver->caps);
1040 1041 1042
    qemu_driver->caps = caps;

    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1043
        virReportOOMError();
1044 1045

cleanup:
1046
    qemuDriverUnlock(driver);
1047

1048
    return xml;
1049 1050 1051
}


1052 1053 1054 1055 1056
static int
qemudGetProcessInfo(unsigned long long *cpuTime, int *lastCpu, int pid,
                    int tid)
{
    char *proc;
D
Daniel P. Berrange 已提交
1057
    FILE *pidinfo;
1058
    unsigned long long usertime, systime;
1059 1060
    int cpu;
    int ret;
D
Daniel P. Berrange 已提交
1061

1062
    if (tid)
1063
        ret = virAsprintf(&proc, "/proc/%d/task/%d/stat", pid, tid);
1064
    else
1065 1066
        ret = virAsprintf(&proc, "/proc/%d/stat", pid);
    if (ret < 0)
D
Daniel P. Berrange 已提交
1067 1068 1069 1070
        return -1;

    if (!(pidinfo = fopen(proc, "r"))) {
        /* VM probably shut down, so fake 0 */
1071 1072 1073 1074
        if (cpuTime)
            *cpuTime = 0;
        if (lastCpu)
            *lastCpu = 0;
1075
        VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1076 1077
        return 0;
    }
1078
    VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1079

1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
    /* See 'man proc' for information about what all these fields are. We're
     * only interested in a very few of them */
    if (fscanf(pidinfo,
               /* pid -> stime */
               "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu"
               /* cutime -> endcode */
               "%*d %*d %*d %*d %*d %*u %*u %*d %*u %*u %*u %*u"
               /* startstack -> processor */
               "%*u %*u %*u %*u %*u %*u %*u %*u %*u %*u %*d %d",
               &usertime, &systime, &cpu) != 3) {
1090
        VIR_FORCE_FCLOSE(pidinfo);
1091
        VIR_WARN("cannot parse process status data");
1092
        errno = -EINVAL;
D
Daniel P. Berrange 已提交
1093 1094 1095 1096 1097 1098 1099 1100
        return -1;
    }

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
1101 1102 1103 1104 1105
    if (cpuTime)
        *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
    if (lastCpu)
        *lastCpu = cpu;

D
Daniel P. Berrange 已提交
1106

1107 1108
    VIR_DEBUG("Got status for %d/%d user=%llu sys=%llu cpu=%d",
              pid, tid, usertime, systime, cpu);
D
Daniel P. Berrange 已提交
1109

1110
    VIR_FORCE_FCLOSE(pidinfo);
D
Daniel P. Berrange 已提交
1111 1112 1113 1114 1115

    return 0;
}


1116
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1117
                                          int id) {
1118 1119 1120 1121
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1122
    qemuDriverLock(driver);
1123
    vm  = virDomainFindByID(&driver->domains, id);
1124
    qemuDriverUnlock(driver);
1125 1126

    if (!vm) {
1127 1128
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching id %d"), id);
1129
        goto cleanup;
1130 1131
    }

1132
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1133
    if (dom) dom->id = vm->def->id;
1134 1135

cleanup:
1136 1137
    if (vm)
        virDomainObjUnlock(vm);
1138 1139
    return dom;
}
1140

1141
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1142
                                            const unsigned char *uuid) {
1143 1144 1145
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1146

1147
    qemuDriverLock(driver);
1148
    vm = virDomainFindByUUID(&driver->domains, uuid);
1149 1150
    qemuDriverUnlock(driver);

1151
    if (!vm) {
1152 1153
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
1154 1155
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1156
        goto cleanup;
1157 1158
    }

1159
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1160
    if (dom) dom->id = vm->def->id;
1161 1162

cleanup:
1163 1164
    if (vm)
        virDomainObjUnlock(vm);
1165 1166
    return dom;
}
1167

1168
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1169
                                            const char *name) {
1170 1171 1172
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1173

1174
    qemuDriverLock(driver);
1175
    vm = virDomainFindByName(&driver->domains, name);
1176 1177
    qemuDriverUnlock(driver);

1178
    if (!vm) {
1179 1180
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), name);
1181
        goto cleanup;
1182 1183
    }

1184
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1185
    if (dom) dom->id = vm->def->id;
1186 1187

cleanup:
1188 1189
    if (vm)
        virDomainObjUnlock(vm);
1190 1191 1192
    return dom;
}

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203

static int qemuDomainIsActive(virDomainPtr dom)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    qemuDriverLock(driver);
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);
    if (!obj) {
E
Eric Blake 已提交
1204 1205 1206 1207
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
        goto cleanup;
    }
    ret = virDomainObjIsActive(obj);

cleanup:
    if (obj)
        virDomainObjUnlock(obj);
    return ret;
}

static int qemuDomainIsPersistent(virDomainPtr dom)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    qemuDriverLock(driver);
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);
    if (!obj) {
E
Eric Blake 已提交
1228 1229 1230 1231
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
        goto cleanup;
    }
    ret = obj->persistent;

cleanup:
    if (obj)
        virDomainObjUnlock(obj);
    return ret;
}

1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
static int qemuDomainIsUpdated(virDomainPtr dom)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    qemuDriverLock(driver);
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);
    if (!obj) {
E
Eric Blake 已提交
1252 1253 1254 1255
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1256 1257 1258 1259 1260 1261 1262 1263 1264
        goto cleanup;
    }
    ret = obj->updated;

cleanup:
    if (obj)
        virDomainObjUnlock(obj);
    return ret;
}
1265

1266
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1267 1268 1269
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

1270
    qemuDriverLock(driver);
1271
    if (qemuCapsExtractVersion(driver->caps, &driver->qemuVersion) < 0)
1272
        goto cleanup;
1273

1274
    *version = driver->qemuVersion;
1275 1276 1277
    ret = 0;

cleanup:
1278
    qemuDriverUnlock(driver);
1279
    return ret;
D
Daniel P. Berrange 已提交
1280 1281
}

1282
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1283
    struct qemud_driver *driver = conn->privateData;
1284
    int n;
1285

1286
    qemuDriverLock(driver);
1287
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1288
    qemuDriverUnlock(driver);
1289

1290
    return n;
D
Daniel P. Berrange 已提交
1291
}
1292

1293
static int qemudNumDomains(virConnectPtr conn) {
1294
    struct qemud_driver *driver = conn->privateData;
1295
    int n;
1296

1297
    qemuDriverLock(driver);
1298
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1299
    qemuDriverUnlock(driver);
1300

1301
    return n;
D
Daniel P. Berrange 已提交
1302
}
1303

1304
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
1305
                                      unsigned int flags) {
1306
    struct qemud_driver *driver = conn->privateData;
1307
    virDomainDefPtr def;
1308
    virDomainObjPtr vm = NULL;
1309
    virDomainPtr dom = NULL;
1310
    virDomainEventPtr event = NULL;
1311
    virDomainEventPtr event2 = NULL;
D
Daniel P. Berrange 已提交
1312

1313 1314
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
                  VIR_DOMAIN_START_AUTODESTROY, NULL);
1315

1316
    qemuDriverLock(driver);
1317
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1318
                                        QEMU_EXPECTED_VIRT_TYPES,
1319
                                        VIR_DOMAIN_XML_INACTIVE)))
1320
        goto cleanup;
1321

1322
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
1323 1324
        goto cleanup;

1325 1326
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
        goto cleanup;
1327

1328 1329 1330
    if (qemudCanonicalizeMachine(driver, def) < 0)
        goto cleanup;

1331
    if (qemuDomainAssignAddresses(def) < 0)
1332 1333
        goto cleanup;

1334
    if (!(vm = virDomainAssignDef(driver->caps,
1335
                                  &driver->domains,
1336
                                  def, false)))
1337 1338 1339
        goto cleanup;

    def = NULL;
D
Daniel P. Berrange 已提交
1340

1341
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
1342 1343
        goto cleanup; /* XXXX free the 'vm' we created ? */

1344 1345
    if (qemuProcessStart(conn, driver, vm, NULL,
                         (flags & VIR_DOMAIN_START_PAUSED) != 0,
1346
                         (flags & VIR_DOMAIN_START_AUTODESTROY) != 0,
1347
                         -1, NULL, NULL, VIR_NETDEV_VPORT_PROFILE_OP_CREATE) < 0) {
1348
        virDomainAuditStart(vm, "booted", false);
1349
        if (qemuDomainObjEndJob(driver, vm) > 0)
1350
            qemuDomainRemoveInactive(driver, vm);
1351
        vm = NULL;
1352
        goto cleanup;
D
Daniel P. Berrange 已提交
1353
    }
1354 1355 1356 1357

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
    if (event && (flags & VIR_DOMAIN_START_PAUSED)) {
        /* There are two classes of event-watching clients - those
         * that only care about on/off (and must see a started event
         * no matter what, but don't care about suspend events), and
         * those that also care about running/paused.  To satisfy both
         * client types, we have to send two events.  */
        event2 = virDomainEventNewFromObj(vm,
                                          VIR_DOMAIN_EVENT_SUSPENDED,
                                          VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
    }
1368
    virDomainAuditStart(vm, "booted", true);
D
Daniel P. Berrange 已提交
1369

1370
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1371
    if (dom) dom->id = vm->def->id;
1372

1373
    if (vm &&
1374
        qemuDomainObjEndJob(driver, vm) == 0)
1375
        vm = NULL;
1376

1377 1378
cleanup:
    virDomainDefFree(def);
1379 1380
    if (vm)
        virDomainObjUnlock(vm);
1381
    if (event) {
1382
        qemuDomainEventQueue(driver, event);
1383 1384 1385
        if (event2)
            qemuDomainEventQueue(driver, event2);
    }
1386
    qemuDriverUnlock(driver);
1387
    return dom;
D
Daniel P. Berrange 已提交
1388 1389 1390
}


1391
static int qemudDomainSuspend(virDomainPtr dom) {
1392 1393 1394
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1395
    virDomainEventPtr event = NULL;
1396
    qemuDomainObjPrivatePtr priv;
1397 1398
    virDomainPausedReason reason;
    int eventDetail;
1399

1400
    qemuDriverLock(driver);
1401
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1402

D
Daniel P. Berrange 已提交
1403
    if (!vm) {
1404 1405
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1406 1407
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1408
        goto cleanup;
D
Daniel P. Berrange 已提交
1409
    }
D
Daniel P. Berrange 已提交
1410
    if (!virDomainObjIsActive(vm)) {
1411 1412
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1413
        goto cleanup;
D
Daniel P. Berrange 已提交
1414
    }
1415 1416 1417

    priv = vm->privateData;

1418
    if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_OUT) {
1419 1420
        reason = VIR_DOMAIN_PAUSED_MIGRATION;
        eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED;
1421
    } else {
1422 1423 1424
        reason = VIR_DOMAIN_PAUSED_USER;
        eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_PAUSED;
    }
1425

1426 1427 1428 1429 1430 1431 1432 1433 1434
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_SUSPEND) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }
    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
1435
        if (qemuProcessStopCPUs(driver, vm, reason, QEMU_ASYNC_JOB_NONE) < 0) {
1436
            goto endjob;
1437
        }
1438 1439 1440
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         eventDetail);
D
Daniel P. Berrange 已提交
1441
    }
1442 1443 1444
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
        goto endjob;
    ret = 0;
1445

1446
endjob:
1447
    if (qemuDomainObjEndJob(driver, vm) == 0)
1448
        vm = NULL;
1449

1450
cleanup:
1451 1452
    if (vm)
        virDomainObjUnlock(vm);
1453

1454
    if (event)
1455
        qemuDomainEventQueue(driver, event);
1456
    qemuDriverUnlock(driver);
1457
    return ret;
D
Daniel P. Berrange 已提交
1458 1459 1460
}


1461
static int qemudDomainResume(virDomainPtr dom) {
1462 1463 1464
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1465
    virDomainEventPtr event = NULL;
1466

1467
    qemuDriverLock(driver);
1468
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1469

D
Daniel P. Berrange 已提交
1470
    if (!vm) {
1471 1472
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1473 1474
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1475
        goto cleanup;
D
Daniel P. Berrange 已提交
1476
    }
1477

1478
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
1479 1480
        goto cleanup;

D
Daniel P. Berrange 已提交
1481
    if (!virDomainObjIsActive(vm)) {
1482 1483
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1484
        goto endjob;
D
Daniel P. Berrange 已提交
1485
    }
J
Jiri Denemark 已提交
1486 1487
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
        if (qemuProcessStartCPUs(driver, vm, dom->conn,
1488 1489
                                 VIR_DOMAIN_RUNNING_UNPAUSED,
                                 QEMU_ASYNC_JOB_NONE) < 0) {
1490
            if (virGetLastError() == NULL)
1491 1492
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("resume operation failed"));
1493
            goto endjob;
1494
        }
1495 1496 1497
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
D
Daniel P. Berrange 已提交
1498
    }
1499
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
1500
        goto endjob;
1501 1502
    ret = 0;

1503
endjob:
1504
    if (qemuDomainObjEndJob(driver, vm) == 0)
1505
        vm = NULL;
1506

1507
cleanup:
1508 1509
    if (vm)
        virDomainObjUnlock(vm);
1510
    if (event)
1511
        qemuDomainEventQueue(driver, event);
1512
    qemuDriverUnlock(driver);
1513
    return ret;
D
Daniel P. Berrange 已提交
1514 1515
}

1516
static int qemuDomainShutdownFlags(virDomainPtr dom, unsigned int flags) {
1517 1518 1519
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1520
    qemuDomainObjPrivatePtr priv;
1521 1522 1523 1524
    bool useAgent = false;

    virCheckFlags(VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN |
                  VIR_DOMAIN_SHUTDOWN_GUEST_AGENT, -1);
1525

1526
    qemuDriverLock(driver);
1527
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1528 1529
    qemuDriverUnlock(driver);

1530
    if (!vm) {
1531 1532
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1533 1534
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1535
        goto cleanup;
1536 1537
    }

1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
    priv = vm->privateData;

    if ((flags & VIR_DOMAIN_SHUTDOWN_GUEST_AGENT) ||
        (!(flags & VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN) &&
         priv->agent))
        useAgent = true;

    if (useAgent) {
        if (priv->agentError) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("QEMU guest agent is not available due to an error"));
1549
            goto cleanup;
1550 1551 1552 1553
        }
        if (!priv->agent) {
            qemuReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("QEMU guest agent is not configured"));
1554
            goto cleanup;
1555 1556 1557
        }
    }

1558
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1559 1560
        goto cleanup;

D
Daniel P. Berrange 已提交
1561
    if (!virDomainObjIsActive(vm)) {
1562 1563
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1564
        goto endjob;
1565 1566
    }

1567 1568 1569 1570 1571 1572
    if (useAgent) {
        qemuDomainObjEnterAgent(driver, vm);
        ret = qemuAgentShutdown(priv->agent, QEMU_AGENT_SHUTDOWN_POWERDOWN);
        qemuDomainObjExitAgent(driver, vm);
    } else {
        qemuDomainSetFakeReboot(driver, vm, false);
1573

1574 1575 1576 1577
        qemuDomainObjEnterMonitor(driver, vm);
        ret = qemuMonitorSystemPowerdown(priv->mon);
        qemuDomainObjExitMonitor(driver, vm);
    }
1578

1579
endjob:
1580
    if (qemuDomainObjEndJob(driver, vm) == 0)
1581
        vm = NULL;
1582

1583
cleanup:
1584 1585
    if (vm)
        virDomainObjUnlock(vm);
1586
    return ret;
1587 1588
}

1589 1590 1591 1592
static int qemuDomainShutdown(virDomainPtr dom) {
    return qemuDomainShutdownFlags(dom, 0);
}

1593

1594 1595 1596 1597 1598
static int qemuDomainReboot(virDomainPtr dom, unsigned int flags) {
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;
1599
    bool useAgent = false;
1600

1601 1602
    virCheckFlags(VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN |
                  VIR_DOMAIN_SHUTDOWN_GUEST_AGENT , -1);
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

1616 1617
    priv = vm->privateData;

1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
    if ((flags & VIR_DOMAIN_SHUTDOWN_GUEST_AGENT) ||
        (!(flags & VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN) &&
         priv->agent))
        useAgent = true;

    if (useAgent) {
        if (priv->agentError) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("QEMU guest agent is not available due to an error"));
            goto cleanup;
        }
        if (!priv->agent) {
            qemuReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("QEMU guest agent is not configured"));
            goto cleanup;
        }
    } else {
#if HAVE_YAJL
        if (qemuCapsGet(priv->qemuCaps, QEMU_CAPS_MONITOR_JSON)) {
            if (!qemuCapsGet(priv->qemuCaps, QEMU_CAPS_NO_SHUTDOWN)) {
                qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                _("Reboot is not supported with this QEMU binary"));
                goto cleanup;
            }
        } else {
#endif
1644
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
1645
                            _("Reboot is not supported without the JSON monitor"));
1646
            goto cleanup;
1647
#if HAVE_YAJL
1648
        }
1649 1650
#endif
    }
1651

1652 1653
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;
1654

1655 1656 1657 1658 1659
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }
1660

1661 1662 1663 1664 1665
    if (useAgent) {
        qemuDomainObjEnterAgent(driver, vm);
        ret = qemuAgentShutdown(priv->agent, QEMU_AGENT_SHUTDOWN_REBOOT);
        qemuDomainObjExitAgent(driver, vm);
    } else {
1666
        qemuDomainObjEnterMonitor(driver, vm);
1667
        ret = qemuMonitorSystemPowerdown(priv->mon);
1668
        qemuDomainObjExitMonitor(driver, vm);
1669

1670 1671
        if (ret == 0)
            qemuDomainSetFakeReboot(driver, vm, true);
1672 1673
    }

1674 1675 1676 1677
endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;

1678 1679 1680 1681 1682 1683 1684
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
static int
qemuDomainReset(virDomainPtr dom, unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, -1);

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

    priv = vm->privateData;
    qemuDomainObjEnterMonitor(driver, vm);
    ret = qemuMonitorSystemReset(priv->mon);
    qemuDomainObjExitMonitor(driver, vm);

    priv->fakeReboot = false;

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
/* Count how many snapshots in a set have external disk snapshots.  */
static void
qemuDomainSnapshotCountExternal(void *payload,
                                const void *name ATTRIBUTE_UNUSED,
                                void *data)
{
    virDomainSnapshotObjPtr snap = payload;
    int *count = data;

    if (snap->def->state == VIR_DOMAIN_DISK_SNAPSHOT)
        (*count)++;
}

1747 1748 1749 1750
static int
qemuDomainDestroyFlags(virDomainPtr dom,
                       unsigned int flags)
{
1751 1752 1753
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1754
    virDomainEventPtr event = NULL;
1755
    qemuDomainObjPrivatePtr priv;
1756

1757 1758
    virCheckFlags(0, -1);

1759
    qemuDriverLock(driver);
1760
    vm  = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel P. Berrange 已提交
1761
    if (!vm) {
1762 1763
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1764 1765
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1766
        goto cleanup;
D
Daniel P. Berrange 已提交
1767
    }
1768

1769 1770
    priv = vm->privateData;

1771
    qemuDomainSetFakeReboot(driver, vm, false);
1772

1773 1774 1775 1776 1777
    /* Although qemuProcessStop does this already, there may
     * be an outstanding job active. We want to make sure we
     * can kill the process even if a job is active. Killing
     * it now means the job will be released
     */
1778
    qemuProcessKill(vm, false);
1779

1780 1781 1782 1783 1784
    /* We need to prevent monitor EOF callback from doing our work (and sending
     * misleading events) while the vm is unlocked inside BeginJob API
     */
    priv->beingDestroyed = true;

1785
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_DESTROY) < 0)
1786 1787
        goto cleanup;

1788 1789
    priv->beingDestroyed = false;

D
Daniel P. Berrange 已提交
1790
    if (!virDomainObjIsActive(vm)) {
1791 1792
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1793
        goto endjob;
1794
    }
1795

J
Jiri Denemark 已提交
1796
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_DESTROYED);
1797 1798 1799
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1800
    virDomainAuditStop(vm, "destroyed");
1801

1802
    if (!vm->persistent) {
1803
        if (qemuDomainObjEndJob(driver, vm) > 0)
1804
            qemuDomainRemoveInactive(driver, vm);
1805 1806
        vm = NULL;
    }
1807 1808
    ret = 0;

1809
endjob:
1810
    if (vm &&
1811
        qemuDomainObjEndJob(driver, vm) == 0)
1812
        vm = NULL;
1813

1814
cleanup:
1815 1816
    if (vm)
        virDomainObjUnlock(vm);
1817 1818
    if (event)
        qemuDomainEventQueue(driver, event);
1819
    qemuDriverUnlock(driver);
1820
    return ret;
D
Daniel P. Berrange 已提交
1821 1822
}

1823 1824 1825 1826 1827
static int
qemuDomainDestroy(virDomainPtr dom)
{
    return qemuDomainDestroyFlags(dom, 0);
}
D
Daniel P. Berrange 已提交
1828

1829
static char *qemudDomainGetOSType(virDomainPtr dom) {
1830 1831 1832
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1833

1834
    qemuDriverLock(driver);
1835
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1836
    qemuDriverUnlock(driver);
1837
    if (!vm) {
1838 1839
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1840 1841
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1842
        goto cleanup;
1843 1844
    }

1845
    if (!(type = strdup(vm->def->os.type)))
1846
        virReportOOMError();
1847 1848

cleanup:
1849 1850
    if (vm)
        virDomainObjUnlock(vm);
1851 1852 1853
    return type;
}

1854 1855
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
1856 1857 1858
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
1859

1860
    qemuDriverLock(driver);
1861
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1862 1863
    qemuDriverUnlock(driver);

1864
    if (!vm) {
1865 1866
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1867 1868
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1869
        goto cleanup;
1870 1871
    }

1872
    ret = vm->def->mem.max_balloon;
1873 1874

cleanup:
1875 1876
    if (vm)
        virDomainObjUnlock(vm);
1877
    return ret;
1878 1879
}

1880 1881
static int qemudDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
                                     unsigned int flags) {
1882
    struct qemud_driver *driver = dom->conn->privateData;
1883
    qemuDomainObjPrivatePtr priv;
1884
    virDomainObjPtr vm;
1885
    virDomainDefPtr persistentDef = NULL;
1886
    int ret = -1, r;
1887

1888 1889
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
1890
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1891

1892
    qemuDriverLock(driver);
1893
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1894
    qemuDriverUnlock(driver);
1895
    if (!vm) {
1896 1897
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1898 1899
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1900
        goto cleanup;
1901 1902
    }

1903
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1904 1905
        goto cleanup;

1906 1907
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
1908
        goto endjob;
1909

1910 1911 1912
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */

1913
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
1914 1915 1916
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot resize the maximum memory on an "
                              "active domain"));
1917
            goto endjob;
1918
        }
1919

1920
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
1921 1922
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
1923 1924 1925 1926
            persistentDef->mem.max_balloon = newmem;
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
1927 1928 1929
            goto endjob;
        }

1930 1931 1932 1933 1934 1935 1936 1937 1938
    } else {
        /* resize the current memory */

        if (newmem > vm->def->mem.max_balloon) {
            qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                            _("cannot set memory higher than max memory"));
            goto endjob;
        }

1939
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
1940
            priv = vm->privateData;
1941
            qemuDomainObjEnterMonitor(driver, vm);
1942
            r = qemuMonitorSetBalloon(priv->mon, newmem);
1943
            qemuDomainObjExitMonitor(driver, vm);
1944 1945
            virDomainAuditMemory(vm, vm->def->mem.cur_balloon, newmem, "update",
                                 r == 1);
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
            if (r < 0)
                goto endjob;

            /* Lack of balloon support is a fatal error */
            if (r == 0) {
                qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                _("cannot set memory of an active domain"));
                goto endjob;
            }
        }

1957
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
1958
            sa_assert(persistentDef);
1959 1960 1961 1962
            persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
            goto endjob;
        }
1963
    }
1964

1965
    ret = 0;
1966
endjob:
1967
    if (qemuDomainObjEndJob(driver, vm) == 0)
1968
        vm = NULL;
1969

1970
cleanup:
1971 1972
    if (vm)
        virDomainObjUnlock(vm);
1973
    return ret;
1974 1975
}

1976 1977
static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem)
{
1978
    return qemudDomainSetMemoryFlags(dom, newmem, VIR_DOMAIN_AFFECT_LIVE);
1979 1980
}

1981 1982 1983 1984 1985
static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return qemudDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
static int qemuDomainInjectNMI(virDomainPtr domain, unsigned int flags)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, -1);

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

    priv = vm->privateData;

2013
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
2014
        goto cleanup;
2015 2016 2017 2018 2019 2020 2021

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

2022
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2023 2024
    ret = qemuMonitorInjectNMI(priv->mon);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
2025 2026

endjob:
2027
    if (qemuDomainObjEndJob(driver, vm) == 0) {
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
        vm = NULL;
        goto cleanup;
    }

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
static int qemuDomainSendKey(virDomainPtr domain,
                             unsigned int codeset,
                             unsigned int holdtime,
                             unsigned int *keycodes,
                             int nkeycodes,
                             unsigned int flags)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, -1);

2053 2054
    /* translate the keycode to RFB for qemu driver */
    if (codeset != VIR_KEYCODE_SET_RFB) {
2055 2056 2057 2058
        int i;
        int keycode;

        for (i = 0; i < nkeycodes; i++) {
2059
            keycode = virKeycodeValueTranslate(codeset, VIR_KEYCODE_SET_RFB,
2060 2061 2062
                                               keycodes[i]);
            if (keycode < 0) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
2063
             _("cannot translate keycode %u of %s codeset to rfb keycode"),
2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
                                keycodes[i],
                                virKeycodeSetTypeToString(codeset));
                return -1;
            }
            keycodes[i] = keycode;
        }
    }

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    priv = vm->privateData;

    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
2090
        goto endjob;
2091 2092
    }

2093
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2094 2095
    ret = qemuMonitorSendKey(priv->mon, holdtime, keycodes, nkeycodes);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
2096 2097 2098

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
2099 2100 2101 2102 2103 2104 2105 2106 2107
        vm = NULL;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

2108
static int qemudDomainGetInfo(virDomainPtr dom,
2109 2110
                              virDomainInfoPtr info)
{
2111 2112 2113
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2114 2115
    int err;
    unsigned long balloon;
2116

2117
    qemuDriverLock(driver);
2118
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2119
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
2120
    if (!vm) {
2121 2122
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2123 2124
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
2125
        goto cleanup;
D
Daniel P. Berrange 已提交
2126 2127
    }

J
Jiri Denemark 已提交
2128
    info->state = virDomainObjGetState(vm, NULL);
D
Daniel P. Berrange 已提交
2129

D
Daniel P. Berrange 已提交
2130
    if (!virDomainObjIsActive(vm)) {
2131
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
2132
    } else {
2133
        if (qemudGetProcessInfo(&(info->cpuTime), NULL, vm->pid, 0) < 0) {
E
Eric Blake 已提交
2134 2135
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("cannot read cputime for domain"));
2136
            goto cleanup;
D
Daniel P. Berrange 已提交
2137 2138 2139
        }
    }

2140
    info->maxMem = vm->def->mem.max_balloon;
2141

D
Daniel P. Berrange 已提交
2142
    if (virDomainObjIsActive(vm)) {
2143
        qemuDomainObjPrivatePtr priv = vm->privateData;
2144 2145 2146

        if ((vm->def->memballoon != NULL) &&
            (vm->def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_NONE)) {
2147
            info->memory = vm->def->mem.max_balloon;
2148
        } else if (qemuDomainJobAllowed(priv, QEMU_JOB_QUERY)) {
2149
            if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
2150
                goto cleanup;
2151 2152 2153
            if (!virDomainObjIsActive(vm))
                err = 0;
            else {
2154
                qemuDomainObjEnterMonitor(driver, vm);
2155
                err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
2156
                qemuDomainObjExitMonitor(driver, vm);
2157
            }
2158
            if (qemuDomainObjEndJob(driver, vm) == 0) {
2159
                vm = NULL;
2160 2161 2162
                goto cleanup;
            }

2163 2164 2165 2166 2167 2168 2169
            if (err < 0) {
                /* We couldn't get current memory allocation but that's not
                 * a show stopper; we wouldn't get it if there was a job
                 * active either
                 */
                info->memory = vm->def->mem.cur_balloon;
            } else if (err == 0) {
2170
                /* Balloon not supported, so maxmem is always the allocation */
2171
                info->memory = vm->def->mem.max_balloon;
2172
            } else {
2173
                info->memory = balloon;
2174
            }
2175
        } else {
2176
            info->memory = vm->def->mem.cur_balloon;
2177
        }
2178
    } else {
2179
        info->memory = vm->def->mem.cur_balloon;
2180 2181
    }

2182
    info->nrVirtCpu = vm->def->vcpus;
2183 2184 2185
    ret = 0;

cleanup:
2186 2187
    if (vm)
        virDomainObjUnlock(vm);
2188
    return ret;
D
Daniel P. Berrange 已提交
2189 2190
}

2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
static int
qemuDomainGetState(virDomainPtr dom,
                   int *state,
                   int *reason,
                   unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

J
Jiri Denemark 已提交
2215
    *state = virDomainObjGetState(vm, reason);
2216 2217 2218 2219 2220 2221 2222 2223
    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

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 2255 2256 2257 2258 2259
static int
qemuDomainGetControlInfo(virDomainPtr dom,
                          virDomainControlInfoPtr info,
                          unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(0, -1);

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

    priv = vm->privateData;

    memset(info, 0, sizeof(*info));

    if (priv->monError) {
        info->state = VIR_DOMAIN_CONTROL_ERROR;
2260
    } else if (priv->job.active) {
2261 2262
        if (!priv->monStart) {
            info->state = VIR_DOMAIN_CONTROL_JOB;
2263
            if (virTimeMillisNow(&info->stateTime) < 0)
2264
                goto cleanup;
2265
            info->stateTime -= priv->job.start;
2266 2267
        } else {
            info->state = VIR_DOMAIN_CONTROL_OCCUPIED;
2268
            if (virTimeMillisNow(&info->stateTime) < 0)
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283
                goto cleanup;
            info->stateTime -= priv->monStart;
        }
    } else {
        info->state = VIR_DOMAIN_CONTROL_OK;
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

D
Daniel P. Berrange 已提交
2284

E
Eric Blake 已提交
2285 2286
#define QEMUD_SAVE_MAGIC   "LibvirtQemudSave"
#define QEMUD_SAVE_PARTIAL "LibvirtQemudPart"
2287 2288
#define QEMUD_SAVE_VERSION 2

E
Eric Blake 已提交
2289 2290
verify(sizeof(QEMUD_SAVE_MAGIC) == sizeof(QEMUD_SAVE_PARTIAL));

2291
enum qemud_save_formats {
2292 2293 2294
    QEMUD_SAVE_FORMAT_RAW = 0,
    QEMUD_SAVE_FORMAT_GZIP = 1,
    QEMUD_SAVE_FORMAT_BZIP2 = 2,
2295 2296
    /*
     * Deprecated by xz and never used as part of a release
2297
     * QEMUD_SAVE_FORMAT_LZMA
2298 2299
     */
    QEMUD_SAVE_FORMAT_XZ = 3,
2300
    QEMUD_SAVE_FORMAT_LZOP = 4,
2301 2302 2303
    /* Note: add new members only at the end.
       These values are used in the on-disk format.
       Do not change or re-use numbers. */
2304 2305

    QEMUD_SAVE_FORMAT_LAST
2306
};
2307

2308 2309 2310 2311 2312
VIR_ENUM_DECL(qemudSaveCompression)
VIR_ENUM_IMPL(qemudSaveCompression, QEMUD_SAVE_FORMAT_LAST,
              "raw",
              "gzip",
              "bzip2",
2313 2314
              "xz",
              "lzop")
2315

2316 2317
struct qemud_save_header {
    char magic[sizeof(QEMUD_SAVE_MAGIC)-1];
2318 2319 2320 2321 2322
    uint32_t version;
    uint32_t xml_len;
    uint32_t was_running;
    uint32_t compressed;
    uint32_t unused[15];
2323 2324
};

2325 2326 2327 2328 2329 2330 2331 2332 2333
static inline void
bswap_header(struct qemud_save_header *hdr) {
    hdr->version = bswap_32(hdr->version);
    hdr->xml_len = bswap_32(hdr->xml_len);
    hdr->was_running = bswap_32(hdr->was_running);
    hdr->compressed = bswap_32(hdr->compressed);
}


2334
/* return -errno on failure, or 0 on success */
E
Eric Blake 已提交
2335 2336 2337 2338
static int
qemuDomainSaveHeader(int fd, const char *path, char *xml,
                     struct qemud_save_header *header)
{
2339 2340
    int ret = 0;

E
Eric Blake 已提交
2341
    if (safewrite(fd, header, sizeof(*header)) != sizeof(*header)) {
2342
        ret = -errno;
2343
        qemuReportError(VIR_ERR_OPERATION_FAILED,
2344
                        _("failed to write header to domain save file '%s'"),
E
Eric Blake 已提交
2345
                        path);
2346 2347 2348
        goto endjob;
    }

E
Eric Blake 已提交
2349
    if (safewrite(fd, xml, header->xml_len) != header->xml_len) {
2350
        ret = -errno;
2351
        qemuReportError(VIR_ERR_OPERATION_FAILED,
E
Eric Blake 已提交
2352
                         _("failed to write xml to '%s'"), path);
2353 2354 2355 2356 2357 2358
        goto endjob;
    }
endjob:
    return ret;
}

2359 2360 2361 2362 2363 2364 2365 2366 2367
/* Given a enum qemud_save_formats compression level, return the name
 * of the program to run, or NULL if no program is needed.  */
static const char *
qemuCompressProgramName(int compress)
{
    return (compress == QEMUD_SAVE_FORMAT_RAW ? NULL :
            qemudSaveCompressionTypeToString(compress));
}

E
Eric Blake 已提交
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474
/* Internal function to properly create or open existing files, with
 * ownership affected by qemu driver setup.  */
static int
qemuOpenFile(struct qemud_driver *driver, const char *path, int oflags,
             bool *needUnlink, bool *bypassSecurityDriver)
{
    struct stat sb;
    bool is_reg = true;
    bool need_unlink = false;
    bool bypass_security = false;
    int fd = -1;
    uid_t uid = getuid();
    gid_t gid = getgid();

    /* path might be a pre-existing block dev, in which case
     * we need to skip the create step, and also avoid unlink
     * in the failure case */
    if (oflags & O_CREAT) {
        need_unlink = true;
        if (stat(path, &sb) == 0) {
            is_reg = !!S_ISREG(sb.st_mode);
            /* If the path is regular file which exists
             * already and dynamic_ownership is off, we don't
             * want to change it's ownership, just open it as-is */
            if (is_reg && !driver->dynamicOwnership) {
                uid = sb.st_uid;
                gid = sb.st_gid;
            }
        }
    }

    /* First try creating the file as root */
    if (!is_reg) {
        fd = open(path, oflags & ~O_CREAT);
        if (fd < 0) {
            virReportSystemError(errno, _("unable to open %s"), path);
            goto cleanup;
        }
    } else {
        if ((fd = virFileOpenAs(path, oflags, S_IRUSR | S_IWUSR,
                                uid, gid, 0)) < 0) {
            /* If we failed as root, and the error was permission-denied
               (EACCES or EPERM), assume it's on a network-connected share
               where root access is restricted (eg, root-squashed NFS). If the
               qemu user (driver->user) is non-root, just set a flag to
               bypass security driver shenanigans, and retry the operation
               after doing setuid to qemu user */
            if ((fd != -EACCES && fd != -EPERM) ||
                driver->user == getuid()) {
                virReportSystemError(-fd,
                                     _("Failed to create file '%s'"),
                                     path);
                goto cleanup;
            }

            /* On Linux we can also verify the FS-type of the directory. */
            switch (virStorageFileIsSharedFS(path)) {
                case 1:
                   /* it was on a network share, so we'll continue
                    * as outlined above
                    */
                   break;

                case -1:
                   virReportSystemError(errno,
                                        _("Failed to create file "
                                          "'%s': couldn't determine fs type"),
                                        path);
                   goto cleanup;

                case 0:
                default:
                   /* local file - log the error returned by virFileOpenAs */
                   virReportSystemError(-fd,
                                        _("Failed to create file '%s'"),
                                        path);
                   goto cleanup;
            }

            /* Retry creating the file as driver->user */

            if ((fd = virFileOpenAs(path, oflags,
                                    S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP,
                                    driver->user, driver->group,
                                    VIR_FILE_OPEN_AS_UID)) < 0) {
                virReportSystemError(-fd,
                                   _("Error from child process creating '%s'"),
                                     path);
                goto cleanup;
            }

            /* Since we had to setuid to create the file, and the fstype
               is NFS, we assume it's a root-squashing NFS share, and that
               the security driver stuff would have failed anyway */

            bypass_security = true;
        }
    }
cleanup:
    if (needUnlink)
        *needUnlink = need_unlink;
    if (bypassSecurityDriver)
        *bypassSecurityDriver = bypass_security;

    return fd;
}

2475
/* This internal function expects the driver lock to already be held on
2476 2477 2478 2479
 * entry and the vm must be active + locked. Vm will be unlocked and
 * potentially free'd after this returns (eg transient VMs are freed
 * shutdown). So 'vm' must not be referenced by the caller after
 * this returns (whether returning success or failure).
2480
 */
2481 2482 2483
static int
qemuDomainSaveInternal(struct qemud_driver *driver, virDomainPtr dom,
                       virDomainObjPtr vm, const char *path,
2484
                       int compressed, const char *xmlin, unsigned int flags)
2485
{
2486
    char *xml = NULL;
2487
    struct qemud_save_header header;
2488
    bool bypassSecurityDriver = false;
2489
    int ret = -1;
2490
    int rc;
2491
    virDomainEventPtr event = NULL;
2492
    qemuDomainObjPrivatePtr priv;
E
Eric Blake 已提交
2493
    bool needUnlink = false;
2494
    size_t len;
2495
    unsigned long long offset;
2496
    unsigned long long pad;
2497
    int fd = -1;
2498 2499
    int directFlag = 0;
    virFileDirectFdPtr directFd = NULL;
2500
    bool bypass_cache = flags & VIR_DOMAIN_SAVE_BYPASS_CACHE;
2501

2502 2503 2504
    if (qemuProcessAutoDestroyActive(driver, vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is marked for auto destroy"));
2505
        goto cleanup;
2506 2507
    }

2508
    memset(&header, 0, sizeof(header));
E
Eric Blake 已提交
2509
    memcpy(header.magic, QEMUD_SAVE_PARTIAL, sizeof(header.magic));
2510 2511
    header.version = QEMUD_SAVE_VERSION;

2512
    header.compressed = compressed;
2513

2514
    priv = vm->privateData;
2515

2516 2517
    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             QEMU_ASYNC_JOB_SAVE) < 0)
2518 2519
        goto cleanup;

2520 2521
    memset(&priv->job.info, 0, sizeof(priv->job.info));
    priv->job.info.type = VIR_DOMAIN_JOB_UNBOUNDED;
2522

2523
    /* Pause */
J
Jiri Denemark 已提交
2524
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
2525
        header.was_running = 1;
2526 2527
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_SAVE) < 0)
2528
            goto endjob;
2529 2530 2531 2532 2533 2534

        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto endjob;
        }
2535
    }
2536 2537 2538 2539 2540
    /* libvirt.c already guaranteed these two flags are exclusive.  */
    if (flags & VIR_DOMAIN_SAVE_RUNNING)
        header.was_running = 1;
    else if (flags & VIR_DOMAIN_SAVE_PAUSED)
        header.was_running = 0;
2541

2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563
    /* Get XML for the domain.  Restore needs only the inactive xml,
     * including secure.  We should get the same result whether xmlin
     * is NULL or whether it was the live xml of the domain moments
     * before.  */
    if (xmlin) {
        virDomainDefPtr def = NULL;

        if (!(def = virDomainDefParseString(driver->caps, xmlin,
                                            QEMU_EXPECTED_VIRT_TYPES,
                                            VIR_DOMAIN_XML_INACTIVE))) {
            goto endjob;
        }
        if (!virDomainDefCheckABIStability(vm->def, def)) {
            virDomainDefFree(def);
            goto endjob;
        }
        xml = virDomainDefFormat(def, (VIR_DOMAIN_XML_INACTIVE |
                                       VIR_DOMAIN_XML_SECURE));
    } else {
        xml = virDomainDefFormat(vm->def, (VIR_DOMAIN_XML_INACTIVE |
                                           VIR_DOMAIN_XML_SECURE));
    }
2564
    if (!xml) {
2565 2566
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to get domain xml"));
2567
        goto endjob;
2568
    }
2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588
    len = strlen(xml) + 1;
    offset = sizeof(header) + len;

    /* Due to way we append QEMU state on our header with dd,
     * we need to ensure there's a 512 byte boundary. Unfortunately
     * we don't have an explicit offset in the header, so we fake
     * it by padding the XML string with NUL bytes.  Additionally,
     * we want to ensure that virDomainSaveImageDefineXML can supply
     * slightly larger XML, so we add a miminum padding prior to
     * rounding out to page boundaries.
     */
    pad = 1024;
    pad += (QEMU_MONITOR_MIGRATE_TO_FILE_BS -
            ((offset + pad) % QEMU_MONITOR_MIGRATE_TO_FILE_BS));
    if (VIR_EXPAND_N(xml, len, pad) < 0) {
        virReportOOMError();
        goto endjob;
    }
    offset += pad;
    header.xml_len = len;
2589

2590
    /* Obtain the file handle.  */
2591 2592 2593 2594 2595
    if (bypass_cache) {
        directFlag = virFileDirectFdFlag();
        if (directFlag < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("bypass cache unsupported by this system"));
E
Eric Blake 已提交
2596
            goto cleanup;
2597
        }
2598
    }
E
Eric Blake 已提交
2599 2600 2601 2602
    fd = qemuOpenFile(driver, path, O_WRONLY | O_TRUNC | O_CREAT | directFlag,
                      &needUnlink, &bypassSecurityDriver);
    if (fd < 0)
        goto endjob;
2603 2604 2605
    if (bypass_cache && (directFd = virFileDirectFdNew(&fd, path)) == NULL)
        goto endjob;

2606
    /* Write header to file, followed by XML */
E
Eric Blake 已提交
2607
    if (qemuDomainSaveHeader(fd, path, xml, &header) < 0) {
2608 2609 2610 2611
        VIR_FORCE_CLOSE(fd);
        goto endjob;
    }

2612
    /* Perform the migration */
2613
    if (qemuMigrationToFile(driver, vm, fd, offset, path,
2614
                            qemuCompressProgramName(compressed),
E
Eric Blake 已提交
2615
                            bypassSecurityDriver,
2616
                            QEMU_ASYNC_JOB_SAVE) < 0)
2617
        goto endjob;
E
Eric Blake 已提交
2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644

    /* Touch up file header to mark image complete.  */
    if (bypass_cache) {
        /* Reopen the file to touch up the header, since we aren't set
         * up to seek backwards on directFd.  The reopened fd will
         * trigger a single page of file system cache pollution, but
         * that's acceptable.  */
        if (VIR_CLOSE(fd) < 0) {
            virReportSystemError(errno, _("unable to close %s"), path);
            goto endjob;
        }
        if (virFileDirectFdClose(directFd) < 0)
            goto endjob;
        fd = qemuOpenFile(driver, path, O_WRONLY, NULL, NULL);
        if (fd < 0)
            goto endjob;
    } else {
        if (lseek(fd, 0, SEEK_SET) != 0) {
            virReportSystemError(errno, _("unable to seek %s"), path);
            goto endjob;
        }
    }
    memcpy(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic));
    if (safewrite(fd, &header, sizeof(header)) != sizeof(header)) {
        virReportSystemError(errno, _("unable to write %s"), path);
        goto endjob;
    }
2645 2646
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("unable to close %s"), path);
2647
        goto endjob;
2648 2649
    }

2650 2651
    ret = 0;

2652
    /* Shut it down */
J
Jiri Denemark 已提交
2653
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_SAVED);
2654
    virDomainAuditStop(vm, "saved");
2655 2656 2657
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2658
    if (!vm->persistent) {
2659
        if (qemuDomainObjEndAsyncJob(driver, vm) > 0)
2660
            qemuDomainRemoveInactive(driver, vm);
2661 2662
        vm = NULL;
    }
2663

2664
endjob:
2665
    if (vm) {
2666
        if (ret != 0) {
2667
            if (header.was_running && virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
2668
                rc = qemuProcessStartCPUs(driver, vm, dom->conn,
2669 2670
                                          VIR_DOMAIN_RUNNING_SAVE_CANCELED,
                                          QEMU_ASYNC_JOB_SAVE);
2671
                if (rc < 0)
2672
                    VIR_WARN("Unable to resume guest CPUs after save failure");
2673
            }
2674
        }
2675
        if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
2676
            vm = NULL;
2677
    }
2678

2679
cleanup:
2680
    VIR_FORCE_CLOSE(fd);
2681
    virFileDirectFdFree(directFd);
2682
    VIR_FREE(xml);
E
Eric Blake 已提交
2683
    if (ret != 0 && needUnlink)
2684
        unlink(path);
2685 2686
    if (event)
        qemuDomainEventQueue(driver, event);
2687 2688
    if (vm)
        virDomainObjUnlock(vm);
2689
    return ret;
D
Daniel P. Berrange 已提交
2690 2691
}

2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707
/* Returns true if a compression program is available in PATH */
static bool qemudCompressProgramAvailable(enum qemud_save_formats compress)
{
    const char *prog;
    char *c;

    if (compress == QEMUD_SAVE_FORMAT_RAW)
        return true;
    prog = qemudSaveCompressionTypeToString(compress);
    c = virFindFileInPath(prog);
    if (!c)
        return false;
    VIR_FREE(c);
    return true;
}

2708 2709 2710
static int
qemuDomainSaveFlags(virDomainPtr dom, const char *path, const char *dxml,
                    unsigned int flags)
2711 2712 2713
{
    struct qemud_driver *driver = dom->conn->privateData;
    int compressed;
2714 2715 2716
    int ret = -1;
    virDomainObjPtr vm = NULL;

2717 2718 2719
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
                  VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
2720

2721
    qemuDriverLock(driver);
2722 2723 2724 2725 2726 2727 2728 2729 2730

    if (driver->saveImageFormat == NULL)
        compressed = QEMUD_SAVE_FORMAT_RAW;
    else {
        compressed = qemudSaveCompressionTypeFromString(driver->saveImageFormat);
        if (compressed < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Invalid save image format specified "
                                    "in configuration file"));
2731
            goto cleanup;
2732
        }
2733 2734 2735 2736
        if (!qemudCompressProgramAvailable(compressed)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Compression program for image format "
                                    "in configuration file isn't available"));
2737
            goto cleanup;
2738
        }
2739 2740
    }

2741 2742 2743 2744 2745 2746 2747 2748 2749
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

2750 2751 2752 2753 2754 2755
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2756
    ret = qemuDomainSaveInternal(driver, dom, vm, path, compressed,
2757
                                 dxml, flags);
2758
    vm = NULL;
2759 2760 2761 2762 2763 2764 2765

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);

    return ret;
2766 2767
}

2768 2769 2770 2771 2772 2773
static int
qemuDomainSave(virDomainPtr dom, const char *path)
{
    return qemuDomainSaveFlags(dom, path, NULL, 0);
}

2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
static char *
qemuDomainManagedSavePath(struct qemud_driver *driver, virDomainObjPtr vm) {
    char *ret;

    if (virAsprintf(&ret, "%s/%s.save", driver->saveDir, vm->def->name) < 0) {
        virReportOOMError();
        return(NULL);
    }

    return(ret);
}

static int
qemuDomainManagedSave(virDomainPtr dom, unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *name = NULL;
    int ret = -1;
    int compressed;

2795 2796 2797
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
                  VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
2798 2799 2800 2801 2802 2803 2804 2805

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
2806
        goto cleanup;
2807 2808
    }

2809 2810 2811 2812 2813
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }
2814 2815 2816 2817 2818
    if (!vm->persistent) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot do managed save for transient domain"));
        goto cleanup;
    }
2819

2820 2821
    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
2822
        goto cleanup;
2823

2824
    VIR_INFO("Saving state to %s", name);
2825 2826

    compressed = QEMUD_SAVE_FORMAT_RAW;
2827
    ret = qemuDomainSaveInternal(driver, dom, vm, name, compressed,
2828
                                 NULL, flags);
2829
    vm = NULL;
2830 2831 2832 2833 2834

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
2835 2836 2837
    VIR_FREE(name);

    return ret;
2838 2839 2840 2841 2842 2843 2844 2845 2846 2847
}

static int
qemuDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    char *name = NULL;

2848
    virCheckFlags(0, -1);
2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = virFileExists(name);

cleanup:
    VIR_FREE(name);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

static int
qemuDomainManagedSaveRemove(virDomainPtr dom, unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    char *name = NULL;

2882
    virCheckFlags(0, -1);
2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = unlink(name);

cleanup:
    VIR_FREE(name);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
D
Daniel P. Berrange 已提交
2907

2908 2909 2910 2911
static int
doCoreDump(struct qemud_driver *driver,
           virDomainObjPtr vm,
           const char *path,
2912 2913
           enum qemud_save_formats compress,
           bool bypass_cache)
H
Hu Tao 已提交
2914 2915 2916
{
    int fd = -1;
    int ret = -1;
2917 2918
    virFileDirectFdPtr directFd = NULL;
    int directFlag = 0;
H
Hu Tao 已提交
2919 2920

    /* Create an empty file with appropriate ownership.  */
2921 2922 2923 2924 2925 2926 2927 2928
    if (bypass_cache) {
        directFlag = virFileDirectFdFlag();
        if (directFlag < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("bypass cache unsupported by this system"));
            goto cleanup;
        }
    }
E
Eric Blake 已提交
2929 2930 2931 2932 2933 2934
    /* Core dumps usually imply last-ditch analysis efforts are
     * desired, so we intentionally do not unlink even if a file was
     * created.  */
    if ((fd = qemuOpenFile(driver, path,
                           O_CREAT | O_TRUNC | O_WRONLY | directFlag,
                           NULL, NULL)) < 0)
H
Hu Tao 已提交
2935 2936
        goto cleanup;

2937 2938 2939
    if (bypass_cache && (directFd = virFileDirectFdNew(&fd, path)) == NULL)
        goto cleanup;

2940
    if (qemuMigrationToFile(driver, vm, fd, 0, path,
E
Eric Blake 已提交
2941
                            qemuCompressProgramName(compress), false,
2942
                            QEMU_ASYNC_JOB_DUMP) < 0)
2943 2944
        goto cleanup;

H
Hu Tao 已提交
2945 2946 2947 2948 2949 2950
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno,
                             _("unable to save file %s"),
                             path);
        goto cleanup;
    }
2951 2952
    if (virFileDirectFdClose(directFd) < 0)
        goto cleanup;
H
Hu Tao 已提交
2953

2954
    ret = 0;
H
Hu Tao 已提交
2955 2956

cleanup:
2957
    VIR_FORCE_CLOSE(fd);
2958
    virFileDirectFdFree(directFd);
H
Hu Tao 已提交
2959 2960 2961 2962 2963
    if (ret != 0)
        unlink(path);
    return ret;
}

2964 2965 2966 2967 2968
static enum qemud_save_formats
getCompressionType(struct qemud_driver *driver)
{
    int compress = QEMUD_SAVE_FORMAT_RAW;

2969 2970 2971 2972 2973 2974
    /*
     * We reuse "save" flag for "dump" here. Then, we can support the same
     * format in "save" and "dump".
     */
    if (driver->dumpImageFormat) {
        compress = qemudSaveCompressionTypeFromString(driver->dumpImageFormat);
2975 2976 2977
        /* Use "raw" as the format if the specified format is not valid,
         * or the compress program is not available.
         */
2978
        if (compress < 0) {
2979 2980
            VIR_WARN("%s", _("Invalid dump image format specified in "
                             "configuration file, using raw"));
2981
            return QEMUD_SAVE_FORMAT_RAW;
2982
        }
2983
        if (!qemudCompressProgramAvailable(compress)) {
2984 2985 2986
            VIR_WARN("%s", _("Compression program for dump image format "
                             "in configuration file isn't available, "
                             "using raw"));
2987
            return QEMUD_SAVE_FORMAT_RAW;
2988
        }
2989
    }
2990 2991 2992 2993 2994
    return compress;
}

static int qemudDomainCoreDump(virDomainPtr dom,
                               const char *path,
2995
                               unsigned int flags)
2996
{
2997 2998
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
M
Michal Privoznik 已提交
2999
    qemuDomainObjPrivatePtr priv;
3000
    int resume = 0, paused = 0;
H
Hu Tao 已提交
3001
    int ret = -1;
3002 3003
    virDomainEventPtr event = NULL;

M
Michal Privoznik 已提交
3004 3005
    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH |
                  VIR_DUMP_BYPASS_CACHE | VIR_DUMP_RESET, -1);
3006

P
Paolo Bonzini 已提交
3007 3008 3009 3010 3011 3012
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3013 3014
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
P
Paolo Bonzini 已提交
3015 3016 3017
        goto cleanup;
    }

3018 3019
    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             QEMU_ASYNC_JOB_DUMP) < 0)
3020 3021
        goto cleanup;

D
Daniel P. Berrange 已提交
3022
    if (!virDomainObjIsActive(vm)) {
3023 3024
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
3025
        goto endjob;
P
Paolo Bonzini 已提交
3026 3027
    }

P
Paolo Bonzini 已提交
3028 3029
    /* Migrate will always stop the VM, so the resume condition is
       independent of whether the stop command is issued.  */
J
Jiri Denemark 已提交
3030
    resume = virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING;
P
Paolo Bonzini 已提交
3031 3032

    /* Pause domain for non-live dump */
J
Jiri Denemark 已提交
3033 3034
    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
3035 3036
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_DUMP,
                                QEMU_ASYNC_JOB_DUMP) < 0)
3037
            goto endjob;
P
Paolo Bonzini 已提交
3038
        paused = 1;
3039 3040 3041 3042 3043 3044

        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto endjob;
        }
P
Paolo Bonzini 已提交
3045 3046
    }

3047 3048
    ret = doCoreDump(driver, vm, path, getCompressionType(driver),
                     (flags & VIR_DUMP_BYPASS_CACHE) != 0);
3049 3050 3051 3052
    if (ret < 0)
        goto endjob;

    paused = 1;
3053 3054

endjob:
3055
    if ((ret == 0) && (flags & VIR_DUMP_CRASH)) {
J
Jiri Denemark 已提交
3056
        qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_CRASHED);
3057
        virDomainAuditStop(vm, "crashed");
3058 3059 3060 3061 3062
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
    }

P
Paolo Bonzini 已提交
3063 3064 3065
    /* Since the monitor is always attached to a pty for libvirt, it
       will support synchronous operations so we always get here after
       the migration is complete.  */
M
Michal Privoznik 已提交
3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077
    else if (((resume && paused) || (flags & VIR_DUMP_RESET)) &&
             virDomainObjIsActive(vm)) {
        if ((ret == 0) && (flags & VIR_DUMP_RESET)) {
            priv =  vm->privateData;
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
            ret = qemuMonitorSystemReset(priv->mon);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
        }

        if (resume && qemuProcessStartCPUs(driver, vm, dom->conn,
                                           VIR_DOMAIN_RUNNING_UNPAUSED,
                                           QEMU_ASYNC_JOB_DUMP) < 0) {
3078
            if (virGetLastError() == NULL)
3079 3080
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("resuming after dump failed"));
P
Paolo Bonzini 已提交
3081 3082
        }
    }
3083

3084
    if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
3085
        vm = NULL;
3086
    else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
3087
        qemuDomainRemoveInactive(driver, vm);
3088 3089
        vm = NULL;
    }
3090 3091

cleanup:
P
Paolo Bonzini 已提交
3092 3093
    if (vm)
        virDomainObjUnlock(vm);
3094 3095
    if (event)
        qemuDomainEventQueue(driver, event);
3096
    qemuDriverUnlock(driver);
P
Paolo Bonzini 已提交
3097 3098 3099
    return ret;
}

3100 3101 3102 3103
static char *
qemuDomainScreenshot(virDomainPtr dom,
                     virStreamPtr st,
                     unsigned int screen,
E
Eric Blake 已提交
3104
                     unsigned int flags)
3105 3106 3107 3108 3109 3110 3111
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    char *tmp = NULL;
    int tmp_fd = -1;
    char *ret = NULL;
E
Eric Blake 已提交
3112
    bool unlink_tmp = false;
3113

E
Eric Blake 已提交
3114 3115
    virCheckFlags(0, NULL);

3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    priv = vm->privateData;

3130
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

    /* Well, even if qemu allows multiple graphic cards, heads, whatever,
     * screenshot command does not */
    if (screen) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("currently is supported only taking "
                                "screenshots of screen ID 0"));
        goto endjob;
    }

    if (virAsprintf(&tmp, "%s/qemu.screendump.XXXXXX", driver->cacheDir) < 0) {
        virReportOOMError();
        goto endjob;
    }

    if ((tmp_fd = mkstemp(tmp)) == -1) {
        virReportSystemError(errno, _("mkstemp(\"%s\") failed"), tmp);
        goto endjob;
    }
E
Eric Blake 已提交
3157
    unlink_tmp = true;
3158

3159
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm->def, tmp);
3160

3161
    qemuDomainObjEnterMonitor(driver, vm);
3162
    if (qemuMonitorScreendump(priv->mon, tmp) < 0) {
3163
        qemuDomainObjExitMonitor(driver, vm);
3164 3165
        goto endjob;
    }
3166
    qemuDomainObjExitMonitor(driver, vm);
3167 3168 3169 3170 3171 3172

    if (VIR_CLOSE(tmp_fd) < 0) {
        virReportSystemError(errno, _("unable to close %s"), tmp);
        goto endjob;
    }

E
Eric Blake 已提交
3173
    if (virFDStreamOpenFile(st, tmp, 0, 0, O_RDONLY) < 0) {
3174 3175 3176 3177 3178 3179 3180 3181 3182
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("unable to open stream"));
        goto endjob;
    }

    ret = strdup("image/x-portable-pixmap");

endjob:
    VIR_FORCE_CLOSE(tmp_fd);
E
Eric Blake 已提交
3183 3184
    if (unlink_tmp)
        unlink(tmp);
E
Eric Blake 已提交
3185
    VIR_FREE(tmp);
3186

3187
    if (qemuDomainObjEndJob(driver, vm) == 0)
3188 3189 3190 3191 3192 3193 3194 3195
        vm = NULL;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

H
Hu Tao 已提交
3196 3197 3198
static void processWatchdogEvent(void *data, void *opaque)
{
    int ret;
3199
    struct qemuDomainWatchdogEvent *wdEvent = data;
H
Hu Tao 已提交
3200 3201
    struct qemud_driver *driver = opaque;

W
Wen Congyang 已提交
3202 3203 3204
    qemuDriverLock(driver);
    virDomainObjLock(wdEvent->vm);

H
Hu Tao 已提交
3205 3206 3207 3208 3209
    switch (wdEvent->action) {
    case VIR_DOMAIN_WATCHDOG_ACTION_DUMP:
        {
            char *dumpfile;

E
Eric Blake 已提交
3210
            if (virAsprintf(&dumpfile, "%s/%s-%u",
H
Hu Tao 已提交
3211 3212
                            driver->autoDumpPath,
                            wdEvent->vm->def->name,
E
Eric Blake 已提交
3213 3214
                            (unsigned int)time(NULL)) < 0) {
                virReportOOMError();
W
Wen Congyang 已提交
3215
                goto unlock;
E
Eric Blake 已提交
3216
            }
H
Hu Tao 已提交
3217

3218 3219
            if (qemuDomainObjBeginAsyncJobWithDriver(driver, wdEvent->vm,
                                                     QEMU_ASYNC_JOB_DUMP) < 0) {
W
Wen Congyang 已提交
3220 3221 3222
                VIR_FREE(dumpfile);
                goto unlock;
            }
H
Hu Tao 已提交
3223 3224 3225 3226

            if (!virDomainObjIsActive(wdEvent->vm)) {
                qemuReportError(VIR_ERR_OPERATION_INVALID,
                                "%s", _("domain is not running"));
W
Wen Congyang 已提交
3227 3228
                VIR_FREE(dumpfile);
                goto endjob;
H
Hu Tao 已提交
3229 3230
            }

3231
            ret = doCoreDump(driver, wdEvent->vm, dumpfile,
3232 3233
                             getCompressionType(driver),
                             driver->autoDumpBypassCache);
H
Hu Tao 已提交
3234 3235 3236 3237
            if (ret < 0)
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("Dump failed"));

J
Jiri Denemark 已提交
3238
            ret = qemuProcessStartCPUs(driver, wdEvent->vm, NULL,
3239 3240
                                       VIR_DOMAIN_RUNNING_UNPAUSED,
                                       QEMU_ASYNC_JOB_DUMP);
H
Hu Tao 已提交
3241 3242 3243 3244 3245 3246 3247 3248

            if (ret < 0)
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("Resuming after dump failed"));

            VIR_FREE(dumpfile);
        }
        break;
W
Wen Congyang 已提交
3249 3250
    default:
        goto unlock;
H
Hu Tao 已提交
3251 3252
    }

W
Wen Congyang 已提交
3253 3254 3255 3256
endjob:
    /* Safe to ignore value since ref count was incremented in
     * qemuProcessHandleWatchdog().
     */
3257
    ignore_value(qemuDomainObjEndAsyncJob(driver, wdEvent->vm));
W
Wen Congyang 已提交
3258 3259 3260 3261 3262

unlock:
    if (virDomainObjUnref(wdEvent->vm) > 0)
        virDomainObjUnlock(wdEvent->vm);
    qemuDriverUnlock(driver);
H
Hu Tao 已提交
3263 3264
    VIR_FREE(wdEvent);
}
P
Paolo Bonzini 已提交
3265

3266 3267 3268
static int qemudDomainHotplugVcpus(struct qemud_driver *driver,
                                   virDomainObjPtr vm,
                                   unsigned int nvcpus)
3269 3270
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
3271
    int i, rc = 1;
3272
    int ret = -1;
3273
    int oldvcpus = vm->def->vcpus;
E
Eric Blake 已提交
3274
    int vcpus = oldvcpus;
3275

3276
    qemuDomainObjEnterMonitor(driver, vm);
3277

3278 3279 3280
    /* We need different branches here, because we want to offline
     * in reverse order to onlining, so any partial fail leaves us in a
     * reasonably sensible state */
E
Eric Blake 已提交
3281 3282
    if (nvcpus > vcpus) {
        for (i = vcpus ; i < nvcpus ; i++) {
3283 3284 3285 3286 3287 3288 3289
            /* Online new CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 1);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
3290
            vcpus++;
3291 3292
        }
    } else {
E
Eric Blake 已提交
3293
        for (i = vcpus - 1 ; i >= nvcpus ; i--) {
3294 3295 3296 3297 3298 3299 3300
            /* Offline old CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 0);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
3301
            vcpus--;
3302 3303 3304 3305 3306 3307
        }
    }

    ret = 0;

cleanup:
3308
    qemuDomainObjExitMonitor(driver, vm);
E
Eric Blake 已提交
3309
    vm->def->vcpus = vcpus;
3310
    virDomainAuditVcpu(vm, oldvcpus, nvcpus, "update", rc == 1);
3311 3312 3313 3314 3315 3316 3317 3318 3319
    return ret;

unsupported:
    qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("cannot change vcpu count of this domain"));
    goto cleanup;
}


3320
static int
3321 3322
qemuDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                        unsigned int flags)
3323
{
3324 3325
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3326
    virDomainDefPtr persistentDef;
3327 3328
    const char * type;
    int max;
3329
    int ret = -1;
3330
    bool maximum;
3331

3332 3333
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
3334 3335 3336 3337 3338
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

    if (!nvcpus || (unsigned short) nvcpus != nvcpus) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("argument out of range: %d"), nvcpus);
3339 3340 3341
        return -1;
    }

3342
    qemuDriverLock(driver);
3343
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3344 3345
    qemuDriverUnlock(driver);

3346
    if (!vm) {
3347 3348
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3349 3350
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
3351
        goto cleanup;
3352 3353
    }

3354
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
3355 3356
        goto cleanup;

3357 3358 3359
    maximum = (flags & VIR_DOMAIN_VCPU_MAXIMUM) != 0;
    flags &= ~VIR_DOMAIN_VCPU_MAXIMUM;

3360 3361 3362
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto endjob;
3363 3364 3365 3366 3367 3368 3369 3370

    /* MAXIMUM cannot be mixed with LIVE.  */
    if (maximum && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("cannot adjust maximum on running domain"));
        goto endjob;
    }

3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383
    if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unknown virt type in domain definition '%d'"),
                        vm->def->virtType);
        goto endjob;
    }

    if ((max = qemudGetMaxVCPUs(NULL, type)) < 0) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("could not determine max vcpus for the domain"));
        goto endjob;
    }

3384
    if (!maximum && vm->def->maxvcpus < max) {
3385 3386 3387
        max = vm->def->maxvcpus;
    }

3388 3389 3390 3391 3392 3393 3394
    if (nvcpus > max) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("requested vcpus is greater than max allowable"
                          " vcpus for the domain: %d > %d"), nvcpus, max);
        goto endjob;
    }

3395
    switch (flags) {
3396
    case VIR_DOMAIN_AFFECT_CONFIG:
3397 3398 3399 3400 3401 3402 3403
        if (maximum) {
            persistentDef->maxvcpus = nvcpus;
            if (nvcpus < persistentDef->vcpus)
                persistentDef->vcpus = nvcpus;
        } else {
            persistentDef->vcpus = nvcpus;
        }
3404 3405 3406
        ret = 0;
        break;

3407
    case VIR_DOMAIN_AFFECT_LIVE:
3408
        ret = qemudDomainHotplugVcpus(driver, vm, nvcpus);
3409 3410
        break;

3411
    case VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG:
3412
        ret = qemudDomainHotplugVcpus(driver, vm, nvcpus);
3413 3414 3415
        if (ret == 0) {
            persistentDef->vcpus = nvcpus;
        }
3416 3417
        break;
    }
3418

3419
    /* Save the persistent config to disk */
3420
    if (flags & VIR_DOMAIN_AFFECT_CONFIG)
3421 3422
        ret = virDomainSaveConfig(driver->configDir, persistentDef);

3423
endjob:
3424
    if (qemuDomainObjEndJob(driver, vm) == 0)
3425
        vm = NULL;
3426

3427
cleanup:
3428 3429
    if (vm)
        virDomainObjUnlock(vm);
3430
    return ret;
3431 3432
}

3433
static int
3434
qemuDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
3435
{
3436
    return qemuDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
3437 3438
}

3439 3440

static int
3441 3442 3443 3444 3445 3446
qemudDomainPinVcpuFlags(virDomainPtr dom,
                        unsigned int vcpu,
                        unsigned char *cpumap,
                        int maplen,
                        unsigned int flags) {

3447 3448
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3449
    virDomainDefPtr persistentDef = NULL;
3450
    int maxcpu, hostcpus;
3451
    virNodeInfo nodeinfo;
3452
    int ret = -1;
3453
    qemuDomainObjPrivatePtr priv;
3454
    bool canResetting = true;
E
Eric Blake 已提交
3455
    int pcpu;
3456

3457 3458 3459
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

3460
    qemuDriverLock(driver);
3461
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3462 3463
    qemuDriverUnlock(driver);

3464 3465 3466
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3467 3468
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
3469 3470 3471
        goto cleanup;
    }

3472 3473
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
3474
        goto cleanup;
3475

3476 3477 3478
    priv = vm->privateData;

    if (vcpu > (priv->nvcpupids-1)) {
3479 3480 3481
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("vcpu number out of range %d > %d"),
                        vcpu, priv->nvcpupids);
3482
        goto cleanup;
3483 3484
    }

3485 3486 3487 3488 3489 3490 3491 3492 3493
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
        goto cleanup;
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
    maxcpu = maplen * 8;
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
    /* pinning to all physical cpus means resetting,
     * so check if we can reset setting.
     */
E
Eric Blake 已提交
3494
    for (pcpu = 0; pcpu < hostcpus; pcpu++) {
3495 3496 3497 3498 3499
        if ((cpumap[pcpu/8] & (1 << (pcpu % 8))) == 0) {
            canResetting = false;
            break;
        }
    }
3500

3501
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3502 3503 3504 3505 3506 3507

        if (priv->vcpupids != NULL) {
            if (virProcessInfoSetAffinity(priv->vcpupids[vcpu],
                                          cpumap, maplen, maxcpu) < 0)
                goto cleanup;
        } else {
3508
            qemuReportError(VIR_ERR_OPERATION_INVALID,
3509 3510 3511 3512
                            "%s", _("cpu affinity is not supported"));
            goto cleanup;
        }

3513
        if (canResetting) {
E
Eric Blake 已提交
3514
            if (virDomainVcpuPinDel(vm->def, vcpu) < 0) {
3515 3516 3517 3518 3519 3520
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to delete vcpupin xml of "
                                  "a running domain"));
                goto cleanup;
            }
        } else {
E
Eric Blake 已提交
3521
            if (virDomainVcpuPinAdd(vm->def, cpumap, maplen, vcpu) < 0) {
3522 3523 3524 3525 3526
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to update or add vcpupin xml of "
                                  "a running domain"));
                goto cleanup;
            }
3527 3528
        }

3529 3530
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
            goto cleanup;
3531
    }
3532

3533 3534
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {

3535
        if (canResetting) {
E
Eric Blake 已提交
3536
            if (virDomainVcpuPinDel(persistentDef, vcpu) < 0) {
3537 3538 3539 3540 3541 3542
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to delete vcpupin xml of "
                                  "a persistent domain"));
                goto cleanup;
            }
        } else {
E
Eric Blake 已提交
3543
            if (virDomainVcpuPinAdd(persistentDef, cpumap, maplen, vcpu) < 0) {
3544 3545 3546 3547 3548
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to update or add vcpupin xml of "
                                  "a persistent domain"));
                goto cleanup;
            }
3549
        }
3550

3551
        ret = virDomainSaveConfig(driver->configDir, persistentDef);
3552 3553 3554
        goto cleanup;
    }

3555
    ret = 0;
3556

3557
cleanup:
3558 3559
    if (vm)
        virDomainObjUnlock(vm);
3560
    return ret;
3561 3562
}

3563 3564 3565 3566 3567 3568 3569 3570 3571
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
    return qemudDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

3572
static int
E
Eric Blake 已提交
3573
qemudDomainGetVcpuPinInfo(virDomainPtr dom,
3574 3575 3576 3577 3578 3579
                          int ncpumaps,
                          unsigned char *cpumaps,
                          int maplen,
                          unsigned int flags) {

    struct qemud_driver *driver = dom->conn->privateData;
E
Eric Blake 已提交
3580
    virDomainObjPtr vm = NULL;
3581 3582 3583 3584 3585
    virNodeInfo nodeinfo;
    virDomainDefPtr targetDef = NULL;
    int ret = -1;
    int maxcpu, hostcpus, vcpu, pcpu;
    int n;
E
Eric Blake 已提交
3586
    virDomainVcpuPinDefPtr *vcpupin_list;
3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604
    char *cpumask = NULL;
    unsigned char *cpumap;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

3605 3606 3607
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &targetDef) < 0)
        goto cleanup;
3608 3609 3610 3611 3612

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        targetDef = vm->def;
    }

3613 3614 3615
    /* Coverity didn't realize that targetDef must be set if we got here.  */
    sa_assert(targetDef);

3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
        goto cleanup;
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
    maxcpu = maplen * 8;
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;

    /* Clamp to actual number of vcpus */
    if (ncpumaps > targetDef->vcpus)
        ncpumaps = targetDef->vcpus;

    if (ncpumaps < 1) {
        goto cleanup;
    }

    /* initialize cpumaps */
    memset(cpumaps, 0xff, maplen * ncpumaps);
    if (maxcpu % 8) {
        for (vcpu = 0; vcpu < ncpumaps; vcpu++) {
            cpumap = VIR_GET_CPUMAP(cpumaps, maplen, vcpu);
            cpumap[maplen - 1] &= (1 << maxcpu % 8) - 1;
        }
    }

    /* if vcpupin setting exists, there are unused physical cpus */
    for (n = 0; n < targetDef->cputune.nvcpupin; n++) {
        vcpupin_list = targetDef->cputune.vcpupin;
        vcpu = vcpupin_list[n]->vcpuid;
        cpumask = vcpupin_list[n]->cpumask;
        cpumap = VIR_GET_CPUMAP(cpumaps, maplen, vcpu);
        for (pcpu = 0; pcpu < maxcpu; pcpu++) {
            if (cpumask[pcpu] == 0)
                VIR_UNUSE_CPU(cpumap, pcpu);
        }
    }
    ret = ncpumaps;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

3659 3660 3661 3662 3663 3664
static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
3665 3666
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3667
    virNodeInfo nodeinfo;
3668
    int i, v, maxcpu, hostcpus;
3669
    int ret = -1;
3670
    qemuDomainObjPrivatePtr priv;
3671

3672
    qemuDriverLock(driver);
3673
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3674 3675
    qemuDriverUnlock(driver);

3676 3677 3678
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3679 3680
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
3681 3682 3683
        goto cleanup;
    }

D
Daniel P. Berrange 已提交
3684
    if (!virDomainObjIsActive(vm)) {
3685 3686 3687
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s",
                        _("cannot list vcpu pinning for an inactive domain"));
3688
        goto cleanup;
3689 3690
    }

3691 3692
    priv = vm->privateData;

3693
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
3694
        goto cleanup;
3695

3696
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
3697
    maxcpu = maplen * 8;
3698 3699
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
3700 3701

    /* Clamp to actual number of vcpus */
3702 3703
    if (maxinfo > priv->nvcpupids)
        maxinfo = priv->nvcpupids;
3704

3705 3706 3707 3708 3709 3710
    if (maxinfo >= 1) {
        if (info != NULL) {
            memset(info, 0, sizeof(*info) * maxinfo);
            for (i = 0 ; i < maxinfo ; i++) {
                info[i].number = i;
                info[i].state = VIR_VCPU_RUNNING;
3711

3712
                if (priv->vcpupids != NULL &&
3713 3714 3715
                    qemudGetProcessInfo(&(info[i].cpuTime),
                                        &(info[i].cpu),
                                        vm->pid,
3716
                                        priv->vcpupids[i]) < 0) {
3717
                    virReportSystemError(errno, "%s",
3718 3719 3720
                                         _("cannot get vCPU placement & pCPU time"));
                    goto cleanup;
                }
3721
            }
3722 3723
        }

3724 3725
        if (cpumaps != NULL) {
            memset(cpumaps, 0, maplen * maxinfo);
3726
            if (priv->vcpupids != NULL) {
3727 3728 3729
                for (v = 0 ; v < maxinfo ; v++) {
                    unsigned char *cpumap = VIR_GET_CPUMAP(cpumaps, maplen, v);

3730
                    if (virProcessInfoGetAffinity(priv->vcpupids[v],
3731
                                                  cpumap, maplen, maxcpu) < 0)
3732
                        goto cleanup;
3733
                }
3734
            } else {
3735
                qemuReportError(VIR_ERR_OPERATION_INVALID,
3736
                                "%s", _("cpu affinity is not available"));
3737
                goto cleanup;
3738 3739 3740
            }
        }
    }
3741
    ret = maxinfo;
3742

3743
cleanup:
3744 3745
    if (vm)
        virDomainObjUnlock(vm);
3746
    return ret;
3747 3748 3749
}


3750 3751 3752
static int
qemudDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
3753 3754
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3755
    virDomainDefPtr def;
3756
    int ret = -1;
3757

3758 3759
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
3760 3761
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

3762
    qemuDriverLock(driver);
3763
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3764 3765
    qemuDriverUnlock(driver);

3766
    if (!vm) {
3767 3768
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3769 3770
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
3771
        goto cleanup;
3772 3773
    }

3774 3775
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags, &def) < 0)
        goto cleanup;
3776

3777
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3778
        def = vm->def;
3779 3780
    }

3781
    ret = (flags & VIR_DOMAIN_VCPU_MAXIMUM) ? def->maxvcpus : def->vcpus;
3782

3783
cleanup:
3784 3785
    if (vm)
        virDomainObjUnlock(vm);
3786 3787 3788
    return ret;
}

3789 3790 3791
static int
qemudDomainGetMaxVcpus(virDomainPtr dom)
{
3792
    return qemudDomainGetVcpusFlags(dom, (VIR_DOMAIN_AFFECT_LIVE |
3793 3794 3795
                                          VIR_DOMAIN_VCPU_MAXIMUM));
}

3796 3797 3798 3799 3800 3801 3802 3803 3804
static int qemudDomainGetSecurityLabel(virDomainPtr dom, virSecurityLabelPtr seclabel)
{
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

3805 3806
    memset(seclabel, 0, sizeof(*seclabel));

3807 3808 3809
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3810 3811
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
3812 3813 3814
        goto cleanup;
    }

3815
    if (!virDomainVirtTypeToString(vm->def->virtType)) {
3816 3817 3818
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unknown virt type in domain definition '%d'"),
                        vm->def->virtType);
3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835
        goto cleanup;
    }

    /*
     * Theoretically, the pid can be replaced during this operation and
     * return the label of a different process.  If atomicity is needed,
     * further validation will be required.
     *
     * Comment from Dan Berrange:
     *
     *   Well the PID as stored in the virDomainObjPtr can't be changed
     *   because you've got a locked object.  The OS level PID could have
     *   exited, though and in extreme circumstances have cycled through all
     *   PIDs back to ours. We could sanity check that our PID still exists
     *   after reading the label, by checking that our FD connecting to the
     *   QEMU monitor hasn't seen SIGHUP/ERR on poll().
     */
D
Daniel P. Berrange 已提交
3836
    if (virDomainObjIsActive(vm)) {
3837
        if (virSecurityManagerGetProcessLabel(driver->securityManager,
3838
                                              vm->def, vm->pid, seclabel) < 0) {
3839 3840 3841
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("Failed to get security label"));
            goto cleanup;
3842 3843 3844 3845 3846 3847 3848 3849
        }
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
3850
    qemuDriverUnlock(driver);
3851 3852 3853
    return ret;
}

3854 3855
static int qemudNodeGetSecurityModel(virConnectPtr conn,
                                     virSecurityModelPtr secmodel)
3856 3857 3858
{
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
    char *p;
3859
    int ret = 0;
3860

3861
    qemuDriverLock(driver);
3862 3863 3864 3865 3866
    memset(secmodel, 0, sizeof(*secmodel));

    /* NULL indicates no driver, which we treat as
     * success, but simply return no data in *secmodel */
    if (driver->caps->host.secModel.model == NULL)
3867
        goto cleanup;
3868

3869 3870
    p = driver->caps->host.secModel.model;
    if (strlen(p) >= VIR_SECURITY_MODEL_BUFLEN-1) {
3871 3872 3873
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security model string exceeds max %d bytes"),
                        VIR_SECURITY_MODEL_BUFLEN-1);
3874 3875
        ret = -1;
        goto cleanup;
3876 3877 3878 3879 3880
    }
    strcpy(secmodel->model, p);

    p = driver->caps->host.secModel.doi;
    if (strlen(p) >= VIR_SECURITY_DOI_BUFLEN-1) {
3881 3882 3883
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security DOI string exceeds max %d bytes"),
                        VIR_SECURITY_DOI_BUFLEN-1);
3884 3885
        ret = -1;
        goto cleanup;
3886 3887
    }
    strcpy(secmodel->doi, p);
3888 3889 3890 3891

cleanup:
    qemuDriverUnlock(driver);
    return ret;
3892 3893
}

E
Eric Blake 已提交
3894
/* Return -1 on most failures after raising error, -2 if edit was specified
3895 3896 3897
 * but xmlin and state (-1 for no change, 0 for paused, 1 for running) do
 * not represent any changes (no error raised), -3 if corrupt image was
 * unlinked (no error raised), and opened fd on success.  */
3898
static int ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4)
3899 3900 3901
qemuDomainSaveImageOpen(struct qemud_driver *driver,
                        const char *path,
                        virDomainDefPtr *ret_def,
3902
                        struct qemud_save_header *ret_header,
3903
                        bool bypass_cache, virFileDirectFdPtr *directFd,
3904 3905
                        const char *xmlin, int state, bool edit,
                        bool unlink_corrupt)
J
Jiri Denemark 已提交
3906 3907
{
    int fd;
3908
    struct qemud_save_header header;
J
Jiri Denemark 已提交
3909 3910
    char *xml = NULL;
    virDomainDefPtr def = NULL;
3911
    int oflags = edit ? O_RDWR : O_RDONLY;
3912

3913
    if (bypass_cache) {
3914
        int directFlag = virFileDirectFdFlag();
3915 3916 3917 3918 3919
        if (directFlag < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("bypass cache unsupported by this system"));
            goto error;
        }
3920
        oflags |= directFlag;
3921
    }
3922

E
Eric Blake 已提交
3923 3924
    if ((fd = qemuOpenFile(driver, path, oflags, NULL, NULL)) < 0)
        goto error;
3925 3926
    if (bypass_cache && (*directFd = virFileDirectFdNew(&fd, path)) == NULL)
        goto error;
3927 3928

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
3929 3930 3931 3932 3933 3934 3935 3936 3937
        if (unlink_corrupt) {
            if (VIR_CLOSE(fd) < 0 || unlink(path) < 0) {
                virReportSystemError(errno,
                                     _("cannot remove corrupt file: %s"),
                                     path);
                goto error;
            }
            return -3;
        }
3938 3939
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read qemu header"));
J
Jiri Denemark 已提交
3940
        goto error;
3941 3942 3943
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
E
Eric Blake 已提交
3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959
        const char *msg = _("image magic is incorrect");

        if (memcmp(header.magic, QEMUD_SAVE_PARTIAL,
                   sizeof(header.magic)) == 0) {
            msg = _("save image is incomplete");
            if (unlink_corrupt) {
                if (VIR_CLOSE(fd) < 0 || unlink(path) < 0) {
                    virReportSystemError(errno,
                                         _("cannot remove corrupt file: %s"),
                                         path);
                    goto error;
                }
                return -3;
            }
        }
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s", msg);
J
Jiri Denemark 已提交
3960
        goto error;
3961 3962 3963
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3964 3965 3966 3967 3968
        /* convert endianess and try again */
        bswap_header(&header);
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3969 3970 3971
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("image version is not supported (%d > %d)"),
                        header.version, QEMUD_SAVE_VERSION);
J
Jiri Denemark 已提交
3972
        goto error;
3973 3974
    }

3975 3976 3977
    if (header.xml_len <= 0) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("invalid XML length: %d"), header.xml_len);
J
Jiri Denemark 已提交
3978
        goto error;
3979 3980
    }

3981 3982
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
        virReportOOMError();
J
Jiri Denemark 已提交
3983
        goto error;
3984 3985 3986
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
3987 3988
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read XML"));
J
Jiri Denemark 已提交
3989
        goto error;
3990 3991
    }

3992 3993
    if (edit && STREQ(xml, xmlin) &&
        (state < 0 || state == header.was_running)) {
3994 3995 3996 3997 3998 3999 4000
        VIR_FREE(xml);
        if (VIR_CLOSE(fd) < 0) {
            virReportSystemError(errno, _("cannot close file: %s"), path);
            goto error;
        }
        return -2;
    }
4001 4002
    if (state >= 0)
        header.was_running = state;
4003

4004
    /* Create a domain from this XML */
4005
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
4006
                                        QEMU_EXPECTED_VIRT_TYPES,
4007
                                        VIR_DOMAIN_XML_INACTIVE)))
J
Jiri Denemark 已提交
4008
        goto error;
4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022
    if (xmlin) {
        virDomainDefPtr def2 = NULL;

        if (!(def2 = virDomainDefParseString(driver->caps, xmlin,
                                             QEMU_EXPECTED_VIRT_TYPES,
                                             VIR_DOMAIN_XML_INACTIVE)))
            goto error;
        if (!virDomainDefCheckABIStability(def, def2)) {
            virDomainDefFree(def2);
            goto error;
        }
        virDomainDefFree(def);
        def = def2;
    }
4023

J
Jiri Denemark 已提交
4024
    VIR_FREE(xml);
4025

J
Jiri Denemark 已提交
4026 4027
    *ret_def = def;
    *ret_header = header;
4028

J
Jiri Denemark 已提交
4029
    return fd;
4030

J
Jiri Denemark 已提交
4031 4032 4033
error:
    virDomainDefFree(def);
    VIR_FREE(xml);
4034
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
4035 4036 4037 4038

    return -1;
}

4039 4040 4041 4042 4043 4044
static int ATTRIBUTE_NONNULL(4) ATTRIBUTE_NONNULL(5) ATTRIBUTE_NONNULL(6)
qemuDomainSaveImageStartVM(virConnectPtr conn,
                           struct qemud_driver *driver,
                           virDomainObjPtr vm,
                           int *fd,
                           const struct qemud_save_header *header,
4045 4046
                           const char *path,
                           bool start_paused)
J
Jiri Denemark 已提交
4047 4048 4049 4050
{
    int ret = -1;
    virDomainEventPtr event;
    int intermediatefd = -1;
4051
    virCommandPtr cmd = NULL;
J
Jiri Denemark 已提交
4052 4053 4054

    if (header->version == 2) {
        const char *prog = qemudSaveCompressionTypeToString(header->compressed);
4055
        if (prog == NULL) {
4056 4057
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("Invalid compressed save format %d"),
J
Jiri Denemark 已提交
4058 4059
                            header->compressed);
            goto out;
4060
        }
4061

J
Jiri Denemark 已提交
4062
        if (header->compressed != QEMUD_SAVE_FORMAT_RAW) {
4063
            cmd = virCommandNewArgList(prog, "-dc", NULL);
4064 4065
            intermediatefd = *fd;
            *fd = -1;
4066 4067 4068 4069 4070

            virCommandSetInputFD(cmd, intermediatefd);
            virCommandSetOutputFD(cmd, fd);

            if (virCommandRunAsync(cmd, NULL) < 0) {
4071 4072
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Failed to start decompression binary %s"),
4073
                                prog);
4074
                *fd = intermediatefd;
J
Jiri Denemark 已提交
4075
                goto out;
4076 4077 4078
            }
        }
    }
J
Jiri Denemark 已提交
4079

4080
    /* Set the migration source and start it up. */
4081
    ret = qemuProcessStart(conn, driver, vm, "stdio", true,
4082
                           false, *fd, path, NULL, VIR_NETDEV_VPORT_PROFILE_OP_RESTORE);
J
Jiri Denemark 已提交
4083

4084
    if (intermediatefd != -1) {
4085
        if (ret < 0) {
4086 4087 4088
            /* if there was an error setting up qemu, the intermediate
             * process will wait forever to write to stdout, so we
             * must manually kill it.
4089 4090
             */
            VIR_FORCE_CLOSE(intermediatefd);
4091
            VIR_FORCE_CLOSE(*fd);
4092 4093
        }

4094 4095
        if (virCommandWait(cmd, NULL) < 0)
            ret = -1;
4096
    }
4097
    VIR_FORCE_CLOSE(intermediatefd);
J
Jiri Denemark 已提交
4098

4099 4100 4101
    if (VIR_CLOSE(*fd) < 0) {
        virReportSystemError(errno, _("cannot close file: %s"), path);
        ret = -1;
4102
    }
J
Jiri Denemark 已提交
4103

4104
    if (ret < 0) {
4105
        virDomainAuditStart(vm, "restored", false);
J
Jiri Denemark 已提交
4106
        goto out;
4107
    }
4108

4109 4110 4111
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
4112
    virDomainAuditStart(vm, "restored", true);
J
Jiri Denemark 已提交
4113 4114 4115
    if (event)
        qemuDomainEventQueue(driver, event);

4116

4117 4118
    /* If it was running before, resume it now unless caller requested pause. */
    if (header->was_running && !start_paused) {
J
Jiri Denemark 已提交
4119
        if (qemuProcessStartCPUs(driver, vm, conn,
4120 4121
                                 VIR_DOMAIN_RUNNING_RESTORED,
                                 QEMU_ASYNC_JOB_NONE) < 0) {
4122
            if (virGetLastError() == NULL)
4123 4124
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("failed to resume domain"));
J
Jiri Denemark 已提交
4125
            goto out;
4126
        }
4127 4128
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
J
Jiri Denemark 已提交
4129
            goto out;
4130
        }
4131 4132 4133 4134 4135 4136 4137 4138
    } else {
        int detail = (start_paused ? VIR_DOMAIN_EVENT_SUSPENDED_PAUSED :
                      VIR_DOMAIN_EVENT_SUSPENDED_RESTORED);
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         detail);
        if (event)
            qemuDomainEventQueue(driver, event);
4139
    }
J
Jiri Denemark 已提交
4140

4141
    ret = 0;
4142

J
Jiri Denemark 已提交
4143
out:
4144
    virCommandFree(cmd);
4145
    if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
4146
                                                 vm->def, path) < 0)
4147 4148
        VIR_WARN("failed to restore save state label on %s", path);

J
Jiri Denemark 已提交
4149 4150 4151
    return ret;
}

4152
static int
4153 4154 4155 4156
qemuDomainRestoreFlags(virConnectPtr conn,
                       const char *path,
                       const char *dxml,
                       unsigned int flags)
4157
{
J
Jiri Denemark 已提交
4158 4159 4160 4161 4162 4163
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    int fd = -1;
    int ret = -1;
    struct qemud_save_header header;
4164
    virFileDirectFdPtr directFd = NULL;
4165
    int state = -1;
J
Jiri Denemark 已提交
4166

4167 4168 4169
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
                  VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
4170

J
Jiri Denemark 已提交
4171 4172
    qemuDriverLock(driver);

4173 4174 4175 4176 4177
    if (flags & VIR_DOMAIN_SAVE_RUNNING)
        state = 1;
    else if (flags & VIR_DOMAIN_SAVE_PAUSED)
        state = 0;

4178 4179
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header,
                                 (flags & VIR_DOMAIN_SAVE_BYPASS_CACHE) != 0,
4180
                                 &directFd, dxml, state, false, false);
J
Jiri Denemark 已提交
4181 4182 4183 4184 4185 4186 4187 4188 4189
    if (fd < 0)
        goto cleanup;

    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
        goto cleanup;

    if (!(vm = virDomainAssignDef(driver->caps,
                                  &driver->domains,
                                  def, true))) {
4190
        /* virDomainAssignDef already set the error */
J
Jiri Denemark 已提交
4191 4192 4193 4194
        goto cleanup;
    }
    def = NULL;

4195
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
J
Jiri Denemark 已提交
4196 4197
        goto cleanup;

4198 4199
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path,
                                     false);
4200 4201
    if (virFileDirectFdClose(directFd) < 0)
        VIR_WARN("Failed to close %s", path);
J
Jiri Denemark 已提交
4202

4203
    if (qemuDomainObjEndJob(driver, vm) == 0)
4204
        vm = NULL;
J
Jiri Denemark 已提交
4205
    else if (ret < 0 && !vm->persistent) {
4206
        qemuDomainRemoveInactive(driver, vm);
J
Jiri Denemark 已提交
4207 4208
        vm = NULL;
    }
4209

4210 4211
cleanup:
    virDomainDefFree(def);
4212
    VIR_FORCE_CLOSE(fd);
4213
    virFileDirectFdFree(directFd);
4214 4215 4216
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
4217
    return ret;
D
Daniel P. Berrange 已提交
4218 4219
}

4220 4221 4222 4223 4224 4225 4226
static int
qemuDomainRestore(virConnectPtr conn,
                  const char *path)
{
    return qemuDomainRestoreFlags(conn, path, NULL, 0);
}

4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242
static char *
qemuDomainSaveImageGetXMLDesc(virConnectPtr conn, const char *path,
                              unsigned int flags)
{
    struct qemud_driver *driver = conn->privateData;
    char *ret = NULL;
    virDomainDefPtr def = NULL;
    int fd = -1;
    struct qemud_save_header header;

    /* We only take subset of virDomainDefFormat flags.  */
    virCheckFlags(VIR_DOMAIN_XML_SECURE, NULL);

    qemuDriverLock(driver);

    fd = qemuDomainSaveImageOpen(driver, path, &def, &header, false, NULL,
4243
                                 NULL, -1, false, false);
4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267

    if (fd < 0)
        goto cleanup;

    ret = qemuDomainDefFormatXML(driver, def, flags);

cleanup:
    virDomainDefFree(def);
    VIR_FORCE_CLOSE(fd);
    qemuDriverUnlock(driver);
    return ret;
}

static int
qemuDomainSaveImageDefineXML(virConnectPtr conn, const char *path,
                             const char *dxml, unsigned int flags)
{
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;
    virDomainDefPtr def = NULL;
    int fd = -1;
    struct qemud_save_header header;
    char *xml = NULL;
    size_t len;
4268
    int state = -1;
4269

4270 4271
    virCheckFlags(VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
4272 4273 4274

    qemuDriverLock(driver);

4275 4276 4277 4278 4279
    if (flags & VIR_DOMAIN_SAVE_RUNNING)
        state = 1;
    else if (flags & VIR_DOMAIN_SAVE_PAUSED)
        state = 0;

4280
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header, false, NULL,
4281
                                 dxml, state, true, false);
4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305

    if (fd < 0) {
        /* Check for special case of no change needed.  */
        if (fd == -2)
            ret = 0;
        goto cleanup;
    }

    xml = qemuDomainDefFormatXML(driver, def, (VIR_DOMAIN_XML_INACTIVE |
                                               VIR_DOMAIN_XML_SECURE));
    if (!xml)
        goto cleanup;
    len = strlen(xml) + 1;

    if (len > header.xml_len) {
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("new xml too large to fit in file"));
        goto cleanup;
    }
    if (VIR_EXPAND_N(xml, len, header.xml_len - len) < 0) {
        virReportOOMError();
        goto cleanup;
    }

4306
    if (lseek(fd, 0, SEEK_SET) != 0) {
4307 4308 4309
        virReportSystemError(errno, _("cannot seek in '%s'"), path);
        goto cleanup;
    }
4310 4311
    if (safewrite(fd, &header, sizeof(header)) != sizeof(header) ||
        safewrite(fd, xml, len) != len ||
4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326
        VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("failed to write xml to '%s'"), path);
        goto cleanup;
    }

    ret = 0;

cleanup:
    virDomainDefFree(def);
    VIR_FORCE_CLOSE(fd);
    VIR_FREE(xml);
    qemuDriverUnlock(driver);
    return ret;
}

E
Eric Blake 已提交
4327 4328
/* Return 0 on success, 1 if incomplete saved image was silently unlinked,
 * and -1 on failure with error raised.  */
4329 4330 4331 4332
static int
qemuDomainObjRestore(virConnectPtr conn,
                     struct qemud_driver *driver,
                     virDomainObjPtr vm,
4333
                     const char *path,
4334
                     bool start_paused,
4335
                     bool bypass_cache)
J
Jiri Denemark 已提交
4336 4337 4338 4339 4340
{
    virDomainDefPtr def = NULL;
    int fd = -1;
    int ret = -1;
    struct qemud_save_header header;
4341
    virFileDirectFdPtr directFd = NULL;
J
Jiri Denemark 已提交
4342

4343
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header,
4344 4345
                                 bypass_cache, &directFd, NULL, -1, false,
                                 true);
E
Eric Blake 已提交
4346 4347 4348
    if (fd < 0) {
        if (fd == -3)
            ret = 1;
J
Jiri Denemark 已提交
4349
        goto cleanup;
E
Eric Blake 已提交
4350
    }
J
Jiri Denemark 已提交
4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368

    if (STRNEQ(vm->def->name, def->name) ||
        memcmp(vm->def->uuid, def->uuid, VIR_UUID_BUFLEN)) {
        char vm_uuidstr[VIR_UUID_STRING_BUFLEN];
        char def_uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(vm->def->uuid, vm_uuidstr);
        virUUIDFormat(def->uuid, def_uuidstr);
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("cannot restore domain '%s' uuid %s from a file"
                          " which belongs to domain '%s' uuid %s"),
                        vm->def->name, vm_uuidstr,
                        def->name, def_uuidstr);
        goto cleanup;
    }

    virDomainObjAssignDef(vm, def, true);
    def = NULL;

4369 4370
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path,
                                     start_paused);
4371 4372
    if (virFileDirectFdClose(directFd) < 0)
        VIR_WARN("Failed to close %s", path);
J
Jiri Denemark 已提交
4373 4374 4375

cleanup:
    virDomainDefFree(def);
4376
    VIR_FORCE_CLOSE(fd);
4377
    virFileDirectFdFree(directFd);
J
Jiri Denemark 已提交
4378 4379 4380
    return ret;
}

D
Daniel P. Berrange 已提交
4381

4382
static char *qemuDomainGetXMLDesc(virDomainPtr dom,
4383 4384
                                  unsigned int flags)
{
4385 4386 4387
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;
4388
    unsigned long balloon;
4389
    int err = 0;
4390

4391
    /* Flags checked by virDomainDefFormat */
4392

4393
    qemuDriverLock(driver);
4394
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4395

D
Daniel P. Berrange 已提交
4396
    if (!vm) {
4397 4398
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4399 4400
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4401
        goto cleanup;
D
Daniel P. Berrange 已提交
4402 4403
    }

4404 4405 4406 4407
    /* Refresh current memory based on balloon info if supported */
    if ((vm->def->memballoon != NULL) &&
        (vm->def->memballoon->model != VIR_DOMAIN_MEMBALLOON_MODEL_NONE) &&
        (virDomainObjIsActive(vm))) {
4408
        qemuDomainObjPrivatePtr priv = vm->privateData;
4409 4410
        /* Don't delay if someone's using the monitor, just use
         * existing most recent data instead */
4411
        if (qemuDomainJobAllowed(priv, QEMU_JOB_QUERY)) {
4412
            if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_QUERY) < 0)
4413 4414
                goto cleanup;

4415 4416 4417 4418 4419 4420
            if (!virDomainObjIsActive(vm)) {
                qemuReportError(VIR_ERR_OPERATION_INVALID,
                                "%s", _("domain is not running"));
                goto endjob;
            }

4421
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
4422
            err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
4423
            qemuDomainObjExitMonitorWithDriver(driver, vm);
4424 4425

endjob:
4426
            if (qemuDomainObjEndJob(driver, vm) == 0) {
4427 4428 4429
                vm = NULL;
                goto cleanup;
            }
4430 4431 4432
            if (err < 0)
                goto cleanup;
            if (err > 0)
4433
                vm->def->mem.cur_balloon = balloon;
4434 4435
            /* err == 0 indicates no balloon support, so ignore it */
        }
4436
    }
4437

4438
    ret = qemuDomainFormatXML(driver, vm, flags);
4439 4440

cleanup:
4441 4442
    if (vm)
        virDomainObjUnlock(vm);
4443
    qemuDriverUnlock(driver);
4444
    return ret;
D
Daniel P. Berrange 已提交
4445 4446 4447
}


4448 4449 4450
static char *qemuDomainXMLFromNative(virConnectPtr conn,
                                     const char *format,
                                     const char *config,
E
Eric Blake 已提交
4451 4452
                                     unsigned int flags)
{
4453
    struct qemud_driver *driver = conn->privateData;
4454 4455 4456
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
4457 4458
    virCheckFlags(0, NULL);

4459
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
4460 4461
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
4462 4463 4464
        goto cleanup;
    }

4465
    qemuDriverLock(driver);
4466 4467
    def = qemuParseCommandLineString(driver->caps, config,
                                     NULL, NULL, NULL);
4468
    qemuDriverUnlock(driver);
4469 4470 4471
    if (!def)
        goto cleanup;

4472 4473 4474 4475 4476 4477
    if (!def->name &&
        !(def->name = strdup("unnamed"))) {
        virReportOOMError();
        goto cleanup;
    }

4478
    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
4479 4480 4481 4482 4483 4484

cleanup:
    virDomainDefFree(def);
    return xml;
}

4485 4486 4487
static char *qemuDomainXMLToNative(virConnectPtr conn,
                                   const char *format,
                                   const char *xmlData,
E
Eric Blake 已提交
4488 4489
                                   unsigned int flags)
{
4490 4491
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
4492
    virDomainChrSourceDef monConfig;
4493
    virBitmapPtr qemuCaps = NULL;
T
tangchen 已提交
4494
    bool monitor_json = false;
E
Eric Blake 已提交
4495
    virCommandPtr cmd = NULL;
4496 4497 4498
    char *ret = NULL;
    int i;

E
Eric Blake 已提交
4499 4500
    virCheckFlags(0, NULL);

4501 4502
    qemuDriverLock(driver);

4503
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
4504 4505
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
4506 4507 4508
        goto cleanup;
    }

M
Matthias Bolte 已提交
4509 4510
    def = virDomainDefParseString(driver->caps, xmlData,
                                  QEMU_EXPECTED_VIRT_TYPES, 0);
4511 4512 4513
    if (!def)
        goto cleanup;

4514 4515
    /* Since we're just exporting args, we can't do bridge/network/direct
     * setups, since libvirt will normally create TAP/macvtap devices
4516 4517 4518 4519 4520
     * directly. We convert those configs into generic 'ethernet'
     * config and assume the user has suitable 'ifup-qemu' scripts
     */
    for (i = 0 ; i < def->nnets ; i++) {
        virDomainNetDefPtr net = def->nets[i];
4521
        int bootIndex = net->info.bootIndex;
4522 4523 4524 4525
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            int actualType = virDomainNetGetActualType(net);
            const char *brname;

4526
            VIR_FREE(net->data.network.name);
4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541
            VIR_FREE(net->data.network.portgroup);
            if ((actualType == VIR_DOMAIN_NET_TYPE_BRIDGE) &&
                (brname = virDomainNetGetActualBridgeName(net))) {

                char *brnamecopy = strdup(brname);
                if (!brnamecopy) {
                    virReportOOMError();
                    goto cleanup;
                }

                virDomainActualNetDefFree(net->data.network.actual);

                memset(net, 0, sizeof *net);

                net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
4542
                net->script = NULL;
4543 4544 4545 4546 4547 4548 4549 4550 4551 4552
                net->data.ethernet.dev = brnamecopy;
                net->data.ethernet.ipaddr = NULL;
            } else {
                /* actualType is either NETWORK or DIRECT. In either
                 * case, the best we can do is NULL everything out.
                 */
                virDomainActualNetDefFree(net->data.network.actual);
                memset(net, 0, sizeof *net);

                net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
4553
                net->script = NULL;
4554 4555 4556 4557 4558 4559
                net->data.ethernet.dev = NULL;
                net->data.ethernet.ipaddr = NULL;
            }
        } else if (net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
            VIR_FREE(net->data.direct.linkdev);
            VIR_FREE(net->data.direct.virtPortProfile);
4560 4561 4562 4563

            memset(net, 0, sizeof *net);

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
4564
            net->script = NULL;
4565 4566 4567
            net->data.ethernet.dev = NULL;
            net->data.ethernet.ipaddr = NULL;
        } else if (net->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
4568
            char *script = net->script;
4569 4570 4571 4572 4573 4574
            char *brname = net->data.bridge.brname;
            char *ipaddr = net->data.bridge.ipaddr;

            memset(net, 0, sizeof *net);

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
4575
            net->script = script;
4576 4577 4578
            net->data.ethernet.dev = brname;
            net->data.ethernet.ipaddr = ipaddr;
        }
4579
        net->info.bootIndex = bootIndex;
4580 4581 4582 4583
    }
    for (i = 0 ; i < def->ngraphics ; i++) {
        if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
            def->graphics[i]->data.vnc.autoport)
4584
            def->graphics[i]->data.vnc.port = QEMU_VNC_PORT_MIN;
4585 4586
    }

4587
    if (qemuCapsExtractVersionInfo(def->emulator, def->os.arch,
4588
                                   NULL,
4589
                                   &qemuCaps) < 0)
4590 4591
        goto cleanup;

T
tangchen 已提交
4592 4593
    monitor_json = qemuCapsGet(qemuCaps, QEMU_CAPS_MONITOR_JSON);

4594
    if (qemuProcessPrepareMonitorChr(driver, &monConfig, def->name) < 0)
4595
        goto cleanup;
4596

4597 4598 4599
    if (qemuAssignDeviceAliases(def, qemuCaps) < 0)
        goto cleanup;

4600
    if (!(cmd = qemuBuildCommandLine(conn, driver, def,
T
tangchen 已提交
4601
                                     &monConfig, monitor_json, qemuCaps,
4602
                                     NULL, -1, NULL, VIR_NETDEV_VPORT_PROFILE_OP_NO_OP)))
4603 4604
        goto cleanup;

E
Eric Blake 已提交
4605
    ret = virCommandToString(cmd);
4606 4607

cleanup:
4608
    qemuDriverUnlock(driver);
4609

4610
    qemuCapsFree(qemuCaps);
E
Eric Blake 已提交
4611
    virCommandFree(cmd);
4612 4613 4614 4615 4616
    virDomainDefFree(def);
    return ret;
}


4617
static int qemudListDefinedDomains(virConnectPtr conn,
4618
                            char **const names, int nnames) {
4619
    struct qemud_driver *driver = conn->privateData;
4620
    int n;
4621

4622
    qemuDriverLock(driver);
4623
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
4624
    qemuDriverUnlock(driver);
4625
    return n;
D
Daniel P. Berrange 已提交
4626 4627
}

4628
static int qemudNumDefinedDomains(virConnectPtr conn) {
4629
    struct qemud_driver *driver = conn->privateData;
4630
    int n;
4631

4632
    qemuDriverLock(driver);
4633
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
4634
    qemuDriverUnlock(driver);
4635

4636
    return n;
D
Daniel P. Berrange 已提交
4637 4638 4639
}


4640 4641 4642 4643
static int
qemuDomainObjStart(virConnectPtr conn,
                   struct qemud_driver *driver,
                   virDomainObjPtr vm,
4644
                   unsigned int flags)
J
Jiri Denemark 已提交
4645 4646 4647
{
    int ret = -1;
    char *managed_save;
4648 4649 4650 4651
    bool start_paused = (flags & VIR_DOMAIN_START_PAUSED) != 0;
    bool autodestroy = (flags & VIR_DOMAIN_START_AUTODESTROY) != 0;
    bool bypass_cache = (flags & VIR_DOMAIN_START_BYPASS_CACHE) != 0;
    bool force_boot = (flags & VIR_DOMAIN_START_FORCE_BOOT) != 0;
J
Jiri Denemark 已提交
4652 4653 4654

    /*
     * If there is a managed saved state restore it instead of starting
4655
     * from scratch. The old state is removed once the restoring succeeded.
J
Jiri Denemark 已提交
4656 4657
     */
    managed_save = qemuDomainManagedSavePath(driver, vm);
4658 4659 4660 4661

    if (!managed_save)
        goto cleanup;

E
Eric Blake 已提交
4662
    if (virFileExists(managed_save)) {
4663 4664 4665 4666 4667 4668 4669 4670 4671
        if (force_boot) {
            if (unlink(managed_save) < 0) {
                virReportSystemError(errno,
                                     _("cannot remove managed save file %s"),
                                     managed_save);
                goto cleanup;
            }
        } else {
            ret = qemuDomainObjRestore(conn, driver, vm, managed_save,
4672
                                       start_paused, bypass_cache);
J
Jiri Denemark 已提交
4673

E
Eric Blake 已提交
4674
            if (ret == 0 && unlink(managed_save) < 0)
4675
                VIR_WARN("Failed to remove the managed state %s", managed_save);
E
Eric Blake 已提交
4676 4677 4678 4679
            if (ret > 0)
                VIR_WARN("Ignoring incomplete managed state %s", managed_save);
            else
                goto cleanup;
4680
        }
J
Jiri Denemark 已提交
4681 4682
    }

4683
    ret = qemuProcessStart(conn, driver, vm, NULL, start_paused,
4684
                           autodestroy, -1, NULL, NULL, VIR_NETDEV_VPORT_PROFILE_OP_CREATE);
4685
    virDomainAuditStart(vm, "booted", ret >= 0);
4686
    if (ret >= 0) {
J
Jiri Denemark 已提交
4687 4688 4689 4690
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
4691
        if (event) {
J
Jiri Denemark 已提交
4692
            qemuDomainEventQueue(driver, event);
4693 4694 4695 4696 4697 4698 4699 4700
            if (start_paused) {
                event = virDomainEventNewFromObj(vm,
                                                 VIR_DOMAIN_EVENT_SUSPENDED,
                                                 VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
                if (event)
                    qemuDomainEventQueue(driver, event);
            }
        }
J
Jiri Denemark 已提交
4701 4702 4703 4704 4705 4706 4707
    }

cleanup:
    VIR_FREE(managed_save);
    return ret;
}

4708
static int
4709
qemuDomainStartWithFlags(virDomainPtr dom, unsigned int flags)
4710
{
4711 4712 4713
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
4714

4715
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
4716
                  VIR_DOMAIN_START_AUTODESTROY |
4717 4718
                  VIR_DOMAIN_START_BYPASS_CACHE |
                  VIR_DOMAIN_START_FORCE_BOOT, -1);
4719

4720
    qemuDriverLock(driver);
4721
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4722

4723
    if (!vm) {
4724 4725
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4726 4727
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4728
        goto cleanup;
4729 4730
    }

4731
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
4732 4733 4734
        goto cleanup;

    if (virDomainObjIsActive(vm)) {
4735 4736
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is already running"));
4737 4738 4739
        goto endjob;
    }

4740
    if (qemuDomainObjStart(dom->conn, driver, vm, flags) < 0)
4741 4742 4743
        goto endjob;

    ret = 0;
4744

4745
endjob:
4746
    if (qemuDomainObjEndJob(driver, vm) == 0)
4747
        vm = NULL;
4748

4749
cleanup:
4750 4751
    if (vm)
        virDomainObjUnlock(vm);
4752
    qemuDriverUnlock(driver);
4753
    return ret;
D
Daniel P. Berrange 已提交
4754 4755
}

4756
static int
4757
qemuDomainStart(virDomainPtr dom)
4758
{
4759
    return qemuDomainStartWithFlags(dom, 0);
4760 4761
}

4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776
static int
qemudCanonicalizeMachineFromInfo(virDomainDefPtr def,
                                 virCapsGuestDomainInfoPtr info,
                                 char **canonical)
{
    int i;

    *canonical = NULL;

    for (i = 0; i < info->nmachines; i++) {
        virCapsGuestMachinePtr machine = info->machines[i];

        if (!machine->canonical)
            continue;

4777
        if (def->os.machine && STRNEQ(def->os.machine, machine->name))
4778 4779 4780
            continue;

        if (!(*canonical = strdup(machine->canonical))) {
4781
            virReportOOMError();
4782 4783 4784 4785 4786 4787 4788 4789 4790
            return -1;
        }

        break;
    }

    return 0;
}

4791 4792 4793 4794 4795 4796
static int
qemudCanonicalizeMachineDirect(virDomainDefPtr def, char **canonical)
{
    virCapsGuestMachinePtr *machines = NULL;
    int i, nmachines = 0;

4797
    if (qemuCapsProbeMachineTypes(def->emulator, &machines, &nmachines) < 0)
4798 4799 4800 4801 4802 4803
        return -1;

    for (i = 0; i < nmachines; i++) {
        if (!machines[i]->canonical)
            continue;

4804
        if (def->os.machine && STRNEQ(def->os.machine, machines[i]->name))
4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816
            continue;

        *canonical = machines[i]->canonical;
        machines[i]->canonical = NULL;
        break;
    }

    virCapabilitiesFreeMachines(machines, nmachines);

    return 0;
}

4817 4818
int
qemudCanonicalizeMachine(struct qemud_driver *driver, virDomainDefPtr def)
4819 4820 4821 4822 4823 4824
{
    char *canonical = NULL;
    int i;

    for (i = 0; i < driver->caps->nguests; i++) {
        virCapsGuestPtr guest = driver->caps->guests[i];
4825
        virCapsGuestDomainInfoPtr info;
4826 4827 4828
        int j;

        for (j = 0; j < guest->arch.ndomains; j++) {
4829
            info = &guest->arch.domains[j]->info;
4830

4831 4832 4833 4834 4835 4836 4837 4838 4839
            if (!info->emulator || !STREQ(info->emulator, def->emulator))
                continue;

            if (!info->nmachines)
                info = &guest->arch.defaultInfo;

            if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
                return -1;
            goto out;
4840 4841
        }

4842 4843 4844 4845
        info = &guest->arch.defaultInfo;

        if (info->emulator && STREQ(info->emulator, def->emulator)) {
            if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
4846 4847 4848 4849
                return -1;
            goto out;
        }
    }
4850 4851 4852 4853

    if (qemudCanonicalizeMachineDirect(def, &canonical) < 0)
        return -1;

4854 4855 4856 4857 4858 4859 4860
out:
    if (canonical) {
        VIR_FREE(def->os.machine);
        def->os.machine = canonical;
    }
    return 0;
}
D
Daniel P. Berrange 已提交
4861

4862
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
4863
    struct qemud_driver *driver = conn->privateData;
4864
    virDomainDefPtr def;
4865
    virDomainObjPtr vm = NULL;
4866
    virDomainPtr dom = NULL;
4867
    virDomainEventPtr event = NULL;
4868
    int dupVM;
4869

4870
    qemuDriverLock(driver);
4871
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
4872
                                        QEMU_EXPECTED_VIRT_TYPES,
4873
                                        VIR_DOMAIN_XML_INACTIVE)))
4874
        goto cleanup;
4875

4876
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
4877 4878
        goto cleanup;

4879 4880
    if ((dupVM = virDomainObjIsDuplicate(&driver->domains, def, 0)) < 0)
        goto cleanup;
4881

4882
    if (qemudCanonicalizeMachine(driver, def) < 0)
4883 4884
        goto cleanup;

4885
    if (qemuDomainAssignAddresses(def) < 0)
4886 4887
        goto cleanup;

4888
    if (!(vm = virDomainAssignDef(driver->caps,
4889
                                  &driver->domains,
4890
                                  def, false))) {
4891
        goto cleanup;
4892
    }
4893
    def = NULL;
4894
    vm->persistent = 1;
4895

4896
    if (virDomainSaveConfig(driver->configDir,
4897
                            vm->newDef ? vm->newDef : vm->def) < 0) {
4898
        VIR_INFO("Defining domain '%s'", vm->def->name);
4899
        qemuDomainRemoveInactive(driver, vm);
4900
        vm = NULL;
4901
        goto cleanup;
4902 4903
    }

4904 4905
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
4906
                                     !dupVM ?
4907 4908
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
4909

4910
    VIR_INFO("Creating domain '%s'", vm->def->name);
4911
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
4912
    if (dom) dom->id = vm->def->id;
4913 4914

cleanup:
4915
    virDomainDefFree(def);
4916 4917
    if (vm)
        virDomainObjUnlock(vm);
4918 4919
    if (event)
        qemuDomainEventQueue(driver, event);
4920
    qemuDriverUnlock(driver);
4921
    return dom;
D
Daniel P. Berrange 已提交
4922 4923
}

4924 4925
static int
qemuDomainUndefineFlags(virDomainPtr dom,
4926
                        unsigned int flags)
4927
{
4928 4929
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4930
    virDomainEventPtr event = NULL;
4931
    char *name = NULL;
4932
    int ret = -1;
4933
    int nsnapshots;
D
Daniel P. Berrange 已提交
4934

4935 4936
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE |
                  VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA, -1);
4937

4938
    qemuDriverLock(driver);
4939
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4940

D
Daniel P. Berrange 已提交
4941
    if (!vm) {
4942 4943
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4944 4945
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4946
        goto cleanup;
D
Daniel P. Berrange 已提交
4947 4948
    }

4949 4950 4951 4952 4953 4954
    if (!vm->persistent) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot undefine transient domain"));
        goto cleanup;
    }

4955 4956
    if (!virDomainObjIsActive(vm) &&
        (nsnapshots = virDomainSnapshotObjListNum(&vm->snapshots, 0))) {
4957
        if (!(flags & VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA)) {
4958 4959 4960 4961 4962 4963
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            _("cannot delete inactive domain with %d "
                              "snapshots"),
                            nsnapshots);
            goto cleanup;
        }
4964
        if (qemuDomainSnapshotDiscardAllMetadata(driver, vm) < 0)
4965
            goto cleanup;
4966 4967
    }

4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987
    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("Failed to remove domain managed "
                                  "save image"));
                goto cleanup;
            }
        } else {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("Refusing to undefine while domain managed "
                              "save image exists"));
            goto cleanup;
        }
    }

4988
    if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
4989
        goto cleanup;
D
Daniel P. Berrange 已提交
4990

4991 4992 4993
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
4994

4995
    VIR_INFO("Undefining domain '%s'", vm->def->name);
4996 4997 4998 4999 5000 5001 5002 5003

    /* If the domain is active, keep it running but set it as transient.
     * domainDestroy and domainShutdown will take care of removing the
     * domain obj from the hash table.
     */
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
5004
        qemuDomainRemoveInactive(driver, vm);
5005 5006 5007
        vm = NULL;
    }

5008
    ret = 0;
D
Daniel P. Berrange 已提交
5009

5010
cleanup:
5011
    VIR_FREE(name);
5012 5013
    if (vm)
        virDomainObjUnlock(vm);
5014 5015
    if (event)
        qemuDomainEventQueue(driver, event);
5016
    qemuDriverUnlock(driver);
5017
    return ret;
D
Daniel P. Berrange 已提交
5018 5019
}

5020 5021 5022 5023 5024 5025
static int
qemudDomainUndefine(virDomainPtr dom)
{
    return qemuDomainUndefineFlags(dom, 0);
}

5026
static int
5027 5028
qemuDomainAttachDeviceDiskLive(virConnectPtr conn,
                               struct qemud_driver *driver,
5029
                               virDomainObjPtr vm,
5030
                               virDomainDeviceDefPtr dev)
5031 5032 5033 5034
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
    int ret = -1;
5035

5036
    if (disk->driverName != NULL && !STREQ(disk->driverName, "qemu")) {
5037
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055
                        _("unsupported driver name '%s' for disk '%s'"),
                        disk->driverName, disk->src);
        goto end;
    }

    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Unable to find cgroup for %s"),
                            vm->def->name);
            goto end;
        }
        if (qemuSetupDiskCgroup(driver, vm, cgroup, disk) < 0)
            goto end;
    }
    switch (disk->device)  {
    case VIR_DOMAIN_DISK_DEVICE_CDROM:
    case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
5056
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, false);
5057 5058
        break;
    case VIR_DOMAIN_DISK_DEVICE_DISK:
5059
    case VIR_DOMAIN_DISK_DEVICE_LUN:
5060
        if (disk->bus == VIR_DOMAIN_DISK_BUS_USB)
5061
            ret = qemuDomainAttachUsbMassstorageDevice(conn, driver, vm,
5062
                                                       disk);
5063
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
5064
            ret = qemuDomainAttachPciDiskDevice(conn, driver, vm, disk);
5065
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
5066
            ret = qemuDomainAttachSCSIDisk(conn, driver, vm, disk);
5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092
        else
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                            _("disk bus '%s' cannot be hotplugged."),
                            virDomainDiskBusTypeToString(disk->bus));
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("disk device type '%s' cannot be hotplugged"),
                        virDomainDiskDeviceTypeToString(disk->device));
        break;
    }

    if (ret != 0 && cgroup) {
        if (qemuTeardownDiskCgroup(driver, vm, cgroup, disk) < 0)
            VIR_WARN("Failed to teardown cgroup for disk path %s",
                     NULLSTR(disk->src));
    }
end:
    if (cgroup)
        virCgroupFree(&cgroup);
    return ret;
}

static int
qemuDomainAttachDeviceControllerLive(struct qemud_driver *driver,
                                     virDomainObjPtr vm,
5093
                                     virDomainDeviceDefPtr dev)
5094 5095 5096 5097 5098 5099
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
5100
        ret = qemuDomainAttachPciControllerDevice(driver, vm, cont);
5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("disk controller bus '%s' cannot be hotplugged."),
                        virDomainControllerTypeToString(cont->type));
        break;
    }
    return ret;
}

static int
qemuDomainAttachDeviceLive(virDomainObjPtr vm,
                           virDomainDeviceDefPtr dev,
5114
                           virDomainPtr dom)
5115 5116 5117 5118 5119 5120
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
5121
        qemuDomainObjCheckDiskTaint(driver, vm, dev->data.disk, -1);
5122
        ret = qemuDomainAttachDeviceDiskLive(dom->conn, driver, vm, dev);
5123 5124 5125 5126 5127
        if (!ret)
            dev->data.disk = NULL;
        break;

    case VIR_DOMAIN_DEVICE_CONTROLLER:
5128
        ret = qemuDomainAttachDeviceControllerLive(driver, vm, dev);
5129 5130 5131 5132
        if (!ret)
            dev->data.controller = NULL;
        break;

5133 5134 5135 5136 5137 5138 5139
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainAttachLease(driver, vm,
                                    dev->data.lease);
        if (ret == 0)
            dev->data.lease = NULL;
        break;

5140
    case VIR_DOMAIN_DEVICE_NET:
5141
        qemuDomainObjCheckNetTaint(driver, vm, dev->data.net, -1);
5142
        ret = qemuDomainAttachNetDevice(dom->conn, driver, vm,
5143
                                        dev->data.net);
5144 5145 5146 5147 5148 5149
        if (!ret)
            dev->data.net = NULL;
        break;

    case VIR_DOMAIN_DEVICE_HOSTDEV:
        ret = qemuDomainAttachHostDevice(driver, vm,
5150
                                         dev->data.hostdev);
5151 5152 5153 5154
        if (!ret)
            dev->data.hostdev = NULL;
        break;

5155 5156 5157 5158 5159 5160 5161
    case VIR_DOMAIN_DEVICE_REDIRDEV:
        ret = qemuDomainAttachRedirdevDevice(driver, vm,
                                             dev->data.redirdev);
        if (!ret)
            dev->data.redirdev = NULL;
        break;

5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("device type '%s' cannot be attached"),
                        virDomainDeviceTypeToString(dev->type));
        break;
    }

    return ret;
}

static int
qemuDomainDetachDeviceDiskLive(struct qemud_driver *driver,
                               virDomainObjPtr vm,
5175
                               virDomainDeviceDefPtr dev)
5176 5177 5178 5179 5180 5181
{
    virDomainDiskDefPtr disk = dev->data.disk;
    int ret = -1;

    switch (disk->device) {
    case VIR_DOMAIN_DISK_DEVICE_DISK:
5182
    case VIR_DOMAIN_DISK_DEVICE_LUN:
5183
        if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
5184
            ret = qemuDomainDetachPciDiskDevice(driver, vm, dev);
5185
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
5186
            ret =  qemuDomainDetachDiskDevice(driver, vm, dev);
5187
        else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB)
5188
            ret = qemuDomainDetachDiskDevice(driver, vm, dev);
5189 5190 5191 5192 5193 5194
        else
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                            _("This type of disk cannot be hot unplugged"));
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5195 5196
                        _("disk device type '%s' cannot be detached"),
                        virDomainDiskDeviceTypeToString(disk->type));
5197 5198 5199 5200 5201 5202 5203 5204
        break;
    }
    return ret;
}

static int
qemuDomainDetachDeviceControllerLive(struct qemud_driver *driver,
                                     virDomainObjPtr vm,
5205
                                     virDomainDeviceDefPtr dev)
5206 5207 5208 5209 5210 5211
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
5212
        ret = qemuDomainDetachPciControllerDevice(driver, vm, dev);
5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224
        break;
    default :
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("disk controller bus '%s' cannot be hotunplugged."),
                        virDomainControllerTypeToString(cont->type));
    }
    return ret;
}

static int
qemuDomainDetachDeviceLive(virDomainObjPtr vm,
                           virDomainDeviceDefPtr dev,
5225
                           virDomainPtr dom)
5226 5227 5228 5229 5230 5231
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
5232
        ret = qemuDomainDetachDeviceDiskLive(driver, vm, dev);
5233 5234
        break;
    case VIR_DOMAIN_DEVICE_CONTROLLER:
5235
        ret = qemuDomainDetachDeviceControllerLive(driver, vm, dev);
5236
        break;
5237 5238 5239
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainDetachLease(driver, vm, dev->data.lease);
        break;
5240
    case VIR_DOMAIN_DEVICE_NET:
5241
        ret = qemuDomainDetachNetDevice(driver, vm, dev);
5242 5243
        break;
    case VIR_DOMAIN_DEVICE_HOSTDEV:
5244
        ret = qemuDomainDetachHostDevice(driver, vm, dev);
5245 5246 5247 5248 5249 5250 5251 5252 5253 5254
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        "%s", _("This type of device cannot be hot unplugged"));
        break;
    }

    return ret;
}

5255 5256 5257 5258 5259 5260 5261 5262
static int
qemuDomainChangeDiskMediaLive(virDomainObjPtr vm,
                              virDomainDeviceDefPtr dev,
                              struct qemud_driver *driver,
                              bool force)
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
5263
    int ret = -1;
5264 5265 5266

    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup,
5267
                               vm->def->name, &cgroup, 0) != 0) {
5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Unable to find cgroup for %s"),
                            vm->def->name);
            goto end;
        }
        if (qemuSetupDiskCgroup(driver, vm, cgroup, disk) < 0)
            goto end;
    }

    switch (disk->device) {
    case VIR_DOMAIN_DISK_DEVICE_CDROM:
    case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
5280
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, force);
5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312
        if (ret == 0)
            dev->data.disk = NULL;
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("disk bus '%s' cannot be updated."),
                        virDomainDiskBusTypeToString(disk->bus));
        break;
    }

    if (ret != 0 && cgroup) {
        if (qemuTeardownDiskCgroup(driver, vm, cgroup, disk) < 0)
             VIR_WARN("Failed to teardown cgroup for disk path %s",
                      NULLSTR(disk->src));
    }
end:
    if (cgroup)
        virCgroupFree(&cgroup);
    return ret;
}

static int
qemuDomainUpdateDeviceLive(virDomainObjPtr vm,
                           virDomainDeviceDefPtr dev,
                           virDomainPtr dom,
                           bool force)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
5313
        ret = qemuDomainChangeDiskMediaLive(vm, dev, driver, force);
5314 5315 5316 5317
        break;
    case VIR_DOMAIN_DEVICE_GRAPHICS:
        ret = qemuDomainChangeGraphics(driver, vm, dev->data.graphics);
        break;
5318 5319 5320
    case VIR_DOMAIN_DEVICE_NET:
        ret = qemuDomainChangeNet(driver, vm, dom, dev->data.net);
        break;
5321 5322 5323 5324 5325 5326 5327 5328 5329 5330
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("device type '%s' cannot be updated"),
                        virDomainDeviceTypeToString(dev->type));
        break;
    }

    return ret;
}

5331
static int
5332
qemuDomainAttachDeviceConfig(virDomainDefPtr vmdef,
5333 5334
                             virDomainDeviceDefPtr dev)
{
5335
    virDomainDiskDefPtr disk;
5336
    virDomainNetDefPtr net;
5337
    virDomainLeaseDefPtr lease;
5338

5339
    switch (dev->type) {
5340 5341
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
5342
        if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("target %s already exists."), disk->dst);
            return -1;
        }
        if (virDomainDiskInsert(vmdef, disk)) {
            virReportOOMError();
            return -1;
        }
        /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
        dev->data.disk = NULL;
        if (disk->bus != VIR_DOMAIN_DISK_BUS_VIRTIO)
            if (virDomainDefAddImplicitControllers(vmdef) < 0)
                return -1;
5356
        if (qemuDomainAssignAddresses(vmdef) < 0)
5357 5358 5359
            return -1;
        break;

5360 5361 5362 5363
    case VIR_DOMAIN_DEVICE_NET:
        net = dev->data.net;
        if (virDomainNetIndexByMac(vmdef, net->mac) >= 0) {
            char macbuf[VIR_MAC_STRING_BUFLEN];
5364
            virMacAddrFormat(net->mac, macbuf);
5365 5366 5367 5368 5369 5370 5371 5372 5373
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("mac %s already exists"), macbuf);
            return -1;
        }
        if (virDomainNetInsert(vmdef, net)) {
            virReportOOMError();
            return -1;
        }
        dev->data.net = NULL;
5374
        if (qemuDomainAssignAddresses(vmdef) < 0)
5375 5376
            return -1;
        break;
5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392

    case VIR_DOMAIN_DEVICE_LEASE:
        lease = dev->data.lease;
        if (virDomainLeaseIndex(vmdef, lease) >= 0) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Lease %s in lockspace %s already exists"),
                            lease->key, NULLSTR(lease->lockspace));
            return -1;
        }
        if (virDomainLeaseInsert(vmdef, lease) < 0)
            return -1;

        /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
        dev->data.lease = NULL;
        break;

5393 5394 5395 5396 5397 5398 5399 5400 5401 5402
    default:
         qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                         _("persistent attach of device is not supported"));
         return -1;
    }
    return 0;
}


static int
5403
qemuDomainDetachDeviceConfig(virDomainDefPtr vmdef,
5404 5405
                             virDomainDeviceDefPtr dev)
{
5406
    virDomainDiskDefPtr disk;
5407
    virDomainNetDefPtr net;
5408
    virDomainLeaseDefPtr lease;
5409

5410
    switch (dev->type) {
5411 5412 5413 5414 5415 5416 5417 5418
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
        if (virDomainDiskRemoveByName(vmdef, disk->dst)) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("no target device %s"), disk->dst);
            return -1;
        }
        break;
5419

5420 5421 5422 5423 5424
    case VIR_DOMAIN_DEVICE_NET:
        net = dev->data.net;
        if (virDomainNetRemoveByMac(vmdef, net->mac)) {
            char macbuf[VIR_MAC_STRING_BUFLEN];

5425
            virMacAddrFormat(net->mac, macbuf);
5426 5427 5428 5429 5430
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("no nic of mac %s"), macbuf);
            return -1;
        }
        break;
5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441

    case VIR_DOMAIN_DEVICE_LEASE:
        lease = dev->data.lease;
        if (virDomainLeaseRemove(vmdef, lease) < 0) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Lease %s in lockspace %s does not exist"),
                            lease->key, NULLSTR(lease->lockspace));
            return -1;
        }
        break;

5442 5443 5444 5445 5446 5447 5448 5449 5450
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("persistent detach of device is not supported"));
        return -1;
    }
    return 0;
}

static int
5451
qemuDomainUpdateDeviceConfig(virDomainDefPtr vmdef,
5452 5453
                             virDomainDeviceDefPtr dev)
{
5454
    virDomainDiskDefPtr orig, disk;
5455
    virDomainNetDefPtr net;
5456 5457
    int pos;

5458
    switch (dev->type) {
5459 5460
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
5461
        pos = virDomainDiskIndexByName(vmdef, disk->dst, false);
5462 5463
        if (pos < 0) {
            qemuReportError(VIR_ERR_INVALID_ARG,
5464
                            _("target %s doesn't exist."), disk->dst);
5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493
            return -1;
        }
        orig = vmdef->disks[pos];
        if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM) &&
            !(orig->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY)) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("this disk doesn't support update"));
            return -1;
        }
        /*
         * Update 'orig'
         * We allow updating src/type//driverType/cachemode/
         */
        VIR_FREE(orig->src);
        orig->src = disk->src;
        orig->type = disk->type;
        orig->cachemode = disk->cachemode;
        if (disk->driverName) {
            VIR_FREE(orig->driverName);
            orig->driverName = disk->driverName;
            disk->driverName = NULL;
        }
        if (disk->driverType) {
            VIR_FREE(orig->driverType);
            orig->driverType = disk->driverType;
            disk->driverType = NULL;
        }
        disk->src = NULL;
        break;
5494 5495 5496 5497 5498

    case VIR_DOMAIN_DEVICE_NET:
        net = dev->data.net;
        if ((pos = virDomainNetIndexByMac(vmdef, net->mac)) < 0) {
            char macbuf[VIR_MAC_STRING_BUFLEN];
5499
            virMacAddrFormat(net->mac, macbuf);
5500 5501 5502 5503 5504 5505 5506 5507 5508 5509
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("mac %s doesn't exist"), macbuf);
            return -1;
        }

        VIR_FREE(vmdef->nets[pos]);

        vmdef->nets[pos] = net;
        dev->data.net = NULL;

5510
        if (qemuDomainAssignAddresses(vmdef) < 0)
5511 5512 5513
            return -1;
        break;

5514 5515 5516 5517 5518 5519 5520 5521
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                         _("persistent update of device is not supported"));
        return -1;
    }
    return 0;
}

5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532
/* Actions for qemuDomainModifyDeviceFlags */
enum {
    QEMU_DEVICE_ATTACH,
    QEMU_DEVICE_DETACH,
    QEMU_DEVICE_UPDATE,
};


static int
qemuDomainModifyDeviceFlags(virDomainPtr dom, const char *xml,
                            unsigned int flags, int action)
5533
{
5534
    struct qemud_driver *driver = dom->conn->privateData;
5535
    virDomainObjPtr vm = NULL;
5536
    virDomainDefPtr vmdef = NULL;
5537
    virDomainDeviceDefPtr dev = NULL;
5538
    bool force = (flags & VIR_DOMAIN_DEVICE_MODIFY_FORCE) != 0;
5539
    int ret = -1;
5540
    unsigned int affect;
5541

5542 5543
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
5544 5545 5546
                  (action == QEMU_DEVICE_UPDATE ?
                   VIR_DOMAIN_DEVICE_MODIFY_FORCE : 0), -1);

5547 5548
    affect = flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG);

5549 5550 5551 5552 5553 5554 5555
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5556 5557 5558
        goto cleanup;
    }

5559
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
5560
        goto cleanup;
5561

5562
    if (virDomainObjIsActive(vm)) {
5563
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
5564
            flags |= VIR_DOMAIN_AFFECT_LIVE;
5565
    } else {
5566
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
5567
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
5568
        /* check consistency between flags and the vm state */
5569
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5570 5571 5572 5573 5574 5575
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s",
                            _("cannot do live update a device on "
                              "inactive domain"));
            goto endjob;
        }
5576
    }
5577

5578
    if ((flags & VIR_DOMAIN_AFFECT_CONFIG) && !vm->persistent) {
5579 5580 5581 5582
         qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("cannot modify device on transient domain"));
         goto endjob;
    }
5583

5584
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5585 5586 5587 5588 5589
        dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                      VIR_DOMAIN_XML_INACTIVE);
        if (dev == NULL)
            goto endjob;

5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608
        /* Make a copy for updated domain. */
        vmdef = virDomainObjCopyPersistentDef(driver->caps, vm);
        if (!vmdef)
            goto endjob;
        switch (action) {
        case QEMU_DEVICE_ATTACH:
            ret = qemuDomainAttachDeviceConfig(vmdef, dev);
            break;
        case QEMU_DEVICE_DETACH:
            ret = qemuDomainDetachDeviceConfig(vmdef, dev);
            break;
        case QEMU_DEVICE_UPDATE:
            ret = qemuDomainUpdateDeviceConfig(vmdef, dev);
            break;
        default:
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("unknown domain modify action %d"), action);
            break;
        }
5609

5610 5611 5612 5613 5614
        if (ret == -1)
            goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5615 5616 5617 5618
        /* If dev exists it was created to modify the domain config. Free it. */
        virDomainDeviceDefFree(dev);
        dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                      VIR_DOMAIN_XML_INACTIVE);
5619 5620
        if (dev == NULL) {
            ret = -1;
5621
            goto endjob;
5622
        }
5623

5624 5625
        switch (action) {
        case QEMU_DEVICE_ATTACH:
5626
            ret = qemuDomainAttachDeviceLive(vm, dev, dom);
5627 5628
            break;
        case QEMU_DEVICE_DETACH:
5629
            ret = qemuDomainDetachDeviceLive(vm, dev, dom);
5630 5631
            break;
        case QEMU_DEVICE_UPDATE:
5632
            ret = qemuDomainUpdateDeviceLive(vm, dev, dom, force);
5633 5634 5635 5636
            break;
        default:
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("unknown domain modify action %d"), action);
5637
            ret = -1;
5638 5639
            break;
        }
5640 5641 5642

        if (ret == -1)
            goto endjob;
5643 5644
        /*
         * update domain status forcibly because the domain status may be
5645 5646
         * changed even if we failed to attach the device. For example,
         * a new controller may be created.
5647
         */
5648
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
5649
            ret = -1;
5650 5651
            goto endjob;
        }
5652
    }
5653

5654
    /* Finally, if no error until here, we can save config. */
5655
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5656 5657 5658 5659 5660 5661
        ret = virDomainSaveConfig(driver->configDir, vmdef);
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false);
            vmdef = NULL;
        }
    }
5662 5663

endjob:
5664
    if (qemuDomainObjEndJob(driver, vm) == 0)
5665 5666 5667
        vm = NULL;

cleanup:
5668
    virDomainDefFree(vmdef);
5669 5670 5671 5672
    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
5673 5674 5675
    return ret;
}

5676 5677 5678 5679 5680 5681
static int qemuDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_ATTACH);
}

5682 5683 5684
static int qemuDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainAttachDeviceFlags(dom, xml,
5685
                                       VIR_DOMAIN_AFFECT_LIVE);
5686
}
5687

5688

5689 5690 5691 5692
static int qemuDomainUpdateDeviceFlags(virDomainPtr dom,
                                       const char *xml,
                                       unsigned int flags)
{
5693
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_UPDATE);
5694 5695
}

5696 5697 5698
static int qemuDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
5699
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_DETACH);
5700 5701
}

5702 5703 5704
static int qemuDomainDetachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainDetachDeviceFlags(dom, xml,
5705
                                       VIR_DOMAIN_AFFECT_LIVE);
5706 5707
}

5708
static int qemudDomainGetAutostart(virDomainPtr dom,
5709
                                   int *autostart) {
5710 5711 5712
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
5713

5714
    qemuDriverLock(driver);
5715
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5716 5717
    qemuDriverUnlock(driver);

5718
    if (!vm) {
5719 5720
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5721 5722
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5723
        goto cleanup;
5724 5725 5726
    }

    *autostart = vm->autostart;
5727
    ret = 0;
5728

5729
cleanup:
5730 5731
    if (vm)
        virDomainObjUnlock(vm);
5732
    return ret;
5733 5734
}

5735
static int qemudDomainSetAutostart(virDomainPtr dom,
5736
                                   int autostart) {
5737 5738
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
5739 5740
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
5741

5742
    qemuDriverLock(driver);
5743
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5744

5745
    if (!vm) {
5746 5747
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5748 5749
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5750
        goto cleanup;
5751 5752
    }

5753
    if (!vm->persistent) {
5754
        qemuReportError(VIR_ERR_OPERATION_INVALID,
5755
                        "%s", _("cannot set autostart for transient domain"));
5756
        goto cleanup;
5757 5758
    }

5759 5760
    autostart = (autostart != 0);

5761
    if (vm->autostart != autostart) {
5762
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
5763
            goto cleanup;
5764
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
5765
            goto cleanup;
5766

5767
        if (autostart) {
5768 5769
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
5770 5771
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
5772 5773
                goto cleanup;
            }
5774

5775
            if (symlink(configFile, autostartLink) < 0) {
5776
                virReportSystemError(errno,
5777 5778
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
5779 5780 5781 5782
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
5783
                virReportSystemError(errno,
5784 5785
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
5786 5787
                goto cleanup;
            }
5788 5789
        }

5790
        vm->autostart = autostart;
5791
    }
5792
    ret = 0;
5793

5794 5795 5796
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
5797 5798
    if (vm)
        virDomainObjUnlock(vm);
5799
    qemuDriverUnlock(driver);
5800
    return ret;
5801 5802
}

5803

5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836
/*
 * check whether the host supports CFS bandwidth
 *
 * Return 1 when CFS bandwidth is supported, 0 when CFS bandwidth is not
 * supported, -1 on error.
 */
static int qemuGetCpuBWStatus(virCgroupPtr cgroup)
{
    char *cfs_period_path = NULL;
    int ret = -1;

    if (!cgroup)
        return 0;

    if (virCgroupPathOfController(cgroup, VIR_CGROUP_CONTROLLER_CPU,
                                  "cpu.cfs_period_us", &cfs_period_path) < 0) {
        VIR_INFO("cannot get the path of cgroup CPU controller");
        ret = 0;
        goto cleanup;
    }

    if (access(cfs_period_path, F_OK) < 0) {
        ret = 0;
    } else {
        ret = 1;
    }

cleanup:
    VIR_FREE(cfs_period_path);
    return ret;
}


5837 5838 5839 5840
static char *qemuGetSchedulerType(virDomainPtr dom,
                                  int *nparams)
{
    struct qemud_driver *driver = dom->conn->privateData;
5841
    char *ret = NULL;
5842
    int rc;
5843

5844
    qemuDriverLock(driver);
5845
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
5846 5847
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup CPU controller is not mounted"));
5848
        goto cleanup;
5849 5850
    }

5851 5852 5853 5854 5855 5856 5857 5858 5859
    if (nparams) {
        rc = qemuGetCpuBWStatus(driver->cgroup);
        if (rc < 0)
            goto cleanup;
        else if (rc == 0)
            *nparams = 1;
        else
            *nparams = 3;
    }
5860 5861 5862

    ret = strdup("posix");
    if (!ret)
5863
        virReportOOMError();
5864 5865 5866

cleanup:
    qemuDriverUnlock(driver);
5867 5868 5869
    return ret;
}

5870 5871 5872 5873
/* deviceWeightStr in the form of /device/path,weight,/device/path,weight
 * for example, /dev/disk/by-path/pci-0000:00:1f.2-scsi-0:0:0:0,800
 */
static int
5874 5875
qemuDomainParseDeviceWeightStr(char *deviceWeightStr,
                               virBlkioDeviceWeightPtr *dw, size_t *size)
5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951
{
    char *temp;
    int ndevices = 0;
    int nsep = 0;
    int i;
    virBlkioDeviceWeightPtr result = NULL;

    temp = deviceWeightStr;
    while (temp) {
        temp = strchr(temp, ',');
        if (temp) {
            temp++;
            nsep++;
        }
    }

    /* A valid string must have even number of fields, hence an odd
     * number of commas.  */
    if (!(nsep & 1))
        goto error;

    ndevices = (nsep + 1) / 2;

    if (VIR_ALLOC_N(result, ndevices) < 0) {
        virReportOOMError();
        return -1;
    }

    i = 0;
    temp = deviceWeightStr;
    while (temp) {
        char *p = temp;

        /* device path */
        p = strchr(p, ',');
        if (!p)
            goto error;

        result[i].path = strndup(temp, p - temp);
        if (!result[i].path) {
            virReportOOMError();
            goto cleanup;
        }

        /* weight */
        temp = p + 1;

        if (virStrToLong_ui(temp, &p, 10, &result[i].weight) < 0)
            goto error;

        i++;

        if (*p == '\0')
            break;
        else if (*p != ',')
            goto error;
        temp = p + 1;
    }

    if (!i)
        VIR_FREE(result);

    *dw = result;
    *size = i;

    return 0;

error:
    qemuReportError(VIR_ERR_INVALID_ARG,
                    _("unable to parse %s"), deviceWeightStr);
cleanup:
    virBlkioDeviceWeightArrayClear(result, ndevices);
    VIR_FREE(result);
    return -1;
}

5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986
/* Modify def to reflect all device weight changes described in tmp.  */
static int
qemuDomainMergeDeviceWeights(virBlkioDeviceWeightPtr *def, size_t *def_size,
                             virBlkioDeviceWeightPtr tmp, size_t tmp_size)
{
    int i, j;
    virBlkioDeviceWeightPtr dw;

    for (i = 0; i < tmp_size; i++) {
        bool found = false;

        dw = &tmp[i];
        for (j = 0; j < *def_size; j++) {
            if (STREQ(dw->path, (*def)[j].path)) {
                found = true;
                (*def)[j].weight = dw->weight;
                break;
            }
        }
        if (!found) {
            if (!dw->weight)
                continue;
            if (VIR_EXPAND_N(*def, *def_size, 1) < 0) {
                virReportOOMError();
                return -1;
            }
            (*def)[*def_size - 1].path = dw->path;
            (*def)[*def_size - 1].weight = dw->weight;
            dw->path = NULL;
        }
    }

    return 0;
}

5987 5988 5989 5990 5991
static int
qemuDomainSetBlkioParameters(virDomainPtr dom,
                             virTypedParameterPtr params,
                             int nparams,
                             unsigned int flags)
5992 5993 5994 5995 5996
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5997
    virDomainDefPtr persistentDef = NULL;
5998 5999
    int ret = -1;

6000 6001
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6002 6003 6004 6005 6006 6007 6008
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_BLKIO_WEIGHT,
                                       VIR_TYPED_PARAM_UINT,
                                       VIR_DOMAIN_BLKIO_DEVICE_WEIGHT,
                                       VIR_TYPED_PARAM_STRING,
                                       NULL) < 0)
        return -1;
6009

6010
    qemuDriverLock(driver);
6011 6012 6013 6014 6015 6016 6017 6018
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (vm == NULL) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No such domain %s"), dom->uuid);
        goto cleanup;
    }

6019 6020 6021
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;
6022

6023 6024
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
6025 6026
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            _("blkio cgroup isn't mounted"));
6027 6028 6029 6030 6031
            goto cleanup;
        }

        if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
6032 6033
                            _("cannot find cgroup for domain %s"),
                            vm->def->name);
6034 6035 6036 6037
            goto cleanup;
        }
    }

6038
    ret = 0;
6039 6040
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        for (i = 0; i < nparams; i++) {
6041
            int rc;
6042 6043 6044 6045 6046 6047 6048 6049 6050
            virTypedParameterPtr param = &params[i];

            if (STREQ(param->field, VIR_DOMAIN_BLKIO_WEIGHT)) {
                if (params[i].value.ui > 1000 || params[i].value.ui < 100) {
                    qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                    _("out of blkio weight range."));
                    ret = -1;
                    continue;
                }
6051

6052 6053 6054 6055 6056 6057
                rc = virCgroupSetBlkioWeight(group, params[i].value.ui);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set blkio weight tunable"));
                    ret = -1;
                }
6058
            } else if (STREQ(param->field, VIR_DOMAIN_BLKIO_DEVICE_WEIGHT)) {
6059
                size_t ndevices;
6060
                virBlkioDeviceWeightPtr devices = NULL;
6061 6062
                int j;

6063 6064 6065
                if (qemuDomainParseDeviceWeightStr(params[i].value.s,
                                                   &devices,
                                                   &ndevices) < 0) {
6066 6067 6068
                    ret = -1;
                    continue;
                }
6069
                for (j = 0; j < ndevices; j++) {
6070
                    rc = virCgroupSetBlkioDeviceWeight(group,
6071 6072
                                                       devices[j].path,
                                                       devices[j].weight);
6073 6074 6075 6076
                    if (rc < 0) {
                        virReportSystemError(-rc,
                                             _("Unable to set io device weight "
                                               "for path %s"),
6077
                                             devices[j].path);
6078 6079 6080
                        break;
                    }
                }
6081 6082
                if (j != ndevices ||
                    qemuDomainMergeDeviceWeights(&vm->def->blkio.devices,
6083 6084 6085 6086 6087
                                                 &vm->def->blkio.ndevices,
                                                 devices, ndevices) < 0)
                    ret = -1;
                virBlkioDeviceWeightArrayClear(devices, ndevices);
                VIR_FREE(devices);
6088
            }
6089
        }
E
Eric Blake 已提交
6090 6091 6092 6093
    }
    if (ret < 0)
        goto cleanup;
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
6094 6095 6096
        /* Clang can't see that if we get here, persistentDef was set.  */
        sa_assert(persistentDef);

6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108
        for (i = 0; i < nparams; i++) {
            virTypedParameterPtr param = &params[i];

            if (STREQ(param->field, VIR_DOMAIN_BLKIO_WEIGHT)) {
                if (params[i].value.ui > 1000 || params[i].value.ui < 100) {
                    qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                    _("out of blkio weight range."));
                    ret = -1;
                    continue;
                }

                persistentDef->blkio.weight = params[i].value.ui;
6109 6110
            } else if (STREQ(param->field, VIR_DOMAIN_BLKIO_DEVICE_WEIGHT)) {
                virBlkioDeviceWeightPtr devices = NULL;
6111
                size_t ndevices;
6112

6113 6114 6115
                if (qemuDomainParseDeviceWeightStr(params[i].value.s,
                                                   &devices,
                                                   &ndevices) < 0) {
6116 6117 6118
                    ret = -1;
                    continue;
                }
6119 6120 6121 6122 6123 6124
                if (qemuDomainMergeDeviceWeights(&vm->def->blkio.devices,
                                                 &vm->def->blkio.ndevices,
                                                 devices, ndevices) < 0)
                    ret = -1;
                virBlkioDeviceWeightArrayClear(devices, ndevices);
                VIR_FREE(devices);
6125 6126
            }
        }
A
Alex Jia 已提交
6127 6128 6129

        if (virDomainSaveConfig(driver->configDir, persistentDef) < 0)
            ret = -1;
6130 6131 6132 6133 6134 6135 6136 6137 6138 6139
    }

cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

6140 6141 6142 6143 6144
static int
qemuDomainGetBlkioParameters(virDomainPtr dom,
                             virTypedParameterPtr params,
                             int *nparams,
                             unsigned int flags)
6145 6146
{
    struct qemud_driver *driver = dom->conn->privateData;
6147
    int i, j;
6148 6149
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6150
    virDomainDefPtr persistentDef = NULL;
6151 6152 6153 6154
    unsigned int val;
    int ret = -1;
    int rc;

6155
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
6156 6157
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);
6158 6159
    qemuDriverLock(driver);

6160 6161 6162
    /* We blindly return a string, and let libvirt.c and
     * remote_driver.c do the filtering on behalf of older clients
     * that can't parse it.  */
6163 6164
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (vm == NULL) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No such domain %s"), dom->uuid);
        goto cleanup;
    }

    if ((*nparams) == 0) {
        /* Current number of blkio parameters supported by cgroups */
        *nparams = QEMU_NB_BLKIO_PARAM;
        ret = 0;
        goto cleanup;
    }

6180 6181 6182
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;
6183

6184 6185
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
6186
            qemuReportError(VIR_ERR_OPERATION_INVALID, _("blkio cgroup isn't mounted"));
6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197
            goto cleanup;
        }

        if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot find cgroup for domain %s"), vm->def->name);
            goto cleanup;
        }
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6198
        for (i = 0; i < *nparams && i < QEMU_NB_BLKIO_PARAM; i++) {
6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209
            virTypedParameterPtr param = &params[i];
            val = 0;

            switch (i) {
            case 0: /* fill blkio weight here */
                rc = virCgroupGetBlkioWeight(group, &val);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to get blkio weight"));
                    goto cleanup;
                }
6210 6211
                if (virTypedParameterAssign(param, VIR_DOMAIN_BLKIO_WEIGHT,
                                            VIR_TYPED_PARAM_UINT, val) < 0)
6212 6213
                    goto cleanup;
                break;
6214 6215 6216 6217
            case 1: /* blkiotune.device_weight */
                if (vm->def->blkio.ndevices > 0) {
                    virBuffer buf = VIR_BUFFER_INITIALIZER;
                    bool comma = false;
6218

6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235
                    for (j = 0; j < vm->def->blkio.ndevices; j++) {
                        if (!vm->def->blkio.devices[j].weight)
                            continue;
                        if (comma)
                            virBufferAddChar(&buf, ',');
                        else
                            comma = true;
                        virBufferAsprintf(&buf, "%s,%u",
                                          vm->def->blkio.devices[j].path,
                                          vm->def->blkio.devices[j].weight);
                    }
                    if (virBufferError(&buf)) {
                        virReportOOMError();
                        goto cleanup;
                    }
                    param->value.s = virBufferContentAndReset(&buf);
                }
6236 6237 6238 6239
                if (virTypedParameterAssign(param,
                                            VIR_DOMAIN_BLKIO_DEVICE_WEIGHT,
                                            VIR_TYPED_PARAM_STRING,
                                            param->value.s) < 0)
6240 6241
                    goto cleanup;
                break;
6242 6243 6244 6245

            default:
                break;
                /* should not hit here */
6246
            }
6247 6248
        }
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6249
        for (i = 0; i < *nparams && i < QEMU_NB_BLKIO_PARAM; i++) {
6250 6251 6252 6253 6254 6255 6256 6257 6258
            virTypedParameterPtr param = &params[i];
            val = 0;
            param->value.ui = 0;
            param->type = VIR_TYPED_PARAM_UINT;

            switch (i) {
            case 0: /* fill blkio weight here */
                if (virStrcpyStatic(param->field, VIR_DOMAIN_BLKIO_WEIGHT) == NULL) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
6259 6260
                                    _("Field name '%s' too long"),
                                    VIR_DOMAIN_BLKIO_WEIGHT);
6261 6262 6263 6264
                    goto cleanup;
                }
                param->value.ui = persistentDef->blkio.weight;
                break;
6265

6266 6267 6268
            case 1: /* blkiotune.device_weight */
                if (persistentDef->blkio.ndevices > 0) {
                    virBuffer buf = VIR_BUFFER_INITIALIZER;
6269 6270
                    bool comma = false;

6271
                    for (j = 0; j < persistentDef->blkio.ndevices; j++) {
6272 6273 6274
                        if (!persistentDef->blkio.devices[j].weight)
                            continue;
                        if (comma)
6275
                            virBufferAddChar(&buf, ',');
6276 6277
                        else
                            comma = true;
6278 6279 6280 6281 6282 6283 6284 6285 6286
                        virBufferAsprintf(&buf, "%s,%u",
                                          persistentDef->blkio.devices[j].path,
                                          persistentDef->blkio.devices[j].weight);
                    }
                    if (virBufferError(&buf)) {
                        virReportOOMError();
                        goto cleanup;
                    }
                    param->value.s = virBufferContentAndReset(&buf);
6287 6288
                }
                if (!param->value.s) {
6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304
                    param->value.s = strdup("");
                    if (!param->value.s) {
                        virReportOOMError();
                        goto cleanup;
                    }
                }
                param->type = VIR_TYPED_PARAM_STRING;
                if (virStrcpyStatic(param->field,
                                    VIR_DOMAIN_BLKIO_DEVICE_WEIGHT) == NULL) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                    _("Field name '%s' too long"),
                                    VIR_DOMAIN_BLKIO_DEVICE_WEIGHT);
                    goto cleanup;
                }
                break;

6305 6306 6307 6308
            default:
                break;
                /* should not hit here */
            }
6309 6310 6311
        }
    }

6312 6313
    if (QEMU_NB_BLKIO_PARAM < *nparams)
        *nparams = QEMU_NB_BLKIO_PARAM;
6314 6315 6316 6317 6318 6319 6320 6321 6322 6323
    ret = 0;

cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
6324

6325 6326 6327 6328 6329
static int
qemuDomainSetMemoryParameters(virDomainPtr dom,
                              virTypedParameterPtr params,
                              int nparams,
                              unsigned int flags)
6330 6331 6332
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
6333
    virDomainDefPtr persistentDef = NULL;
6334 6335 6336
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;
6337
    int rc;
6338

6339 6340
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6341 6342 6343 6344 6345 6346 6347 6348 6349
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_MEMORY_HARD_LIMIT,
                                       VIR_TYPED_PARAM_ULLONG,
                                       VIR_DOMAIN_MEMORY_SOFT_LIMIT,
                                       VIR_TYPED_PARAM_ULLONG,
                                       VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT,
                                       VIR_TYPED_PARAM_ULLONG,
                                       NULL) < 0)
        return -1;
6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360

    qemuDriverLock(driver);

    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (vm == NULL) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No such domain %s"), dom->uuid);
        goto cleanup;
    }

6361 6362 6363
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;
6364

6365
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("cgroup memory controller is not mounted"));
            goto cleanup;
        }

        if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot find cgroup for domain %s"), vm->def->name);
            goto cleanup;
        }
    }

6379 6380
    ret = 0;
    for (i = 0; i < nparams; i++) {
6381
        virTypedParameterPtr param = &params[i];
6382 6383

        if (STREQ(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT)) {
6384
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6385 6386 6387 6388 6389 6390 6391 6392
                rc = virCgroupSetMemoryHardLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory hard_limit tunable"));
                    ret = -1;
                }
            }

6393
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6394
                persistentDef->mem.hard_limit = params[i].value.ul;
6395 6396
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT)) {
6397
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6398 6399 6400 6401 6402 6403 6404 6405
                rc = virCgroupSetMemorySoftLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory soft_limit tunable"));
                    ret = -1;
                }
            }

6406
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6407
                persistentDef->mem.soft_limit = params[i].value.ul;
6408
            }
6409
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT)) {
6410
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6411 6412 6413 6414 6415 6416 6417
                rc = virCgroupSetMemSwapHardLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set swap_hard_limit tunable"));
                    ret = -1;
                }
            }
6418
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6419
                persistentDef->mem.swap_hard_limit = params[i].value.ul;
6420 6421 6422 6423
            }
        }
    }

6424
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6425 6426
        if (virDomainSaveConfig(driver->configDir, persistentDef) < 0)
            ret = -1;
6427 6428
    }

6429 6430 6431 6432 6433 6434 6435 6436
cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

6437 6438 6439 6440 6441
static int
qemuDomainGetMemoryParameters(virDomainPtr dom,
                              virTypedParameterPtr params,
                              int *nparams,
                              unsigned int flags)
6442 6443 6444 6445 6446
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6447
    virDomainDefPtr persistentDef = NULL;
6448 6449 6450
    int ret = -1;
    int rc;

6451
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
6452 6453
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);
6454

6455
    qemuDriverLock(driver);
6456

6457 6458 6459
    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

6460 6461 6462 6463 6464 6465 6466 6467
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (vm == NULL) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No such domain %s"), dom->uuid);
        goto cleanup;
    }

6468 6469 6470
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;
6471

6472
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("cgroup memory controller is not mounted"));
            goto cleanup;
        }

        if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot find cgroup for domain %s"), vm->def->name);
            goto cleanup;
        }
    }

6486 6487 6488 6489 6490 6491 6492
    if ((*nparams) == 0) {
        /* Current number of memory parameters supported by cgroups */
        *nparams = QEMU_NB_MEM_PARAM;
        ret = 0;
        goto cleanup;
    }

6493
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6494
        for (i = 0; i < *nparams && i < QEMU_NB_MEM_PARAM; i++) {
6495 6496 6497 6498
            virMemoryParameterPtr param = &params[i];

            switch (i) {
            case 0: /* fill memory hard limit here */
6499 6500 6501 6502
                if (virTypedParameterAssign(param,
                                            VIR_DOMAIN_MEMORY_HARD_LIMIT,
                                            VIR_TYPED_PARAM_ULLONG,
                                            persistentDef->mem.hard_limit) < 0)
6503 6504 6505 6506
                    goto cleanup;
                break;

            case 1: /* fill memory soft limit here */
6507 6508 6509 6510
                if (virTypedParameterAssign(param,
                                            VIR_DOMAIN_MEMORY_SOFT_LIMIT,
                                            VIR_TYPED_PARAM_ULLONG,
                                            persistentDef->mem.soft_limit) < 0)
6511 6512 6513 6514
                    goto cleanup;
                break;

            case 2: /* fill swap hard limit here */
6515 6516 6517 6518
                if (virTypedParameterAssign(param,
                                            VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT,
                                            VIR_TYPED_PARAM_ULLONG,
                                            persistentDef->mem.swap_hard_limit) < 0)
6519 6520 6521 6522 6523 6524 6525 6526 6527
                    goto cleanup;
                break;

            default:
                break;
                /* should not hit here */
            }
        }
        goto out;
6528 6529
    }

6530
    for (i = 0; i < *nparams && i < QEMU_NB_MEM_PARAM; i++) {
6531
        virTypedParameterPtr param = &params[i];
6532
        unsigned long long val = 0;
6533

6534 6535 6536
        /* Coverity does not realize that if we get here, group is set.  */
        sa_assert(group);

6537
        switch (i) {
6538 6539 6540 6541 6542
        case 0: /* fill memory hard limit here */
            rc = virCgroupGetMemoryHardLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory hard limit"));
6543
                goto cleanup;
6544
            }
6545 6546 6547
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_MEMORY_HARD_LIMIT,
                                        VIR_TYPED_PARAM_ULLONG, val) < 0)
6548
                goto cleanup;
6549 6550 6551 6552 6553 6554 6555
            break;

        case 1: /* fill memory soft limit here */
            rc = virCgroupGetMemorySoftLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory soft limit"));
6556
                goto cleanup;
6557
            }
6558 6559 6560
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_MEMORY_SOFT_LIMIT,
                                        VIR_TYPED_PARAM_ULLONG, val) < 0)
6561
                goto cleanup;
6562 6563 6564
            break;

        case 2: /* fill swap hard limit here */
6565
            rc = virCgroupGetMemSwapHardLimit(group, &val);
6566 6567 6568
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get swap hard limit"));
6569
                goto cleanup;
6570
            }
6571 6572 6573
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT,
                                        VIR_TYPED_PARAM_ULLONG, val) < 0)
6574
                goto cleanup;
6575 6576 6577 6578 6579 6580 6581 6582
            break;

        default:
            break;
            /* should not hit here */
        }
    }

6583
out:
6584 6585
    if (QEMU_NB_MEM_PARAM < *nparams)
        *nparams = QEMU_NB_MEM_PARAM;
6586 6587
    ret = 0;

6588 6589 6590 6591 6592 6593 6594 6595 6596
cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611
static int
qemuDomainSetNumaParameters(virDomainPtr dom,
                            virTypedParameterPtr params,
                            int nparams,
                            unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virDomainDefPtr persistentDef = NULL;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6612 6613 6614 6615 6616 6617 6618
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_NUMA_MODE,
                                       VIR_TYPED_PARAM_INT,
                                       VIR_DOMAIN_NUMA_NODESET,
                                       VIR_TYPED_PARAM_STRING,
                                       NULL) < 0)
        return -1;
6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666

    qemuDriverLock(driver);

    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (vm == NULL) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No such domain %s"), dom->uuid);
        goto cleanup;
    }

    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPUSET)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("cgroup cpuset controller is not mounted"));
            goto cleanup;
        }

        if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot find cgroup for domain %s"),
                            vm->def->name);
            goto cleanup;
        }
    }

    ret = 0;
    for (i = 0; i < nparams; i++) {
        virTypedParameterPtr param = &params[i];

        if (STREQ(param->field, VIR_DOMAIN_NUMA_MODE)) {
            if ((flags & VIR_DOMAIN_AFFECT_LIVE) &&
                vm->def->numatune.memory.mode != params[i].value.i) {
                qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                _("can't change numa mode for running domain"));
                ret = -1;
                goto cleanup;
            }

            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
                persistentDef->numatune.memory.mode = params[i].value.i;
            }
        } else if (STREQ(param->field, VIR_DOMAIN_NUMA_NODESET)) {
            int rc;
H
Hu Tao 已提交
6667
            bool savedmask;
6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688
            char oldnodemask[VIR_DOMAIN_CPUMASK_LEN];

            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
                if (vm->def->numatune.memory.mode !=
                    VIR_DOMAIN_NUMATUNE_MEM_STRICT) {
                    qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                    _("change of nodeset for running domain "
                                      "requires strict numa mode"));
                    ret = -1;
                    continue;
                }
                rc = virCgroupSetCpusetMems(group, params[i].value.s);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set numa tunable"));
                    ret = -1;
                    continue;
                }

                /* update vm->def here so that dumpxml can read the new
                 * values from vm->def. */
H
Hu Tao 已提交
6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701
                savedmask = false;
                if (!vm->def->numatune.memory.nodemask) {
                    if (VIR_ALLOC_N(vm->def->numatune.memory.nodemask,
                                    VIR_DOMAIN_CPUMASK_LEN) < 0) {
                        virReportOOMError();
                        ret = -1;
                        goto cleanup;
                    }
                } else {
                    memcpy(oldnodemask, vm->def->numatune.memory.nodemask,
                           VIR_DOMAIN_CPUMASK_LEN);
                    savedmask = true;
                }
6702 6703 6704 6705
                if (virDomainCpuSetParse(params[i].value.s,
                                         0,
                                         vm->def->numatune.memory.nodemask,
                                         VIR_DOMAIN_CPUMASK_LEN) < 0) {
H
Hu Tao 已提交
6706 6707 6708 6709 6710
                    if (savedmask)
                        memcpy(vm->def->numatune.memory.nodemask,
                               oldnodemask, VIR_DOMAIN_CPUMASK_LEN);
                    else
                        VIR_FREE(vm->def->numatune.memory.nodemask);
6711 6712 6713 6714 6715 6716
                    ret = -1;
                    continue;
                }
            }

            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
H
Hu Tao 已提交
6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729
                savedmask = false;
                if (!persistentDef->numatune.memory.nodemask) {
                    if (VIR_ALLOC_N(persistentDef->numatune.memory.nodemask,
                                    VIR_DOMAIN_CPUMASK_LEN) < 0) {
                        virReportOOMError();
                        ret = -1;
                        goto cleanup;
                    }
                } else {
                    memcpy(oldnodemask, persistentDef->numatune.memory.nodemask,
                           VIR_DOMAIN_CPUMASK_LEN);
                    savedmask = true;
                }
6730 6731 6732 6733
                if (virDomainCpuSetParse(params[i].value.s,
                                         0,
                                         persistentDef->numatune.memory.nodemask,
                                         VIR_DOMAIN_CPUMASK_LEN) < 0) {
H
Hu Tao 已提交
6734 6735 6736 6737 6738
                    if (savedmask)
                        memcpy(persistentDef->numatune.memory.nodemask,
                               oldnodemask, VIR_DOMAIN_CPUMASK_LEN);
                    else
                        VIR_FREE(persistentDef->numatune.memory.nodemask);
6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822
                    ret = -1;
                    continue;
                }
            }
        }
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        if (virDomainSaveConfig(driver->configDir, persistentDef) < 0)
            ret = -1;
    }

cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

static int
qemuDomainGetNumaParameters(virDomainPtr dom,
                            virTypedParameterPtr params,
                            int *nparams,
                            unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr persistentDef = NULL;
    char *nodeset = NULL;
    int ret = -1;
    int rc;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);

    qemuDriverLock(driver);

    /* We blindly return a string, and let libvirt.c and
     * remote_driver.c do the filtering on behalf of older clients
     * that can't parse it.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (vm == NULL) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No such domain %s"), dom->uuid);
        goto cleanup;
    }

    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;

    if ((*nparams) == 0) {
        *nparams = QEMU_NB_NUMA_PARAM;
        ret = 0;
        goto cleanup;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("cgroup memory controller is not mounted"));
            goto cleanup;
        }

        if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot find cgroup for domain %s"),
                            vm->def->name);
            goto cleanup;
        }
    }

    for (i = 0; i < QEMU_NB_NUMA_PARAM && i < *nparams; i++) {
        virMemoryParameterPtr param = &params[i];

        switch (i) {
        case 0: /* fill numa mode here */
6823 6824
            if (virTypedParameterAssign(param, VIR_DOMAIN_NUMA_MODE,
                                        VIR_TYPED_PARAM_INT, 0) < 0)
6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847
                goto cleanup;
            if (flags & VIR_DOMAIN_AFFECT_CONFIG)
                param->value.i = persistentDef->numatune.memory.mode;
            else
                param->value.i = vm->def->numatune.memory.mode;
            break;

        case 1: /* fill numa nodeset here */
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
                char *mask = persistentDef->numatune.memory.nodemask;
                if (mask)
                    nodeset = virDomainCpuSetFormat(mask,
                                                    VIR_DOMAIN_CPUMASK_LEN);
                else
                    nodeset = strdup("");
            } else {
                rc = virCgroupGetCpusetMems(group, &nodeset);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to get numa nodeset"));
                    goto cleanup;
                }
            }
6848 6849
            if (virTypedParameterAssign(param, VIR_DOMAIN_NUMA_NODESET,
                                        VIR_TYPED_PARAM_STRING, nodeset) < 0)
6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870
                goto cleanup;
            break;

        default:
            break;
            /* should not hit here */
        }
    }

    if (*nparams > QEMU_NB_NUMA_PARAM)
        *nparams = QEMU_NB_NUMA_PARAM;
    ret = 0;

cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

6871 6872 6873 6874 6875 6876 6877 6878
static int
qemuSetVcpusBWLive(virDomainObjPtr vm, virCgroupPtr cgroup,
                   unsigned long long period, long long quota)
{
    int i;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virCgroupPtr cgroup_vcpu = NULL;
    int rc;
W
Wen Congyang 已提交
6879 6880 6881
    long long vm_quota = 0;
    long long old_quota = 0;
    unsigned long long old_period = 0;
6882 6883 6884 6885

    if (period == 0 && quota == 0)
        return 0;

W
Wen Congyang 已提交
6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904
    /* Ensure that we can multiply by vcpus without overflowing. */
    if (quota > LLONG_MAX / vm->def->vcpus) {
        virReportSystemError(EINVAL,
                             _("%s"),
                             "Unable to set cpu bandwidth quota");
        goto cleanup;
    }

    if (quota > 0)
        vm_quota = quota * vm->def->vcpus;
    else
        vm_quota = quota;

    rc = virCgroupGetCpuCfsQuota(cgroup, &old_quota);
    if (rc < 0) {
        virReportSystemError(-rc, "%s",
                             _("unable to get cpu bandwidth tunable"));
        goto cleanup;
    }
6905

W
Wen Congyang 已提交
6906 6907 6908 6909 6910
    rc = virCgroupGetCpuCfsPeriod(cgroup, &old_period);
    if (rc < 0) {
        virReportSystemError(-rc, "%s",
                             _("unable to get cpu bandwidth period tunable"));
        goto cleanup;
6911 6912
    }

W
Wen Congyang 已提交
6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933
    /*
     * If quota will be changed to a small value, we should modify vcpu's quota
     * first. Otherwise, we should modify vm's quota first.
     *
     * If period will be changed to a small value, we should modify vm's period
     * first. Otherwise, we should modify vcpu's period first.
     *
     * If both quota and period will be changed to a big/small value, we cannot
     * modify period and quota together.
     */
    if ((quota != 0) && (period != 0)) {
        if (((quota > old_quota) && (period > old_period)) ||
            ((quota < old_quota) && (period < old_period))) {
            /* modify period */
            if (qemuSetVcpusBWLive(vm, cgroup, period, 0) < 0)
                goto cleanup;

            /* modify quota */
            if (qemuSetVcpusBWLive(vm, cgroup, 0, quota) < 0)
                goto cleanup;
            return 0;
6934
        }
W
Wen Congyang 已提交
6935
    }
6936

W
Wen Congyang 已提交
6937 6938 6939 6940
    if (((vm_quota != 0) && (vm_quota > old_quota)) ||
        ((period != 0) && (period < old_period)))
        /* Set cpu bandwidth for the vm */
        if (qemuSetupCgroupVcpuBW(cgroup, period, vm_quota) < 0)
6941 6942
            goto cleanup;

W
Wen Congyang 已提交
6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962
    /* If we does not know VCPU<->PID mapping or all vcpu runs in the same
     * thread, we cannot control each vcpu. So we only modify cpu bandwidth
     * when each vcpu has a separated thread.
     */
    if (priv->nvcpupids != 0 && priv->vcpupids[0] != vm->pid) {
        for (i = 0; i < priv->nvcpupids; i++) {
            rc = virCgroupForVcpu(cgroup, i, &cgroup_vcpu, 0);
            if (rc < 0) {
                virReportSystemError(-rc,
                                     _("Unable to find vcpu cgroup for %s(vcpu:"
                                       " %d)"),
                                     vm->def->name, i);
                goto cleanup;
            }

            if (qemuSetupCgroupVcpuBW(cgroup_vcpu, period, quota) < 0)
                goto cleanup;

            virCgroupFree(&cgroup_vcpu);
        }
6963 6964
    }

W
Wen Congyang 已提交
6965 6966 6967 6968 6969 6970
    if (((vm_quota != 0) && (vm_quota <= old_quota)) ||
        ((period != 0) && (period >= old_period)))
        /* Set cpu bandwidth for the vm */
        if (qemuSetupCgroupVcpuBW(cgroup, period, vm_quota) < 0)
            goto cleanup;

6971 6972 6973 6974 6975 6976 6977
    return 0;

cleanup:
    virCgroupFree(&cgroup_vcpu);
    return -1;
}

6978 6979 6980 6981 6982
static int
qemuSetSchedulerParametersFlags(virDomainPtr dom,
                                virTypedParameterPtr params,
                                int nparams,
                                unsigned int flags)
6983 6984 6985 6986 6987
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6988
    virDomainDefPtr vmdef = NULL;
6989
    int ret = -1;
6990
    int rc;
6991

6992 6993
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6994 6995 6996 6997 6998 6999 7000 7001 7002
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_SCHEDULER_CPU_SHARES,
                                       VIR_TYPED_PARAM_ULLONG,
                                       VIR_DOMAIN_SCHEDULER_VCPU_PERIOD,
                                       VIR_TYPED_PARAM_ULLONG,
                                       VIR_DOMAIN_SCHEDULER_VCPU_QUOTA,
                                       VIR_TYPED_PARAM_LLONG,
                                       NULL) < 0)
        return -1;
7003

7004
    qemuDriverLock(driver);
7005 7006 7007 7008

    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (vm == NULL) {
7009 7010
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No such domain %s"), dom->uuid);
7011 7012 7013
        goto cleanup;
    }

7014 7015 7016
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &vmdef) < 0)
        goto cleanup;
7017

7018 7019 7020 7021 7022
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        /* Make a copy for updated domain. */
        vmdef = virDomainObjCopyPersistentDef(driver->caps, vm);
        if (!vmdef)
            goto cleanup;
7023 7024
    }

7025
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("cgroup CPU controller is not mounted"));
            goto cleanup;
        }
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot find cgroup for domain %s"),
                            vm->def->name);
            goto cleanup;
        }
    }

7039
    for (i = 0; i < nparams; i++) {
7040
        virTypedParameterPtr param = &params[i];
7041

7042
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CPU_SHARES)) {
7043
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7044 7045 7046 7047 7048 7049 7050 7051
                rc = virCgroupSetCpuShares(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set cpu shares tunable"));
                    goto cleanup;
                }

                vm->def->cputune.shares = params[i].value.ul;
7052
            }
7053

7054
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
7055 7056
                vmdef->cputune.shares = params[i].value.ul;
            }
7057
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_VCPU_PERIOD)) {
7058 7059 7060
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
                rc = qemuSetVcpusBWLive(vm, group, params[i].value.ul, 0);
                if (rc != 0)
7061
                    goto cleanup;
7062 7063 7064 7065 7066 7067 7068 7069

                if (params[i].value.ul)
                    vm->def->cputune.period = params[i].value.ul;
            }

            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
                vmdef->cputune.period = params[i].value.ul;
            }
7070
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_VCPU_QUOTA)) {
7071 7072 7073
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
                rc = qemuSetVcpusBWLive(vm, group, 0, params[i].value.l);
                if (rc != 0)
7074
                    goto cleanup;
7075 7076 7077 7078 7079 7080 7081

                if (params[i].value.l)
                    vm->def->cputune.quota = params[i].value.l;
            }

            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
                vmdef->cputune.quota = params[i].value.l;
7082
            }
7083 7084
        }
    }
7085

7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
        goto cleanup;


    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        rc = virDomainSaveConfig(driver->configDir, vmdef);
        if (rc < 0)
            goto cleanup;

        virDomainObjAssignDef(vm, vmdef, false);
        vmdef = NULL;
    }

7099 7100 7101
    ret = 0;

cleanup:
7102
    virDomainDefFree(vmdef);
7103 7104 7105
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
7106
    qemuDriverUnlock(driver);
7107 7108 7109
    return ret;
}

7110 7111 7112 7113
static int
qemuSetSchedulerParameters(virDomainPtr dom,
                           virTypedParameterPtr params,
                           int nparams)
7114 7115 7116 7117
{
    return qemuSetSchedulerParametersFlags(dom,
                                           params,
                                           nparams,
7118
                                           VIR_DOMAIN_AFFECT_LIVE);
7119 7120
}

7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185
static int
qemuGetVcpuBWLive(virCgroupPtr cgroup, unsigned long long *period,
                  long long *quota)
{
    int rc;

    rc = virCgroupGetCpuCfsPeriod(cgroup, period);
    if (rc < 0) {
        virReportSystemError(-rc, "%s",
                             _("unable to get cpu bandwidth period tunable"));
        return -1;
    }

    rc = virCgroupGetCpuCfsQuota(cgroup, quota);
    if (rc < 0) {
        virReportSystemError(-rc, "%s",
                             _("unable to get cpu bandwidth tunable"));
        return -1;
    }

    return 0;
}

static int
qemuGetVcpusBWLive(virDomainObjPtr vm, virCgroupPtr cgroup,
                   unsigned long long *period, long long *quota)
{
    virCgroupPtr cgroup_vcpu = NULL;
    qemuDomainObjPrivatePtr priv = NULL;
    int rc;
    int ret = -1;

    priv = vm->privateData;
    if (priv->nvcpupids == 0 || priv->vcpupids[0] == vm->pid) {
        /* We do not create sub dir for each vcpu */
        rc = qemuGetVcpuBWLive(cgroup, period, quota);
        if (rc < 0)
            goto cleanup;

        if (*quota > 0)
            *quota /= vm->def->vcpus;
        goto out;
    }

    /* get period and quota for vcpu0 */
    rc = virCgroupForVcpu(cgroup, 0, &cgroup_vcpu, 0);
    if (!cgroup_vcpu) {
        virReportSystemError(-rc,
                             _("Unable to find vcpu cgroup for %s(vcpu: 0)"),
                             vm->def->name);
        goto cleanup;
    }

    rc = qemuGetVcpuBWLive(cgroup_vcpu, period, quota);
    if (rc < 0)
        goto cleanup;

out:
    ret = 0;

cleanup:
    virCgroupFree(&cgroup_vcpu);
    return ret;
}

7186 7187 7188 7189 7190
static int
qemuGetSchedulerParametersFlags(virDomainPtr dom,
                                virTypedParameterPtr params,
                                int *nparams,
                                unsigned int flags)
7191 7192 7193 7194
{
    struct qemud_driver *driver = dom->conn->privateData;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
7195 7196 7197
    unsigned long long shares;
    unsigned long long period;
    long long quota;
7198 7199
    int ret = -1;
    int rc;
7200
    bool cpu_bw_status = false;
7201
    int saved_nparams = 0;
7202
    virDomainDefPtr persistentDef;
7203

7204
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
7205 7206
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);
7207

7208 7209
    qemuDriverLock(driver);

7210 7211 7212
    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

7213 7214 7215 7216 7217 7218 7219
    if (*nparams > 1) {
        rc = qemuGetCpuBWStatus(driver->cgroup);
        if (rc < 0)
            goto cleanup;
        cpu_bw_status = !!rc;
    }

7220 7221 7222
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (vm == NULL) {
7223 7224
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No such domain %s"), dom->uuid);
7225 7226 7227
        goto cleanup;
    }

7228 7229 7230
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;
7231

7232
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
7233 7234 7235 7236
        shares = persistentDef->cputune.shares;
        if (*nparams > 1 && cpu_bw_status) {
            period = persistentDef->cputune.period;
            quota = persistentDef->cputune.quota;
7237
        }
7238
        goto out;
7239 7240
    }

7241 7242 7243 7244 7245 7246
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup CPU controller is not mounted"));
        goto cleanup;
    }

7247
    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
7248 7249
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find cgroup for domain %s"), vm->def->name);
7250 7251 7252
        goto cleanup;
    }

7253
    rc = virCgroupGetCpuShares(group, &shares);
7254
    if (rc != 0) {
7255
        virReportSystemError(-rc, "%s",
7256 7257 7258
                             _("unable to get cpu shares tunable"));
        goto cleanup;
    }
7259 7260 7261 7262 7263 7264

    if (*nparams > 1 && cpu_bw_status) {
        rc = qemuGetVcpusBWLive(vm, group, &period, &quota);
        if (rc != 0)
            goto cleanup;
    }
7265
out:
7266 7267
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CPU_SHARES,
                                VIR_TYPED_PARAM_ULLONG, shares) < 0)
C
Chris Lalancette 已提交
7268
        goto cleanup;
7269 7270 7271 7272
    saved_nparams++;

    if (cpu_bw_status) {
        if (*nparams > saved_nparams) {
7273 7274 7275
            if (virTypedParameterAssign(&params[1],
                                        VIR_DOMAIN_SCHEDULER_VCPU_PERIOD,
                                        VIR_TYPED_PARAM_ULLONG, period) < 0)
7276 7277 7278 7279 7280
                goto cleanup;
            saved_nparams++;
        }

        if (*nparams > saved_nparams) {
7281 7282 7283
            if (virTypedParameterAssign(&params[2],
                                        VIR_DOMAIN_SCHEDULER_VCPU_QUOTA,
                                        VIR_TYPED_PARAM_LLONG, quota) < 0)
7284 7285 7286 7287 7288 7289 7290
                goto cleanup;
            saved_nparams++;
        }
    }

    *nparams = saved_nparams;

7291 7292 7293 7294 7295 7296
    ret = 0;

cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
7297
    qemuDriverUnlock(driver);
7298 7299 7300
    return ret;
}

7301 7302 7303 7304 7305 7306
static int
qemuGetSchedulerParameters(virDomainPtr dom,
                           virTypedParameterPtr params,
                           int *nparams)
{
    return qemuGetSchedulerParametersFlags(dom, params, nparams,
7307
                                           VIR_DOMAIN_AFFECT_CURRENT);
7308
}
7309

7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369
/**
 * Resize a block device while a guest is running. Resize to a lower size
 * is supported, but should be used with extreme caution.  Note that it
 * only supports to resize image files, it can't resize block devices
 * like LVM volumes.
 */
static int
qemuDomainBlockResize (virDomainPtr dom,
                       const char *path,
                       unsigned long long size,
                       unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1, i;
    char *device = NULL;
    virDomainDiskDefPtr disk = NULL;

    virCheckFlags(0, -1);

    if (path[0] == '\0') {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("empty path"));
        return -1;
    }

    if (size > ULLONG_MAX / 1024) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("size must be less than %llu"),
                        ULLONG_MAX / 1024);
        return -1;
    }

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    priv = vm->privateData;

    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

    if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path: %s"), path);
7370
        goto endjob;
7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399
    }
    disk = vm->def->disks[i];

    if (virAsprintf(&device, "%s%s", QEMU_DRIVE_HOST_PREFIX,
                    disk->info.alias) < 0) {
        virReportOOMError();
        goto endjob;
    }

    qemuDomainObjEnterMonitor(driver, vm);
    if (qemuMonitorBlockResize(priv->mon, device, size) < 0) {
        qemuDomainObjExitMonitor(driver, vm);
        goto endjob;
    }
    qemuDomainObjExitMonitor(driver, vm);

    ret = 0;

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;

cleanup:
    VIR_FREE(device);
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

7400 7401 7402 7403 7404
/* This uses the 'info blockstats' monitor command which was
 * integrated into both qemu & kvm in late 2007.  If the command is
 * not supported we detect this and return the appropriate error.
 */
static int
7405 7406 7407
qemuDomainBlockStats(virDomainPtr dom,
                     const char *path,
                     struct _virDomainBlockStats *stats)
7408
{
7409
    struct qemud_driver *driver = dom->conn->privateData;
7410
    int i, ret = -1;
7411
    virDomainObjPtr vm;
7412
    virDomainDiskDefPtr disk = NULL;
7413
    qemuDomainObjPrivatePtr priv;
7414

7415
    qemuDriverLock(driver);
7416
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7417
    qemuDriverUnlock(driver);
7418
    if (!vm) {
7419 7420
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
7421 7422
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
7423
        goto cleanup;
7424
    }
7425

7426 7427 7428 7429 7430 7431
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

7432
    if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
7433 7434
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path: %s"), path);
7435
        goto cleanup;
7436
    }
7437
    disk = vm->def->disks[i];
7438

7439
    if (!disk->info.alias) {
7440 7441
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("missing disk device alias name for %s"), disk->dst);
7442
        goto cleanup;
7443
    }
7444

7445
    priv = vm->privateData;
7446 7447
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
        goto cleanup;
7448

7449 7450 7451 7452 7453
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }
7454

7455
    qemuDomainObjEnterMonitor(driver, vm);
7456 7457 7458 7459
    ret = qemuMonitorGetBlockStatsInfo(priv->mon,
                                       disk->info.alias,
                                       &stats->rd_req,
                                       &stats->rd_bytes,
7460
                                       NULL,
7461 7462
                                       &stats->wr_req,
                                       &stats->wr_bytes,
7463 7464 7465
                                       NULL,
                                       NULL,
                                       NULL,
7466 7467
                                       &stats->errs);
    qemuDomainObjExitMonitor(driver, vm);
7468

7469
endjob:
7470 7471
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
7472

7473
cleanup:
7474 7475
    if (vm)
        virDomainObjUnlock(vm);
7476
    return ret;
7477 7478
}

7479
static int
7480 7481 7482 7483 7484
qemuDomainBlockStatsFlags(virDomainPtr dom,
                          const char *path,
                          virTypedParameterPtr params,
                          int *nparams,
                          unsigned int flags)
7485 7486 7487 7488 7489 7490 7491 7492
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i, tmp, ret = -1;
    virDomainObjPtr vm;
    virDomainDiskDefPtr disk = NULL;
    qemuDomainObjPrivatePtr priv;
    long long rd_req, rd_bytes, wr_req, wr_bytes, rd_total_times;
    long long wr_total_times, flush_req, flush_total_times, errs;
7493
    virTypedParameterPtr param;
7494

7495 7496 7497 7498
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;
7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

    if (*nparams != 0) {
7518
        if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
7519 7520 7521 7522
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("invalid path: %s"), path);
            goto cleanup;
        }
7523
        disk = vm->def->disks[i];
7524 7525 7526

        if (!disk->info.alias) {
             qemuReportError(VIR_ERR_INTERNAL_ERROR,
7527 7528
                             _("missing disk device alias name for %s"),
                             disk->dst);
7529 7530 7531 7532 7533 7534 7535 7536 7537 7538
             goto cleanup;
        }
    }

    priv = vm->privateData;
    VIR_DEBUG("priv=%p, params=%p, flags=%x", priv, params, flags);

    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
        goto cleanup;

7539 7540 7541 7542 7543 7544
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

7545 7546 7547 7548
    qemuDomainObjEnterMonitor(driver, vm);
    tmp = *nparams;
    ret = qemuMonitorGetBlockStatsParamsNumber(priv->mon, nparams);

7549
    if (tmp == 0 || ret < 0) {
7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570
        qemuDomainObjExitMonitor(driver, vm);
        goto endjob;
    }

    ret = qemuMonitorGetBlockStatsInfo(priv->mon,
                                       disk->info.alias,
                                       &rd_req,
                                       &rd_bytes,
                                       &rd_total_times,
                                       &wr_req,
                                       &wr_bytes,
                                       &wr_total_times,
                                       &flush_req,
                                       &flush_total_times,
                                       &errs);

    qemuDomainObjExitMonitor(driver, vm);

    if (ret < 0)
        goto endjob;

7571 7572
    tmp = 0;
    ret = -1;
7573

7574 7575
    if (tmp < *nparams && wr_bytes != -1) {
        param = &params[tmp];
7576 7577
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_WRITE_BYTES,
                                    VIR_TYPED_PARAM_LLONG, wr_bytes) < 0)
7578 7579 7580
            goto endjob;
        tmp++;
    }
7581

7582
    if (tmp < *nparams && wr_req != -1) {
7583
        param = &params[tmp];
7584 7585
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_WRITE_REQ,
                                    VIR_TYPED_PARAM_LLONG, wr_req) < 0)
7586 7587 7588
            goto endjob;
        tmp++;
    }
7589

7590
    if (tmp < *nparams && rd_bytes != -1) {
7591
        param = &params[tmp];
7592 7593
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_READ_BYTES,
                                    VIR_TYPED_PARAM_LLONG, rd_bytes) < 0)
7594 7595 7596
            goto endjob;
        tmp++;
    }
7597

7598
    if (tmp < *nparams && rd_req != -1) {
7599
        param = &params[tmp];
7600 7601
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_READ_REQ,
                                    VIR_TYPED_PARAM_LLONG, rd_req) < 0)
7602 7603 7604
            goto endjob;
        tmp++;
    }
7605

7606
    if (tmp < *nparams && flush_req != -1) {
7607
        param = &params[tmp];
7608 7609
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_FLUSH_REQ,
                                    VIR_TYPED_PARAM_LLONG, flush_req) < 0)
7610 7611 7612
            goto endjob;
        tmp++;
    }
7613

7614
    if (tmp < *nparams && wr_total_times != -1) {
7615
        param = &params[tmp];
7616 7617 7618
        if (virTypedParameterAssign(param,
                                    VIR_DOMAIN_BLOCK_STATS_WRITE_TOTAL_TIMES,
                                    VIR_TYPED_PARAM_LLONG, wr_total_times) < 0)
7619 7620 7621
            goto endjob;
        tmp++;
    }
7622

7623
    if (tmp < *nparams && rd_total_times != -1) {
7624
        param = &params[tmp];
7625 7626 7627
        if (virTypedParameterAssign(param,
                                    VIR_DOMAIN_BLOCK_STATS_READ_TOTAL_TIMES,
                                    VIR_TYPED_PARAM_LLONG, rd_total_times) < 0)
7628 7629 7630
            goto endjob;
        tmp++;
    }
7631

7632
    if (tmp < *nparams && flush_total_times != -1) {
7633
        param = &params[tmp];
7634 7635 7636 7637
        if (virTypedParameterAssign(param,
                                    VIR_DOMAIN_BLOCK_STATS_FLUSH_TOTAL_TIMES,
                                    VIR_TYPED_PARAM_LLONG,
                                    flush_total_times) < 0)
7638 7639
            goto endjob;
        tmp++;
7640 7641
    }

7642 7643 7644 7645 7646
    /* Field 'errs' is meaningless for QEMU, won't set it. */

    ret = 0;
    *nparams = tmp;

7647 7648 7649 7650 7651 7652 7653 7654 7655 7656
endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

7657
#ifdef __linux__
7658 7659 7660 7661 7662
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
7663 7664
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
7665
    int i;
7666
    int ret = -1;
7667

7668
    qemuDriverLock(driver);
7669
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7670 7671
    qemuDriverUnlock(driver);

7672
    if (!vm) {
7673 7674
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
7675 7676
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
7677
        goto cleanup;
7678 7679
    }

D
Daniel P. Berrange 已提交
7680
    if (!virDomainObjIsActive(vm)) {
7681 7682
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
7683
        goto cleanup;
7684 7685 7686
    }

    /* Check the path is one of the domain's network interfaces. */
7687 7688
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
7689 7690 7691 7692
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
7693 7694
    }

7695
    if (ret == 0)
7696
        ret = linuxDomainInterfaceStats(path, stats);
7697
    else
7698 7699
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path, '%s' is not a known interface"), path);
7700

7701
cleanup:
7702 7703
    if (vm)
        virDomainObjUnlock(vm);
7704 7705
    return ret;
}
7706
#else
7707 7708 7709 7710
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
7711
{
7712 7713
    qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                    _("interface stats not implemented on this platform"));
7714 7715
    return -1;
}
7716
#endif
7717

7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731
static int
qemuDomainSetInterfaceParameters(virDomainPtr dom,
                                 const char *device,
                                 virTypedParameterPtr params,
                                 int nparams,
                                 unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr persistentDef = NULL;
    int ret = -1;
    virDomainNetDefPtr net = NULL, persistentNet = NULL;
7732
    virNetDevBandwidthPtr bandwidth = NULL, newBandwidth = NULL;
7733 7734 7735

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_BANDWIDTH_IN_AVERAGE,
                                       VIR_TYPED_PARAM_UINT,
                                       VIR_DOMAIN_BANDWIDTH_IN_PEAK,
                                       VIR_TYPED_PARAM_UINT,
                                       VIR_DOMAIN_BANDWIDTH_IN_BURST,
                                       VIR_TYPED_PARAM_UINT,
                                       VIR_DOMAIN_BANDWIDTH_OUT_AVERAGE,
                                       VIR_TYPED_PARAM_UINT,
                                       VIR_DOMAIN_BANDWIDTH_OUT_PEAK,
                                       VIR_TYPED_PARAM_UINT,
                                       VIR_DOMAIN_BANDWIDTH_OUT_BURST,
                                       VIR_TYPED_PARAM_UINT,
                                       NULL) < 0)
        return -1;
7751

7752
    qemuDriverLock(driver);
7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (vm == NULL) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No such domain %s"), dom->uuid);
        goto cleanup;
    }

    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        net = virDomainNetFind(vm->def, device);
        if (!net) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Can't find device %s"), device);
            goto cleanup;
        }
    }
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        persistentNet = virDomainNetFind(persistentDef, device);
        if (!persistentNet) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Can't find device %s"), device);
            goto cleanup;
        }
    }

7782 7783 7784
    if ((VIR_ALLOC(bandwidth) < 0) ||
        (VIR_ALLOC(bandwidth->in) < 0) ||
        (VIR_ALLOC(bandwidth->out) < 0)) {
7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806
        virReportOOMError();
        goto cleanup;
    }

    for (i = 0; i < nparams; i++) {
        virTypedParameterPtr param = &params[i];

        if (STREQ(param->field, VIR_DOMAIN_BANDWIDTH_IN_AVERAGE)) {
            bandwidth->in->average = params[i].value.ui;
        } else if (STREQ(param->field, VIR_DOMAIN_BANDWIDTH_IN_PEAK)) {
            bandwidth->in->peak = params[i].value.ui;
        } else if (STREQ(param->field, VIR_DOMAIN_BANDWIDTH_IN_BURST)) {
            bandwidth->in->burst = params[i].value.ui;
        } else if (STREQ(param->field, VIR_DOMAIN_BANDWIDTH_OUT_AVERAGE)) {
            bandwidth->out->average = params[i].value.ui;
        } else if (STREQ(param->field, VIR_DOMAIN_BANDWIDTH_OUT_PEAK)) {
            bandwidth->out->peak = params[i].value.ui;
        } else if (STREQ(param->field, VIR_DOMAIN_BANDWIDTH_OUT_BURST)) {
            bandwidth->out->burst = params[i].value.ui;
        }
    }

7807
    /* average is mandatory, peak and burst are optional. So if no
7808
     * average is given, we free inbound/outbound here which causes
7809
     * inbound/outbound to not be set. */
7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824
    if (!bandwidth->in->average) {
        VIR_FREE(bandwidth->in);
    }
    if (!bandwidth->out->average) {
        VIR_FREE(bandwidth->out);
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (VIR_ALLOC(newBandwidth) < 0) {
            virReportOOMError();
            goto cleanup;
        }

        /* virNetDevBandwidthSet() will clear any previous value of
         * bandwidth parameters, so merge with old bandwidth parameters
7825
         * here to prevent them from being lost. */
7826 7827
        if (bandwidth->in ||
            (net->bandwidth && net->bandwidth->in)) {
7828 7829 7830 7831
            if (VIR_ALLOC(newBandwidth->in) < 0) {
                virReportOOMError();
                goto cleanup;
            }
7832 7833 7834 7835 7836 7837 7838

            memcpy(newBandwidth->in,
                   bandwidth->in ? bandwidth->in : net->bandwidth->in,
                   sizeof(*newBandwidth->in));
        }
        if (bandwidth->out ||
            (net->bandwidth && net->bandwidth->out)) {
7839 7840 7841 7842
            if (VIR_ALLOC(newBandwidth->out) < 0) {
                virReportOOMError();
                goto cleanup;
            }
7843 7844 7845 7846

            memcpy(newBandwidth->out,
                   bandwidth->out ? bandwidth->out : net->bandwidth->out,
                   sizeof(*newBandwidth->out));
7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857
        }

        if (virNetDevBandwidthSet(net->ifname, newBandwidth) < 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot set bandwidth limits on %s"),
                            device);
            goto cleanup;
        }

        virNetDevBandwidthFree(net->bandwidth);
        net->bandwidth = newBandwidth;
E
Eric Blake 已提交
7858
        newBandwidth = NULL;
7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883
    }
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        if (!persistentNet->bandwidth) {
            persistentNet->bandwidth = bandwidth;
            bandwidth = NULL;
        } else {
            if (bandwidth->in) {
                VIR_FREE(persistentNet->bandwidth->in);
                persistentNet->bandwidth->in = bandwidth->in;
                bandwidth->in = NULL;
            }
            if (bandwidth->out) {
                VIR_FREE(persistentNet->bandwidth->out);
                persistentNet->bandwidth->out = bandwidth->out;
                bandwidth->out = NULL;
            }
        }

        if (virDomainSaveConfig(driver->configDir, persistentDef) < 0)
            goto cleanup;
    }

    ret = 0;
cleanup:
    virNetDevBandwidthFree(bandwidth);
7884
    virNetDevBandwidthFree(newBandwidth);
7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

static int
qemuDomainGetInterfaceParameters(virDomainPtr dom,
                                 const char *device,
                                 virTypedParameterPtr params,
                                 int *nparams,
                                 unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    virDomainDefPtr persistentDef = NULL;
    virDomainNetDefPtr net = NULL;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);

    qemuDriverLock(driver);

    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (vm == NULL) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No such domain %s"), dom->uuid);
        goto cleanup;
    }

    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;

    if ((*nparams) == 0) {
        *nparams = QEMU_NB_BANDWIDTH_PARAM;
        ret = 0;
        goto cleanup;
    }

    def = persistentDef;
    if (!def)
        def = vm->def;

    net = virDomainNetFind(def, device);
    if (!net) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("Can't find device %s"), device);
        goto cleanup;
    }

    for (i = 0; i < *nparams && i < QEMU_NB_BANDWIDTH_PARAM; i++) {
        switch(i) {
        case 0: /* inbound.average */
7948 7949 7950
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_IN_AVERAGE,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
7951 7952 7953 7954 7955
                goto cleanup;
            if (net->bandwidth && net->bandwidth->in)
                params[i].value.ui = net->bandwidth->in->average;
            break;
        case 1: /* inbound.peak */
7956 7957 7958
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_IN_PEAK,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
7959 7960 7961 7962 7963
                goto cleanup;
            if (net->bandwidth && net->bandwidth->in)
                params[i].value.ui = net->bandwidth->in->peak;
            break;
        case 2: /* inbound.burst */
7964 7965 7966
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_IN_BURST,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
7967 7968 7969 7970 7971
                goto cleanup;
            if (net->bandwidth && net->bandwidth->in)
                params[i].value.ui = net->bandwidth->in->burst;
            break;
        case 3: /* outbound.average */
7972 7973 7974
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_OUT_AVERAGE,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
7975 7976 7977 7978 7979
                goto cleanup;
            if (net->bandwidth && net->bandwidth->out)
                params[i].value.ui = net->bandwidth->out->average;
            break;
        case 4: /* outbound.peak */
7980 7981 7982
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_OUT_PEAK,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
7983 7984 7985 7986 7987
                goto cleanup;
            if (net->bandwidth && net->bandwidth->out)
                params[i].value.ui = net->bandwidth->out->peak;
            break;
        case 5: /* outbound.burst */
7988 7989 7990
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_OUT_BURST,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013
                goto cleanup;
            if (net->bandwidth && net->bandwidth->out)
                params[i].value.ui = net->bandwidth->out->burst;
            break;
        default:
            break;
            /* should not hit here */
        }
    }

    if (*nparams > QEMU_NB_BANDWIDTH_PARAM)
        *nparams = QEMU_NB_BANDWIDTH_PARAM;
    ret = 0;

cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

8014 8015 8016
static int
qemudDomainMemoryStats (virDomainPtr dom,
                        struct _virDomainMemoryStat *stats,
8017 8018
                        unsigned int nr_stats,
                        unsigned int flags)
8019 8020 8021 8022 8023
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned int ret = -1;

8024 8025
    virCheckFlags(0, -1);

8026 8027 8028 8029 8030 8031 8032
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
8033 8034
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
8035 8036 8037
        goto cleanup;
    }

8038
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
8039 8040
        goto cleanup;

8041 8042
    if (virDomainObjIsActive(vm)) {
        qemuDomainObjPrivatePtr priv = vm->privateData;
8043
        qemuDomainObjEnterMonitor(driver, vm);
8044
        ret = qemuMonitorGetMemoryStats(priv->mon, stats, nr_stats);
8045
        qemuDomainObjExitMonitor(driver, vm);
8046
    } else {
8047 8048
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
8049 8050
    }

8051
    if (qemuDomainObjEndJob(driver, vm) == 0)
8052 8053
        vm = NULL;

8054 8055 8056 8057 8058 8059
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

8060 8061 8062 8063 8064
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
E
Eric Blake 已提交
8065
                      unsigned int flags)
8066
{
8067 8068
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
8069 8070
    int fd = -1, ret = -1;
    const char *actual;
8071

E
Eric Blake 已提交
8072 8073
    virCheckFlags(0, -1);

8074
    qemuDriverLock(driver);
8075
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
8076 8077
    qemuDriverUnlock(driver);

8078
    if (!vm) {
8079 8080
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
8081 8082
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
8083
        goto cleanup;
8084 8085 8086
    }

    if (!path || path[0] == '\0') {
8087 8088
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("NULL or empty path"));
8089
        goto cleanup;
8090 8091
    }

8092 8093 8094 8095 8096
    /* Check the path belongs to this domain.  */
    if (!(actual = virDomainDiskPathByName(vm->def, path))) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path '%s'"), path);
        goto cleanup;
8097
    }
8098
    path = actual;
8099

8100 8101 8102 8103 8104 8105 8106
    /* The path is correct, now try to open it and get its size. */
    fd = open(path, O_RDONLY);
    if (fd == -1) {
        virReportSystemError(errno,
                             _("%s: failed to open"), path);
        goto cleanup;
    }
8107

8108 8109 8110 8111 8112 8113 8114 8115 8116
    /* Seek and read. */
    /* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
     * be 64 bits on all platforms.
     */
    if (lseek(fd, offset, SEEK_SET) == (off_t) -1 ||
        saferead(fd, buffer, size) == (ssize_t) -1) {
        virReportSystemError(errno,
                             _("%s: failed to seek or read"), path);
        goto cleanup;
8117 8118
    }

8119 8120
    ret = 0;

8121
cleanup:
8122
    VIR_FORCE_CLOSE(fd);
8123 8124
    if (vm)
        virDomainObjUnlock(vm);
8125 8126 8127
    return ret;
}

R
Richard W.M. Jones 已提交
8128 8129 8130 8131 8132 8133
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
8134 8135
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
8136
    char *tmp = NULL;
R
Richard W.M. Jones 已提交
8137
    int fd = -1, ret = -1;
8138
    qemuDomainObjPrivatePtr priv;
R
Richard W.M. Jones 已提交
8139

8140 8141
    virCheckFlags(VIR_MEMORY_VIRTUAL | VIR_MEMORY_PHYSICAL, -1);

8142
    qemuDriverLock(driver);
8143
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
8144
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
8145 8146

    if (!vm) {
8147 8148
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
8149 8150
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
8151 8152 8153
        goto cleanup;
    }

8154
    if (flags != VIR_MEMORY_VIRTUAL && flags != VIR_MEMORY_PHYSICAL) {
8155 8156
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("flags parameter must be VIR_MEMORY_VIRTUAL or VIR_MEMORY_PHYSICAL"));
8157
        goto cleanup;
R
Richard W.M. Jones 已提交
8158 8159
    }

8160
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
8161 8162
        goto cleanup;

D
Daniel P. Berrange 已提交
8163
    if (!virDomainObjIsActive(vm)) {
8164 8165
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
8166
        goto endjob;
R
Richard W.M. Jones 已提交
8167 8168
    }

8169
    if (virAsprintf(&tmp, "%s/qemu.mem.XXXXXX", driver->cacheDir) < 0) {
8170
        virReportOOMError();
8171
        goto endjob;
8172 8173
    }

R
Richard W.M. Jones 已提交
8174 8175
    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
8176 8177
        virReportSystemError(errno,
                             _("mkstemp(\"%s\") failed"), tmp);
8178
        goto endjob;
R
Richard W.M. Jones 已提交
8179 8180
    }

8181
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm->def, tmp);
8182

8183
    priv = vm->privateData;
8184
    qemuDomainObjEnterMonitor(driver, vm);
8185
    if (flags == VIR_MEMORY_VIRTUAL) {
8186
        if (qemuMonitorSaveVirtualMemory(priv->mon, offset, size, tmp) < 0) {
8187
            qemuDomainObjExitMonitor(driver, vm);
8188
            goto endjob;
8189
        }
8190
    } else {
8191
        if (qemuMonitorSavePhysicalMemory(priv->mon, offset, size, tmp) < 0) {
8192
            qemuDomainObjExitMonitor(driver, vm);
8193
            goto endjob;
8194
        }
R
Richard W.M. Jones 已提交
8195
    }
8196
    qemuDomainObjExitMonitor(driver, vm);
R
Richard W.M. Jones 已提交
8197 8198

    /* Read the memory file into buffer. */
8199
    if (saferead(fd, buffer, size) == (ssize_t) -1) {
8200 8201 8202
        virReportSystemError(errno,
                             _("failed to read temporary file "
                               "created with template %s"), tmp);
8203
        goto endjob;
R
Richard W.M. Jones 已提交
8204 8205 8206
    }

    ret = 0;
8207

8208
endjob:
8209
    if (qemuDomainObjEndJob(driver, vm) == 0)
8210
        vm = NULL;
8211

8212
cleanup:
8213
    VIR_FORCE_CLOSE(fd);
8214 8215
    if (tmp)
        unlink(tmp);
W
Wen Congyang 已提交
8216
    VIR_FREE(tmp);
8217 8218
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
8219 8220 8221
    return ret;
}

8222

8223 8224 8225 8226 8227 8228 8229 8230 8231
static int qemuDomainGetBlockInfo(virDomainPtr dom,
                                  const char *path,
                                  virDomainBlockInfoPtr info,
                                  unsigned int flags) {
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    int fd = -1;
    off_t end;
8232
    virStorageFileMetadata *meta = NULL;
8233
    virDomainDiskDefPtr disk = NULL;
8234
    struct stat sb;
8235
    int i;
8236
    int format;
8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257

    virCheckFlags(0, -1);

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!path || path[0] == '\0') {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("NULL or empty path"));
        goto cleanup;
    }

    /* Check the path belongs to this domain. */
8258
    if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
8259 8260 8261 8262
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path %s not assigned to domain"), path);
        goto cleanup;
    }
8263 8264 8265 8266 8267 8268 8269 8270
    disk = vm->def->disks[i];
    if (!disk->src) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("disk %s does not currently have a source assigned"),
                        path);
        goto cleanup;
    }
    path = disk->src;
8271 8272

    /* The path is correct, now try to open it and get its size. */
8273
    fd = open(path, O_RDONLY);
8274 8275 8276 8277 8278 8279 8280
    if (fd == -1) {
        virReportSystemError(errno,
                             _("failed to open path '%s'"), path);
        goto cleanup;
    }

    /* Probe for magic formats */
8281 8282 8283 8284 8285 8286 8287 8288
    if (disk->driverType) {
        if ((format = virStorageFileFormatTypeFromString(disk->driverType)) < 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("unknown disk format %s for %s"),
                            disk->driverType, disk->src);
            goto cleanup;
        }
    } else {
8289 8290 8291 8292 8293 8294 8295
        if (driver->allowDiskFormatProbing) {
            if ((format = virStorageFileProbeFormat(disk->src)) < 0)
                goto cleanup;
        } else {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("no disk format for %s and probing is disabled"),
                            disk->src);
8296
            goto cleanup;
8297
        }
8298 8299
    }

8300 8301 8302 8303 8304
    if (VIR_ALLOC(meta) < 0) {
        virReportOOMError();
        goto cleanup;
    }

8305 8306
    if (virStorageFileGetMetadataFromFD(path, fd,
                                        format,
8307
                                        meta) < 0)
8308 8309 8310 8311 8312 8313 8314 8315 8316 8317
        goto cleanup;

    /* Get info for normal formats */
    if (fstat(fd, &sb) < 0) {
        virReportSystemError(errno,
                             _("cannot stat file '%s'"), path);
        goto cleanup;
    }

    if (S_ISREG(sb.st_mode)) {
8318
#ifndef WIN32
8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331
        info->physical = (unsigned long long)sb.st_blocks *
            (unsigned long long)DEV_BSIZE;
#else
        info->physical = sb.st_size;
#endif
        /* Regular files may be sparse, so logical size (capacity) is not same
         * as actual physical above
         */
        info->capacity = sb.st_size;
    } else {
        /* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
         * be 64 bits on all platforms.
         */
8332
        end = lseek(fd, 0, SEEK_END);
8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343
        if (end == (off_t)-1) {
            virReportSystemError(errno,
                                 _("failed to seek to end of %s"), path);
            goto cleanup;
        }
        info->physical = end;
        info->capacity = end;
    }

    /* If the file we probed has a capacity set, then override
     * what we calculated from file/block extents */
8344 8345
    if (meta->capacity)
        info->capacity = meta->capacity;
8346

8347
    /* Set default value .. */
8348 8349
    info->allocation = info->physical;

8350 8351 8352
    /* ..but if guest is running & not using raw
       disk format and on a block device, then query
       highest allocated extent from QEMU */
8353
    if (disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
8354
        format != VIR_STORAGE_FILE_RAW &&
8355 8356
        S_ISBLK(sb.st_mode) &&
        virDomainObjIsActive(vm)) {
8357
        qemuDomainObjPrivatePtr priv = vm->privateData;
8358

8359 8360
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
            goto cleanup;
8361

8362
        if (virDomainObjIsActive(vm)) {
8363
            qemuDomainObjEnterMonitor(driver, vm);
8364 8365 8366 8367
            ret = qemuMonitorGetBlockExtent(priv->mon,
                                            disk->info.alias,
                                            &info->allocation);
            qemuDomainObjExitMonitor(driver, vm);
8368
        } else {
8369
            ret = 0;
8370
        }
8371 8372 8373

        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
8374 8375 8376
    } else {
        ret = 0;
    }
8377 8378

cleanup:
8379
    virStorageFileFreeMetadata(meta);
8380
    VIR_FORCE_CLOSE(fd);
8381 8382 8383 8384 8385 8386
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


8387
static int
8388 8389 8390 8391
qemuDomainEventRegister(virConnectPtr conn,
                        virConnectDomainEventCallback callback,
                        void *opaque,
                        virFreeCallback freecb)
8392
{
8393 8394 8395
    struct qemud_driver *driver = conn->privateData;
    int ret;

8396
    qemuDriverLock(driver);
8397 8398 8399
    ret = virDomainEventStateRegister(conn,
                                      driver->domainEventState,
                                      callback, opaque, freecb);
8400
    qemuDriverUnlock(driver);
8401

8402
    return ret;
8403 8404
}

8405

8406
static int
8407 8408
qemuDomainEventDeregister(virConnectPtr conn,
                          virConnectDomainEventCallback callback)
8409
{
8410 8411 8412
    struct qemud_driver *driver = conn->privateData;
    int ret;

8413
    qemuDriverLock(driver);
8414 8415 8416
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
8417
    qemuDriverUnlock(driver);
8418

8419
    return ret;
8420 8421
}

8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434

static int
qemuDomainEventRegisterAny(virConnectPtr conn,
                           virDomainPtr dom,
                           int eventID,
                           virConnectDomainEventGenericCallback callback,
                           void *opaque,
                           virFreeCallback freecb)
{
    struct qemud_driver *driver = conn->privateData;
    int ret;

    qemuDriverLock(driver);
8435 8436 8437 8438
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID,
                                      callback, opaque, freecb, &ret) < 0)
8439
        ret = -1;
8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453
    qemuDriverUnlock(driver);

    return ret;
}


static int
qemuDomainEventDeregisterAny(virConnectPtr conn,
                             int callbackID)
{
    struct qemud_driver *driver = conn->privateData;
    int ret;

    qemuDriverLock(driver);
8454 8455 8456
    ret = virDomainEventStateDeregisterID(conn,
                                          driver->domainEventState,
                                          callbackID);
8457 8458 8459 8460 8461 8462
    qemuDriverUnlock(driver);

    return ret;
}


8463 8464 8465
/*******************************************************************
 * Migration Protocol Version 2
 *******************************************************************/
D
Daniel Veillard 已提交
8466

C
Chris Lalancette 已提交
8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481
/* Prepare is the first step, and it runs on the destination host.
 *
 * This version starts an empty VM listening on a localhost TCP port, and
 * sets up the corresponding virStream to handle the incoming data.
 */
static int
qemudDomainMigratePrepareTunnel(virConnectPtr dconn,
                                virStreamPtr st,
                                unsigned long flags,
                                const char *dname,
                                unsigned long resource ATTRIBUTE_UNUSED,
                                const char *dom_xml)
{
    struct qemud_driver *driver = dconn->privateData;
    int ret = -1;
8482

8483
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
8484

8485 8486
    qemuDriverLock(driver);

C
Chris Lalancette 已提交
8487
    if (!dom_xml) {
8488 8489
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
C
Chris Lalancette 已提交
8490 8491 8492
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
8493
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
8494 8495 8496 8497
                         "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
        goto cleanup;
    }
    if (st == NULL) {
8498 8499
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("tunnelled migration requested but NULL stream passed"));
C
Chris Lalancette 已提交
8500 8501 8502
        goto cleanup;
    }

8503 8504 8505 8506 8507 8508 8509
    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

8510 8511 8512
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     NULL, 0, NULL, NULL, /* No cookies in v2 */
                                     st, dname, dom_xml);
8513

C
Chris Lalancette 已提交
8514
cleanup:
8515
    qemuDriverUnlock(driver);
C
Chris Lalancette 已提交
8516 8517 8518
    return ret;
}

D
Daniel Veillard 已提交
8519 8520 8521 8522
/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
8523
static int ATTRIBUTE_NONNULL (5)
D
Daniel Veillard 已提交
8524
qemudDomainMigratePrepare2 (virConnectPtr dconn,
8525 8526
                            char **cookie ATTRIBUTE_UNUSED,
                            int *cookielen ATTRIBUTE_UNUSED,
D
Daniel Veillard 已提交
8527 8528
                            const char *uri_in,
                            char **uri_out,
C
Chris Lalancette 已提交
8529
                            unsigned long flags,
D
Daniel Veillard 已提交
8530 8531 8532 8533
                            const char *dname,
                            unsigned long resource ATTRIBUTE_UNUSED,
                            const char *dom_xml)
{
8534
    struct qemud_driver *driver = dconn->privateData;
8535
    int ret = -1;
8536

8537
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
8538

8539
    *uri_out = NULL;
D
Daniel Veillard 已提交
8540

8541
    qemuDriverLock(driver);
8542 8543 8544 8545 8546 8547 8548 8549

    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

C
Chris Lalancette 已提交
8550 8551 8552 8553
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
8554 8555
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Tunnelled migration requested but invalid RPC method called"));
C
Chris Lalancette 已提交
8556 8557 8558
        goto cleanup;
    }

D
Daniel Veillard 已提交
8559
    if (!dom_xml) {
8560 8561
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
8562
        goto cleanup;
D
Daniel Veillard 已提交
8563 8564
    }

8565 8566 8567 8568
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
8569
    ret = qemuMigrationPrepareDirect(driver, dconn,
8570
                                     NULL, 0, NULL, NULL, /* No cookies */
8571 8572
                                     uri_in, uri_out,
                                     dname, dom_xml);
D
Daniel Veillard 已提交
8573

8574 8575 8576 8577
cleanup:
    qemuDriverUnlock(driver);
    return ret;
}
C
Chris Lalancette 已提交
8578

D
Daniel Veillard 已提交
8579

8580 8581 8582
/* Perform is the second step, and it runs on the source host. */
static int
qemudDomainMigratePerform (virDomainPtr dom,
8583 8584
                           const char *cookie,
                           int cookielen,
8585 8586 8587 8588 8589 8590 8591 8592
                           const char *uri,
                           unsigned long flags,
                           const char *dname,
                           unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
8593
    const char *dconnuri = NULL;
8594

8595
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
8596

8597
    qemuDriverLock(driver);
8598 8599 8600 8601 8602 8603 8604
    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

8605
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel Veillard 已提交
8606
    if (!vm) {
8607 8608
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
8609 8610
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
8611
        goto cleanup;
D
Daniel Veillard 已提交
8612 8613
    }

8614 8615 8616 8617 8618
    if (flags & VIR_MIGRATE_PEER2PEER) {
        dconnuri = uri;
        uri = NULL;
    }

8619 8620 8621 8622 8623 8624
    /* Do not output cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd.
     *
     * Consume any cookie we were able to decode though
     */
8625
    ret = qemuMigrationPerform(driver, dom->conn, vm,
8626
                               NULL, dconnuri, uri, cookie, cookielen,
8627
                               NULL, NULL, /* No output cookies in v2 */
8628
                               flags, dname, resource, false);
8629

8630
cleanup:
8631
    qemuDriverUnlock(driver);
8632
    return ret;
D
Daniel Veillard 已提交
8633 8634
}

8635

D
Daniel Veillard 已提交
8636 8637 8638 8639 8640 8641 8642
/* Finish is the third and final step, and it runs on the destination host. */
static virDomainPtr
qemudDomainMigrateFinish2 (virConnectPtr dconn,
                           const char *dname,
                           const char *cookie ATTRIBUTE_UNUSED,
                           int cookielen ATTRIBUTE_UNUSED,
                           const char *uri ATTRIBUTE_UNUSED,
C
Chris Lalancette 已提交
8643
                           unsigned long flags,
D
Daniel Veillard 已提交
8644 8645
                           int retcode)
{
8646 8647 8648
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
D
Daniel Veillard 已提交
8649

8650
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
C
Chris Lalancette 已提交
8651

8652
    qemuDriverLock(driver);
8653
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
8654
    if (!vm) {
8655 8656
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
8657
        goto cleanup;
D
Daniel Veillard 已提交
8658 8659
    }

8660 8661 8662 8663
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
8664
    dom = qemuMigrationFinish(driver, dconn, vm,
8665
                              NULL, 0, NULL, NULL, /* No cookies */
8666
                              flags, retcode, false);
8667

8668
cleanup:
8669
    qemuDriverUnlock(driver);
8670
    return dom;
D
Daniel Veillard 已提交
8671 8672
}

8673

8674 8675 8676 8677 8678 8679
/*******************************************************************
 * Migration Protocol Version 3
 *******************************************************************/

static char *
qemuDomainMigrateBegin3(virDomainPtr domain,
8680
                        const char *xmlin,
8681 8682 8683
                        char **cookieout,
                        int *cookieoutlen,
                        unsigned long flags,
8684
                        const char *dname,
8685 8686 8687 8688 8689 8690
                        unsigned long resource ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    char *xml = NULL;

8691
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716
    if ((flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        if (qemuMigrationJobStart(driver, vm, QEMU_ASYNC_JOB_MIGRATION_OUT) < 0)
            goto cleanup;
    } else {
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
            goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

8717 8718 8719 8720 8721 8722 8723
    /* Check if there is any ejected media.
     * We don't want to require them on the destination.
     */

    if (qemuDomainCheckEjectableMedia(driver, vm) < 0)
        goto endjob;

8724
    if (!(xml = qemuMigrationBegin(driver, vm, xmlin, dname,
8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743
                                   cookieout, cookieoutlen)))
        goto endjob;

    if ((flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        /* We keep the job active across API calls until the confirm() call.
         * This prevents any other APIs being invoked while migration is taking
         * place.
         */
        if (qemuMigrationJobContinue(vm) == 0) {
            vm = NULL;
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("domain disappeared"));
            VIR_FREE(xml);
            if (cookieout)
                VIR_FREE(*cookieout);
        }
    } else {
        goto endjob;
    }
8744 8745

cleanup:
8746 8747
    if (vm)
        virDomainObjUnlock(vm);
8748 8749
    qemuDriverUnlock(driver);
    return xml;
8750 8751 8752 8753 8754 8755 8756 8757 8758 8759

endjob:
    if ((flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        if (qemuMigrationJobFinish(driver, vm) == 0)
            vm = NULL;
    } else {
        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
    }
    goto cleanup;
8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777
}

static int
qemuDomainMigratePrepare3(virConnectPtr dconn,
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
                          const char *uri_in,
                          char **uri_out,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource ATTRIBUTE_UNUSED,
                          const char *dom_xml)
{
    struct qemud_driver *driver = dconn->privateData;
    int ret = -1;

8778
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824

    *uri_out = NULL;

    qemuDriverLock(driver);
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Tunnelled migration requested but invalid RPC method called"));
        goto cleanup;
    }

    if (!dom_xml) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
        goto cleanup;
    }

    ret = qemuMigrationPrepareDirect(driver, dconn,
                                     cookiein, cookieinlen,
                                     cookieout, cookieoutlen,
                                     uri_in, uri_out,
                                     dname, dom_xml);

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}


static int
qemuDomainMigratePrepareTunnel3(virConnectPtr dconn,
                                virStreamPtr st,
                                const char *cookiein,
                                int cookieinlen,
                                char **cookieout,
                                int *cookieoutlen,
                                unsigned long flags,
                                const char *dname,
                                unsigned long resource ATTRIBUTE_UNUSED,
                                const char *dom_xml)
{
    struct qemud_driver *driver = dconn->privateData;
    int ret = -1;

8825
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856

    if (!dom_xml) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                         "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
        goto cleanup;
    }
    if (st == NULL) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("tunnelled migration requested but NULL stream passed"));
        goto cleanup;
    }

    qemuDriverLock(driver);
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     cookiein, cookieinlen,
                                     cookieout, cookieoutlen,
                                     st, dname, dom_xml);
    qemuDriverUnlock(driver);

cleanup:
    return ret;
}


static int
qemuDomainMigratePerform3(virDomainPtr dom,
8857
                          const char *xmlin,
8858 8859 8860 8861
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
8862
                          const char *dconnuri,
8863 8864 8865 8866 8867 8868 8869 8870 8871
                          const char *uri,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

8872
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

8884
    ret = qemuMigrationPerform(driver, dom->conn, vm, xmlin,
8885
                               dconnuri, uri, cookiein, cookieinlen,
8886
                               cookieout, cookieoutlen,
8887
                               flags, dname, resource, true);
8888 8889 8890 8891 8892 8893 8894

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}


8895
static virDomainPtr
8896 8897 8898 8899 8900 8901
qemuDomainMigrateFinish3(virConnectPtr dconn,
                         const char *dname,
                         const char *cookiein,
                         int cookieinlen,
                         char **cookieout,
                         int *cookieoutlen,
8902
                         const char *dconnuri ATTRIBUTE_UNUSED,
8903 8904
                         const char *uri ATTRIBUTE_UNUSED,
                         unsigned long flags,
8905
                         int cancelled)
8906 8907 8908
{
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
8909
    virDomainPtr dom = NULL;
8910

8911
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
8912 8913 8914 8915 8916 8917 8918 8919 8920

    qemuDriverLock(driver);
    vm = virDomainFindByName(&driver->domains, dname);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
        goto cleanup;
    }

8921 8922 8923 8924
    dom = qemuMigrationFinish(driver, dconn, vm,
                              cookiein, cookieinlen,
                              cookieout, cookieoutlen,
                              flags, cancelled, true);
8925 8926 8927

cleanup:
    qemuDriverUnlock(driver);
8928
    return dom;
8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940
}

static int
qemuDomainMigrateConfirm3(virDomainPtr domain,
                          const char *cookiein,
                          int cookieinlen,
                          unsigned long flags,
                          int cancelled)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
8941
    enum qemuMigrationJobPhase phase;
8942

8943
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

8955
    if (!qemuMigrationJobIsActive(vm, QEMU_ASYNC_JOB_MIGRATION_OUT))
8956 8957
        goto cleanup;

8958 8959 8960 8961 8962 8963 8964
    if (cancelled)
        phase = QEMU_MIGRATION_PHASE_CONFIRM3_CANCELLED;
    else
        phase = QEMU_MIGRATION_PHASE_CONFIRM3;

    qemuMigrationJobStartPhase(driver, vm, phase);

8965 8966
    ret = qemuMigrationConfirm(driver, domain->conn, vm,
                               cookiein, cookieinlen,
8967 8968
                               flags, cancelled);

8969
    if (qemuMigrationJobFinish(driver, vm) == 0) {
8970 8971 8972 8973 8974
        vm = NULL;
    } else if (!virDomainObjIsActive(vm) &&
               (!vm->persistent || (flags & VIR_MIGRATE_UNDEFINE_SOURCE))) {
        if (flags & VIR_MIGRATE_UNDEFINE_SOURCE)
            virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm);
8975
        qemuDomainRemoveInactive(driver, vm);
8976 8977 8978
        vm = NULL;
    }

8979
cleanup:
8980 8981
    if (vm)
        virDomainObjUnlock(vm);
8982 8983 8984 8985 8986
    qemuDriverUnlock(driver);
    return ret;
}


8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002
static int
qemudNodeDeviceGetPciInfo (virNodeDevicePtr dev,
                           unsigned *domain,
                           unsigned *bus,
                           unsigned *slot,
                           unsigned *function)
{
    virNodeDeviceDefPtr def = NULL;
    virNodeDevCapsDefPtr cap;
    char *xml = NULL;
    int ret = -1;

    xml = virNodeDeviceGetXMLDesc(dev, 0);
    if (!xml)
        goto out;

9003
    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE);
9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020
    if (!def)
        goto out;

    cap = def->caps;
    while (cap) {
        if (cap->type == VIR_NODE_DEV_CAP_PCI_DEV) {
            *domain   = cap->data.pci_dev.domain;
            *bus      = cap->data.pci_dev.bus;
            *slot     = cap->data.pci_dev.slot;
            *function = cap->data.pci_dev.function;
            break;
        }

        cap = cap->next;
    }

    if (!cap) {
9021 9022
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("device %s is not a PCI device"), dev->name);
9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035
        goto out;
    }

    ret = 0;
out:
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
qemudNodeDeviceDettach (virNodeDevicePtr dev)
{
9036
    struct qemud_driver *driver = dev->conn->privateData;
9037 9038 9039
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;
9040
    bool in_inactive_list = false;
9041 9042 9043 9044

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

9045
    pci = pciGetDevice(domain, bus, slot, function);
9046 9047 9048
    if (!pci)
        return -1;

9049
    qemuDriverLock(driver);
9050 9051 9052 9053
    in_inactive_list = pciDeviceListFind(driver->inactivePciHostdevs, pci);

    if (pciDettachDevice(pci, driver->activePciHostdevs,
                         driver->inactivePciHostdevs) < 0)
9054 9055 9056 9057
        goto out;

    ret = 0;
out:
9058
    qemuDriverUnlock(driver);
9059 9060
    if (in_inactive_list)
        pciFreeDevice(pci);
9061 9062 9063 9064 9065 9066
    return ret;
}

static int
qemudNodeDeviceReAttach (virNodeDevicePtr dev)
{
9067
    struct qemud_driver *driver = dev->conn->privateData;
9068
    pciDevice *pci;
9069
    pciDevice *other;
9070 9071 9072 9073 9074 9075
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

9076
    pci = pciGetDevice(domain, bus, slot, function);
9077 9078 9079
    if (!pci)
        return -1;

9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093
    other = pciDeviceListFind(driver->activePciHostdevs, pci);
    if (other) {
        const char *other_name = pciDeviceGetUsedBy(other);

        if (other_name)
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            _("PCI device %s is still in use by domain %s"),
                            pciDeviceGetName(pci), other_name);
        else
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            _("PCI device %s is still in use"),
                            pciDeviceGetName(pci));
    }

9094 9095
    pciDeviceReAttachInit(pci);

9096
    qemuDriverLock(driver);
9097 9098
    if (pciReAttachDevice(pci, driver->activePciHostdevs,
                          driver->inactivePciHostdevs) < 0)
9099 9100 9101 9102
        goto out;

    ret = 0;
out:
9103
    qemuDriverUnlock(driver);
9104
    pciFreeDevice(pci);
9105 9106 9107 9108 9109 9110
    return ret;
}

static int
qemudNodeDeviceReset (virNodeDevicePtr dev)
{
9111
    struct qemud_driver *driver = dev->conn->privateData;
9112 9113 9114 9115 9116 9117 9118
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

9119
    pci = pciGetDevice(domain, bus, slot, function);
9120 9121 9122
    if (!pci)
        return -1;

9123 9124
    qemuDriverLock(driver);

9125 9126
    if (pciResetDevice(pci, driver->activePciHostdevs,
                       driver->inactivePciHostdevs) < 0)
9127 9128 9129 9130
        goto out;

    ret = 0;
out:
9131
    qemuDriverUnlock(driver);
9132
    pciFreeDevice(pci);
9133 9134 9135
    return ret;
}

9136 9137 9138
static int
qemuCPUCompare(virConnectPtr conn,
               const char *xmlDesc,
E
Eric Blake 已提交
9139
               unsigned int flags)
9140 9141 9142 9143
{
    struct qemud_driver *driver = conn->privateData;
    int ret = VIR_CPU_COMPARE_ERROR;

E
Eric Blake 已提交
9144 9145
    virCheckFlags(0, VIR_CPU_COMPARE_ERROR);

9146 9147 9148
    qemuDriverLock(driver);

    if (!driver->caps || !driver->caps->host.cpu) {
9149
        qemuReportError(VIR_ERR_OPERATION_INVALID,
9150
                        "%s", _("cannot get host CPU capabilities"));
E
Eric Blake 已提交
9151
    } else {
9152
        ret = cpuCompareXML(driver->caps->host.cpu, xmlDesc);
E
Eric Blake 已提交
9153
    }
9154 9155 9156 9157 9158 9159

    qemuDriverUnlock(driver);

    return ret;
}

9160

9161 9162 9163 9164
static char *
qemuCPUBaseline(virConnectPtr conn ATTRIBUTE_UNUSED,
                const char **xmlCPUs,
                unsigned int ncpus,
E
Eric Blake 已提交
9165
                unsigned int flags)
9166 9167 9168
{
    char *cpu;

E
Eric Blake 已提交
9169 9170
    virCheckFlags(0, NULL);

9171 9172 9173 9174 9175
    cpu = cpuBaselineXML(xmlCPUs, ncpus, NULL, 0);

    return cpu;
}

9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197

static int qemuDomainGetJobInfo(virDomainPtr dom,
                                virDomainJobInfoPtr info) {
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    priv = vm->privateData;

    if (virDomainObjIsActive(vm)) {
9198
        if (priv->job.asyncJob) {
9199
            memcpy(info, &priv->job.info, sizeof(*info));
9200 9201 9202 9203 9204 9205

            /* Refresh elapsed time again just to ensure it
             * is fully updated. This is primarily for benefit
             * of incoming migration which we don't currently
             * monitor actively in the background thread
             */
9206
            if (virTimeMillisNow(&info->timeElapsed) < 0)
9207
                goto cleanup;
9208
            info->timeElapsed -= priv->job.start;
9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227
        } else {
            memset(info, 0, sizeof(*info));
            info->type = VIR_DOMAIN_JOB_NONE;
        }
    } else {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244
static int qemuDomainAbortJob(virDomainPtr dom) {
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

9245 9246
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_ABORT) < 0)
        goto cleanup;
9247

9248
    if (!virDomainObjIsActive(vm)) {
9249 9250
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
9251
        goto endjob;
9252 9253
    }

9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267
    priv = vm->privateData;

    if (!priv->job.asyncJob) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("no job is active on the domain"));
        goto endjob;
    } else if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_IN) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot abort incoming migration;"
                          " use virDomainDestroy instead"));
        goto endjob;
    }

    VIR_DEBUG("Cancelling job at client request");
9268
    qemuDomainObjEnterMonitor(driver, vm);
9269 9270 9271 9272 9273 9274
    ret = qemuMonitorMigrateCancel(priv->mon);
    qemuDomainObjExitMonitor(driver, vm);

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
9275 9276 9277 9278 9279 9280 9281 9282

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


9283 9284 9285 9286 9287 9288 9289 9290 9291 9292
static int
qemuDomainMigrateSetMaxDowntime(virDomainPtr dom,
                                unsigned long long downtime,
                                unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1;

9293
    virCheckFlags(0, -1);
9294 9295 9296

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
9297
    qemuDriverUnlock(driver);
9298 9299 9300 9301 9302 9303

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
9304
        return -1;
9305 9306
    }

9307 9308 9309
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
        goto cleanup;

9310 9311 9312
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
9313
        goto endjob;
9314 9315 9316 9317
    }

    priv = vm->privateData;

9318
    if (priv->job.asyncJob != QEMU_ASYNC_JOB_MIGRATION_OUT) {
9319 9320
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not being migrated"));
9321
        goto endjob;
9322 9323
    }

9324
    VIR_DEBUG("Setting migration downtime to %llums", downtime);
9325
    qemuDomainObjEnterMonitor(driver, vm);
9326 9327 9328 9329 9330 9331
    ret = qemuMonitorSetMigrationDowntime(priv->mon, downtime);
    qemuDomainObjExitMonitor(driver, vm);

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
9332 9333 9334 9335 9336 9337 9338

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352
static int
qemuDomainMigrateSetMaxSpeed(virDomainPtr dom,
                             unsigned long bandwidth,
                             unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(0, -1);

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
9353
    qemuDriverUnlock(driver);
9354 9355 9356 9357 9358 9359

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
9360
        return -1;
9361 9362 9363
    }

    priv = vm->privateData;
9364 9365 9366
    if (virDomainObjIsActive(vm)) {
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
            goto cleanup;
9367

9368 9369 9370 9371 9372 9373
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto endjob;
        }

9374 9375 9376 9377
        VIR_DEBUG("Setting migration bandwidth to %luMbs", bandwidth);
        qemuDomainObjEnterMonitor(driver, vm);
        ret = qemuMonitorSetMigrationSpeed(priv->mon, bandwidth);
        qemuDomainObjExitMonitor(driver, vm);
9378

9379 9380
        if (ret == 0)
            priv->migMaxBandwidth = bandwidth;
9381

9382
endjob:
9383 9384 9385 9386 9387 9388
        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
    } else {
        priv->migMaxBandwidth = bandwidth;
        ret = 0;
    }
9389 9390 9391 9392 9393 9394 9395

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

9396 9397 9398 9399 9400 9401 9402
static int
qemuDomainMigrateGetMaxSpeed(virDomainPtr dom,
                             unsigned long *bandwidth,
                             unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
9403
    qemuDomainObjPrivatePtr priv;
9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419
    int ret = -1;

    virCheckFlags(0, -1);

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

J
Jim Fehlig 已提交
9420 9421
    priv = vm->privateData;
    *bandwidth = priv->migMaxBandwidth;
9422 9423 9424 9425 9426 9427 9428 9429
    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

C
Chris Lalancette 已提交
9430 9431 9432 9433 9434 9435 9436 9437 9438
static int qemuDomainSnapshotIsAllowed(virDomainObjPtr vm)
{
    int i;

    /* FIXME: we need to figure out what else here might succeed; in
     * particular, if it's a raw device but on LVM, we could probably make
     * that succeed as well
     */
    for (i = 0; i < vm->def->ndisks; i++) {
9439 9440 9441
        if ((vm->def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_LUN) ||
            (vm->def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
             STRNEQ_NULLABLE(vm->def->disks[i]->driverType, "qcow2"))) {
C
Chris Lalancette 已提交
9442
            qemuReportError(VIR_ERR_OPERATION_INVALID,
9443 9444
                            _("Disk '%s' does not support snapshotting"),
                            vm->def->disks[i]->src);
C
Chris Lalancette 已提交
9445 9446 9447 9448 9449 9450 9451
            return 0;
        }
    }

    return 1;
}

9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501
static int
qemuDomainSnapshotFSFreeze(struct qemud_driver *driver,
                           virDomainObjPtr vm) {
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int freezed;

    if (priv->agentError) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("QEMU guest agent is not "
                          "available due to an error"));
        return -1;
    }
    if (!priv->agent) {
        qemuReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                        _("QEMU guest agent is not configured"));
        return -1;
    }

    qemuDomainObjEnterAgent(driver, vm);
    freezed = qemuAgentFSFreeze(priv->agent);
    qemuDomainObjExitAgent(driver, vm);

    return freezed;
}

static int
qemuDomainSnapshotFSThaw(struct qemud_driver *driver,
                         virDomainObjPtr vm) {
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int thawed;

    if (priv->agentError) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("QEMU guest agent is not "
                          "available due to an error"));
        return -1;
    }
    if (!priv->agent) {
        qemuReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                        _("QEMU guest agent is not configured"));
        return -1;
    }

    qemuDomainObjEnterAgent(driver, vm);
    thawed = qemuAgentFSThaw(priv->agent);
    qemuDomainObjExitAgent(driver, vm);

    return thawed;
}

9502 9503
/* The domain is expected to be locked and inactive. */
static int
E
Eric Blake 已提交
9504 9505
qemuDomainSnapshotCreateInactive(struct qemud_driver *driver,
                                 virDomainObjPtr vm,
9506 9507
                                 virDomainSnapshotObjPtr snap)
{
E
Eric Blake 已提交
9508
    return qemuDomainSnapshotForEachQcow2(driver, vm, snap, "-c", false);
9509 9510
}

9511 9512
/* The domain is expected to be locked and active. */
static int
9513 9514
qemuDomainSnapshotCreateActive(virConnectPtr conn,
                               struct qemud_driver *driver,
9515
                               virDomainObjPtr *vmptr,
9516 9517
                               virDomainSnapshotObjPtr snap,
                               unsigned int flags)
9518 9519 9520
{
    virDomainObjPtr vm = *vmptr;
    qemuDomainObjPrivatePtr priv = vm->privateData;
9521 9522
    bool resume = false;
    int ret = -1;
9523

9524
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
9525 9526
        return -1;

9527 9528 9529 9530 9531 9532
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

J
Jiri Denemark 已提交
9533
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
9534 9535 9536 9537
        /* savevm monitor command pauses the domain emitting an event which
         * confuses libvirt since it's not notified when qemu resumes the
         * domain. Thus we stop and start CPUs ourselves.
         */
9538 9539
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_NONE) < 0)
9540 9541 9542 9543 9544 9545 9546 9547 9548 9549
            goto cleanup;

        resume = true;
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto cleanup;
        }
    }

9550
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
9551 9552
    ret = qemuMonitorCreateSnapshot(priv->mon, snap->def->name);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570
    if (ret < 0)
        goto cleanup;

    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT) {
        virDomainEventPtr event;

        event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT);
        qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT);
        virDomainAuditStop(vm, "from-snapshot");
        /* We already filtered the _HALT flag for persistent domains
         * only, so this end job never drops the last reference.  */
        ignore_value(qemuDomainObjEndJob(driver, vm));
        resume = false;
        vm = NULL;
        if (event)
            qemuDomainEventQueue(driver, event);
    }
9571

9572 9573
cleanup:
    if (resume && virDomainObjIsActive(vm) &&
J
Jiri Denemark 已提交
9574
        qemuProcessStartCPUs(driver, vm, conn,
9575 9576
                             VIR_DOMAIN_RUNNING_UNPAUSED,
                             QEMU_ASYNC_JOB_NONE) < 0 &&
9577 9578 9579 9580 9581
        virGetLastError() == NULL) {
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("resuming after snapshot failed"));
    }

9582
endjob:
9583
    if (vm && qemuDomainObjEndJob(driver, vm) == 0) {
9584 9585
        /* Only possible if a transient vm quit while our locks were down,
         * in which case we don't want to save snapshot metadata.  */
9586
        *vmptr = NULL;
9587 9588
        ret = -1;
    }
9589 9590 9591 9592

    return ret;
}

9593
static int
9594 9595
qemuDomainSnapshotDiskPrepare(virDomainObjPtr vm, virDomainSnapshotDefPtr def,
                              bool allow_reuse)
9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647
{
    int ret = -1;
    int i;
    bool found = false;
    bool active = virDomainObjIsActive(vm);
    struct stat st;

    for (i = 0; i < def->ndisks; i++) {
        virDomainSnapshotDiskDefPtr disk = &def->disks[i];

        switch (disk->snapshot) {
        case VIR_DOMAIN_DISK_SNAPSHOT_INTERNAL:
            if (active) {
                qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                _("active qemu domains require external disk "
                                  "snapshots; disk %s requested internal"),
                                disk->name);
                goto cleanup;
            }
            if (!vm->def->disks[i]->driverType ||
                STRNEQ(vm->def->disks[i]->driverType, "qcow2")) {
                qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                _("internal snapshot for disk %s unsupported "
                                  "for storage type %s"),
                                disk->name,
                                NULLSTR(vm->def->disks[i]->driverType));
                goto cleanup;
            }
            found = true;
            break;

        case VIR_DOMAIN_DISK_SNAPSHOT_EXTERNAL:
            if (!disk->driverType) {
                if (!(disk->driverType = strdup("qcow2"))) {
                    virReportOOMError();
                    goto cleanup;
                }
            } else if (STRNEQ(disk->driverType, "qcow2")) {
                /* XXX We should also support QED */
                qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                _("external snapshot format for disk %s "
                                  "is unsupported: %s"),
                                disk->name, disk->driverType);
                goto cleanup;
            }
            if (stat(disk->file, &st) < 0) {
                if (errno != ENOENT) {
                    virReportSystemError(errno,
                                         _("unable to stat for disk %s: %s"),
                                         disk->name, disk->file);
                    goto cleanup;
                }
9648
            } else if (!(S_ISBLK(st.st_mode) || allow_reuse)) {
9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683
                qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                _("external snapshot file for disk %s already "
                                  "exists and is not a block device: %s"),
                                disk->name, disk->file);
                goto cleanup;
            }
            found = true;
            break;

        case VIR_DOMAIN_DISK_SNAPSHOT_NO:
            break;

        case VIR_DOMAIN_DISK_SNAPSHOT_DEFAULT:
        default:
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("unexpected code path"));
            goto cleanup;
        }
    }

    if (!found) {
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("disk snapshots require at least one disk to be "
                          "selected for snapshot"));
        goto cleanup;
    }

    ret = 0;

cleanup:
    return ret;
}

/* The domain is expected to hold monitor lock.  */
static int
9684 9685
qemuDomainSnapshotCreateSingleDiskActive(struct qemud_driver *driver,
                                         virDomainObjPtr vm,
9686
                                         virDomainSnapshotDiskDefPtr snap,
9687 9688
                                         virDomainDiskDefPtr disk,
                                         virDomainDiskDefPtr persistDisk)
9689 9690 9691 9692 9693
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *device = NULL;
    char *source = NULL;
    char *driverType = NULL;
9694 9695
    char *persistSource = NULL;
    char *persistDriverType = NULL;
9696
    int ret = -1;
9697 9698 9699 9700
    int fd = -1;
    char *origsrc = NULL;
    char *origdriver = NULL;
    bool need_unlink = false;
9701 9702 9703 9704 9705 9706 9707 9708 9709 9710

    if (snap->snapshot != VIR_DOMAIN_DISK_SNAPSHOT_EXTERNAL) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("unexpected code path"));
        return -1;
    }

    if (virAsprintf(&device, "drive-%s", disk->info.alias) < 0 ||
        !(source = strdup(snap->file)) ||
        (STRNEQ_NULLABLE(disk->driverType, "qcow2") &&
9711 9712 9713 9714 9715
         !(driverType = strdup("qcow2"))) ||
        (persistDisk &&
         (!(persistSource = strdup(source)) ||
          (STRNEQ_NULLABLE(persistDisk->driverType, "qcow2") &&
           !(persistDriverType = strdup("qcow2")))))) {
9716 9717 9718 9719
        virReportOOMError();
        goto cleanup;
    }

9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730
    /* create the stub file and set selinux labels; manipulate disk in
     * place, in a way that can be reverted on failure. */
    fd = qemuOpenFile(driver, source, O_WRONLY | O_TRUNC | O_CREAT,
                      &need_unlink, NULL);
    if (fd < 0)
        goto cleanup;
    VIR_FORCE_CLOSE(fd);

    origsrc = disk->src;
    disk->src = source;
    origdriver = disk->driverType;
9731
    disk->driverType = (char *) "raw"; /* Don't want to probe backing files */
9732 9733 9734

    if (virDomainLockDiskAttach(driver->lockManager, vm, disk) < 0)
        goto cleanup;
9735
    if (virSecurityManagerSetImageLabel(driver->securityManager, vm->def,
9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747
                                        disk) < 0) {
        if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
            VIR_WARN("Unable to release lock on %s", source);
        goto cleanup;
    }

    disk->src = origsrc;
    origsrc = NULL;
    disk->driverType = origdriver;
    origdriver = NULL;

    /* create the actual snapshot */
9748 9749 9750 9751 9752 9753
    ret = qemuMonitorDiskSnapshot(priv->mon, device, source);
    virDomainAuditDisk(vm, disk->src, source, "snapshot", ret >= 0);
    if (ret < 0)
        goto cleanup;

    /* Update vm in place to match changes.  */
9754
    need_unlink = false;
9755 9756 9757 9758 9759 9760 9761 9762
    VIR_FREE(disk->src);
    disk->src = source;
    source = NULL;
    if (driverType) {
        VIR_FREE(disk->driverType);
        disk->driverType = driverType;
        driverType = NULL;
    }
9763 9764 9765 9766 9767 9768 9769 9770 9771 9772
    if (persistDisk) {
        VIR_FREE(persistDisk->src);
        persistDisk->src = persistSource;
        persistSource = NULL;
        if (persistDriverType) {
            VIR_FREE(persistDisk->driverType);
            persistDisk->driverType = persistDriverType;
            persistDriverType = NULL;
        }
    }
9773 9774

cleanup:
9775 9776 9777 9778 9779 9780
    if (origsrc) {
        disk->src = origsrc;
        disk->driverType = origdriver;
    }
    if (need_unlink && unlink(source))
        VIR_WARN("unable to unlink just-created %s", source);
9781 9782 9783
    VIR_FREE(device);
    VIR_FREE(source);
    VIR_FREE(driverType);
9784 9785
    VIR_FREE(persistSource);
    VIR_FREE(persistDriverType);
9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800
    return ret;
}

/* The domain is expected to be locked and active. */
static int
qemuDomainSnapshotCreateDiskActive(virConnectPtr conn,
                                   struct qemud_driver *driver,
                                   virDomainObjPtr *vmptr,
                                   virDomainSnapshotObjPtr snap,
                                   unsigned int flags)
{
    virDomainObjPtr vm = *vmptr;
    bool resume = false;
    int ret = -1;
    int i;
9801
    bool persist = false;
9802 9803 9804 9805

    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
        return -1;

9806 9807 9808 9809 9810 9811 9812
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }


9813
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
9814 9815 9816 9817 9818 9819
        if ((flags & VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) &&
            (qemuDomainSnapshotFSFreeze(driver, vm) < 0)) {
            /* helper reported the error */
            goto endjob;
        }

9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844
        /* In qemu, snapshot_blkdev on a single disk will pause cpus,
         * but this confuses libvirt since notifications are not given
         * when qemu resumes.  And for multiple disks, libvirt must
         * pause externally to get all snapshots to be at the same
         * point in time.  For simplicitly, we always pause ourselves
         * rather than relying on qemu doing pause.
         */
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_NONE) < 0)
            goto cleanup;

        resume = true;
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto cleanup;
        }
    }

    /* No way to roll back if first disk succeeds but later disks
     * fail.  Based on earlier qemuDomainSnapshotDiskPrepare, all
     * disks in this list are now either SNAPSHOT_NO, or
     * SNAPSHOT_EXTERNAL with a valid file name and qcow2 format.  */
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    for (i = 0; i < snap->def->ndisks; i++) {
9845 9846
        virDomainDiskDefPtr persistDisk = NULL;

9847 9848
        if (snap->def->disks[i].snapshot == VIR_DOMAIN_DISK_SNAPSHOT_NO)
            continue;
9849 9850 9851 9852 9853 9854 9855 9856 9857
        if (vm->newDef) {
            int indx = virDomainDiskIndexByName(vm->newDef,
                                                vm->def->disks[i]->dst,
                                                false);
            if (indx >= 0) {
                persistDisk = vm->newDef->disks[indx];
                persist = true;
            }
        }
9858

9859
        ret = qemuDomainSnapshotCreateSingleDiskActive(driver, vm,
9860
                                                       &snap->def->disks[i],
9861 9862
                                                       vm->def->disks[i],
                                                       persistDisk);
9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886
        if (ret < 0)
            break;
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);
    if (ret < 0)
        goto cleanup;

    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT) {
        virDomainEventPtr event;

        event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT);
        qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT);
        virDomainAuditStop(vm, "from-snapshot");
        /* We already filtered the _HALT flag for persistent domains
         * only, so this end job never drops the last reference.  */
        ignore_value(qemuDomainObjEndJob(driver, vm));
        resume = false;
        vm = NULL;
        if (event)
            qemuDomainEventQueue(driver, event);
    }

cleanup:
9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900
    if (resume && virDomainObjIsActive(vm)) {
        if (qemuProcessStartCPUs(driver, vm, conn,
                                 VIR_DOMAIN_RUNNING_UNPAUSED,
                                 QEMU_ASYNC_JOB_NONE) < 0 &&
            virGetLastError() == NULL) {
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("resuming after snapshot failed"));
            goto endjob;
        }

        if ((flags & VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) &&
            qemuDomainSnapshotFSThaw(driver, vm) < 0) {
            /* helper reported the error */
        }
9901 9902 9903
    }

    if (vm) {
9904 9905 9906
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0 ||
            (persist &&
             virDomainSaveConfig(driver->configDir, vm->newDef) < 0))
9907
            ret = -1;
9908 9909 9910 9911
    }

endjob:
    if (vm && (qemuDomainObjEndJob(driver, vm) == 0)) {
9912 9913 9914 9915 9916 9917 9918 9919 9920
            /* Only possible if a transient vm quit while our locks were down,
             * in which case we don't want to save snapshot metadata.  */
            *vmptr = NULL;
            ret = -1;
    }

    return ret;
}

9921 9922 9923 9924
static virDomainSnapshotPtr
qemuDomainSnapshotCreateXML(virDomainPtr domain,
                            const char *xmlDesc,
                            unsigned int flags)
C
Chris Lalancette 已提交
9925 9926 9927
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
9928
    char *xml = NULL;
C
Chris Lalancette 已提交
9929 9930 9931
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
9932
    virDomainSnapshotDefPtr def = NULL;
9933 9934
    bool update_current = true;
    unsigned int parse_flags = 0;
9935
    virDomainSnapshotObjPtr other = NULL;
C
Chris Lalancette 已提交
9936

9937 9938
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE |
                  VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT |
9939
                  VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA |
9940
                  VIR_DOMAIN_SNAPSHOT_CREATE_HALT |
9941
                  VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY |
9942 9943 9944 9945 9946 9947 9948 9949 9950
                  VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT |
                  VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE, NULL);

    if ((flags & VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) &&
        !(flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("quiesce requires disk-only"));
        return NULL;
    }
9951 9952 9953 9954 9955 9956 9957

    if (((flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) &&
         !(flags & VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT)) ||
        (flags & VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA))
        update_current = false;
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE)
        parse_flags |= VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE;
9958 9959
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY)
        parse_flags |= VIR_DOMAIN_SNAPSHOT_PARSE_DISKS;
9960

C
Chris Lalancette 已提交
9961 9962 9963 9964 9965 9966 9967 9968 9969
    qemuDriverLock(driver);
    virUUIDFormat(domain->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

9970 9971 9972 9973 9974
    if (qemuProcessAutoDestroyActive(driver, vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is marked for auto destroy"));
        goto cleanup;
    }
9975 9976 9977 9978 9979
    if (!vm->persistent && (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot halt after transient domain snapshot"));
        goto cleanup;
    }
9980

9981 9982 9983
    if (!(def = virDomainSnapshotDefParseString(xmlDesc, driver->caps,
                                                QEMU_EXPECTED_VIRT_TYPES,
                                                parse_flags)))
C
Chris Lalancette 已提交
9984 9985
        goto cleanup;

9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) {
        /* Prevent circular chains */
        if (def->parent) {
            if (STREQ(def->name, def->parent)) {
                qemuReportError(VIR_ERR_INVALID_ARG,
                                _("cannot set snapshot %s as its own parent"),
                                def->name);
                goto cleanup;
            }
            other = virDomainSnapshotFindByName(&vm->snapshots, def->parent);
            if (!other) {
                qemuReportError(VIR_ERR_INVALID_ARG,
                                _("parent %s for snapshot %s not found"),
                                def->parent, def->name);
                goto cleanup;
            }
            while (other->def->parent) {
                if (STREQ(other->def->parent, def->name)) {
                    qemuReportError(VIR_ERR_INVALID_ARG,
                                    _("parent %s would create cycle to %s"),
                                    other->def->name, def->name);
                    goto cleanup;
                }
                other = virDomainSnapshotFindByName(&vm->snapshots,
                                                    other->def->parent);
                if (!other) {
                    VIR_WARN("snapshots are inconsistent for %s",
                             vm->def->name);
                    break;
                }
            }
        }

        /* Check that any replacement is compatible */
10020 10021 10022 10023 10024 10025 10026
        if (def->dom &&
            memcmp(def->dom->uuid, domain->uuid, VIR_UUID_BUFLEN)) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("definition for snapshot %s must use uuid %s"),
                            def->name, uuidstr);
            goto cleanup;
        }
10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038
        other = virDomainSnapshotFindByName(&vm->snapshots, def->name);
        if (other) {
            if ((other->def->state == VIR_DOMAIN_RUNNING ||
                 other->def->state == VIR_DOMAIN_PAUSED) !=
                (def->state == VIR_DOMAIN_RUNNING ||
                 def->state == VIR_DOMAIN_PAUSED)) {
                qemuReportError(VIR_ERR_INVALID_ARG,
                                _("cannot change between online and offline "
                                  "snapshot state in snapshot %s"),
                                def->name);
                goto cleanup;
            }
10039 10040 10041 10042 10043 10044 10045 10046
            if ((other->def->state == VIR_DOMAIN_DISK_SNAPSHOT) !=
                (def->state == VIR_DOMAIN_DISK_SNAPSHOT)) {
                qemuReportError(VIR_ERR_INVALID_ARG,
                                _("cannot change between disk snapshot and "
                                  "system checkpoint in snapshot %s"),
                                def->name);
                goto cleanup;
            }
10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057
            if (other->def->dom) {
                if (def->dom) {
                    if (!virDomainDefCheckABIStability(other->def->dom,
                                                       def->dom))
                        goto cleanup;
                } else {
                    /* Transfer the domain def */
                    def->dom = other->def->dom;
                    other->def->dom = NULL;
                }
            }
10058 10059 10060 10061
            if (other == vm->current_snapshot) {
                update_current = true;
                vm->current_snapshot = NULL;
            }
10062 10063 10064 10065 10066 10067
            /* Drop and rebuild the parent relationship, but keep all
             * child relations by reusing snap.  */
            virDomainSnapshotDropParent(&vm->snapshots, other);
            virDomainSnapshotDefFree(other->def);
            other->def = NULL;
            snap = other;
10068
        }
10069 10070 10071 10072 10073 10074
        if (def->state == VIR_DOMAIN_DISK_SNAPSHOT && def->dom) {
            if (virDomainSnapshotAlignDisks(def,
                                            VIR_DOMAIN_DISK_SNAPSHOT_EXTERNAL,
                                            false) < 0)
                goto cleanup;
        }
10075 10076 10077 10078 10079 10080 10081 10082 10083 10084
    } else {
        /* Easiest way to clone inactive portion of vm->def is via
         * conversion in and back out of xml.  */
        if (!(xml = virDomainDefFormat(vm->def, (VIR_DOMAIN_XML_INACTIVE |
                                                 VIR_DOMAIN_XML_SECURE))) ||
            !(def->dom = virDomainDefParseString(driver->caps, xml,
                                                 QEMU_EXPECTED_VIRT_TYPES,
                                                 VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

10085
        if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) {
10086 10087 10088
            bool allow_reuse;

            allow_reuse = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT) != 0;
10089 10090 10091 10092
            if (virDomainSnapshotAlignDisks(def,
                                            VIR_DOMAIN_DISK_SNAPSHOT_EXTERNAL,
                                            false) < 0)
                goto cleanup;
10093
            if (qemuDomainSnapshotDiskPrepare(vm, def, allow_reuse) < 0)
10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109
                goto cleanup;
            def->state = VIR_DOMAIN_DISK_SNAPSHOT;
        } else {
            /* In a perfect world, we would allow qemu to tell us this.
             * The problem is that qemu only does this check
             * device-by-device; so if you had a domain that booted from a
             * large qcow2 device, but had a secondary raw device
             * attached, you wouldn't find out that you can't snapshot
             * your guest until *after* it had spent the time to snapshot
             * the boot device.  This is probably a bug in qemu, but we'll
             * work around it here for now.
             */
            if (!qemuDomainSnapshotIsAllowed(vm))
                goto cleanup;
            def->state = virDomainObjGetState(vm, NULL);
        }
10110 10111
    }

10112 10113 10114
    if (snap)
        snap->def = def;
    else if (!(snap = virDomainSnapshotAssignDef(&vm->snapshots, def)))
C
Chris Lalancette 已提交
10115
        goto cleanup;
10116
    def = NULL;
C
Chris Lalancette 已提交
10117

10118 10119
    if (update_current)
        snap->def->current = true;
10120
    if (vm->current_snapshot) {
10121 10122 10123 10124 10125 10126
        if (!(flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE)) {
            snap->def->parent = strdup(vm->current_snapshot->def->name);
            if (snap->def->parent == NULL) {
                virReportOOMError();
                goto cleanup;
            }
10127
        }
10128
        if (update_current) {
10129 10130 10131 10132 10133 10134
            vm->current_snapshot->def->current = false;
            if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                                driver->snapshotDir) < 0)
                goto cleanup;
            vm->current_snapshot = NULL;
        }
10135
    }
10136

C
Chris Lalancette 已提交
10137
    /* actually do the snapshot */
10138 10139
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) {
        /* XXX Should we validate that the redefined snapshot even
10140 10141
         * makes sense, such as checking that qemu-img recognizes the
         * snapshot name in at least one of the domain's disks?  */
10142 10143 10144 10145 10146 10147 10148 10149 10150 10151
    } else if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) {
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                            _("disk snapshots of inactive domains not "
                              "implemented yet"));
            goto cleanup;
        }
        if (qemuDomainSnapshotCreateDiskActive(domain->conn, driver,
                                               &vm, snap, flags) < 0)
            goto cleanup;
10152
    } else if (!virDomainObjIsActive(vm)) {
E
Eric Blake 已提交
10153
        if (qemuDomainSnapshotCreateInactive(driver, vm, snap) < 0)
C
Chris Lalancette 已提交
10154
            goto cleanup;
E
Eric Blake 已提交
10155
    } else {
10156
        if (qemuDomainSnapshotCreateActive(domain->conn, driver,
10157
                                           &vm, snap, flags) < 0)
10158
            goto cleanup;
C
Chris Lalancette 已提交
10159 10160
    }

10161
    /* If we fail after this point, there's not a whole lot we can
C
Chris Lalancette 已提交
10162 10163 10164 10165 10166 10167
     * do; we've successfully taken the snapshot, and we are now running
     * on it, so we have to go forward the best we can
     */
    snapshot = virGetDomainSnapshot(domain, snap->def->name);

cleanup:
10168
    if (vm) {
10169
        if (snapshot && !(flags & VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA)) {
10170
            if (qemuDomainSnapshotWriteMetadata(vm, snap,
10171
                                                driver->snapshotDir) < 0) {
10172 10173
                VIR_WARN("unable to save metadata for snapshot %s",
                         snap->def->name);
10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189
            } else {
                if (update_current)
                    vm->current_snapshot = snap;
                if (snap->def->parent) {
                    other = virDomainSnapshotFindByName(&vm->snapshots,
                                                        snap->def->parent);
                    snap->parent = other;
                    other->nchildren++;
                    snap->sibling = other->first_child;
                    other->first_child = snap;
                } else {
                    vm->snapshots.nroots++;
                    snap->sibling = vm->snapshots.first_root;
                    vm->snapshots.first_root = snap;
                }
            }
10190
        } else if (snap) {
10191
            virDomainSnapshotObjListRemove(&vm->snapshots, snap);
10192
        }
C
Chris Lalancette 已提交
10193
        virDomainObjUnlock(vm);
10194 10195
    }
    virDomainSnapshotDefFree(def);
10196
    VIR_FREE(xml);
C
Chris Lalancette 已提交
10197 10198 10199 10200 10201 10202
    qemuDriverUnlock(driver);
    return snapshot;
}

static int qemuDomainSnapshotListNames(virDomainPtr domain, char **names,
                                       int nameslen,
10203
                                       unsigned int flags)
C
Chris Lalancette 已提交
10204 10205 10206 10207 10208
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

10209
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
10210 10211
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
10212

C
Chris Lalancette 已提交
10213 10214 10215 10216 10217 10218 10219 10220 10221 10222
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

10223 10224
    n = virDomainSnapshotObjListGetNames(&vm->snapshots, names, nameslen,
                                         flags);
C
Chris Lalancette 已提交
10225 10226 10227 10228 10229 10230 10231 10232 10233

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return n;
}

static int qemuDomainSnapshotNum(virDomainPtr domain,
10234
                                 unsigned int flags)
C
Chris Lalancette 已提交
10235 10236 10237 10238 10239
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

10240
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
10241 10242
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
10243

C
Chris Lalancette 已提交
10244 10245 10246 10247 10248 10249 10250 10251 10252 10253
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

10254 10255 10256 10257
    /* All qemu snapshots have libvirt metadata, so
     * VIR_DOMAIN_SNAPSHOT_LIST_METADATA makes no difference to our
     * answer.  */

10258
    n = virDomainSnapshotObjListNum(&vm->snapshots, flags);
C
Chris Lalancette 已提交
10259 10260 10261 10262 10263 10264 10265 10266

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return n;
}

10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278
static int
qemuDomainSnapshotListChildrenNames(virDomainSnapshotPtr snapshot,
                                    char **names,
                                    int nameslen,
                                    unsigned int flags)
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    int n = -1;

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
10279 10280
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(snapshot->domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
    if (!snap) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                        _("no domain snapshot with matching name '%s'"),
                        snapshot->name);
        goto cleanup;
    }

E
Eric Blake 已提交
10300
    n = virDomainSnapshotObjListGetNamesFrom(snap, names, nameslen, flags);
10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return n;
}

static int
qemuDomainSnapshotNumChildren(virDomainSnapshotPtr snapshot,
                              unsigned int flags)
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    int n = -1;

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
10319 10320
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(snapshot->domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
    if (!snap) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                        _("no domain snapshot with matching name '%s'"),
                        snapshot->name);
        goto cleanup;
    }

    /* All qemu snapshots have libvirt metadata, so
     * VIR_DOMAIN_SNAPSHOT_LIST_METADATA makes no difference to our
     * answer.  */

E
Eric Blake 已提交
10344
    n = virDomainSnapshotObjListNumFrom(snap, flags);
10345 10346 10347 10348 10349 10350 10351 10352

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return n;
}

C
Chris Lalancette 已提交
10353 10354
static virDomainSnapshotPtr qemuDomainSnapshotLookupByName(virDomainPtr domain,
                                                           const char *name,
10355
                                                           unsigned int flags)
C
Chris Lalancette 已提交
10356 10357 10358 10359 10360 10361
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;

10362 10363
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    snap = virDomainSnapshotFindByName(&vm->snapshots, name);
    if (!snap) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                        _("no snapshot with matching name '%s'"), name);
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, snap->def->name);

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return snapshot;
}

static int qemuDomainHasCurrentSnapshot(virDomainPtr domain,
10391
                                        unsigned int flags)
C
Chris Lalancette 已提交
10392 10393 10394 10395 10396
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

10397 10398
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    ret = (vm->current_snapshot != NULL);

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462
static virDomainSnapshotPtr
qemuDomainSnapshotGetParent(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr parent = NULL;

    virCheckFlags(0, NULL);

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(snapshot->domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
    if (!snap) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                        _("no domain snapshot with matching name '%s'"),
                        snapshot->name);
        goto cleanup;
    }

    if (!snap->def->parent) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                        _("snapshot '%s' does not have a parent"),
                        snap->def->name);
        goto cleanup;
    }

    parent = virGetDomainSnapshot(snapshot->domain, snap->def->parent);

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return parent;
}

C
Chris Lalancette 已提交
10463
static virDomainSnapshotPtr qemuDomainSnapshotCurrent(virDomainPtr domain,
10464
                                                      unsigned int flags)
C
Chris Lalancette 已提交
10465 10466 10467 10468 10469
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotPtr snapshot = NULL;

10470 10471
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!vm->current_snapshot) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT, "%s",
                        _("the domain does not have a current snapshot"));
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, vm->current_snapshot->def->name);

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return snapshot;
}

10497 10498
static char *qemuDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                                          unsigned int flags)
C
Chris Lalancette 已提交
10499 10500 10501 10502 10503 10504 10505
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *xml = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

10506
    virCheckFlags(VIR_DOMAIN_XML_SECURE, NULL);
10507

C
Chris Lalancette 已提交
10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524
    qemuDriverLock(driver);
    virUUIDFormat(snapshot->domain->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
    if (!snap) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                        _("no domain snapshot with matching name '%s'"),
                        snapshot->name);
        goto cleanup;
    }

10525
    xml = virDomainSnapshotDefFormat(uuidstr, snap->def, flags, 0);
C
Chris Lalancette 已提交
10526 10527 10528 10529 10530 10531 10532 10533

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return xml;
}

10534 10535
/* The domain is expected to be locked and inactive. */
static int
E
Eric Blake 已提交
10536 10537
qemuDomainSnapshotRevertInactive(struct qemud_driver *driver,
                                 virDomainObjPtr vm,
10538 10539 10540
                                 virDomainSnapshotObjPtr snap)
{
    /* Try all disks, but report failure if we skipped any.  */
E
Eric Blake 已提交
10541
    int ret = qemuDomainSnapshotForEachQcow2(driver, vm, snap, "-a", true);
10542 10543 10544
    return ret > 0 ? -1 : ret;
}

C
Chris Lalancette 已提交
10545
static int qemuDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
10546
                                      unsigned int flags)
C
Chris Lalancette 已提交
10547 10548 10549 10550 10551 10552 10553
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virDomainEventPtr event = NULL;
10554
    virDomainEventPtr event2 = NULL;
10555
    int detail;
C
Chris Lalancette 已提交
10556 10557
    qemuDomainObjPrivatePtr priv;
    int rc;
10558
    virDomainDefPtr config = NULL;
C
Chris Lalancette 已提交
10559

10560
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING |
10561 10562
                  VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED |
                  VIR_DOMAIN_SNAPSHOT_REVERT_FORCE, -1);
10563

10564 10565 10566 10567 10568 10569 10570 10571 10572 10573
    /* We have the following transitions, which create the following events:
     * 1. inactive -> inactive: none
     * 2. inactive -> running:  EVENT_STARTED
     * 3. inactive -> paused:   EVENT_STARTED, EVENT_PAUSED
     * 4. running  -> inactive: EVENT_STOPPED
     * 5. running  -> running:  none
     * 6. running  -> paused:   EVENT_PAUSED
     * 7. paused   -> inactive: EVENT_STOPPED
     * 8. paused   -> running:  EVENT_RESUMED
     * 9. paused   -> paused:   none
10574 10575
     * Also, several transitions occur even if we fail partway through,
     * and use of FORCE can cause multiple transitions.
10576 10577
     */

C
Chris Lalancette 已提交
10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594
    qemuDriverLock(driver);
    virUUIDFormat(snapshot->domain->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
    if (!snap) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                        _("no domain snapshot with matching name '%s'"),
                        snapshot->name);
        goto cleanup;
    }

10595 10596 10597 10598 10599 10600 10601 10602 10603 10604
    if (!vm->persistent &&
        snap->def->state != VIR_DOMAIN_RUNNING &&
        snap->def->state != VIR_DOMAIN_PAUSED &&
        (flags & (VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING |
                  VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED)) == 0) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("transient domain needs to request run or pause "
                          "to revert to inactive snapshot"));
        goto cleanup;
    }
10605 10606 10607 10608 10609 10610
    if (snap->def->state == VIR_DOMAIN_DISK_SNAPSHOT) {
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("revert to external disk snapshot not supported "
                          "yet"));
        goto cleanup;
    }
10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628
    if (!(flags & VIR_DOMAIN_SNAPSHOT_REVERT_FORCE)) {
        if (!snap->def->dom) {
            qemuReportError(VIR_ERR_SNAPSHOT_REVERT_RISKY,
                            _("snapshot '%s' lacks domain '%s' rollback info"),
                            snap->def->name, vm->def->name);
            goto cleanup;
        }
        if (virDomainObjIsActive(vm) &&
            !(snap->def->state == VIR_DOMAIN_RUNNING
              || snap->def->state == VIR_DOMAIN_PAUSED) &&
            (flags & (VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING |
                      VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED))) {
            qemuReportError(VIR_ERR_SNAPSHOT_REVERT_RISKY,
                            _("must respawn qemu to start inactive snapshot"));
            goto cleanup;
        }
    }

10629

10630 10631 10632 10633 10634 10635 10636 10637 10638 10639
    if (vm->current_snapshot) {
        vm->current_snapshot->def->current = false;
        if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                            driver->snapshotDir) < 0)
            goto cleanup;
        vm->current_snapshot = NULL;
        /* XXX Should we restore vm->current_snapshot after this point
         * in the failure cases where we know there was no change?  */
    }

10640 10641 10642 10643 10644
    /* Prepare to copy the snapshot inactive xml as the config of this
     * domain.  Easiest way is by a round trip through xml.
     *
     * XXX Should domain snapshots track live xml rather
     * than inactive xml?  */
10645
    snap->def->current = true;
10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658
    if (snap->def->dom) {
        char *xml;
        if (!(xml = virDomainDefFormat(snap->def->dom,
                                       (VIR_DOMAIN_XML_INACTIVE |
                                        VIR_DOMAIN_XML_SECURE))))
            goto cleanup;
        config = virDomainDefParseString(driver->caps, xml,
                                         QEMU_EXPECTED_VIRT_TYPES,
                                         VIR_DOMAIN_XML_INACTIVE);
        VIR_FREE(xml);
        if (!config)
            goto cleanup;
    }
C
Chris Lalancette 已提交
10659

10660
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
C
Chris Lalancette 已提交
10661 10662 10663 10664
        goto cleanup;

    if (snap->def->state == VIR_DOMAIN_RUNNING
        || snap->def->state == VIR_DOMAIN_PAUSED) {
10665 10666 10667 10668 10669 10670 10671 10672 10673
        /* Transitions 2, 3, 5, 6, 8, 9 */
        bool was_running = false;
        bool was_stopped = false;

        /* When using the loadvm monitor command, qemu does not know
         * whether to pause or run the reverted domain, and just stays
         * in the same state as before the monitor command, whether
         * that is paused or running.  We always pause before loadvm,
         * to have finer control.  */
C
Chris Lalancette 已提交
10674
        if (virDomainObjIsActive(vm)) {
10675
            /* Transitions 5, 6, 8, 9 */
10676 10677
            /* Check for ABI compatibility.  */
            if (config && !virDomainDefCheckABIStability(vm->def, config)) {
10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697
                virErrorPtr err = virGetLastError();

                if (!(flags & VIR_DOMAIN_SNAPSHOT_REVERT_FORCE)) {
                    /* Re-spawn error using correct category. */
                    if (err->code == VIR_ERR_CONFIG_UNSUPPORTED)
                        qemuReportError(VIR_ERR_SNAPSHOT_REVERT_RISKY, "%s",
                                        err->str2);
                    goto endjob;
                }
                virResetError(err);
                qemuProcessStop(driver, vm, 0,
                                VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT);
                virDomainAuditStop(vm, "from-snapshot");
                detail = VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT;
                event = virDomainEventNewFromObj(vm,
                                                 VIR_DOMAIN_EVENT_STOPPED,
                                                 detail);
                if (event)
                    qemuDomainEventQueue(driver, event);
                goto load;
10698 10699
            }

C
Chris Lalancette 已提交
10700
            priv = vm->privateData;
10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720
            if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
                /* Transitions 5, 6 */
                was_running = true;
                if (qemuProcessStopCPUs(driver, vm,
                                        VIR_DOMAIN_PAUSED_FROM_SNAPSHOT,
                                        QEMU_ASYNC_JOB_NONE) < 0)
                    goto endjob;
                /* Create an event now in case the restore fails, so
                 * that user will be alerted that they are now paused.
                 * If restore later succeeds, we might replace this. */
                detail = VIR_DOMAIN_EVENT_SUSPENDED_FROM_SNAPSHOT;
                event = virDomainEventNewFromObj(vm,
                                                 VIR_DOMAIN_EVENT_SUSPENDED,
                                                 detail);
                if (!virDomainObjIsActive(vm)) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                    _("guest unexpectedly quit"));
                    goto endjob;
                }
            }
10721
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
C
Chris Lalancette 已提交
10722 10723
            rc = qemuMonitorLoadSnapshot(priv->mon, snap->def->name);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
10724 10725 10726
            if (rc < 0) {
                /* XXX resume domain if it was running before the
                 * failed loadvm attempt? */
10727
                goto endjob;
10728
            }
10729 10730
            if (config)
                virDomainObjAssignDef(vm, config, false);
E
Eric Blake 已提交
10731
        } else {
10732
            /* Transitions 2, 3 */
10733
        load:
10734
            was_stopped = true;
10735 10736 10737
            if (config)
                virDomainObjAssignDef(vm, config, false);

10738
            rc = qemuProcessStart(snapshot->domain->conn, driver, vm, NULL,
10739
                                  true, false, -1, NULL, snap,
10740
                                  VIR_NETDEV_VPORT_PROFILE_OP_CREATE);
10741
            virDomainAuditStart(vm, "from-snapshot", rc >= 0);
10742 10743 10744 10745
            detail = VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT;
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STARTED,
                                             detail);
C
Chris Lalancette 已提交
10746
            if (rc < 0)
10747
                goto endjob;
C
Chris Lalancette 已提交
10748 10749
        }

10750
        /* Touch up domain state.  */
10751 10752 10753
        if (!(flags & VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING) &&
            (snap->def->state == VIR_DOMAIN_PAUSED ||
             (flags & VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED))) {
10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773
            /* Transitions 3, 6, 9 */
            virDomainObjSetState(vm, VIR_DOMAIN_PAUSED,
                                 VIR_DOMAIN_PAUSED_FROM_SNAPSHOT);
            if (was_stopped) {
                /* Transition 3, use event as-is and add event2 */
                detail = VIR_DOMAIN_EVENT_SUSPENDED_FROM_SNAPSHOT;
                event2 = virDomainEventNewFromObj(vm,
                                                  VIR_DOMAIN_EVENT_SUSPENDED,
                                                  detail);
            } /* else transition 6 and 9 use event as-is */
        } else {
            /* Transitions 2, 5, 8 */
            if (!virDomainObjIsActive(vm)) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("guest unexpectedly quit"));
                goto endjob;
            }
            rc = qemuProcessStartCPUs(driver, vm, snapshot->domain->conn,
                                      VIR_DOMAIN_RUNNING_FROM_SNAPSHOT,
                                      QEMU_ASYNC_JOB_NONE);
H
Hu Tao 已提交
10774
            if (rc < 0)
10775
                goto endjob;
10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790
            virDomainEventFree(event);
            event = NULL;
            if (was_stopped) {
                /* Transition 2 */
                detail = VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT;
                event = virDomainEventNewFromObj(vm,
                                                 VIR_DOMAIN_EVENT_STARTED,
                                                 detail);
            } else if (was_running) {
                /* Transition 8 */
                detail = VIR_DOMAIN_EVENT_RESUMED;
                event = virDomainEventNewFromObj(vm,
                                                 VIR_DOMAIN_EVENT_RESUMED,
                                                 detail);
            }
C
Chris Lalancette 已提交
10791
        }
E
Eric Blake 已提交
10792
    } else {
10793
        /* Transitions 1, 4, 7 */
10794 10795 10796
        /* Newer qemu -loadvm refuses to revert to the state of a snapshot
         * created by qemu-img snapshot -c.  If the domain is running, we
         * must take it offline; then do the revert using qemu-img.
C
Chris Lalancette 已提交
10797 10798 10799
         */

        if (virDomainObjIsActive(vm)) {
10800
            /* Transitions 4, 7 */
J
Jiri Denemark 已提交
10801
            qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT);
10802
            virDomainAuditStop(vm, "from-snapshot");
10803
            detail = VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT;
C
Chris Lalancette 已提交
10804 10805
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STOPPED,
10806
                                             detail);
10807 10808
        }

E
Eric Blake 已提交
10809
        if (qemuDomainSnapshotRevertInactive(driver, vm, snap) < 0) {
10810
            if (!vm->persistent) {
10811
                if (qemuDomainObjEndJob(driver, vm) > 0)
10812
                    qemuDomainRemoveInactive(driver, vm);
10813
                vm = NULL;
10814
                goto cleanup;
10815
            }
10816
            goto endjob;
C
Chris Lalancette 已提交
10817
        }
10818 10819
        if (config)
            virDomainObjAssignDef(vm, config, false);
10820

10821 10822 10823 10824 10825 10826 10827 10828 10829
        if (flags & (VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING |
                     VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED)) {
            /* Flush first event, now do transition 2 or 3 */
            bool paused = (flags & VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED) != 0;

            if (event)
                qemuDomainEventQueue(driver, event);
            rc = qemuProcessStart(snapshot->domain->conn, driver, vm, NULL,
                                  paused, false, -1, NULL, NULL,
10830
                                  VIR_NETDEV_VPORT_PROFILE_OP_CREATE);
10831 10832 10833 10834
            virDomainAuditStart(vm, "from-snapshot", rc >= 0);
            if (rc < 0) {
                if (!vm->persistent) {
                    if (qemuDomainObjEndJob(driver, vm) > 0)
10835
                        qemuDomainRemoveInactive(driver, vm);
10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851
                    vm = NULL;
                    goto cleanup;
                }
                goto endjob;
            }
            detail = VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT;
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STARTED,
                                             detail);
            if (paused) {
                detail = VIR_DOMAIN_EVENT_SUSPENDED_FROM_SNAPSHOT;
                event2 = virDomainEventNewFromObj(vm,
                                                  VIR_DOMAIN_EVENT_SUSPENDED,
                                                  detail);
            }
        }
C
Chris Lalancette 已提交
10852 10853 10854 10855
    }

    ret = 0;

10856
endjob:
10857
    if (vm && qemuDomainObjEndJob(driver, vm) == 0)
C
Chris Lalancette 已提交
10858 10859
        vm = NULL;

10860
cleanup:
10861 10862 10863 10864 10865 10866 10867 10868 10869
    if (vm && ret == 0) {
        if (qemuDomainSnapshotWriteMetadata(vm, snap,
                                            driver->snapshotDir) < 0)
            ret = -1;
        else
            vm->current_snapshot = snap;
    } else if (snap) {
        snap->def->current = false;
    }
10870
    if (event) {
C
Chris Lalancette 已提交
10871
        qemuDomainEventQueue(driver, event);
10872 10873 10874
        if (event2)
            qemuDomainEventQueue(driver, event2);
    }
C
Chris Lalancette 已提交
10875 10876 10877 10878 10879 10880 10881
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);

    return ret;
}

10882 10883
struct snap_reparent {
    struct qemud_driver *driver;
10884
    virDomainSnapshotObjPtr parent;
10885 10886
    virDomainObjPtr vm;
    int err;
10887
    virDomainSnapshotObjPtr last;
10888 10889 10890 10891
};

static void
qemuDomainSnapshotReparentChildren(void *payload,
10892
                                   const void *name ATTRIBUTE_UNUSED,
10893 10894 10895 10896 10897 10898 10899 10900 10901
                                   void *data)
{
    virDomainSnapshotObjPtr snap = payload;
    struct snap_reparent *rep = data;

    if (rep->err < 0) {
        return;
    }

10902
    VIR_FREE(snap->def->parent);
10903
    snap->parent = rep->parent;
10904

10905 10906
    if (rep->parent) {
        snap->def->parent = strdup(rep->parent->def->name);
10907

10908 10909 10910 10911
        if (snap->def->parent == NULL) {
            virReportOOMError();
            rep->err = -1;
            return;
10912 10913
        }
    }
10914

10915 10916 10917
    if (!snap->sibling)
        rep->last = snap;

10918 10919
    rep->err = qemuDomainSnapshotWriteMetadata(rep->vm, snap,
                                               rep->driver->snapshotDir);
10920 10921
}

C
Chris Lalancette 已提交
10922 10923 10924 10925 10926 10927 10928 10929
static int qemuDomainSnapshotDelete(virDomainSnapshotPtr snapshot,
                                    unsigned int flags)
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
10930
    struct qemu_snap_remove rem;
10931
    struct snap_reparent rep;
10932
    bool metadata_only = !!(flags & VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY);
10933
    int external = 0;
C
Chris Lalancette 已提交
10934

10935
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
10936 10937
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY |
                  VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY, -1);
10938

C
Chris Lalancette 已提交
10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955
    qemuDriverLock(driver);
    virUUIDFormat(snapshot->domain->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
    if (!snap) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                        _("no domain snapshot with matching name '%s'"),
                        snapshot->name);
        goto cleanup;
    }

10956 10957 10958 10959 10960
    if (!(flags & VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY)) {
        if (!(flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY) &&
            snap->def->state == VIR_DOMAIN_DISK_SNAPSHOT)
            external++;
        if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN)
E
Eric Blake 已提交
10961
            virDomainSnapshotForEachDescendant(snap,
10962 10963 10964 10965 10966 10967 10968 10969 10970 10971
                                               qemuDomainSnapshotCountExternal,
                                               &external);
        if (external) {
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                            _("deletion of %d external disk snapshots not "
                              "supported yet"), external);
            goto cleanup;
        }
    }

10972
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
10973 10974
        goto cleanup;

10975 10976
    if (flags & (VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                 VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY)) {
C
Chris Lalancette 已提交
10977 10978
        rem.driver = driver;
        rem.vm = vm;
10979
        rem.metadata_only = metadata_only;
C
Chris Lalancette 已提交
10980
        rem.err = 0;
10981
        rem.current = false;
E
Eric Blake 已提交
10982
        virDomainSnapshotForEachDescendant(snap,
E
Eric Blake 已提交
10983
                                           qemuDomainSnapshotDiscardAll,
10984
                                           &rem);
C
Chris Lalancette 已提交
10985
        if (rem.err < 0)
10986
            goto endjob;
10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998
        if (rem.current) {
            if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY) {
                snap->def->current = true;
                if (qemuDomainSnapshotWriteMetadata(vm, snap,
                                                    driver->snapshotDir) < 0) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                    _("failed to set snapshot '%s' as current"),
                                    snap->def->name);
                    snap->def->current = false;
                    goto endjob;
                }
            }
10999
            vm->current_snapshot = snap;
11000
        }
11001
    } else if (snap->nchildren) {
11002
        rep.driver = driver;
11003
        rep.parent = snap->parent;
11004 11005
        rep.vm = vm;
        rep.err = 0;
11006
        rep.last = NULL;
E
Eric Blake 已提交
11007
        virDomainSnapshotForEachChild(snap,
11008 11009
                                      qemuDomainSnapshotReparentChildren,
                                      &rep);
11010 11011
        if (rep.err < 0)
            goto endjob;
11012 11013 11014 11015 11016 11017 11018 11019 11020 11021
        /* Can't modify siblings during ForEachChild, so do it now.  */
        if (snap->parent) {
            snap->parent->nchildren += snap->nchildren;
            rep.last->sibling = snap->parent->first_child;
            snap->parent->first_child = snap->first_child;
        } else {
            vm->snapshots.nroots += snap->nchildren;
            rep.last->sibling = vm->snapshots.first_root;
            vm->snapshots.first_root = snap->first_child;
        }
C
Chris Lalancette 已提交
11022 11023
    }

11024 11025 11026
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY) {
        snap->nchildren = 0;
        snap->first_child = NULL;
11027
        ret = 0;
11028 11029
    } else {
        virDomainSnapshotDropParent(&vm->snapshots, snap);
11030
        ret = qemuDomainSnapshotDiscard(driver, vm, snap, true, metadata_only);
11031
    }
C
Chris Lalancette 已提交
11032

11033
endjob:
11034
    if (qemuDomainObjEndJob(driver, vm) == 0)
11035 11036
        vm = NULL;

C
Chris Lalancette 已提交
11037 11038 11039 11040 11041 11042
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
11043

11044 11045 11046 11047 11048 11049 11050
static int qemuDomainMonitorCommand(virDomainPtr domain, const char *cmd,
                                    char **result, unsigned int flags)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;
11051
    bool hmp;
11052

11053
    virCheckFlags(VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP, -1);
11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
   }

11071 11072 11073 11074 11075 11076 11077 11078 11079
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("domain is not running"));
        goto endjob;
    }

11080 11081
    priv = vm->privateData;

11082
    qemuDomainObjTaint(driver, vm, VIR_DOMAIN_TAINT_CUSTOM_MONITOR, -1);
11083

11084 11085
    hmp = !!(flags & VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP);

11086
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
11087
    ret = qemuMonitorArbitraryCommand(priv->mon, cmd, result, hmp);
11088
    qemuDomainObjExitMonitorWithDriver(driver, vm);
11089 11090

endjob:
11091
    if (qemuDomainObjEndJob(driver, vm) == 0) {
11092 11093 11094 11095 11096 11097 11098 11099 11100 11101
        vm = NULL;
    }

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

11102

11103 11104 11105 11106 11107 11108 11109 11110 11111 11112
static virDomainPtr qemuDomainAttach(virConnectPtr conn,
                                     unsigned int pid,
                                     unsigned int flags)
{
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    virDomainPtr dom = NULL;
    virDomainChrSourceDefPtr monConfig = NULL;
    bool monJSON = false;
11113
    char *pidfile = NULL;
11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147

    virCheckFlags(0, NULL);

    qemuDriverLock(driver);

    if (!(def = qemuParseCommandLinePid(driver->caps, pid,
                                        &pidfile, &monConfig, &monJSON)))
        goto cleanup;

    if (!monConfig) {
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("No monitor connection for pid %u"),
                        pid);
        goto cleanup;
    }
    if (monConfig->type != VIR_DOMAIN_CHR_TYPE_UNIX) {
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("Cannot connect to monitor connection of type '%s' for pid %u"),
                        virDomainChrTypeToString(monConfig->type), pid);
        goto cleanup;
    }

    if (!(def->name) &&
        virAsprintf(&def->name, "attach-pid-%u", pid) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
        goto cleanup;

    if (qemudCanonicalizeMachine(driver, def) < 0)
        goto cleanup;

11148
    if (qemuDomainAssignAddresses(def) < 0)
11149 11150 11151 11152 11153 11154 11155 11156 11157
        goto cleanup;

    if (!(vm = virDomainAssignDef(driver->caps,
                                  &driver->domains,
                                  def, false)))
        goto cleanup;

    def = NULL;

11158
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172
        goto cleanup;

    if (qemuProcessAttach(conn, driver, vm, pid,
                          pidfile, monConfig, monJSON) < 0) {
        monConfig = NULL;
        goto endjob;
    }

    monConfig = NULL;

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom) dom->id = vm->def->id;

endjob:
11173
    if (qemuDomainObjEndJob(driver, vm) == 0) {
11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188
        vm = NULL;
        goto cleanup;
    }

cleanup:
    virDomainDefFree(def);
    virDomainChrSourceDefFree(monConfig);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    VIR_FREE(pidfile);
    return dom;
}


11189 11190
static int
qemuDomainOpenConsole(virDomainPtr dom,
11191
                      const char *dev_name,
11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218
                      virStreamPtr st,
                      unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    int ret = -1;
    int i;
    virDomainChrDefPtr chr = NULL;

    virCheckFlags(0, -1);

    qemuDriverLock(driver);
    virUUIDFormat(dom->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

11219
    if (dev_name) {
11220 11221 11222 11223 11224
        for (i = 0 ; !chr && i < vm->def->nconsoles ; i++) {
            if (vm->def->consoles[i]->info.alias &&
                STREQ(dev_name, vm->def->consoles[i]->info.alias))
                chr = vm->def->consoles[i];
        }
11225
        for (i = 0 ; !chr && i < vm->def->nserials ; i++) {
11226
            if (STREQ(dev_name, vm->def->serials[i]->info.alias))
11227 11228 11229
                chr = vm->def->serials[i];
        }
        for (i = 0 ; !chr && i < vm->def->nparallels ; i++) {
11230
            if (STREQ(dev_name, vm->def->parallels[i]->info.alias))
11231 11232 11233
                chr = vm->def->parallels[i];
        }
    } else {
11234 11235
        if (vm->def->nconsoles)
            chr = vm->def->consoles[0];
11236 11237 11238 11239 11240 11241 11242
        else if (vm->def->nserials)
            chr = vm->def->serials[0];
    }

    if (!chr) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find character device %s"),
11243
                        NULLSTR(dev_name));
11244 11245 11246
        goto cleanup;
    }

11247
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
11248 11249
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"),
11250
                        NULLSTR(dev_name));
11251 11252 11253
        goto cleanup;
    }

11254
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
E
Eric Blake 已提交
11255
                            0, 0, O_RDWR) < 0)
11256 11257 11258 11259 11260 11261 11262 11263 11264 11265
        goto cleanup;

    ret = 0;
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

E
Eric Blake 已提交
11266 11267 11268
static char *
qemuDiskPathToAlias(virDomainObjPtr vm, const char *path)
{
11269 11270
    int i;
    char *ret = NULL;
11271
    virDomainDiskDefPtr disk;
11272

11273 11274 11275
    i = virDomainDiskIndexByName(vm->def, path, true);
    if (i < 0)
        goto cleanup;
11276

11277
    disk = vm->def->disks[i];
11278

11279 11280 11281 11282 11283 11284 11285 11286
    if (disk->type != VIR_DOMAIN_DISK_TYPE_BLOCK &&
        disk->type != VIR_DOMAIN_DISK_TYPE_FILE)
        goto cleanup;

    if (disk->src) {
        if (virAsprintf(&ret, "drive-%s", disk->info.alias) < 0) {
            virReportOOMError();
            return NULL;
11287 11288 11289
        }
    }

11290
cleanup:
11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306
    if (!ret) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("No device found for specified path"));
    }
    return ret;
}

static int
qemuDomainBlockJobImpl(virDomainPtr dom, const char *path,
                       unsigned long bandwidth, virDomainBlockJobInfoPtr info,
                       int mode)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    qemuDomainObjPrivatePtr priv;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
E
Eric Blake 已提交
11307
    char *device = NULL;
11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331
    int ret = -1;

    qemuDriverLock(driver);
    virUUIDFormat(dom->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

    device = qemuDiskPathToAlias(vm, path);
    if (!device) {
        goto cleanup;
    }

    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;
11332 11333 11334 11335 11336 11337 11338

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("domain is not running"));
        goto endjob;
    }

11339
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
11340 11341 11342
    priv = vm->privateData;
    ret = qemuMonitorBlockJob(priv->mon, device, bandwidth, info, mode);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
11343 11344

endjob:
11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384
    if (qemuDomainObjEndJob(driver, vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

cleanup:
    VIR_FREE(device);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

static int
qemuDomainBlockJobAbort(virDomainPtr dom, const char *path, unsigned int flags)
{
    virCheckFlags(0, -1);
    return qemuDomainBlockJobImpl(dom, path, 0, NULL, BLOCK_JOB_ABORT);
}

static int
qemuDomainGetBlockJobInfo(virDomainPtr dom, const char *path,
                           virDomainBlockJobInfoPtr info, unsigned int flags)
{
    virCheckFlags(0, -1);
    return qemuDomainBlockJobImpl(dom, path, 0, info, BLOCK_JOB_INFO);
}

static int
qemuDomainBlockJobSetSpeed(virDomainPtr dom, const char *path,
                           unsigned long bandwidth, unsigned int flags)
{
    virCheckFlags(0, -1);
    return qemuDomainBlockJobImpl(dom, path, bandwidth, NULL, BLOCK_JOB_SPEED);
}

static int
qemuDomainBlockPull(virDomainPtr dom, const char *path, unsigned long bandwidth,
                    unsigned int flags)
{
11385 11386
    int ret;

11387
    virCheckFlags(0, -1);
11388 11389 11390 11391 11392
    ret = qemuDomainBlockJobImpl(dom, path, bandwidth, NULL, BLOCK_JOB_PULL);
    if (ret == 0 && bandwidth != 0)
        ret = qemuDomainBlockJobImpl(dom, path, bandwidth, NULL,
                                     BLOCK_JOB_SPEED);
    return ret;
11393
}
11394

11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463
static int
qemuDomainOpenGraphics(virDomainPtr dom,
                       unsigned int idx,
                       int fd,
                       unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    int ret = -1;
    qemuDomainObjPrivatePtr priv;
    const char *protocol;

    virCheckFlags(VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH, -1);

    qemuDriverLock(driver);
    virUUIDFormat(dom->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

    priv = vm->privateData;

    if (idx >= vm->def->ngraphics) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No graphics backend with index %d"), idx);
        goto cleanup;
    }
    switch (vm->def->graphics[idx]->type) {
    case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
        protocol = "vnc";
        break;
    case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
        protocol = "spice";
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("Can only open VNC or SPICE graphics backends, not %s"),
                        virDomainGraphicsTypeToString(vm->def->graphics[idx]->type));
        goto cleanup;
    }

    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    ret = qemuMonitorOpenGraphics(priv->mon, protocol, fd, "graphicsfd",
                                  (flags & VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH) != 0);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
    if (qemuDomainObjEndJob(driver, vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483
static int
qemuDomainSetBlockIoTune(virDomainPtr dom,
                         const char *disk,
                         virTypedParameterPtr params,
                         int nparams,
                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    qemuDomainObjPrivatePtr priv;
    virDomainDefPtr persistentDef = NULL;
    virDomainBlockIoTuneInfo info;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    const char *device = NULL;
    int ret = -1;
    int i;
    int idx = -1;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_BYTES_SEC,
                                       VIR_TYPED_PARAM_ULLONG,
                                       VIR_DOMAIN_BLOCK_IOTUNE_READ_BYTES_SEC,
                                       VIR_TYPED_PARAM_ULLONG,
                                       VIR_DOMAIN_BLOCK_IOTUNE_WRITE_BYTES_SEC,
                                       VIR_TYPED_PARAM_ULLONG,
                                       VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_IOPS_SEC,
                                       VIR_TYPED_PARAM_ULLONG,
                                       VIR_DOMAIN_BLOCK_IOTUNE_READ_IOPS_SEC,
                                       VIR_TYPED_PARAM_ULLONG,
                                       VIR_DOMAIN_BLOCK_IOTUNE_WRITE_IOPS_SEC,
                                       VIR_TYPED_PARAM_ULLONG,
                                       NULL) < 0)
        return -1;
11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518

    memset(&info, 0, sizeof(info));

    qemuDriverLock(driver);
    virUUIDFormat(dom->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    device = qemuDiskPathToAlias(vm, disk);
    if (!device) {
        goto cleanup;
    }

    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;

11519 11520
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564
        goto endjob;

    for (i = 0; i < nparams; i++) {
        virTypedParameterPtr param = &params[i];

        if (STREQ(param->field, VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_BYTES_SEC)) {
            info.total_bytes_sec = param->value.ul;
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_READ_BYTES_SEC)) {
            info.read_bytes_sec = param->value.ul;
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_WRITE_BYTES_SEC)) {
            info.write_bytes_sec = param->value.ul;
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_IOPS_SEC)) {
            info.total_iops_sec = param->value.ul;
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_READ_IOPS_SEC)) {
            info.read_iops_sec = param->value.ul;
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_WRITE_IOPS_SEC)) {
            info.write_iops_sec = param->value.ul;
        }
    }

    if ((info.total_bytes_sec && info.read_bytes_sec) ||
        (info.total_bytes_sec && info.write_bytes_sec)) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("total and read/write of bytes_sec cannot be set at the same time"));
        goto endjob;
    }

    if ((info.total_iops_sec && info.read_iops_sec) ||
        (info.total_iops_sec && info.write_iops_sec)) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("total and read/write of iops_sec cannot be set at the same time"));
        goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        priv = vm->privateData;
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
        ret = qemuMonitorSetBlockIoThrottle(priv->mon, device, &info);
        qemuDomainObjExitMonitorWithDriver(driver, vm);
L
Lei Li 已提交
11565 11566
        if (ret < 0)
            goto endjob;
11567 11568 11569
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
11570 11571 11572 11573
        sa_assert(persistentDef);
        idx = virDomainDiskIndexByName(persistentDef, disk, true);
        if (idx < 0)
            goto endjob;
11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643
        persistentDef->disks[idx]->blkdeviotune = info;
        ret = virDomainSaveConfig(driver->configDir, persistentDef);
        if (ret < 0) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Write to config file failed"));
            goto endjob;
        }
    }

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;

cleanup:
    VIR_FREE(device);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

static int
qemuDomainGetBlockIoTune(virDomainPtr dom,
                         const char *disk,
                         virTypedParameterPtr params,
                         int *nparams,
                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    qemuDomainObjPrivatePtr priv;
    virDomainDefPtr persistentDef = NULL;
    virDomainBlockIoTuneInfo reply;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    const char *device = NULL;
    int ret = -1;
    int i;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);

    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

    qemuDriverLock(driver);
    virUUIDFormat(dom->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if ((*nparams) == 0) {
        /* Current number of parameters supported by QEMU Block I/O Throttling */
        *nparams = QEMU_NB_BLOCK_IO_TUNE_PARAM;
        ret = 0;
        goto cleanup;
    }

    device = qemuDiskPathToAlias(vm, disk);

    if (!device) {
        goto cleanup;
    }

    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;

11644 11645
    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668
        goto endjob;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        priv = vm->privateData;
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
        ret = qemuMonitorGetBlockIoThrottle(priv->mon, device, &reply);
        qemuDomainObjExitMonitorWithDriver(driver, vm);
        if (ret < 0)
            goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        int idx = virDomainDiskIndexByName(vm->def, disk, true);
        if (idx < 0)
            goto endjob;
        reply = persistentDef->disks[idx]->blkdeviotune;
    }

    for (i = 0; i < QEMU_NB_BLOCK_IO_TUNE_PARAM && i < *nparams; i++) {
        virTypedParameterPtr param = &params[i];

        switch(i) {
        case 0:
11669 11670 11671 11672
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_BYTES_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.total_bytes_sec) < 0)
11673 11674 11675
                goto endjob;
            break;
        case 1:
11676 11677 11678 11679
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_READ_BYTES_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.read_bytes_sec) < 0)
11680 11681 11682
                goto endjob;
            break;
        case 2:
11683 11684 11685 11686
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_WRITE_BYTES_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.write_bytes_sec) < 0)
11687 11688 11689
                goto endjob;
            break;
        case 3:
11690 11691 11692 11693
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_IOPS_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.total_iops_sec) < 0)
11694 11695 11696
                goto endjob;
            break;
        case 4:
11697 11698 11699 11700
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_READ_IOPS_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.read_iops_sec) < 0)
11701 11702 11703
                goto endjob;
            break;
        case 5:
11704 11705 11706 11707
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_WRITE_IOPS_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.write_iops_sec) < 0)
11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729
                goto endjob;
            break;
        default:
            break;
        }
    }

    if (*nparams > QEMU_NB_BLOCK_IO_TUNE_PARAM)
        *nparams = QEMU_NB_BLOCK_IO_TUNE_PARAM;
    ret = 0;

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;

cleanup:
    VIR_FREE(device);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
11730

11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815
static int
qemuDomainGetDiskErrors(virDomainPtr dom,
                        virDomainDiskErrorPtr errors,
                        unsigned int nerrors,
                        unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    qemuDomainObjPrivatePtr priv;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virHashTablePtr table = NULL;
    int ret = -1;
    int i;
    int n = 0;

    virCheckFlags(0, -1);

    qemuDriverLock(driver);
    virUUIDFormat(dom->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    priv = vm->privateData;

    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

    if (!errors) {
        ret = vm->def->ndisks;
        goto endjob;
    }

    qemuDomainObjEnterMonitor(driver, vm);
    table = qemuMonitorGetBlockInfo(priv->mon);
    qemuDomainObjExitMonitor(driver, vm);
    if (!table)
        goto endjob;

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

        if ((info = virHashLookup(table, disk->info.alias)) &&
            info->io_status != VIR_DOMAIN_DISK_ERROR_NONE) {
            if (n == nerrors)
                break;

            if (!(errors[n].disk = strdup(disk->dst))) {
                virReportOOMError();
                goto endjob;
            }
            errors[n].error = info->io_status;
            n++;
        }
    }

    ret = n;

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    virHashFree(table);
    if (ret < 0) {
        for (i = 0; i < n; i++)
            VIR_FREE(errors[i].disk);
    }
    return ret;
}

11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987
static int
qemuDomainSetMetadata(virDomainPtr dom,
                      int type,
                      const char *metadata,
                      const char *key ATTRIBUTE_UNUSED,
                      const char *uri ATTRIBUTE_UNUSED,
                      unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDefPtr persistentDef;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags,
                                        &persistentDef) < 0)
        goto cleanup;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        switch ((virDomainMetadataType) type) {
        case VIR_DOMAIN_METADATA_DESCRIPTION:
            VIR_FREE(vm->def->description);
            if (metadata &&
                !(vm->def->description = strdup(metadata)))
                goto no_memory;
            break;
        case VIR_DOMAIN_METADATA_TITLE:
            VIR_FREE(vm->def->title);
            if (metadata &&
                !(vm->def->title = strdup(metadata)))
                goto no_memory;
            break;
        case VIR_DOMAIN_METADATA_ELEMENT:
            qemuReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("QEmu driver does not support modifying"
                              "<metadata> element"));
            goto cleanup;
            break;
        default:
            qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                            _("unknown metadata type"));
            goto cleanup;
            break;
        }
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        switch ((virDomainMetadataType) type) {
        case VIR_DOMAIN_METADATA_DESCRIPTION:
            VIR_FREE(persistentDef->description);
            if (metadata &&
                !(persistentDef->description = strdup(metadata)))
                goto no_memory;
            break;
        case VIR_DOMAIN_METADATA_TITLE:
            VIR_FREE(persistentDef->title);
            if (metadata &&
                !(persistentDef->title = strdup(metadata)))
                goto no_memory;
            break;
        case VIR_DOMAIN_METADATA_ELEMENT:
            qemuReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("QEMU driver does not support"
                              "<metadata> element"));
            goto cleanup;
         default:
            qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                            _("unknown metadata type"));
            goto cleanup;
            break;
        }

        if (virDomainSaveConfig(driver->configDir, persistentDef) < 0)
            goto cleanup;
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
no_memory:
    virReportOOMError();
    goto cleanup;
}

static char *
qemuDomainGetMetadata(virDomainPtr dom,
                      int type,
                      const char *uri ATTRIBUTE_UNUSED,
                      unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDefPtr def;
    char *ret = NULL;
    char *field = NULL;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, NULL);

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (virDomainLiveConfigHelperMethod(driver->caps, vm, &flags, &def) < 0)
        goto cleanup;

    /* use correct domain definition according to flags */
    if (flags & VIR_DOMAIN_AFFECT_LIVE)
        def = vm->def;

    switch ((virDomainMetadataType) type) {
    case VIR_DOMAIN_METADATA_DESCRIPTION:
        field = def->description;
        break;
    case VIR_DOMAIN_METADATA_TITLE:
        field = def->title;
        break;
    case VIR_DOMAIN_METADATA_ELEMENT:
        qemuReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                        _("QEMU driver does not support"
                          "<metadata> element"));
        goto cleanup;
        break;
    default:
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("unknown metadata type"));
        goto cleanup;
        break;
    }

    if (!field) {
        qemuReportError(VIR_ERR_NO_DOMAIN_METADATA, "%s",
                        _("Requested metadata element is not present"));
        goto cleanup;
    }

    if (!(ret = strdup(field))) {
        virReportOOMError();
        goto cleanup;
    }

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

11988
static virDriver qemuDriver = {
11989 11990
    .no = VIR_DRV_QEMU,
    .name = "QEMU",
11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008
    .open = qemudOpen, /* 0.2.0 */
    .close = qemudClose, /* 0.2.0 */
    .supports_feature = qemudSupportsFeature, /* 0.5.0 */
    .type = qemudGetType, /* 0.2.0 */
    .version = qemudGetVersion, /* 0.2.0 */
    .getHostname = virGetHostname, /* 0.3.3 */
    .getSysinfo = qemuGetSysinfo, /* 0.8.8 */
    .getMaxVcpus = qemudGetMaxVCPUs, /* 0.2.1 */
    .nodeGetInfo = nodeGetInfo, /* 0.2.0 */
    .getCapabilities = qemudGetCapabilities, /* 0.2.1 */
    .listDomains = qemudListDomains, /* 0.2.0 */
    .numOfDomains = qemudNumDomains, /* 0.2.0 */
    .domainCreateXML = qemudDomainCreate, /* 0.2.0 */
    .domainLookupByID = qemudDomainLookupByID, /* 0.2.0 */
    .domainLookupByUUID = qemudDomainLookupByUUID, /* 0.2.0 */
    .domainLookupByName = qemudDomainLookupByName, /* 0.2.0 */
    .domainSuspend = qemudDomainSuspend, /* 0.2.0 */
    .domainResume = qemudDomainResume, /* 0.2.0 */
12009
    .domainShutdown = qemuDomainShutdown, /* 0.2.0 */
12010
    .domainShutdownFlags = qemuDomainShutdownFlags, /* 0.9.10 */
12011
    .domainReboot = qemuDomainReboot, /* 0.9.3 */
12012
    .domainReset = qemuDomainReset, /* 0.9.7 */
12013 12014
    .domainDestroy = qemuDomainDestroy, /* 0.2.0 */
    .domainDestroyFlags = qemuDomainDestroyFlags, /* 0.9.4 */
12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025
    .domainGetOSType = qemudDomainGetOSType, /* 0.2.2 */
    .domainGetMaxMemory = qemudDomainGetMaxMemory, /* 0.4.2 */
    .domainSetMaxMemory = qemudDomainSetMaxMemory, /* 0.4.2 */
    .domainSetMemory = qemudDomainSetMemory, /* 0.4.2 */
    .domainSetMemoryFlags = qemudDomainSetMemoryFlags, /* 0.9.0 */
    .domainSetMemoryParameters = qemuDomainSetMemoryParameters, /* 0.8.5 */
    .domainGetMemoryParameters = qemuDomainGetMemoryParameters, /* 0.8.5 */
    .domainSetBlkioParameters = qemuDomainSetBlkioParameters, /* 0.9.0 */
    .domainGetBlkioParameters = qemuDomainGetBlkioParameters, /* 0.9.0 */
    .domainGetInfo = qemudDomainGetInfo, /* 0.2.0 */
    .domainGetState = qemuDomainGetState, /* 0.9.2 */
12026
    .domainGetControlInfo = qemuDomainGetControlInfo, /* 0.9.3 */
12027 12028
    .domainSave = qemuDomainSave, /* 0.2.0 */
    .domainSaveFlags = qemuDomainSaveFlags, /* 0.9.4 */
12029
    .domainRestore = qemuDomainRestore, /* 0.2.0 */
12030
    .domainRestoreFlags = qemuDomainRestoreFlags, /* 0.9.4 */
12031 12032
    .domainSaveImageGetXMLDesc = qemuDomainSaveImageGetXMLDesc, /* 0.9.4 */
    .domainSaveImageDefineXML = qemuDomainSaveImageDefineXML, /* 0.9.4 */
12033 12034
    .domainCoreDump = qemudDomainCoreDump, /* 0.7.0 */
    .domainScreenshot = qemuDomainScreenshot, /* 0.9.2 */
12035 12036
    .domainSetVcpus = qemuDomainSetVcpus, /* 0.4.4 */
    .domainSetVcpusFlags = qemuDomainSetVcpusFlags, /* 0.8.5 */
12037 12038
    .domainGetVcpusFlags = qemudDomainGetVcpusFlags, /* 0.8.5 */
    .domainPinVcpu = qemudDomainPinVcpu, /* 0.4.4 */
12039
    .domainPinVcpuFlags = qemudDomainPinVcpuFlags, /* 0.9.3 */
E
Eric Blake 已提交
12040
    .domainGetVcpuPinInfo = qemudDomainGetVcpuPinInfo, /* 0.9.3 */
12041 12042 12043 12044 12045 12046 12047 12048 12049
    .domainGetVcpus = qemudDomainGetVcpus, /* 0.4.4 */
    .domainGetMaxVcpus = qemudDomainGetMaxVcpus, /* 0.4.4 */
    .domainGetSecurityLabel = qemudDomainGetSecurityLabel, /* 0.6.1 */
    .nodeGetSecurityModel = qemudNodeGetSecurityModel, /* 0.6.1 */
    .domainGetXMLDesc = qemuDomainGetXMLDesc, /* 0.2.0 */
    .domainXMLFromNative = qemuDomainXMLFromNative, /* 0.6.4 */
    .domainXMLToNative = qemuDomainXMLToNative, /* 0.6.4 */
    .listDefinedDomains = qemudListDefinedDomains, /* 0.2.0 */
    .numOfDefinedDomains = qemudNumDefinedDomains, /* 0.2.0 */
12050 12051
    .domainCreate = qemuDomainStart, /* 0.2.0 */
    .domainCreateWithFlags = qemuDomainStartWithFlags, /* 0.8.2 */
12052 12053
    .domainDefineXML = qemudDomainDefine, /* 0.2.0 */
    .domainUndefine = qemudDomainUndefine, /* 0.2.0 */
12054
    .domainUndefineFlags = qemuDomainUndefineFlags, /* 0.9.4 */
12055 12056 12057 12058 12059 12060 12061 12062 12063
    .domainAttachDevice = qemuDomainAttachDevice, /* 0.4.1 */
    .domainAttachDeviceFlags = qemuDomainAttachDeviceFlags, /* 0.7.7 */
    .domainDetachDevice = qemuDomainDetachDevice, /* 0.5.0 */
    .domainDetachDeviceFlags = qemuDomainDetachDeviceFlags, /* 0.7.7 */
    .domainUpdateDeviceFlags = qemuDomainUpdateDeviceFlags, /* 0.8.0 */
    .domainGetAutostart = qemudDomainGetAutostart, /* 0.2.1 */
    .domainSetAutostart = qemudDomainSetAutostart, /* 0.2.1 */
    .domainGetSchedulerType = qemuGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = qemuGetSchedulerParameters, /* 0.7.0 */
12064
    .domainGetSchedulerParametersFlags = qemuGetSchedulerParametersFlags, /* 0.9.2 */
12065
    .domainSetSchedulerParameters = qemuSetSchedulerParameters, /* 0.7.0 */
12066
    .domainSetSchedulerParametersFlags = qemuSetSchedulerParametersFlags, /* 0.9.2 */
12067
    .domainMigratePerform = qemudDomainMigratePerform, /* 0.5.0 */
12068
    .domainBlockResize = qemuDomainBlockResize, /* 0.9.8 */
12069 12070
    .domainBlockStats = qemuDomainBlockStats, /* 0.4.1 */
    .domainBlockStatsFlags = qemuDomainBlockStatsFlags, /* 0.9.5 */
12071 12072 12073 12074 12075
    .domainInterfaceStats = qemudDomainInterfaceStats, /* 0.4.1 */
    .domainMemoryStats = qemudDomainMemoryStats, /* 0.7.5 */
    .domainBlockPeek = qemudDomainBlockPeek, /* 0.4.4 */
    .domainMemoryPeek = qemudDomainMemoryPeek, /* 0.4.4 */
    .domainGetBlockInfo = qemuDomainGetBlockInfo, /* 0.8.1 */
12076
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
12077
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098
    .nodeGetCellsFreeMemory = nodeGetCellsFreeMemory, /* 0.4.4 */
    .nodeGetFreeMemory = nodeGetFreeMemory, /* 0.4.4 */
    .domainEventRegister = qemuDomainEventRegister, /* 0.5.0 */
    .domainEventDeregister = qemuDomainEventDeregister, /* 0.5.0 */
    .domainMigratePrepare2 = qemudDomainMigratePrepare2, /* 0.5.0 */
    .domainMigrateFinish2 = qemudDomainMigrateFinish2, /* 0.5.0 */
    .nodeDeviceDettach = qemudNodeDeviceDettach, /* 0.6.1 */
    .nodeDeviceReAttach = qemudNodeDeviceReAttach, /* 0.6.1 */
    .nodeDeviceReset = qemudNodeDeviceReset, /* 0.6.1 */
    .domainMigratePrepareTunnel = qemudDomainMigratePrepareTunnel, /* 0.7.2 */
    .isEncrypted = qemuIsEncrypted, /* 0.7.3 */
    .isSecure = qemuIsSecure, /* 0.7.3 */
    .domainIsActive = qemuDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = qemuDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = qemuDomainIsUpdated, /* 0.8.6 */
    .cpuCompare = qemuCPUCompare, /* 0.7.5 */
    .cpuBaseline = qemuCPUBaseline, /* 0.7.7 */
    .domainGetJobInfo = qemuDomainGetJobInfo, /* 0.7.7 */
    .domainAbortJob = qemuDomainAbortJob, /* 0.7.7 */
    .domainMigrateSetMaxDowntime = qemuDomainMigrateSetMaxDowntime, /* 0.8.0 */
    .domainMigrateSetMaxSpeed = qemuDomainMigrateSetMaxSpeed, /* 0.9.0 */
12099
    .domainMigrateGetMaxSpeed = qemuDomainMigrateGetMaxSpeed, /* 0.9.5 */
12100 12101 12102 12103 12104 12105 12106 12107 12108
    .domainEventRegisterAny = qemuDomainEventRegisterAny, /* 0.8.0 */
    .domainEventDeregisterAny = qemuDomainEventDeregisterAny, /* 0.8.0 */
    .domainManagedSave = qemuDomainManagedSave, /* 0.8.0 */
    .domainHasManagedSaveImage = qemuDomainHasManagedSaveImage, /* 0.8.0 */
    .domainManagedSaveRemove = qemuDomainManagedSaveRemove, /* 0.8.0 */
    .domainSnapshotCreateXML = qemuDomainSnapshotCreateXML, /* 0.8.0 */
    .domainSnapshotGetXMLDesc = qemuDomainSnapshotGetXMLDesc, /* 0.8.0 */
    .domainSnapshotNum = qemuDomainSnapshotNum, /* 0.8.0 */
    .domainSnapshotListNames = qemuDomainSnapshotListNames, /* 0.8.0 */
12109 12110
    .domainSnapshotNumChildren = qemuDomainSnapshotNumChildren, /* 0.9.7 */
    .domainSnapshotListChildrenNames = qemuDomainSnapshotListChildrenNames, /* 0.9.7 */
12111 12112
    .domainSnapshotLookupByName = qemuDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = qemuDomainHasCurrentSnapshot, /* 0.8.0 */
12113
    .domainSnapshotGetParent = qemuDomainSnapshotGetParent, /* 0.9.7 */
12114 12115 12116 12117
    .domainSnapshotCurrent = qemuDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = qemuDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = qemuDomainSnapshotDelete, /* 0.8.0 */
    .qemuDomainMonitorCommand = qemuDomainMonitorCommand, /* 0.8.3 */
12118
    .qemuDomainAttach = qemuDomainAttach, /* 0.9.4 */
12119
    .domainOpenConsole = qemuDomainOpenConsole, /* 0.8.6 */
12120
    .domainOpenGraphics = qemuDomainOpenGraphics, /* 0.9.7 */
12121
    .domainInjectNMI = qemuDomainInjectNMI, /* 0.9.2 */
12122 12123 12124 12125 12126 12127
    .domainMigrateBegin3 = qemuDomainMigrateBegin3, /* 0.9.2 */
    .domainMigratePrepare3 = qemuDomainMigratePrepare3, /* 0.9.2 */
    .domainMigratePrepareTunnel3 = qemuDomainMigratePrepareTunnel3, /* 0.9.2 */
    .domainMigratePerform3 = qemuDomainMigratePerform3, /* 0.9.2 */
    .domainMigrateFinish3 = qemuDomainMigrateFinish3, /* 0.9.2 */
    .domainMigrateConfirm3 = qemuDomainMigrateConfirm3, /* 0.9.2 */
12128
    .domainSendKey = qemuDomainSendKey, /* 0.9.4 */
12129 12130 12131 12132
    .domainBlockJobAbort = qemuDomainBlockJobAbort, /* 0.9.4 */
    .domainGetBlockJobInfo = qemuDomainGetBlockJobInfo, /* 0.9.4 */
    .domainBlockJobSetSpeed = qemuDomainBlockJobSetSpeed, /* 0.9.4 */
    .domainBlockPull = qemuDomainBlockPull, /* 0.9.4 */
12133
    .isAlive = qemuIsAlive, /* 0.9.8 */
12134
    .nodeSuspendForDuration = nodeSuspendForDuration, /* 0.9.8 */
12135 12136
    .domainSetBlockIoTune = qemuDomainSetBlockIoTune, /* 0.9.8 */
    .domainGetBlockIoTune = qemuDomainGetBlockIoTune, /* 0.9.8 */
12137 12138
    .domainSetNumaParameters = qemuDomainSetNumaParameters, /* 0.9.9 */
    .domainGetNumaParameters = qemuDomainGetNumaParameters, /* 0.9.9 */
12139 12140
    .domainGetInterfaceParameters = qemuDomainGetInterfaceParameters, /* 0.9.9 */
    .domainSetInterfaceParameters = qemuDomainSetInterfaceParameters, /* 0.9.9 */
12141
    .domainGetDiskErrors = qemuDomainGetDiskErrors, /* 0.9.10 */
12142 12143
    .domainSetMetadata = qemuDomainSetMetadata, /* 0.9.10 */
    .domainGetMetadata = qemuDomainGetMetadata, /* 0.9.10 */
12144 12145 12146
};


12147
static virStateDriver qemuStateDriver = {
12148
    .name = "QEMU",
12149 12150 12151 12152
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
12153
};
12154

12155
static void
12156
qemuVMDriverLock(void) {
12157 12158 12159 12160 12161
    qemuDriverLock(qemu_driver);
};


static void
12162
qemuVMDriverUnlock(void) {
12163 12164 12165 12166
    qemuDriverUnlock(qemu_driver);
};


12167 12168 12169 12170 12171 12172 12173 12174 12175
static int
qemuVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                    virHashIterator iter, void *data)
{
    virHashForEach(qemu_driver->domains.objs, iter, data);

    return 0;
}

S
Stefan Berger 已提交
12176 12177
static virNWFilterCallbackDriver qemuCallbackDriver = {
    .name = "QEMU",
12178 12179 12180
    .vmFilterRebuild = qemuVMFilterRebuild,
    .vmDriverLock = qemuVMDriverLock,
    .vmDriverUnlock = qemuVMDriverUnlock,
S
Stefan Berger 已提交
12181 12182
};

12183
int qemuRegister(void) {
12184 12185
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
S
Stefan Berger 已提交
12186
    virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);
12187 12188
    return 0;
}