qemu_driver.c 363.9 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-2011 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 50
#include "qemu_driver.h"
#include "qemu_conf.h"
51
#include "qemu_capabilities.h"
52
#include "qemu_command.h"
53
#include "qemu_cgroup.h"
54
#include "qemu_hostdev.h"
55
#include "qemu_hotplug.h"
56
#include "qemu_monitor.h"
57
#include "qemu_bridge_filter.h"
58
#include "qemu_process.h"
59
#include "qemu_migration.h"
60 61 62 63

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

94 95
#define VIR_FROM_THIS VIR_FROM_QEMU

96 97
#define QEMU_NB_MEM_PARAM  3

98 99
#define QEMU_NB_BLOCK_IO_TUNE_PARAM  6

100 101 102
#if HAVE_LINUX_KVM_H
# include <linux/kvm.h>
#endif
103

104 105
/* device for kvm ioctls */
#define KVM_DEVICE "/dev/kvm"
106

107 108 109 110 111 112 113 114 115 116 117
/* 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

118
#define QEMU_NB_BLKIO_PARAM  2
119

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

122 123
static int qemudShutdown(void);

124 125 126
static int qemuDomainObjStart(virConnectPtr conn,
                              struct qemud_driver *driver,
                              virDomainObjPtr vm,
127
                              unsigned int flags);
J
Jiri Denemark 已提交
128

129
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
130

131
struct qemud_driver *qemu_driver = NULL;
132 133


134 135 136 137
struct qemuAutostartData {
    struct qemud_driver *driver;
    virConnectPtr conn;
};
138

139
static void
140 141
qemuAutostartDomain(void *payload, const void *name ATTRIBUTE_UNUSED,
                    void *opaque)
142 143 144
{
    virDomainObjPtr vm = payload;
    struct qemuAutostartData *data = opaque;
145
    virErrorPtr err;
146 147 148 149
    int flags = 0;

    if (data->driver->autoStartBypassCache)
        flags |= VIR_DOMAIN_START_BYPASS_CACHE;
150 151

    virDomainObjLock(vm);
152
    virResetLastError();
153 154 155 156 157 158 159 160 161 162 163 164
    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) {
165
            err = virGetLastError();
166
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
167
                      vm->def->name,
168
                      err ? err->message : _("unknown error"));
169
        }
170

171
        if (qemuDomainObjEndJob(data->driver, vm) == 0)
172
            vm = NULL;
173
    }
174

175
cleanup:
176 177
    if (vm)
        virDomainObjUnlock(vm);
178 179
}

180

181
static void
182 183
qemuAutostartDomains(struct qemud_driver *driver)
{
184 185 186 187 188
    /* 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
     */
189 190 191
    virConnectPtr conn = virConnectOpen(driver->privileged ?
                                        "qemu:///system" :
                                        "qemu:///session");
192
    /* Ignoring NULL conn which is mostly harmless here */
193
    struct qemuAutostartData data = { driver, conn };
194

195
    qemuDriverLock(driver);
196
    virHashForEach(driver->domains.objs, qemuAutostartDomain, &data);
197
    qemuDriverUnlock(driver);
198

199 200
    if (conn)
        virConnectClose(conn);
201 202
}

203
static int
204
qemuSecurityInit(struct qemud_driver *driver)
205
{
206 207 208 209
    virSecurityManagerPtr mgr = virSecurityManagerNew(driver->securityDriverName,
                                                      driver->allowDiskFormatProbing);
    if (!mgr)
        goto error;
D
Daniel Veillard 已提交
210

211 212 213 214 215 216 217
    if (driver->privileged) {
        virSecurityManagerPtr dac = virSecurityManagerNewDAC(driver->user,
                                                             driver->group,
                                                             driver->allowDiskFormatProbing,
                                                             driver->dynamicOwnership);
        if (!dac)
            goto error;
218

219
        if (!(driver->securityManager = virSecurityManagerNewStack(mgr,
E
Eric Blake 已提交
220 221 222
                                                                   dac))) {

            virSecurityManagerFree(dac);
223
            goto error;
E
Eric Blake 已提交
224
        }
225 226 227
    } else {
        driver->securityManager = mgr;
    }
D
Daniel Veillard 已提交
228

229
    return 0;
230

231
error:
232
    VIR_ERROR(_("Failed to initialize security drivers"));
233 234 235
    virSecurityManagerFree(mgr);
    return -1;
}
236

237

238 239 240 241 242
static virCapsPtr
qemuCreateCapabilities(virCapsPtr oldcaps,
                       struct qemud_driver *driver)
{
    virCapsPtr caps;
243

244 245 246 247
    /* Basic host arch / guest machine capabilities */
    if (!(caps = qemuCapsInit(oldcaps))) {
        virReportOOMError();
        return NULL;
248 249
    }

250 251 252 253 254 255
    if (driver->allowDiskFormatProbing) {
        caps->defaultDiskDriverName = NULL;
        caps->defaultDiskDriverType = NULL;
    } else {
        caps->defaultDiskDriverName = "qemu";
        caps->defaultDiskDriverType = "raw";
256 257
    }

258 259
    qemuDomainSetPrivateDataHooks(caps);
    qemuDomainSetNamespaceHooks(caps);
260

261 262 263 264
    if (virGetHostUUID(caps->host.host_uuid)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot get the host uuid"));
        goto err_exit;
265
    }
266

267 268
    /* Security driver data */
    const char *doi, *model;
269

270 271 272 273 274 275 276
    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;
277
    }
278

279 280
    VIR_DEBUG("Initialized caps for security driver \"%s\" with "
              "DOI \"%s\"", model, doi);
281

282
    return caps;
283

284 285 286 287
no_memory:
    virReportOOMError();
err_exit:
    virCapabilitiesFree(caps);
288 289 290
    return NULL;
}

291
static void qemuDomainSnapshotLoad(void *payload,
292
                                   const void *name ATTRIBUTE_UNUSED,
293
                                   void *data)
294
{
295 296 297 298 299 300 301 302 303
    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;
304
    virDomainSnapshotObjPtr snap = NULL;
305
    virDomainSnapshotObjPtr current = NULL;
306
    char ebuf[1024];
307
    unsigned int flags = (VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE |
308
                          VIR_DOMAIN_SNAPSHOT_PARSE_DISKS |
309
                          VIR_DOMAIN_SNAPSHOT_PARSE_INTERNAL);
310

311 312 313 314
    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);
315
        goto cleanup;
316 317
    }

318 319
    VIR_INFO("Scanning for snapshots for domain %s in %s", vm->def->name,
             snapDir);
320

321 322 323 324 325
    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)));
326
        goto cleanup;
327 328
    }

329 330 331
    while ((entry = readdir(dir))) {
        if (entry->d_name[0] == '.')
            continue;
332

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

337
        if (virAsprintf(&fullpath, "%s/%s", snapDir, entry->d_name) < 0) {
338
            VIR_ERROR(_("Failed to allocate memory for path"));
339 340
            continue;
        }
341

342 343 344 345 346 347 348 349
        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;
        }
350

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

363 364 365
        snap = virDomainSnapshotAssignDef(&vm->snapshots, def);
        if (snap == NULL) {
            virDomainSnapshotDefFree(def);
366 367 368 369
        } else if (snap->def->current) {
            current = snap;
            if (!vm->current_snapshot)
                vm->current_snapshot = snap;
370
        }
371

372 373
        VIR_FREE(fullpath);
        VIR_FREE(xmlStr);
374 375
    }

376 377 378 379 380 381
    if (vm->current_snapshot != current) {
        VIR_ERROR(_("Too many snapshots claiming to be current for domain %s"),
                  vm->def->name);
        vm->current_snapshot = NULL;
    }

382 383 384 385
    if (virDomainSnapshotUpdateRelations(&vm->snapshots) < 0)
        VIR_ERROR(_("Snapshots have inconsistent relations for domain %s"),
                  vm->def->name);

386 387 388 389 390 391 392 393
    /* 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.
     */
394

395
    virResetLastError();
396

397 398 399 400
cleanup:
    if (dir)
        closedir(dir);
    VIR_FREE(snapDir);
401 402 403
    virDomainObjUnlock(vm);
}

404 405 406 407 408
/**
 * qemudStartup:
 *
 * Initialization function for the QEmu daemon
 */
409
static int
410 411 412 413 414
qemudStartup(int privileged) {
    char *base = NULL;
    char *driverConf = NULL;
    int rc;
    virConnectPtr conn = NULL;
415

416 417
    if (VIR_ALLOC(qemu_driver) < 0)
        return -1;
418

419
    if (virMutexInit(&qemu_driver->lock) < 0) {
420
        VIR_ERROR(_("cannot initialize mutex"));
421 422
        VIR_FREE(qemu_driver);
        return -1;
423
    }
424 425
    qemuDriverLock(qemu_driver);
    qemu_driver->privileged = privileged;
426

427 428
    /* Don't have a dom0 so start from 1 */
    qemu_driver->nextvmid = 1;
429

430 431
    if (virDomainObjListInit(&qemu_driver->domains) < 0)
        goto out_of_memory;
432

433 434 435 436 437 438
    /* Init domain events */
    qemu_driver->domainEventState = virDomainEventStateNew(qemuDomainEventFlush,
                                                           qemu_driver,
                                                           NULL,
                                                           true);
    if (!qemu_driver->domainEventState)
439
        goto error;
440

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

446 447 448
    /* read the host sysinfo */
    if (privileged)
        qemu_driver->hostsysinfo = virSysinfoRead();
449

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

455 456
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
            goto out_of_memory;
457

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

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

466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
        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;
483

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

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

496 497 498 499 500 501 502 503 504 505 506 507
        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;
508
    }
H
Hu Tao 已提交
509

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

547 548 549 550 551 552 553
    /* 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;
554

555
    VIR_FREE(base);
556

557 558 559 560 561
    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)));
562 563
    }

564 565 566 567
    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
        goto error;
    }
    VIR_FREE(driverConf);
568

569 570 571 572 573 574 575 576
    /* 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;
    }

577 578
    if (qemuSecurityInit(qemu_driver) < 0)
        goto error;
579

580 581 582
    if ((qemu_driver->caps = qemuCreateCapabilities(NULL,
                                                    qemu_driver)) == NULL)
        goto error;
583

584
    if ((qemu_driver->activePciHostdevs = pciDeviceListNew()) == NULL)
585
        goto error;
586

587 588 589 590 591 592
    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;
593
        }
594
        if (chown(qemu_driver->cacheDir, qemu_driver->user, qemu_driver->group) < 0) {
595
            virReportSystemError(errno,
596 597 598
                                 _("unable to set ownership of '%s' to %d:%d"),
                                 qemu_driver->cacheDir, qemu_driver->user, qemu_driver->group);
            goto error;
599
        }
600 601 602 603 604 605 606 607 608 609 610
        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;
611
        }
612
    }
613

614 615 616 617 618 619
    /* 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
620
     */
621 622 623 624 625
    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;
626

627 628
        if (virFileMakePath(mempath) < 0) {
            virReportSystemError(errno,
629 630 631
                                 _("unable to create hugepage path %s"), mempath);
            VIR_FREE(mempath);
            goto error;
632
        }
633 634 635 636 637 638 639
        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 已提交
640
        }
E
Eric Blake 已提交
641

642
        qemu_driver->hugepage_path = mempath;
643
    }
644

645 646 647
    if (qemuProcessAutoDestroyInit(qemu_driver) < 0)
        goto error;

648 649 650 651 652
    /* Get all the running persistent or transient configs first */
    if (virDomainLoadAllConfigs(qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->stateDir,
                                NULL,
M
Matthias Bolte 已提交
653 654
                                1, QEMU_EXPECTED_VIRT_TYPES,
                                NULL, NULL) < 0)
655
        goto error;
656

657 658 659
    conn = virConnectOpen(qemu_driver->privileged ?
                          "qemu:///system" :
                          "qemu:///session");
660

661
    qemuProcessReconnectAll(conn, qemu_driver);
662

663 664 665 666 667
    /* Then inactive persistent configs */
    if (virDomainLoadAllConfigs(qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->configDir,
                                qemu_driver->autostartDir,
M
Matthias Bolte 已提交
668 669
                                0, QEMU_EXPECTED_VIRT_TYPES,
                                NULL, NULL) < 0)
670
        goto error;
671

672

673 674
    virHashForEach(qemu_driver->domains.objs, qemuDomainSnapshotLoad,
                   qemu_driver->snapshotDir);
675

676
    qemu_driver->workerPool = virThreadPoolNew(0, 1, 0, processWatchdogEvent, qemu_driver);
677 678
    if (!qemu_driver->workerPool)
        goto error;
679

680 681 682 683
    qemuDriverUnlock(qemu_driver);

    qemuAutostartDomains(qemu_driver);

684 685
    if (conn)
        virConnectClose(conn);
686

687
    return 0;
688

689 690 691 692 693 694 695 696 697 698
out_of_memory:
    virReportOOMError();
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
    if (conn)
        virConnectClose(conn);
    VIR_FREE(base);
    VIR_FREE(driverConf);
    qemudShutdown();
699
    return -1;
700 701
}

702 703 704
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;
705

706 707 708 709 710 711 712
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
E
Eric Blake 已提交
713
    }
714
}
E
Eric Blake 已提交
715

716 717 718 719 720 721 722 723 724 725
/**
 * 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;
726

727 728 729 730 731
    qemuDriverLock(qemu_driver);
    virDomainLoadAllConfigs(qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
                            qemu_driver->autostartDir,
M
Matthias Bolte 已提交
732 733
                            0, QEMU_EXPECTED_VIRT_TYPES,
                            qemudNotifyLoadDomain, qemu_driver);
734
    qemuDriverUnlock(qemu_driver);
735

736
    qemuAutostartDomains(qemu_driver);
737

738 739
    return 0;
}
S
Stefan Berger 已提交
740

741 742 743 744 745 746 747 748 749 750 751
/**
 * 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;
752

753 754
    if (!qemu_driver)
        return 0;
755

756 757 758 759 760 761
    /* 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;
}
762

763 764 765 766 767 768 769 770
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
    int i;
771

772 773
    if (!qemu_driver)
        return -1;
774

775 776 777
    qemuDriverLock(qemu_driver);
    pciDeviceListFree(qemu_driver->activePciHostdevs);
    virCapabilitiesFree(qemu_driver->caps);
778

779 780
    virDomainObjListDeinit(&qemu_driver->domains);
    virBitmapFree(qemu_driver->reservedVNCPorts);
781

782
    virSysinfoDefFree(qemu_driver->hostsysinfo);
783

784 785
    qemuProcessAutoDestroyShutdown(qemu_driver);

786 787 788 789 790 791 792 793
    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 已提交
794
    VIR_FREE(qemu_driver->qemuImgBinary);
795 796 797 798 799 800 801 802 803 804 805 806
    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);
807

808
    virSecurityManagerFree(qemu_driver->securityManager);
809

810
    ebtablesContextFree(qemu_driver->ebtables);
811

812 813 814 815
    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 已提交
816 817
    }

818
    /* Free domain callback list */
819
    virDomainEventStateFree(qemu_driver->domainEventState);
D
Daniel P. Berrange 已提交
820

821
    virCgroupFree(&qemu_driver->cgroup);
822

823 824
    virLockManagerPluginUnref(qemu_driver->lockManager);

825 826 827 828
    qemuDriverUnlock(qemu_driver);
    virMutexDestroy(&qemu_driver->lock);
    virThreadPoolFree(qemu_driver->workerPool);
    VIR_FREE(qemu_driver);
829

830
    return 0;
831 832
}

833

834
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
835
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
836
                                  unsigned int flags)
837
{
E
Eric Blake 已提交
838 839
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

840
    if (conn->uri == NULL) {
841 842 843
        if (qemu_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

844
        conn->uri = xmlParseURI(qemu_driver->privileged ?
845 846
                                "qemu:///system" :
                                "qemu:///session");
847
        if (!conn->uri) {
848
            virReportOOMError();
849 850
            return VIR_DRV_OPEN_ERROR;
        }
851 852 853 854 855 856 857 858 859 860
    } 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;

861
        if (qemu_driver == NULL) {
862 863
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("qemu state driver is not active"));
864 865 866
            return VIR_DRV_OPEN_ERROR;
        }

867
        if (conn->uri->path == NULL) {
868 869 870 871 872
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("no QEMU URI path given, try %s"),
                            qemu_driver->privileged
                            ? "qemu:///system"
                            : "qemu:///session");
873 874 875
                return VIR_DRV_OPEN_ERROR;
        }

876
        if (qemu_driver->privileged) {
877 878
            if (STRNEQ (conn->uri->path, "/system") &&
                STRNEQ (conn->uri->path, "/session")) {
879 880 881
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("unexpected QEMU URI path '%s', try qemu:///system"),
                                conn->uri->path);
882 883 884 885
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
886 887 888
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("unexpected QEMU URI path '%s', try qemu:///session"),
                                conn->uri->path);
889 890 891
                return VIR_DRV_OPEN_ERROR;
            }
        }
892 893 894 895 896 897 898
    }
    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int qemudClose(virConnectPtr conn) {
899
    struct qemud_driver *driver = conn->privateData;
900 901

    /* Get rid of callbacks registered for this conn */
902
    qemuDriverLock(driver);
903 904
    virDomainEventCallbackListRemoveConn(conn,
                                         driver->domainEventState->callbacks);
905
    qemuProcessAutoDestroyRun(driver, conn);
906
    qemuDriverUnlock(driver);
907 908 909 910 911 912

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
913 914 915 916 917
/* Which features are supported by this driver? */
static int
qemudSupportsFeature (virConnectPtr conn ATTRIBUTE_UNUSED, int feature)
{
    switch (feature) {
918
    case VIR_DRV_FEATURE_MIGRATION_V2:
919
    case VIR_DRV_FEATURE_MIGRATION_V3:
920
    case VIR_DRV_FEATURE_MIGRATION_P2P:
921
    case VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION:
922
    case VIR_DRV_FEATURE_FD_PASSING:
923
    case VIR_DRV_FEATURE_TYPED_PARAM_STRING:
924 925 926
        return 1;
    default:
        return 0;
D
Daniel Veillard 已提交
927 928 929
    }
}

930
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
931
    return "QEMU";
932 933
}

934

935 936 937 938 939 940 941 942 943 944 945 946
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;
}

947 948 949 950 951
static int qemuIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    return 1;
}

952

953 954 955 956
static int kvmGetMaxVCPUs(void) {
    int maxvcpus = 1;

    int r, fd;
957

958 959
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
960
        virReportSystemError(errno, _("Unable to open %s"), KVM_DEVICE);
961
        return -1;
962 963 964 965 966 967
    }

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

968
    VIR_FORCE_CLOSE(fd);
969 970 971 972
    return maxvcpus;
}


E
Eric Blake 已提交
973 974 975 976
static char *
qemuGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    struct qemud_driver *driver = conn->privateData;
977
    virBuffer buf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
978 979 980 981 982 983 984 985 986

    virCheckFlags(0, NULL);

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

987 988 989 990 991 992 993
    if (virSysinfoFormat(&buf, driver->hostsysinfo) < 0)
        return NULL;
    if (virBufferError(&buf)) {
        virReportOOMError();
        return NULL;
    }
    return virBufferContentAndReset(&buf);
E
Eric Blake 已提交
994 995
}

996
static int qemudGetMaxVCPUs(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
997 998 999
    if (!type)
        return 16;

1000
    if (STRCASEEQ(type, "qemu"))
1001 1002
        return 16;

1003
    if (STRCASEEQ(type, "kvm"))
1004
        return kvmGetMaxVCPUs();
1005

1006
    if (STRCASEEQ(type, "kqemu"))
1007
        return 1;
1008

1009 1010
    qemuReportError(VIR_ERR_INVALID_ARG,
                    _("unknown type '%s'"), type);
1011 1012 1013
    return -1;
}

1014

1015
static char *qemudGetCapabilities(virConnectPtr conn) {
1016
    struct qemud_driver *driver = conn->privateData;
1017
    virCapsPtr caps = NULL;
1018
    char *xml = NULL;
1019

1020
    qemuDriverLock(driver);
1021

1022
    if ((caps = qemuCreateCapabilities(qemu_driver->caps,
1023
                                       qemu_driver)) == NULL) {
1024 1025 1026
        virCapabilitiesFree(caps);
        goto cleanup;
    }
1027

1028
    virCapabilitiesFree(qemu_driver->caps);
1029 1030 1031
    qemu_driver->caps = caps;

    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1032
        virReportOOMError();
1033 1034

cleanup:
1035
    qemuDriverUnlock(driver);
1036

1037
    return xml;
1038 1039 1040
}


1041 1042 1043 1044 1045
static int
qemudGetProcessInfo(unsigned long long *cpuTime, int *lastCpu, int pid,
                    int tid)
{
    char *proc;
D
Daniel P. Berrange 已提交
1046
    FILE *pidinfo;
1047
    unsigned long long usertime, systime;
1048 1049
    int cpu;
    int ret;
D
Daniel P. Berrange 已提交
1050

1051
    if (tid)
1052
        ret = virAsprintf(&proc, "/proc/%d/task/%d/stat", pid, tid);
1053
    else
1054 1055
        ret = virAsprintf(&proc, "/proc/%d/stat", pid);
    if (ret < 0)
D
Daniel P. Berrange 已提交
1056 1057 1058 1059
        return -1;

    if (!(pidinfo = fopen(proc, "r"))) {
        /* VM probably shut down, so fake 0 */
1060 1061 1062 1063
        if (cpuTime)
            *cpuTime = 0;
        if (lastCpu)
            *lastCpu = 0;
1064
        VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1065 1066
        return 0;
    }
1067
    VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1068

1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    /* 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) {
1079
        VIR_FORCE_FCLOSE(pidinfo);
1080
        VIR_WARN("cannot parse process status data");
1081
        errno = -EINVAL;
D
Daniel P. Berrange 已提交
1082 1083 1084 1085 1086 1087 1088 1089
        return -1;
    }

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
1090 1091 1092 1093 1094
    if (cpuTime)
        *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
    if (lastCpu)
        *lastCpu = cpu;

D
Daniel P. Berrange 已提交
1095

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

1099
    VIR_FORCE_FCLOSE(pidinfo);
D
Daniel P. Berrange 已提交
1100 1101 1102 1103 1104

    return 0;
}


1105
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1106
                                          int id) {
1107 1108 1109 1110
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1111
    qemuDriverLock(driver);
1112
    vm  = virDomainFindByID(&driver->domains, id);
1113
    qemuDriverUnlock(driver);
1114 1115

    if (!vm) {
1116 1117
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching id %d"), id);
1118
        goto cleanup;
1119 1120
    }

1121
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1122
    if (dom) dom->id = vm->def->id;
1123 1124

cleanup:
1125 1126
    if (vm)
        virDomainObjUnlock(vm);
1127 1128
    return dom;
}
1129

1130
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1131
                                            const unsigned char *uuid) {
1132 1133 1134
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1135

1136
    qemuDriverLock(driver);
1137
    vm = virDomainFindByUUID(&driver->domains, uuid);
1138 1139
    qemuDriverUnlock(driver);

1140
    if (!vm) {
1141 1142
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
1143 1144
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1145
        goto cleanup;
1146 1147
    }

1148
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1149
    if (dom) dom->id = vm->def->id;
1150 1151

cleanup:
1152 1153
    if (vm)
        virDomainObjUnlock(vm);
1154 1155
    return dom;
}
1156

1157
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1158
                                            const char *name) {
1159 1160 1161
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1162

1163
    qemuDriverLock(driver);
1164
    vm = virDomainFindByName(&driver->domains, name);
1165 1166
    qemuDriverUnlock(driver);

1167
    if (!vm) {
1168 1169
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), name);
1170
        goto cleanup;
1171 1172
    }

1173
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1174
    if (dom) dom->id = vm->def->id;
1175 1176

cleanup:
1177 1178
    if (vm)
        virDomainObjUnlock(vm);
1179 1180 1181
    return dom;
}

1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192

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 已提交
1193 1194 1195 1196
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
        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 已提交
1217 1218 1219 1220
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
        goto cleanup;
    }
    ret = obj->persistent;

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

1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
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 已提交
1241 1242 1243 1244
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1245 1246 1247 1248 1249 1250 1251 1252 1253
        goto cleanup;
    }
    ret = obj->updated;

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

1255
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1256 1257 1258
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

1259
    qemuDriverLock(driver);
1260
    if (qemuCapsExtractVersion(driver->caps, &driver->qemuVersion) < 0)
1261
        goto cleanup;
1262

1263
    *version = driver->qemuVersion;
1264 1265 1266
    ret = 0;

cleanup:
1267
    qemuDriverUnlock(driver);
1268
    return ret;
D
Daniel P. Berrange 已提交
1269 1270
}

1271
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1272
    struct qemud_driver *driver = conn->privateData;
1273
    int n;
1274

1275
    qemuDriverLock(driver);
1276
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1277
    qemuDriverUnlock(driver);
1278

1279
    return n;
D
Daniel P. Berrange 已提交
1280
}
1281

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

1286
    qemuDriverLock(driver);
1287
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1288
    qemuDriverUnlock(driver);
1289

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

1293
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
1294
                                      unsigned int flags) {
1295
    struct qemud_driver *driver = conn->privateData;
1296
    virDomainDefPtr def;
1297
    virDomainObjPtr vm = NULL;
1298
    virDomainPtr dom = NULL;
1299
    virDomainEventPtr event = NULL;
1300
    virDomainEventPtr event2 = NULL;
D
Daniel P. Berrange 已提交
1301

1302 1303
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
                  VIR_DOMAIN_START_AUTODESTROY, NULL);
1304

1305
    qemuDriverLock(driver);
1306
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1307
                                        QEMU_EXPECTED_VIRT_TYPES,
1308
                                        VIR_DOMAIN_XML_INACTIVE)))
1309
        goto cleanup;
1310

1311
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
1312 1313
        goto cleanup;

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

1317 1318 1319
    if (qemudCanonicalizeMachine(driver, def) < 0)
        goto cleanup;

1320
    if (qemuDomainAssignPCIAddresses(def) < 0)
1321 1322
        goto cleanup;

1323
    if (!(vm = virDomainAssignDef(driver->caps,
1324
                                  &driver->domains,
1325
                                  def, false)))
1326 1327 1328
        goto cleanup;

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

1330
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
1331 1332
        goto cleanup; /* XXXX free the 'vm' we created ? */

1333 1334
    if (qemuProcessStart(conn, driver, vm, NULL,
                         (flags & VIR_DOMAIN_START_PAUSED) != 0,
1335
                         (flags & VIR_DOMAIN_START_AUTODESTROY) != 0,
1336
                         -1, NULL, NULL, VIR_NETDEV_VPORT_PROFILE_OP_CREATE) < 0) {
1337
        virDomainAuditStart(vm, "booted", false);
1338
        if (qemuDomainObjEndJob(driver, vm) > 0)
1339
            qemuDomainRemoveInactive(driver, vm);
1340
        vm = NULL;
1341
        goto cleanup;
D
Daniel P. Berrange 已提交
1342
    }
1343 1344 1345 1346

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
    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);
    }
1357
    virDomainAuditStart(vm, "booted", true);
D
Daniel P. Berrange 已提交
1358

1359
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1360
    if (dom) dom->id = vm->def->id;
1361

1362
    if (vm &&
1363
        qemuDomainObjEndJob(driver, vm) == 0)
1364
        vm = NULL;
1365

1366 1367
cleanup:
    virDomainDefFree(def);
1368 1369
    if (vm)
        virDomainObjUnlock(vm);
1370
    if (event) {
1371
        qemuDomainEventQueue(driver, event);
1372 1373 1374
        if (event2)
            qemuDomainEventQueue(driver, event2);
    }
1375
    qemuDriverUnlock(driver);
1376
    return dom;
D
Daniel P. Berrange 已提交
1377 1378 1379
}


