qemu_driver.c 342.5 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 "macvtap.h"
81
#include "sysinfo.h"
82
#include "domain_nwfilter.h"
83
#include "hooks.h"
84
#include "storage_file.h"
E
Eric Blake 已提交
85
#include "virfile.h"
86
#include "fdstream.h"
87
#include "configmake.h"
H
Hu Tao 已提交
88
#include "threadpool.h"
89
#include "locking/lock_manager.h"
90
#include "locking/domain_lock.h"
91
#include "virkeycode.h"
92

93 94
#define VIR_FROM_THIS VIR_FROM_QEMU

95 96
#define QEMU_NB_MEM_PARAM  3

97 98 99
#if HAVE_LINUX_KVM_H
# include <linux/kvm.h>
#endif
100

101 102
/* device for kvm ioctls */
#define KVM_DEVICE "/dev/kvm"
103

104 105 106 107 108 109 110 111 112 113 114
/* 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

115
#define QEMU_NB_BLKIO_PARAM  1
116

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

119 120
static int qemudShutdown(void);

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

126
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
127

128
struct qemud_driver *qemu_driver = NULL;
129 130


131 132 133 134
struct qemuAutostartData {
    struct qemud_driver *driver;
    virConnectPtr conn;
};
135

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

    if (data->driver->autoStartBypassCache)
        flags |= VIR_DOMAIN_START_BYPASS_CACHE;
147 148

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

168
        if (qemuDomainObjEndJob(data->driver, vm) == 0)
169
            vm = NULL;
170
    }
171

172
cleanup:
173 174
    if (vm)
        virDomainObjUnlock(vm);
175 176
}

177

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

192
    qemuDriverLock(driver);
193
    virHashForEach(driver->domains.objs, qemuAutostartDomain, &data);
194
    qemuDriverUnlock(driver);
195

196 197
    if (conn)
        virConnectClose(conn);
198 199
}

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

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

216
        if (!(driver->securityManager = virSecurityManagerNewStack(mgr,
E
Eric Blake 已提交
217 218 219
                                                                   dac))) {

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

226
    return 0;
227

228
error:
229
    VIR_ERROR(_("Failed to initialize security drivers"));
230 231 232
    virSecurityManagerFree(mgr);
    return -1;
}
233

234

235 236 237 238 239
static virCapsPtr
qemuCreateCapabilities(virCapsPtr oldcaps,
                       struct qemud_driver *driver)
{
    virCapsPtr caps;
240

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

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

255 256
    qemuDomainSetPrivateDataHooks(caps);
    qemuDomainSetNamespaceHooks(caps);
257

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

264 265
    /* Security driver data */
    const char *doi, *model;
266

267 268 269 270 271 272 273
    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;
274
    }
275

276 277
    VIR_DEBUG("Initialized caps for security driver \"%s\" with "
              "DOI \"%s\"", model, doi);
278

279
    return caps;
280

281 282 283 284
no_memory:
    virReportOOMError();
err_exit:
    virCapabilitiesFree(caps);
285 286 287
    return NULL;
}

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

308 309 310 311
    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);
312
        goto cleanup;
313 314
    }

315 316
    VIR_INFO("Scanning for snapshots for domain %s in %s", vm->def->name,
             snapDir);
317

318 319 320 321 322
    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)));
323
        goto cleanup;
324 325
    }

326 327 328
    while ((entry = readdir(dir))) {
        if (entry->d_name[0] == '.')
            continue;
329

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

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

339 340 341 342 343 344 345 346
        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;
        }
347

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

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

369 370
        VIR_FREE(fullpath);
        VIR_FREE(xmlStr);
371 372
    }

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

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

383 384 385 386 387 388 389 390
    /* 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.
     */
391

392
    virResetLastError();
393

394 395 396 397
cleanup:
    if (dir)
        closedir(dir);
    VIR_FREE(snapDir);
398 399 400
    virDomainObjUnlock(vm);
}

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

413 414
    if (VIR_ALLOC(qemu_driver) < 0)
        return -1;
415

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

424 425
    /* Don't have a dom0 so start from 1 */
    qemu_driver->nextvmid = 1;
426

427 428
    if (virDomainObjListInit(&qemu_driver->domains) < 0)
        goto out_of_memory;
429

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

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

443 444 445
    /* read the host sysinfo */
    if (privileged)
        qemu_driver->hostsysinfo = virSysinfoRead();
446

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

452 453
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
            goto out_of_memory;
454

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

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

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

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

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

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

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

544 545 546 547 548 549 550
    /* 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;
551

552
    VIR_FREE(base);
553

554 555 556 557 558
    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)));
559 560
    }

561 562 563 564
    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
        goto error;
    }
    VIR_FREE(driverConf);
565

566 567 568 569 570 571 572 573
    /* 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;
    }

574 575
    if (qemuSecurityInit(qemu_driver) < 0)
        goto error;
576

577 578 579
    if ((qemu_driver->caps = qemuCreateCapabilities(NULL,
                                                    qemu_driver)) == NULL)
        goto error;
580

581
    if ((qemu_driver->activePciHostdevs = pciDeviceListNew()) == NULL)
582
        goto error;
583

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

611 612 613 614 615 616
    /* 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
617
     */
618 619 620 621 622
    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;
623

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

639
        qemu_driver->hugepage_path = mempath;
640
    }
641

642 643 644
    if (qemuProcessAutoDestroyInit(qemu_driver) < 0)
        goto error;

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

654 655 656
    conn = virConnectOpen(qemu_driver->privileged ?
                          "qemu:///system" :
                          "qemu:///session");
657

658
    qemuProcessReconnectAll(conn, qemu_driver);
659

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

669

670 671
    virHashForEach(qemu_driver->domains.objs, qemuDomainSnapshotLoad,
                   qemu_driver->snapshotDir);
672

673
    qemu_driver->workerPool = virThreadPoolNew(0, 1, 0, processWatchdogEvent, qemu_driver);
674 675
    if (!qemu_driver->workerPool)
        goto error;
676

677 678 679 680
    qemuDriverUnlock(qemu_driver);

    qemuAutostartDomains(qemu_driver);

681 682
    if (conn)
        virConnectClose(conn);
683

684
    return 0;
685

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

699 700 701
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;
702

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

713 714 715 716 717 718 719 720 721 722
/**
 * 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;
723

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

733
    qemuAutostartDomains(qemu_driver);
734

735 736
    return 0;
}
S
Stefan Berger 已提交
737

738 739 740 741 742 743 744 745 746 747 748
/**
 * 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;
749

750 751
    if (!qemu_driver)
        return 0;
752

753 754 755 756 757 758
    /* 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;
}
759

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

769 770
    if (!qemu_driver)
        return -1;
771

772 773 774
    qemuDriverLock(qemu_driver);
    pciDeviceListFree(qemu_driver->activePciHostdevs);
    virCapabilitiesFree(qemu_driver->caps);
775

776 777
    virDomainObjListDeinit(&qemu_driver->domains);
    virBitmapFree(qemu_driver->reservedVNCPorts);
778

779
    virSysinfoDefFree(qemu_driver->hostsysinfo);
780

781 782
    qemuProcessAutoDestroyShutdown(qemu_driver);

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

805
    virSecurityManagerFree(qemu_driver->securityManager);
806

807
    ebtablesContextFree(qemu_driver->ebtables);
808

809 810 811 812
    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 已提交
813 814
    }

815
    /* Free domain callback list */
816
    virDomainEventStateFree(qemu_driver->domainEventState);
D
Daniel P. Berrange 已提交
817

818 819
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);
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 924 925
        return 1;
    default:
        return 0;
D
Daniel Veillard 已提交
926 927 928
    }
}

929
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
930
    return "QEMU";
931 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
static int kvmGetMaxVCPUs(void) {
    int maxvcpus = 1;

    int r, fd;
951

952 953
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
954
        virReportSystemError(errno, _("Unable to open %s"), KVM_DEVICE);
955
        return -1;
956 957 958 959 960 961
    }

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

962
    VIR_FORCE_CLOSE(fd);
963 964 965 966
    return maxvcpus;
}


E
Eric Blake 已提交
967 968 969 970
static char *
qemuGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    struct qemud_driver *driver = conn->privateData;
971
    virBuffer buf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
972 973 974 975 976 977 978 979 980

    virCheckFlags(0, NULL);

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

981 982 983 984 985 986 987
    if (virSysinfoFormat(&buf, driver->hostsysinfo) < 0)
        return NULL;
    if (virBufferError(&buf)) {
        virReportOOMError();
        return NULL;
    }
    return virBufferContentAndReset(&buf);
E
Eric Blake 已提交
988 989
}

990
static int qemudGetMaxVCPUs(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
991 992 993
    if (!type)
        return 16;

994
    if (STRCASEEQ(type, "qemu"))
995 996
        return 16;

997
    if (STRCASEEQ(type, "kvm"))
998
        return kvmGetMaxVCPUs();
999

1000
    if (STRCASEEQ(type, "kqemu"))
1001
        return 1;
1002

1003 1004
    qemuReportError(VIR_ERR_INVALID_ARG,
                    _("unknown type '%s'"), type);
1005 1006 1007
    return -1;
}

1008

1009
static char *qemudGetCapabilities(virConnectPtr conn) {
1010
    struct qemud_driver *driver = conn->privateData;
1011
    virCapsPtr caps = NULL;
1012
    char *xml = NULL;
1013

1014
    qemuDriverLock(driver);
1015

1016
    if ((caps = qemuCreateCapabilities(qemu_driver->caps,
1017
                                       qemu_driver)) == NULL) {
1018 1019 1020
        virCapabilitiesFree(caps);
        goto cleanup;
    }
1021

1022
    virCapabilitiesFree(qemu_driver->caps);
1023 1024 1025
    qemu_driver->caps = caps;

    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1026
        virReportOOMError();
1027 1028

cleanup:
1029
    qemuDriverUnlock(driver);
1030

1031
    return xml;
1032 1033 1034
}


1035 1036 1037 1038 1039
static int
qemudGetProcessInfo(unsigned long long *cpuTime, int *lastCpu, int pid,
                    int tid)
{
    char *proc;
D
Daniel P. Berrange 已提交
1040
    FILE *pidinfo;
1041
    unsigned long long usertime, systime;
1042 1043
    int cpu;
    int ret;
D
Daniel P. Berrange 已提交
1044

1045
    if (tid)
1046
        ret = virAsprintf(&proc, "/proc/%d/task/%d/stat", pid, tid);
1047
    else
1048 1049
        ret = virAsprintf(&proc, "/proc/%d/stat", pid);
    if (ret < 0)
D
Daniel P. Berrange 已提交
1050 1051 1052 1053
        return -1;

    if (!(pidinfo = fopen(proc, "r"))) {
        /* VM probably shut down, so fake 0 */
1054 1055 1056 1057
        if (cpuTime)
            *cpuTime = 0;
        if (lastCpu)
            *lastCpu = 0;
1058
        VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1059 1060
        return 0;
    }
1061
    VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1062

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

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
1084 1085 1086 1087 1088
    if (cpuTime)
        *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
    if (lastCpu)
        *lastCpu = cpu;

D
Daniel P. Berrange 已提交
1089

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

1093
    VIR_FORCE_FCLOSE(pidinfo);
D
Daniel P. Berrange 已提交
1094 1095 1096 1097 1098

    return 0;
}


1099
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1100
                                          int id) {
1101 1102 1103 1104
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1105
    qemuDriverLock(driver);
1106
    vm  = virDomainFindByID(&driver->domains, id);
1107
    qemuDriverUnlock(driver);
1108 1109

    if (!vm) {
1110 1111
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching id %d"), id);
1112
        goto cleanup;
1113 1114
    }

1115
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1116
    if (dom) dom->id = vm->def->id;
1117 1118

cleanup:
1119 1120
    if (vm)
        virDomainObjUnlock(vm);
1121 1122
    return dom;
}
1123

1124
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1125
                                            const unsigned char *uuid) {
1126 1127 1128
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1129

1130
    qemuDriverLock(driver);
1131
    vm = virDomainFindByUUID(&driver->domains, uuid);
1132 1133
    qemuDriverUnlock(driver);

1134
    if (!vm) {
1135 1136
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
1137 1138
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1139
        goto cleanup;
1140 1141
    }

1142
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1143
    if (dom) dom->id = vm->def->id;
1144 1145

cleanup:
1146 1147
    if (vm)
        virDomainObjUnlock(vm);
1148 1149
    return dom;
}
1150

1151
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1152
                                            const char *name) {
1153 1154 1155
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1156

1157
    qemuDriverLock(driver);
1158
    vm = virDomainFindByName(&driver->domains, name);
1159 1160
    qemuDriverUnlock(driver);

1161
    if (!vm) {
1162 1163
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), name);
1164
        goto cleanup;
1165 1166
    }

1167
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1168
    if (dom) dom->id = vm->def->id;
1169 1170

cleanup:
1171 1172
    if (vm)
        virDomainObjUnlock(vm);
1173 1174 1175
    return dom;
}

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186

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

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

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

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

1249
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1250 1251 1252
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

1253
    qemuDriverLock(driver);
1254
    if (qemuCapsExtractVersion(driver->caps, &driver->qemuVersion) < 0)
1255
        goto cleanup;
1256

1257
    *version = driver->qemuVersion;
1258 1259 1260
    ret = 0;

cleanup:
1261
    qemuDriverUnlock(driver);
1262
    return ret;
D
Daniel P. Berrange 已提交
1263 1264
}

1265
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1266
    struct qemud_driver *driver = conn->privateData;
1267
    int n;
1268

1269
    qemuDriverLock(driver);
1270
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1271
    qemuDriverUnlock(driver);
1272

1273
    return n;
D
Daniel P. Berrange 已提交
1274
}
1275

1276
static int qemudNumDomains(virConnectPtr conn) {
1277
    struct qemud_driver *driver = conn->privateData;
1278
    int n;
1279

1280
    qemuDriverLock(driver);
1281
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1282
    qemuDriverUnlock(driver);
1283

1284
    return n;
D
Daniel P. Berrange 已提交
1285
}
1286

1287
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
1288
                                      unsigned int flags) {
1289
    struct qemud_driver *driver = conn->privateData;
1290
    virDomainDefPtr def;
1291
    virDomainObjPtr vm = NULL;
1292
    virDomainPtr dom = NULL;
1293
    virDomainEventPtr event = NULL;
1294
    virDomainEventPtr event2 = NULL;
D
Daniel P. Berrange 已提交
1295

1296 1297
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
                  VIR_DOMAIN_START_AUTODESTROY, NULL);
1298

1299
    qemuDriverLock(driver);
1300
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1301
                                        QEMU_EXPECTED_VIRT_TYPES,
1302
                                        VIR_DOMAIN_XML_INACTIVE)))
1303
        goto cleanup;
1304

1305
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
1306 1307
        goto cleanup;

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

1311 1312 1313
    if (qemudCanonicalizeMachine(driver, def) < 0)
        goto cleanup;

1314
    if (qemuDomainAssignPCIAddresses(def) < 0)
1315 1316
        goto cleanup;

1317
    if (!(vm = virDomainAssignDef(driver->caps,
1318
                                  &driver->domains,
1319
                                  def, false)))
1320 1321 1322
        goto cleanup;

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

1324
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
1325 1326
        goto cleanup; /* XXXX free the 'vm' we created ? */

1327 1328
    if (qemuProcessStart(conn, driver, vm, NULL,
                         (flags & VIR_DOMAIN_START_PAUSED) != 0,
1329
                         (flags & VIR_DOMAIN_START_AUTODESTROY) != 0,
1330
                         -1, NULL, NULL, VIR_VM_OP_CREATE) < 0) {
1331
        virDomainAuditStart(vm, "booted", false);
1332
        if (qemuDomainObjEndJob(driver, vm) > 0)
1333
            qemuDomainRemoveInactive(driver, vm);
1334
        vm = NULL;
1335
        goto cleanup;
D
Daniel P. Berrange 已提交
1336
    }
1337 1338 1339 1340

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
    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);
    }
1351
    virDomainAuditStart(vm, "booted", true);
D
Daniel P. Berrange 已提交
1352

1353
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1354
    if (dom) dom->id = vm->def->id;
1355

1356
    if (vm &&
1357
        qemuDomainObjEndJob(driver, vm) == 0)
1358
        vm = NULL;
1359

1360 1361
cleanup:
    virDomainDefFree(def);
1362 1363
    if (vm)
        virDomainObjUnlock(vm);
1364
    if (event) {
1365
        qemuDomainEventQueue(driver, event);
1366 1367 1368
        if (event2)
            qemuDomainEventQueue(driver, event2);
    }
1369
    qemuDriverUnlock(driver);
1370
    return dom;
D
Daniel P. Berrange 已提交
1371 1372 1373
}


1374
static int qemudDomainSuspend(virDomainPtr dom) {
1375 1376 1377
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1378
    virDomainEventPtr event = NULL;
1379
    qemuDomainObjPrivatePtr priv;
1380 1381
    virDomainPausedReason reason;
    int eventDetail;
1382

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

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

    priv = vm->privateData;

1401
    if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_OUT) {
1402 1403
        reason = VIR_DOMAIN_PAUSED_MIGRATION;
        eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED;
1404
    } else {
1405 1406 1407
        reason = VIR_DOMAIN_PAUSED_USER;
        eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_PAUSED;
    }
1408

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

1429
endjob:
1430
    if (qemuDomainObjEndJob(driver, vm) == 0)
1431
        vm = NULL;
1432

1433
cleanup:
1434 1435
    if (vm)
        virDomainObjUnlock(vm);
1436

1437
    if (event)
1438
        qemuDomainEventQueue(driver, event);
1439
    qemuDriverUnlock(driver);
1440
    return ret;
D
Daniel P. Berrange 已提交
1441 1442 1443
}