1380
static int qemudDomainSuspend(virDomainPtr dom) {
1381 1382 1383
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1384
    virDomainEventPtr event = NULL;
1385
    qemuDomainObjPrivatePtr priv;
1386 1387
    virDomainPausedReason reason;
    int eventDetail;
1388

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

D
Daniel P. Berrange 已提交
1392
    if (!vm) {
1393 1394
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1395 1396
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1397
        goto cleanup;
D
Daniel P. Berrange 已提交
1398
    }
D
Daniel P. Berrange 已提交
1399
    if (!virDomainObjIsActive(vm)) {
1400 1401
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1402
        goto cleanup;
D
Daniel P. Berrange 已提交
1403
    }
1404 1405 1406

    priv = vm->privateData;

1407
    if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_OUT) {
1408 1409
        reason = VIR_DOMAIN_PAUSED_MIGRATION;
        eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED;
1410
    } else {
1411 1412 1413
        reason = VIR_DOMAIN_PAUSED_USER;
        eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_PAUSED;
    }
1414

1415 1416 1417 1418 1419 1420 1421 1422 1423
    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) {
1424
        if (qemuProcessStopCPUs(driver, vm, reason, QEMU_ASYNC_JOB_NONE) < 0) {
1425
            goto endjob;
1426
        }
1427 1428 1429
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         eventDetail);
D
Daniel P. Berrange 已提交
1430
    }
1431 1432 1433
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
        goto endjob;
    ret = 0;
1434

1435
endjob:
1436
    if (qemuDomainObjEndJob(driver, vm) == 0)
1437
        vm = NULL;
1438

1439
cleanup:
1440 1441
    if (vm)
        virDomainObjUnlock(vm);
1442

1443
    if (event)
1444
        qemuDomainEventQueue(driver, event);
1445
    qemuDriverUnlock(driver);
1446
    return ret;
D
Daniel P. Berrange 已提交
1447 1448 1449
}


1450
static int qemudDomainResume(virDomainPtr dom) {
1451 1452 1453
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1454
    virDomainEventPtr event = NULL;
1455

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

D
Daniel P. Berrange 已提交
1459
    if (!vm) {
1460 1461
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1462 1463
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1464
        goto cleanup;
D
Daniel P. Berrange 已提交
1465
    }
1466

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

D
Daniel P. Berrange 已提交
1470
    if (!virDomainObjIsActive(vm)) {
1471 1472
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1473
        goto endjob;
D
Daniel P. Berrange 已提交
1474
    }
J
Jiri Denemark 已提交
1475 1476
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
        if (qemuProcessStartCPUs(driver, vm, dom->conn,
1477 1478
                                 VIR_DOMAIN_RUNNING_UNPAUSED,
                                 QEMU_ASYNC_JOB_NONE) < 0) {
1479
            if (virGetLastError() == NULL)
1480 1481
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("resume operation failed"));
1482
            goto endjob;
1483
        }
1484 1485 1486
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
D
Daniel P. Berrange 已提交
1487
    }
1488
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
1489
        goto endjob;
1490 1491
    ret = 0;

1492
endjob:
1493
    if (qemuDomainObjEndJob(driver, vm) == 0)
1494
        vm = NULL;
1495

1496
cleanup:
1497 1498
    if (vm)
        virDomainObjUnlock(vm);
1499
    if (event)
1500
        qemuDomainEventQueue(driver, event);
1501
    qemuDriverUnlock(driver);
1502
    return ret;
D
Daniel P. Berrange 已提交
1503 1504 1505
}


1506
static int qemuDomainShutdown(virDomainPtr dom) {
1507 1508 1509
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1510
    qemuDomainObjPrivatePtr priv;
1511

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

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

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

D
Daniel P. Berrange 已提交
1527
    if (!virDomainObjIsActive(vm)) {
1528 1529
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1530
        goto endjob;
1531 1532
    }

1533 1534
    qemuDomainSetFakeReboot(driver, vm, false);

1535
    priv = vm->privateData;
1536
    qemuDomainObjEnterMonitor(driver, vm);
1537
    ret = qemuMonitorSystemPowerdown(priv->mon);
1538
    qemuDomainObjExitMonitor(driver, vm);
1539

1540
endjob:
1541
    if (qemuDomainObjEndJob(driver, vm) == 0)
1542
        vm = NULL;
1543

1544
cleanup:
1545 1546
    if (vm)
        virDomainObjUnlock(vm);
1547
    return ret;
1548 1549 1550
}


1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
static int qemuDomainReboot(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;
    }

1571 1572
    priv = vm->privateData;

1573
    if (qemuCapsGet(priv->qemuCaps, QEMU_CAPS_MONITOR_JSON)) {
1574 1575 1576 1577 1578 1579
        if (!qemuCapsGet(priv->qemuCaps, QEMU_CAPS_NO_SHUTDOWN)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("Reboot is not supported with this QEMU binary"));
            goto cleanup;
        }

1580
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1581 1582 1583 1584 1585 1586 1587 1588
            goto cleanup;

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

1589
        qemuDomainObjEnterMonitor(driver, vm);
1590
        ret = qemuMonitorSystemPowerdown(priv->mon);
1591
        qemuDomainObjExitMonitor(driver, vm);
1592

1593 1594
        if (ret == 0)
            qemuDomainSetFakeReboot(driver, vm, true);
1595 1596

    endjob:
1597
        if (qemuDomainObjEndJob(driver, vm) == 0)
1598 1599
            vm = NULL;
    } else {
1600
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
                        _("Reboot is not supported without the JSON monitor"));
    }

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


1611 1612 1613 1614 1615 1616 1617 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 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
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;
}


1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
/* 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)++;
}

1673 1674 1675 1676
static int
qemuDomainDestroyFlags(virDomainPtr dom,
                       unsigned int flags)
{
1677 1678 1679
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1680
    virDomainEventPtr event = NULL;
1681

1682 1683
    virCheckFlags(0, -1);

1684
    qemuDriverLock(driver);
1685
    vm  = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel P. Berrange 已提交
1686
    if (!vm) {
1687 1688
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1689 1690
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1691
        goto cleanup;
D
Daniel P. Berrange 已提交
1692
    }
1693

1694
    qemuDomainSetFakeReboot(driver, vm, false);
1695

1696 1697 1698 1699 1700
    /* 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
     */
1701
    qemuProcessKill(vm, false);
1702

1703
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_DESTROY) < 0)
1704 1705
        goto cleanup;

D
Daniel P. Berrange 已提交
1706
    if (!virDomainObjIsActive(vm)) {
1707 1708
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1709
        goto endjob;
1710
    }
1711

J
Jiri Denemark 已提交
1712
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_DESTROYED);
1713 1714 1715
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1716
    virDomainAuditStop(vm, "destroyed");
1717

1718
    if (!vm->persistent) {
1719
        if (qemuDomainObjEndJob(driver, vm) > 0)
1720
            qemuDomainRemoveInactive(driver, vm);
1721 1722
        vm = NULL;
    }
1723 1724
    ret = 0;

1725
endjob:
1726
    if (vm &&
1727
        qemuDomainObjEndJob(driver, vm) == 0)
1728
        vm = NULL;
1729

1730
cleanup:
1731 1732
    if (vm)
        virDomainObjUnlock(vm);
1733 1734
    if (event)
        qemuDomainEventQueue(driver, event);
1735
    qemuDriverUnlock(driver);
1736
    return ret;
D
Daniel P. Berrange 已提交
1737 1738
}

1739 1740 1741 1742 1743
static int
qemuDomainDestroy(virDomainPtr dom)
{
    return qemuDomainDestroyFlags(dom, 0);
}
D
Daniel P. Berrange 已提交
1744

1745
static char *qemudDomainGetOSType(virDomainPtr dom) {
1746 1747 1748
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1749

1750
    qemuDriverLock(driver);
1751
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1752
    qemuDriverUnlock(driver);
1753
    if (!vm) {
1754 1755
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1756 1757
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1758
        goto cleanup;
1759 1760
    }

1761
    if (!(type = strdup(vm->def->os.type)))
1762
        virReportOOMError();
1763 1764

cleanup:
1765 1766
    if (vm)
        virDomainObjUnlock(vm);
1767 1768 1769
    return type;
}

1770 1771
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
1772 1773 1774
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
1775

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

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

1788
    ret = vm->def->mem.max_balloon;
1789 1790

cleanup:
1791 1792
    if (vm)
        virDomainObjUnlock(vm);
1793
    return ret;
1794 1795
}

1796 1797
static int qemudDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
                                     unsigned int flags) {
1798
    struct qemud_driver *driver = dom->conn->privateData;
1799
    qemuDomainObjPrivatePtr priv;
1800
    virDomainObjPtr vm;
1801
    virDomainDefPtr persistentDef = NULL;
1802
    int ret = -1, r;
1803
    bool isActive;
1804

1805 1806
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
1807
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1808

1809
    qemuDriverLock(driver);
1810
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1811
    qemuDriverUnlock(driver);
1812
    if (!vm) {
1813 1814
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1815 1816
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1817
        goto cleanup;
1818 1819
    }

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

1823 1824
    isActive = virDomainObjIsActive(vm);

1825
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
1826
        if (isActive)
1827
            flags = VIR_DOMAIN_AFFECT_LIVE;
1828
        else
1829
            flags = VIR_DOMAIN_AFFECT_CONFIG;
1830
    }
1831 1832
    if (flags == VIR_DOMAIN_MEM_MAXIMUM) {
        if (isActive)
1833
            flags = VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_MEM_MAXIMUM;
1834
        else
1835
            flags = VIR_DOMAIN_AFFECT_CONFIG | VIR_DOMAIN_MEM_MAXIMUM;
1836
    }
1837

1838
    if (!isActive && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
1839 1840 1841 1842 1843
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

1844
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
1845 1846 1847 1848 1849 1850 1851 1852
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot change persistent config of a transient domain"));
            goto endjob;
        }
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
            goto endjob;
    }
1853

1854 1855 1856
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */

1857
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
1858 1859 1860
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot resize the maximum memory on an "
                              "active domain"));
1861
            goto endjob;
1862
        }
1863

1864
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
1865 1866
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
1867 1868 1869 1870
            persistentDef->mem.max_balloon = newmem;
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
1871 1872 1873
            goto endjob;
        }

1874 1875 1876 1877 1878 1879 1880 1881 1882
    } 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;
        }

1883
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
1884
            priv = vm->privateData;
1885
            qemuDomainObjEnterMonitor(driver, vm);
1886
            r = qemuMonitorSetBalloon(priv->mon, newmem);
1887
            qemuDomainObjExitMonitor(driver, vm);
1888 1889
            virDomainAuditMemory(vm, vm->def->mem.cur_balloon, newmem, "update",
                                 r == 1);
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
            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;
            }
        }

1901
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
1902
            sa_assert(persistentDef);
1903 1904 1905 1906
            persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
            goto endjob;
        }
1907
    }
1908

1909
    ret = 0;
1910
endjob:
1911
    if (qemuDomainObjEndJob(driver, vm) == 0)
1912
        vm = NULL;
1913

1914
cleanup:
1915 1916
    if (vm)
        virDomainObjUnlock(vm);
1917
    return ret;
1918 1919
}

1920 1921
static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem)
{
1922
    return qemudDomainSetMemoryFlags(dom, newmem, VIR_DOMAIN_AFFECT_LIVE);
1923 1924
}

1925 1926 1927 1928 1929
static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return qemudDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
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;

1957
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
1958
        goto cleanup;
1959 1960 1961 1962 1963 1964 1965

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

1966
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
1967 1968
    ret = qemuMonitorInjectNMI(priv->mon);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
1969 1970

endjob:
1971
    if (qemuDomainObjEndJob(driver, vm) == 0) {
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
        vm = NULL;
        goto cleanup;
    }

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

1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
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);

1997 1998
    /* translate the keycode to RFB for qemu driver */
    if (codeset != VIR_KEYCODE_SET_RFB) {
1999 2000 2001 2002
        int i;
        int keycode;

        for (i = 0; i < nkeycodes; i++) {
2003
            keycode = virKeycodeValueTranslate(codeset, VIR_KEYCODE_SET_RFB,
2004 2005 2006
                                               keycodes[i]);
            if (keycode < 0) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
2007
             _("cannot translate keycode %u of %s codeset to rfb keycode"),
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
                                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"));
2034
        goto endjob;
2035 2036
    }

2037
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2038 2039
    ret = qemuMonitorSendKey(priv->mon, holdtime, keycodes, nkeycodes);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
2040 2041 2042

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
2043 2044 2045 2046 2047 2048 2049 2050 2051
        vm = NULL;

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

2052
static int qemudDomainGetInfo(virDomainPtr dom,
2053 2054
                              virDomainInfoPtr info)
{
2055 2056 2057
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2058 2059
    int err;
    unsigned long balloon;
2060

2061
    qemuDriverLock(driver);
2062
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2063
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
2064
    if (!vm) {
2065 2066
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2067 2068
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
2069
        goto cleanup;
D
Daniel P. Berrange 已提交
2070 2071
    }

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

D
Daniel P. Berrange 已提交
2074
    if (!virDomainObjIsActive(vm)) {
2075
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
2076
    } else {
2077
        if (qemudGetProcessInfo(&(info->cpuTime), NULL, vm->pid, 0) < 0) {
E
Eric Blake 已提交
2078 2079
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("cannot read cputime for domain"));
2080
            goto cleanup;
D
Daniel P. Berrange 已提交
2081 2082 2083
        }
    }

2084
    info->maxMem = vm->def->mem.max_balloon;
2085

D
Daniel P. Berrange 已提交
2086
    if (virDomainObjIsActive(vm)) {
2087
        qemuDomainObjPrivatePtr priv = vm->privateData;
2088 2089 2090

        if ((vm->def->memballoon != NULL) &&
            (vm->def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_NONE)) {
2091
            info->memory = vm->def->mem.max_balloon;
2092
        } else if (qemuDomainJobAllowed(priv, QEMU_JOB_QUERY)) {
2093
            if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
2094
                goto cleanup;
2095 2096 2097
            if (!virDomainObjIsActive(vm))
                err = 0;
            else {
2098
                qemuDomainObjEnterMonitor(driver, vm);
2099
                err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
2100
                qemuDomainObjExitMonitor(driver, vm);
2101
            }
2102
            if (qemuDomainObjEndJob(driver, vm) == 0) {
2103
                vm = NULL;
2104 2105 2106
                goto cleanup;
            }

2107 2108 2109 2110 2111 2112 2113
            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) {
2114
                /* Balloon not supported, so maxmem is always the allocation */
2115
                info->memory = vm->def->mem.max_balloon;
2116
            } else {
2117
                info->memory = balloon;
2118
            }
2119
        } else {
2120
            info->memory = vm->def->mem.cur_balloon;
2121
        }
2122
    } else {
2123
        info->memory = vm->def->mem.cur_balloon;
2124 2125
    }

2126
    info->nrVirtCpu = vm->def->vcpus;
2127 2128 2129
    ret = 0;

cleanup:
2130 2131
    if (vm)
        virDomainObjUnlock(vm);
2132
    return ret;
D
Daniel P. Berrange 已提交
2133 2134
}

2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
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 已提交
2159
    *state = virDomainObjGetState(vm, reason);
2160 2161 2162 2163 2164 2165 2166 2167
    ret = 0;

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

2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
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;
2204
    } else if (priv->job.active) {
2205 2206
        if (!priv->monStart) {
            info->state = VIR_DOMAIN_CONTROL_JOB;
2207
            if (virTimeMillisNow(&info->stateTime) < 0)
2208
                goto cleanup;
2209
            info->stateTime -= priv->job.start;
2210 2211
        } else {
            info->state = VIR_DOMAIN_CONTROL_OCCUPIED;
2212
            if (virTimeMillisNow(&info->stateTime) < 0)
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
                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 已提交
2228

E
Eric Blake 已提交
2229 2230
#define QEMUD_SAVE_MAGIC   "LibvirtQemudSave"
#define QEMUD_SAVE_PARTIAL "LibvirtQemudPart"
2231 2232
#define QEMUD_SAVE_VERSION 2

E
Eric Blake 已提交
2233 2234
verify(sizeof(QEMUD_SAVE_MAGIC) == sizeof(QEMUD_SAVE_PARTIAL));

2235
enum qemud_save_formats {
2236 2237 2238
    QEMUD_SAVE_FORMAT_RAW = 0,
    QEMUD_SAVE_FORMAT_GZIP = 1,
    QEMUD_SAVE_FORMAT_BZIP2 = 2,
2239 2240
    /*
     * Deprecated by xz and never used as part of a release
2241
     * QEMUD_SAVE_FORMAT_LZMA
2242 2243
     */
    QEMUD_SAVE_FORMAT_XZ = 3,
2244
    QEMUD_SAVE_FORMAT_LZOP = 4,
2245 2246 2247
    /* Note: add new members only at the end.
       These values are used in the on-disk format.
       Do not change or re-use numbers. */
2248 2249

    QEMUD_SAVE_FORMAT_LAST
2250
};
2251

2252 2253 2254 2255 2256
VIR_ENUM_DECL(qemudSaveCompression)
VIR_ENUM_IMPL(qemudSaveCompression, QEMUD_SAVE_FORMAT_LAST,
              "raw",
              "gzip",
              "bzip2",
2257 2258
              "xz",
              "lzop")
2259

2260 2261
struct qemud_save_header {
    char magic[sizeof(QEMUD_SAVE_MAGIC)-1];
2262 2263 2264 2265 2266
    uint32_t version;
    uint32_t xml_len;
    uint32_t was_running;
    uint32_t compressed;
    uint32_t unused[15];
2267 2268
};

2269 2270 2271 2272 2273 2274 2275 2276 2277
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);
}


2278
/* return -errno on failure, or 0 on success */
E
Eric Blake 已提交
2279 2280 2281 2282
static int
qemuDomainSaveHeader(int fd, const char *path, char *xml,
                     struct qemud_save_header *header)
{
2283 2284
    int ret = 0;

E
Eric Blake 已提交
2285
    if (safewrite(fd, header, sizeof(*header)) != sizeof(*header)) {
2286
        ret = -errno;
2287
        qemuReportError(VIR_ERR_OPERATION_FAILED,
2288
                        _("failed to write header to domain save file '%s'"),
E
Eric Blake 已提交
2289
                        path);
2290 2291 2292
        goto endjob;
    }

E
Eric Blake 已提交
2293
    if (safewrite(fd, xml, header->xml_len) != header->xml_len) {
2294
        ret = -errno;
2295
        qemuReportError(VIR_ERR_OPERATION_FAILED,
E
Eric Blake 已提交
2296
                         _("failed to write xml to '%s'"), path);
2297 2298 2299 2300 2301 2302
        goto endjob;
    }
endjob:
    return ret;
}

2303 2304 2305 2306 2307 2308 2309 2310 2311
/* 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 已提交
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 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
/* 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;
}

2419
/* This internal function expects the driver lock to already be held on
2420 2421 2422 2423
 * 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).
2424
 */
2425 2426 2427
static int
qemuDomainSaveInternal(struct qemud_driver *driver, virDomainPtr dom,
                       virDomainObjPtr vm, const char *path,
2428
                       int compressed, const char *xmlin, unsigned int flags)
2429
{
2430
    char *xml = NULL;
2431
    struct qemud_save_header header;
2432
    bool bypassSecurityDriver = false;
2433
    int ret = -1;
2434
    int rc;
2435
    virDomainEventPtr event = NULL;
2436
    qemuDomainObjPrivatePtr priv;
E
Eric Blake 已提交
2437
    bool needUnlink = false;
2438
    size_t len;
2439
    unsigned long long offset;
2440
    unsigned long long pad;
2441
    int fd = -1;
2442 2443
    int directFlag = 0;
    virFileDirectFdPtr directFd = NULL;
2444
    bool bypass_cache = flags & VIR_DOMAIN_SAVE_BYPASS_CACHE;
2445

2446 2447 2448
    if (qemuProcessAutoDestroyActive(driver, vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is marked for auto destroy"));
2449
        goto cleanup;
2450 2451
    }

2452
    memset(&header, 0, sizeof(header));
E
Eric Blake 已提交
2453
    memcpy(header.magic, QEMUD_SAVE_PARTIAL, sizeof(header.magic));
2454 2455
    header.version = QEMUD_SAVE_VERSION;

2456
    header.compressed = compressed;
2457

2458
    priv = vm->privateData;
2459

2460 2461
    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             QEMU_ASYNC_JOB_SAVE) < 0)
2462 2463
        goto cleanup;

2464 2465
    memset(&priv->job.info, 0, sizeof(priv->job.info));
    priv->job.info.type = VIR_DOMAIN_JOB_UNBOUNDED;
2466

2467
    /* Pause */
J
Jiri Denemark 已提交
2468
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
2469
        header.was_running = 1;
2470 2471
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_SAVE) < 0)
2472
            goto endjob;
2473 2474 2475 2476 2477 2478

        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto endjob;
        }
2479
    }
2480 2481 2482 2483 2484
    /* 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;
2485

2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
    /* 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));
    }
2508
    if (!xml) {
2509 2510
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to get domain xml"));
2511
        goto endjob;
2512
    }
2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
    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;
2533

2534
    /* Obtain the file handle.  */
2535 2536 2537 2538 2539
    if (bypass_cache) {
        directFlag = virFileDirectFdFlag();
        if (directFlag < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("bypass cache unsupported by this system"));
E
Eric Blake 已提交
2540
            goto cleanup;
2541
        }
2542
    }
E
Eric Blake 已提交
2543 2544 2545 2546
    fd = qemuOpenFile(driver, path, O_WRONLY | O_TRUNC | O_CREAT | directFlag,
                      &needUnlink, &bypassSecurityDriver);
    if (fd < 0)
        goto endjob;
2547 2548 2549
    if (bypass_cache && (directFd = virFileDirectFdNew(&fd, path)) == NULL)
        goto endjob;

2550
    /* Write header to file, followed by XML */
E
Eric Blake 已提交
2551
    if (qemuDomainSaveHeader(fd, path, xml, &header) < 0) {
2552 2553 2554 2555
        VIR_FORCE_CLOSE(fd);
        goto endjob;
    }

2556
    /* Perform the migration */
2557
    if (qemuMigrationToFile(driver, vm, fd, offset, path,
2558
                            qemuCompressProgramName(compressed),
E
Eric Blake 已提交
2559
                            bypassSecurityDriver,
2560
                            QEMU_ASYNC_JOB_SAVE) < 0)
2561
        goto endjob;
E
Eric Blake 已提交
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588

    /* 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;
    }
2589 2590
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("unable to close %s"), path);
2591
        goto endjob;
2592 2593
    }

2594 2595
    ret = 0;

2596
    /* Shut it down */
J
Jiri Denemark 已提交
2597
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_SAVED);
2598
    virDomainAuditStop(vm, "saved");
2599 2600 2601
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2602
    if (!vm->persistent) {
2603
        if (qemuDomainObjEndAsyncJob(driver, vm) > 0)
2604
            qemuDomainRemoveInactive(driver, vm);
2605 2606
        vm = NULL;
    }
2607

2608
endjob:
2609
    if (vm) {
2610
        if (ret != 0) {
2611
            if (header.was_running && virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
2612
                rc = qemuProcessStartCPUs(driver, vm, dom->conn,
2613 2614
                                          VIR_DOMAIN_RUNNING_SAVE_CANCELED,
                                          QEMU_ASYNC_JOB_SAVE);
2615
                if (rc < 0)
2616
                    VIR_WARN("Unable to resume guest CPUs after save failure");
2617
            }
2618
        }
2619
        if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
2620
            vm = NULL;
2621
    }
2622

2623
cleanup:
2624
    VIR_FORCE_CLOSE(fd);
2625
    virFileDirectFdFree(directFd);
2626
    VIR_FREE(xml);
E
Eric Blake 已提交
2627
    if (ret != 0 && needUnlink)
2628
        unlink(path);
2629 2630
    if (event)
        qemuDomainEventQueue(driver, event);
2631 2632
    if (vm)
        virDomainObjUnlock(vm);
2633
    return ret;
D
Daniel P. Berrange 已提交
2634 2635
}

2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
/* 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;
}

2652 2653 2654
static int
qemuDomainSaveFlags(virDomainPtr dom, const char *path, const char *dxml,
                    unsigned int flags)
2655 2656 2657
{
    struct qemud_driver *driver = dom->conn->privateData;
    int compressed;
2658 2659 2660
    int ret = -1;
    virDomainObjPtr vm = NULL;

2661 2662 2663
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
                  VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
2664

2665
    qemuDriverLock(driver);
2666 2667 2668 2669 2670 2671 2672 2673 2674

    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"));
2675
            goto cleanup;
2676
        }
2677 2678 2679 2680
        if (!qemudCompressProgramAvailable(compressed)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Compression program for image format "
                                    "in configuration file isn't available"));
2681
            goto cleanup;
2682
        }
2683 2684
    }

2685 2686 2687 2688 2689 2690 2691 2692 2693
    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;
    }

2694 2695 2696 2697 2698 2699
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2700
    ret = qemuDomainSaveInternal(driver, dom, vm, path, compressed,
2701
                                 dxml, flags);
2702
    vm = NULL;
2703 2704 2705 2706 2707 2708 2709

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

    return ret;
2710 2711
}

2712 2713 2714 2715 2716 2717
static int
qemuDomainSave(virDomainPtr dom, const char *path)
{
    return qemuDomainSaveFlags(dom, path, NULL, 0);
}

2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738
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;

2739 2740 2741
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
                  VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
2742 2743 2744 2745 2746 2747 2748 2749

    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);
2750
        goto cleanup;
2751 2752
    }

2753 2754 2755 2756 2757
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }
2758 2759 2760 2761 2762
    if (!vm->persistent) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot do managed save for transient domain"));
        goto cleanup;
    }
2763

2764 2765
    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
2766
        goto cleanup;
2767

2768
    VIR_INFO("Saving state to %s", name);
2769 2770

    compressed = QEMUD_SAVE_FORMAT_RAW;
2771
    ret = qemuDomainSaveInternal(driver, dom, vm, name, compressed,
2772
                                 NULL, flags);
2773
    vm = NULL;
2774 2775 2776 2777 2778

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
2779 2780 2781
    VIR_FREE(name);

    return ret;
2782 2783 2784 2785 2786 2787 2788 2789 2790 2791
}

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

2792
    virCheckFlags(0, -1);
2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825

    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;

2826
    virCheckFlags(0, -1);
2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850

    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 已提交
2851

2852 2853 2854 2855
static int
doCoreDump(struct qemud_driver *driver,
           virDomainObjPtr vm,
           const char *path,
2856 2857
           enum qemud_save_formats compress,
           bool bypass_cache)
H
Hu Tao 已提交
2858 2859 2860
{
    int fd = -1;
    int ret = -1;
2861 2862
    virFileDirectFdPtr directFd = NULL;
    int directFlag = 0;
H
Hu Tao 已提交
2863 2864

    /* Create an empty file with appropriate ownership.  */
2865 2866 2867 2868 2869 2870 2871 2872
    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 已提交
2873 2874 2875 2876 2877 2878
    /* 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 已提交
2879 2880
        goto cleanup;

2881 2882 2883
    if (bypass_cache && (directFd = virFileDirectFdNew(&fd, path)) == NULL)
        goto cleanup;

2884
    if (qemuMigrationToFile(driver, vm, fd, 0, path,
E
Eric Blake 已提交
2885
                            qemuCompressProgramName(compress), false,
2886
                            QEMU_ASYNC_JOB_DUMP) < 0)
2887 2888
        goto cleanup;

H
Hu Tao 已提交
2889 2890 2891 2892 2893 2894
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno,
                             _("unable to save file %s"),
                             path);
        goto cleanup;
    }
2895 2896
    if (virFileDirectFdClose(directFd) < 0)
        goto cleanup;
H
Hu Tao 已提交
2897

2898
    ret = 0;
H
Hu Tao 已提交
2899 2900

cleanup:
2901
    VIR_FORCE_CLOSE(fd);
2902
    virFileDirectFdFree(directFd);
H
Hu Tao 已提交
2903 2904 2905 2906 2907
    if (ret != 0)
        unlink(path);
    return ret;
}

2908 2909 2910 2911 2912
static enum qemud_save_formats
getCompressionType(struct qemud_driver *driver)
{
    int compress = QEMUD_SAVE_FORMAT_RAW;

2913 2914 2915 2916 2917 2918
    /*
     * 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);
2919 2920 2921
        /* Use "raw" as the format if the specified format is not valid,
         * or the compress program is not available.
         */
2922
        if (compress < 0) {
2923 2924
            VIR_WARN("%s", _("Invalid dump image format specified in "
                             "configuration file, using raw"));
2925
            return QEMUD_SAVE_FORMAT_RAW;
2926
        }