1444
static int qemudDomainResume(virDomainPtr dom) {
1445 1446 1447
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1448
    virDomainEventPtr event = NULL;
1449

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

D
Daniel P. Berrange 已提交
1453
    if (!vm) {
1454 1455
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1456 1457
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1458
        goto cleanup;
D
Daniel P. Berrange 已提交
1459
    }
1460

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

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

1486
endjob:
1487
    if (qemuDomainObjEndJob(driver, vm) == 0)
1488
        vm = NULL;
1489

1490
cleanup:
1491 1492
    if (vm)
        virDomainObjUnlock(vm);
1493
    if (event)
1494
        qemuDomainEventQueue(driver, event);
1495
    qemuDriverUnlock(driver);
1496
    return ret;
D
Daniel P. Berrange 已提交
1497 1498 1499
}


1500
static int qemuDomainShutdown(virDomainPtr dom) {
1501 1502 1503
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1504
    qemuDomainObjPrivatePtr priv;
1505

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

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

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

D
Daniel P. Berrange 已提交
1521
    if (!virDomainObjIsActive(vm)) {
1522 1523
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1524
        goto endjob;
1525 1526
    }

1527 1528
    qemuDomainSetFakeReboot(driver, vm, false);

1529
    priv = vm->privateData;
1530
    qemuDomainObjEnterMonitor(driver, vm);
1531
    ret = qemuMonitorSystemPowerdown(priv->mon);
1532
    qemuDomainObjExitMonitor(driver, vm);
1533

1534
endjob:
1535
    if (qemuDomainObjEndJob(driver, vm) == 0)
1536
        vm = NULL;
1537

1538
cleanup:
1539 1540
    if (vm)
        virDomainObjUnlock(vm);
1541
    return ret;
1542 1543 1544
}


1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
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;
    }

1565 1566
    priv = vm->privateData;

1567
    if (qemuCapsGet(priv->qemuCaps, QEMU_CAPS_MONITOR_JSON)) {
1568 1569 1570 1571 1572 1573
        if (!qemuCapsGet(priv->qemuCaps, QEMU_CAPS_NO_SHUTDOWN)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("Reboot is not supported with this QEMU binary"));
            goto cleanup;
        }

1574
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1575 1576 1577 1578 1579 1580 1581 1582
            goto cleanup;

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

1583
        qemuDomainObjEnterMonitor(driver, vm);
1584
        ret = qemuMonitorSystemPowerdown(priv->mon);
1585
        qemuDomainObjExitMonitor(driver, vm);
1586

1587 1588
        if (ret == 0)
            qemuDomainSetFakeReboot(driver, vm, true);
1589 1590

    endjob:
1591
        if (qemuDomainObjEndJob(driver, vm) == 0)
1592 1593
            vm = NULL;
    } else {
1594
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
                        _("Reboot is not supported without the JSON monitor"));
    }

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


1605 1606 1607 1608 1609 1610 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
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;
}


1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
/* 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)++;
}

1667 1668 1669 1670
static int
qemuDomainDestroyFlags(virDomainPtr dom,
                       unsigned int flags)
{
1671 1672 1673
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1674
    virDomainEventPtr event = NULL;
1675

1676 1677
    virCheckFlags(0, -1);

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

1688
    qemuDomainSetFakeReboot(driver, vm, false);
1689

1690 1691 1692 1693 1694
    /* 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
     */
1695
    qemuProcessKill(vm, false);
1696

1697
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_DESTROY) < 0)
1698 1699
        goto cleanup;

D
Daniel P. Berrange 已提交
1700
    if (!virDomainObjIsActive(vm)) {
1701 1702
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1703
        goto endjob;
1704
    }
1705

J
Jiri Denemark 已提交
1706
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_DESTROYED);
1707 1708 1709
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1710
    virDomainAuditStop(vm, "destroyed");
1711

1712
    if (!vm->persistent) {
1713
        if (qemuDomainObjEndJob(driver, vm) > 0)
1714
            qemuDomainRemoveInactive(driver, vm);
1715 1716
        vm = NULL;
    }
1717 1718
    ret = 0;

1719
endjob:
1720
    if (vm &&
1721
        qemuDomainObjEndJob(driver, vm) == 0)
1722
        vm = NULL;
1723

1724
cleanup:
1725 1726
    if (vm)
        virDomainObjUnlock(vm);
1727 1728
    if (event)
        qemuDomainEventQueue(driver, event);
1729
    qemuDriverUnlock(driver);
1730
    return ret;
D
Daniel P. Berrange 已提交
1731 1732
}

1733 1734 1735 1736 1737
static int
qemuDomainDestroy(virDomainPtr dom)
{
    return qemuDomainDestroyFlags(dom, 0);
}
D
Daniel P. Berrange 已提交
1738

1739
static char *qemudDomainGetOSType(virDomainPtr dom) {
1740 1741 1742
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1743

1744
    qemuDriverLock(driver);
1745
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1746
    qemuDriverUnlock(driver);
1747
    if (!vm) {
1748 1749
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1750 1751
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1752
        goto cleanup;
1753 1754
    }

1755
    if (!(type = strdup(vm->def->os.type)))
1756
        virReportOOMError();
1757 1758

cleanup:
1759 1760
    if (vm)
        virDomainObjUnlock(vm);
1761 1762 1763
    return type;
}

1764 1765
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
1766 1767 1768
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
1769

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

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

1782
    ret = vm->def->mem.max_balloon;
1783 1784

cleanup:
1785 1786
    if (vm)
        virDomainObjUnlock(vm);
1787
    return ret;
1788 1789
}

1790 1791
static int qemudDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
                                     unsigned int flags) {
1792
    struct qemud_driver *driver = dom->conn->privateData;
1793
    qemuDomainObjPrivatePtr priv;
1794
    virDomainObjPtr vm;
1795
    virDomainDefPtr persistentDef = NULL;
1796
    int ret = -1, r;
1797
    bool isActive;
1798

1799 1800
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
1801
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1802

1803
    qemuDriverLock(driver);
1804
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1805
    qemuDriverUnlock(driver);
1806
    if (!vm) {
1807 1808
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1809 1810
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1811
        goto cleanup;
1812 1813
    }

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

1817 1818
    isActive = virDomainObjIsActive(vm);

1819
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
1820
        if (isActive)
1821
            flags = VIR_DOMAIN_AFFECT_LIVE;
1822
        else
1823
            flags = VIR_DOMAIN_AFFECT_CONFIG;
1824
    }
1825 1826
    if (flags == VIR_DOMAIN_MEM_MAXIMUM) {
        if (isActive)
1827
            flags = VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_MEM_MAXIMUM;
1828
        else
1829
            flags = VIR_DOMAIN_AFFECT_CONFIG | VIR_DOMAIN_MEM_MAXIMUM;
1830
    }
1831

1832
    if (!isActive && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
1833 1834 1835 1836 1837
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

1838
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
1839 1840 1841 1842 1843 1844 1845 1846
        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;
    }
1847

1848 1849 1850
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */

1851
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
1852 1853 1854
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot resize the maximum memory on an "
                              "active domain"));
1855
            goto endjob;
1856
        }
1857

1858
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
1859 1860
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
1861 1862 1863 1864
            persistentDef->mem.max_balloon = newmem;
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
1865 1866 1867
            goto endjob;
        }

1868 1869 1870 1871 1872 1873 1874 1875 1876
    } 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;
        }

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

1895
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
1896
            sa_assert(persistentDef);
1897 1898 1899 1900
            persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
            goto endjob;
        }
1901
    }
1902

1903
    ret = 0;
1904
endjob:
1905
    if (qemuDomainObjEndJob(driver, vm) == 0)
1906
        vm = NULL;
1907

1908
cleanup:
1909 1910
    if (vm)
        virDomainObjUnlock(vm);
1911
    return ret;
1912 1913
}

1914 1915
static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem)
{
1916
    return qemudDomainSetMemoryFlags(dom, newmem, VIR_DOMAIN_AFFECT_LIVE);
1917 1918
}

1919 1920 1921 1922 1923
static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return qemudDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
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;

1951
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
1952
        goto cleanup;
1953 1954 1955 1956 1957 1958 1959

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

1960
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
1961 1962
    ret = qemuMonitorInjectNMI(priv->mon);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
1963 1964

endjob:
1965
    if (qemuDomainObjEndJob(driver, vm) == 0) {
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
        vm = NULL;
        goto cleanup;
    }

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

1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
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);

1991 1992
    /* translate the keycode to RFB for qemu driver */
    if (codeset != VIR_KEYCODE_SET_RFB) {
1993 1994 1995 1996
        int i;
        int keycode;

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

2031
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2032 2033
    ret = qemuMonitorSendKey(priv->mon, holdtime, keycodes, nkeycodes);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
2034 2035 2036

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
2037 2038 2039 2040 2041 2042 2043 2044 2045
        vm = NULL;

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

2046
static int qemudDomainGetInfo(virDomainPtr dom,
2047 2048
                              virDomainInfoPtr info)
{
2049 2050 2051
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2052 2053
    int err;
    unsigned long balloon;
2054

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

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

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

2078
    info->maxMem = vm->def->mem.max_balloon;
2079

D
Daniel P. Berrange 已提交
2080
    if (virDomainObjIsActive(vm)) {
2081
        qemuDomainObjPrivatePtr priv = vm->privateData;
2082 2083 2084

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

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

2120
    info->nrVirtCpu = vm->def->vcpus;
2121 2122 2123
    ret = 0;

cleanup:
2124 2125
    if (vm)
        virDomainObjUnlock(vm);
2126
    return ret;
D
Daniel P. Berrange 已提交
2127 2128
}

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

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

2162 2163 2164 2165 2166 2167 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
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;
2198
    } else if (priv->job.active) {
2199 2200 2201 2202
        if (!priv->monStart) {
            info->state = VIR_DOMAIN_CONTROL_JOB;
            if (virTimeMs(&info->stateTime) < 0)
                goto cleanup;
2203
            info->stateTime -= priv->job.start;
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
        } else {
            info->state = VIR_DOMAIN_CONTROL_OCCUPIED;
            if (virTimeMs(&info->stateTime) < 0)
                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 已提交
2222

E
Eric Blake 已提交
2223 2224
#define QEMUD_SAVE_MAGIC   "LibvirtQemudSave"
#define QEMUD_SAVE_PARTIAL "LibvirtQemudPart"
2225 2226
#define QEMUD_SAVE_VERSION 2

E
Eric Blake 已提交
2227 2228
verify(sizeof(QEMUD_SAVE_MAGIC) == sizeof(QEMUD_SAVE_PARTIAL));

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

    QEMUD_SAVE_FORMAT_LAST
2244
};
2245

2246 2247 2248 2249 2250
VIR_ENUM_DECL(qemudSaveCompression)
VIR_ENUM_IMPL(qemudSaveCompression, QEMUD_SAVE_FORMAT_LAST,
              "raw",
              "gzip",
              "bzip2",
2251 2252
              "xz",
              "lzop")
2253

2254 2255
struct qemud_save_header {
    char magic[sizeof(QEMUD_SAVE_MAGIC)-1];
2256 2257 2258 2259 2260
    uint32_t version;
    uint32_t xml_len;
    uint32_t was_running;
    uint32_t compressed;
    uint32_t unused[15];
2261 2262
};

2263 2264 2265 2266 2267 2268 2269 2270 2271
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);
}


2272
/* return -errno on failure, or 0 on success */
E
Eric Blake 已提交
2273 2274 2275 2276
static int
qemuDomainSaveHeader(int fd, const char *path, char *xml,
                     struct qemud_save_header *header)
{
2277 2278
    int ret = 0;

E
Eric Blake 已提交
2279
    if (safewrite(fd, header, sizeof(*header)) != sizeof(*header)) {
2280
        ret = -errno;
2281
        qemuReportError(VIR_ERR_OPERATION_FAILED,
2282
                        _("failed to write header to domain save file '%s'"),
E
Eric Blake 已提交
2283
                        path);
2284 2285 2286
        goto endjob;
    }

E
Eric Blake 已提交
2287
    if (safewrite(fd, xml, header->xml_len) != header->xml_len) {
2288
        ret = -errno;
2289
        qemuReportError(VIR_ERR_OPERATION_FAILED,
E
Eric Blake 已提交
2290
                         _("failed to write xml to '%s'"), path);
2291 2292 2293 2294 2295 2296
        goto endjob;
    }
endjob:
    return ret;
}

2297 2298 2299 2300 2301 2302 2303 2304 2305
/* 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 已提交
2306 2307 2308 2309 2310 2311 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
/* 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;
}

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

2440 2441 2442
    if (qemuProcessAutoDestroyActive(driver, vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is marked for auto destroy"));
2443
        goto cleanup;
2444 2445
    }

2446
    memset(&header, 0, sizeof(header));
E
Eric Blake 已提交
2447
    memcpy(header.magic, QEMUD_SAVE_PARTIAL, sizeof(header.magic));
2448 2449
    header.version = QEMUD_SAVE_VERSION;

2450
    header.compressed = compressed;
2451

2452
    priv = vm->privateData;
2453

2454 2455
    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             QEMU_ASYNC_JOB_SAVE) < 0)
2456 2457
        goto cleanup;

2458 2459
    memset(&priv->job.info, 0, sizeof(priv->job.info));
    priv->job.info.type = VIR_DOMAIN_JOB_UNBOUNDED;
2460

2461
    /* Pause */
J
Jiri Denemark 已提交
2462
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
2463
        header.was_running = 1;
2464 2465
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_SAVE) < 0)
2466
            goto endjob;
2467 2468 2469 2470 2471 2472

        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto endjob;
        }
2473
    }
2474 2475 2476 2477 2478
    /* 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;
2479

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

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

2544
    /* Write header to file, followed by XML */
E
Eric Blake 已提交
2545
    if (qemuDomainSaveHeader(fd, path, xml, &header) < 0) {
2546 2547 2548 2549
        VIR_FORCE_CLOSE(fd);
        goto endjob;
    }

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

    /* 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;
    }
2583 2584
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("unable to close %s"), path);
2585
        goto endjob;
2586 2587
    }

2588 2589
    ret = 0;

2590
    /* Shut it down */
J
Jiri Denemark 已提交
2591
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_SAVED);
2592
    virDomainAuditStop(vm, "saved");
2593 2594 2595
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2596
    if (!vm->persistent) {
2597
        if (qemuDomainObjEndAsyncJob(driver, vm) > 0)
2598
            qemuDomainRemoveInactive(driver, vm);
2599 2600
        vm = NULL;
    }
2601

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

2617
cleanup:
2618
    VIR_FORCE_CLOSE(fd);
2619
    virFileDirectFdFree(directFd);
2620
    VIR_FREE(xml);
E
Eric Blake 已提交
2621
    if (ret != 0 && needUnlink)
2622
        unlink(path);
2623 2624
    if (event)
        qemuDomainEventQueue(driver, event);
2625 2626
    if (vm)
        virDomainObjUnlock(vm);
2627
    return ret;
D
Daniel P. Berrange 已提交
2628 2629
}

2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645
/* 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;
}

2646 2647 2648
static int
qemuDomainSaveFlags(virDomainPtr dom, const char *path, const char *dxml,
                    unsigned int flags)
2649 2650 2651
{
    struct qemud_driver *driver = dom->conn->privateData;
    int compressed;
2652 2653 2654
    int ret = -1;
    virDomainObjPtr vm = NULL;

2655 2656 2657
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
                  VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
2658

2659
    qemuDriverLock(driver);
2660 2661 2662 2663 2664 2665 2666 2667 2668

    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"));
2669
            goto cleanup;
2670
        }
2671 2672 2673 2674
        if (!qemudCompressProgramAvailable(compressed)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Compression program for image format "
                                    "in configuration file isn't available"));
2675
            goto cleanup;
2676
        }
2677 2678
    }

2679 2680 2681 2682 2683 2684 2685 2686 2687
    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;
    }

2688 2689 2690 2691 2692 2693
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2694
    ret = qemuDomainSaveInternal(driver, dom, vm, path, compressed,
2695
                                 dxml, flags);
2696
    vm = NULL;
2697 2698 2699 2700 2701 2702 2703

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

    return ret;
2704 2705
}

2706 2707 2708 2709 2710 2711
static int
qemuDomainSave(virDomainPtr dom, const char *path)
{
    return qemuDomainSaveFlags(dom, path, NULL, 0);
}

2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732
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;

2733 2734 2735
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
                  VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
2736 2737 2738 2739 2740 2741 2742 2743

    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);
2744
        goto cleanup;
2745 2746
    }

2747 2748 2749 2750 2751
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }
2752 2753 2754 2755 2756
    if (!vm->persistent) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot do managed save for transient domain"));
        goto cleanup;
    }
2757

2758 2759
    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
2760
        goto cleanup;
2761

2762
    VIR_INFO("Saving state to %s", name);
2763 2764

    compressed = QEMUD_SAVE_FORMAT_RAW;
2765
    ret = qemuDomainSaveInternal(driver, dom, vm, name, compressed,
2766
                                 NULL, flags);
2767
    vm = NULL;
2768 2769 2770 2771 2772

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
2773 2774 2775
    VIR_FREE(name);

    return ret;
2776 2777 2778 2779 2780 2781 2782 2783 2784 2785
}

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

2786
    virCheckFlags(0, -1);
2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819

    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;

2820
    virCheckFlags(0, -1);
2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844

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

2846 2847 2848 2849
static int
doCoreDump(struct qemud_driver *driver,
           virDomainObjPtr vm,
           const char *path,
2850 2851
           enum qemud_save_formats compress,
           bool bypass_cache)
H
Hu Tao 已提交
2852 2853 2854
{
    int fd = -1;
    int ret = -1;
2855 2856
    virFileDirectFdPtr directFd = NULL;
    int directFlag = 0;
H
Hu Tao 已提交
2857 2858

    /* Create an empty file with appropriate ownership.  */
2859 2860 2861 2862 2863 2864 2865 2866
    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 已提交
2867 2868 2869 2870 2871 2872
    /* 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 已提交
2873 2874
        goto cleanup;

2875 2876 2877
    if (bypass_cache && (directFd = virFileDirectFdNew(&fd, path)) == NULL)
        goto cleanup;

2878
    if (qemuMigrationToFile(driver, vm, fd, 0, path,
E
Eric Blake 已提交
2879
                            qemuCompressProgramName(compress), false,
2880
                            QEMU_ASYNC_JOB_DUMP) < 0)
2881 2882
        goto cleanup;

H
Hu Tao 已提交
2883 2884 2885 2886 2887 2888
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno,
                             _("unable to save file %s"),
                             path);
        goto cleanup;
    }
2889 2890
    if (virFileDirectFdClose(directFd) < 0)
        goto cleanup;
H
Hu Tao 已提交
2891

2892
    ret = 0;
H
Hu Tao 已提交
2893 2894

cleanup:
2895
    VIR_FORCE_CLOSE(fd);
2896
    virFileDirectFdFree(directFd);
H
Hu Tao 已提交
2897 2898 2899 2900 2901
    if (ret != 0)
        unlink(path);
    return ret;
}

2902 2903 2904 2905 2906
static enum qemud_save_formats
getCompressionType(struct qemud_driver *driver)
{
    int compress = QEMUD_SAVE_FORMAT_RAW;

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

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

M
Michal Privoznik 已提交
2942 2943
    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH |
                  VIR_DUMP_BYPASS_CACHE | VIR_DUMP_RESET, -1);
2944

P
Paolo Bonzini 已提交
2945 2946 2947 2948 2949 2950
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2951 2952
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
P
Paolo Bonzini 已提交
2953 2954 2955
        goto cleanup;
    }

2956 2957
    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             QEMU_ASYNC_JOB_DUMP) < 0)
2958 2959
        goto cleanup;

D
Daniel P. Berrange 已提交
2960
    if (!virDomainObjIsActive(vm)) {
2961 2962
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
2963
        goto endjob;
P
Paolo Bonzini 已提交
2964 2965
    }

P
Paolo Bonzini 已提交
2966 2967
    /* Migrate will always stop the VM, so the resume condition is
       independent of whether the stop command is issued.  */
J
Jiri Denemark 已提交
2968
    resume = virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING;
P
Paolo Bonzini 已提交
2969 2970

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

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

2985 2986
    ret = doCoreDump(driver, vm, path, getCompressionType(driver),
                     (flags & VIR_DUMP_BYPASS_CACHE) != 0);
2987 2988 2989 2990
    if (ret < 0)
        goto endjob;

    paused = 1;
2991 2992

endjob:
2993
    if ((ret == 0) && (flags & VIR_DUMP_CRASH)) {
J
Jiri Denemark 已提交
2994
        qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_CRASHED);
2995
        virDomainAuditStop(vm, "crashed");
2996 2997 2998 2999 3000
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
    }

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

3022
    if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
3023
        vm = NULL;
3024
    else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
3025
        qemuDomainRemoveInactive(driver, vm);
3026 3027
        vm = NULL;
    }
3028 3029

cleanup:
P
Paolo Bonzini 已提交
3030 3031
    if (vm)
        virDomainObjUnlock(vm);
3032 3033
    if (event)
        qemuDomainEventQueue(driver, event);
3034
    qemuDriverUnlock(driver);
P
Paolo Bonzini 已提交
3035 3036 3037
    return ret;
}

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

E
Eric Blake 已提交
3052 3053
    virCheckFlags(0, NULL);

3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067
    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;

3068
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094
        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 已提交
3095
    unlink_tmp = true;
3096

3097 3098
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm, tmp);

3099
    qemuDomainObjEnterMonitor(driver, vm);
3100
    if (qemuMonitorScreendump(priv->mon, tmp) < 0) {
3101
        qemuDomainObjExitMonitor(driver, vm);
3102 3103
        goto endjob;
    }
3104
    qemuDomainObjExitMonitor(driver, vm);
3105 3106 3107 3108 3109 3110

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

E
Eric Blake 已提交
3111
    if (virFDStreamOpenFile(st, tmp, 0, 0, O_RDONLY) < 0) {
3112 3113 3114 3115 3116 3117 3118 3119 3120
        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 已提交
3121 3122
    if (unlink_tmp)
        unlink(tmp);
E
Eric Blake 已提交
3123
    VIR_FREE(tmp);
3124

3125
    if (qemuDomainObjEndJob(driver, vm) == 0)
3126 3127 3128 3129 3130 3131 3132 3133
        vm = NULL;

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

H
Hu Tao 已提交
3134 3135 3136
static void processWatchdogEvent(void *data, void *opaque)
{
    int ret;
3137
    struct qemuDomainWatchdogEvent *wdEvent = data;
H
Hu Tao 已提交
3138 3139
    struct qemud_driver *driver = opaque;

W
Wen Congyang 已提交
3140 3141 3142
    qemuDriverLock(driver);
    virDomainObjLock(wdEvent->vm);

H
Hu Tao 已提交
3143 3144 3145 3146 3147
    switch (wdEvent->action) {
    case VIR_DOMAIN_WATCHDOG_ACTION_DUMP:
        {
            char *dumpfile;

E
Eric Blake 已提交
3148
            if (virAsprintf(&dumpfile, "%s/%s-%u",
H
Hu Tao 已提交
3149 3150
                            driver->autoDumpPath,
                            wdEvent->vm->def->name,
E
Eric Blake 已提交
3151 3152
                            (unsigned int)time(NULL)) < 0) {
                virReportOOMError();
W
Wen Congyang 已提交
3153
                goto unlock;
E
Eric Blake 已提交
3154
            }
H
Hu Tao 已提交
3155

3156 3157
            if (qemuDomainObjBeginAsyncJobWithDriver(driver, wdEvent->vm,
                                                     QEMU_ASYNC_JOB_DUMP) < 0) {
W
Wen Congyang 已提交
3158 3159 3160
                VIR_FREE(dumpfile);
                goto unlock;
            }
H
Hu Tao 已提交
3161 3162 3163 3164

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

3169
            ret = doCoreDump(driver, wdEvent->vm, dumpfile,
3170 3171
                             getCompressionType(driver),
                             driver->autoDumpBypassCache);
H
Hu Tao 已提交
3172 3173 3174 3175
            if (ret < 0)
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("Dump failed"));

J
Jiri Denemark 已提交
3176
            ret = qemuProcessStartCPUs(driver, wdEvent->vm, NULL,
3177 3178
                                       VIR_DOMAIN_RUNNING_UNPAUSED,
                                       QEMU_ASYNC_JOB_DUMP);
H
Hu Tao 已提交
3179 3180 3181 3182 3183 3184 3185 3186

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

            VIR_FREE(dumpfile);
        }
        break;
W
Wen Congyang 已提交
3187 3188
    default:
        goto unlock;
H
Hu Tao 已提交
3189 3190
    }

W
Wen Congyang 已提交
3191 3192 3193 3194
endjob:
    /* Safe to ignore value since ref count was incremented in
     * qemuProcessHandleWatchdog().
     */
3195
    ignore_value(qemuDomainObjEndAsyncJob(driver, wdEvent->vm));
W
Wen Congyang 已提交
3196 3197 3198 3199 3200

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

3204 3205 3206
static int qemudDomainHotplugVcpus(struct qemud_driver *driver,
                                   virDomainObjPtr vm,
                                   unsigned int nvcpus)
3207 3208
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
3209
    int i, rc = 1;
3210
    int ret = -1;
3211
    int oldvcpus = vm->def->vcpus;
E
Eric Blake 已提交
3212
    int vcpus = oldvcpus;
3213

3214
    qemuDomainObjEnterMonitor(driver, vm);
3215

3216 3217 3218
    /* 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 已提交
3219 3220
    if (nvcpus > vcpus) {
        for (i = vcpus ; i < nvcpus ; i++) {
3221 3222 3223 3224 3225 3226 3227
            /* Online new CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 1);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
3228
            vcpus++;
3229 3230
        }
    } else {
E
Eric Blake 已提交
3231
        for (i = vcpus - 1 ; i >= nvcpus ; i--) {
3232 3233 3234 3235 3236 3237 3238
            /* Offline old CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 0);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
3239
            vcpus--;
3240 3241 3242 3243 3244 3245
        }
    }

    ret = 0;

cleanup:
3246
    qemuDomainObjExitMonitor(driver, vm);
E
Eric Blake 已提交
3247
    vm->def->vcpus = vcpus;
3248
    virDomainAuditVcpu(vm, oldvcpus, nvcpus, "update", rc == 1);
3249 3250 3251 3252 3253 3254 3255 3256 3257
    return ret;

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


3258
static int
3259 3260
qemuDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                        unsigned int flags)
3261
{
3262 3263
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3264
    virDomainDefPtr persistentDef;
3265 3266
    const char * type;
    int max;
3267
    int ret = -1;
3268 3269
    bool isActive;
    bool maximum;
3270

3271 3272
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
3273 3274 3275 3276 3277
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

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

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

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

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

3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314
    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)) {
3315 3316
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("domain is not running"));
3317
        goto endjob;
3318 3319
    }

3320
    if (!vm->persistent && (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
3321 3322 3323 3324 3325
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot change persistent config of a transient domain"));
        goto endjob;
    }

3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338
    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;
    }

3339
    if (!maximum && vm->def->maxvcpus < max) {
3340 3341 3342
        max = vm->def->maxvcpus;
    }

3343 3344 3345 3346 3347 3348 3349
    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;
    }

3350 3351 3352
    if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
        goto endjob;

3353
    switch (flags) {
3354
    case VIR_DOMAIN_AFFECT_CONFIG:
3355 3356 3357 3358 3359 3360 3361
        if (maximum) {
            persistentDef->maxvcpus = nvcpus;
            if (nvcpus < persistentDef->vcpus)
                persistentDef->vcpus = nvcpus;
        } else {
            persistentDef->vcpus = nvcpus;
        }
3362 3363 3364
        ret = 0;
        break;

3365
    case VIR_DOMAIN_AFFECT_LIVE:
3366
        ret = qemudDomainHotplugVcpus(driver, vm, nvcpus);
3367 3368
        break;

3369
    case VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG:
3370
        ret = qemudDomainHotplugVcpus(driver, vm, nvcpus);
3371 3372 3373
        if (ret == 0) {
            persistentDef->vcpus = nvcpus;
        }
3374 3375
        break;
    }
3376

3377
    /* Save the persistent config to disk */
3378
    if (flags & VIR_DOMAIN_AFFECT_CONFIG)
3379 3380
        ret = virDomainSaveConfig(driver->configDir, persistentDef);

3381
endjob:
3382
    if (qemuDomainObjEndJob(driver, vm) == 0)
3383
        vm = NULL;
3384

3385
cleanup:
3386 3387
    if (vm)
        virDomainObjUnlock(vm);
3388
    return ret;
3389 3390
}

3391
static int
3392
qemuDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
3393
{
3394
    return qemuDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
3395 3396
}

3397 3398

static int
3399 3400 3401 3402 3403 3404
qemudDomainPinVcpuFlags(virDomainPtr dom,
                        unsigned int vcpu,
                        unsigned char *cpumap,
                        int maplen,
                        unsigned int flags) {

3405 3406
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3407
    virDomainDefPtr persistentDef = NULL;
3408
    int maxcpu, hostcpus;
3409
    virNodeInfo nodeinfo;
3410
    int ret = -1;
3411
    bool isActive;
3412
    qemuDomainObjPrivatePtr priv;
3413
    bool canResetting = true;
E
Eric Blake 已提交
3414
    int pcpu;
3415

3416 3417 3418
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

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

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

3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442
    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"));
3443
        goto cleanup;
3444 3445
    }

3446 3447 3448
    priv = vm->privateData;

    if (vcpu > (priv->nvcpupids-1)) {
3449 3450 3451
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("vcpu number out of range %d > %d"),
                        vcpu, priv->nvcpupids);
3452
        goto cleanup;
3453 3454
    }

3455 3456 3457 3458 3459 3460 3461 3462 3463
    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;
    }
3464

3465 3466 3467 3468 3469 3470 3471 3472 3473
    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 已提交
3474
    for (pcpu = 0; pcpu < hostcpus; pcpu++) {
3475 3476 3477 3478 3479
        if ((cpumap[pcpu/8] & (1 << (pcpu % 8))) == 0) {
            canResetting = false;
            break;
        }
    }
3480

3481
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3482 3483 3484 3485 3486 3487

        if (priv->vcpupids != NULL) {
            if (virProcessInfoSetAffinity(priv->vcpupids[vcpu],
                                          cpumap, maplen, maxcpu) < 0)
                goto cleanup;
        } else {
3488
            qemuReportError(VIR_ERR_OPERATION_INVALID,
3489 3490 3491 3492
                            "%s", _("cpu affinity is not supported"));
            goto cleanup;
        }

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

3509 3510
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
            goto cleanup;
3511
    }
3512

3513 3514
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {

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

3531
        ret = virDomainSaveConfig(driver->configDir, persistentDef);
3532 3533 3534
        goto cleanup;
    }

3535
    ret = 0;
3536

3537
cleanup:
3538 3539
    if (vm)
        virDomainObjUnlock(vm);
3540
    return ret;
3541 3542
}

3543 3544 3545 3546 3547 3548 3549 3550 3551
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
    return qemudDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

3552
static int
E
Eric Blake 已提交
3553
qemudDomainGetVcpuPinInfo(virDomainPtr dom,
3554 3555 3556 3557 3558 3559
                          int ncpumaps,
                          unsigned char *cpumaps,
                          int maplen,
                          unsigned int flags) {

    struct qemud_driver *driver = dom->conn->privateData;
E
Eric Blake 已提交
3560
    virDomainObjPtr vm = NULL;
3561 3562 3563 3564 3565 3566
    virNodeInfo nodeinfo;
    virDomainDefPtr targetDef = NULL;
    int ret = -1;
    bool isActive;
    int maxcpu, hostcpus, vcpu, pcpu;
    int n;
E
Eric Blake 已提交
3567
    virDomainVcpuPinDefPtr *vcpupin_list;
3568 3569 3570 3571 3572 3573 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 3619
    char *cpumask = NULL;
    unsigned char *cpumap;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

    if ((flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)) ==
        (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("cannot get live and persistent info concurrently"));
        goto cleanup;
    }

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

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

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

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

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

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

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

3698 3699
    priv = vm->privateData;

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

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

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

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

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

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

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

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


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

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

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

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

3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795
    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;
    }

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

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

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

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

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

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

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

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

    ret = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

J
Jiri Denemark 已提交
4051
    return fd;
4052

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

    return -1;
}

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

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

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

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

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

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

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

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

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

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

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

4138

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

4163
    ret = 0;
4164

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    qemuDriverLock(driver);

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

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

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

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

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

    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;

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

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

D
Daniel P. Berrange 已提交
4403

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

4413
    /* Flags checked by virDomainDefFormat */
4414

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

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

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

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

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

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

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

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


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

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

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

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

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

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

cleanup:
    virDomainDefFree(def);
    return xml;
}

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

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

4523 4524
    qemuDriverLock(driver);

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

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

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

4548
            VIR_FREE(net->data.network.name);
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 4581
            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);
4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600

            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;
        }
4601
        net->bootIndex = bootIndex;
4602 4603 4604 4605
    }
    for (i = 0 ; i < def->ngraphics ; i++) {
        if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
            def->graphics[i]->data.vnc.autoport)
4606
            def->graphics[i]->data.vnc.port = QEMU_VNC_PORT_MIN;
4607 4608
    }

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

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

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

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

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

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

cleanup:
4630
    qemuDriverUnlock(driver);
4631

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


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

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

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

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

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


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

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

    if (!managed_save)
        goto cleanup;

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

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

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

cleanup:
    VIR_FREE(managed_save);
    return ret;
}

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

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

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

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

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

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

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

    ret = 0;
4766

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

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

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

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

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

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

        break;
    }

    return 0;
}

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

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

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

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

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

    virCapabilitiesFreeMachines(machines, nmachines);

    return 0;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5058
    if (disk->driverName != NULL && !STREQ(disk->driverName, "qemu")) {
5059
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077
                        _("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:
5078
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, false);
5079 5080 5081
        break;
    case VIR_DOMAIN_DISK_DEVICE_DISK:
        if (disk->bus == VIR_DOMAIN_DISK_BUS_USB)
5082
            ret = qemuDomainAttachUsbMassstorageDevice(conn, driver, vm,
5083
                                                       disk);
5084
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
5085
            ret = qemuDomainAttachPciDiskDevice(conn, driver, vm, disk);
5086
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
5087
            ret = qemuDomainAttachSCSIDisk(conn, driver, vm, disk);
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 5113
        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,
5114
                                     virDomainDeviceDefPtr dev)
5115 5116 5117 5118 5119 5120
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

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

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

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

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

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

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

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

5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195
    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,
5196
                               virDomainDeviceDefPtr dev)
5197 5198 5199 5200 5201 5202 5203
{
    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)
5204
            ret = qemuDomainDetachPciDiskDevice(driver, vm, dev);
5205
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
5206
            ret =  qemuDomainDetachDiskDevice(driver, vm, dev);
5207
        else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB)
5208
            ret = qemuDomainDetachDiskDevice(driver, vm, dev);
5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224
        else
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                            _("This type of disk cannot be hot unplugged"));
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("device type '%s' cannot be detached"),
                        virDomainDeviceTypeToString(dev->type));
        break;
    }
    return ret;
}

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

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

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

    return ret;
}

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

    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup,