2927
        if (!qemudCompressProgramAvailable(compress)) {
2928 2929 2930
            VIR_WARN("%s", _("Compression program for dump image format "
                             "in configuration file isn't available, "
                             "using raw"));
2931
            return QEMUD_SAVE_FORMAT_RAW;
2932
        }
2933
    }
2934 2935 2936 2937 2938
    return compress;
}

static int qemudDomainCoreDump(virDomainPtr dom,
                               const char *path,
2939
                               unsigned int flags)
2940
{
2941 2942
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
M
Michal Privoznik 已提交
2943
    qemuDomainObjPrivatePtr priv;
2944
    int resume = 0, paused = 0;
H
Hu Tao 已提交
2945
    int ret = -1;
2946 2947
    virDomainEventPtr event = NULL;

M
Michal Privoznik 已提交
2948 2949
    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH |
                  VIR_DUMP_BYPASS_CACHE | VIR_DUMP_RESET, -1);
2950

P
Paolo Bonzini 已提交
2951 2952 2953 2954 2955 2956
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2957 2958
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
P
Paolo Bonzini 已提交
2959 2960 2961
        goto cleanup;
    }

2962 2963
    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             QEMU_ASYNC_JOB_DUMP) < 0)
2964 2965
        goto cleanup;

D
Daniel P. Berrange 已提交
2966
    if (!virDomainObjIsActive(vm)) {
2967 2968
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
2969
        goto endjob;
P
Paolo Bonzini 已提交
2970 2971
    }

P
Paolo Bonzini 已提交
2972 2973
    /* Migrate will always stop the VM, so the resume condition is
       independent of whether the stop command is issued.  */
J
Jiri Denemark 已提交
2974
    resume = virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING;
P
Paolo Bonzini 已提交
2975 2976

    /* Pause domain for non-live dump */
J
Jiri Denemark 已提交
2977 2978
    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
2979 2980
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_DUMP,
                                QEMU_ASYNC_JOB_DUMP) < 0)
2981
            goto endjob;
P
Paolo Bonzini 已提交
2982
        paused = 1;
2983 2984 2985 2986 2987 2988

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

2991 2992
    ret = doCoreDump(driver, vm, path, getCompressionType(driver),
                     (flags & VIR_DUMP_BYPASS_CACHE) != 0);
2993 2994 2995 2996
    if (ret < 0)
        goto endjob;

    paused = 1;
2997 2998

endjob:
2999
    if ((ret == 0) && (flags & VIR_DUMP_CRASH)) {
J
Jiri Denemark 已提交
3000
        qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_CRASHED);
3001
        virDomainAuditStop(vm, "crashed");
3002 3003 3004 3005 3006
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
    }

P
Paolo Bonzini 已提交
3007 3008 3009
    /* 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 已提交
3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021
    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) {
3022
            if (virGetLastError() == NULL)
3023 3024
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("resuming after dump failed"));
P
Paolo Bonzini 已提交
3025 3026
        }
    }
3027

3028
    if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
3029
        vm = NULL;
3030
    else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
3031
        qemuDomainRemoveInactive(driver, vm);
3032 3033
        vm = NULL;
    }
3034 3035

cleanup:
P
Paolo Bonzini 已提交
3036 3037
    if (vm)
        virDomainObjUnlock(vm);
3038 3039
    if (event)
        qemuDomainEventQueue(driver, event);
3040
    qemuDriverUnlock(driver);
P
Paolo Bonzini 已提交
3041 3042 3043
    return ret;
}

3044 3045 3046 3047
static char *
qemuDomainScreenshot(virDomainPtr dom,
                     virStreamPtr st,
                     unsigned int screen,
E
Eric Blake 已提交
3048
                     unsigned int flags)
3049 3050 3051 3052 3053 3054 3055
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    char *tmp = NULL;
    int tmp_fd = -1;
    char *ret = NULL;
E
Eric Blake 已提交
3056
    bool unlink_tmp = false;
3057

E
Eric Blake 已提交
3058 3059
    virCheckFlags(0, NULL);

3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073
    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;

3074
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100
        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 已提交
3101
    unlink_tmp = true;
3102

3103 3104
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm, tmp);

3105
    qemuDomainObjEnterMonitor(driver, vm);
3106
    if (qemuMonitorScreendump(priv->mon, tmp) < 0) {
3107
        qemuDomainObjExitMonitor(driver, vm);
3108 3109
        goto endjob;
    }
3110
    qemuDomainObjExitMonitor(driver, vm);
3111 3112 3113 3114 3115 3116

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

E
Eric Blake 已提交
3117
    if (virFDStreamOpenFile(st, tmp, 0, 0, O_RDONLY) < 0) {
3118 3119 3120 3121 3122 3123 3124 3125 3126
        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 已提交
3127 3128
    if (unlink_tmp)
        unlink(tmp);
E
Eric Blake 已提交
3129
    VIR_FREE(tmp);
3130

3131
    if (qemuDomainObjEndJob(driver, vm) == 0)
3132 3133 3134 3135 3136 3137 3138 3139
        vm = NULL;

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

H
Hu Tao 已提交
3140 3141 3142
static void processWatchdogEvent(void *data, void *opaque)
{
    int ret;
3143
    struct qemuDomainWatchdogEvent *wdEvent = data;
H
Hu Tao 已提交
3144 3145
    struct qemud_driver *driver = opaque;

W
Wen Congyang 已提交
3146 3147 3148
    qemuDriverLock(driver);
    virDomainObjLock(wdEvent->vm);

H
Hu Tao 已提交
3149 3150 3151 3152 3153
    switch (wdEvent->action) {
    case VIR_DOMAIN_WATCHDOG_ACTION_DUMP:
        {
            char *dumpfile;

E
Eric Blake 已提交
3154
            if (virAsprintf(&dumpfile, "%s/%s-%u",
H
Hu Tao 已提交
3155 3156
                            driver->autoDumpPath,
                            wdEvent->vm->def->name,
E
Eric Blake 已提交
3157 3158
                            (unsigned int)time(NULL)) < 0) {
                virReportOOMError();
W
Wen Congyang 已提交
3159
                goto unlock;
E
Eric Blake 已提交
3160
            }
H
Hu Tao 已提交
3161

3162 3163
            if (qemuDomainObjBeginAsyncJobWithDriver(driver, wdEvent->vm,
                                                     QEMU_ASYNC_JOB_DUMP) < 0) {
W
Wen Congyang 已提交
3164 3165 3166
                VIR_FREE(dumpfile);
                goto unlock;
            }
H
Hu Tao 已提交
3167 3168 3169 3170

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

3175
            ret = doCoreDump(driver, wdEvent->vm, dumpfile,
3176 3177
                             getCompressionType(driver),
                             driver->autoDumpBypassCache);
H
Hu Tao 已提交
3178 3179 3180 3181
            if (ret < 0)
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("Dump failed"));

J
Jiri Denemark 已提交
3182
            ret = qemuProcessStartCPUs(driver, wdEvent->vm, NULL,
3183 3184
                                       VIR_DOMAIN_RUNNING_UNPAUSED,
                                       QEMU_ASYNC_JOB_DUMP);
H
Hu Tao 已提交
3185 3186 3187 3188 3189 3190 3191 3192

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

            VIR_FREE(dumpfile);
        }
        break;
W
Wen Congyang 已提交
3193 3194
    default:
        goto unlock;
H
Hu Tao 已提交
3195 3196
    }

W
Wen Congyang 已提交
3197 3198 3199 3200
endjob:
    /* Safe to ignore value since ref count was incremented in
     * qemuProcessHandleWatchdog().
     */
3201
    ignore_value(qemuDomainObjEndAsyncJob(driver, wdEvent->vm));
W
Wen Congyang 已提交
3202 3203 3204 3205 3206

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

3210 3211 3212
static int qemudDomainHotplugVcpus(struct qemud_driver *driver,
                                   virDomainObjPtr vm,
                                   unsigned int nvcpus)
3213 3214
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
3215
    int i, rc = 1;
3216
    int ret = -1;
3217
    int oldvcpus = vm->def->vcpus;
E
Eric Blake 已提交
3218
    int vcpus = oldvcpus;
3219

3220
    qemuDomainObjEnterMonitor(driver, vm);
3221

3222 3223 3224
    /* 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 已提交
3225 3226
    if (nvcpus > vcpus) {
        for (i = vcpus ; i < nvcpus ; i++) {
3227 3228 3229 3230 3231 3232 3233
            /* Online new CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 1);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
3234
            vcpus++;
3235 3236
        }
    } else {
E
Eric Blake 已提交
3237
        for (i = vcpus - 1 ; i >= nvcpus ; i--) {
3238 3239 3240 3241 3242 3243 3244
            /* Offline old CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 0);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
3245
            vcpus--;
3246 3247 3248 3249 3250 3251
        }
    }

    ret = 0;

cleanup:
3252
    qemuDomainObjExitMonitor(driver, vm);
E
Eric Blake 已提交
3253
    vm->def->vcpus = vcpus;
3254
    virDomainAuditVcpu(vm, oldvcpus, nvcpus, "update", rc == 1);
3255 3256 3257 3258 3259 3260 3261 3262 3263
    return ret;

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


3264
static int
3265 3266
qemuDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                        unsigned int flags)
3267
{
3268 3269
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3270
    virDomainDefPtr persistentDef;
3271 3272
    const char * type;
    int max;
3273
    int ret = -1;
3274 3275
    bool isActive;
    bool maximum;
3276

3277 3278
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
3279 3280 3281 3282 3283
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

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

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

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

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

3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320
    isActive = virDomainObjIsActive(vm);
    maximum = (flags & VIR_DOMAIN_VCPU_MAXIMUM) != 0;
    flags &= ~VIR_DOMAIN_VCPU_MAXIMUM;

    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
        if (isActive)
            flags |= VIR_DOMAIN_AFFECT_LIVE;
        else
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
    }

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

    if (!isActive && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
3321 3322
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("domain is not running"));
3323
        goto endjob;
3324 3325
    }

3326
    if (!vm->persistent && (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
3327 3328 3329 3330 3331
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot change persistent config of a transient domain"));
        goto endjob;
    }

3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344
    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;
    }

3345
    if (!maximum && vm->def->maxvcpus < max) {
3346 3347 3348
        max = vm->def->maxvcpus;
    }

3349 3350 3351 3352 3353 3354 3355
    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;
    }

3356 3357 3358
    if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
        goto endjob;

3359
    switch (flags) {
3360
    case VIR_DOMAIN_AFFECT_CONFIG:
3361 3362 3363 3364 3365 3366 3367
        if (maximum) {
            persistentDef->maxvcpus = nvcpus;
            if (nvcpus < persistentDef->vcpus)
                persistentDef->vcpus = nvcpus;
        } else {
            persistentDef->vcpus = nvcpus;
        }
3368 3369 3370
        ret = 0;
        break;

3371
    case VIR_DOMAIN_AFFECT_LIVE:
3372
        ret = qemudDomainHotplugVcpus(driver, vm, nvcpus);
3373 3374
        break;

3375
    case VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG:
3376
        ret = qemudDomainHotplugVcpus(driver, vm, nvcpus);
3377 3378 3379
        if (ret == 0) {
            persistentDef->vcpus = nvcpus;
        }
3380 3381
        break;
    }
3382

3383
    /* Save the persistent config to disk */
3384
    if (flags & VIR_DOMAIN_AFFECT_CONFIG)
3385 3386
        ret = virDomainSaveConfig(driver->configDir, persistentDef);

3387
endjob:
3388
    if (qemuDomainObjEndJob(driver, vm) == 0)
3389
        vm = NULL;
3390

3391
cleanup:
3392 3393
    if (vm)
        virDomainObjUnlock(vm);
3394
    return ret;
3395 3396
}

3397
static int
3398
qemuDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
3399
{
3400
    return qemuDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
3401 3402
}

3403 3404

static int
3405 3406 3407 3408 3409 3410
qemudDomainPinVcpuFlags(virDomainPtr dom,
                        unsigned int vcpu,
                        unsigned char *cpumap,
                        int maplen,
                        unsigned int flags) {

3411 3412
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3413
    virDomainDefPtr persistentDef = NULL;
3414
    int maxcpu, hostcpus;
3415
    virNodeInfo nodeinfo;
3416
    int ret = -1;
3417
    bool isActive;
3418
    qemuDomainObjPrivatePtr priv;
3419
    bool canResetting = true;
E
Eric Blake 已提交
3420
    int pcpu;
3421

3422 3423 3424
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

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

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

3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448
    isActive = virDomainObjIsActive(vm);
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
        if (isActive)
            flags = VIR_DOMAIN_AFFECT_LIVE;
        else
            flags = VIR_DOMAIN_AFFECT_CONFIG;
    }

    if (!isActive && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("a domain is inactive; can change only "
                          "persistent config"));
3449
        goto cleanup;
3450 3451
    }

3452 3453 3454
    priv = vm->privateData;

    if (vcpu > (priv->nvcpupids-1)) {
3455 3456 3457
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("vcpu number out of range %d > %d"),
                        vcpu, priv->nvcpupids);
3458
        goto cleanup;
3459 3460
    }

3461 3462 3463 3464 3465 3466 3467 3468 3469
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                   _("cannot change persistent config of a transient domain"));
            goto cleanup;
        }
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
            goto cleanup;
    }
3470

3471 3472 3473 3474 3475 3476 3477 3478 3479
    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 已提交
3480
    for (pcpu = 0; pcpu < hostcpus; pcpu++) {
3481 3482 3483 3484 3485
        if ((cpumap[pcpu/8] & (1 << (pcpu % 8))) == 0) {
            canResetting = false;
            break;
        }
    }
3486

3487
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3488 3489 3490 3491 3492 3493

        if (priv->vcpupids != NULL) {
            if (virProcessInfoSetAffinity(priv->vcpupids[vcpu],
                                          cpumap, maplen, maxcpu) < 0)
                goto cleanup;
        } else {
3494
            qemuReportError(VIR_ERR_OPERATION_INVALID,
3495 3496 3497 3498
                            "%s", _("cpu affinity is not supported"));
            goto cleanup;
        }

3499
        if (canResetting) {
E
Eric Blake 已提交
3500
            if (virDomainVcpuPinDel(vm->def, vcpu) < 0) {
3501 3502 3503 3504 3505 3506
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to delete vcpupin xml of "
                                  "a running domain"));
                goto cleanup;
            }
        } else {
E
Eric Blake 已提交
3507
            if (virDomainVcpuPinAdd(vm->def, cpumap, maplen, vcpu) < 0) {
3508 3509 3510 3511 3512
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to update or add vcpupin xml of "
                                  "a running domain"));
                goto cleanup;
            }
3513 3514
        }

3515 3516
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
            goto cleanup;
3517
    }
3518

3519 3520
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {

3521
        if (canResetting) {
E
Eric Blake 已提交
3522
            if (virDomainVcpuPinDel(persistentDef, vcpu) < 0) {
3523 3524 3525 3526 3527 3528
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to delete vcpupin xml of "
                                  "a persistent domain"));
                goto cleanup;
            }
        } else {
E
Eric Blake 已提交
3529
            if (virDomainVcpuPinAdd(persistentDef, cpumap, maplen, vcpu) < 0) {
3530 3531 3532 3533 3534
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to update or add vcpupin xml of "
                                  "a persistent domain"));
                goto cleanup;
            }
3535
        }
3536

3537
        ret = virDomainSaveConfig(driver->configDir, persistentDef);
3538 3539 3540
        goto cleanup;
    }

3541
    ret = 0;
3542

3543
cleanup:
3544 3545
    if (vm)
        virDomainObjUnlock(vm);
3546
    return ret;
3547 3548
}

3549 3550 3551 3552 3553 3554 3555 3556 3557
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
    return qemudDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

3558
static int
E
Eric Blake 已提交
3559
qemudDomainGetVcpuPinInfo(virDomainPtr dom,
3560 3561 3562 3563 3564 3565
                          int ncpumaps,
                          unsigned char *cpumaps,
                          int maplen,
                          unsigned int flags) {

    struct qemud_driver *driver = dom->conn->privateData;
E
Eric Blake 已提交
3566
    virDomainObjPtr vm = NULL;
3567 3568 3569 3570 3571 3572
    virNodeInfo nodeinfo;
    virDomainDefPtr targetDef = NULL;
    int ret = -1;
    bool isActive;
    int maxcpu, hostcpus, vcpu, pcpu;
    int n;
E
Eric Blake 已提交
3573
    virDomainVcpuPinDefPtr *vcpupin_list;
3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618
    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;
    }

    isActive = virDomainObjIsActive(vm);
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
        if (isActive)
            flags = VIR_DOMAIN_AFFECT_LIVE;
        else
            flags = VIR_DOMAIN_AFFECT_CONFIG;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }
        targetDef = vm->def;
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                   _("cannot get persistent config of a transient domain"));
            goto cleanup;
        }
        if (!(targetDef = virDomainObjGetPersistentDef(driver->caps, vm)))
            goto cleanup;
    }

3619 3620 3621
    /* Coverity didn't realize that targetDef must be set if we got here.  */
    sa_assert(targetDef);

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 3659 3660 3661 3662 3663 3664
    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;
}

3665 3666 3667 3668 3669 3670
static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
3671 3672
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3673
    virNodeInfo nodeinfo;
3674
    int i, v, maxcpu, hostcpus;
3675
    int ret = -1;
3676
    qemuDomainObjPrivatePtr priv;
3677

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

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

D
Daniel P. Berrange 已提交
3690
    if (!virDomainObjIsActive(vm)) {
3691 3692 3693
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s",
                        _("cannot list vcpu pinning for an inactive domain"));
3694
        goto cleanup;
3695 3696
    }

3697 3698
    priv = vm->privateData;

3699
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
3700
        goto cleanup;
3701

3702
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
3703
    maxcpu = maplen * 8;
3704 3705
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
3706 3707

    /* Clamp to actual number of vcpus */
3708 3709
    if (maxinfo > priv->nvcpupids)
        maxinfo = priv->nvcpupids;
3710

3711 3712 3713 3714 3715 3716
    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;
3717

3718
                if (priv->vcpupids != NULL &&
3719 3720 3721
                    qemudGetProcessInfo(&(info[i].cpuTime),
                                        &(info[i].cpu),
                                        vm->pid,
3722
                                        priv->vcpupids[i]) < 0) {
3723
                    virReportSystemError(errno, "%s",
3724 3725 3726
                                         _("cannot get vCPU placement & pCPU time"));
                    goto cleanup;
                }
3727
            }
3728 3729
        }

3730 3731
        if (cpumaps != NULL) {
            memset(cpumaps, 0, maplen * maxinfo);
3732
            if (priv->vcpupids != NULL) {
3733 3734 3735
                for (v = 0 ; v < maxinfo ; v++) {
                    unsigned char *cpumap = VIR_GET_CPUMAP(cpumaps, maplen, v);

3736
                    if (virProcessInfoGetAffinity(priv->vcpupids[v],
3737
                                                  cpumap, maplen, maxcpu) < 0)
3738
                        goto cleanup;
3739
                }
3740
            } else {
3741
                qemuReportError(VIR_ERR_OPERATION_INVALID,
3742
                                "%s", _("cpu affinity is not available"));
3743
                goto cleanup;
3744 3745 3746
            }
        }
    }
3747
    ret = maxinfo;
3748

3749
cleanup:
3750 3751
    if (vm)
        virDomainObjUnlock(vm);
3752
    return ret;
3753 3754 3755
}


3756 3757 3758
static int
qemudDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
3759 3760
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3761
    virDomainDefPtr def;
3762
    int ret = -1;
3763
    bool active;
3764

3765 3766
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
3767 3768
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

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

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

3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794
    active = virDomainObjIsActive(vm);

    if ((flags & (VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG)) == 0) {
        if (active)
            flags |= VIR_DOMAIN_VCPU_LIVE;
        else
            flags |= VIR_DOMAIN_VCPU_CONFIG;
    }
    if ((flags & VIR_DOMAIN_AFFECT_LIVE) && (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid flag combination: (0x%x)"), flags);
        return -1;
    }

3795
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3796
        if (!active) {
3797 3798 3799 3800 3801 3802
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("domain not active"));
            goto cleanup;
        }
        def = vm->def;
    } else {
3803 3804 3805 3806 3807
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("domain is transient"));
            goto cleanup;
        }
3808
        def = vm->newDef ? vm->newDef : vm->def;
3809 3810
    }

3811
    ret = (flags & VIR_DOMAIN_VCPU_MAXIMUM) ? def->maxvcpus : def->vcpus;
3812

3813
cleanup:
3814 3815
    if (vm)
        virDomainObjUnlock(vm);
3816 3817 3818
    return ret;
}

3819 3820 3821
static int
qemudDomainGetMaxVcpus(virDomainPtr dom)
{
3822
    return qemudDomainGetVcpusFlags(dom, (VIR_DOMAIN_AFFECT_LIVE |
3823 3824 3825
                                          VIR_DOMAIN_VCPU_MAXIMUM));
}

3826 3827 3828 3829 3830 3831 3832 3833 3834
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);

3835 3836
    memset(seclabel, 0, sizeof(*seclabel));

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

3845
    if (!virDomainVirtTypeToString(vm->def->virtType)) {
3846 3847 3848
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unknown virt type in domain definition '%d'"),
                        vm->def->virtType);
3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865
        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 已提交
3866
    if (virDomainObjIsActive(vm)) {
3867 3868
        if (virSecurityManagerGetProcessLabel(driver->securityManager,
                                              vm, seclabel) < 0) {
3869 3870 3871
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("Failed to get security label"));
            goto cleanup;
3872 3873 3874 3875 3876 3877 3878 3879
        }
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
3880
    qemuDriverUnlock(driver);
3881 3882 3883
    return ret;
}

3884 3885
static int qemudNodeGetSecurityModel(virConnectPtr conn,
                                     virSecurityModelPtr secmodel)
3886 3887 3888
{
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
    char *p;
3889
    int ret = 0;
3890

3891
    qemuDriverLock(driver);
3892 3893 3894 3895 3896
    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)
3897
        goto cleanup;
3898

3899 3900
    p = driver->caps->host.secModel.model;
    if (strlen(p) >= VIR_SECURITY_MODEL_BUFLEN-1) {
3901 3902 3903
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security model string exceeds max %d bytes"),
                        VIR_SECURITY_MODEL_BUFLEN-1);
3904 3905
        ret = -1;
        goto cleanup;
3906 3907 3908 3909 3910
    }
    strcpy(secmodel->model, p);

    p = driver->caps->host.secModel.doi;
    if (strlen(p) >= VIR_SECURITY_DOI_BUFLEN-1) {
3911 3912 3913
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security DOI string exceeds max %d bytes"),
                        VIR_SECURITY_DOI_BUFLEN-1);
3914 3915
        ret = -1;
        goto cleanup;
3916 3917
    }
    strcpy(secmodel->doi, p);
3918 3919 3920 3921

cleanup:
    qemuDriverUnlock(driver);
    return ret;
3922 3923
}

E
Eric Blake 已提交
3924
/* Return -1 on most failures after raising error, -2 if edit was specified
3925 3926 3927
 * 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.  */
3928
static int ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4)
3929 3930 3931
qemuDomainSaveImageOpen(struct qemud_driver *driver,
                        const char *path,
                        virDomainDefPtr *ret_def,
3932
                        struct qemud_save_header *ret_header,
3933
                        bool bypass_cache, virFileDirectFdPtr *directFd,
3934 3935
                        const char *xmlin, int state, bool edit,
                        bool unlink_corrupt)
J
Jiri Denemark 已提交
3936 3937
{
    int fd;
3938
    struct qemud_save_header header;
J
Jiri Denemark 已提交
3939 3940
    char *xml = NULL;
    virDomainDefPtr def = NULL;
3941
    int oflags = edit ? O_RDWR : O_RDONLY;
3942

3943
    if (bypass_cache) {
3944
        int directFlag = virFileDirectFdFlag();
3945 3946 3947 3948 3949
        if (directFlag < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("bypass cache unsupported by this system"));
            goto error;
        }
3950
        oflags |= directFlag;
3951
    }
3952

E
Eric Blake 已提交
3953 3954
    if ((fd = qemuOpenFile(driver, path, oflags, NULL, NULL)) < 0)
        goto error;
3955 3956
    if (bypass_cache && (*directFd = virFileDirectFdNew(&fd, path)) == NULL)
        goto error;
3957 3958

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
3959 3960
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read qemu header"));
J
Jiri Denemark 已提交
3961
        goto error;
3962 3963 3964
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
E
Eric Blake 已提交
3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980
        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 已提交
3981
        goto error;
3982 3983 3984
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3985 3986 3987 3988 3989
        /* convert endianess and try again */
        bswap_header(&header);
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3990 3991 3992
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("image version is not supported (%d > %d)"),
                        header.version, QEMUD_SAVE_VERSION);
J
Jiri Denemark 已提交
3993
        goto error;
3994 3995
    }

3996 3997 3998
    if (header.xml_len <= 0) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("invalid XML length: %d"), header.xml_len);
J
Jiri Denemark 已提交
3999
        goto error;
4000 4001
    }

4002 4003
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
        virReportOOMError();
J
Jiri Denemark 已提交
4004
        goto error;
4005 4006 4007
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
4008 4009
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read XML"));
J
Jiri Denemark 已提交
4010
        goto error;
4011 4012
    }

4013 4014
    if (edit && STREQ(xml, xmlin) &&
        (state < 0 || state == header.was_running)) {
4015 4016 4017 4018 4019 4020 4021
        VIR_FREE(xml);
        if (VIR_CLOSE(fd) < 0) {
            virReportSystemError(errno, _("cannot close file: %s"), path);
            goto error;
        }
        return -2;
    }
4022 4023
    if (state >= 0)
        header.was_running = state;
4024

4025
    /* Create a domain from this XML */
4026
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
4027
                                        QEMU_EXPECTED_VIRT_TYPES,
4028
                                        VIR_DOMAIN_XML_INACTIVE)))
J
Jiri Denemark 已提交
4029
        goto error;
4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043
    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;
    }
4044

J
Jiri Denemark 已提交
4045
    VIR_FREE(xml);
4046

J
Jiri Denemark 已提交
4047 4048
    *ret_def = def;
    *ret_header = header;
4049

J
Jiri Denemark 已提交
4050
    return fd;
4051

J
Jiri Denemark 已提交
4052 4053 4054
error:
    virDomainDefFree(def);
    VIR_FREE(xml);
4055
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
4056 4057 4058 4059

    return -1;
}

4060 4061 4062 4063 4064 4065
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,
4066 4067
                           const char *path,
                           bool start_paused)
J
Jiri Denemark 已提交
4068 4069 4070 4071
{
    int ret = -1;
    virDomainEventPtr event;
    int intermediatefd = -1;
4072
    virCommandPtr cmd = NULL;
J
Jiri Denemark 已提交
4073 4074 4075

    if (header->version == 2) {
        const char *prog = qemudSaveCompressionTypeToString(header->compressed);
4076
        if (prog == NULL) {
4077 4078
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("Invalid compressed save format %d"),
J
Jiri Denemark 已提交
4079 4080
                            header->compressed);
            goto out;
4081
        }
4082

J
Jiri Denemark 已提交
4083
        if (header->compressed != QEMUD_SAVE_FORMAT_RAW) {
4084
            cmd = virCommandNewArgList(prog, "-dc", NULL);
4085 4086
            intermediatefd = *fd;
            *fd = -1;
4087 4088 4089 4090 4091

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

            if (virCommandRunAsync(cmd, NULL) < 0) {
4092 4093
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Failed to start decompression binary %s"),
4094
                                prog);
4095
                *fd = intermediatefd;
J
Jiri Denemark 已提交
4096
                goto out;
4097 4098 4099
            }
        }
    }
J
Jiri Denemark 已提交
4100

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

4105
    if (intermediatefd != -1) {
4106
        if (ret < 0) {
4107 4108 4109
            /* if there was an error setting up qemu, the intermediate
             * process will wait forever to write to stdout, so we
             * must manually kill it.
4110 4111
             */
            VIR_FORCE_CLOSE(intermediatefd);
4112
            VIR_FORCE_CLOSE(*fd);
4113 4114
        }

4115 4116
        if (virCommandWait(cmd, NULL) < 0)
            ret = -1;
4117
    }
4118
    VIR_FORCE_CLOSE(intermediatefd);