5287
                               vm->def->name, &cgroup, 0) != 0) {
5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299
            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:
5300
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, force);
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 5332
        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:
5333
        ret = qemuDomainChangeDiskMediaLive(vm, dev, driver, force);
5334 5335 5336 5337
        break;
    case VIR_DOMAIN_DEVICE_GRAPHICS:
        ret = qemuDomainChangeGraphics(driver, vm, dev->data.graphics);
        break;
5338 5339 5340
    case VIR_DOMAIN_DEVICE_NET:
        ret = qemuDomainChangeNet(driver, vm, dom, dev->data.net);
        break;
5341 5342 5343 5344 5345 5346 5347 5348 5349 5350
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("device type '%s' cannot be updated"),
                        virDomainDeviceTypeToString(dev->type));
        break;
    }

    return ret;
}

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

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

5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396
    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;
5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412

    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;

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


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

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

5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450
    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;
5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461

    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;

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

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

5478
    switch (dev->type) {
5479 5480
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
5481
        pos = virDomainDiskIndexByName(vmdef, disk->dst, false);
5482 5483
        if (pos < 0) {
            qemuReportError(VIR_ERR_INVALID_ARG,
5484
                            _("target %s doesn't exist."), disk->dst);
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 5513
            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;
5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533

    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;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5708

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

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

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

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

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

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

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

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

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

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

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

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

5779 5780
    autostart = (autostart != 0);

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

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

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

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

5814 5815 5816
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
5817 5818
    if (vm)
        virDomainObjUnlock(vm);
5819
    qemuDriverUnlock(driver);
5820
    return ret;
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 5856
/*
 * 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;
}


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

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

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

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

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

5890
static int qemuDomainSetBlkioParameters(virDomainPtr dom,
5891
                                         virTypedParameterPtr params,
5892 5893 5894 5895 5896 5897 5898
                                         int nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5899
    virDomainDefPtr persistentDef = NULL;
5900
    int ret = -1;
5901
    bool isActive;
5902

5903 5904
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5905 5906 5907 5908 5909 5910 5911 5912 5913 5914
    qemuDriverLock(driver);

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

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

5915 5916 5917 5918 5919 5920 5921
    isActive = virDomainObjIsActive(vm);

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

5924 5925 5926 5927 5928 5929 5930 5931
    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)) {
5932
            qemuReportError(VIR_ERR_OPERATION_INVALID, _("blkio cgroup isn't mounted"));
5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950
            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;
5951 5952 5953
    }

    ret = 0;
5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        for (i = 0; i < nparams; i++) {
            virTypedParameterPtr param = &params[i];

            if (STREQ(param->field, VIR_DOMAIN_BLKIO_WEIGHT)) {
                int rc;
                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;
                }
5973

5974 5975 5976 5977 5978 5979 5980 5981 5982
                rc = virCgroupSetBlkioWeight(group, params[i].value.ui);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set blkio weight tunable"));
                    ret = -1;
                }
            } else {
                qemuReportError(VIR_ERR_INVALID_ARG,
                                _("Parameter `%s' not supported"), param->field);
5983 5984
                ret = -1;
            }
5985 5986
        }
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
5987 5988 5989
        /* Clang can't see that if we get here, persistentDef was set.  */
        sa_assert(persistentDef);

5990 5991 5992 5993 5994 5995 5996 5997 5998 5999
        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;
                }
6000

6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011
                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;
            } else {
                qemuReportError(VIR_ERR_INVALID_ARG,
                                _("Parameter `%s' not supported"), param->field);
6012 6013 6014
                ret = -1;
            }
        }
A
Alex Jia 已提交
6015 6016 6017

        if (virDomainSaveConfig(driver->configDir, persistentDef) < 0)
            ret = -1;
6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028
    }

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

static int qemuDomainGetBlkioParameters(virDomainPtr dom,
6029
                                         virTypedParameterPtr params,
6030 6031 6032 6033 6034 6035 6036
                                         int *nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6037
    virDomainDefPtr persistentDef = NULL;
6038 6039 6040
    unsigned int val;
    int ret = -1;
    int rc;
6041
    bool isActive;
6042

6043 6044
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061
    qemuDriverLock(driver);

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

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

    if ((*nparams) == 0) {
        /* Current number of blkio parameters supported by cgroups */
        *nparams = QEMU_NB_BLKIO_PARAM;
        ret = 0;
        goto cleanup;
    }

6062 6063 6064 6065 6066 6067 6068
    isActive = virDomainObjIsActive(vm);

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

6071 6072 6073 6074 6075 6076
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }
6077

6078
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
6079
            qemuReportError(VIR_ERR_OPERATION_INVALID, _("blkio cgroup isn't mounted"));
6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100
            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) {
6101
        for (i = 0; i < *nparams && i < QEMU_NB_BLKIO_PARAM; i++) {
6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116
            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,
6117 6118
                                    _("Field name '%s' too long"),
                                    VIR_DOMAIN_BLKIO_WEIGHT);
6119 6120 6121 6122 6123 6124 6125 6126
                    goto cleanup;
                }
                param->value.ui = val;
                break;

            default:
                break;
                /* should not hit here */
6127
            }
6128 6129
        }
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6130
        for (i = 0; i < *nparams && i < QEMU_NB_BLKIO_PARAM; i++) {
6131 6132 6133 6134 6135 6136 6137 6138 6139
            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,
6140 6141
                                    _("Field name '%s' too long"),
                                    VIR_DOMAIN_BLKIO_WEIGHT);
6142 6143 6144 6145
                    goto cleanup;
                }
                param->value.ui = persistentDef->blkio.weight;
                break;
6146

6147 6148 6149 6150
            default:
                break;
                /* should not hit here */
            }
6151 6152 6153
        }
    }

6154 6155
    if (QEMU_NB_BLKIO_PARAM < *nparams)
        *nparams = QEMU_NB_BLKIO_PARAM;
6156 6157 6158 6159 6160 6161 6162 6163 6164 6165
    ret = 0;

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

static int qemuDomainSetMemoryParameters(virDomainPtr dom,
6168
                                         virTypedParameterPtr params,
6169
                                         int nparams,
6170
                                         unsigned int flags)
6171 6172 6173
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
6174
    virDomainDefPtr persistentDef = NULL;
6175 6176 6177
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;
6178 6179
    bool isActive;

6180 6181
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192

    qemuDriverLock(driver);

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

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

6193 6194
    isActive = virDomainObjIsActive(vm);

6195
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
6196
        if (isActive)
6197
            flags = VIR_DOMAIN_AFFECT_LIVE;
6198
        else
6199
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6200 6201
    }

6202
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221
        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;
        }
    }

6222
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6223 6224 6225 6226 6227 6228 6229
        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;
6230 6231 6232 6233
    }

    ret = 0;
    for (i = 0; i < nparams; i++) {
6234
        virTypedParameterPtr param = &params[i];
6235 6236 6237

        if (STREQ(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT)) {
            int rc;
6238
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
6239 6240 6241 6242 6243 6244
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for memory hard_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

6245
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6246 6247 6248 6249 6250 6251 6252 6253
                rc = virCgroupSetMemoryHardLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory hard_limit tunable"));
                    ret = -1;
                }
            }

6254
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6255
                persistentDef->mem.hard_limit = params[i].value.ul;
6256 6257 6258
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT)) {
            int rc;
6259
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
6260 6261 6262 6263 6264 6265
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for memory soft_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

6266
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6267 6268 6269 6270 6271 6272 6273 6274
                rc = virCgroupSetMemorySoftLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory soft_limit tunable"));
                    ret = -1;
                }
            }

6275
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6276
                persistentDef->mem.soft_limit = params[i].value.ul;
6277
            }
6278
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT)) {
6279
            int rc;
6280
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
6281 6282 6283 6284 6285 6286
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for swap_hard_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

6287
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6288 6289 6290 6291 6292 6293 6294
                rc = virCgroupSetMemSwapHardLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set swap_hard_limit tunable"));
                    ret = -1;
                }
            }
6295
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6296
                persistentDef->mem.swap_hard_limit = params[i].value.ul;
6297 6298 6299
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
            qemuReportError(VIR_ERR_INVALID_ARG,
6300 6301
                            _("Memory tunable `%s' not implemented"),
                            param->field);
6302 6303 6304 6305 6306 6307 6308 6309
            ret = -1;
        } else {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Parameter `%s' not supported"), param->field);
            ret = -1;
        }
    }

6310
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6311 6312
        if (virDomainSaveConfig(driver->configDir, persistentDef) < 0)
            ret = -1;
6313 6314
    }

6315 6316 6317 6318 6319 6320 6321 6322
cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

6323
static int qemuDomainGetMemoryParameters(virDomainPtr dom,
6324
                                         virTypedParameterPtr params,
6325
                                         int *nparams,
6326
                                         unsigned int flags)
6327 6328 6329 6330 6331
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6332
    virDomainDefPtr persistentDef = NULL;
6333
    unsigned long long val;
6334 6335
    int ret = -1;
    int rc;
6336
    bool isActive;
6337

6338 6339
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6340

6341
    qemuDriverLock(driver);
6342 6343 6344 6345 6346 6347 6348 6349 6350

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

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

6351 6352
    isActive = virDomainObjIsActive(vm);

6353
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
6354
        if (isActive)
6355
            flags = VIR_DOMAIN_AFFECT_LIVE;
6356
        else
6357
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6358 6359
    }

6360
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379
        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;
        }
    }

6380
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6381 6382 6383 6384 6385 6386 6387
        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;
6388 6389
    }

6390 6391 6392 6393 6394 6395 6396
    if ((*nparams) == 0) {
        /* Current number of memory parameters supported by cgroups */
        *nparams = QEMU_NB_MEM_PARAM;
        ret = 0;
        goto cleanup;
    }

6397
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6398
        for (i = 0; i < *nparams && i < QEMU_NB_MEM_PARAM; i++) {
6399 6400 6401
            virMemoryParameterPtr param = &params[i];
            val = 0;
            param->value.ul = 0;
6402
            param->type = VIR_TYPED_PARAM_ULLONG;
6403 6404 6405 6406 6407

            switch (i) {
            case 0: /* fill memory hard limit here */
                if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT) == NULL) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
6408 6409
                                    _("Field name '%s' too long"),
                                    VIR_DOMAIN_MEMORY_HARD_LIMIT);
6410 6411 6412 6413 6414 6415 6416 6417
                    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,
6418 6419
                                    _("Field name '%s' too long"),
                                    VIR_DOMAIN_MEMORY_SOFT_LIMIT);
6420 6421 6422 6423 6424 6425 6426 6427
                    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,
6428 6429
                                    _("Field name '%s' too long"),
                                    VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT);
6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440
                    goto cleanup;
                }
                param->value.ul = persistentDef->mem.swap_hard_limit;
                break;

            default:
                break;
                /* should not hit here */
            }
        }
        goto out;
6441 6442
    }

6443
    for (i = 0; i < *nparams && i < QEMU_NB_MEM_PARAM; i++) {
6444
        virTypedParameterPtr param = &params[i];
6445 6446
        val = 0;
        param->value.ul = 0;
6447
        param->type = VIR_TYPED_PARAM_ULLONG;
6448

6449 6450 6451
        /* Coverity does not realize that if we get here, group is set.  */
        sa_assert(group);

6452
        switch (i) {
6453 6454 6455 6456 6457
        case 0: /* fill memory hard limit here */
            rc = virCgroupGetMemoryHardLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory hard limit"));
6458
                goto cleanup;
6459 6460 6461
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
6462 6463
                                _("Field name '%s' too long"),
                                VIR_DOMAIN_MEMORY_HARD_LIMIT);
6464
                goto cleanup;
6465 6466 6467 6468 6469 6470 6471 6472 6473
            }
            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"));
6474
                goto cleanup;
6475 6476 6477
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
6478 6479
                                _("Field name '%s' too long"),
                                VIR_DOMAIN_MEMORY_SOFT_LIMIT);
6480
                goto cleanup;
6481 6482 6483 6484 6485
            }
            param->value.ul = val;
            break;

        case 2: /* fill swap hard limit here */
6486
            rc = virCgroupGetMemSwapHardLimit(group, &val);
6487 6488 6489
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get swap hard limit"));
6490
                goto cleanup;
6491
            }
6492
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT) == NULL) {
6493
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
6494 6495
                                _("Field name '%s' too long"),
                                VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT);
6496
                goto cleanup;
6497 6498 6499 6500 6501 6502 6503 6504 6505 6506
            }
            param->value.ul = val;
            break;

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

6507
out:
6508 6509
    if (QEMU_NB_MEM_PARAM < *nparams)
        *nparams = QEMU_NB_MEM_PARAM;
6510 6511
    ret = 0;

6512 6513 6514 6515 6516 6517 6518 6519 6520
cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

6521 6522 6523 6524 6525 6526 6527 6528
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 已提交
6529 6530 6531
    long long vm_quota = 0;
    long long old_quota = 0;
    unsigned long long old_period = 0;
6532 6533 6534 6535

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

W
Wen Congyang 已提交
6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554
    /* 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;
    }
6555

W
Wen Congyang 已提交
6556 6557 6558 6559 6560
    rc = virCgroupGetCpuCfsPeriod(cgroup, &old_period);
    if (rc < 0) {
        virReportSystemError(-rc, "%s",
                             _("unable to get cpu bandwidth period tunable"));
        goto cleanup;
6561 6562
    }

W
Wen Congyang 已提交
6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583
    /*
     * 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;
6584
        }
W
Wen Congyang 已提交
6585
    }
6586

W
Wen Congyang 已提交
6587 6588 6589 6590
    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)
6591 6592
            goto cleanup;

W
Wen Congyang 已提交
6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612
    /* 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);
        }
6613 6614
    }

W
Wen Congyang 已提交
6615 6616 6617 6618 6619 6620
    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;

6621 6622 6623 6624 6625 6626 6627
    return 0;

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

6628
static int qemuSetSchedulerParametersFlags(virDomainPtr dom,
6629
                                           virTypedParameterPtr params,
6630 6631
                                           int nparams,
                                           unsigned int flags)
6632 6633 6634 6635 6636
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6637
    virDomainDefPtr vmdef = NULL;
6638
    int ret = -1;
6639
    bool isActive;
6640
    int rc;
6641

6642 6643
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6644

6645
    qemuDriverLock(driver);
6646 6647 6648 6649

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

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

6655 6656
    isActive = virDomainObjIsActive(vm);

6657
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
6658
        if (isActive)
6659
            flags = VIR_DOMAIN_AFFECT_LIVE;
6660
        else
6661
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6662 6663
    }

6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674
    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;
6675 6676
    }

6677
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696
        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;
        }
    }

6697
    for (i = 0; i < nparams; i++) {
6698
        virTypedParameterPtr param = &params[i];
6699

6700
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CPU_SHARES)) {
6701
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
6702 6703
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for cpu_shares tunable, expected a 'ullong'"));
6704 6705 6706
                goto cleanup;
            }

6707
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6708 6709 6710 6711 6712 6713 6714 6715
                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;
6716
            }
6717

6718
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6719 6720
                vmdef->cputune.shares = params[i].value.ul;
            }
6721
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_VCPU_PERIOD)) {
6722 6723
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
W
Wen Congyang 已提交
6724
                                _("invalid type for vcpu_period tunable,"
6725 6726 6727 6728 6729 6730 6731
                                  " expected a 'ullong'"));
                goto cleanup;
            }

            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
                rc = qemuSetVcpusBWLive(vm, group, params[i].value.ul, 0);
                if (rc != 0)
6732
                    goto cleanup;
6733 6734 6735 6736 6737 6738 6739 6740

                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;
            }
6741
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_VCPU_QUOTA)) {
6742 6743
            if (param->type != VIR_TYPED_PARAM_LLONG) {
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
W
Wen Congyang 已提交
6744
                                _("invalid type for vcpu_quota tunable,"
6745 6746 6747 6748 6749 6750 6751
                                  " expected a 'llong'"));
                goto cleanup;
            }

            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
                rc = qemuSetVcpusBWLive(vm, group, 0, params[i].value.l);
                if (rc != 0)
6752
                    goto cleanup;
6753 6754 6755 6756 6757 6758 6759

                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;
6760
            }
6761
        } else {
6762 6763
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Invalid parameter `%s'"), param->field);
6764 6765 6766
            goto cleanup;
        }
    }
6767

6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780
    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;
    }

6781 6782 6783
    ret = 0;

cleanup:
6784
    virDomainDefFree(vmdef);
6785 6786 6787
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
6788
    qemuDriverUnlock(driver);
6789 6790 6791
    return ret;
}

6792
static int qemuSetSchedulerParameters(virDomainPtr dom,
6793
                                      virTypedParameterPtr params,
6794 6795 6796 6797 6798
                                      int nparams)
{
    return qemuSetSchedulerParametersFlags(dom,
                                           params,
                                           nparams,
6799
                                           VIR_DOMAIN_AFFECT_LIVE);
6800 6801
}

6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866
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;
}

6867 6868 6869 6870 6871
static int
qemuGetSchedulerParametersFlags(virDomainPtr dom,
                                virTypedParameterPtr params,
                                int *nparams,
                                unsigned int flags)
6872 6873 6874 6875
{
    struct qemud_driver *driver = dom->conn->privateData;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6876 6877 6878
    unsigned long long shares;
    unsigned long long period;
    long long quota;
6879 6880
    int ret = -1;
    int rc;
6881
    bool isActive;
6882
    bool cpu_bw_status = false;
6883
    int saved_nparams = 0;
6884

6885 6886
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6887

6888 6889
    qemuDriverLock(driver);

6890 6891
    if ((flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)) ==
        (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)) {
6892 6893
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("cannot query live and config together"));
6894
        goto cleanup;
6895 6896
    }