J
Jiri Denemark 已提交
4119

4120 4121 4122
    if (VIR_CLOSE(*fd) < 0) {
        virReportSystemError(errno, _("cannot close file: %s"), path);
        ret = -1;
4123
    }
J
Jiri Denemark 已提交
4124

4125
    if (ret < 0) {
4126
        virDomainAuditStart(vm, "restored", false);
J
Jiri Denemark 已提交
4127
        goto out;
4128
    }
4129

4130 4131 4132
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
4133
    virDomainAuditStart(vm, "restored", true);
J
Jiri Denemark 已提交
4134 4135 4136
    if (event)
        qemuDomainEventQueue(driver, event);

4137

4138 4139
    /* If it was running before, resume it now unless caller requested pause. */
    if (header->was_running && !start_paused) {
J
Jiri Denemark 已提交
4140
        if (qemuProcessStartCPUs(driver, vm, conn,
4141 4142
                                 VIR_DOMAIN_RUNNING_RESTORED,
                                 QEMU_ASYNC_JOB_NONE) < 0) {
4143
            if (virGetLastError() == NULL)
4144 4145
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("failed to resume domain"));
J
Jiri Denemark 已提交
4146
            goto out;
4147
        }
4148 4149
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
J
Jiri Denemark 已提交
4150
            goto out;
4151
        }
4152 4153 4154 4155 4156 4157 4158 4159
    } 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);
4160
    }
J
Jiri Denemark 已提交
4161

4162
    ret = 0;
4163

J
Jiri Denemark 已提交
4164
out:
4165
    virCommandFree(cmd);
4166 4167
    if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
                                                 vm, path) < 0)
4168 4169
        VIR_WARN("failed to restore save state label on %s", path);

J
Jiri Denemark 已提交
4170 4171 4172
    return ret;
}

4173
static int
4174 4175 4176 4177
qemuDomainRestoreFlags(virConnectPtr conn,
                       const char *path,
                       const char *dxml,
                       unsigned int flags)
4178
{
J
Jiri Denemark 已提交
4179 4180 4181 4182 4183 4184
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    int fd = -1;
    int ret = -1;
    struct qemud_save_header header;
4185
    virFileDirectFdPtr directFd = NULL;
4186
    int state = -1;
J
Jiri Denemark 已提交
4187

4188 4189 4190
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
                  VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
4191

J
Jiri Denemark 已提交
4192 4193
    qemuDriverLock(driver);

4194 4195 4196 4197 4198
    if (flags & VIR_DOMAIN_SAVE_RUNNING)
        state = 1;
    else if (flags & VIR_DOMAIN_SAVE_PAUSED)
        state = 0;

4199 4200
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header,
                                 (flags & VIR_DOMAIN_SAVE_BYPASS_CACHE) != 0,
4201
                                 &directFd, dxml, state, false, false);
J
Jiri Denemark 已提交
4202 4203 4204 4205 4206 4207 4208 4209 4210
    if (fd < 0)
        goto cleanup;

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

    if (!(vm = virDomainAssignDef(driver->caps,
                                  &driver->domains,
                                  def, true))) {
4211
        /* virDomainAssignDef already set the error */
J
Jiri Denemark 已提交
4212 4213 4214 4215
        goto cleanup;
    }
    def = NULL;

4216
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
J
Jiri Denemark 已提交
4217 4218
        goto cleanup;

4219 4220
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path,
                                     false);
4221 4222
    if (virFileDirectFdClose(directFd) < 0)
        VIR_WARN("Failed to close %s", path);
J
Jiri Denemark 已提交
4223

4224
    if (qemuDomainObjEndJob(driver, vm) == 0)
4225
        vm = NULL;
J
Jiri Denemark 已提交
4226
    else if (ret < 0 && !vm->persistent) {
4227
        qemuDomainRemoveInactive(driver, vm);
J
Jiri Denemark 已提交
4228 4229
        vm = NULL;
    }
4230

4231 4232
cleanup:
    virDomainDefFree(def);
4233
    VIR_FORCE_CLOSE(fd);
4234
    virFileDirectFdFree(directFd);
4235 4236 4237
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
4238
    return ret;
D
Daniel P. Berrange 已提交
4239 4240
}

4241 4242 4243 4244 4245 4246 4247
static int
qemuDomainRestore(virConnectPtr conn,
                  const char *path)
{
    return qemuDomainRestoreFlags(conn, path, NULL, 0);
}

4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263
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,
4264
                                 NULL, -1, false, false);
4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288

    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;
4289
    int state = -1;
4290

4291 4292
    virCheckFlags(VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
4293 4294 4295

    qemuDriverLock(driver);

4296 4297 4298 4299 4300
    if (flags & VIR_DOMAIN_SAVE_RUNNING)
        state = 1;
    else if (flags & VIR_DOMAIN_SAVE_PAUSED)
        state = 0;

4301
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header, false, NULL,
4302
                                 dxml, state, true, false);
4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326

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

4327
    if (lseek(fd, 0, SEEK_SET) != 0) {
4328 4329 4330
        virReportSystemError(errno, _("cannot seek in '%s'"), path);
        goto cleanup;
    }
4331 4332
    if (safewrite(fd, &header, sizeof(header)) != sizeof(header) ||
        safewrite(fd, xml, len) != len ||
4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347
        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 已提交
4348 4349
/* Return 0 on success, 1 if incomplete saved image was silently unlinked,
 * and -1 on failure with error raised.  */
4350 4351 4352 4353
static int
qemuDomainObjRestore(virConnectPtr conn,
                     struct qemud_driver *driver,
                     virDomainObjPtr vm,
4354
                     const char *path,
4355
                     bool start_paused,
4356
                     bool bypass_cache)
J
Jiri Denemark 已提交
4357 4358 4359 4360 4361
{
    virDomainDefPtr def = NULL;
    int fd = -1;
    int ret = -1;
    struct qemud_save_header header;
4362
    virFileDirectFdPtr directFd = NULL;
J
Jiri Denemark 已提交
4363

4364
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header,
4365 4366
                                 bypass_cache, &directFd, NULL, -1, false,
                                 true);
E
Eric Blake 已提交
4367 4368 4369
    if (fd < 0) {
        if (fd == -3)
            ret = 1;
J
Jiri Denemark 已提交
4370
        goto cleanup;
E
Eric Blake 已提交
4371
    }
J
Jiri Denemark 已提交
4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389

    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;

4390 4391
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path,
                                     start_paused);
4392 4393
    if (virFileDirectFdClose(directFd) < 0)
        VIR_WARN("Failed to close %s", path);
J
Jiri Denemark 已提交
4394 4395 4396

cleanup:
    virDomainDefFree(def);
4397
    VIR_FORCE_CLOSE(fd);
4398
    virFileDirectFdFree(directFd);
J
Jiri Denemark 已提交
4399 4400 4401
    return ret;
}

D
Daniel P. Berrange 已提交
4402

4403
static char *qemuDomainGetXMLDesc(virDomainPtr dom,
4404 4405
                                  unsigned int flags)
{
4406 4407 4408
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;
4409
    unsigned long balloon;
4410
    int err = 0;
4411

4412
    /* Flags checked by virDomainDefFormat */
4413

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

D
Daniel P. Berrange 已提交
4417
    if (!vm) {
4418 4419
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4420 4421
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4422
        goto cleanup;
D
Daniel P. Berrange 已提交
4423 4424
    }

4425 4426 4427 4428
    /* 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))) {
4429
        qemuDomainObjPrivatePtr priv = vm->privateData;
4430 4431
        /* Don't delay if someone's using the monitor, just use
         * existing most recent data instead */
4432
        if (qemuDomainJobAllowed(priv, QEMU_JOB_QUERY)) {
4433
            if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_QUERY) < 0)
4434 4435
                goto cleanup;

4436 4437 4438 4439 4440 4441
            if (!virDomainObjIsActive(vm)) {
                qemuReportError(VIR_ERR_OPERATION_INVALID,
                                "%s", _("domain is not running"));
                goto endjob;
            }

4442
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
4443
            err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
4444
            qemuDomainObjExitMonitorWithDriver(driver, vm);
4445 4446

endjob:
4447
            if (qemuDomainObjEndJob(driver, vm) == 0) {
4448 4449 4450
                vm = NULL;
                goto cleanup;
            }
4451 4452 4453
            if (err < 0)
                goto cleanup;
            if (err > 0)
4454
                vm->def->mem.cur_balloon = balloon;
4455 4456
            /* err == 0 indicates no balloon support, so ignore it */
        }
4457
    }
4458

4459
    ret = qemuDomainFormatXML(driver, vm, flags);
4460 4461

cleanup:
4462 4463
    if (vm)
        virDomainObjUnlock(vm);
4464
    qemuDriverUnlock(driver);
4465
    return ret;
D
Daniel P. Berrange 已提交
4466 4467 4468
}


4469 4470 4471
static char *qemuDomainXMLFromNative(virConnectPtr conn,
                                     const char *format,
                                     const char *config,
E
Eric Blake 已提交
4472 4473
                                     unsigned int flags)
{
4474
    struct qemud_driver *driver = conn->privateData;
4475 4476 4477
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
4478 4479
    virCheckFlags(0, NULL);

4480
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
4481 4482
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
4483 4484 4485
        goto cleanup;
    }

4486
    qemuDriverLock(driver);
4487 4488
    def = qemuParseCommandLineString(driver->caps, config,
                                     NULL, NULL, NULL);
4489
    qemuDriverUnlock(driver);
4490 4491 4492
    if (!def)
        goto cleanup;

4493 4494 4495 4496 4497 4498
    if (!def->name &&
        !(def->name = strdup("unnamed"))) {
        virReportOOMError();
        goto cleanup;
    }

4499
    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
4500 4501 4502 4503 4504 4505

cleanup:
    virDomainDefFree(def);
    return xml;
}

4506 4507 4508
static char *qemuDomainXMLToNative(virConnectPtr conn,
                                   const char *format,
                                   const char *xmlData,
E
Eric Blake 已提交
4509 4510
                                   unsigned int flags)
{
4511 4512
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
4513
    virDomainChrSourceDef monConfig;
4514
    virBitmapPtr qemuCaps = NULL;
T
tangchen 已提交
4515
    bool monitor_json = false;
E
Eric Blake 已提交
4516
    virCommandPtr cmd = NULL;
4517 4518 4519
    char *ret = NULL;
    int i;

E
Eric Blake 已提交
4520 4521
    virCheckFlags(0, NULL);

4522 4523
    qemuDriverLock(driver);

4524
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
4525 4526
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
4527 4528 4529
        goto cleanup;
    }

M
Matthias Bolte 已提交
4530 4531
    def = virDomainDefParseString(driver->caps, xmlData,
                                  QEMU_EXPECTED_VIRT_TYPES, 0);
4532 4533 4534
    if (!def)
        goto cleanup;

4535 4536
    /* Since we're just exporting args, we can't do bridge/network/direct
     * setups, since libvirt will normally create TAP/macvtap devices
4537 4538 4539 4540 4541
     * 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];
4542
        int bootIndex = net->bootIndex;
4543 4544 4545 4546
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            int actualType = virDomainNetGetActualType(net);
            const char *brname;

4547
            VIR_FREE(net->data.network.name);
4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580
            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;
                net->data.ethernet.dev = brnamecopy;
                net->data.ethernet.script = NULL;
                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;
                net->data.ethernet.dev = NULL;
                net->data.ethernet.script = 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);
4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599

            memset(net, 0, sizeof *net);

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
            net->data.ethernet.dev = NULL;
            net->data.ethernet.script = NULL;
            net->data.ethernet.ipaddr = NULL;
        } else if (net->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
            char *brname = net->data.bridge.brname;
            char *script = net->data.bridge.script;
            char *ipaddr = net->data.bridge.ipaddr;

            memset(net, 0, sizeof *net);

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
            net->data.ethernet.dev = brname;
            net->data.ethernet.script = script;
            net->data.ethernet.ipaddr = ipaddr;
        }
4600
        net->bootIndex = bootIndex;
4601 4602 4603 4604
    }
    for (i = 0 ; i < def->ngraphics ; i++) {
        if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
            def->graphics[i]->data.vnc.autoport)
4605
            def->graphics[i]->data.vnc.port = QEMU_VNC_PORT_MIN;
4606 4607
    }

4608
    if (qemuCapsExtractVersionInfo(def->emulator, def->os.arch,
4609
                                   NULL,
4610
                                   &qemuCaps) < 0)
4611 4612
        goto cleanup;

T
tangchen 已提交
4613 4614
    monitor_json = qemuCapsGet(qemuCaps, QEMU_CAPS_MONITOR_JSON);

4615
    if (qemuProcessPrepareMonitorChr(driver, &monConfig, def->name) < 0)
4616
        goto cleanup;
4617

4618 4619 4620
    if (qemuAssignDeviceAliases(def, qemuCaps) < 0)
        goto cleanup;

4621
    if (!(cmd = qemuBuildCommandLine(conn, driver, def,
T
tangchen 已提交
4622
                                     &monConfig, monitor_json, qemuCaps,
4623
                                     NULL, -1, NULL, VIR_NETDEV_VPORT_PROFILE_OP_NO_OP)))
4624 4625
        goto cleanup;

E
Eric Blake 已提交
4626
    ret = virCommandToString(cmd);
4627 4628

cleanup:
4629
    qemuDriverUnlock(driver);
4630

4631
    qemuCapsFree(qemuCaps);
E
Eric Blake 已提交
4632
    virCommandFree(cmd);
4633 4634 4635 4636 4637
    virDomainDefFree(def);
    return ret;
}


4638
static int qemudListDefinedDomains(virConnectPtr conn,
4639
                            char **const names, int nnames) {
4640
    struct qemud_driver *driver = conn->privateData;
4641
    int n;
4642

4643
    qemuDriverLock(driver);
4644
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
4645
    qemuDriverUnlock(driver);
4646
    return n;
D
Daniel P. Berrange 已提交
4647 4648
}

4649
static int qemudNumDefinedDomains(virConnectPtr conn) {
4650
    struct qemud_driver *driver = conn->privateData;
4651
    int n;
4652

4653
    qemuDriverLock(driver);
4654
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
4655
    qemuDriverUnlock(driver);
4656

4657
    return n;
D
Daniel P. Berrange 已提交
4658 4659 4660
}


4661 4662 4663 4664
static int
qemuDomainObjStart(virConnectPtr conn,
                   struct qemud_driver *driver,
                   virDomainObjPtr vm,
4665
                   unsigned int flags)
J
Jiri Denemark 已提交
4666 4667 4668
{
    int ret = -1;
    char *managed_save;
4669 4670 4671 4672
    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 已提交
4673 4674 4675

    /*
     * If there is a managed saved state restore it instead of starting
4676
     * from scratch. The old state is removed once the restoring succeeded.
J
Jiri Denemark 已提交
4677 4678
     */
    managed_save = qemuDomainManagedSavePath(driver, vm);
4679 4680 4681 4682

    if (!managed_save)
        goto cleanup;

E
Eric Blake 已提交
4683
    if (virFileExists(managed_save)) {
4684 4685 4686 4687 4688 4689 4690 4691 4692
        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,
4693
                                       start_paused, bypass_cache);
J
Jiri Denemark 已提交
4694

E
Eric Blake 已提交
4695
            if (ret == 0 && unlink(managed_save) < 0)
4696
                VIR_WARN("Failed to remove the managed state %s", managed_save);
E
Eric Blake 已提交
4697 4698 4699 4700
            if (ret > 0)
                VIR_WARN("Ignoring incomplete managed state %s", managed_save);
            else
                goto cleanup;
4701
        }
J
Jiri Denemark 已提交
4702 4703
    }

4704
    ret = qemuProcessStart(conn, driver, vm, NULL, start_paused,
4705
                           autodestroy, -1, NULL, NULL, VIR_NETDEV_VPORT_PROFILE_OP_CREATE);
4706
    virDomainAuditStart(vm, "booted", ret >= 0);
4707
    if (ret >= 0) {
J
Jiri Denemark 已提交
4708 4709 4710 4711
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
4712
        if (event) {
J
Jiri Denemark 已提交
4713
            qemuDomainEventQueue(driver, event);
4714 4715 4716 4717 4718 4719 4720 4721
            if (start_paused) {
                event = virDomainEventNewFromObj(vm,
                                                 VIR_DOMAIN_EVENT_SUSPENDED,
                                                 VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
                if (event)
                    qemuDomainEventQueue(driver, event);
            }
        }
J
Jiri Denemark 已提交
4722 4723 4724 4725 4726 4727 4728
    }

cleanup:
    VIR_FREE(managed_save);
    return ret;
}

4729
static int
4730
qemuDomainStartWithFlags(virDomainPtr dom, unsigned int flags)
4731
{
4732 4733 4734
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
4735

4736
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
4737
                  VIR_DOMAIN_START_AUTODESTROY |
4738 4739
                  VIR_DOMAIN_START_BYPASS_CACHE |
                  VIR_DOMAIN_START_FORCE_BOOT, -1);
4740

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

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

4752
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
4753 4754 4755
        goto cleanup;

    if (virDomainObjIsActive(vm)) {
4756 4757
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is already running"));
4758 4759 4760
        goto endjob;
    }

4761
    if (qemuDomainObjStart(dom->conn, driver, vm, flags) < 0)
4762 4763 4764
        goto endjob;

    ret = 0;
4765

4766
endjob:
4767
    if (qemuDomainObjEndJob(driver, vm) == 0)
4768
        vm = NULL;
4769

4770
cleanup:
4771 4772
    if (vm)
        virDomainObjUnlock(vm);
4773
    qemuDriverUnlock(driver);
4774
    return ret;
D
Daniel P. Berrange 已提交
4775 4776
}

4777
static int
4778
qemuDomainStart(virDomainPtr dom)
4779
{
4780
    return qemuDomainStartWithFlags(dom, 0);
4781 4782
}

4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797
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;

4798
        if (def->os.machine && STRNEQ(def->os.machine, machine->name))
4799 4800 4801
            continue;

        if (!(*canonical = strdup(machine->canonical))) {
4802
            virReportOOMError();
4803 4804 4805 4806 4807 4808 4809 4810 4811
            return -1;
        }

        break;
    }

    return 0;
}

4812 4813 4814 4815 4816 4817
static int
qemudCanonicalizeMachineDirect(virDomainDefPtr def, char **canonical)
{
    virCapsGuestMachinePtr *machines = NULL;
    int i, nmachines = 0;

4818
    if (qemuCapsProbeMachineTypes(def->emulator, &machines, &nmachines) < 0)
4819 4820 4821 4822 4823 4824
        return -1;

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

4825
        if (def->os.machine && STRNEQ(def->os.machine, machines[i]->name))
4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837
            continue;

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

    virCapabilitiesFreeMachines(machines, nmachines);

    return 0;
}

4838 4839
int
qemudCanonicalizeMachine(struct qemud_driver *driver, virDomainDefPtr def)
4840 4841 4842 4843 4844 4845
{
    char *canonical = NULL;
    int i;

    for (i = 0; i < driver->caps->nguests; i++) {
        virCapsGuestPtr guest = driver->caps->guests[i];
4846
        virCapsGuestDomainInfoPtr info;
4847 4848 4849
        int j;

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

4852 4853 4854 4855 4856 4857 4858 4859 4860
            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;
4861 4862
        }

4863 4864 4865 4866
        info = &guest->arch.defaultInfo;

        if (info->emulator && STREQ(info->emulator, def->emulator)) {
            if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
4867 4868 4869 4870
                return -1;
            goto out;
        }
    }
4871 4872 4873 4874

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

4875 4876 4877 4878 4879 4880 4881
out:
    if (canonical) {
        VIR_FREE(def->os.machine);
        def->os.machine = canonical;
    }
    return 0;
}
D
Daniel P. Berrange 已提交
4882

4883
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
4884
    struct qemud_driver *driver = conn->privateData;
4885
    virDomainDefPtr def;
4886
    virDomainObjPtr vm = NULL;
4887
    virDomainPtr dom = NULL;
4888
    virDomainEventPtr event = NULL;
4889
    int dupVM;
4890

4891
    qemuDriverLock(driver);
4892
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
4893
                                        QEMU_EXPECTED_VIRT_TYPES,
4894
                                        VIR_DOMAIN_XML_INACTIVE)))
4895
        goto cleanup;
4896

4897
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
4898 4899
        goto cleanup;

4900 4901
    if ((dupVM = virDomainObjIsDuplicate(&driver->domains, def, 0)) < 0)
        goto cleanup;
4902

4903
    if (qemudCanonicalizeMachine(driver, def) < 0)
4904 4905
        goto cleanup;

4906
    if (qemuDomainAssignPCIAddresses(def) < 0)
4907 4908
        goto cleanup;

4909
    if (!(vm = virDomainAssignDef(driver->caps,
4910
                                  &driver->domains,
4911
                                  def, false))) {
4912
        goto cleanup;
4913
    }
4914
    def = NULL;
4915
    vm->persistent = 1;
4916

4917
    if (virDomainSaveConfig(driver->configDir,
4918
                            vm->newDef ? vm->newDef : vm->def) < 0) {
4919
        VIR_INFO("Defining domain '%s'", vm->def->name);
4920
        qemuDomainRemoveInactive(driver, vm);
4921
        vm = NULL;
4922
        goto cleanup;
4923 4924
    }

4925 4926
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
4927
                                     !dupVM ?
4928 4929
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
4930

4931
    VIR_INFO("Creating domain '%s'", vm->def->name);
4932
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
4933
    if (dom) dom->id = vm->def->id;
4934 4935

cleanup:
4936
    virDomainDefFree(def);
4937 4938
    if (vm)
        virDomainObjUnlock(vm);
4939 4940
    if (event)
        qemuDomainEventQueue(driver, event);
4941
    qemuDriverUnlock(driver);
4942
    return dom;
D
Daniel P. Berrange 已提交
4943 4944
}

4945 4946
static int
qemuDomainUndefineFlags(virDomainPtr dom,
4947
                        unsigned int flags)
4948
{
4949 4950
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4951
    virDomainEventPtr event = NULL;
4952
    char *name = NULL;
4953
    int ret = -1;
4954
    int nsnapshots;
D
Daniel P. Berrange 已提交
4955

4956 4957
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE |
                  VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA, -1);
4958

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

D
Daniel P. Berrange 已提交
4962
    if (!vm) {
4963 4964
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4965 4966
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4967
        goto cleanup;
D
Daniel P. Berrange 已提交
4968 4969
    }

4970 4971 4972 4973 4974 4975
    if (!vm->persistent) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot undefine transient domain"));
        goto cleanup;
    }

4976 4977
    if (!virDomainObjIsActive(vm) &&
        (nsnapshots = virDomainSnapshotObjListNum(&vm->snapshots, 0))) {
4978
        if (!(flags & VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA)) {
4979 4980 4981 4982 4983 4984
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            _("cannot delete inactive domain with %d "
                              "snapshots"),
                            nsnapshots);
            goto cleanup;
        }
4985
        if (qemuDomainSnapshotDiscardAllMetadata(driver, vm) < 0)
4986
            goto cleanup;
4987 4988
    }

4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008
    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;
        }
    }

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

5012 5013 5014
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
5015

5016
    VIR_INFO("Undefining domain '%s'", vm->def->name);