6897 6898 6899 6900 6901 6902 6903
    if (*nparams > 1) {
        rc = qemuGetCpuBWStatus(driver->cgroup);
        if (rc < 0)
            goto cleanup;
        cpu_bw_status = !!rc;
    }

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

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

6912 6913
    isActive = virDomainObjIsActive(vm);

6914
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
6915
        if (isActive)
6916
            flags = VIR_DOMAIN_AFFECT_LIVE;
6917
        else
6918
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6919 6920
    }

6921
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936
        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;
            }
6937 6938 6939 6940 6941
            shares = persistentDef->cputune.shares;
            if (*nparams > 1 && cpu_bw_status) {
                period = persistentDef->cputune.period;
                quota = persistentDef->cputune.quota;
            }
6942
        } else {
6943 6944 6945 6946 6947
            shares = vm->def->cputune.shares;
            if (*nparams > 1 && cpu_bw_status) {
                period = vm->def->cputune.period;
                quota = vm->def->cputune.quota;
            }
6948
        }
6949
        goto out;
6950 6951
    }

6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963
    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;
    }

6964
    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
6965 6966
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find cgroup for domain %s"), vm->def->name);
6967 6968 6969
        goto cleanup;
    }

6970
    rc = virCgroupGetCpuShares(group, &shares);
6971
    if (rc != 0) {
6972
        virReportSystemError(-rc, "%s",
6973 6974 6975
                             _("unable to get cpu shares tunable"));
        goto cleanup;
    }
6976 6977 6978 6979 6980 6981

    if (*nparams > 1 && cpu_bw_status) {
        rc = qemuGetVcpusBWLive(vm, group, &period, &quota);
        if (rc != 0)
            goto cleanup;
    }
6982
out:
6983
    params[0].value.ul = shares;
6984
    params[0].type = VIR_TYPED_PARAM_ULLONG;
6985 6986
    if (virStrcpyStatic(params[0].field,
                        VIR_DOMAIN_SCHEDULER_CPU_SHARES) == NULL) {
6987
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
6988
                        _("Field name '%s' too long"),
6989
                        VIR_DOMAIN_SCHEDULER_CPU_SHARES);
C
Chris Lalancette 已提交
6990 6991
        goto cleanup;
    }
6992

6993 6994 6995 6996 6997 6998
    saved_nparams++;

    if (cpu_bw_status) {
        if (*nparams > saved_nparams) {
            params[1].value.ul = period;
            params[1].type = VIR_TYPED_PARAM_ULLONG;
6999 7000
            if (virStrcpyStatic(params[1].field,
                                VIR_DOMAIN_SCHEDULER_VCPU_PERIOD) == NULL) {
7001
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
7002
                                _("Field name '%s' too long"),
7003
                                VIR_DOMAIN_SCHEDULER_VCPU_PERIOD);
7004 7005 7006 7007 7008 7009 7010 7011
                goto cleanup;
            }
            saved_nparams++;
        }

        if (*nparams > saved_nparams) {
            params[2].value.ul = quota;
            params[2].type = VIR_TYPED_PARAM_LLONG;
7012 7013
            if (virStrcpyStatic(params[2].field,
                                VIR_DOMAIN_SCHEDULER_VCPU_QUOTA) == NULL) {
7014
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
7015
                                _("Field name '%s' too long"),
7016
                                VIR_DOMAIN_SCHEDULER_VCPU_QUOTA);
7017 7018 7019 7020 7021 7022 7023 7024
                goto cleanup;
            }
            saved_nparams++;
        }
    }

    *nparams = saved_nparams;

7025 7026 7027 7028 7029 7030
    ret = 0;

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

7035 7036 7037 7038 7039 7040
static int
qemuGetSchedulerParameters(virDomainPtr dom,
                           virTypedParameterPtr params,
                           int *nparams)
{
    return qemuGetSchedulerParametersFlags(dom, params, nparams,
7041
                                           VIR_DOMAIN_AFFECT_CURRENT);
7042
}
7043

7044 7045 7046 7047 7048
/* 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
7049 7050 7051
qemuDomainBlockStats(virDomainPtr dom,
                     const char *path,
                     struct _virDomainBlockStats *stats)
7052
{
7053
    struct qemud_driver *driver = dom->conn->privateData;
7054
    int i, ret = -1;
7055
    virDomainObjPtr vm;
7056
    virDomainDiskDefPtr disk = NULL;
7057
    qemuDomainObjPrivatePtr priv;
7058

7059
    qemuDriverLock(driver);
7060
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7061
    qemuDriverUnlock(driver);
7062
    if (!vm) {
7063 7064
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
7065 7066
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
7067
        goto cleanup;
7068
    }
7069

7070 7071 7072 7073 7074 7075
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

7076 7077 7078 7079 7080 7081 7082 7083
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

    if (!disk) {
7084 7085
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path: %s"), path);
7086
        goto cleanup;
7087 7088
    }

7089
    if (!disk->info.alias) {
7090 7091
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("missing disk device alias name for %s"), disk->dst);
7092
        goto cleanup;
7093
    }
7094

7095
    priv = vm->privateData;
7096 7097
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
        goto cleanup;
7098

7099 7100 7101 7102 7103
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }
7104

7105
    qemuDomainObjEnterMonitor(driver, vm);
7106 7107 7108 7109
    ret = qemuMonitorGetBlockStatsInfo(priv->mon,
                                       disk->info.alias,
                                       &stats->rd_req,
                                       &stats->rd_bytes,
7110
                                       NULL,
7111 7112
                                       &stats->wr_req,
                                       &stats->wr_bytes,
7113 7114 7115
                                       NULL,
                                       NULL,
                                       NULL,
7116 7117
                                       &stats->errs);
    qemuDomainObjExitMonitor(driver, vm);
7118

7119
endjob:
7120 7121
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
7122

7123
cleanup:
7124 7125
    if (vm)
        virDomainObjUnlock(vm);
7126
    return ret;
7127 7128
}

7129
static int
7130 7131 7132 7133 7134
qemuDomainBlockStatsFlags(virDomainPtr dom,
                          const char *path,
                          virTypedParameterPtr params,
                          int *nparams,
                          unsigned int flags)
7135 7136 7137 7138 7139 7140 7141 7142
{
    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;
7143
    virTypedParameterPtr param;
7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179

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

    if (*nparams != 0) {
        for (i = 0 ; i < vm->def->ndisks ; i++) {
            if (STREQ(path, vm->def->disks[i]->dst)) {
                disk = vm->def->disks[i];
                break;
            }
        }

        if (!disk) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("invalid path: %s"), path);
            goto cleanup;
        }

        if (!disk->info.alias) {
             qemuReportError(VIR_ERR_INTERNAL_ERROR,
7180 7181
                             _("missing disk device alias name for %s"),
                             disk->dst);
7182 7183 7184 7185 7186 7187 7188 7189 7190 7191
             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;

7192 7193 7194 7195 7196 7197
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

7198 7199 7200 7201
    qemuDomainObjEnterMonitor(driver, vm);
    tmp = *nparams;
    ret = qemuMonitorGetBlockStatsParamsNumber(priv->mon, nparams);

7202
    if (tmp == 0 || ret < 0) {
7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223
        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;

7224 7225
    tmp = 0;
    ret = -1;
7226

7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239
    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++;
    }
7240

7241
    if (tmp < *nparams && wr_req != -1) {
7242
        param = &params[tmp];
7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253
        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++;
    }
7254

7255
    if (tmp < *nparams && rd_bytes != -1) {
7256
        param = &params[tmp];
7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267
        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++;
    }
7268

7269
    if (tmp < *nparams && rd_req != -1) {
7270
        param = &params[tmp];
7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281
        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++;
    }
7282

7283
    if (tmp < *nparams && flush_req != -1) {
7284
        param = &params[tmp];
7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295
        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++;
    }
7296

7297
    if (tmp < *nparams && wr_total_times != -1) {
7298
        param = &params[tmp];
7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309
        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++;
    }
7310

7311
    if (tmp < *nparams && rd_total_times != -1) {
7312
        param = &params[tmp];
7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323
        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++;
    }
7324

7325
    if (tmp < *nparams && flush_total_times != -1) {
7326
        param = &params[tmp];
7327 7328 7329 7330 7331 7332
        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;
7333
        }
7334 7335 7336
        param->type = VIR_TYPED_PARAM_LLONG;
        param->value.l = flush_total_times;
        tmp++;
7337 7338
    }

7339 7340 7341 7342 7343
    /* Field 'errs' is meaningless for QEMU, won't set it. */

    ret = 0;
    *nparams = tmp;

7344 7345 7346 7347 7348 7349 7350 7351 7352 7353
endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;

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

7354
#ifdef __linux__
7355 7356 7357 7358 7359
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
7360 7361
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
7362
    int i;
7363
    int ret = -1;
7364

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

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

D
Daniel P. Berrange 已提交
7377
    if (!virDomainObjIsActive(vm)) {
7378 7379
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
7380
        goto cleanup;
7381 7382 7383
    }

    /* Check the path is one of the domain's network interfaces. */
7384 7385
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
7386 7387 7388 7389
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
7390 7391
    }

7392
    if (ret == 0)
7393
        ret = linuxDomainInterfaceStats(path, stats);
7394
    else
7395 7396
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path, '%s' is not a known interface"), path);
7397

7398
cleanup:
7399 7400
    if (vm)
        virDomainObjUnlock(vm);
7401 7402
    return ret;
}
7403
#else
7404 7405 7406 7407
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
7408
{
7409 7410
    qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                    _("interface stats not implemented on this platform"));
7411 7412
    return -1;
}
7413
#endif
7414

7415 7416 7417
static int
qemudDomainMemoryStats (virDomainPtr dom,
                        struct _virDomainMemoryStat *stats,
7418 7419
                        unsigned int nr_stats,
                        unsigned int flags)
7420 7421 7422 7423 7424
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned int ret = -1;

7425 7426
    virCheckFlags(0, -1);

7427 7428 7429 7430 7431 7432 7433
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

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

7439
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
7440 7441
        goto cleanup;

7442 7443
    if (virDomainObjIsActive(vm)) {
        qemuDomainObjPrivatePtr priv = vm->privateData;
7444
        qemuDomainObjEnterMonitor(driver, vm);
7445
        ret = qemuMonitorGetMemoryStats(priv->mon, stats, nr_stats);
7446
        qemuDomainObjExitMonitor(driver, vm);
7447
    } else {
7448 7449
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
7450 7451
    }

7452
    if (qemuDomainObjEndJob(driver, vm) == 0)
7453 7454
        vm = NULL;

7455 7456 7457 7458 7459 7460
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

7461 7462 7463 7464 7465
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
E
Eric Blake 已提交
7466
                      unsigned int flags)
7467
{
7468 7469
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
7470 7471
    int fd = -1, ret = -1;
    const char *actual;
7472

E
Eric Blake 已提交
7473 7474
    virCheckFlags(0, -1);

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

7479
    if (!vm) {
7480 7481
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
7482 7483
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
7484
        goto cleanup;
7485 7486 7487
    }

    if (!path || path[0] == '\0') {
7488 7489
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("NULL or empty path"));
7490
        goto cleanup;
7491 7492
    }

7493 7494 7495 7496 7497
    /* Check the path belongs to this domain.  */
    if (!(actual = virDomainDiskPathByName(vm->def, path))) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path '%s'"), path);
        goto cleanup;
7498
    }
7499
    path = actual;
7500

7501 7502 7503 7504 7505 7506 7507
    /* 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;
    }
7508

7509 7510 7511 7512 7513 7514 7515 7516 7517
    /* 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;
7518 7519
    }

7520 7521
    ret = 0;

7522
cleanup:
7523
    VIR_FORCE_CLOSE(fd);
7524 7525
    if (vm)
        virDomainObjUnlock(vm);
7526 7527 7528
    return ret;
}

R
Richard W.M. Jones 已提交
7529 7530 7531 7532 7533 7534
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
7535 7536
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
7537
    char *tmp = NULL;
R
Richard W.M. Jones 已提交
7538
    int fd = -1, ret = -1;
7539
    qemuDomainObjPrivatePtr priv;
R
Richard W.M. Jones 已提交
7540

7541 7542
    virCheckFlags(VIR_MEMORY_VIRTUAL | VIR_MEMORY_PHYSICAL, -1);

7543
    qemuDriverLock(driver);
7544
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7545
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
7546 7547

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

7555
    if (flags != VIR_MEMORY_VIRTUAL && flags != VIR_MEMORY_PHYSICAL) {
7556 7557
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("flags parameter must be VIR_MEMORY_VIRTUAL or VIR_MEMORY_PHYSICAL"));
7558
        goto cleanup;
R
Richard W.M. Jones 已提交
7559 7560
    }

7561
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
7562 7563
        goto cleanup;

D
Daniel P. Berrange 已提交
7564
    if (!virDomainObjIsActive(vm)) {
7565 7566
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
7567
        goto endjob;
R
Richard W.M. Jones 已提交
7568 7569
    }

7570
    if (virAsprintf(&tmp, "%s/qemu.mem.XXXXXX", driver->cacheDir) < 0) {
7571
        virReportOOMError();
7572
        goto endjob;
7573 7574
    }

R
Richard W.M. Jones 已提交
7575 7576
    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
7577 7578
        virReportSystemError(errno,
                             _("mkstemp(\"%s\") failed"), tmp);
7579
        goto endjob;
R
Richard W.M. Jones 已提交
7580 7581
    }

7582 7583
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm, tmp);

7584
    priv = vm->privateData;
7585
    qemuDomainObjEnterMonitor(driver, vm);
7586
    if (flags == VIR_MEMORY_VIRTUAL) {
7587
        if (qemuMonitorSaveVirtualMemory(priv->mon, offset, size, tmp) < 0) {
7588
            qemuDomainObjExitMonitor(driver, vm);
7589
            goto endjob;
7590
        }
7591
    } else {
7592
        if (qemuMonitorSavePhysicalMemory(priv->mon, offset, size, tmp) < 0) {
7593
            qemuDomainObjExitMonitor(driver, vm);
7594
            goto endjob;
7595
        }
R
Richard W.M. Jones 已提交
7596
    }
7597
    qemuDomainObjExitMonitor(driver, vm);
R
Richard W.M. Jones 已提交
7598 7599

    /* Read the memory file into buffer. */
7600
    if (saferead(fd, buffer, size) == (ssize_t) -1) {
7601 7602 7603
        virReportSystemError(errno,
                             _("failed to read temporary file "
                               "created with template %s"), tmp);
7604
        goto endjob;
R
Richard W.M. Jones 已提交
7605 7606 7607
    }

    ret = 0;
7608

7609
endjob:
7610
    if (qemuDomainObjEndJob(driver, vm) == 0)
7611
        vm = NULL;
7612

7613
cleanup:
7614
    VIR_FORCE_CLOSE(fd);
7615 7616
    if (tmp)
        unlink(tmp);
W
Wen Congyang 已提交
7617
    VIR_FREE(tmp);
7618 7619
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
7620 7621 7622
    return ret;
}

7623

7624 7625 7626 7627 7628 7629 7630 7631 7632
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;
7633
    virStorageFileMetadata *meta = NULL;
7634
    virDomainDiskDefPtr disk = NULL;
7635
    struct stat sb;
7636
    int i;
7637
    int format;
7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658

    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. */
7659
    if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
7660 7661 7662 7663
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path %s not assigned to domain"), path);
        goto cleanup;
    }
7664 7665 7666 7667 7668 7669 7670 7671
    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;
7672 7673

    /* The path is correct, now try to open it and get its size. */
7674
    fd = open(path, O_RDONLY);
7675 7676 7677 7678 7679 7680 7681
    if (fd == -1) {
        virReportSystemError(errno,
                             _("failed to open path '%s'"), path);
        goto cleanup;
    }

    /* Probe for magic formats */
7682 7683 7684 7685 7686 7687 7688 7689
    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 {
7690 7691 7692 7693 7694 7695 7696
        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);
7697
            goto cleanup;
7698
        }
7699 7700
    }

7701 7702 7703 7704 7705
    if (VIR_ALLOC(meta) < 0) {
        virReportOOMError();
        goto cleanup;
    }

7706 7707
    if (virStorageFileGetMetadataFromFD(path, fd,
                                        format,
7708
                                        meta) < 0)
7709 7710 7711 7712 7713 7714 7715 7716 7717 7718
        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)) {
7719
#ifndef WIN32
7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732
        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.
         */
7733
        end = lseek(fd, 0, SEEK_END);
7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744
        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 */
7745 7746
    if (meta->capacity)
        info->capacity = meta->capacity;
7747

7748
    /* Set default value .. */
7749 7750
    info->allocation = info->physical;

7751 7752 7753
    /* ..but if guest is running & not using raw
       disk format and on a block device, then query
       highest allocated extent from QEMU */
7754
    if (disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
7755
        format != VIR_STORAGE_FILE_RAW &&
7756 7757
        S_ISBLK(sb.st_mode) &&
        virDomainObjIsActive(vm)) {
7758
        qemuDomainObjPrivatePtr priv = vm->privateData;
7759

7760 7761
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
            goto cleanup;
7762

7763
        if (virDomainObjIsActive(vm)) {
7764
            qemuDomainObjEnterMonitor(driver, vm);
7765 7766 7767 7768
            ret = qemuMonitorGetBlockExtent(priv->mon,
                                            disk->info.alias,
                                            &info->allocation);
            qemuDomainObjExitMonitor(driver, vm);
7769
        } else {
7770
            ret = 0;
7771
        }
7772 7773 7774

        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
7775 7776 7777
    } else {
        ret = 0;
    }
7778 7779

cleanup:
7780
    virStorageFileFreeMetadata(meta);
7781
    VIR_FORCE_CLOSE(fd);
7782 7783 7784 7785 7786 7787
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


7788
static int
7789 7790 7791 7792
qemuDomainEventRegister(virConnectPtr conn,
                        virConnectDomainEventCallback callback,
                        void *opaque,
                        virFreeCallback freecb)
7793
{
7794 7795 7796
    struct qemud_driver *driver = conn->privateData;
    int ret;

7797
    qemuDriverLock(driver);
7798 7799
    ret = virDomainEventCallbackListAdd(conn,
                                        driver->domainEventState->callbacks,
7800
                                        callback, opaque, freecb);
7801
    qemuDriverUnlock(driver);
7802

7803
    return ret;
7804 7805
}

7806

7807
static int
7808 7809
qemuDomainEventDeregister(virConnectPtr conn,
                          virConnectDomainEventCallback callback)
7810
{
7811 7812 7813
    struct qemud_driver *driver = conn->privateData;
    int ret;

7814
    qemuDriverLock(driver);
7815 7816 7817
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
7818
    qemuDriverUnlock(driver);
7819

7820
    return ret;
7821 7822
}

7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836

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,
7837
                                          driver->domainEventState->callbacks,
7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853
                                          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);