5017 5018 5019 5020 5021 5022 5023 5024

    /* 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 {
5025
        qemuDomainRemoveInactive(driver, vm);
5026 5027 5028
        vm = NULL;
    }

5029
    ret = 0;
D
Daniel P. Berrange 已提交
5030

5031
cleanup:
5032
    VIR_FREE(name);
5033 5034
    if (vm)
        virDomainObjUnlock(vm);
5035 5036
    if (event)
        qemuDomainEventQueue(driver, event);
5037
    qemuDriverUnlock(driver);
5038
    return ret;
D
Daniel P. Berrange 已提交
5039 5040
}

5041 5042 5043 5044 5045 5046
static int
qemudDomainUndefine(virDomainPtr dom)
{
    return qemuDomainUndefineFlags(dom, 0);
}

5047
static int
5048 5049
qemuDomainAttachDeviceDiskLive(virConnectPtr conn,
                               struct qemud_driver *driver,
5050
                               virDomainObjPtr vm,
5051
                               virDomainDeviceDefPtr dev)
5052 5053 5054 5055
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
    int ret = -1;
5056

5057
    if (disk->driverName != NULL && !STREQ(disk->driverName, "qemu")) {
5058
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076
                        _("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:
5077
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, false);
5078 5079 5080
        break;
    case VIR_DOMAIN_DISK_DEVICE_DISK:
        if (disk->bus == VIR_DOMAIN_DISK_BUS_USB)
5081
            ret = qemuDomainAttachUsbMassstorageDevice(conn, driver, vm,
5082
                                                       disk);
5083
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
5084
            ret = qemuDomainAttachPciDiskDevice(conn, driver, vm, disk);
5085
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
5086
            ret = qemuDomainAttachSCSIDisk(conn, driver, vm, disk);
5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112
        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,
5113
                                     virDomainDeviceDefPtr dev)
5114 5115 5116 5117 5118 5119
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
5120
        ret = qemuDomainAttachPciControllerDevice(driver, vm, cont);
5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133
        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,
5134
                           virDomainPtr dom)
5135 5136 5137 5138 5139 5140
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
5141
        qemuDomainObjCheckDiskTaint(driver, vm, dev->data.disk, -1);
5142
        ret = qemuDomainAttachDeviceDiskLive(dom->conn, driver, vm, dev);
5143 5144 5145 5146 5147
        if (!ret)
            dev->data.disk = NULL;
        break;

    case VIR_DOMAIN_DEVICE_CONTROLLER:
5148
        ret = qemuDomainAttachDeviceControllerLive(driver, vm, dev);
5149 5150 5151 5152
        if (!ret)
            dev->data.controller = NULL;
        break;

5153 5154 5155 5156 5157 5158 5159
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainAttachLease(driver, vm,
                                    dev->data.lease);
        if (ret == 0)
            dev->data.lease = NULL;
        break;

5160
    case VIR_DOMAIN_DEVICE_NET:
5161
        qemuDomainObjCheckNetTaint(driver, vm, dev->data.net, -1);
5162
        ret = qemuDomainAttachNetDevice(dom->conn, driver, vm,
5163
                                        dev->data.net);
5164 5165 5166 5167 5168 5169
        if (!ret)
            dev->data.net = NULL;
        break;

    case VIR_DOMAIN_DEVICE_HOSTDEV:
        ret = qemuDomainAttachHostDevice(driver, vm,
5170
                                         dev->data.hostdev);
5171 5172 5173 5174
        if (!ret)
            dev->data.hostdev = NULL;
        break;

5175 5176 5177 5178 5179 5180 5181
    case VIR_DOMAIN_DEVICE_REDIRDEV:
        ret = qemuDomainAttachRedirdevDevice(driver, vm,
                                             dev->data.redirdev);
        if (!ret)
            dev->data.redirdev = NULL;
        break;

5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194
    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,
5195
                               virDomainDeviceDefPtr dev)
5196 5197 5198 5199 5200 5201 5202
{
    virDomainDiskDefPtr disk = dev->data.disk;
    int ret = -1;

    switch (disk->device) {
    case VIR_DOMAIN_DISK_DEVICE_DISK:
        if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
5203
            ret = qemuDomainDetachPciDiskDevice(driver, vm, dev);
5204
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
5205
            ret =  qemuDomainDetachDiskDevice(driver, vm, dev);
5206
        else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB)
5207
            ret = qemuDomainDetachDiskDevice(driver, vm, dev);
5208 5209 5210 5211 5212 5213
        else
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                            _("This type of disk cannot be hot unplugged"));
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5214 5215
                        _("disk device type '%s' cannot be detached"),
                        virDomainDiskDeviceTypeToString(disk->type));
5216 5217 5218 5219 5220 5221 5222 5223
        break;
    }
    return ret;
}

static int
qemuDomainDetachDeviceControllerLive(struct qemud_driver *driver,
                                     virDomainObjPtr vm,
5224
                                     virDomainDeviceDefPtr dev)
5225 5226 5227 5228 5229 5230
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
5231
        ret = qemuDomainDetachPciControllerDevice(driver, vm, dev);
5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243
        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,
5244
                           virDomainPtr dom)
5245 5246 5247 5248 5249 5250
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
5251
        ret = qemuDomainDetachDeviceDiskLive(driver, vm, dev);
5252 5253
        break;
    case VIR_DOMAIN_DEVICE_CONTROLLER:
5254
        ret = qemuDomainDetachDeviceControllerLive(driver, vm, dev);
5255
        break;
5256 5257 5258
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainDetachLease(driver, vm, dev->data.lease);
        break;
5259
    case VIR_DOMAIN_DEVICE_NET:
5260
        ret = qemuDomainDetachNetDevice(driver, vm, dev);
5261 5262
        break;
    case VIR_DOMAIN_DEVICE_HOSTDEV:
5263
        ret = qemuDomainDetachHostDevice(driver, vm, dev);
5264 5265 5266 5267 5268 5269 5270 5271 5272 5273
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        "%s", _("This type of device cannot be hot unplugged"));
        break;
    }

    return ret;
}

5274 5275 5276 5277 5278 5279 5280 5281
static int
qemuDomainChangeDiskMediaLive(virDomainObjPtr vm,
                              virDomainDeviceDefPtr dev,
                              struct qemud_driver *driver,
                              bool force)
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
5282
    int ret = -1;
5283 5284 5285

    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup,
5286
                               vm->def->name, &cgroup, 0) != 0) {
5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298
            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:
5299
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, force);
5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331
        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:
5332
        ret = qemuDomainChangeDiskMediaLive(vm, dev, driver, force);
5333 5334 5335 5336
        break;
    case VIR_DOMAIN_DEVICE_GRAPHICS:
        ret = qemuDomainChangeGraphics(driver, vm, dev->data.graphics);
        break;
5337 5338 5339
    case VIR_DOMAIN_DEVICE_NET:
        ret = qemuDomainChangeNet(driver, vm, dom, dev->data.net);
        break;
5340 5341 5342 5343 5344 5345 5346 5347 5348 5349
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("device type '%s' cannot be updated"),
                        virDomainDeviceTypeToString(dev->type));
        break;
    }

    return ret;
}

5350
static int
5351
qemuDomainAttachDeviceConfig(virDomainDefPtr vmdef,
5352 5353
                             virDomainDeviceDefPtr dev)
{
5354
    virDomainDiskDefPtr disk;
5355
    virDomainNetDefPtr net;
5356
    virDomainLeaseDefPtr lease;
5357

5358
    switch (dev->type) {
5359 5360
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
5361
        if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378
            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;
        if (qemuDomainAssignPCIAddresses(vmdef) < 0)
            return -1;
        break;

5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395
    case VIR_DOMAIN_DEVICE_NET:
        net = dev->data.net;
        if (virDomainNetIndexByMac(vmdef, net->mac) >= 0) {
            char macbuf[VIR_MAC_STRING_BUFLEN];
            virFormatMacAddr(net->mac, macbuf);
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("mac %s already exists"), macbuf);
            return -1;
        }
        if (virDomainNetInsert(vmdef, net)) {
            virReportOOMError();
            return -1;
        }
        dev->data.net = NULL;
        if (qemuDomainAssignPCIAddresses(vmdef) < 0)
            return -1;
        break;
5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411

    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;

5412 5413 5414 5415 5416 5417 5418 5419 5420 5421
    default:
         qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                         _("persistent attach of device is not supported"));
         return -1;
    }
    return 0;
}


static int
5422
qemuDomainDetachDeviceConfig(virDomainDefPtr vmdef,
5423 5424
                             virDomainDeviceDefPtr dev)
{
5425
    virDomainDiskDefPtr disk;
5426
    virDomainNetDefPtr net;
5427
    virDomainLeaseDefPtr lease;
5428

5429
    switch (dev->type) {
5430 5431 5432 5433 5434 5435 5436 5437
    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;
5438

5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449
    case VIR_DOMAIN_DEVICE_NET:
        net = dev->data.net;
        if (virDomainNetRemoveByMac(vmdef, net->mac)) {
            char macbuf[VIR_MAC_STRING_BUFLEN];

            virFormatMacAddr(net->mac, macbuf);
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("no nic of mac %s"), macbuf);
            return -1;
        }
        break;
5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460

    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;

5461 5462 5463 5464 5465 5466 5467 5468 5469
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("persistent detach of device is not supported"));
        return -1;
    }
    return 0;
}

static int
5470
qemuDomainUpdateDeviceConfig(virDomainDefPtr vmdef,
5471 5472
                             virDomainDeviceDefPtr dev)
{
5473
    virDomainDiskDefPtr orig, disk;
5474
    virDomainNetDefPtr net;
5475 5476
    int pos;

5477
    switch (dev->type) {
5478 5479
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
5480
        pos = virDomainDiskIndexByName(vmdef, disk->dst, false);
5481 5482
        if (pos < 0) {
            qemuReportError(VIR_ERR_INVALID_ARG,
5483
                            _("target %s doesn't exist."), disk->dst);
5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512
            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;
5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532

    case VIR_DOMAIN_DEVICE_NET:
        net = dev->data.net;
        if ((pos = virDomainNetIndexByMac(vmdef, net->mac)) < 0) {
            char macbuf[VIR_MAC_STRING_BUFLEN];
            virFormatMacAddr(net->mac, macbuf);
            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;

        if (qemuDomainAssignPCIAddresses(vmdef) < 0)
            return -1;
        break;

5533 5534 5535 5536 5537 5538 5539 5540
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                         _("persistent update of device is not supported"));
        return -1;
    }
    return 0;
}

5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551
/* 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)
5552
{
5553
    struct qemud_driver *driver = dom->conn->privateData;
5554
    virDomainObjPtr vm = NULL;
5555
    virDomainDefPtr vmdef = NULL;
5556
    virDomainDeviceDefPtr dev = NULL;
5557
    bool force = (flags & VIR_DOMAIN_DEVICE_MODIFY_FORCE) != 0;
5558
    int ret = -1;
5559
    unsigned int affect;
5560

5561 5562
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
5563 5564 5565
                  (action == QEMU_DEVICE_UPDATE ?
                   VIR_DOMAIN_DEVICE_MODIFY_FORCE : 0), -1);

5566 5567
    affect = flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG);

5568 5569 5570 5571 5572 5573 5574
    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);
5575 5576 5577
        goto cleanup;
    }

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

5581
    if (virDomainObjIsActive(vm)) {
5582
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
5583
            flags |= VIR_DOMAIN_AFFECT_LIVE;
5584
    } else {
5585
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
5586
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
5587
        /* check consistency between flags and the vm state */
5588
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5589 5590 5591 5592 5593 5594
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s",
                            _("cannot do live update a device on "
                              "inactive domain"));
            goto endjob;
        }
5595
    }
5596

5597
    if ((flags & VIR_DOMAIN_AFFECT_CONFIG) && !vm->persistent) {
5598 5599 5600 5601
         qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("cannot modify device on transient domain"));
         goto endjob;
    }
5602

5603
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5604 5605 5606 5607 5608
        dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                      VIR_DOMAIN_XML_INACTIVE);
        if (dev == NULL)
            goto endjob;

5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627
        /* 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;
        }
5628

5629 5630 5631 5632 5633
        if (ret == -1)
            goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5634 5635 5636 5637
        /* 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);
5638 5639
        if (dev == NULL) {
            ret = -1;
5640
            goto endjob;
5641
        }
5642

5643 5644
        switch (action) {
        case QEMU_DEVICE_ATTACH:
5645
            ret = qemuDomainAttachDeviceLive(vm, dev, dom);
5646 5647
            break;
        case QEMU_DEVICE_DETACH:
5648
            ret = qemuDomainDetachDeviceLive(vm, dev, dom);
5649 5650
            break;
        case QEMU_DEVICE_UPDATE:
5651
            ret = qemuDomainUpdateDeviceLive(vm, dev, dom, force);
5652 5653 5654 5655
            break;
        default:
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("unknown domain modify action %d"), action);
5656
            ret = -1;
5657 5658
            break;
        }
5659 5660 5661

        if (ret == -1)
            goto endjob;
5662 5663
        /*
         * update domain status forcibly because the domain status may be
5664 5665
         * changed even if we failed to attach the device. For example,
         * a new controller may be created.
5666
         */
5667
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
5668
            ret = -1;
5669 5670
            goto endjob;
        }
5671
    }
5672

5673
    /* Finally, if no error until here, we can save config. */
5674
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5675 5676 5677 5678 5679 5680
        ret = virDomainSaveConfig(driver->configDir, vmdef);
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false);
            vmdef = NULL;
        }
    }
5681 5682

endjob:
5683
    if (qemuDomainObjEndJob(driver, vm) == 0)
5684 5685 5686
        vm = NULL;

cleanup:
5687
    virDomainDefFree(vmdef);
5688 5689 5690 5691
    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
5692 5693 5694
    return ret;
}

5695 5696 5697 5698 5699 5700
static int qemuDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_ATTACH);
}

5701 5702 5703
static int qemuDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainAttachDeviceFlags(dom, xml,
5704
                                       VIR_DOMAIN_AFFECT_LIVE);
5705
}
5706

5707

5708 5709 5710 5711
static int qemuDomainUpdateDeviceFlags(virDomainPtr dom,
                                       const char *xml,
                                       unsigned int flags)
{
5712
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_UPDATE);
5713 5714
}

5715 5716 5717
static int qemuDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
5718
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_DETACH);
5719 5720
}

5721 5722 5723
static int qemuDomainDetachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainDetachDeviceFlags(dom, xml,
5724
                                       VIR_DOMAIN_AFFECT_LIVE);
5725 5726
}

5727
static int qemudDomainGetAutostart(virDomainPtr dom,
5728
                                   int *autostart) {
5729 5730 5731
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
5732

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

5737
    if (!vm) {
5738 5739
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5740 5741
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5742
        goto cleanup;
5743 5744 5745
    }

    *autostart = vm->autostart;
5746
    ret = 0;
5747

5748
cleanup:
5749 5750
    if (vm)
        virDomainObjUnlock(vm);
5751
    return ret;
5752 5753
}

5754
static int qemudDomainSetAutostart(virDomainPtr dom,
5755
                                   int autostart) {
5756 5757
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
5758 5759
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
5760

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

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

5772
    if (!vm->persistent) {
5773
        qemuReportError(VIR_ERR_OPERATION_INVALID,
5774
                        "%s", _("cannot set autostart for transient domain"));
5775
        goto cleanup;
5776 5777
    }

5778 5779
    autostart = (autostart != 0);

5780
    if (vm->autostart != autostart) {
5781
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
5782
            goto cleanup;
5783
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
5784
            goto cleanup;
5785

5786
        if (autostart) {
5787 5788
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
5789 5790
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
5791 5792
                goto cleanup;
            }
5793

5794
            if (symlink(configFile, autostartLink) < 0) {
5795
                virReportSystemError(errno,
5796 5797
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
5798 5799 5800 5801
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
5802
                virReportSystemError(errno,
5803 5804
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
5805 5806
                goto cleanup;
            }
5807 5808
        }

5809
        vm->autostart = autostart;
5810
    }
5811
    ret = 0;
5812

5813 5814 5815
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
5816 5817
    if (vm)
        virDomainObjUnlock(vm);
5818
    qemuDriverUnlock(driver);
5819
    return ret;
5820 5821
}

5822

5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855
/*
 * 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;
}


5856 5857 5858 5859
static char *qemuGetSchedulerType(virDomainPtr dom,
                                  int *nparams)
{
    struct qemud_driver *driver = dom->conn->privateData;
5860
    char *ret = NULL;
5861
    int rc;
5862

5863
    qemuDriverLock(driver);
5864
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
5865 5866
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup CPU controller is not mounted"));
5867
        goto cleanup;
5868 5869
    }

5870 5871 5872 5873 5874 5875 5876 5877 5878
    if (nparams) {
        rc = qemuGetCpuBWStatus(driver->cgroup);
        if (rc < 0)
            goto cleanup;
        else if (rc == 0)
            *nparams = 1;
        else
            *nparams = 3;
    }
5879 5880 5881

    ret = strdup("posix");
    if (!ret)
5882
        virReportOOMError();
5883 5884 5885

cleanup:
    qemuDriverUnlock(driver);
5886 5887 5888
    return ret;
}

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 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970
/* 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
parseBlkioWeightDeviceStr(char *deviceWeightStr,
                          virBlkioDeviceWeightPtr *dw, int *size)
{
    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;
}

5971
static int qemuDomainSetBlkioParameters(virDomainPtr dom,
5972
                                         virTypedParameterPtr params,
5973 5974 5975 5976 5977 5978 5979
                                         int nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5980
    virDomainDefPtr persistentDef = NULL;
5981
    int ret = -1;
5982
    bool isActive;
5983

5984 5985
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5986 5987 5988 5989 5990 5991 5992 5993 5994 5995
    qemuDriverLock(driver);

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

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

5996 5997 5998 5999 6000 6001 6002
    isActive = virDomainObjIsActive(vm);

    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
        if (isActive)
            flags = VIR_DOMAIN_AFFECT_LIVE;
        else
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6003 6004
    }

6005 6006 6007 6008 6009 6010 6011 6012
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }

        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
6013
            qemuReportError(VIR_ERR_OPERATION_INVALID, _("blkio cgroup isn't mounted"));
6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031
            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_CONFIG) {
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot change persistent config of a transient domain"));
            goto cleanup;
        }
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
            goto cleanup;
6032 6033 6034
    }

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

            if (STREQ(param->field, VIR_DOMAIN_BLKIO_WEIGHT)) {
                if (param->type != VIR_TYPED_PARAM_UINT) {
                    qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                    _("invalid type for blkio weight tunable, expected a 'unsigned int'"));
                    ret = -1;
                    continue;
                }

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

6055 6056 6057 6058 6059 6060
                rc = virCgroupSetBlkioWeight(group, params[i].value.ui);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set blkio weight tunable"));
                    ret = -1;
                }
6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098
            } else if (STREQ(param->field, VIR_DOMAIN_BLKIO_DEVICE_WEIGHT)) {
                int ndevices;
                virBlkioDeviceWeightPtr devices = NULL;
                if (param->type != VIR_TYPED_PARAM_STRING) {
                    qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                    _("invalid type for device_weight tunable, "
                                      "expected a 'char *'"));
                    ret = -1;
                    continue;
                }

                if (parseBlkioWeightDeviceStr(params[i].value.s,
                                              &devices,
                                              &ndevices) < 0) {
                    ret = -1;
                    continue;
                }
                for (i = 0; i < ndevices; i++) {
                    rc = virCgroupSetBlkioDeviceWeight(group,
                                                       devices[i].path,
                                                       devices[i].weight);
                    if (rc < 0) {
                        virReportSystemError(-rc,
                                             _("Unable to set io device weight "
                                               "for path %s"),
                                             devices[i].path);
                        break;
                    }
                }
                if (i != ndevices) {
                    ret = -1;
                    continue;
                }
                virBlkioDeviceWeightArrayClear(vm->def->blkio.devices,
                                               vm->def->blkio.ndevices);
                VIR_FREE(vm->def->blkio.devices);
                vm->def->blkio.devices = devices;
                vm->def->blkio.ndevices = ndevices;
6099 6100 6101
            } else {
                qemuReportError(VIR_ERR_INVALID_ARG,
                                _("Parameter `%s' not supported"), param->field);
6102 6103
                ret = -1;
            }
6104
        }
E
Eric Blake 已提交
6105 6106 6107 6108
    }
    if (ret < 0)
        goto cleanup;
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
6109 6110 6111
        /* Clang can't see that if we get here, persistentDef was set.  */
        sa_assert(persistentDef);

6112 6113 6114 6115 6116 6117 6118 6119 6120 6121
        for (i = 0; i < nparams; i++) {
            virTypedParameterPtr param = &params[i];

            if (STREQ(param->field, VIR_DOMAIN_BLKIO_WEIGHT)) {
                if (param->type != VIR_TYPED_PARAM_UINT) {
                    qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                    _("invalid type for blkio weight tunable, expected a 'unsigned int'"));
                    ret = -1;
                    continue;
                }
6122

6123 6124 6125 6126 6127 6128 6129 6130
                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;
6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151
            } else if (STREQ(param->field, VIR_DOMAIN_BLKIO_DEVICE_WEIGHT)) {
                virBlkioDeviceWeightPtr devices = NULL;
                int ndevices;
                if (param->type != VIR_TYPED_PARAM_STRING) {
                    qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                    _("invalid type for device_weight tunable, "
                                      "expected a 'char *'"));
                    ret = -1;
                    continue;
                }
                if (parseBlkioWeightDeviceStr(params[i].value.s,
                                              &devices,
                                              &ndevices) < 0) {
                    ret = -1;
                    continue;
                }
                virBlkioDeviceWeightArrayClear(persistentDef->blkio.devices,
                                               persistentDef->blkio.ndevices);
                VIR_FREE(persistentDef->blkio.devices);
                persistentDef->blkio.devices = devices;
                persistentDef->blkio.ndevices = ndevices;
6152 6153
            } else {
                qemuReportError(VIR_ERR_INVALID_ARG,
6154 6155
                                _("Parameter `%s' not supported"),
                                param->field);
6156 6157 6158
                ret = -1;
            }
        }
A
Alex Jia 已提交
6159 6160 6161

        if (virDomainSaveConfig(driver->configDir, persistentDef) < 0)
            ret = -1;
6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172
    }

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

static int qemuDomainGetBlkioParameters(virDomainPtr dom,
6173
                                         virTypedParameterPtr params,
6174 6175 6176 6177
                                         int *nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
6178
    int i, j;
6179 6180
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6181
    virDomainDefPtr persistentDef = NULL;
6182 6183 6184
    unsigned int val;
    int ret = -1;
    int rc;
6185
    bool isActive;
6186

6187
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
6188 6189
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);
6190 6191
    qemuDriverLock(driver);

6192 6193 6194
    /* 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.  */
6195 6196
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211
    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;
    }

6212 6213 6214 6215 6216 6217 6218
    isActive = virDomainObjIsActive(vm);

    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
        if (isActive)
            flags = VIR_DOMAIN_AFFECT_LIVE;
        else
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6219 6220
    }

6221 6222 6223 6224 6225 6226
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }
6227

6228
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
6229
            qemuReportError(VIR_ERR_OPERATION_INVALID, _("blkio cgroup isn't mounted"));
6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250
            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_CONFIG) {
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot change persistent config of a transient domain"));
            goto cleanup;
        }
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
            goto cleanup;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6251
        for (i = 0; i < *nparams && i < QEMU_NB_BLKIO_PARAM; i++) {
6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266
            virTypedParameterPtr param = &params[i];
            val = 0;
            param->value.ui = 0;
            param->type = VIR_TYPED_PARAM_UINT;

            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;
                }
                if (virStrcpyStatic(param->field, VIR_DOMAIN_BLKIO_WEIGHT) == NULL) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
6267 6268
                                    _("Field name '%s' too long"),
                                    VIR_DOMAIN_BLKIO_WEIGHT);
6269 6270 6271 6272
                    goto cleanup;
                }
                param->value.ui = val;
                break;
6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309
            case 1: /* blkiotune.device_weight */
                if (vm->def->blkio.ndevices > 0) {
                    virBuffer buf = VIR_BUFFER_INITIALIZER;
                    bool comma = false;
                    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);
                }
                if (!param->value.s) {
                    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;
6310 6311 6312 6313

            default:
                break;
                /* should not hit here */
6314
            }
6315 6316
        }
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6317
        for (i = 0; i < *nparams && i < QEMU_NB_BLKIO_PARAM; i++) {
6318 6319 6320 6321 6322 6323 6324 6325 6326
            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,
6327 6328
                                    _("Field name '%s' too long"),
                                    VIR_DOMAIN_BLKIO_WEIGHT);
6329 6330 6331 6332
                    goto cleanup;
                }
                param->value.ui = persistentDef->blkio.weight;
                break;
6333

6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365
            case 1: /* blkiotune.device_weight */
                if (persistentDef->blkio.ndevices > 0) {
                    virBuffer buf = VIR_BUFFER_INITIALIZER;
                    for (j = 0; j < persistentDef->blkio.ndevices; j++) {
                        if (j)
                            virBufferAddChar(&buf, ',');
                        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);
                } else {
                    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;

6366 6367 6368 6369
            default:
                break;
                /* should not hit here */
            }
6370 6371 6372
        }
    }

6373 6374
    if (QEMU_NB_BLKIO_PARAM < *nparams)
        *nparams = QEMU_NB_BLKIO_PARAM;
6375 6376 6377 6378 6379 6380 6381 6382 6383 6384
    ret = 0;

cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
6385 6386

static int qemuDomainSetMemoryParameters(virDomainPtr dom,
6387
                                         virTypedParameterPtr params,
6388
                                         int nparams,
6389
                                         unsigned int flags)
6390 6391 6392
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
6393
    virDomainDefPtr persistentDef = NULL;
6394 6395 6396
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;
6397 6398
    bool isActive;

6399 6400
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411

    qemuDriverLock(driver);

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

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

6412 6413
    isActive = virDomainObjIsActive(vm);

6414
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
6415
        if (isActive)
6416
            flags = VIR_DOMAIN_AFFECT_LIVE;
6417
        else
6418
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6419 6420
    }

6421
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }

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

6441
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6442 6443 6444 6445 6446 6447 6448
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot change persistent config of a transient domain"));
            goto cleanup;
        }
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
            goto cleanup;
6449 6450 6451 6452
    }

    ret = 0;
    for (i = 0; i < nparams; i++) {
6453
        virTypedParameterPtr param = &params[i];
6454 6455 6456

        if (STREQ(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT)) {
            int rc;
6457
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
6458 6459 6460 6461 6462 6463
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for memory hard_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

6464
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6465 6466 6467 6468 6469 6470 6471 6472
                rc = virCgroupSetMemoryHardLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory hard_limit tunable"));
                    ret = -1;
                }
            }

6473
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6474
                persistentDef->mem.hard_limit = params[i].value.ul;
6475 6476 6477
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT)) {
            int rc;
6478
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
6479 6480 6481 6482 6483 6484
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for memory soft_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

6485
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6486 6487 6488 6489 6490 6491 6492 6493
                rc = virCgroupSetMemorySoftLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory soft_limit tunable"));
                    ret = -1;
                }
            }

6494
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6495
                persistentDef->mem.soft_limit = params[i].value.ul;
6496
            }
6497
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT)) {
6498
            int rc;
6499
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
6500 6501 6502 6503 6504 6505
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for swap_hard_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

6506
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6507 6508 6509 6510 6511 6512 6513
                rc = virCgroupSetMemSwapHardLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set swap_hard_limit tunable"));
                    ret = -1;
                }
            }
6514
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6515
                persistentDef->mem.swap_hard_limit = params[i].value.ul;
6516 6517 6518
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
            qemuReportError(VIR_ERR_INVALID_ARG,
6519 6520
                            _("Memory tunable `%s' not implemented"),
                            param->field);
6521 6522 6523 6524 6525 6526 6527 6528
            ret = -1;
        } else {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Parameter `%s' not supported"), param->field);
            ret = -1;
        }
    }

6529
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6530 6531
        if (virDomainSaveConfig(driver->configDir, persistentDef) < 0)
            ret = -1;
6532 6533
    }

6534 6535 6536 6537 6538 6539 6540 6541
cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

6542
static int qemuDomainGetMemoryParameters(virDomainPtr dom,
6543
                                         virTypedParameterPtr params,
6544
                                         int *nparams,
6545
                                         unsigned int flags)
6546 6547 6548 6549 6550
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6551
    virDomainDefPtr persistentDef = NULL;
6552
    unsigned long long val;
6553 6554
    int ret = -1;
    int rc;
6555
    bool isActive;
6556

6557
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
6558 6559
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);
6560

6561
    qemuDriverLock(driver);
6562

6563 6564 6565
    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

6566 6567 6568 6569 6570 6571 6572 6573
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

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

6574 6575
    isActive = virDomainObjIsActive(vm);

6576
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
6577
        if (isActive)
6578
            flags = VIR_DOMAIN_AFFECT_LIVE;
6579
        else
6580
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6581 6582
    }

6583
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }

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

6603
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6604 6605 6606 6607 6608 6609 6610
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot change persistent config of a transient domain"));
            goto cleanup;
        }
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
            goto cleanup;
6611 6612
    }

6613 6614 6615 6616 6617 6618 6619
    if ((*nparams) == 0) {
        /* Current number of memory parameters supported by cgroups */
        *nparams = QEMU_NB_MEM_PARAM;
        ret = 0;
        goto cleanup;
    }

6620
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6621
        for (i = 0; i < *nparams && i < QEMU_NB_MEM_PARAM; i++) {
6622 6623 6624
            virMemoryParameterPtr param = &params[i];
            val = 0;
            param->value.ul = 0;
6625
            param->type = VIR_TYPED_PARAM_ULLONG;
6626 6627 6628 6629 6630

            switch (i) {
            case 0: /* fill memory hard limit here */
                if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT) == NULL) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
6631 6632
                                    _("Field name '%s' too long"),
                                    VIR_DOMAIN_MEMORY_HARD_LIMIT);
6633 6634 6635 6636 6637 6638 6639 6640
                    goto cleanup;
                }
                param->value.ul = persistentDef->mem.hard_limit;
                break;

            case 1: /* fill memory soft limit here */
                if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT) == NULL) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
6641 6642
                                    _("Field name '%s' too long"),
                                    VIR_DOMAIN_MEMORY_SOFT_LIMIT);
6643 6644 6645 6646 6647 6648 6649 6650
                    goto cleanup;
                }
                param->value.ul = persistentDef->mem.soft_limit;
                break;

            case 2: /* fill swap hard limit here */
                if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT) == NULL) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
6651 6652
                                    _("Field name '%s' too long"),
                                    VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT);
6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663
                    goto cleanup;
                }
                param->value.ul = persistentDef->mem.swap_hard_limit;
                break;

            default:
                break;
                /* should not hit here */
            }
        }
        goto out;
6664 6665
    }

6666
    for (i = 0; i < *nparams && i < QEMU_NB_MEM_PARAM; i++) {
6667
        virTypedParameterPtr param = &params[i];
6668 6669
        val = 0;
        param->value.ul = 0;
6670
        param->type = VIR_TYPED_PARAM_ULLONG;
6671

6672 6673 6674
        /* Coverity does not realize that if we get here, group is set.  */
        sa_assert(group);

6675
        switch (i) {
6676 6677 6678 6679 6680
        case 0: /* fill memory hard limit here */
            rc = virCgroupGetMemoryHardLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory hard limit"));
6681
                goto cleanup;
6682 6683 6684
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
6685 6686
                                _("Field name '%s' too long"),
                                VIR_DOMAIN_MEMORY_HARD_LIMIT);
6687
                goto cleanup;
6688 6689 6690 6691 6692 6693 6694 6695 6696
            }
            param->value.ul = val;
            break;

        case 1: /* fill memory soft limit here */
            rc = virCgroupGetMemorySoftLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory soft limit"));
6697
                goto cleanup;
6698 6699 6700
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
6701 6702
                                _("Field name '%s' too long"),
                                VIR_DOMAIN_MEMORY_SOFT_LIMIT);
6703
                goto cleanup;
6704 6705 6706 6707 6708
            }
            param->value.ul = val;
            break;

        case 2: /* fill swap hard limit here */
6709
            rc = virCgroupGetMemSwapHardLimit(group, &val);
6710 6711 6712
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get swap hard limit"));
6713
                goto cleanup;
6714
            }
6715
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT) == NULL) {
6716
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
6717 6718
                                _("Field name '%s' too long"),
                                VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT);
6719
                goto cleanup;
6720 6721 6722 6723 6724 6725 6726 6727 6728 6729
            }
            param->value.ul = val;
            break;

        default:
            break;
            /* should not hit here */
        }
    }

6730
out:
6731 6732
    if (QEMU_NB_MEM_PARAM < *nparams)
        *nparams = QEMU_NB_MEM_PARAM;
6733 6734
    ret = 0;

6735 6736 6737 6738 6739 6740 6741 6742 6743
cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

6744 6745 6746 6747 6748 6749 6750 6751
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 已提交
6752 6753 6754
    long long vm_quota = 0;
    long long old_quota = 0;
    unsigned long long old_period = 0;
6755 6756 6757 6758

    if (period == 0 && quota == 0)
        return 0;

W
Wen Congyang 已提交
6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777
    /* 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;
    }
6778

W
Wen Congyang 已提交
6779 6780 6781 6782 6783
    rc = virCgroupGetCpuCfsPeriod(cgroup, &old_period);
    if (rc < 0) {
        virReportSystemError(-rc, "%s",
                             _("unable to get cpu bandwidth period tunable"));
        goto cleanup;
6784 6785
    }

W
Wen Congyang 已提交
6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806
    /*
     * 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;
6807
        }
W
Wen Congyang 已提交
6808
    }
6809

W
Wen Congyang 已提交
6810 6811 6812 6813
    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)
6814 6815
            goto cleanup;

W
Wen Congyang 已提交
6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835
    /* 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);
        }
6836 6837
    }

W
Wen Congyang 已提交
6838 6839 6840 6841 6842 6843
    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;

6844 6845 6846 6847 6848 6849 6850
    return 0;

cleanup:
    virCgroupFree(&cgroup_vcpu);
    return -1;
}

6851
static int qemuSetSchedulerParametersFlags(virDomainPtr dom,
6852
                                           virTypedParameterPtr params,
6853 6854
                                           int nparams,
                                           unsigned int flags)
6855 6856 6857 6858 6859
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6860
    virDomainDefPtr vmdef = NULL;
6861
    int ret = -1;
6862
    bool isActive;
6863
    int rc;
6864

6865 6866
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6867

6868
    qemuDriverLock(driver);
6869 6870 6871 6872

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

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

6878 6879
    isActive = virDomainObjIsActive(vm);

6880
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
6881
        if (isActive)
6882
            flags = VIR_DOMAIN_AFFECT_LIVE;
6883
        else
6884
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6885 6886
    }

6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot change persistent config of a transient domain"));
            goto cleanup;
        }

        /* Make a copy for updated domain. */
        vmdef = virDomainObjCopyPersistentDef(driver->caps, vm);
        if (!vmdef)
            goto cleanup;
6898 6899
    }

6900
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }

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

6920
    for (i = 0; i < nparams; i++) {
6921
        virTypedParameterPtr param = &params[i];
6922

6923
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CPU_SHARES)) {
6924
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
6925 6926
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for cpu_shares tunable, expected a 'ullong'"));
6927 6928 6929
                goto cleanup;
            }

6930
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6931 6932 6933 6934 6935 6936 6937 6938
                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;
6939
            }
6940

6941
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6942 6943
                vmdef->cputune.shares = params[i].value.ul;
            }
6944
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_VCPU_PERIOD)) {
6945 6946
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
W
Wen Congyang 已提交
6947
                                _("invalid type for vcpu_period tunable,"
6948 6949 6950 6951 6952 6953 6954
                                  " expected a 'ullong'"));
                goto cleanup;
            }

            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
                rc = qemuSetVcpusBWLive(vm, group, params[i].value.ul, 0);
                if (rc != 0)
6955
                    goto cleanup;
6956 6957 6958 6959 6960 6961 6962 6963

                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;
            }
6964
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_VCPU_QUOTA)) {
6965 6966
            if (param->type != VIR_TYPED_PARAM_LLONG) {
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
W
Wen Congyang 已提交
6967
                                _("invalid type for vcpu_quota tunable,"
6968 6969 6970 6971 6972 6973 6974
                                  " expected a 'llong'"));
                goto cleanup;
            }

            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
                rc = qemuSetVcpusBWLive(vm, group, 0, params[i].value.l);
                if (rc != 0)
6975
                    goto cleanup;
6976 6977 6978 6979 6980 6981 6982

                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;
6983
            }
6984
        } else {
6985 6986
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Invalid parameter `%s'"), param->field);
6987 6988 6989
            goto cleanup;
        }
    }
6990

6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003
    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;
    }

7004 7005 7006
    ret = 0;

cleanup:
7007
    virDomainDefFree(vmdef);
7008 7009 7010
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
7011
    qemuDriverUnlock(driver);
7012 7013 7014
    return ret;
}

7015
static int qemuSetSchedulerParameters(virDomainPtr dom,
7016
                                      virTypedParameterPtr params,
7017 7018 7019 7020 7021
                                      int nparams)
{
    return qemuSetSchedulerParametersFlags(dom,
                                           params,
                                           nparams,
7022
                                           VIR_DOMAIN_AFFECT_LIVE);
7023 7024
}

7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089
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;
}

7090 7091 7092 7093 7094
static int
qemuGetSchedulerParametersFlags(virDomainPtr dom,
                                virTypedParameterPtr params,
                                int *nparams,
                                unsigned int flags)
7095 7096 7097 7098
{
    struct qemud_driver *driver = dom->conn->privateData;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
7099 7100 7101
    unsigned long long shares;
    unsigned long long period;
    long long quota;
7102 7103
    int ret = -1;
    int rc;
7104
    bool isActive;
7105
    bool cpu_bw_status = false;
7106
    int saved_nparams = 0;
7107

7108
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
7109 7110
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);
7111

7112 7113
    qemuDriverLock(driver);

7114 7115 7116
    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

7117 7118 7119 7120 7121 7122 7123
    if (*nparams > 1) {
        rc = qemuGetCpuBWStatus(driver->cgroup);
        if (rc < 0)
            goto cleanup;
        cpu_bw_status = !!rc;
    }

7124 7125 7126
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

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

7132 7133
    isActive = virDomainObjIsActive(vm);

7134
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
7135
        if (isActive)
7136
            flags = VIR_DOMAIN_AFFECT_LIVE;
7137
        else
7138
            flags = VIR_DOMAIN_AFFECT_CONFIG;
7139 7140
    }

7141
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot query persistent config of a transient domain"));
            goto cleanup;
        }

        if (isActive) {
            virDomainDefPtr persistentDef;

            persistentDef = virDomainObjGetPersistentDef(driver->caps, vm);
            if (!persistentDef) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("can't get persistentDef"));
                goto cleanup;
            }
7157 7158 7159 7160 7161
            shares = persistentDef->cputune.shares;
            if (*nparams > 1 && cpu_bw_status) {
                period = persistentDef->cputune.period;
                quota = persistentDef->cputune.quota;
            }
7162
        } else {
7163 7164 7165 7166 7167
            shares = vm->def->cputune.shares;
            if (*nparams > 1 && cpu_bw_status) {
                period = vm->def->cputune.period;
                quota = vm->def->cputune.quota;
            }
7168
        }
7169
        goto out;
7170 7171
    }

7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183
    if (!isActive) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("domain is not running"));
        goto cleanup;
    }

    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup CPU controller is not mounted"));
        goto cleanup;
    }

7184
    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
7185 7186
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find cgroup for domain %s"), vm->def->name);
7187 7188 7189
        goto cleanup;
    }

7190
    rc = virCgroupGetCpuShares(group, &shares);
7191
    if (rc != 0) {
7192
        virReportSystemError(-rc, "%s",
7193 7194 7195
                             _("unable to get cpu shares tunable"));
        goto cleanup;
    }
7196 7197 7198 7199 7200 7201

    if (*nparams > 1 && cpu_bw_status) {
        rc = qemuGetVcpusBWLive(vm, group, &period, &quota);
        if (rc != 0)
            goto cleanup;
    }
7202
out:
7203
    params[0].value.ul = shares;
7204
    params[0].type = VIR_TYPED_PARAM_ULLONG;
7205 7206
    if (virStrcpyStatic(params[0].field,
                        VIR_DOMAIN_SCHEDULER_CPU_SHARES) == NULL) {
7207
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
7208
                        _("Field name '%s' too long"),
7209
                        VIR_DOMAIN_SCHEDULER_CPU_SHARES);
C
Chris Lalancette 已提交
7210 7211
        goto cleanup;
    }
7212

7213 7214 7215 7216 7217 7218
    saved_nparams++;

    if (cpu_bw_status) {
        if (*nparams > saved_nparams) {
            params[1].value.ul = period;
            params[1].type = VIR_TYPED_PARAM_ULLONG;
7219 7220
            if (virStrcpyStatic(params[1].field,
                                VIR_DOMAIN_SCHEDULER_VCPU_PERIOD) == NULL) {
7221
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
7222
                                _("Field name '%s' too long"),
7223
                                VIR_DOMAIN_SCHEDULER_VCPU_PERIOD);
7224 7225 7226 7227 7228 7229 7230 7231
                goto cleanup;
            }
            saved_nparams++;
        }

        if (*nparams > saved_nparams) {
            params[2].value.ul = quota;
            params[2].type = VIR_TYPED_PARAM_LLONG;
7232 7233
            if (virStrcpyStatic(params[2].field,
                                VIR_DOMAIN_SCHEDULER_VCPU_QUOTA) == NULL) {
7234
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
7235
                                _("Field name '%s' too long"),
7236
                                VIR_DOMAIN_SCHEDULER_VCPU_QUOTA);
7237 7238 7239 7240 7241 7242 7243 7244
                goto cleanup;
            }
            saved_nparams++;
        }
    }

    *nparams = saved_nparams;

7245 7246 7247 7248 7249 7250
    ret = 0;

cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
7251
    qemuDriverUnlock(driver);
7252 7253 7254
    return ret;
}

7255 7256 7257 7258 7259 7260
static int
qemuGetSchedulerParameters(virDomainPtr dom,
                           virTypedParameterPtr params,
                           int *nparams)
{
    return qemuGetSchedulerParametersFlags(dom, params, nparams,
7261
                                           VIR_DOMAIN_AFFECT_CURRENT);
7262
}
7263

7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 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
/**
 * 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);
        goto cleanup;
    }
    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;
}

7354 7355 7356 7357 7358
/* 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
7359 7360 7361
qemuDomainBlockStats(virDomainPtr dom,
                     const char *path,
                     struct _virDomainBlockStats *stats)
7362
{
7363
    struct qemud_driver *driver = dom->conn->privateData;
7364
    int i, ret = -1;
7365
    virDomainObjPtr vm;
7366
    virDomainDiskDefPtr disk = NULL;
7367
    qemuDomainObjPrivatePtr priv;
7368

7369
    qemuDriverLock(driver);
7370
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7371
    qemuDriverUnlock(driver);
7372
    if (!vm) {
7373 7374
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
7375 7376
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
7377
        goto cleanup;
7378
    }
7379

7380 7381 7382 7383 7384 7385
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

7386
    if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
7387 7388
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path: %s"), path);
7389
        goto cleanup;
7390
    }
7391
    disk = vm->def->disks[i];
7392

7393
    if (!disk->info.alias) {
7394 7395
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("missing disk device alias name for %s"), disk->dst);
7396
        goto cleanup;
7397
    }
7398

7399
    priv = vm->privateData;
7400 7401
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
        goto cleanup;
7402

7403 7404 7405 7406 7407
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }
7408

7409
    qemuDomainObjEnterMonitor(driver, vm);
7410 7411 7412 7413
    ret = qemuMonitorGetBlockStatsInfo(priv->mon,
                                       disk->info.alias,
                                       &stats->rd_req,
                                       &stats->rd_bytes,
7414
                                       NULL,
7415 7416
                                       &stats->wr_req,
                                       &stats->wr_bytes,
7417 7418 7419
                                       NULL,
                                       NULL,
                                       NULL,
7420 7421
                                       &stats->errs);
    qemuDomainObjExitMonitor(driver, vm);
7422

7423
endjob:
7424 7425
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
7426

7427
cleanup:
7428 7429
    if (vm)
        virDomainObjUnlock(vm);
7430
    return ret;
7431 7432
}

7433
static int
7434 7435 7436 7437 7438
qemuDomainBlockStatsFlags(virDomainPtr dom,
                          const char *path,
                          virTypedParameterPtr params,
                          int *nparams,
                          unsigned int flags)
7439 7440 7441 7442 7443 7444 7445 7446
{
    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;
7447
    virTypedParameterPtr param;
7448

7449 7450 7451 7452
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;
7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471

    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) {
7472
        if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
7473 7474 7475 7476
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("invalid path: %s"), path);
            goto cleanup;
        }
7477
        disk = vm->def->disks[i];
7478 7479 7480

        if (!disk->info.alias) {
             qemuReportError(VIR_ERR_INTERNAL_ERROR,
7481 7482
                             _("missing disk device alias name for %s"),
                             disk->dst);
7483 7484 7485 7486 7487 7488 7489 7490 7491 7492
             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;

7493 7494 7495 7496 7497 7498
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

7499 7500 7501 7502
    qemuDomainObjEnterMonitor(driver, vm);
    tmp = *nparams;
    ret = qemuMonitorGetBlockStatsParamsNumber(priv->mon, nparams);

7503
    if (tmp == 0 || ret < 0) {
7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524
        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;

7525 7526
    tmp = 0;
    ret = -1;
7527

7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540
    if (tmp < *nparams && wr_bytes != -1) {
        param = &params[tmp];
        if (virStrcpyStatic(param->field,
                            VIR_DOMAIN_BLOCK_STATS_WRITE_BYTES) == NULL) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Field name '%s' too long"),
                            VIR_DOMAIN_BLOCK_STATS_WRITE_BYTES);
            goto endjob;
        }
        param->type = VIR_TYPED_PARAM_LLONG;
        param->value.l = wr_bytes;
        tmp++;
    }
7541

7542
    if (tmp < *nparams && wr_req != -1) {
7543
        param = &params[tmp];
7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554
        if (virStrcpyStatic(param->field,
                            VIR_DOMAIN_BLOCK_STATS_WRITE_REQ) == NULL) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Field name '%s' too long"),
                            VIR_DOMAIN_BLOCK_STATS_WRITE_REQ);
            goto endjob;
        }
        param->type = VIR_TYPED_PARAM_LLONG;
        param->value.l = wr_req;
        tmp++;
    }
7555

7556
    if (tmp < *nparams && rd_bytes != -1) {
7557
        param = &params[tmp];
7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568
        if (virStrcpyStatic(param->field,
                            VIR_DOMAIN_BLOCK_STATS_READ_BYTES) == NULL) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Field name '%s' too long"),
                            VIR_DOMAIN_BLOCK_STATS_READ_BYTES);
            goto endjob;
        }
        param->type = VIR_TYPED_PARAM_LLONG;
        param->value.l = rd_bytes;
        tmp++;
    }
7569

7570
    if (tmp < *nparams && rd_req != -1) {
7571
        param = &params[tmp];
7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582
        if (virStrcpyStatic(param->field,
                            VIR_DOMAIN_BLOCK_STATS_READ_REQ) == NULL) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Field name '%s' too long"),
                            VIR_DOMAIN_BLOCK_STATS_READ_REQ);
            goto endjob;
        }
        param->type = VIR_TYPED_PARAM_LLONG;
        param->value.l = rd_req;
        tmp++;
    }
7583

7584
    if (tmp < *nparams && flush_req != -1) {
7585
        param = &params[tmp];
7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596
        if (virStrcpyStatic(param->field,
                            VIR_DOMAIN_BLOCK_STATS_FLUSH_REQ) == NULL) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Field name '%s' too long"),
                            VIR_DOMAIN_BLOCK_STATS_FLUSH_REQ);
            goto endjob;
        }
        param->type = VIR_TYPED_PARAM_LLONG;
        param->value.l = flush_req;
        tmp++;
    }
7597

7598
    if (tmp < *nparams && wr_total_times != -1) {
7599
        param = &params[tmp];
7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610
        if (virStrcpyStatic(param->field,
                            VIR_DOMAIN_BLOCK_STATS_WRITE_TOTAL_TIMES) == NULL) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Field name '%s' too long"),
                            VIR_DOMAIN_BLOCK_STATS_WRITE_TOTAL_TIMES);
            goto endjob;
        }
        param->type = VIR_TYPED_PARAM_LLONG;
        param->value.l = wr_total_times;
        tmp++;
    }
7611

7612
    if (tmp < *nparams && rd_total_times != -1) {
7613
        param = &params[tmp];
7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624
        if (virStrcpyStatic(param->field,
                            VIR_DOMAIN_BLOCK_STATS_READ_TOTAL_TIMES) == NULL) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Field name '%s' too long"),
                            VIR_DOMAIN_BLOCK_STATS_READ_TOTAL_TIMES);
            goto endjob;
        }
        param->type = VIR_TYPED_PARAM_LLONG;
        param->value.l = rd_total_times;
        tmp++;
    }
7625

7626
    if (tmp < *nparams && flush_total_times != -1) {
7627
        param = &params[tmp];
7628 7629 7630 7631 7632 7633
        if (virStrcpyStatic(param->field,
                            VIR_DOMAIN_BLOCK_STATS_READ_TOTAL_TIMES) == NULL) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Field name '%s' too long"),
                            VIR_DOMAIN_BLOCK_STATS_READ_TOTAL_TIMES);
            goto endjob;
7634
        }
7635 7636 7637
        param->type = VIR_TYPED_PARAM_LLONG;
        param->value.l = flush_total_times;
        tmp++;
7638 7639
    }

7640 7641 7642 7643 7644
    /* Field 'errs' is meaningless for QEMU, won't set it. */

    ret = 0;
    *nparams = tmp;

7645 7646 7647 7648 7649 7650 7651 7652 7653 7654
endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;

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

7655
#ifdef __linux__
7656 7657 7658 7659 7660
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
7661 7662
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
7663
    int i;
7664
    int ret = -1;
7665

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

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

D
Daniel P. Berrange 已提交
7678
    if (!virDomainObjIsActive(vm)) {
7679 7680
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
7681
        goto cleanup;
7682 7683 7684
    }

    /* Check the path is one of the domain's network interfaces. */
7685 7686
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
7687 7688 7689 7690
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
7691 7692
    }

7693
    if (ret == 0)
7694
        ret = linuxDomainInterfaceStats(path, stats);
7695
    else
7696 7697
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path, '%s' is not a known interface"), path);
7698

7699
cleanup:
7700 7701
    if (vm)
        virDomainObjUnlock(vm);
7702 7703
    return ret;
}
7704
#else
7705 7706 7707 7708
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
7709
{
7710 7711
    qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                    _("interface stats not implemented on this platform"));
7712 7713
    return -1;
}
7714
#endif
7715

7716 7717 7718
static int
qemudDomainMemoryStats (virDomainPtr dom,
                        struct _virDomainMemoryStat *stats,
7719 7720
                        unsigned int nr_stats,
                        unsigned int flags)
7721 7722 7723 7724 7725
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned int ret = -1;

7726 7727
    virCheckFlags(0, -1);

7728 7729 7730 7731 7732 7733 7734
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

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

7740
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
7741 7742
        goto cleanup;

7743 7744
    if (virDomainObjIsActive(vm)) {
        qemuDomainObjPrivatePtr priv = vm->privateData;
7745
        qemuDomainObjEnterMonitor(driver, vm);
7746
        ret = qemuMonitorGetMemoryStats(priv->mon, stats, nr_stats);
7747
        qemuDomainObjExitMonitor(driver, vm);
7748
    } else {
7749 7750
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
7751 7752
    }

7753
    if (qemuDomainObjEndJob(driver, vm) == 0)
7754 7755
        vm = NULL;

7756 7757 7758 7759 7760 7761
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

7762 7763 7764 7765 7766
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
E
Eric Blake 已提交
7767
                      unsigned int flags)
7768
{
7769 7770
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
7771 7772
    int fd = -1, ret = -1;
    const char *actual;
7773

E
Eric Blake 已提交
7774 7775
    virCheckFlags(0, -1);

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

7780
    if (!vm) {
7781 7782
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
7783 7784
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
7785
        goto cleanup;
7786 7787 7788
    }

    if (!path || path[0] == '\0') {
7789 7790
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("NULL or empty path"));
7791
        goto cleanup;
7792 7793
    }

7794 7795 7796 7797 7798
    /* Check the path belongs to this domain.  */
    if (!(actual = virDomainDiskPathByName(vm->def, path))) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path '%s'"), path);
        goto cleanup;
7799
    }
7800
    path = actual;
7801

7802 7803 7804 7805 7806 7807 7808
    /* 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;
    }
7809

7810 7811 7812 7813 7814 7815 7816 7817 7818
    /* 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;
7819 7820
    }

7821 7822
    ret = 0;

7823
cleanup:
7824
    VIR_FORCE_CLOSE(fd);
7825 7826
    if (vm)
        virDomainObjUnlock(vm);
7827 7828 7829
    return ret;
}

R
Richard W.M. Jones 已提交
7830 7831 7832 7833 7834 7835
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
7836 7837
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
7838
    char *tmp = NULL;
R
Richard W.M. Jones 已提交
7839
    int fd = -1, ret = -1;
7840
    qemuDomainObjPrivatePtr priv;
R
Richard W.M. Jones 已提交
7841

7842 7843
    virCheckFlags(VIR_MEMORY_VIRTUAL | VIR_MEMORY_PHYSICAL, -1);

7844
    qemuDriverLock(driver);
7845
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7846
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
7847 7848

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

7856
    if (flags != VIR_MEMORY_VIRTUAL && flags != VIR_MEMORY_PHYSICAL) {
7857 7858
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("flags parameter must be VIR_MEMORY_VIRTUAL or VIR_MEMORY_PHYSICAL"));
7859
        goto cleanup;
R
Richard W.M. Jones 已提交
7860 7861
    }

7862
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
7863 7864
        goto cleanup;

D
Daniel P. Berrange 已提交
7865
    if (!virDomainObjIsActive(vm)) {
7866 7867
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
7868
        goto endjob;
R
Richard W.M. Jones 已提交
7869 7870
    }

7871
    if (virAsprintf(&tmp, "%s/qemu.mem.XXXXXX", driver->cacheDir) < 0) {
7872
        virReportOOMError();
7873
        goto endjob;
7874 7875
    }

R
Richard W.M. Jones 已提交
7876 7877
    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
7878 7879
        virReportSystemError(errno,
                             _("mkstemp(\"%s\") failed"), tmp);
7880
        goto endjob;
R
Richard W.M. Jones 已提交
7881 7882
    }

7883 7884
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm, tmp);

7885
    priv = vm->privateData;
7886
    qemuDomainObjEnterMonitor(driver, vm);
7887
    if (flags == VIR_MEMORY_VIRTUAL) {
7888
        if (qemuMonitorSaveVirtualMemory(priv->mon, offset, size, tmp) < 0) {
7889
            qemuDomainObjExitMonitor(driver, vm);
7890
            goto endjob;
7891
        }
7892
    } else {
7893
        if (qemuMonitorSavePhysicalMemory(priv->mon, offset, size, tmp) < 0) {
7894
            qemuDomainObjExitMonitor(driver, vm);
7895
            goto endjob;
7896
        }
R
Richard W.M. Jones 已提交
7897
    }
7898
    qemuDomainObjExitMonitor(driver, vm);
R
Richard W.M. Jones 已提交
7899 7900

    /* Read the memory file into buffer. */
7901
    if (saferead(fd, buffer, size) == (ssize_t) -1) {
7902 7903 7904
        virReportSystemError(errno,
                             _("failed to read temporary file "
                               "created with template %s"), tmp);
7905
        goto endjob;
R
Richard W.M. Jones 已提交
7906 7907 7908
    }

    ret = 0;
7909

7910
endjob:
7911
    if (qemuDomainObjEndJob(driver, vm) == 0)
7912
        vm = NULL;
7913

7914
cleanup:
7915
    VIR_FORCE_CLOSE(fd);
7916 7917
    if (tmp)
        unlink(tmp);
W
Wen Congyang 已提交
7918
    VIR_FREE(tmp);
7919 7920
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
7921 7922 7923
    return ret;
}

7924

7925 7926 7927 7928 7929 7930 7931 7932 7933
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;
7934
    virStorageFileMetadata *meta = NULL;
7935
    virDomainDiskDefPtr disk = NULL;
7936
    struct stat sb;
7937
    int i;
7938
    int format;
7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959

    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. */
7960
    if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
7961 7962 7963 7964
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path %s not assigned to domain"), path);
        goto cleanup;
    }
7965 7966 7967 7968 7969 7970 7971 7972
    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;
7973 7974

    /* The path is correct, now try to open it and get its size. */
7975
    fd = open(path, O_RDONLY);
7976 7977 7978 7979 7980 7981 7982
    if (fd == -1) {
        virReportSystemError(errno,
                             _("failed to open path '%s'"), path);
        goto cleanup;
    }

    /* Probe for magic formats */
7983 7984 7985 7986 7987 7988 7989 7990
    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 {
7991 7992 7993 7994 7995 7996 7997
        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);
7998
            goto cleanup;
7999
        }
8000 8001
    }

8002 8003 8004 8005 8006
    if (VIR_ALLOC(meta) < 0) {
        virReportOOMError();
        goto cleanup;
    }

8007 8008
    if (virStorageFileGetMetadataFromFD(path, fd,
                                        format,
8009
                                        meta) < 0)
8010 8011 8012 8013 8014 8015 8016 8017 8018 8019
        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)) {
8020
#ifndef WIN32
8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033
        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.
         */
8034
        end = lseek(fd, 0, SEEK_END);
8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045
        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 */
8046 8047
    if (meta->capacity)
        info->capacity = meta->capacity;
8048

8049
    /* Set default value .. */
8050 8051
    info->allocation = info->physical;

8052 8053 8054
    /* ..but if guest is running & not using raw
       disk format and on a block device, then query
       highest allocated extent from QEMU */
8055
    if (disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
8056
        format != VIR_STORAGE_FILE_RAW &&
8057 8058
        S_ISBLK(sb.st_mode) &&
        virDomainObjIsActive(vm)) {
8059
        qemuDomainObjPrivatePtr priv = vm->privateData;
8060

8061 8062
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
            goto cleanup;
8063

8064
        if (virDomainObjIsActive(vm)) {
8065
            qemuDomainObjEnterMonitor(driver, vm);
8066 8067 8068 8069
            ret = qemuMonitorGetBlockExtent(priv->mon,
                                            disk->info.alias,
                                            &info->allocation);
            qemuDomainObjExitMonitor(driver, vm);
8070
        } else {
8071
            ret = 0;
8072
        }
8073 8074 8075

        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
8076 8077 8078
    } else {
        ret = 0;
    }
8079 8080

cleanup:
8081
    virStorageFileFreeMetadata(meta);
8082
    VIR_FORCE_CLOSE(fd);
8083 8084 8085 8086 8087 8088
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


8089
static int
8090 8091 8092 8093
qemuDomainEventRegister(virConnectPtr conn,
                        virConnectDomainEventCallback callback,
                        void *opaque,
                        virFreeCallback freecb)
8094
{
8095 8096 8097
    struct qemud_driver *driver = conn->privateData;
    int ret;

8098
    qemuDriverLock(driver);
8099 8100
    ret = virDomainEventCallbackListAdd(conn,
                                        driver->domainEventState->callbacks,
8101
                                        callback, opaque, freecb);
8102
    qemuDriverUnlock(driver);
8103

8104
    return ret;
8105 8106
}

8107

8108
static int
8109 8110
qemuDomainEventDeregister(virConnectPtr conn,
                          virConnectDomainEventCallback callback)
8111
{
8112 8113 8114
    struct qemud_driver *driver = conn->privateData;
    int ret;

8115
    qemuDriverLock(driver);
8116 8117 8118
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
8119
    qemuDriverUnlock(driver);
8120

8121
    return ret;
8122 8123
}

8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137

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);
    ret = virDomainEventCallbackListAddID(conn,
8138
                                          driver->domainEventState->callbacks,
8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154
                                          dom, eventID,
                                          callback, opaque, freecb);
    qemuDriverUnlock(driver);

    return ret;
}


static int
qemuDomainEventDeregisterAny(virConnectPtr conn,
                             int callbackID)
{
    struct qemud_driver *driver = conn->privateData;
    int ret;

    qemuDriverLock(driver);
8155 8156 8157
    ret = virDomainEventStateDeregisterAny(conn,
                                           driver->domainEventState,
                                           callbackID);
8158 8159 8160 8161 8162 8163
    qemuDriverUnlock(driver);

    return ret;
}


8164 8165 8166
/*******************************************************************
 * Migration Protocol Version 2
 *******************************************************************/
D
Daniel Veillard 已提交
8167

C
Chris Lalancette 已提交
8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182
/* 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;
8183

8184
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
8185

8186 8187
    qemuDriverLock(driver);

C
Chris Lalancette 已提交
8188
    if (!dom_xml) {
8189 8190
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
C
Chris Lalancette 已提交
8191 8192 8193
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
8194
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
8195 8196 8197 8198
                         "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
        goto cleanup;
    }
    if (st == NULL) {
8199 8200
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("tunnelled migration requested but NULL stream passed"));
C
Chris Lalancette 已提交
8201 8202 8203
        goto cleanup;
    }

8204 8205 8206 8207 8208 8209 8210
    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

8211 8212 8213
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     NULL, 0, NULL, NULL, /* No cookies in v2 */
                                     st, dname, dom_xml);