7854 7855 7856
    ret = virDomainEventStateDeregisterAny(conn,
                                           driver->domainEventState,
                                           callbackID);
7857 7858 7859 7860 7861 7862
    qemuDriverUnlock(driver);

    return ret;
}


7863 7864 7865
/*******************************************************************
 * Migration Protocol Version 2
 *******************************************************************/
D
Daniel Veillard 已提交
7866

C
Chris Lalancette 已提交
7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881
/* 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;
7882

7883
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
7884

7885 7886
    qemuDriverLock(driver);

C
Chris Lalancette 已提交
7887
    if (!dom_xml) {
7888 7889
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
C
Chris Lalancette 已提交
7890 7891 7892
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
7893
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
7894 7895 7896 7897
                         "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
        goto cleanup;
    }
    if (st == NULL) {
7898 7899
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("tunnelled migration requested but NULL stream passed"));
C
Chris Lalancette 已提交
7900 7901 7902
        goto cleanup;
    }

7903 7904 7905 7906 7907 7908 7909
    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

7910 7911 7912
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     NULL, 0, NULL, NULL, /* No cookies in v2 */
                                     st, dname, dom_xml);
7913

C
Chris Lalancette 已提交
7914
cleanup:
7915
    qemuDriverUnlock(driver);
C
Chris Lalancette 已提交
7916 7917 7918
    return ret;
}

D
Daniel Veillard 已提交
7919 7920 7921 7922
/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
7923
static int ATTRIBUTE_NONNULL (5)
D
Daniel Veillard 已提交
7924
qemudDomainMigratePrepare2 (virConnectPtr dconn,
7925 7926
                            char **cookie ATTRIBUTE_UNUSED,
                            int *cookielen ATTRIBUTE_UNUSED,
D
Daniel Veillard 已提交
7927 7928
                            const char *uri_in,
                            char **uri_out,
C
Chris Lalancette 已提交
7929
                            unsigned long flags,
D
Daniel Veillard 已提交
7930 7931 7932 7933
                            const char *dname,
                            unsigned long resource ATTRIBUTE_UNUSED,
                            const char *dom_xml)
{
7934
    struct qemud_driver *driver = dconn->privateData;
7935
    int ret = -1;
7936

7937
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
7938

7939
    *uri_out = NULL;
D
Daniel Veillard 已提交
7940

7941
    qemuDriverLock(driver);
7942 7943 7944 7945 7946 7947 7948 7949

    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 已提交
7950 7951 7952 7953
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
7954 7955
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Tunnelled migration requested but invalid RPC method called"));
C
Chris Lalancette 已提交
7956 7957 7958
        goto cleanup;
    }

D
Daniel Veillard 已提交
7959
    if (!dom_xml) {
7960 7961
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
7962
        goto cleanup;
D
Daniel Veillard 已提交
7963 7964
    }

7965 7966 7967 7968
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
7969
    ret = qemuMigrationPrepareDirect(driver, dconn,
7970
                                     NULL, 0, NULL, NULL, /* No cookies */
7971 7972
                                     uri_in, uri_out,
                                     dname, dom_xml);
D
Daniel Veillard 已提交
7973

7974 7975 7976 7977
cleanup:
    qemuDriverUnlock(driver);
    return ret;
}
C
Chris Lalancette 已提交
7978

D
Daniel Veillard 已提交
7979

7980 7981 7982
/* Perform is the second step, and it runs on the source host. */
static int
qemudDomainMigratePerform (virDomainPtr dom,
7983 7984
                           const char *cookie,
                           int cookielen,
7985 7986 7987 7988 7989 7990 7991 7992
                           const char *uri,
                           unsigned long flags,
                           const char *dname,
                           unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
7993
    const char *dconnuri = NULL;
7994

7995
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
7996

7997
    qemuDriverLock(driver);
7998 7999 8000 8001 8002 8003 8004
    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

8005
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel Veillard 已提交
8006
    if (!vm) {
8007 8008
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
8009 8010
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
8011
        goto cleanup;
D
Daniel Veillard 已提交
8012 8013
    }

8014 8015 8016 8017 8018
    if (flags & VIR_MIGRATE_PEER2PEER) {
        dconnuri = uri;
        uri = NULL;
    }

8019 8020 8021 8022 8023 8024
    /* 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
     */
8025
    ret = qemuMigrationPerform(driver, dom->conn, vm,
8026
                               NULL, dconnuri, uri, cookie, cookielen,
8027
                               NULL, NULL, /* No output cookies in v2 */
8028
                               flags, dname, resource, false);
8029

8030
cleanup:
8031
    qemuDriverUnlock(driver);
8032
    return ret;
D
Daniel Veillard 已提交
8033 8034
}

8035

D
Daniel Veillard 已提交
8036 8037 8038 8039 8040 8041 8042
/* 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 已提交
8043
                           unsigned long flags,
D
Daniel Veillard 已提交
8044 8045
                           int retcode)
{
8046 8047 8048
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
D
Daniel Veillard 已提交
8049

8050
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
C
Chris Lalancette 已提交
8051

8052
    qemuDriverLock(driver);
8053
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
8054
    if (!vm) {
8055 8056
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
8057
        goto cleanup;
D
Daniel Veillard 已提交
8058 8059
    }

8060 8061 8062 8063
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
8064
    dom = qemuMigrationFinish(driver, dconn, vm,
8065
                              NULL, 0, NULL, NULL, /* No cookies */
8066
                              flags, retcode, false);
8067

8068
cleanup:
8069
    qemuDriverUnlock(driver);
8070
    return dom;
D
Daniel Veillard 已提交
8071 8072
}

8073

8074 8075 8076 8077 8078 8079
/*******************************************************************
 * Migration Protocol Version 3
 *******************************************************************/

static char *
qemuDomainMigrateBegin3(virDomainPtr domain,
8080
                        const char *xmlin,
8081 8082 8083
                        char **cookieout,
                        int *cookieoutlen,
                        unsigned long flags,
8084
                        const char *dname,
8085 8086 8087 8088 8089 8090
                        unsigned long resource ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    char *xml = NULL;

8091
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102

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

8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116
    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;
    }

8117 8118 8119 8120 8121 8122 8123
    /* Check if there is any ejected media.
     * We don't want to require them on the destination.
     */

    if (qemuDomainCheckEjectableMedia(driver, vm) < 0)
        goto endjob;

8124
    if (!(xml = qemuMigrationBegin(driver, vm, xmlin, dname,
8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143
                                   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;
    }
8144 8145

cleanup:
8146 8147
    if (vm)
        virDomainObjUnlock(vm);
8148 8149
    qemuDriverUnlock(driver);
    return xml;
8150 8151 8152 8153 8154 8155 8156 8157 8158 8159

endjob:
    if ((flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        if (qemuMigrationJobFinish(driver, vm) == 0)
            vm = NULL;
    } else {
        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
    }
    goto cleanup;
8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177
}

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;

8178
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224

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

8225
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256

    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,
8257
                          const char *xmlin,
8258 8259 8260 8261
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
8262
                          const char *dconnuri,
8263 8264 8265 8266 8267 8268 8269 8270 8271
                          const char *uri,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

8272
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283

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

8284
    ret = qemuMigrationPerform(driver, dom->conn, vm, xmlin,
8285
                               dconnuri, uri, cookiein, cookieinlen,
8286
                               cookieout, cookieoutlen,
8287
                               flags, dname, resource, true);
8288 8289 8290 8291 8292 8293 8294

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}


8295
static virDomainPtr
8296 8297 8298 8299 8300 8301
qemuDomainMigrateFinish3(virConnectPtr dconn,
                         const char *dname,
                         const char *cookiein,
                         int cookieinlen,
                         char **cookieout,
                         int *cookieoutlen,
8302
                         const char *dconnuri ATTRIBUTE_UNUSED,
8303 8304
                         const char *uri ATTRIBUTE_UNUSED,
                         unsigned long flags,
8305
                         int cancelled)
8306 8307 8308
{
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
8309
    virDomainPtr dom = NULL;
8310

8311
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
8312 8313 8314 8315 8316 8317 8318 8319 8320

    qemuDriverLock(driver);
    vm = virDomainFindByName(&driver->domains, dname);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
        goto cleanup;
    }

8321 8322 8323 8324
    dom = qemuMigrationFinish(driver, dconn, vm,
                              cookiein, cookieinlen,
                              cookieout, cookieoutlen,
                              flags, cancelled, true);
8325 8326 8327

cleanup:
    qemuDriverUnlock(driver);
8328
    return dom;
8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340
}

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;
8341
    enum qemuMigrationJobPhase phase;
8342

8343
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354

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

8355
    if (!qemuMigrationJobIsActive(vm, QEMU_ASYNC_JOB_MIGRATION_OUT))
8356 8357
        goto cleanup;

8358 8359 8360 8361 8362 8363 8364
    if (cancelled)
        phase = QEMU_MIGRATION_PHASE_CONFIRM3_CANCELLED;
    else
        phase = QEMU_MIGRATION_PHASE_CONFIRM3;

    qemuMigrationJobStartPhase(driver, vm, phase);

8365 8366
    ret = qemuMigrationConfirm(driver, domain->conn, vm,
                               cookiein, cookieinlen,
8367 8368
                               flags, cancelled);

8369
    if (qemuMigrationJobFinish(driver, vm) == 0) {
8370 8371 8372 8373 8374
        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);
8375
        qemuDomainRemoveInactive(driver, vm);
8376 8377 8378
        vm = NULL;
    }

8379
cleanup:
8380 8381
    if (vm)
        virDomainObjUnlock(vm);
8382 8383 8384 8385 8386
    qemuDriverUnlock(driver);
    return ret;
}


8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402
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;

8403
    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE);
8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420
    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) {
8421 8422
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("device %s is not a PCI device"), dev->name);
8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435
        goto out;
    }

    ret = 0;
out:
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
qemudNodeDeviceDettach (virNodeDevicePtr dev)
{
8436
    struct qemud_driver *driver = dev->conn->privateData;
8437 8438 8439 8440 8441 8442 8443
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

8444
    pci = pciGetDevice(domain, bus, slot, function);
8445 8446 8447
    if (!pci)
        return -1;

8448 8449
    qemuDriverLock(driver);
    if (pciDettachDevice(pci, driver->activePciHostdevs) < 0)
8450 8451 8452 8453
        goto out;

    ret = 0;
out:
8454
    qemuDriverUnlock(driver);
8455
    pciFreeDevice(pci);
8456 8457 8458 8459 8460 8461
    return ret;
}

static int
qemudNodeDeviceReAttach (virNodeDevicePtr dev)
{
8462
    struct qemud_driver *driver = dev->conn->privateData;
8463 8464 8465 8466 8467 8468 8469
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

8470
    pci = pciGetDevice(domain, bus, slot, function);
8471 8472 8473
    if (!pci)
        return -1;

8474 8475
    pciDeviceReAttachInit(pci);

8476 8477
    qemuDriverLock(driver);
    if (pciReAttachDevice(pci, driver->activePciHostdevs) < 0)
8478 8479 8480 8481
        goto out;

    ret = 0;
out:
8482
    qemuDriverUnlock(driver);
8483
    pciFreeDevice(pci);
8484 8485 8486 8487 8488 8489
    return ret;
}

static int
qemudNodeDeviceReset (virNodeDevicePtr dev)
{
8490
    struct qemud_driver *driver = dev->conn->privateData;
8491 8492 8493 8494 8495 8496 8497
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

8498
    pci = pciGetDevice(domain, bus, slot, function);
8499 8500 8501
    if (!pci)
        return -1;

8502 8503
    qemuDriverLock(driver);

8504
    if (pciResetDevice(pci, driver->activePciHostdevs, NULL) < 0)
8505 8506 8507 8508
        goto out;

    ret = 0;
out:
8509
    qemuDriverUnlock(driver);
8510
    pciFreeDevice(pci);
8511 8512 8513
    return ret;
}

8514 8515 8516
static int
qemuCPUCompare(virConnectPtr conn,
               const char *xmlDesc,
E
Eric Blake 已提交
8517
               unsigned int flags)
8518 8519 8520 8521
{
    struct qemud_driver *driver = conn->privateData;
    int ret = VIR_CPU_COMPARE_ERROR;

E
Eric Blake 已提交
8522 8523
    virCheckFlags(0, VIR_CPU_COMPARE_ERROR);

8524 8525 8526
    qemuDriverLock(driver);

    if (!driver->caps || !driver->caps->host.cpu) {
8527
        qemuReportError(VIR_ERR_OPERATION_INVALID,
8528
                        "%s", _("cannot get host CPU capabilities"));
E
Eric Blake 已提交
8529
    } else {
8530
        ret = cpuCompareXML(driver->caps->host.cpu, xmlDesc);
E
Eric Blake 已提交
8531
    }
8532 8533 8534 8535 8536 8537

    qemuDriverUnlock(driver);

    return ret;
}

8538

8539 8540 8541 8542
static char *
qemuCPUBaseline(virConnectPtr conn ATTRIBUTE_UNUSED,
                const char **xmlCPUs,
                unsigned int ncpus,
E
Eric Blake 已提交
8543
                unsigned int flags)
8544 8545 8546
{
    char *cpu;

E
Eric Blake 已提交
8547 8548
    virCheckFlags(0, NULL);

8549 8550 8551 8552 8553
    cpu = cpuBaselineXML(xmlCPUs, ncpus, NULL, 0);

    return cpu;
}

8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575

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)) {
8576
        if (priv->job.asyncJob) {
8577
            memcpy(info, &priv->job.info, sizeof(*info));
8578 8579 8580 8581 8582 8583

            /* 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
             */
J
Jiri Denemark 已提交
8584
            if (virTimeMs(&info->timeElapsed) < 0)
8585
                goto cleanup;
8586
            info->timeElapsed -= priv->job.start;
8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605
        } 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;
}


8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622
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;
    }

8623 8624
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_ABORT) < 0)
        goto cleanup;
8625

8626
    if (!virDomainObjIsActive(vm)) {
8627 8628
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
8629
        goto endjob;
8630 8631
    }

8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645
    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");
8646
    qemuDomainObjEnterMonitor(driver, vm);
8647 8648 8649 8650 8651 8652
    ret = qemuMonitorMigrateCancel(priv->mon);
    qemuDomainObjExitMonitor(driver, vm);

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
8653 8654 8655 8656 8657 8658 8659 8660

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


8661 8662 8663 8664 8665 8666 8667 8668 8669 8670
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;

8671
    virCheckFlags(0, -1);
8672 8673 8674

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
8675
    qemuDriverUnlock(driver);
8676 8677 8678 8679 8680 8681

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

8685 8686 8687
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
        goto cleanup;

8688 8689 8690
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
8691
        goto endjob;
8692 8693 8694 8695
    }

    priv = vm->privateData;

8696
    if (priv->job.asyncJob != QEMU_ASYNC_JOB_MIGRATION_OUT) {
8697 8698
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not being migrated"));
8699
        goto endjob;
8700 8701
    }

8702
    VIR_DEBUG("Setting migration downtime to %llums", downtime);
8703
    qemuDomainObjEnterMonitor(driver, vm);
8704 8705 8706 8707 8708 8709
    ret = qemuMonitorSetMigrationDowntime(priv->mon, downtime);
    qemuDomainObjExitMonitor(driver, vm);

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
8710 8711 8712 8713 8714 8715 8716

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

8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730
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);
8731
    qemuDriverUnlock(driver);
8732 8733 8734 8735 8736 8737

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
8738
        return -1;
8739 8740 8741
    }

    priv = vm->privateData;
8742 8743 8744
    if (virDomainObjIsActive(vm)) {
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
            goto cleanup;
8745

8746 8747 8748 8749 8750 8751
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto endjob;
        }

8752 8753 8754 8755
        VIR_DEBUG("Setting migration bandwidth to %luMbs", bandwidth);
        qemuDomainObjEnterMonitor(driver, vm);
        ret = qemuMonitorSetMigrationSpeed(priv->mon, bandwidth);
        qemuDomainObjExitMonitor(driver, vm);
8756

8757 8758
        if (ret == 0)
            priv->migMaxBandwidth = bandwidth;
8759

8760
endjob:
8761 8762 8763 8764 8765 8766
        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
    } else {
        priv->migMaxBandwidth = bandwidth;
        ret = 0;
    }
8767 8768 8769 8770 8771 8772 8773

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

8774 8775 8776 8777 8778 8779 8780
static int
qemuDomainMigrateGetMaxSpeed(virDomainPtr dom,
                             unsigned long *bandwidth,
                             unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
8781
    qemuDomainObjPrivatePtr priv;
8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797
    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 已提交
8798 8799
    priv = vm->privateData;
    *bandwidth = priv->migMaxBandwidth;
8800 8801 8802 8803 8804 8805 8806 8807
    ret = 0;

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

C
Chris Lalancette 已提交
8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820
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,
8821 8822
                            _("Disk '%s' does not support snapshotting"),
                            vm->def->disks[i]->src);