8214

C
Chris Lalancette 已提交
8215
cleanup:
8216
    qemuDriverUnlock(driver);
C
Chris Lalancette 已提交
8217 8218 8219
    return ret;
}

D
Daniel Veillard 已提交
8220 8221 8222 8223
/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
8224
static int ATTRIBUTE_NONNULL (5)
D
Daniel Veillard 已提交
8225
qemudDomainMigratePrepare2 (virConnectPtr dconn,
8226 8227
                            char **cookie ATTRIBUTE_UNUSED,
                            int *cookielen ATTRIBUTE_UNUSED,
D
Daniel Veillard 已提交
8228 8229
                            const char *uri_in,
                            char **uri_out,
C
Chris Lalancette 已提交
8230
                            unsigned long flags,
D
Daniel Veillard 已提交
8231 8232 8233 8234
                            const char *dname,
                            unsigned long resource ATTRIBUTE_UNUSED,
                            const char *dom_xml)
{
8235
    struct qemud_driver *driver = dconn->privateData;
8236
    int ret = -1;
8237

8238
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
8239

8240
    *uri_out = NULL;
D
Daniel Veillard 已提交
8241

8242
    qemuDriverLock(driver);
8243 8244 8245 8246 8247 8248 8249 8250

    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 已提交
8251 8252 8253 8254
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
8255 8256
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Tunnelled migration requested but invalid RPC method called"));
C
Chris Lalancette 已提交
8257 8258 8259
        goto cleanup;
    }

D
Daniel Veillard 已提交
8260
    if (!dom_xml) {
8261 8262
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
8263
        goto cleanup;
D
Daniel Veillard 已提交
8264 8265
    }

8266 8267 8268 8269
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
8270
    ret = qemuMigrationPrepareDirect(driver, dconn,
8271
                                     NULL, 0, NULL, NULL, /* No cookies */
8272 8273
                                     uri_in, uri_out,
                                     dname, dom_xml);
D
Daniel Veillard 已提交
8274

8275 8276 8277 8278
cleanup:
    qemuDriverUnlock(driver);
    return ret;
}
C
Chris Lalancette 已提交
8279

D
Daniel Veillard 已提交
8280

8281 8282 8283
/* Perform is the second step, and it runs on the source host. */
static int
qemudDomainMigratePerform (virDomainPtr dom,
8284 8285
                           const char *cookie,
                           int cookielen,
8286 8287 8288 8289 8290 8291 8292 8293
                           const char *uri,
                           unsigned long flags,
                           const char *dname,
                           unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
8294
    const char *dconnuri = NULL;
8295

8296
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
8297

8298
    qemuDriverLock(driver);
8299 8300 8301 8302 8303 8304 8305
    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

8306
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel Veillard 已提交
8307
    if (!vm) {
8308 8309
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
8310 8311
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
8312
        goto cleanup;
D
Daniel Veillard 已提交
8313 8314
    }

8315 8316 8317 8318 8319
    if (flags & VIR_MIGRATE_PEER2PEER) {
        dconnuri = uri;
        uri = NULL;
    }

8320 8321 8322 8323 8324 8325
    /* 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
     */
8326
    ret = qemuMigrationPerform(driver, dom->conn, vm,
8327
                               NULL, dconnuri, uri, cookie, cookielen,
8328
                               NULL, NULL, /* No output cookies in v2 */
8329
                               flags, dname, resource, false);
8330

8331
cleanup:
8332
    qemuDriverUnlock(driver);
8333
    return ret;
D
Daniel Veillard 已提交
8334 8335
}

8336

D
Daniel Veillard 已提交
8337 8338 8339 8340 8341 8342 8343
/* 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 已提交
8344
                           unsigned long flags,
D
Daniel Veillard 已提交
8345 8346
                           int retcode)
{
8347 8348 8349
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
D
Daniel Veillard 已提交
8350

8351
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
C
Chris Lalancette 已提交
8352

8353
    qemuDriverLock(driver);
8354
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
8355
    if (!vm) {
8356 8357
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
8358
        goto cleanup;
D
Daniel Veillard 已提交
8359 8360
    }

8361 8362 8363 8364
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
8365
    dom = qemuMigrationFinish(driver, dconn, vm,
8366
                              NULL, 0, NULL, NULL, /* No cookies */
8367
                              flags, retcode, false);
8368

8369
cleanup:
8370
    qemuDriverUnlock(driver);
8371
    return dom;
D
Daniel Veillard 已提交
8372 8373
}

8374

8375 8376 8377 8378 8379 8380
/*******************************************************************
 * Migration Protocol Version 3
 *******************************************************************/

static char *
qemuDomainMigrateBegin3(virDomainPtr domain,
8381
                        const char *xmlin,
8382 8383 8384
                        char **cookieout,
                        int *cookieoutlen,
                        unsigned long flags,
8385
                        const char *dname,
8386 8387 8388 8389 8390 8391
                        unsigned long resource ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    char *xml = NULL;

8392
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403

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

8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417
    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;
    }

8418 8419 8420 8421 8422 8423 8424
    /* Check if there is any ejected media.
     * We don't want to require them on the destination.
     */

    if (qemuDomainCheckEjectableMedia(driver, vm) < 0)
        goto endjob;

8425
    if (!(xml = qemuMigrationBegin(driver, vm, xmlin, dname,
8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444
                                   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;
    }
8445 8446

cleanup:
8447 8448
    if (vm)
        virDomainObjUnlock(vm);
8449 8450
    qemuDriverUnlock(driver);
    return xml;
8451 8452 8453 8454 8455 8456 8457 8458 8459 8460

endjob:
    if ((flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        if (qemuMigrationJobFinish(driver, vm) == 0)
            vm = NULL;
    } else {
        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
    }
    goto cleanup;
8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478
}

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;

8479
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525

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

8526
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557

    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,
8558
                          const char *xmlin,
8559 8560 8561 8562
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
8563
                          const char *dconnuri,
8564 8565 8566 8567 8568 8569 8570 8571 8572
                          const char *uri,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

8573
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584

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

8585
    ret = qemuMigrationPerform(driver, dom->conn, vm, xmlin,
8586
                               dconnuri, uri, cookiein, cookieinlen,
8587
                               cookieout, cookieoutlen,
8588
                               flags, dname, resource, true);
8589 8590 8591 8592 8593 8594 8595

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}


8596
static virDomainPtr
8597 8598 8599 8600 8601 8602
qemuDomainMigrateFinish3(virConnectPtr dconn,
                         const char *dname,
                         const char *cookiein,
                         int cookieinlen,
                         char **cookieout,
                         int *cookieoutlen,
8603
                         const char *dconnuri ATTRIBUTE_UNUSED,
8604 8605
                         const char *uri ATTRIBUTE_UNUSED,
                         unsigned long flags,
8606
                         int cancelled)
8607 8608 8609
{
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
8610
    virDomainPtr dom = NULL;
8611

8612
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
8613 8614 8615 8616 8617 8618 8619 8620 8621

    qemuDriverLock(driver);
    vm = virDomainFindByName(&driver->domains, dname);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
        goto cleanup;
    }

8622 8623 8624 8625
    dom = qemuMigrationFinish(driver, dconn, vm,
                              cookiein, cookieinlen,
                              cookieout, cookieoutlen,
                              flags, cancelled, true);
8626 8627 8628

cleanup:
    qemuDriverUnlock(driver);
8629
    return dom;
8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641
}

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;
8642
    enum qemuMigrationJobPhase phase;
8643

8644
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655

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

8656
    if (!qemuMigrationJobIsActive(vm, QEMU_ASYNC_JOB_MIGRATION_OUT))
8657 8658
        goto cleanup;

8659 8660 8661 8662 8663 8664 8665
    if (cancelled)
        phase = QEMU_MIGRATION_PHASE_CONFIRM3_CANCELLED;
    else
        phase = QEMU_MIGRATION_PHASE_CONFIRM3;

    qemuMigrationJobStartPhase(driver, vm, phase);

8666 8667
    ret = qemuMigrationConfirm(driver, domain->conn, vm,
                               cookiein, cookieinlen,
8668 8669
                               flags, cancelled);

8670
    if (qemuMigrationJobFinish(driver, vm) == 0) {
8671 8672 8673 8674 8675
        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);
8676
        qemuDomainRemoveInactive(driver, vm);
8677 8678 8679
        vm = NULL;
    }

8680
cleanup:
8681 8682
    if (vm)
        virDomainObjUnlock(vm);
8683 8684 8685 8686 8687
    qemuDriverUnlock(driver);
    return ret;
}


8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703
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;

8704
    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE);
8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721
    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) {
8722 8723
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("device %s is not a PCI device"), dev->name);
8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736
        goto out;
    }

    ret = 0;
out:
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
qemudNodeDeviceDettach (virNodeDevicePtr dev)
{
8737
    struct qemud_driver *driver = dev->conn->privateData;
8738 8739 8740 8741 8742 8743 8744
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

8745
    pci = pciGetDevice(domain, bus, slot, function);
8746 8747 8748
    if (!pci)
        return -1;

8749 8750
    qemuDriverLock(driver);
    if (pciDettachDevice(pci, driver->activePciHostdevs) < 0)
8751 8752 8753 8754
        goto out;

    ret = 0;
out:
8755
    qemuDriverUnlock(driver);
8756
    pciFreeDevice(pci);
8757 8758 8759 8760 8761 8762
    return ret;
}

static int
qemudNodeDeviceReAttach (virNodeDevicePtr dev)
{
8763
    struct qemud_driver *driver = dev->conn->privateData;
8764 8765 8766 8767 8768 8769 8770
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

8771
    pci = pciGetDevice(domain, bus, slot, function);
8772 8773 8774
    if (!pci)
        return -1;

8775 8776
    pciDeviceReAttachInit(pci);

8777 8778
    qemuDriverLock(driver);
    if (pciReAttachDevice(pci, driver->activePciHostdevs) < 0)
8779 8780 8781 8782
        goto out;

    ret = 0;
out:
8783
    qemuDriverUnlock(driver);
8784
    pciFreeDevice(pci);
8785 8786 8787 8788 8789 8790
    return ret;
}

static int
qemudNodeDeviceReset (virNodeDevicePtr dev)
{
8791
    struct qemud_driver *driver = dev->conn->privateData;
8792 8793 8794 8795 8796 8797 8798
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

8799
    pci = pciGetDevice(domain, bus, slot, function);
8800 8801 8802
    if (!pci)
        return -1;

8803 8804
    qemuDriverLock(driver);

8805
    if (pciResetDevice(pci, driver->activePciHostdevs, NULL) < 0)
8806 8807 8808 8809
        goto out;

    ret = 0;
out:
8810
    qemuDriverUnlock(driver);
8811
    pciFreeDevice(pci);
8812 8813 8814
    return ret;
}

8815 8816 8817
static int
qemuCPUCompare(virConnectPtr conn,
               const char *xmlDesc,
E
Eric Blake 已提交
8818
               unsigned int flags)
8819 8820 8821 8822
{
    struct qemud_driver *driver = conn->privateData;
    int ret = VIR_CPU_COMPARE_ERROR;

E
Eric Blake 已提交
8823 8824
    virCheckFlags(0, VIR_CPU_COMPARE_ERROR);

8825 8826 8827
    qemuDriverLock(driver);

    if (!driver->caps || !driver->caps->host.cpu) {
8828
        qemuReportError(VIR_ERR_OPERATION_INVALID,
8829
                        "%s", _("cannot get host CPU capabilities"));
E
Eric Blake 已提交
8830
    } else {
8831
        ret = cpuCompareXML(driver->caps->host.cpu, xmlDesc);
E
Eric Blake 已提交
8832
    }
8833 8834 8835 8836 8837 8838

    qemuDriverUnlock(driver);

    return ret;
}

8839

8840 8841 8842 8843
static char *
qemuCPUBaseline(virConnectPtr conn ATTRIBUTE_UNUSED,
                const char **xmlCPUs,
                unsigned int ncpus,
E
Eric Blake 已提交
8844
                unsigned int flags)
8845 8846 8847
{
    char *cpu;

E
Eric Blake 已提交
8848 8849
    virCheckFlags(0, NULL);

8850 8851 8852 8853 8854
    cpu = cpuBaselineXML(xmlCPUs, ncpus, NULL, 0);

    return cpu;
}

8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876

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)) {
8877
        if (priv->job.asyncJob) {
8878
            memcpy(info, &priv->job.info, sizeof(*info));
8879 8880 8881 8882 8883 8884

            /* 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
             */
8885
            if (virTimeMillisNow(&info->timeElapsed) < 0)
8886
                goto cleanup;
8887
            info->timeElapsed -= priv->job.start;
8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906
        } 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;
}


8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923
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;
    }

8924 8925
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_ABORT) < 0)
        goto cleanup;
8926

8927
    if (!virDomainObjIsActive(vm)) {
8928 8929
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
8930
        goto endjob;
8931 8932
    }

8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946
    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");
8947
    qemuDomainObjEnterMonitor(driver, vm);
8948 8949 8950 8951 8952 8953
    ret = qemuMonitorMigrateCancel(priv->mon);
    qemuDomainObjExitMonitor(driver, vm);

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
8954 8955 8956 8957 8958 8959 8960 8961

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


8962 8963 8964 8965 8966 8967 8968 8969 8970 8971
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;

8972
    virCheckFlags(0, -1);
8973 8974 8975

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
8976
    qemuDriverUnlock(driver);
8977 8978 8979 8980 8981 8982

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

8986 8987 8988
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
        goto cleanup;

8989 8990 8991
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
8992
        goto endjob;
8993 8994 8995 8996
    }

    priv = vm->privateData;

8997
    if (priv->job.asyncJob != QEMU_ASYNC_JOB_MIGRATION_OUT) {
8998 8999
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not being migrated"));
9000
        goto endjob;
9001 9002
    }

9003
    VIR_DEBUG("Setting migration downtime to %llums", downtime);
9004
    qemuDomainObjEnterMonitor(driver, vm);
9005 9006 9007 9008 9009 9010
    ret = qemuMonitorSetMigrationDowntime(priv->mon, downtime);
    qemuDomainObjExitMonitor(driver, vm);

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
9011 9012 9013 9014 9015 9016 9017

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

9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031
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);
9032
    qemuDriverUnlock(driver);
9033 9034 9035 9036 9037 9038

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
9039
        return -1;
9040 9041 9042
    }

    priv = vm->privateData;
9043 9044 9045
    if (virDomainObjIsActive(vm)) {
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
            goto cleanup;
9046

9047 9048 9049 9050 9051 9052
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto endjob;
        }

9053 9054 9055 9056
        VIR_DEBUG("Setting migration bandwidth to %luMbs", bandwidth);
        qemuDomainObjEnterMonitor(driver, vm);
        ret = qemuMonitorSetMigrationSpeed(priv->mon, bandwidth);
        qemuDomainObjExitMonitor(driver, vm);
9057

9058 9059
        if (ret == 0)
            priv->migMaxBandwidth = bandwidth;
9060

9061
endjob:
9062 9063 9064 9065 9066 9067
        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
    } else {
        priv->migMaxBandwidth = bandwidth;
        ret = 0;
    }
9068 9069 9070 9071 9072 9073 9074

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

9075 9076 9077 9078 9079 9080 9081
static int
qemuDomainMigrateGetMaxSpeed(virDomainPtr dom,
                             unsigned long *bandwidth,
                             unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
9082
    qemuDomainObjPrivatePtr priv;
9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098
    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 已提交
9099 9100
    priv = vm->privateData;
    *bandwidth = priv->migMaxBandwidth;
9101 9102 9103 9104 9105 9106 9107 9108
    ret = 0;

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

C
Chris Lalancette 已提交
9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121
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++) {
        if (vm->def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
            (!vm->def->disks[i]->driverType ||
             STRNEQ(vm->def->disks[i]->driverType, "qcow2"))) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
9122 9123
                            _("Disk '%s' does not support snapshotting"),
                            vm->def->disks[i]->src);
C
Chris Lalancette 已提交
9124 9125 9126 9127 9128 9129 9130
            return 0;
        }
    }

    return 1;
}

9131 9132
/* The domain is expected to be locked and inactive. */
static int
E
Eric Blake 已提交
9133 9134
qemuDomainSnapshotCreateInactive(struct qemud_driver *driver,
                                 virDomainObjPtr vm,
9135 9136
                                 virDomainSnapshotObjPtr snap)
{
E
Eric Blake 已提交
9137
    return qemuDomainSnapshotForEachQcow2(driver, vm, snap, "-c", false);
9138 9139
}

9140 9141
/* The domain is expected to be locked and active. */
static int
9142 9143
qemuDomainSnapshotCreateActive(virConnectPtr conn,
                               struct qemud_driver *driver,
9144
                               virDomainObjPtr *vmptr,
9145 9146
                               virDomainSnapshotObjPtr snap,
                               unsigned int flags)
9147 9148 9149
{
    virDomainObjPtr vm = *vmptr;
    qemuDomainObjPrivatePtr priv = vm->privateData;
9150 9151
    bool resume = false;
    int ret = -1;
9152

9153
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
9154 9155
        return -1;

9156 9157 9158 9159 9160 9161
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

J
Jiri Denemark 已提交
9162
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
9163 9164 9165 9166
        /* 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.
         */
9167 9168
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_NONE) < 0)
9169 9170 9171 9172 9173 9174 9175 9176 9177 9178
            goto cleanup;

        resume = true;
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto cleanup;
        }
    }

9179
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
9180 9181
    ret = qemuMonitorCreateSnapshot(priv->mon, snap->def->name);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199
    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);
    }
9200

9201 9202
cleanup:
    if (resume && virDomainObjIsActive(vm) &&
J
Jiri Denemark 已提交
9203
        qemuProcessStartCPUs(driver, vm, conn,
9204 9205
                             VIR_DOMAIN_RUNNING_UNPAUSED,
                             QEMU_ASYNC_JOB_NONE) < 0 &&
9206 9207 9208 9209 9210
        virGetLastError() == NULL) {
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("resuming after snapshot failed"));
    }

9211
endjob:
9212
    if (vm && qemuDomainObjEndJob(driver, vm) == 0) {
9213 9214
        /* Only possible if a transient vm quit while our locks were down,
         * in which case we don't want to save snapshot metadata.  */
9215
        *vmptr = NULL;
9216 9217
        ret = -1;
    }
9218 9219 9220 9221

    return ret;
}

9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311
static int
qemuDomainSnapshotDiskPrepare(virDomainObjPtr vm, virDomainSnapshotDefPtr def)
{
    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;
                }
            } else if (!S_ISBLK(st.st_mode)) {
                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
9312 9313
qemuDomainSnapshotCreateSingleDiskActive(struct qemud_driver *driver,
                                         virDomainObjPtr vm,
9314
                                         virDomainSnapshotDiskDefPtr snap,
9315 9316
                                         virDomainDiskDefPtr disk,
                                         virDomainDiskDefPtr persistDisk)
9317 9318 9319 9320 9321
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *device = NULL;
    char *source = NULL;
    char *driverType = NULL;
9322 9323
    char *persistSource = NULL;
    char *persistDriverType = NULL;
9324
    int ret = -1;
9325 9326 9327 9328
    int fd = -1;
    char *origsrc = NULL;
    char *origdriver = NULL;
    bool need_unlink = false;
9329 9330 9331 9332 9333 9334 9335 9336 9337 9338

    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") &&
9339 9340 9341 9342 9343
         !(driverType = strdup("qcow2"))) ||
        (persistDisk &&
         (!(persistSource = strdup(source)) ||
          (STRNEQ_NULLABLE(persistDisk->driverType, "qcow2") &&
           !(persistDriverType = strdup("qcow2")))))) {
9344 9345 9346 9347
        virReportOOMError();
        goto cleanup;
    }

9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358
    /* 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;
9359
    disk->driverType = (char *) "raw"; /* Don't want to probe backing files */
9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375

    if (virDomainLockDiskAttach(driver->lockManager, vm, disk) < 0)
        goto cleanup;
    if (virSecurityManagerSetImageLabel(driver->securityManager, vm,
                                        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 */
9376 9377 9378 9379 9380 9381
    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.  */
9382
    need_unlink = false;
9383 9384 9385 9386 9387 9388 9389 9390
    VIR_FREE(disk->src);
    disk->src = source;
    source = NULL;
    if (driverType) {
        VIR_FREE(disk->driverType);
        disk->driverType = driverType;
        driverType = NULL;
    }
9391 9392 9393 9394 9395 9396 9397 9398 9399 9400
    if (persistDisk) {
        VIR_FREE(persistDisk->src);
        persistDisk->src = persistSource;
        persistSource = NULL;
        if (persistDriverType) {
            VIR_FREE(persistDisk->driverType);
            persistDisk->driverType = persistDriverType;
            persistDriverType = NULL;
        }
    }
9401 9402

cleanup:
9403 9404 9405 9406 9407 9408
    if (origsrc) {
        disk->src = origsrc;
        disk->driverType = origdriver;
    }
    if (need_unlink && unlink(source))
        VIR_WARN("unable to unlink just-created %s", source);
9409 9410 9411
    VIR_FREE(device);
    VIR_FREE(source);
    VIR_FREE(driverType);
9412 9413
    VIR_FREE(persistSource);
    VIR_FREE(persistDriverType);
9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428
    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;
9429
    bool persist = false;
9430 9431 9432 9433

    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
        return -1;

9434 9435 9436 9437 9438 9439 9440
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }


9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
        /* 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++) {
9467 9468
        virDomainDiskDefPtr persistDisk = NULL;

9469 9470
        if (snap->def->disks[i].snapshot == VIR_DOMAIN_DISK_SNAPSHOT_NO)
            continue;
9471 9472 9473 9474 9475 9476 9477 9478 9479
        if (vm->newDef) {
            int indx = virDomainDiskIndexByName(vm->newDef,
                                                vm->def->disks[i]->dst,
                                                false);
            if (indx >= 0) {
                persistDisk = vm->newDef->disks[indx];
                persist = true;
            }
        }
9480

9481
        ret = qemuDomainSnapshotCreateSingleDiskActive(driver, vm,
9482
                                                       &snap->def->disks[i],
9483 9484
                                                       vm->def->disks[i],
                                                       persistDisk);
9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518
        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:
    if (resume && virDomainObjIsActive(vm) &&
        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"));
    }

    if (vm) {
9519 9520 9521
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0 ||
            (persist &&
             virDomainSaveConfig(driver->configDir, vm->newDef) < 0))
9522
            ret = -1;
9523 9524 9525 9526
    }

endjob:
    if (vm && (qemuDomainObjEndJob(driver, vm) == 0)) {
9527 9528 9529 9530 9531 9532 9533 9534 9535
            /* 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;
}

9536 9537 9538 9539
static virDomainSnapshotPtr
qemuDomainSnapshotCreateXML(virDomainPtr domain,
                            const char *xmlDesc,
                            unsigned int flags)
C
Chris Lalancette 已提交
9540 9541 9542
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
9543
    char *xml = NULL;
C
Chris Lalancette 已提交
9544 9545 9546
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
9547
    virDomainSnapshotDefPtr def = NULL;
9548 9549
    bool update_current = true;
    unsigned int parse_flags = 0;
9550
    virDomainSnapshotObjPtr other = NULL;
C
Chris Lalancette 已提交
9551

9552 9553
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE |
                  VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT |
9554
                  VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA |
9555 9556
                  VIR_DOMAIN_SNAPSHOT_CREATE_HALT |
                  VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY, NULL);
9557 9558 9559 9560 9561 9562 9563

    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;
9564 9565
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY)
        parse_flags |= VIR_DOMAIN_SNAPSHOT_PARSE_DISKS;
9566

C
Chris Lalancette 已提交
9567 9568 9569 9570 9571 9572 9573 9574 9575
    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;
    }

9576 9577 9578 9579 9580
    if (qemuProcessAutoDestroyActive(driver, vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is marked for auto destroy"));
        goto cleanup;
    }
9581 9582 9583 9584 9585
    if (!vm->persistent && (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot halt after transient domain snapshot"));
        goto cleanup;
    }
9586

9587 9588 9589
    if (!(def = virDomainSnapshotDefParseString(xmlDesc, driver->caps,
                                                QEMU_EXPECTED_VIRT_TYPES,
                                                parse_flags)))
C
Chris Lalancette 已提交
9590 9591
        goto cleanup;

9592 9593 9594 9595 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
    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 */
9626 9627 9628 9629 9630 9631 9632
        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;
        }
9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644
        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;
            }
9645 9646 9647 9648 9649 9650 9651 9652
            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;
            }
9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663
            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;
                }
            }
9664 9665 9666 9667
            if (other == vm->current_snapshot) {
                update_current = true;
                vm->current_snapshot = NULL;
            }
9668 9669 9670 9671 9672 9673
            /* 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;
9674
        }
9675 9676 9677 9678 9679 9680
        if (def->state == VIR_DOMAIN_DISK_SNAPSHOT && def->dom) {
            if (virDomainSnapshotAlignDisks(def,
                                            VIR_DOMAIN_DISK_SNAPSHOT_EXTERNAL,
                                            false) < 0)
                goto cleanup;
        }
9681 9682 9683 9684 9685 9686 9687 9688 9689 9690
    } 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;

9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712
        if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) {
            if (virDomainSnapshotAlignDisks(def,
                                            VIR_DOMAIN_DISK_SNAPSHOT_EXTERNAL,
                                            false) < 0)
                goto cleanup;
            if (qemuDomainSnapshotDiskPrepare(vm, def) < 0)
                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);
        }
9713 9714
    }

9715 9716 9717
    if (snap)
        snap->def = def;
    else if (!(snap = virDomainSnapshotAssignDef(&vm->snapshots, def)))
C
Chris Lalancette 已提交
9718
        goto cleanup;
9719
    def = NULL;
C
Chris Lalancette 已提交
9720

9721 9722
    if (update_current)
        snap->def->current = true;
9723
    if (vm->current_snapshot) {
9724 9725 9726 9727 9728 9729
        if (!(flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE)) {
            snap->def->parent = strdup(vm->current_snapshot->def->name);
            if (snap->def->parent == NULL) {
                virReportOOMError();
                goto cleanup;
            }
9730
        }
9731
        if (update_current) {
9732 9733 9734 9735 9736 9737
            vm->current_snapshot->def->current = false;
            if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                                driver->snapshotDir) < 0)
                goto cleanup;
            vm->current_snapshot = NULL;
        }
9738
    }
9739

C
Chris Lalancette 已提交
9740
    /* actually do the snapshot */
9741 9742
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) {
        /* XXX Should we validate that the redefined snapshot even
9743 9744
         * makes sense, such as checking that qemu-img recognizes the
         * snapshot name in at least one of the domain's disks?  */
9745 9746 9747 9748 9749 9750 9751 9752 9753 9754
    } 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;
9755
    } else if (!virDomainObjIsActive(vm)) {
E
Eric Blake 已提交
9756
        if (qemuDomainSnapshotCreateInactive(driver, vm, snap) < 0)
C
Chris Lalancette 已提交
9757
            goto cleanup;
E
Eric Blake 已提交
9758
    } else {
9759
        if (qemuDomainSnapshotCreateActive(domain->conn, driver,
9760
                                           &vm, snap, flags) < 0)
9761
            goto cleanup;
C
Chris Lalancette 已提交
9762 9763
    }