C
Chris Lalancette 已提交
8823 8824 8825 8826 8827 8828 8829
            return 0;
        }
    }

    return 1;
}

8830 8831
/* The domain is expected to be locked and inactive. */
static int
E
Eric Blake 已提交
8832 8833
qemuDomainSnapshotCreateInactive(struct qemud_driver *driver,
                                 virDomainObjPtr vm,
8834 8835
                                 virDomainSnapshotObjPtr snap)
{
E
Eric Blake 已提交
8836
    return qemuDomainSnapshotForEachQcow2(driver, vm, snap, "-c", false);
8837 8838
}

8839 8840
/* The domain is expected to be locked and active. */
static int
8841 8842
qemuDomainSnapshotCreateActive(virConnectPtr conn,
                               struct qemud_driver *driver,
8843
                               virDomainObjPtr *vmptr,
8844 8845
                               virDomainSnapshotObjPtr snap,
                               unsigned int flags)
8846 8847 8848
{
    virDomainObjPtr vm = *vmptr;
    qemuDomainObjPrivatePtr priv = vm->privateData;
8849 8850
    bool resume = false;
    int ret = -1;
8851

8852
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
8853 8854
        return -1;

8855 8856 8857 8858 8859 8860
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

J
Jiri Denemark 已提交
8861
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
8862 8863 8864 8865
        /* 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.
         */
8866 8867
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_NONE) < 0)
8868 8869 8870 8871 8872 8873 8874 8875 8876 8877
            goto cleanup;

        resume = true;
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto cleanup;
        }
    }

8878
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
8879 8880
    ret = qemuMonitorCreateSnapshot(priv->mon, snap->def->name);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898
    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);
    }
8899

8900 8901
cleanup:
    if (resume && virDomainObjIsActive(vm) &&
J
Jiri Denemark 已提交
8902
        qemuProcessStartCPUs(driver, vm, conn,
8903 8904
                             VIR_DOMAIN_RUNNING_UNPAUSED,
                             QEMU_ASYNC_JOB_NONE) < 0 &&
8905 8906 8907 8908 8909
        virGetLastError() == NULL) {
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("resuming after snapshot failed"));
    }

8910
endjob:
8911
    if (vm && qemuDomainObjEndJob(driver, vm) == 0) {
8912 8913
        /* Only possible if a transient vm quit while our locks were down,
         * in which case we don't want to save snapshot metadata.  */
8914
        *vmptr = NULL;
8915 8916
        ret = -1;
    }
8917 8918 8919 8920

    return ret;
}

8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010
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
9011 9012
qemuDomainSnapshotCreateSingleDiskActive(struct qemud_driver *driver,
                                         virDomainObjPtr vm,
9013
                                         virDomainSnapshotDiskDefPtr snap,
9014 9015
                                         virDomainDiskDefPtr disk,
                                         virDomainDiskDefPtr persistDisk)
9016 9017 9018 9019 9020
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *device = NULL;
    char *source = NULL;
    char *driverType = NULL;
9021 9022
    char *persistSource = NULL;
    char *persistDriverType = NULL;
9023
    int ret = -1;
9024 9025 9026 9027
    int fd = -1;
    char *origsrc = NULL;
    char *origdriver = NULL;
    bool need_unlink = false;
9028 9029 9030 9031 9032 9033 9034 9035 9036 9037

    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") &&
9038 9039 9040 9041 9042
         !(driverType = strdup("qcow2"))) ||
        (persistDisk &&
         (!(persistSource = strdup(source)) ||
          (STRNEQ_NULLABLE(persistDisk->driverType, "qcow2") &&
           !(persistDriverType = strdup("qcow2")))))) {
9043 9044 9045 9046
        virReportOOMError();
        goto cleanup;
    }

9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057
    /* 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;
9058
    disk->driverType = (char *) "raw"; /* Don't want to probe backing files */
9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074

    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 */
9075 9076 9077 9078 9079 9080
    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.  */
9081
    need_unlink = false;
9082 9083 9084 9085 9086 9087 9088 9089
    VIR_FREE(disk->src);
    disk->src = source;
    source = NULL;
    if (driverType) {
        VIR_FREE(disk->driverType);
        disk->driverType = driverType;
        driverType = NULL;
    }
9090 9091 9092 9093 9094 9095 9096 9097 9098 9099
    if (persistDisk) {
        VIR_FREE(persistDisk->src);
        persistDisk->src = persistSource;
        persistSource = NULL;
        if (persistDriverType) {
            VIR_FREE(persistDisk->driverType);
            persistDisk->driverType = persistDriverType;
            persistDriverType = NULL;
        }
    }
9100 9101

cleanup:
9102 9103 9104 9105 9106 9107
    if (origsrc) {
        disk->src = origsrc;
        disk->driverType = origdriver;
    }
    if (need_unlink && unlink(source))
        VIR_WARN("unable to unlink just-created %s", source);
9108 9109 9110
    VIR_FREE(device);
    VIR_FREE(source);
    VIR_FREE(driverType);
9111 9112
    VIR_FREE(persistSource);
    VIR_FREE(persistDriverType);
9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127
    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;
9128
    bool persist = false;
9129 9130 9131 9132

    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
        return -1;

9133 9134 9135 9136 9137 9138 9139
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }


9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165
    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++) {
9166 9167
        virDomainDiskDefPtr persistDisk = NULL;

9168 9169
        if (snap->def->disks[i].snapshot == VIR_DOMAIN_DISK_SNAPSHOT_NO)
            continue;
9170 9171 9172 9173 9174 9175 9176 9177 9178
        if (vm->newDef) {
            int indx = virDomainDiskIndexByName(vm->newDef,
                                                vm->def->disks[i]->dst,
                                                false);
            if (indx >= 0) {
                persistDisk = vm->newDef->disks[indx];
                persist = true;
            }
        }
9179

9180
        ret = qemuDomainSnapshotCreateSingleDiskActive(driver, vm,
9181
                                                       &snap->def->disks[i],
9182 9183
                                                       vm->def->disks[i],
                                                       persistDisk);
9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217
        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) {
9218 9219 9220
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0 ||
            (persist &&
             virDomainSaveConfig(driver->configDir, vm->newDef) < 0))
9221
            ret = -1;
9222 9223 9224 9225
    }

endjob:
    if (vm && (qemuDomainObjEndJob(driver, vm) == 0)) {
9226 9227 9228 9229 9230 9231 9232 9233 9234
            /* 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;
}

9235 9236 9237 9238
static virDomainSnapshotPtr
qemuDomainSnapshotCreateXML(virDomainPtr domain,
                            const char *xmlDesc,
                            unsigned int flags)
C
Chris Lalancette 已提交
9239 9240 9241
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
9242
    char *xml = NULL;
C
Chris Lalancette 已提交
9243 9244 9245
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
9246
    virDomainSnapshotDefPtr def = NULL;
9247 9248
    bool update_current = true;
    unsigned int parse_flags = 0;
9249
    virDomainSnapshotObjPtr other = NULL;
C
Chris Lalancette 已提交
9250

9251 9252
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE |
                  VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT |
9253
                  VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA |
9254 9255
                  VIR_DOMAIN_SNAPSHOT_CREATE_HALT |
                  VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY, NULL);
9256 9257 9258 9259 9260 9261 9262

    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;
9263 9264
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY)
        parse_flags |= VIR_DOMAIN_SNAPSHOT_PARSE_DISKS;
9265

C
Chris Lalancette 已提交
9266 9267 9268 9269 9270 9271 9272 9273 9274
    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;
    }

9275 9276 9277 9278 9279
    if (qemuProcessAutoDestroyActive(driver, vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is marked for auto destroy"));
        goto cleanup;
    }
9280 9281 9282 9283 9284
    if (!vm->persistent && (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot halt after transient domain snapshot"));
        goto cleanup;
    }
9285

9286 9287 9288
    if (!(def = virDomainSnapshotDefParseString(xmlDesc, driver->caps,
                                                QEMU_EXPECTED_VIRT_TYPES,
                                                parse_flags)))
C
Chris Lalancette 已提交
9289 9290
        goto cleanup;

9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324
    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 */
9325 9326 9327 9328 9329 9330 9331
        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;
        }
9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343
        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;
            }
9344 9345 9346 9347 9348 9349 9350 9351
            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;
            }
9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362
            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;
                }
            }
9363 9364 9365 9366
            if (other == vm->current_snapshot) {
                update_current = true;
                vm->current_snapshot = NULL;
            }
9367 9368 9369 9370 9371 9372
            /* 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;
9373
        }
9374 9375 9376 9377 9378 9379
        if (def->state == VIR_DOMAIN_DISK_SNAPSHOT && def->dom) {
            if (virDomainSnapshotAlignDisks(def,
                                            VIR_DOMAIN_DISK_SNAPSHOT_EXTERNAL,
                                            false) < 0)
                goto cleanup;
        }
9380 9381 9382 9383 9384 9385 9386 9387 9388 9389
    } 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;

9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411
        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);
        }
9412 9413
    }

9414 9415 9416
    if (snap)
        snap->def = def;
    else if (!(snap = virDomainSnapshotAssignDef(&vm->snapshots, def)))
C
Chris Lalancette 已提交
9417
        goto cleanup;
9418
    def = NULL;
C
Chris Lalancette 已提交
9419

9420 9421
    if (update_current)
        snap->def->current = true;
9422
    if (vm->current_snapshot) {
9423 9424 9425 9426 9427 9428
        if (!(flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE)) {
            snap->def->parent = strdup(vm->current_snapshot->def->name);
            if (snap->def->parent == NULL) {
                virReportOOMError();
                goto cleanup;
            }
9429
        }
9430
        if (update_current) {
9431 9432 9433 9434 9435 9436
            vm->current_snapshot->def->current = false;
            if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                                driver->snapshotDir) < 0)
                goto cleanup;
            vm->current_snapshot = NULL;
        }
9437
    }
9438

C
Chris Lalancette 已提交
9439
    /* actually do the snapshot */
9440 9441
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) {
        /* XXX Should we validate that the redefined snapshot even
9442 9443
         * makes sense, such as checking that qemu-img recognizes the
         * snapshot name in at least one of the domain's disks?  */
9444 9445 9446 9447 9448 9449 9450 9451 9452 9453
    } 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;
9454
    } else if (!virDomainObjIsActive(vm)) {
E
Eric Blake 已提交
9455
        if (qemuDomainSnapshotCreateInactive(driver, vm, snap) < 0)
C
Chris Lalancette 已提交
9456
            goto cleanup;
E
Eric Blake 已提交
9457
    } else {
9458
        if (qemuDomainSnapshotCreateActive(domain->conn, driver,
9459
                                           &vm, snap, flags) < 0)
9460
            goto cleanup;
C
Chris Lalancette 已提交
9461 9462
    }

9463
    /* If we fail after this point, there's not a whole lot we can
C
Chris Lalancette 已提交
9464 9465 9466 9467 9468 9469
     * 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:
9470
    if (vm) {
9471
        if (snapshot && !(flags & VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA)) {
9472
            if (qemuDomainSnapshotWriteMetadata(vm, snap,
9473
                                                driver->snapshotDir) < 0) {
9474 9475
                VIR_WARN("unable to save metadata for snapshot %s",
                         snap->def->name);
9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491
            } 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;
                }
            }
9492
        } else if (snap) {
9493
            virDomainSnapshotObjListRemove(&vm->snapshots, snap);
9494
        }
C
Chris Lalancette 已提交
9495
        virDomainObjUnlock(vm);
9496 9497
    }
    virDomainSnapshotDefFree(def);
9498
    VIR_FREE(xml);
C
Chris Lalancette 已提交
9499 9500 9501 9502 9503 9504
    qemuDriverUnlock(driver);
    return snapshot;
}

static int qemuDomainSnapshotListNames(virDomainPtr domain, char **names,
                                       int nameslen,
9505
                                       unsigned int flags)
C
Chris Lalancette 已提交
9506 9507 9508 9509 9510
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

9511
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
9512 9513
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
9514

C
Chris Lalancette 已提交
9515 9516 9517 9518 9519 9520 9521 9522 9523 9524
    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;
    }

9525 9526
    n = virDomainSnapshotObjListGetNames(&vm->snapshots, names, nameslen,
                                         flags);
C
Chris Lalancette 已提交
9527 9528 9529 9530 9531 9532 9533 9534 9535

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

static int qemuDomainSnapshotNum(virDomainPtr domain,
9536
                                 unsigned int flags)
C
Chris Lalancette 已提交
9537 9538 9539 9540 9541
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

9542
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
9543 9544
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
9545

C
Chris Lalancette 已提交
9546 9547 9548 9549 9550 9551 9552 9553 9554 9555
    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;
    }

9556 9557 9558 9559
    /* All qemu snapshots have libvirt metadata, so
     * VIR_DOMAIN_SNAPSHOT_LIST_METADATA makes no difference to our
     * answer.  */

9560
    n = virDomainSnapshotObjListNum(&vm->snapshots, flags);
C
Chris Lalancette 已提交
9561 9562 9563 9564 9565 9566 9567 9568

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

9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580
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 |
9581 9582
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601

    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 已提交
9602
    n = virDomainSnapshotObjListGetNamesFrom(snap, names, nameslen, flags);
9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620

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 |
9621 9622
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645

    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 已提交
9646
    n = virDomainSnapshotObjListNumFrom(snap, flags);
9647 9648 9649 9650 9651 9652 9653 9654

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

C
Chris Lalancette 已提交
9655 9656
static virDomainSnapshotPtr qemuDomainSnapshotLookupByName(virDomainPtr domain,
                                                           const char *name,
9657
                                                           unsigned int flags)
C
Chris Lalancette 已提交
9658 9659 9660 9661 9662 9663
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;

9664 9665
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692
    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,
9693
                                        unsigned int flags)
C
Chris Lalancette 已提交
9694 9695 9696 9697 9698
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

9699 9700
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719
    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;
}

9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764
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 已提交
9765
static virDomainSnapshotPtr qemuDomainSnapshotCurrent(virDomainPtr domain,
9766
                                                      unsigned int flags)
C
Chris Lalancette 已提交
9767 9768 9769 9770 9771
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotPtr snapshot = NULL;

9772 9773
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798
    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;
}

9799 9800
static char *qemuDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                                          unsigned int flags)
C
Chris Lalancette 已提交
9801 9802 9803 9804 9805 9806 9807
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *xml = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

9808
    virCheckFlags(VIR_DOMAIN_XML_SECURE, NULL);
9809

C
Chris Lalancette 已提交
9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826
    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;
    }

9827
    xml = virDomainSnapshotDefFormat(uuidstr, snap->def, flags, 0);
C
Chris Lalancette 已提交
9828 9829 9830 9831 9832 9833 9834 9835

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

9836 9837
/* The domain is expected to be locked and inactive. */
static int
E
Eric Blake 已提交
9838 9839
qemuDomainSnapshotRevertInactive(struct qemud_driver *driver,
                                 virDomainObjPtr vm,
9840 9841 9842
                                 virDomainSnapshotObjPtr snap)
{
    /* Try all disks, but report failure if we skipped any.  */
E
Eric Blake 已提交
9843
    int ret = qemuDomainSnapshotForEachQcow2(driver, vm, snap, "-a", true);
9844 9845 9846
    return ret > 0 ? -1 : ret;
}

C
Chris Lalancette 已提交
9847
static int qemuDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
9848
                                      unsigned int flags)
C
Chris Lalancette 已提交
9849 9850 9851 9852 9853 9854 9855
{
    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;
9856
    virDomainEventPtr event2 = NULL;
9857
    int detail;
C
Chris Lalancette 已提交
9858 9859
    qemuDomainObjPrivatePtr priv;
    int rc;
9860
    virDomainDefPtr config = NULL;
C
Chris Lalancette 已提交
9861

9862
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING |
9863 9864
                  VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED |
                  VIR_DOMAIN_SNAPSHOT_REVERT_FORCE, -1);
9865

9866 9867 9868 9869 9870 9871 9872 9873 9874 9875
    /* 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
9876 9877
     * Also, several transitions occur even if we fail partway through,
     * and use of FORCE can cause multiple transitions.
9878 9879
     */

C
Chris Lalancette 已提交
9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896
    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;
    }

9897 9898 9899 9900 9901 9902 9903 9904 9905 9906
    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;
    }
9907 9908 9909 9910 9911 9912
    if (snap->def->state == VIR_DOMAIN_DISK_SNAPSHOT) {
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("revert to external disk snapshot not supported "
                          "yet"));
        goto cleanup;
    }
9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930
    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;
        }
    }

9931

9932 9933 9934 9935 9936 9937 9938 9939 9940 9941
    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?  */
    }

9942 9943 9944 9945 9946
    /* 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?  */
9947
    snap->def->current = true;
9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960
    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 已提交
9961

9962
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
C
Chris Lalancette 已提交
9963 9964 9965 9966
        goto cleanup;

    if (snap->def->state == VIR_DOMAIN_RUNNING
        || snap->def->state == VIR_DOMAIN_PAUSED) {
9967 9968 9969 9970 9971 9972 9973 9974 9975
        /* 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 已提交
9976
        if (virDomainObjIsActive(vm)) {
9977
            /* Transitions 5, 6, 8, 9 */
9978 9979
            /* Check for ABI compatibility.  */
            if (config && !virDomainDefCheckABIStability(vm->def, config)) {
9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999
                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;
10000 10001
            }

C
Chris Lalancette 已提交
10002
            priv = vm->privateData;
10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022
            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;
                }
            }
10023
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
C
Chris Lalancette 已提交
10024 10025
            rc = qemuMonitorLoadSnapshot(priv->mon, snap->def->name);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