9764
    /* If we fail after this point, there's not a whole lot we can
C
Chris Lalancette 已提交
9765 9766 9767 9768 9769 9770
     * 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:
9771
    if (vm) {
9772
        if (snapshot && !(flags & VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA)) {
9773
            if (qemuDomainSnapshotWriteMetadata(vm, snap,
9774
                                                driver->snapshotDir) < 0) {
9775 9776
                VIR_WARN("unable to save metadata for snapshot %s",
                         snap->def->name);
9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792
            } 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;
                }
            }
9793
        } else if (snap) {
9794
            virDomainSnapshotObjListRemove(&vm->snapshots, snap);
9795
        }
C
Chris Lalancette 已提交
9796
        virDomainObjUnlock(vm);
9797 9798
    }
    virDomainSnapshotDefFree(def);
9799
    VIR_FREE(xml);
C
Chris Lalancette 已提交
9800 9801 9802 9803 9804 9805
    qemuDriverUnlock(driver);
    return snapshot;
}

static int qemuDomainSnapshotListNames(virDomainPtr domain, char **names,
                                       int nameslen,
9806
                                       unsigned int flags)
C
Chris Lalancette 已提交
9807 9808 9809 9810 9811
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

9812
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
9813 9814
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
9815

C
Chris Lalancette 已提交
9816 9817 9818 9819 9820 9821 9822 9823 9824 9825
    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;
    }

9826 9827
    n = virDomainSnapshotObjListGetNames(&vm->snapshots, names, nameslen,
                                         flags);
C
Chris Lalancette 已提交
9828 9829 9830 9831 9832 9833 9834 9835 9836

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

static int qemuDomainSnapshotNum(virDomainPtr domain,
9837
                                 unsigned int flags)
C
Chris Lalancette 已提交
9838 9839 9840 9841 9842
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

9843
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
9844 9845
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
9846

C
Chris Lalancette 已提交
9847 9848 9849 9850 9851 9852 9853 9854 9855 9856
    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;
    }

9857 9858 9859 9860
    /* All qemu snapshots have libvirt metadata, so
     * VIR_DOMAIN_SNAPSHOT_LIST_METADATA makes no difference to our
     * answer.  */

9861
    n = virDomainSnapshotObjListNum(&vm->snapshots, flags);
C
Chris Lalancette 已提交
9862 9863 9864 9865 9866 9867 9868 9869

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

9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881
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 |
9882 9883
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902

    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 已提交
9903
    n = virDomainSnapshotObjListGetNamesFrom(snap, names, nameslen, flags);
9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921

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 |
9922 9923
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946

    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 已提交
9947
    n = virDomainSnapshotObjListNumFrom(snap, flags);
9948 9949 9950 9951 9952 9953 9954 9955

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

C
Chris Lalancette 已提交
9956 9957
static virDomainSnapshotPtr qemuDomainSnapshotLookupByName(virDomainPtr domain,
                                                           const char *name,
9958
                                                           unsigned int flags)
C
Chris Lalancette 已提交
9959 9960 9961 9962 9963 9964
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;

9965 9966
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993
    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,
9994
                                        unsigned int flags)
C
Chris Lalancette 已提交
9995 9996 9997 9998 9999
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

10000 10001
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020
    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;
}

10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065
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 已提交
10066
static virDomainSnapshotPtr qemuDomainSnapshotCurrent(virDomainPtr domain,
10067
                                                      unsigned int flags)
C
Chris Lalancette 已提交
10068 10069 10070 10071 10072
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotPtr snapshot = NULL;

10073 10074
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099
    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;
}

10100 10101
static char *qemuDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                                          unsigned int flags)
C
Chris Lalancette 已提交
10102 10103 10104 10105 10106 10107 10108
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *xml = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

10109
    virCheckFlags(VIR_DOMAIN_XML_SECURE, NULL);
10110

C
Chris Lalancette 已提交
10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127
    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;
    }

10128
    xml = virDomainSnapshotDefFormat(uuidstr, snap->def, flags, 0);
C
Chris Lalancette 已提交
10129 10130 10131 10132 10133 10134 10135 10136

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

10137 10138
/* The domain is expected to be locked and inactive. */
static int
E
Eric Blake 已提交
10139 10140
qemuDomainSnapshotRevertInactive(struct qemud_driver *driver,
                                 virDomainObjPtr vm,
10141 10142 10143
                                 virDomainSnapshotObjPtr snap)
{
    /* Try all disks, but report failure if we skipped any.  */
E
Eric Blake 已提交
10144
    int ret = qemuDomainSnapshotForEachQcow2(driver, vm, snap, "-a", true);
10145 10146 10147
    return ret > 0 ? -1 : ret;
}

C
Chris Lalancette 已提交
10148
static int qemuDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
10149
                                      unsigned int flags)
C
Chris Lalancette 已提交
10150 10151 10152 10153 10154 10155 10156
{
    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;
10157
    virDomainEventPtr event2 = NULL;
10158
    int detail;
C
Chris Lalancette 已提交
10159 10160
    qemuDomainObjPrivatePtr priv;
    int rc;
10161
    virDomainDefPtr config = NULL;
C
Chris Lalancette 已提交
10162

10163
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING |
10164 10165
                  VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED |
                  VIR_DOMAIN_SNAPSHOT_REVERT_FORCE, -1);
10166

10167 10168 10169 10170 10171 10172 10173 10174 10175 10176
    /* 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
10177 10178
     * Also, several transitions occur even if we fail partway through,
     * and use of FORCE can cause multiple transitions.
10179 10180
     */

C
Chris Lalancette 已提交
10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197
    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;
    }

10198 10199 10200 10201 10202 10203 10204 10205 10206 10207
    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;
    }
10208 10209 10210 10211 10212 10213
    if (snap->def->state == VIR_DOMAIN_DISK_SNAPSHOT) {
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("revert to external disk snapshot not supported "
                          "yet"));
        goto cleanup;
    }
10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231
    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;
        }
    }

10232

10233 10234 10235 10236 10237 10238 10239 10240 10241 10242
    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?  */
    }

10243 10244 10245 10246 10247
    /* 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?  */
10248
    snap->def->current = true;
10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261
    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 已提交
10262

10263
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
C
Chris Lalancette 已提交
10264 10265 10266 10267
        goto cleanup;

    if (snap->def->state == VIR_DOMAIN_RUNNING
        || snap->def->state == VIR_DOMAIN_PAUSED) {
10268 10269 10270 10271 10272 10273 10274 10275 10276
        /* 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 已提交
10277
        if (virDomainObjIsActive(vm)) {
10278
            /* Transitions 5, 6, 8, 9 */
10279 10280
            /* Check for ABI compatibility.  */
            if (config && !virDomainDefCheckABIStability(vm->def, config)) {
10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300
                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;
10301 10302
            }

C
Chris Lalancette 已提交
10303
            priv = vm->privateData;
10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323
            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;
                }
            }
10324
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
C
Chris Lalancette 已提交
10325 10326
            rc = qemuMonitorLoadSnapshot(priv->mon, snap->def->name);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
10327 10328 10329
            if (rc < 0) {
                /* XXX resume domain if it was running before the
                 * failed loadvm attempt? */
10330
                goto endjob;
10331
            }
10332 10333
            if (config)
                virDomainObjAssignDef(vm, config, false);
E
Eric Blake 已提交
10334
        } else {
10335
            /* Transitions 2, 3 */
10336
        load:
10337
            was_stopped = true;
10338 10339 10340
            if (config)
                virDomainObjAssignDef(vm, config, false);

10341
            rc = qemuProcessStart(snapshot->domain->conn, driver, vm, NULL,
10342
                                  true, false, -1, NULL, snap,
10343
                                  VIR_NETDEV_VPORT_PROFILE_OP_CREATE);
10344
            virDomainAuditStart(vm, "from-snapshot", rc >= 0);
10345 10346 10347 10348
            detail = VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT;
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STARTED,
                                             detail);
C
Chris Lalancette 已提交
10349
            if (rc < 0)
10350
                goto endjob;
C
Chris Lalancette 已提交
10351 10352
        }

10353
        /* Touch up domain state.  */
10354 10355 10356
        if (!(flags & VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING) &&
            (snap->def->state == VIR_DOMAIN_PAUSED ||
             (flags & VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED))) {
10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376
            /* 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 已提交
10377
            if (rc < 0)
10378
                goto endjob;
10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393
            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 已提交
10394
        }
E
Eric Blake 已提交
10395
    } else {
10396
        /* Transitions 1, 4, 7 */
10397 10398 10399
        /* 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 已提交
10400 10401 10402
         */

        if (virDomainObjIsActive(vm)) {
10403
            /* Transitions 4, 7 */
J
Jiri Denemark 已提交
10404
            qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT);
10405
            virDomainAuditStop(vm, "from-snapshot");
10406
            detail = VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT;
C
Chris Lalancette 已提交
10407 10408
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STOPPED,
10409
                                             detail);
10410 10411
        }

E
Eric Blake 已提交
10412
        if (qemuDomainSnapshotRevertInactive(driver, vm, snap) < 0) {
10413
            if (!vm->persistent) {
10414
                if (qemuDomainObjEndJob(driver, vm) > 0)
10415
                    qemuDomainRemoveInactive(driver, vm);
10416
                vm = NULL;
10417
                goto cleanup;
10418
            }
10419
            goto endjob;
C
Chris Lalancette 已提交
10420
        }
10421 10422
        if (config)
            virDomainObjAssignDef(vm, config, false);
10423

10424 10425 10426 10427 10428 10429 10430 10431 10432
        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,
10433
                                  VIR_NETDEV_VPORT_PROFILE_OP_CREATE);
10434 10435 10436 10437
            virDomainAuditStart(vm, "from-snapshot", rc >= 0);
            if (rc < 0) {
                if (!vm->persistent) {
                    if (qemuDomainObjEndJob(driver, vm) > 0)
10438
                        qemuDomainRemoveInactive(driver, vm);
10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454
                    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 已提交
10455 10456 10457 10458
    }

    ret = 0;

10459
endjob:
10460
    if (vm && qemuDomainObjEndJob(driver, vm) == 0)
C
Chris Lalancette 已提交
10461 10462
        vm = NULL;

10463
cleanup:
10464 10465 10466 10467 10468 10469 10470 10471 10472
    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;
    }
10473
    if (event) {
C
Chris Lalancette 已提交
10474
        qemuDomainEventQueue(driver, event);
10475 10476 10477
        if (event2)
            qemuDomainEventQueue(driver, event2);
    }
C
Chris Lalancette 已提交
10478 10479 10480 10481 10482 10483 10484
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);

    return ret;
}

10485 10486
struct snap_reparent {
    struct qemud_driver *driver;
10487
    virDomainSnapshotObjPtr parent;
10488 10489
    virDomainObjPtr vm;
    int err;
10490
    virDomainSnapshotObjPtr last;
10491 10492 10493 10494
};

static void
qemuDomainSnapshotReparentChildren(void *payload,
10495
                                   const void *name ATTRIBUTE_UNUSED,
10496 10497 10498 10499 10500 10501 10502 10503 10504
                                   void *data)
{
    virDomainSnapshotObjPtr snap = payload;
    struct snap_reparent *rep = data;

    if (rep->err < 0) {
        return;
    }

10505
    VIR_FREE(snap->def->parent);
10506
    snap->parent = rep->parent;
10507

10508 10509
    if (rep->parent) {
        snap->def->parent = strdup(rep->parent->def->name);
10510

10511 10512 10513 10514
        if (snap->def->parent == NULL) {
            virReportOOMError();
            rep->err = -1;
            return;
10515 10516
        }
    }
10517

10518 10519 10520
    if (!snap->sibling)
        rep->last = snap;

10521 10522
    rep->err = qemuDomainSnapshotWriteMetadata(rep->vm, snap,
                                               rep->driver->snapshotDir);
10523 10524
}

C
Chris Lalancette 已提交
10525 10526 10527 10528 10529 10530 10531 10532
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];
10533
    struct qemu_snap_remove rem;
10534
    struct snap_reparent rep;
10535
    bool metadata_only = !!(flags & VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY);
10536
    int external = 0;
C
Chris Lalancette 已提交
10537

10538
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
10539 10540
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY |
                  VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY, -1);
10541

C
Chris Lalancette 已提交
10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558
    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;
    }

10559 10560 10561 10562 10563
    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 已提交
10564
            virDomainSnapshotForEachDescendant(snap,
10565 10566 10567 10568 10569 10570 10571 10572 10573 10574
                                               qemuDomainSnapshotCountExternal,
                                               &external);
        if (external) {
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                            _("deletion of %d external disk snapshots not "
                              "supported yet"), external);
            goto cleanup;
        }
    }

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

10578 10579
    if (flags & (VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                 VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY)) {
C
Chris Lalancette 已提交
10580 10581
        rem.driver = driver;
        rem.vm = vm;
10582
        rem.metadata_only = metadata_only;
C
Chris Lalancette 已提交
10583
        rem.err = 0;
10584
        rem.current = false;
E
Eric Blake 已提交
10585
        virDomainSnapshotForEachDescendant(snap,
E
Eric Blake 已提交
10586
                                           qemuDomainSnapshotDiscardAll,
10587
                                           &rem);
C
Chris Lalancette 已提交
10588
        if (rem.err < 0)
10589
            goto endjob;
10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601
        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;
                }
            }
10602
            vm->current_snapshot = snap;
10603
        }
10604
    } else if (snap->nchildren) {
10605
        rep.driver = driver;
10606
        rep.parent = snap->parent;
10607 10608
        rep.vm = vm;
        rep.err = 0;
10609
        rep.last = NULL;
E
Eric Blake 已提交
10610
        virDomainSnapshotForEachChild(snap,
10611 10612
                                      qemuDomainSnapshotReparentChildren,
                                      &rep);
10613 10614
        if (rep.err < 0)
            goto endjob;
10615 10616 10617 10618 10619 10620 10621 10622 10623 10624
        /* 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 已提交
10625 10626
    }

10627 10628 10629
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY) {
        snap->nchildren = 0;
        snap->first_child = NULL;
10630
        ret = 0;
10631 10632
    } else {
        virDomainSnapshotDropParent(&vm->snapshots, snap);
10633
        ret = qemuDomainSnapshotDiscard(driver, vm, snap, true, metadata_only);
10634
    }
C
Chris Lalancette 已提交
10635

10636
endjob:
10637
    if (qemuDomainObjEndJob(driver, vm) == 0)
10638 10639
        vm = NULL;

C
Chris Lalancette 已提交
10640 10641 10642 10643 10644 10645
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
10646

10647 10648 10649 10650 10651 10652 10653
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;
10654
    bool hmp;
10655

10656
    virCheckFlags(VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP, -1);
10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673

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

10674 10675 10676 10677 10678 10679 10680 10681 10682
    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;
    }

10683 10684
    priv = vm->privateData;

10685
    qemuDomainObjTaint(driver, vm, VIR_DOMAIN_TAINT_CUSTOM_MONITOR, -1);
10686

10687 10688
    hmp = !!(flags & VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP);

10689
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
10690
    ret = qemuMonitorArbitraryCommand(priv->mon, cmd, result, hmp);
10691
    qemuDomainObjExitMonitorWithDriver(driver, vm);
10692 10693

endjob:
10694
    if (qemuDomainObjEndJob(driver, vm) == 0) {
10695 10696 10697 10698 10699 10700 10701 10702 10703 10704
        vm = NULL;
    }

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

10705

10706 10707 10708 10709 10710 10711 10712 10713 10714 10715
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;
10716
    char *pidfile = NULL;
10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760

    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;

    if (qemuDomainAssignPCIAddresses(def) < 0)
        goto cleanup;

    if (!(vm = virDomainAssignDef(driver->caps,
                                  &driver->domains,
                                  def, false)))
        goto cleanup;

    def = NULL;

10761
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775
        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:
10776
    if (qemuDomainObjEndJob(driver, vm) == 0) {
10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791
        vm = NULL;
        goto cleanup;
    }

cleanup:
    virDomainDefFree(def);
    virDomainChrSourceDefFree(monConfig);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    VIR_FREE(pidfile);
    return dom;
}


10792 10793
static int
qemuDomainOpenConsole(virDomainPtr dom,
10794
                      const char *dev_name,
10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821
                      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;
    }

10822
    if (dev_name) {
10823 10824 10825 10826 10827
        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];
        }
10828
        for (i = 0 ; !chr && i < vm->def->nserials ; i++) {
10829
            if (STREQ(dev_name, vm->def->serials[i]->info.alias))
10830 10831 10832
                chr = vm->def->serials[i];
        }
        for (i = 0 ; !chr && i < vm->def->nparallels ; i++) {
10833
            if (STREQ(dev_name, vm->def->parallels[i]->info.alias))
10834 10835 10836
                chr = vm->def->parallels[i];
        }
    } else {
10837 10838
        if (vm->def->nconsoles)
            chr = vm->def->consoles[0];
10839 10840 10841 10842 10843 10844 10845
        else if (vm->def->nserials)
            chr = vm->def->serials[0];
    }

    if (!chr) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find character device %s"),
10846
                        NULLSTR(dev_name));
10847 10848 10849
        goto cleanup;
    }

10850
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
10851 10852
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"),
10853
                        NULLSTR(dev_name));
10854 10855 10856
        goto cleanup;
    }

10857
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
E
Eric Blake 已提交
10858
                            0, 0, O_RDWR) < 0)
10859 10860 10861 10862 10863 10864 10865 10866 10867 10868
        goto cleanup;

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

E
Eric Blake 已提交
10869 10870 10871
static char *
qemuDiskPathToAlias(virDomainObjPtr vm, const char *path)
{
10872 10873
    int i;
    char *ret = NULL;
10874
    virDomainDiskDefPtr disk;
10875

10876 10877 10878
    i = virDomainDiskIndexByName(vm->def, path, true);
    if (i < 0)
        goto cleanup;
10879

10880
    disk = vm->def->disks[i];
10881

10882 10883 10884 10885 10886 10887 10888 10889
    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;
10890 10891 10892
        }
    }

10893
cleanup:
10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909
    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 已提交
10910
    char *device = NULL;
10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934
    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;
10935 10936 10937 10938 10939 10940 10941

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

10942
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
10943 10944 10945
    priv = vm->privateData;
    ret = qemuMonitorBlockJob(priv->mon, device, bandwidth, info, mode);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
10946 10947

endjob:
10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987
    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)
{
10988 10989
    int ret;

10990
    virCheckFlags(0, -1);
10991 10992 10993 10994 10995
    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;
10996
}
10997

10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066
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;
}

11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 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 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 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 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 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 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396
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;
    bool isActive;
    int idx = -1;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

    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;

    isActive = virDomainObjIsActive(vm);

    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
        if (isActive)
            flags = VIR_DOMAIN_AFFECT_LIVE;
        else
            flags = VIR_DOMAIN_AFFECT_CONFIG;
    }

    if (!isActive && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("domain is not running"));
        goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot change persistent config of a transient domain"));
            goto endjob;
        }
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
            goto endjob;
        idx = virDomainDiskIndexByName(persistentDef, disk, true);
        if (idx < 0)
            goto endjob;
    }

    for (i = 0; i < nparams; i++) {
        virTypedParameterPtr param = &params[i];

        if (param->type != VIR_TYPED_PARAM_ULLONG) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("expected unsigned long long for parameter %s"),
                            param->field);
            goto endjob;
        }

        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;
        } else {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Unrecognized parameter %s"),
                            param->field);
            goto endjob;
        }
    }

    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);
    }
    if (ret < 0)
        goto endjob;

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        sa_assert(persistentDef && idx >= 0);
        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;
    bool isActive;

    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;

    isActive = virDomainObjIsActive(vm);

    if (flags  == VIR_DOMAIN_AFFECT_CURRENT) {
        if (isActive)
            flags = VIR_DOMAIN_AFFECT_LIVE;
        else
            flags = VIR_DOMAIN_AFFECT_CONFIG;
    }

    if (!isActive && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("domain is not running"));
        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) {
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("domain is transient"));
            goto endjob;
        }
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
            goto endjob;

        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];
        param->value.ul = 0;
        param->type = VIR_TYPED_PARAM_ULLONG;

        switch(i) {
        case 0:
            if (virStrcpyStatic(param->field,
                                VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_BYTES_SEC) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Field name '%s' too long"),
                                VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_BYTES_SEC);
                goto endjob;
            }
            param->value.ul = reply.total_bytes_sec;
            break;

        case 1:
            if (virStrcpyStatic(param->field,
                                VIR_DOMAIN_BLOCK_IOTUNE_READ_BYTES_SEC) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Field name '%s' too long"),
                                VIR_DOMAIN_BLOCK_IOTUNE_READ_BYTES_SEC);
                goto endjob;
            }
            param->value.ul = reply.read_bytes_sec;
            break;

        case 2:
            if (virStrcpyStatic(param->field,
                                VIR_DOMAIN_BLOCK_IOTUNE_WRITE_BYTES_SEC) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Field name '%s' too long"),
                                VIR_DOMAIN_BLOCK_IOTUNE_WRITE_BYTES_SEC);
                goto endjob;
            }
            param->value.ul = reply.write_bytes_sec;
            break;

        case 3:
            if (virStrcpyStatic(param->field,
                                VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_IOPS_SEC) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Field name '%s' too long"),
                                VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_IOPS_SEC);
                goto endjob;
            }
            param->value.ul = reply.total_iops_sec;
            break;

        case 4:
            if (virStrcpyStatic(param->field,
                                VIR_DOMAIN_BLOCK_IOTUNE_READ_IOPS_SEC) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Field name '%s' too long"),
                                VIR_DOMAIN_BLOCK_IOTUNE_READ_IOPS_SEC);
                goto endjob;
            }
            param->value.ul = reply.read_iops_sec;
            break;

        case 5:
            if (virStrcpyStatic(param->field,
                                VIR_DOMAIN_BLOCK_IOTUNE_WRITE_IOPS_SEC) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Field name '%s' too long"),
                                VIR_DOMAIN_BLOCK_IOTUNE_WRITE_IOPS_SEC);
                goto endjob;
            }
            param->value.ul = reply.write_iops_sec;
            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;
}
11397

11398
static virDriver qemuDriver = {
11399 11400
    .no = VIR_DRV_QEMU,
    .name = "QEMU",
11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418
    .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 */
11419 11420
    .domainShutdown = qemuDomainShutdown, /* 0.2.0 */
    .domainReboot = qemuDomainReboot, /* 0.9.3 */
11421
    .domainReset = qemuDomainReset, /* 0.9.7 */
11422 11423
    .domainDestroy = qemuDomainDestroy, /* 0.2.0 */
    .domainDestroyFlags = qemuDomainDestroyFlags, /* 0.9.4 */
11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434
    .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 */
11435
    .domainGetControlInfo = qemuDomainGetControlInfo, /* 0.9.3 */
11436 11437
    .domainSave = qemuDomainSave, /* 0.2.0 */
    .domainSaveFlags = qemuDomainSaveFlags, /* 0.9.4 */
11438
    .domainRestore = qemuDomainRestore, /* 0.2.0 */
11439
    .domainRestoreFlags = qemuDomainRestoreFlags, /* 0.9.4 */
11440 11441
    .domainSaveImageGetXMLDesc = qemuDomainSaveImageGetXMLDesc, /* 0.9.4 */
    .domainSaveImageDefineXML = qemuDomainSaveImageDefineXML, /* 0.9.4 */
11442 11443
    .domainCoreDump = qemudDomainCoreDump, /* 0.7.0 */
    .domainScreenshot = qemuDomainScreenshot, /* 0.9.2 */
11444 11445
    .domainSetVcpus = qemuDomainSetVcpus, /* 0.4.4 */
    .domainSetVcpusFlags = qemuDomainSetVcpusFlags, /* 0.8.5 */
11446 11447
    .domainGetVcpusFlags = qemudDomainGetVcpusFlags, /* 0.8.5 */
    .domainPinVcpu = qemudDomainPinVcpu, /* 0.4.4 */
11448
    .domainPinVcpuFlags = qemudDomainPinVcpuFlags, /* 0.9.3 */
E
Eric Blake 已提交
11449
    .domainGetVcpuPinInfo = qemudDomainGetVcpuPinInfo, /* 0.9.3 */
11450 11451 11452 11453 11454 11455 11456 11457 11458
    .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 */
11459 11460
    .domainCreate = qemuDomainStart, /* 0.2.0 */
    .domainCreateWithFlags = qemuDomainStartWithFlags, /* 0.8.2 */
11461 11462
    .domainDefineXML = qemudDomainDefine, /* 0.2.0 */
    .domainUndefine = qemudDomainUndefine, /* 0.2.0 */
11463
    .domainUndefineFlags = qemuDomainUndefineFlags, /* 0.9.4 */
11464 11465 11466 11467 11468 11469 11470 11471 11472
    .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 */
11473
    .domainGetSchedulerParametersFlags = qemuGetSchedulerParametersFlags, /* 0.9.2 */
11474
    .domainSetSchedulerParameters = qemuSetSchedulerParameters, /* 0.7.0 */
11475
    .domainSetSchedulerParametersFlags = qemuSetSchedulerParametersFlags, /* 0.9.2 */
11476
    .domainMigratePerform = qemudDomainMigratePerform, /* 0.5.0 */
11477
    .domainBlockResize = qemuDomainBlockResize, /* 0.9.8 */
11478 11479
    .domainBlockStats = qemuDomainBlockStats, /* 0.4.1 */
    .domainBlockStatsFlags = qemuDomainBlockStatsFlags, /* 0.9.5 */
11480 11481 11482 11483 11484
    .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 */
11485
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
11486
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507
    .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 */
11508
    .domainMigrateGetMaxSpeed = qemuDomainMigrateGetMaxSpeed, /* 0.9.5 */
11509 11510 11511 11512 11513 11514 11515 11516 11517
    .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 */
11518 11519
    .domainSnapshotNumChildren = qemuDomainSnapshotNumChildren, /* 0.9.7 */
    .domainSnapshotListChildrenNames = qemuDomainSnapshotListChildrenNames, /* 0.9.7 */
11520 11521
    .domainSnapshotLookupByName = qemuDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = qemuDomainHasCurrentSnapshot, /* 0.8.0 */
11522
    .domainSnapshotGetParent = qemuDomainSnapshotGetParent, /* 0.9.7 */
11523 11524 11525 11526
    .domainSnapshotCurrent = qemuDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = qemuDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = qemuDomainSnapshotDelete, /* 0.8.0 */
    .qemuDomainMonitorCommand = qemuDomainMonitorCommand, /* 0.8.3 */
11527
    .qemuDomainAttach = qemuDomainAttach, /* 0.9.4 */
11528
    .domainOpenConsole = qemuDomainOpenConsole, /* 0.8.6 */
11529
    .domainOpenGraphics = qemuDomainOpenGraphics, /* 0.9.7 */
11530
    .domainInjectNMI = qemuDomainInjectNMI, /* 0.9.2 */
11531 11532 11533 11534 11535 11536
    .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 */
11537
    .domainSendKey = qemuDomainSendKey, /* 0.9.4 */
11538 11539 11540 11541
    .domainBlockJobAbort = qemuDomainBlockJobAbort, /* 0.9.4 */
    .domainGetBlockJobInfo = qemuDomainGetBlockJobInfo, /* 0.9.4 */
    .domainBlockJobSetSpeed = qemuDomainBlockJobSetSpeed, /* 0.9.4 */
    .domainBlockPull = qemuDomainBlockPull, /* 0.9.4 */
11542
    .isAlive = qemuIsAlive, /* 0.9.8 */
11543
    .nodeSuspendForDuration = nodeSuspendForDuration, /* 0.9.8 */
11544 11545
    .domainSetBlockIoTune = qemuDomainSetBlockIoTune, /* 0.9.8 */
    .domainGetBlockIoTune = qemuDomainGetBlockIoTune, /* 0.9.8 */
11546 11547 11548
};


11549
static virStateDriver qemuStateDriver = {
11550
    .name = "QEMU",
11551 11552 11553 11554
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
11555
};
11556

11557
static void
11558
qemuVMDriverLock(void) {
11559 11560 11561 11562 11563
    qemuDriverLock(qemu_driver);
};


static void
11564
qemuVMDriverUnlock(void) {
11565 11566 11567 11568
    qemuDriverUnlock(qemu_driver);
};


11569 11570 11571 11572 11573 11574 11575 11576 11577
static int
qemuVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                    virHashIterator iter, void *data)
{
    virHashForEach(qemu_driver->domains.objs, iter, data);

    return 0;
}

S
Stefan Berger 已提交
11578 11579
static virNWFilterCallbackDriver qemuCallbackDriver = {
    .name = "QEMU",
11580 11581 11582
    .vmFilterRebuild = qemuVMFilterRebuild,
    .vmDriverLock = qemuVMDriverLock,
    .vmDriverUnlock = qemuVMDriverUnlock,
S
Stefan Berger 已提交
11583 11584
};

11585
int qemuRegister(void) {
11586 11587
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
S
Stefan Berger 已提交
11588
    virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);
11589 11590
    return 0;
}