10026 10027 10028
            if (rc < 0) {
                /* XXX resume domain if it was running before the
                 * failed loadvm attempt? */
10029
                goto endjob;
10030
            }
10031 10032
            if (config)
                virDomainObjAssignDef(vm, config, false);
E
Eric Blake 已提交
10033
        } else {
10034
            /* Transitions 2, 3 */
10035
        load:
10036
            was_stopped = true;
10037 10038 10039
            if (config)
                virDomainObjAssignDef(vm, config, false);

10040
            rc = qemuProcessStart(snapshot->domain->conn, driver, vm, NULL,
10041
                                  true, false, -1, NULL, snap,
10042
                                  VIR_VM_OP_CREATE);
10043
            virDomainAuditStart(vm, "from-snapshot", rc >= 0);
10044 10045 10046 10047
            detail = VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT;
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STARTED,
                                             detail);
C
Chris Lalancette 已提交
10048
            if (rc < 0)
10049
                goto endjob;
C
Chris Lalancette 已提交
10050 10051
        }

10052
        /* Touch up domain state.  */
10053 10054 10055
        if (!(flags & VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING) &&
            (snap->def->state == VIR_DOMAIN_PAUSED ||
             (flags & VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED))) {
10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075
            /* 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 已提交
10076
            if (rc < 0)
10077
                goto endjob;
10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092
            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 已提交
10093
        }
E
Eric Blake 已提交
10094
    } else {
10095
        /* Transitions 1, 4, 7 */
10096 10097 10098
        /* 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 已提交
10099 10100 10101
         */

        if (virDomainObjIsActive(vm)) {
10102
            /* Transitions 4, 7 */
J
Jiri Denemark 已提交
10103
            qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT);
10104
            virDomainAuditStop(vm, "from-snapshot");
10105
            detail = VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT;
C
Chris Lalancette 已提交
10106 10107
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STOPPED,
10108
                                             detail);
10109 10110
        }

E
Eric Blake 已提交
10111
        if (qemuDomainSnapshotRevertInactive(driver, vm, snap) < 0) {
10112
            if (!vm->persistent) {
10113
                if (qemuDomainObjEndJob(driver, vm) > 0)
10114
                    qemuDomainRemoveInactive(driver, vm);
10115
                vm = NULL;
10116
                goto cleanup;
10117
            }
10118
            goto endjob;
C
Chris Lalancette 已提交
10119
        }
10120 10121
        if (config)
            virDomainObjAssignDef(vm, config, false);
10122

10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136
        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,
                                  VIR_VM_OP_CREATE);
            virDomainAuditStart(vm, "from-snapshot", rc >= 0);
            if (rc < 0) {
                if (!vm->persistent) {
                    if (qemuDomainObjEndJob(driver, vm) > 0)
10137
                        qemuDomainRemoveInactive(driver, vm);
10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153
                    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 已提交
10154 10155 10156 10157
    }

    ret = 0;

10158
endjob:
10159
    if (vm && qemuDomainObjEndJob(driver, vm) == 0)
C
Chris Lalancette 已提交
10160 10161
        vm = NULL;

10162
cleanup:
10163 10164 10165 10166 10167 10168 10169 10170 10171
    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;
    }
10172
    if (event) {
C
Chris Lalancette 已提交
10173
        qemuDomainEventQueue(driver, event);
10174 10175 10176
        if (event2)
            qemuDomainEventQueue(driver, event2);
    }
C
Chris Lalancette 已提交
10177 10178 10179 10180 10181 10182 10183
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);

    return ret;
}

10184 10185
struct snap_reparent {
    struct qemud_driver *driver;
10186
    virDomainSnapshotObjPtr parent;
10187 10188
    virDomainObjPtr vm;
    int err;
10189
    virDomainSnapshotObjPtr last;
10190 10191 10192 10193
};

static void
qemuDomainSnapshotReparentChildren(void *payload,
10194
                                   const void *name ATTRIBUTE_UNUSED,
10195 10196 10197 10198 10199 10200 10201 10202 10203
                                   void *data)
{
    virDomainSnapshotObjPtr snap = payload;
    struct snap_reparent *rep = data;

    if (rep->err < 0) {
        return;
    }

10204
    VIR_FREE(snap->def->parent);
10205
    snap->parent = rep->parent;
10206

10207 10208
    if (rep->parent) {
        snap->def->parent = strdup(rep->parent->def->name);
10209

10210 10211 10212 10213
        if (snap->def->parent == NULL) {
            virReportOOMError();
            rep->err = -1;
            return;
10214 10215
        }
    }
10216

10217 10218 10219
    if (!snap->sibling)
        rep->last = snap;

10220 10221
    rep->err = qemuDomainSnapshotWriteMetadata(rep->vm, snap,
                                               rep->driver->snapshotDir);
10222 10223
}

C
Chris Lalancette 已提交
10224 10225 10226 10227 10228 10229 10230 10231
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];
10232
    struct qemu_snap_remove rem;
10233
    struct snap_reparent rep;
10234
    bool metadata_only = !!(flags & VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY);
10235
    int external = 0;
C
Chris Lalancette 已提交
10236

10237
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
10238 10239
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY |
                  VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY, -1);
10240

C
Chris Lalancette 已提交
10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257
    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;
    }

10258 10259 10260 10261 10262
    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 已提交
10263
            virDomainSnapshotForEachDescendant(snap,
10264 10265 10266 10267 10268 10269 10270 10271 10272 10273
                                               qemuDomainSnapshotCountExternal,
                                               &external);
        if (external) {
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                            _("deletion of %d external disk snapshots not "
                              "supported yet"), external);
            goto cleanup;
        }
    }

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

10277 10278
    if (flags & (VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                 VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY)) {
C
Chris Lalancette 已提交
10279 10280
        rem.driver = driver;
        rem.vm = vm;
10281
        rem.metadata_only = metadata_only;
C
Chris Lalancette 已提交
10282
        rem.err = 0;
10283
        rem.current = false;
E
Eric Blake 已提交
10284
        virDomainSnapshotForEachDescendant(snap,
E
Eric Blake 已提交
10285
                                           qemuDomainSnapshotDiscardAll,
10286
                                           &rem);
C
Chris Lalancette 已提交
10287
        if (rem.err < 0)
10288
            goto endjob;
10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300
        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;
                }
            }
10301
            vm->current_snapshot = snap;
10302
        }
10303
    } else if (snap->nchildren) {
10304
        rep.driver = driver;
10305
        rep.parent = snap->parent;
10306 10307
        rep.vm = vm;
        rep.err = 0;
10308
        rep.last = NULL;
E
Eric Blake 已提交
10309
        virDomainSnapshotForEachChild(snap,
10310 10311
                                      qemuDomainSnapshotReparentChildren,
                                      &rep);
10312 10313
        if (rep.err < 0)
            goto endjob;
10314 10315 10316 10317 10318 10319 10320 10321 10322 10323
        /* 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 已提交
10324 10325
    }

10326 10327 10328
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY) {
        snap->nchildren = 0;
        snap->first_child = NULL;
10329
        ret = 0;
10330 10331
    } else {
        virDomainSnapshotDropParent(&vm->snapshots, snap);
10332
        ret = qemuDomainSnapshotDiscard(driver, vm, snap, true, metadata_only);
10333
    }
C
Chris Lalancette 已提交
10334

10335
endjob:
10336
    if (qemuDomainObjEndJob(driver, vm) == 0)
10337 10338
        vm = NULL;

C
Chris Lalancette 已提交
10339 10340 10341 10342 10343 10344
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
10345

10346 10347 10348 10349 10350 10351 10352
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;
10353
    bool hmp;
10354

10355
    virCheckFlags(VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP, -1);
10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372

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

10373 10374 10375 10376 10377 10378 10379 10380 10381
    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;
    }

10382 10383
    priv = vm->privateData;

10384
    qemuDomainObjTaint(driver, vm, VIR_DOMAIN_TAINT_CUSTOM_MONITOR, -1);
10385

10386 10387
    hmp = !!(flags & VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP);

10388
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
10389
    ret = qemuMonitorArbitraryCommand(priv->mon, cmd, result, hmp);
10390
    qemuDomainObjExitMonitorWithDriver(driver, vm);
10391 10392

endjob:
10393
    if (qemuDomainObjEndJob(driver, vm) == 0) {
10394 10395 10396 10397 10398 10399 10400 10401 10402 10403
        vm = NULL;
    }

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

10404

10405 10406 10407 10408 10409 10410 10411 10412 10413 10414
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;
10415
    char *pidfile = NULL;
10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459

    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;

10460
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474
        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:
10475
    if (qemuDomainObjEndJob(driver, vm) == 0) {
10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490
        vm = NULL;
        goto cleanup;
    }

cleanup:
    virDomainDefFree(def);
    virDomainChrSourceDefFree(monConfig);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    VIR_FREE(pidfile);
    return dom;
}


10491 10492
static int
qemuDomainOpenConsole(virDomainPtr dom,
10493
                      const char *dev_name,
10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520
                      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;
    }

10521
    if (dev_name) {
10522 10523 10524 10525 10526
        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];
        }
10527
        for (i = 0 ; !chr && i < vm->def->nserials ; i++) {
10528
            if (STREQ(dev_name, vm->def->serials[i]->info.alias))
10529 10530 10531
                chr = vm->def->serials[i];
        }
        for (i = 0 ; !chr && i < vm->def->nparallels ; i++) {
10532
            if (STREQ(dev_name, vm->def->parallels[i]->info.alias))
10533 10534 10535
                chr = vm->def->parallels[i];
        }
    } else {
10536 10537
        if (vm->def->nconsoles)
            chr = vm->def->consoles[0];
10538 10539 10540 10541 10542 10543 10544
        else if (vm->def->nserials)
            chr = vm->def->serials[0];
    }

    if (!chr) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find character device %s"),
10545
                        NULLSTR(dev_name));
10546 10547 10548
        goto cleanup;
    }

10549
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
10550 10551
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"),
10552
                        NULLSTR(dev_name));
10553 10554 10555
        goto cleanup;
    }

10556
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
E
Eric Blake 已提交
10557
                            0, 0, O_RDWR) < 0)
10558 10559 10560 10561 10562 10563 10564 10565 10566 10567
        goto cleanup;

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

10568 10569 10570 10571
static const char *
qemuDiskPathToAlias(virDomainObjPtr vm, const char *path) {
    int i;
    char *ret = NULL;
10572
    virDomainDiskDefPtr disk;
10573

10574 10575 10576
    i = virDomainDiskIndexByName(vm->def, path, true);
    if (i < 0)
        goto cleanup;
10577

10578
    disk = vm->def->disks[i];
10579

10580 10581 10582 10583 10584 10585 10586 10587
    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;
10588 10589 10590
        }
    }

10591
cleanup:
10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632
    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];
    const char *device = NULL;
    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;
10633 10634 10635 10636 10637 10638 10639

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

10640
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
10641 10642 10643
    priv = vm->privateData;
    ret = qemuMonitorBlockJob(priv->mon, device, bandwidth, info, mode);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
10644 10645

endjob:
10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685
    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)
{
10686 10687
    int ret;

10688
    virCheckFlags(0, -1);
10689 10690 10691 10692 10693
    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;
10694
}
10695

10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 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 10761 10762 10763 10764 10765
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;
}


10766
static virDriver qemuDriver = {
10767 10768
    .no = VIR_DRV_QEMU,
    .name = "QEMU",
10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786
    .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 */
10787 10788
    .domainShutdown = qemuDomainShutdown, /* 0.2.0 */
    .domainReboot = qemuDomainReboot, /* 0.9.3 */
10789
    .domainReset = qemuDomainReset, /* 0.9.7 */
10790 10791
    .domainDestroy = qemuDomainDestroy, /* 0.2.0 */
    .domainDestroyFlags = qemuDomainDestroyFlags, /* 0.9.4 */
10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802
    .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 */
10803
    .domainGetControlInfo = qemuDomainGetControlInfo, /* 0.9.3 */
10804 10805
    .domainSave = qemuDomainSave, /* 0.2.0 */
    .domainSaveFlags = qemuDomainSaveFlags, /* 0.9.4 */
10806
    .domainRestore = qemuDomainRestore, /* 0.2.0 */
10807
    .domainRestoreFlags = qemuDomainRestoreFlags, /* 0.9.4 */
10808 10809
    .domainSaveImageGetXMLDesc = qemuDomainSaveImageGetXMLDesc, /* 0.9.4 */
    .domainSaveImageDefineXML = qemuDomainSaveImageDefineXML, /* 0.9.4 */
10810 10811
    .domainCoreDump = qemudDomainCoreDump, /* 0.7.0 */
    .domainScreenshot = qemuDomainScreenshot, /* 0.9.2 */
10812 10813
    .domainSetVcpus = qemuDomainSetVcpus, /* 0.4.4 */
    .domainSetVcpusFlags = qemuDomainSetVcpusFlags, /* 0.8.5 */
10814 10815
    .domainGetVcpusFlags = qemudDomainGetVcpusFlags, /* 0.8.5 */
    .domainPinVcpu = qemudDomainPinVcpu, /* 0.4.4 */
10816
    .domainPinVcpuFlags = qemudDomainPinVcpuFlags, /* 0.9.3 */
E
Eric Blake 已提交
10817
    .domainGetVcpuPinInfo = qemudDomainGetVcpuPinInfo, /* 0.9.3 */
10818 10819 10820 10821 10822 10823 10824 10825 10826
    .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 */
10827 10828
    .domainCreate = qemuDomainStart, /* 0.2.0 */
    .domainCreateWithFlags = qemuDomainStartWithFlags, /* 0.8.2 */
10829 10830
    .domainDefineXML = qemudDomainDefine, /* 0.2.0 */
    .domainUndefine = qemudDomainUndefine, /* 0.2.0 */
10831
    .domainUndefineFlags = qemuDomainUndefineFlags, /* 0.9.4 */
10832 10833 10834 10835 10836 10837 10838 10839 10840
    .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 */
10841
    .domainGetSchedulerParametersFlags = qemuGetSchedulerParametersFlags, /* 0.9.2 */
10842
    .domainSetSchedulerParameters = qemuSetSchedulerParameters, /* 0.7.0 */
10843
    .domainSetSchedulerParametersFlags = qemuSetSchedulerParametersFlags, /* 0.9.2 */
10844
    .domainMigratePerform = qemudDomainMigratePerform, /* 0.5.0 */
10845 10846
    .domainBlockStats = qemuDomainBlockStats, /* 0.4.1 */
    .domainBlockStatsFlags = qemuDomainBlockStatsFlags, /* 0.9.5 */
10847 10848 10849 10850 10851
    .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 */
10852
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
10853
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874
    .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 */
10875
    .domainMigrateGetMaxSpeed = qemuDomainMigrateGetMaxSpeed, /* 0.9.5 */
10876 10877 10878 10879 10880 10881 10882 10883 10884
    .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 */
10885 10886
    .domainSnapshotNumChildren = qemuDomainSnapshotNumChildren, /* 0.9.7 */
    .domainSnapshotListChildrenNames = qemuDomainSnapshotListChildrenNames, /* 0.9.7 */
10887 10888
    .domainSnapshotLookupByName = qemuDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = qemuDomainHasCurrentSnapshot, /* 0.8.0 */
10889
    .domainSnapshotGetParent = qemuDomainSnapshotGetParent, /* 0.9.7 */
10890 10891 10892 10893
    .domainSnapshotCurrent = qemuDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = qemuDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = qemuDomainSnapshotDelete, /* 0.8.0 */
    .qemuDomainMonitorCommand = qemuDomainMonitorCommand, /* 0.8.3 */
10894
    .qemuDomainAttach = qemuDomainAttach, /* 0.9.4 */
10895
    .domainOpenConsole = qemuDomainOpenConsole, /* 0.8.6 */
10896
    .domainOpenGraphics = qemuDomainOpenGraphics, /* 0.9.7 */
10897
    .domainInjectNMI = qemuDomainInjectNMI, /* 0.9.2 */
10898 10899 10900 10901 10902 10903
    .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 */
10904
    .domainSendKey = qemuDomainSendKey, /* 0.9.4 */
10905 10906 10907 10908
    .domainBlockJobAbort = qemuDomainBlockJobAbort, /* 0.9.4 */
    .domainGetBlockJobInfo = qemuDomainGetBlockJobInfo, /* 0.9.4 */
    .domainBlockJobSetSpeed = qemuDomainBlockJobSetSpeed, /* 0.9.4 */
    .domainBlockPull = qemuDomainBlockPull, /* 0.9.4 */
10909 10910 10911
};


10912
static virStateDriver qemuStateDriver = {
10913
    .name = "QEMU",
10914 10915 10916 10917
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
10918
};
10919

10920
static void
10921
qemuVMDriverLock(void) {
10922 10923 10924 10925 10926
    qemuDriverLock(qemu_driver);
};


static void
10927
qemuVMDriverUnlock(void) {
10928 10929 10930 10931
    qemuDriverUnlock(qemu_driver);
};


10932 10933 10934 10935 10936 10937 10938 10939 10940
static int
qemuVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                    virHashIterator iter, void *data)
{
    virHashForEach(qemu_driver->domains.objs, iter, data);

    return 0;
}

S
Stefan Berger 已提交
10941 10942
static virNWFilterCallbackDriver qemuCallbackDriver = {
    .name = "QEMU",
10943 10944 10945
    .vmFilterRebuild = qemuVMFilterRebuild,
    .vmDriverLock = qemuVMDriverLock,
    .vmDriverUnlock = qemuVMDriverUnlock,
S
Stefan Berger 已提交
10946 10947
};

10948
int qemuRegister(void) {
10949 10950
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
S
Stefan Berger 已提交
10951
    virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);
10952 10953
    return 0;
}