qemu_driver.c 290.2 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 "virkeycode.h"
91

92 93
#define VIR_FROM_THIS VIR_FROM_QEMU

94 95
#define QEMU_NB_MEM_PARAM  3

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

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

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

114
#define QEMU_NB_BLKIO_PARAM  1
115

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

118 119
static int qemudShutdown(void);

120 121 122 123 124 125
static int qemuDomainObjStart(virConnectPtr conn,
                              struct qemud_driver *driver,
                              virDomainObjPtr vm,
                              bool start_paused,
                              bool autodestroy,
                              bool bypass_cache);
J
Jiri Denemark 已提交
126

127
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
128

129
struct qemud_driver *qemu_driver = NULL;
130 131


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

137
static void
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

    virDomainObjLock(vm);
145
    virResetLastError();
146 147
    if (qemuDomainObjBeginJobWithDriver(data->driver, vm,
                                        QEMU_JOB_MODIFY) < 0) {
148 149 150 151 152 153 154
        err = virGetLastError();
        VIR_ERROR(_("Failed to start job on VM '%s': %s"),
                  vm->def->name,
                  err ? err->message : _("unknown error"));
    } else {
        if (vm->autostart &&
            !virDomainObjIsActive(vm) &&
155
            qemuDomainObjStart(data->conn, data->driver, vm,
156 157
                               false, false,
                               data->driver->autoStartBypassCache) < 0) {
158
            err = virGetLastError();
159
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
160
                      vm->def->name,
161
                      err ? err->message : _("unknown error"));
162
        }
163

164
        if (qemuDomainObjEndJob(data->driver, vm) == 0)
165
            vm = NULL;
166
    }
167 168 169

    if (vm)
        virDomainObjUnlock(vm);
170 171
}

172

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

187
    qemuDriverLock(driver);
188
    virHashForEach(driver->domains.objs, qemuAutostartDomain, &data);
189
    qemuDriverUnlock(driver);
190

191 192
    if (conn)
        virConnectClose(conn);
193 194
}

195
static int
196
qemuSecurityInit(struct qemud_driver *driver)
197
{
198 199 200 201
    virSecurityManagerPtr mgr = virSecurityManagerNew(driver->securityDriverName,
                                                      driver->allowDiskFormatProbing);
    if (!mgr)
        goto error;
D
Daniel Veillard 已提交
202

203 204 205 206 207 208 209
    if (driver->privileged) {
        virSecurityManagerPtr dac = virSecurityManagerNewDAC(driver->user,
                                                             driver->group,
                                                             driver->allowDiskFormatProbing,
                                                             driver->dynamicOwnership);
        if (!dac)
            goto error;
210

211
        if (!(driver->securityManager = virSecurityManagerNewStack(mgr,
E
Eric Blake 已提交
212 213 214
                                                                   dac))) {

            virSecurityManagerFree(dac);
215
            goto error;
E
Eric Blake 已提交
216
        }
217 218 219
    } else {
        driver->securityManager = mgr;
    }
D
Daniel Veillard 已提交
220

221
    return 0;
222

223
error:
224
    VIR_ERROR(_("Failed to initialize security drivers"));
225 226 227
    virSecurityManagerFree(mgr);
    return -1;
}
228

229

230 231 232 233 234
static virCapsPtr
qemuCreateCapabilities(virCapsPtr oldcaps,
                       struct qemud_driver *driver)
{
    virCapsPtr caps;
235

236 237 238 239
    /* Basic host arch / guest machine capabilities */
    if (!(caps = qemuCapsInit(oldcaps))) {
        virReportOOMError();
        return NULL;
240 241
    }

242 243 244 245 246 247
    if (driver->allowDiskFormatProbing) {
        caps->defaultDiskDriverName = NULL;
        caps->defaultDiskDriverType = NULL;
    } else {
        caps->defaultDiskDriverName = "qemu";
        caps->defaultDiskDriverType = "raw";
248 249
    }

250 251
    qemuDomainSetPrivateDataHooks(caps);
    qemuDomainSetNamespaceHooks(caps);
252

253 254 255 256
    if (virGetHostUUID(caps->host.host_uuid)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot get the host uuid"));
        goto err_exit;
257
    }
258

259 260
    /* Security driver data */
    const char *doi, *model;
261

262 263 264 265 266 267 268
    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;
269
    }
270

271 272
    VIR_DEBUG("Initialized caps for security driver \"%s\" with "
              "DOI \"%s\"", model, doi);
273

274
    return caps;
275

276 277 278 279
no_memory:
    virReportOOMError();
err_exit:
    virCapabilitiesFree(caps);
280 281 282
    return NULL;
}

283
static void qemuDomainSnapshotLoad(void *payload,
284
                                   const void *name ATTRIBUTE_UNUSED,
285
                                   void *data)
286
{
287 288 289 290 291 292 293 294 295 296
    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;
    char ebuf[1024];
297

298 299 300 301
    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);
302
        goto cleanup;
303 304
    }

305 306
    VIR_INFO("Scanning for snapshots for domain %s in %s", vm->def->name,
             snapDir);
307

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

316 317 318
    while ((entry = readdir(dir))) {
        if (entry->d_name[0] == '.')
            continue;
319

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

324
        if (virAsprintf(&fullpath, "%s/%s", snapDir, entry->d_name) < 0) {
325
            VIR_ERROR(_("Failed to allocate memory for path"));
326 327
            continue;
        }
328

329 330 331 332 333 334 335 336
        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;
        }
337

338 339 340 341 342 343 344 345
        def = virDomainSnapshotDefParseString(xmlStr, 0);
        if (def == NULL) {
            /* Nothing we can do here, skip this one */
            VIR_ERROR(_("Failed to parse snapshot XML from file '%s'"), fullpath);
            VIR_FREE(fullpath);
            VIR_FREE(xmlStr);
            continue;
        }
346

347
        virDomainSnapshotAssignDef(&vm->snapshots, def);
348

349 350
        VIR_FREE(fullpath);
        VIR_FREE(xmlStr);
351 352
    }

353 354 355 356 357 358 359 360
    /* 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.
     */
361

362
    virResetLastError();
363

364 365 366 367
cleanup:
    if (dir)
        closedir(dir);
    VIR_FREE(snapDir);
368 369 370
    virDomainObjUnlock(vm);
}

371 372 373 374 375
/**
 * qemudStartup:
 *
 * Initialization function for the QEmu daemon
 */
376
static int
377 378 379 380 381
qemudStartup(int privileged) {
    char *base = NULL;
    char *driverConf = NULL;
    int rc;
    virConnectPtr conn = NULL;
382

383 384
    if (VIR_ALLOC(qemu_driver) < 0)
        return -1;
385

386
    if (virMutexInit(&qemu_driver->lock) < 0) {
387
        VIR_ERROR(_("cannot initialize mutex"));
388 389
        VIR_FREE(qemu_driver);
        return -1;
390
    }
391 392
    qemuDriverLock(qemu_driver);
    qemu_driver->privileged = privileged;
393

394 395
    /* Don't have a dom0 so start from 1 */
    qemu_driver->nextvmid = 1;
396

397 398
    if (virDomainObjListInit(&qemu_driver->domains) < 0)
        goto out_of_memory;
399

400 401 402 403 404 405
    /* Init domain events */
    qemu_driver->domainEventState = virDomainEventStateNew(qemuDomainEventFlush,
                                                           qemu_driver,
                                                           NULL,
                                                           true);
    if (!qemu_driver->domainEventState)
406
        goto error;
407

408 409 410 411
    /* Allocate bitmap for vnc port reservation */
    if ((qemu_driver->reservedVNCPorts =
         virBitmapAlloc(QEMU_VNC_PORT_MAX - QEMU_VNC_PORT_MIN)) == NULL)
        goto out_of_memory;
412

413 414 415
    /* read the host sysinfo */
    if (privileged)
        qemu_driver->hostsysinfo = virSysinfoRead();
416

417 418 419 420
    if (privileged) {
        if (virAsprintf(&qemu_driver->logDir,
                        "%s/log/libvirt/qemu", LOCALSTATEDIR) == -1)
            goto out_of_memory;
421

422 423
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
            goto out_of_memory;
424

425 426 427
        if (virAsprintf(&qemu_driver->stateDir,
                      "%s/run/libvirt/qemu", LOCALSTATEDIR) == -1)
            goto out_of_memory;
428

429 430 431
        if (virAsprintf(&qemu_driver->libDir,
                      "%s/lib/libvirt/qemu", LOCALSTATEDIR) == -1)
            goto out_of_memory;
432

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
        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;
450

451 452 453 454 455
        if (virAsprintf(&qemu_driver->logDir,
                        "%s/.libvirt/qemu/log", userdir) == -1) {
            VIR_FREE(userdir);
            goto out_of_memory;
        }
456

457 458 459 460 461
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1) {
            VIR_FREE(userdir);
            goto out_of_memory;
        }
        VIR_FREE(userdir);
462

463 464 465 466 467 468 469 470 471 472 473 474
        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;
475
    }
H
Hu Tao 已提交
476

477
    if (virFileMakePath(qemu_driver->stateDir) < 0) {
478 479 480 481
        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 已提交
482
    }
483
    if (virFileMakePath(qemu_driver->libDir) < 0) {
484 485 486 487 488
        char ebuf[1024];
        VIR_ERROR(_("Failed to create lib dir '%s': %s"),
                  qemu_driver->libDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
489
    if (virFileMakePath(qemu_driver->cacheDir) < 0) {
490 491 492 493 494
        char ebuf[1024];
        VIR_ERROR(_("Failed to create cache dir '%s': %s"),
                  qemu_driver->cacheDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
495
    if (virFileMakePath(qemu_driver->saveDir) < 0) {
496 497 498 499 500
        char ebuf[1024];
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
                  qemu_driver->saveDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
501
    if (virFileMakePath(qemu_driver->snapshotDir) < 0) {
502 503 504 505 506
        char ebuf[1024];
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
                  qemu_driver->snapshotDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
507
    if (virFileMakePath(qemu_driver->autoDumpPath) < 0) {
508 509 510 511
        char ebuf[1024];
        VIR_ERROR(_("Failed to create dump dir '%s': %s"),
                  qemu_driver->autoDumpPath, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
512 513
    }

514 515 516 517 518 519 520
    /* 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;
521

522
    VIR_FREE(base);
523

524 525 526 527 528
    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)));
529 530
    }

531 532 533 534
    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
        goto error;
    }
    VIR_FREE(driverConf);
535

536 537 538 539 540 541 542 543
    /* 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;
    }

544 545
    if (qemuSecurityInit(qemu_driver) < 0)
        goto error;
546

547 548 549
    if ((qemu_driver->caps = qemuCreateCapabilities(NULL,
                                                    qemu_driver)) == NULL)
        goto error;
550

551
    if ((qemu_driver->activePciHostdevs = pciDeviceListNew()) == NULL)
552
        goto error;
553

554 555 556 557 558 559
    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;
560
        }
561
        if (chown(qemu_driver->cacheDir, qemu_driver->user, qemu_driver->group) < 0) {
562
            virReportSystemError(errno,
563 564 565
                                 _("unable to set ownership of '%s' to %d:%d"),
                                 qemu_driver->cacheDir, qemu_driver->user, qemu_driver->group);
            goto error;
566
        }
567 568 569 570 571 572 573 574 575 576 577
        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;
578
        }
579
    }
580

581 582 583 584 585 586
    /* 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
587
     */
588 589 590 591 592
    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;
593

594 595
        if (virFileMakePath(mempath) < 0) {
            virReportSystemError(errno,
596 597 598
                                 _("unable to create hugepage path %s"), mempath);
            VIR_FREE(mempath);
            goto error;
599
        }
600 601 602 603 604 605 606
        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 已提交
607
        }
E
Eric Blake 已提交
608

609
        qemu_driver->hugepage_path = mempath;
610
    }
611

612 613 614
    if (qemuProcessAutoDestroyInit(qemu_driver) < 0)
        goto error;

615 616 617 618 619
    /* Get all the running persistent or transient configs first */
    if (virDomainLoadAllConfigs(qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->stateDir,
                                NULL,
M
Matthias Bolte 已提交
620 621
                                1, QEMU_EXPECTED_VIRT_TYPES,
                                NULL, NULL) < 0)
622
        goto error;
623

624 625 626
    conn = virConnectOpen(qemu_driver->privileged ?
                          "qemu:///system" :
                          "qemu:///session");
627

628
    qemuProcessReconnectAll(conn, qemu_driver);
629

630 631 632 633 634
    /* Then inactive persistent configs */
    if (virDomainLoadAllConfigs(qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->configDir,
                                qemu_driver->autostartDir,
M
Matthias Bolte 已提交
635 636
                                0, QEMU_EXPECTED_VIRT_TYPES,
                                NULL, NULL) < 0)
637
        goto error;
638

639

640 641
    virHashForEach(qemu_driver->domains.objs, qemuDomainSnapshotLoad,
                   qemu_driver->snapshotDir);
642

643 644 645
    qemu_driver->workerPool = virThreadPoolNew(0, 1, processWatchdogEvent, qemu_driver);
    if (!qemu_driver->workerPool)
        goto error;
646

647 648 649 650
    qemuDriverUnlock(qemu_driver);

    qemuAutostartDomains(qemu_driver);

651 652
    if (conn)
        virConnectClose(conn);
653

654
    return 0;
655

656 657 658 659 660 661 662 663 664 665
out_of_memory:
    virReportOOMError();
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
    if (conn)
        virConnectClose(conn);
    VIR_FREE(base);
    VIR_FREE(driverConf);
    qemudShutdown();
666
    return -1;
667 668
}

669 670 671
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;
672

673 674 675 676 677 678 679
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
E
Eric Blake 已提交
680
    }
681
}
E
Eric Blake 已提交
682

683 684 685 686 687 688 689 690 691 692
/**
 * 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;
693

694 695 696 697 698
    qemuDriverLock(qemu_driver);
    virDomainLoadAllConfigs(qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
                            qemu_driver->autostartDir,
M
Matthias Bolte 已提交
699 700
                            0, QEMU_EXPECTED_VIRT_TYPES,
                            qemudNotifyLoadDomain, qemu_driver);
701
    qemuDriverUnlock(qemu_driver);
702

703
    qemuAutostartDomains(qemu_driver);
704

705 706
    return 0;
}
S
Stefan Berger 已提交
707

708 709 710 711 712 713 714 715 716 717 718
/**
 * 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;
719

720 721
    if (!qemu_driver)
        return 0;
722

723 724 725 726 727 728
    /* 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;
}
729

730 731 732 733 734 735 736 737
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
    int i;
738

739 740
    if (!qemu_driver)
        return -1;
741

742 743 744
    qemuDriverLock(qemu_driver);
    pciDeviceListFree(qemu_driver->activePciHostdevs);
    virCapabilitiesFree(qemu_driver->caps);
745

746 747
    virDomainObjListDeinit(&qemu_driver->domains);
    virBitmapFree(qemu_driver->reservedVNCPorts);
748

749
    virSysinfoDefFree(qemu_driver->hostsysinfo);
750

751 752
    qemuProcessAutoDestroyShutdown(qemu_driver);

753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
    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);
    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);
773

774
    virSecurityManagerFree(qemu_driver->securityManager);
775

776
    ebtablesContextFree(qemu_driver->ebtables);
777

778 779 780 781
    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 已提交
782 783
    }

784
    /* Free domain callback list */
785
    virDomainEventStateFree(qemu_driver->domainEventState);
D
Daniel P. Berrange 已提交
786

787 788
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);
789

790
    virCgroupFree(&qemu_driver->cgroup);
791

792 793
    virLockManagerPluginUnref(qemu_driver->lockManager);

794 795 796 797
    qemuDriverUnlock(qemu_driver);
    virMutexDestroy(&qemu_driver->lock);
    virThreadPoolFree(qemu_driver->workerPool);
    VIR_FREE(qemu_driver);
798

799
    return 0;
800 801
}

802 803 804 805 806 807 808

static int qemuDomainSnapshotSetCurrentActive(virDomainObjPtr vm,
                                              char *snapshotDir);
static int qemuDomainSnapshotSetCurrentInactive(virDomainObjPtr vm,
                                                char *snapshotDir);


809
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
810
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
811
                                  unsigned int flags)
812
{
E
Eric Blake 已提交
813 814
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

815
    if (conn->uri == NULL) {
816 817 818
        if (qemu_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

819
        conn->uri = xmlParseURI(qemu_driver->privileged ?
820 821
                                "qemu:///system" :
                                "qemu:///session");
822
        if (!conn->uri) {
823
            virReportOOMError();
824 825
            return VIR_DRV_OPEN_ERROR;
        }
826 827 828 829 830 831 832 833 834 835
    } 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;

836
        if (qemu_driver == NULL) {
837 838
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("qemu state driver is not active"));
839 840 841
            return VIR_DRV_OPEN_ERROR;
        }

842
        if (conn->uri->path == NULL) {
843 844 845 846 847
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("no QEMU URI path given, try %s"),
                            qemu_driver->privileged
                            ? "qemu:///system"
                            : "qemu:///session");
848 849 850
                return VIR_DRV_OPEN_ERROR;
        }

851
        if (qemu_driver->privileged) {
852 853
            if (STRNEQ (conn->uri->path, "/system") &&
                STRNEQ (conn->uri->path, "/session")) {
854 855 856
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("unexpected QEMU URI path '%s', try qemu:///system"),
                                conn->uri->path);
857 858 859 860
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
861 862 863
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("unexpected QEMU URI path '%s', try qemu:///session"),
                                conn->uri->path);
864 865 866
                return VIR_DRV_OPEN_ERROR;
            }
        }
867 868 869 870 871 872 873
    }
    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int qemudClose(virConnectPtr conn) {
874
    struct qemud_driver *driver = conn->privateData;
875 876

    /* Get rid of callbacks registered for this conn */
877
    qemuDriverLock(driver);
878 879
    virDomainEventCallbackListRemoveConn(conn,
                                         driver->domainEventState->callbacks);
880
    qemuProcessAutoDestroyRun(driver, conn);
881
    qemuDriverUnlock(driver);
882 883 884 885 886 887

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
888 889 890 891 892
/* Which features are supported by this driver? */
static int
qemudSupportsFeature (virConnectPtr conn ATTRIBUTE_UNUSED, int feature)
{
    switch (feature) {
893
    case VIR_DRV_FEATURE_MIGRATION_V2:
894
    case VIR_DRV_FEATURE_MIGRATION_V3:
895
    case VIR_DRV_FEATURE_MIGRATION_P2P:
896
    case VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION:
897 898 899
        return 1;
    default:
        return 0;
D
Daniel Veillard 已提交
900 901 902
    }
}

903
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
904
    return "QEMU";
905 906
}

907

908 909 910 911 912 913 914 915 916 917 918 919 920
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;
}


921 922 923 924
static int kvmGetMaxVCPUs(void) {
    int maxvcpus = 1;

    int r, fd;
925

926 927
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
928
        virReportSystemError(errno, _("Unable to open %s"), KVM_DEVICE);
929
        return -1;
930 931 932 933 934 935
    }

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

936
    VIR_FORCE_CLOSE(fd);
937 938 939 940
    return maxvcpus;
}


E
Eric Blake 已提交
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
static char *
qemuGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    struct qemud_driver *driver = conn->privateData;

    virCheckFlags(0, NULL);

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

    return virSysinfoFormat(driver->hostsysinfo, "");
}

957
static int qemudGetMaxVCPUs(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
958 959 960
    if (!type)
        return 16;

961
    if (STRCASEEQ(type, "qemu"))
962 963
        return 16;

964
    if (STRCASEEQ(type, "kvm"))
965
        return kvmGetMaxVCPUs();
966

967
    if (STRCASEEQ(type, "kqemu"))
968
        return 1;
969

970 971
    qemuReportError(VIR_ERR_INVALID_ARG,
                    _("unknown type '%s'"), type);
972 973 974
    return -1;
}

975

976
static char *qemudGetCapabilities(virConnectPtr conn) {
977
    struct qemud_driver *driver = conn->privateData;
978
    virCapsPtr caps = NULL;
979
    char *xml = NULL;
980

981
    qemuDriverLock(driver);
982

983
    if ((caps = qemuCreateCapabilities(qemu_driver->caps,
984
                                       qemu_driver)) == NULL) {
985 986 987
        virCapabilitiesFree(caps);
        goto cleanup;
    }
988

989
    virCapabilitiesFree(qemu_driver->caps);
990 991 992
    qemu_driver->caps = caps;

    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
993
        virReportOOMError();
994 995

cleanup:
996
    qemuDriverUnlock(driver);
997

998
    return xml;
999 1000 1001
}


1002 1003 1004 1005 1006
static int
qemudGetProcessInfo(unsigned long long *cpuTime, int *lastCpu, int pid,
                    int tid)
{
    char *proc;
D
Daniel P. Berrange 已提交
1007
    FILE *pidinfo;
1008
    unsigned long long usertime, systime;
1009 1010
    int cpu;
    int ret;
D
Daniel P. Berrange 已提交
1011

1012
    if (tid)
1013
        ret = virAsprintf(&proc, "/proc/%d/task/%d/stat", pid, tid);
1014
    else
1015 1016
        ret = virAsprintf(&proc, "/proc/%d/stat", pid);
    if (ret < 0)
D
Daniel P. Berrange 已提交
1017 1018 1019 1020
        return -1;

    if (!(pidinfo = fopen(proc, "r"))) {
        /* VM probably shut down, so fake 0 */
1021 1022 1023 1024
        if (cpuTime)
            *cpuTime = 0;
        if (lastCpu)
            *lastCpu = 0;
1025
        VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1026 1027
        return 0;
    }
1028
    VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1029

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    /* 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) {
1040
        VIR_FORCE_FCLOSE(pidinfo);
1041
        VIR_WARN("cannot parse process status data");
1042
        errno = -EINVAL;
D
Daniel P. Berrange 已提交
1043 1044 1045 1046 1047 1048 1049 1050
        return -1;
    }

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
1051 1052 1053 1054 1055
    if (cpuTime)
        *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
    if (lastCpu)
        *lastCpu = cpu;

D
Daniel P. Berrange 已提交
1056

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

1060
    VIR_FORCE_FCLOSE(pidinfo);
D
Daniel P. Berrange 已提交
1061 1062 1063 1064 1065

    return 0;
}


1066
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1067
                                          int id) {
1068 1069 1070 1071
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1072
    qemuDriverLock(driver);
1073
    vm  = virDomainFindByID(&driver->domains, id);
1074
    qemuDriverUnlock(driver);
1075 1076

    if (!vm) {
1077 1078
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching id %d"), id);
1079
        goto cleanup;
1080 1081
    }

1082
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1083
    if (dom) dom->id = vm->def->id;
1084 1085

cleanup:
1086 1087
    if (vm)
        virDomainObjUnlock(vm);
1088 1089
    return dom;
}
1090

1091
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1092
                                            const unsigned char *uuid) {
1093 1094 1095
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1096

1097
    qemuDriverLock(driver);
1098
    vm = virDomainFindByUUID(&driver->domains, uuid);
1099 1100
    qemuDriverUnlock(driver);

1101
    if (!vm) {
1102 1103
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
1104 1105
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1106
        goto cleanup;
1107 1108
    }

1109
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1110
    if (dom) dom->id = vm->def->id;
1111 1112

cleanup:
1113 1114
    if (vm)
        virDomainObjUnlock(vm);
1115 1116
    return dom;
}
1117

1118
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1119
                                            const char *name) {
1120 1121 1122
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1123

1124
    qemuDriverLock(driver);
1125
    vm = virDomainFindByName(&driver->domains, name);
1126 1127
    qemuDriverUnlock(driver);

1128
    if (!vm) {
1129 1130
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), name);
1131
        goto cleanup;
1132 1133
    }

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

cleanup:
1138 1139
    if (vm)
        virDomainObjUnlock(vm);
1140 1141 1142
    return dom;
}

1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153

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 已提交
1154 1155 1156 1157
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
        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 已提交
1178 1179 1180 1181
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
        goto cleanup;
    }
    ret = obj->persistent;

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

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
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 已提交
1202 1203 1204 1205
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1206 1207 1208 1209 1210 1211 1212 1213 1214
        goto cleanup;
    }
    ret = obj->updated;

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

1216
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1217 1218 1219
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

1220
    qemuDriverLock(driver);
1221
    if (qemuCapsExtractVersion(driver->caps, &driver->qemuVersion) < 0)
1222
        goto cleanup;
1223

1224
    *version = driver->qemuVersion;
1225 1226 1227
    ret = 0;

cleanup:
1228
    qemuDriverUnlock(driver);
1229
    return ret;
D
Daniel P. Berrange 已提交
1230 1231
}

1232
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1233
    struct qemud_driver *driver = conn->privateData;
1234
    int n;
1235

1236
    qemuDriverLock(driver);
1237
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1238
    qemuDriverUnlock(driver);
1239

1240
    return n;
D
Daniel P. Berrange 已提交
1241
}
1242

1243
static int qemudNumDomains(virConnectPtr conn) {
1244
    struct qemud_driver *driver = conn->privateData;
1245
    int n;
1246

1247
    qemuDriverLock(driver);
1248
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1249
    qemuDriverUnlock(driver);
1250

1251
    return n;
D
Daniel P. Berrange 已提交
1252
}
1253

1254
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
1255
                                      unsigned int flags) {
1256
    struct qemud_driver *driver = conn->privateData;
1257
    virDomainDefPtr def;
1258
    virDomainObjPtr vm = NULL;
1259
    virDomainPtr dom = NULL;
1260
    virDomainEventPtr event = NULL;
D
Daniel P. Berrange 已提交
1261

1262 1263
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
                  VIR_DOMAIN_START_AUTODESTROY, NULL);
1264

1265
    qemuDriverLock(driver);
1266
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1267
                                        QEMU_EXPECTED_VIRT_TYPES,
1268
                                        VIR_DOMAIN_XML_INACTIVE)))
1269
        goto cleanup;
1270

1271
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
1272 1273
        goto cleanup;

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

1277 1278 1279
    if (qemudCanonicalizeMachine(driver, def) < 0)
        goto cleanup;

1280
    if (qemuDomainAssignPCIAddresses(def) < 0)
1281 1282
        goto cleanup;

1283
    if (!(vm = virDomainAssignDef(driver->caps,
1284
                                  &driver->domains,
1285
                                  def, false)))
1286 1287 1288
        goto cleanup;

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

1290
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
1291 1292
        goto cleanup; /* XXXX free the 'vm' we created ? */

1293 1294
    if (qemuProcessStart(conn, driver, vm, NULL,
                         (flags & VIR_DOMAIN_START_PAUSED) != 0,
1295
                         (flags & VIR_DOMAIN_START_AUTODESTROY) != 0,
1296
                         -1, NULL, VIR_VM_OP_CREATE) < 0) {
1297
        virDomainAuditStart(vm, "booted", false);
1298
        if (qemuDomainObjEndJob(driver, vm) > 0)
1299 1300
            virDomainRemoveInactive(&driver->domains,
                                    vm);
1301
        vm = NULL;
1302
        goto cleanup;
D
Daniel P. Berrange 已提交
1303
    }
1304 1305 1306 1307

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
1308
    virDomainAuditStart(vm, "booted", true);
D
Daniel P. Berrange 已提交
1309

1310
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1311
    if (dom) dom->id = vm->def->id;
1312

1313
    if (vm &&
1314
        qemuDomainObjEndJob(driver, vm) == 0)
1315
        vm = NULL;
1316

1317 1318
cleanup:
    virDomainDefFree(def);
1319 1320
    if (vm)
        virDomainObjUnlock(vm);
1321 1322
    if (event)
        qemuDomainEventQueue(driver, event);
1323
    qemuDriverUnlock(driver);
1324
    return dom;
D
Daniel P. Berrange 已提交
1325 1326 1327
}


1328
static int qemudDomainSuspend(virDomainPtr dom) {
1329 1330 1331
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1332
    virDomainEventPtr event = NULL;
1333
    qemuDomainObjPrivatePtr priv;
1334 1335
    virDomainPausedReason reason;
    int eventDetail;
1336

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

D
Daniel P. Berrange 已提交
1340
    if (!vm) {
1341 1342
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1343 1344
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1345
        goto cleanup;
D
Daniel P. Berrange 已提交
1346
    }
D
Daniel P. Berrange 已提交
1347
    if (!virDomainObjIsActive(vm)) {
1348 1349
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1350
        goto cleanup;
D
Daniel P. Berrange 已提交
1351
    }
1352

1353 1354 1355 1356 1357 1358
    if (qemuProcessAutoDestroyActive(driver, vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is marked for auto destroy"));
        goto cleanup;
    }

1359 1360
    priv = vm->privateData;

1361
    if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_OUT) {
1362 1363
        reason = VIR_DOMAIN_PAUSED_MIGRATION;
        eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED;
1364
    } else {
1365 1366 1367
        reason = VIR_DOMAIN_PAUSED_USER;
        eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_PAUSED;
    }
1368

1369 1370 1371 1372 1373 1374 1375 1376 1377
    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) {
1378
        if (qemuProcessStopCPUs(driver, vm, reason, QEMU_ASYNC_JOB_NONE) < 0) {
1379
            goto endjob;
1380
        }
1381 1382 1383
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         eventDetail);
D
Daniel P. Berrange 已提交
1384
    }
1385 1386 1387
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
        goto endjob;
    ret = 0;
1388

1389
endjob:
1390
    if (qemuDomainObjEndJob(driver, vm) == 0)
1391
        vm = NULL;
1392

1393
cleanup:
1394 1395
    if (vm)
        virDomainObjUnlock(vm);
1396

1397
    if (event)
1398
        qemuDomainEventQueue(driver, event);
1399
    qemuDriverUnlock(driver);
1400
    return ret;
D
Daniel P. Berrange 已提交
1401 1402 1403
}


1404
static int qemudDomainResume(virDomainPtr dom) {
1405 1406 1407
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1408
    virDomainEventPtr event = NULL;
1409

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

D
Daniel P. Berrange 已提交
1413
    if (!vm) {
1414 1415
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1416 1417
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1418
        goto cleanup;
D
Daniel P. Berrange 已提交
1419
    }
1420

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

D
Daniel P. Berrange 已提交
1424
    if (!virDomainObjIsActive(vm)) {
1425 1426
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1427
        goto endjob;
D
Daniel P. Berrange 已提交
1428
    }
J
Jiri Denemark 已提交
1429 1430
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
        if (qemuProcessStartCPUs(driver, vm, dom->conn,
1431 1432
                                 VIR_DOMAIN_RUNNING_UNPAUSED,
                                 QEMU_ASYNC_JOB_NONE) < 0) {
1433
            if (virGetLastError() == NULL)
1434 1435
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("resume operation failed"));
1436
            goto endjob;
1437
        }
1438 1439 1440
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
D
Daniel P. Berrange 已提交
1441
    }
1442
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
1443
        goto endjob;
1444 1445
    ret = 0;

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

1450
cleanup:
1451 1452
    if (vm)
        virDomainObjUnlock(vm);
1453
    if (event)
1454
        qemuDomainEventQueue(driver, event);
1455
    qemuDriverUnlock(driver);
1456
    return ret;
D
Daniel P. Berrange 已提交
1457 1458 1459
}


1460
static int qemuDomainShutdown(virDomainPtr dom) {
1461 1462 1463
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1464
    qemuDomainObjPrivatePtr priv;
1465

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

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

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

D
Daniel P. Berrange 已提交
1481
    if (!virDomainObjIsActive(vm)) {
1482 1483
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1484
        goto endjob;
1485 1486
    }

1487
    priv = vm->privateData;
1488
    qemuDomainObjEnterMonitor(driver, vm);
1489
    ret = qemuMonitorSystemPowerdown(priv->mon);
1490
    qemuDomainObjExitMonitor(driver, vm);
1491

1492 1493
    priv->fakeReboot = false;

1494
endjob:
1495
    if (qemuDomainObjEndJob(driver, vm) == 0)
1496
        vm = NULL;
1497

1498
cleanup:
1499 1500
    if (vm)
        virDomainObjUnlock(vm);
1501
    return ret;
1502 1503 1504
}


1505 1506 1507 1508
static int qemuDomainReboot(virDomainPtr dom, unsigned int flags) {
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1509
#if HAVE_YAJL
1510
    qemuDomainObjPrivatePtr priv;
1511
#endif
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527

    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 HAVE_YAJL
1528 1529
    priv = vm->privateData;

1530
    if (qemuCapsGet(priv->qemuCaps, QEMU_CAPS_MONITOR_JSON)) {
1531
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1532 1533 1534 1535 1536 1537 1538 1539
            goto cleanup;

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

1540
        qemuDomainObjEnterMonitor(driver, vm);
1541
        ret = qemuMonitorSystemPowerdown(priv->mon);
1542
        qemuDomainObjExitMonitor(driver, vm);
1543 1544 1545 1546

        priv->fakeReboot = true;

    endjob:
1547
        if (qemuDomainObjEndJob(driver, vm) == 0)
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
            vm = NULL;
    } else {
#endif
        qemuReportError(VIR_ERR_NO_SUPPORT, "%s",
                        _("Reboot is not supported without the JSON monitor"));
#if HAVE_YAJL
    }
#endif

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


1564 1565 1566 1567
static int
qemuDomainDestroyFlags(virDomainPtr dom,
                       unsigned int flags)
{
1568 1569 1570
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1571
    virDomainEventPtr event = NULL;
1572
    qemuDomainObjPrivatePtr priv;
1573

1574 1575
    virCheckFlags(0, -1);

1576
    qemuDriverLock(driver);
1577
    vm  = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel P. Berrange 已提交
1578
    if (!vm) {
1579 1580
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1581 1582
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1583
        goto cleanup;
D
Daniel P. Berrange 已提交
1584
    }
1585

1586 1587 1588
    priv = vm->privateData;
    priv->fakeReboot = false;

1589 1590 1591 1592 1593 1594 1595
    /* 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
     */
    qemuProcessKill(vm);

1596
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_DESTROY) < 0)
1597 1598
        goto cleanup;

D
Daniel P. Berrange 已提交
1599
    if (!virDomainObjIsActive(vm)) {
1600 1601
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1602
        goto endjob;
1603
    }
1604

J
Jiri Denemark 已提交
1605
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_DESTROYED);
1606 1607 1608
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1609
    virDomainAuditStop(vm, "destroyed");
1610

1611
    if (!vm->persistent) {
1612
        if (qemuDomainObjEndJob(driver, vm) > 0)
1613 1614
            virDomainRemoveInactive(&driver->domains,
                                    vm);
1615 1616
        vm = NULL;
    }
1617 1618
    ret = 0;

1619
endjob:
1620
    if (vm &&
1621
        qemuDomainObjEndJob(driver, vm) == 0)
1622
        vm = NULL;
1623

1624
cleanup:
1625 1626
    if (vm)
        virDomainObjUnlock(vm);
1627 1628
    if (event)
        qemuDomainEventQueue(driver, event);
1629
    qemuDriverUnlock(driver);
1630
    return ret;
D
Daniel P. Berrange 已提交
1631 1632
}

1633 1634 1635 1636 1637
static int
qemuDomainDestroy(virDomainPtr dom)
{
    return qemuDomainDestroyFlags(dom, 0);
}
D
Daniel P. Berrange 已提交
1638

1639
static char *qemudDomainGetOSType(virDomainPtr dom) {
1640 1641 1642
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1643

1644
    qemuDriverLock(driver);
1645
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1646
    qemuDriverUnlock(driver);
1647
    if (!vm) {
1648 1649
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1650 1651
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1652
        goto cleanup;
1653 1654
    }

1655
    if (!(type = strdup(vm->def->os.type)))
1656
        virReportOOMError();
1657 1658

cleanup:
1659 1660
    if (vm)
        virDomainObjUnlock(vm);
1661 1662 1663
    return type;
}

1664 1665
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
1666 1667 1668
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
1669

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

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

1682
    ret = vm->def->mem.max_balloon;
1683 1684

cleanup:
1685 1686
    if (vm)
        virDomainObjUnlock(vm);
1687
    return ret;
1688 1689
}

1690 1691
static int qemudDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
                                     unsigned int flags) {
1692
    struct qemud_driver *driver = dom->conn->privateData;
1693
    qemuDomainObjPrivatePtr priv;
1694
    virDomainObjPtr vm;
1695
    virDomainDefPtr persistentDef = NULL;
1696
    int ret = -1, r;
1697
    bool isActive;
1698

1699 1700
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
1701
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1702

1703
    qemuDriverLock(driver);
1704
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1705
    qemuDriverUnlock(driver);
1706
    if (!vm) {
1707 1708
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1709 1710
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1711
        goto cleanup;
1712 1713
    }

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

1717 1718
    isActive = virDomainObjIsActive(vm);

1719
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
1720
        if (isActive)
1721
            flags = VIR_DOMAIN_AFFECT_LIVE;
1722
        else
1723
            flags = VIR_DOMAIN_AFFECT_CONFIG;
1724
    }
1725 1726
    if (flags == VIR_DOMAIN_MEM_MAXIMUM) {
        if (isActive)
1727
            flags = VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_MEM_MAXIMUM;
1728
        else
1729
            flags = VIR_DOMAIN_AFFECT_CONFIG | VIR_DOMAIN_MEM_MAXIMUM;
1730
    }
1731

1732
    if (!isActive && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
1733 1734 1735 1736 1737
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

1738
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
1739 1740 1741 1742 1743 1744 1745 1746
        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;
    }
1747

1748 1749 1750
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */

1751
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
1752 1753 1754
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot resize the maximum memory on an "
                              "active domain"));
1755
            goto endjob;
1756
        }
1757

1758
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
1759 1760
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
1761 1762 1763 1764
            persistentDef->mem.max_balloon = newmem;
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
1765 1766 1767
            goto endjob;
        }

1768 1769 1770 1771 1772 1773 1774 1775 1776
    } 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;
        }

1777
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
1778
            priv = vm->privateData;
1779
            qemuDomainObjEnterMonitor(driver, vm);
1780
            r = qemuMonitorSetBalloon(priv->mon, newmem);
1781
            qemuDomainObjExitMonitor(driver, vm);
1782 1783
            virDomainAuditMemory(vm, vm->def->mem.cur_balloon, newmem, "update",
                                 r == 1);
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
            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;
            }
        }

1795
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
1796
            sa_assert(persistentDef);
1797 1798 1799 1800
            persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
            goto endjob;
        }
1801
    }
1802

1803
    ret = 0;
1804
endjob:
1805
    if (qemuDomainObjEndJob(driver, vm) == 0)
1806
        vm = NULL;
1807

1808
cleanup:
1809 1810
    if (vm)
        virDomainObjUnlock(vm);
1811
    return ret;
1812 1813
}

1814 1815
static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem)
{
1816
    return qemudDomainSetMemoryFlags(dom, newmem, VIR_DOMAIN_AFFECT_LIVE);
1817 1818
}

1819 1820 1821 1822 1823
static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return qemudDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
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;

1851
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
1852
        goto cleanup;
1853
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
1854 1855
    ret = qemuMonitorInjectNMI(priv->mon);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
1856
    if (qemuDomainObjEndJob(driver, vm) == 0) {
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
        vm = NULL;
        goto cleanup;
    }

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

1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
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);

    /* translate the keycode to XT_KBD for qemu driver */
    if (codeset != VIR_KEYCODE_SET_XT_KBD) {
        int i;
        int keycode;

        for (i = 0; i < nkeycodes; i++) {
            keycode = virKeycodeValueTranslate(codeset, VIR_KEYCODE_SET_XT_KBD,
                                               keycodes[i]);
            if (keycode < 0) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
             _("cannot translate keycode %u of %s codeset to xt_kbd keycode"),
                                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"));
        goto cleanup;
    }

1922
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
    ret = qemuMonitorSendKey(priv->mon, holdtime, keycodes, nkeycodes);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
    if (qemuDomainObjEndJob(driver, vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

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

1937
static int qemudDomainGetInfo(virDomainPtr dom,
1938 1939
                              virDomainInfoPtr info)
{
1940 1941 1942
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1943 1944
    int err;
    unsigned long balloon;
1945

1946
    qemuDriverLock(driver);
1947
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1948
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
1949
    if (!vm) {
1950 1951
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1952 1953
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1954
        goto cleanup;
D
Daniel P. Berrange 已提交
1955 1956
    }

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

D
Daniel P. Berrange 已提交
1959
    if (!virDomainObjIsActive(vm)) {
1960
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
1961
    } else {
1962
        if (qemudGetProcessInfo(&(info->cpuTime), NULL, vm->pid, 0) < 0) {
E
Eric Blake 已提交
1963 1964
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("cannot read cputime for domain"));
1965
            goto cleanup;
D
Daniel P. Berrange 已提交
1966 1967 1968
        }
    }

1969
    info->maxMem = vm->def->mem.max_balloon;
1970

D
Daniel P. Berrange 已提交
1971
    if (virDomainObjIsActive(vm)) {
1972
        qemuDomainObjPrivatePtr priv = vm->privateData;
1973 1974 1975

        if ((vm->def->memballoon != NULL) &&
            (vm->def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_NONE)) {
1976
            info->memory = vm->def->mem.max_balloon;
1977
        } else if (!priv->job.active) {
1978
            if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
1979
                goto cleanup;
1980 1981 1982
            if (!virDomainObjIsActive(vm))
                err = 0;
            else {
1983
                qemuDomainObjEnterMonitor(driver, vm);
1984
                err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
1985
                qemuDomainObjExitMonitor(driver, vm);
1986
            }
1987
            if (qemuDomainObjEndJob(driver, vm) == 0) {
1988
                vm = NULL;
1989 1990 1991
                goto cleanup;
            }

1992 1993
            if (err < 0)
                goto cleanup;
1994 1995
            if (err == 0)
                /* Balloon not supported, so maxmem is always the allocation */
1996
                info->memory = vm->def->mem.max_balloon;
1997 1998 1999
            else
                info->memory = balloon;
        } else {
2000
            info->memory = vm->def->mem.cur_balloon;
2001
        }
2002
    } else {
2003
        info->memory = vm->def->mem.cur_balloon;
2004 2005
    }

2006
    info->nrVirtCpu = vm->def->vcpus;
2007 2008 2009
    ret = 0;

cleanup:
2010 2011
    if (vm)
        virDomainObjUnlock(vm);
2012
    return ret;
D
Daniel P. Berrange 已提交
2013 2014
}

2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
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 已提交
2039
    *state = virDomainObjGetState(vm, reason);
2040 2041 2042 2043 2044 2045 2046 2047
    ret = 0;

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

2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
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;
2084
    } else if (priv->job.active) {
2085 2086 2087 2088
        if (!priv->monStart) {
            info->state = VIR_DOMAIN_CONTROL_JOB;
            if (virTimeMs(&info->stateTime) < 0)
                goto cleanup;
2089
            info->stateTime -= priv->job.start;
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107
        } 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 已提交
2108

2109
#define QEMUD_SAVE_MAGIC "LibvirtQemudSave"
2110 2111 2112
#define QEMUD_SAVE_VERSION 2

enum qemud_save_formats {
2113 2114 2115
    QEMUD_SAVE_FORMAT_RAW = 0,
    QEMUD_SAVE_FORMAT_GZIP = 1,
    QEMUD_SAVE_FORMAT_BZIP2 = 2,
2116 2117
    /*
     * Deprecated by xz and never used as part of a release
2118
     * QEMUD_SAVE_FORMAT_LZMA
2119 2120
     */
    QEMUD_SAVE_FORMAT_XZ = 3,
2121
    QEMUD_SAVE_FORMAT_LZOP = 4,
2122 2123 2124
    /* Note: add new members only at the end.
       These values are used in the on-disk format.
       Do not change or re-use numbers. */
2125 2126

    QEMUD_SAVE_FORMAT_LAST
2127
};
2128

2129 2130 2131 2132 2133
VIR_ENUM_DECL(qemudSaveCompression)
VIR_ENUM_IMPL(qemudSaveCompression, QEMUD_SAVE_FORMAT_LAST,
              "raw",
              "gzip",
              "bzip2",
2134 2135
              "xz",
              "lzop")
2136

2137 2138
struct qemud_save_header {
    char magic[sizeof(QEMUD_SAVE_MAGIC)-1];
2139 2140 2141 2142 2143
    uint32_t version;
    uint32_t xml_len;
    uint32_t was_running;
    uint32_t compressed;
    uint32_t unused[15];
2144 2145
};

2146 2147 2148 2149 2150 2151 2152 2153 2154
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);
}


2155
/* return -errno on failure, or 0 on success */
E
Eric Blake 已提交
2156 2157 2158 2159
static int
qemuDomainSaveHeader(int fd, const char *path, char *xml,
                     struct qemud_save_header *header)
{
2160 2161
    int ret = 0;

E
Eric Blake 已提交
2162
    if (safewrite(fd, header, sizeof(*header)) != sizeof(*header)) {
2163
        ret = -errno;
2164
        qemuReportError(VIR_ERR_OPERATION_FAILED,
2165
                        _("failed to write header to domain save file '%s'"),
E
Eric Blake 已提交
2166
                        path);
2167 2168 2169
        goto endjob;
    }

E
Eric Blake 已提交
2170
    if (safewrite(fd, xml, header->xml_len) != header->xml_len) {
2171
        ret = -errno;
2172
        qemuReportError(VIR_ERR_OPERATION_FAILED,
E
Eric Blake 已提交
2173
                         _("failed to write xml to '%s'"), path);
2174 2175 2176 2177 2178 2179
        goto endjob;
    }
endjob:
    return ret;
}

2180 2181 2182 2183 2184 2185 2186 2187 2188
/* 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));
}

2189
/* This internal function expects the driver lock to already be held on
2190 2191 2192 2193
 * 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).
2194
 */
2195 2196 2197
static int
qemuDomainSaveInternal(struct qemud_driver *driver, virDomainPtr dom,
                       virDomainObjPtr vm, const char *path,
2198
                       int compressed, bool bypass_cache, const char *xmlin)
2199
{
2200
    char *xml = NULL;
2201
    struct qemud_save_header header;
2202
    bool bypassSecurityDriver = false;
2203
    int ret = -1;
2204
    int rc;
2205
    virDomainEventPtr event = NULL;
2206
    qemuDomainObjPrivatePtr priv;
2207
    struct stat sb;
2208
    bool is_reg = false;
2209
    size_t len;
2210
    unsigned long long offset;
2211
    unsigned long long pad;
2212
    int fd = -1;
2213 2214
    uid_t uid = getuid();
    gid_t gid = getgid();
2215 2216
    int directFlag = 0;
    virFileDirectFdPtr directFd = NULL;
2217 2218 2219 2220 2221

    memset(&header, 0, sizeof(header));
    memcpy(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic));
    header.version = QEMUD_SAVE_VERSION;

2222
    header.compressed = compressed;
2223

2224
    priv = vm->privateData;
2225

2226 2227
    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             QEMU_ASYNC_JOB_SAVE) < 0)
2228 2229
        goto cleanup;

2230 2231
    memset(&priv->job.info, 0, sizeof(priv->job.info));
    priv->job.info.type = VIR_DOMAIN_JOB_UNBOUNDED;
2232

2233
    /* Pause */
J
Jiri Denemark 已提交
2234
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
2235
        header.was_running = 1;
2236 2237
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_SAVE) < 0)
2238
            goto endjob;
2239 2240 2241 2242 2243 2244

        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto endjob;
        }
2245 2246
    }

2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268
    /* 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));
    }
2269
    if (!xml) {
2270 2271
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to get domain xml"));
2272
        goto endjob;
2273
    }
2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293
    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;
2294

2295
    /* Obtain the file handle.  */
2296 2297 2298 2299 2300 2301 2302 2303
    /* 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 (stat(path, &sb) < 0) {
        /* Avoid throwing an error here, since it is possible
         * that with NFS we can't actually stat() the file.
         * The subsequent codepaths will still raise an error
         * if a truely fatal problem is hit */
2304
        is_reg = true;
2305
    } else {
2306
        is_reg = !!S_ISREG(sb.st_mode);
2307
        /* If the path is regular file which exists
2308 2309
         * already and dynamic_ownership is off, we don't
         * want to change it's ownership, just open it as-is */
2310
        if (is_reg && !driver->dynamicOwnership) {
2311 2312 2313
            uid=sb.st_uid;
            gid=sb.st_gid;
        }
2314 2315
    }

2316
    /* First try creating the file as root */
2317 2318 2319 2320 2321 2322 2323 2324
    if (bypass_cache) {
        directFlag = virFileDirectFdFlag();
        if (directFlag < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("bypass cache unsupported by this system"));
            goto endjob;
        }
    }
2325
    if (!is_reg) {
2326
        fd = open(path, O_WRONLY | O_TRUNC | directFlag);
2327 2328
        if (fd < 0) {
            virReportSystemError(errno, _("unable to open %s"), path);
2329 2330
            goto endjob;
        }
2331
    } else {
2332 2333
        int oflags = O_CREAT | O_TRUNC | O_WRONLY | directFlag;
        if ((fd = virFileOpenAs(path, oflags, S_IRUSR | S_IWUSR,
2334
                                uid, gid, 0)) < 0) {
2335
            /* If we failed as root, and the error was permission-denied
2336 2337
               (EACCES or EPERM), assume it's on a network-connected share
               where root access is restricted (eg, root-squashed NFS). If the
2338 2339 2340
               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 */
2341
            rc = fd;
2342
            if (((rc != -EACCES) && (rc != -EPERM)) ||
2343
                driver->user == getuid()) {
2344 2345
                virReportSystemError(-rc,
                                    _("Failed to create domain save file '%s'"),
2346 2347 2348
                                     path);
                goto endjob;
            }
2349

2350
            /* On Linux we can also verify the FS-type of the directory. */
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367
            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 domain save file "
                                          "'%s': couldn't determine fs type"),
                                        path);
                   goto endjob;
                   break;

                case 0:
                default:
2368
                   /* local file - log the error returned by virFileOpenAs */
2369
                   virReportSystemError(-rc,
2370
                                    _("Failed to create domain save file '%s'"),
2371 2372 2373
                                        path);
                   goto endjob;
                   break;
2374 2375 2376

            }

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

2379
            if ((fd = virFileOpenAs(path, oflags,
2380 2381 2382
                                    S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP,
                                    driver->user, driver->group,
                                    VIR_FILE_OPEN_AS_UID)) < 0) {
2383 2384 2385
                virReportSystemError(-fd,
                                   _("Error from child process creating '%s'"),
                                     path);
2386 2387
                goto endjob;
            }
2388

2389 2390 2391
            /* 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 */
2392

2393
            bypassSecurityDriver = true;
2394
        }
2395
    }
2396

2397 2398 2399
    if (bypass_cache && (directFd = virFileDirectFdNew(&fd, path)) == NULL)
        goto endjob;

2400
    /* Write header to file, followed by XML */
E
Eric Blake 已提交
2401
    if (qemuDomainSaveHeader(fd, path, xml, &header) < 0) {
2402 2403 2404 2405
        VIR_FORCE_CLOSE(fd);
        goto endjob;
    }

2406
    /* Perform the migration */
2407
    if (qemuMigrationToFile(driver, vm, fd, offset, path,
2408
                            qemuCompressProgramName(compressed),
2409 2410
                            is_reg, bypassSecurityDriver,
                            QEMU_ASYNC_JOB_SAVE) < 0)
2411
        goto endjob;
2412 2413
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("unable to close %s"), path);
2414
        goto endjob;
2415
    }
2416 2417
    if (virFileDirectFdClose(directFd) < 0)
        goto endjob;
2418

2419 2420
    ret = 0;

2421
    /* Shut it down */
J
Jiri Denemark 已提交
2422
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_SAVED);
2423
    virDomainAuditStop(vm, "saved");
2424 2425 2426
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2427
    if (!vm->persistent) {
2428
        if (qemuDomainObjEndAsyncJob(driver, vm) > 0)
2429 2430
            virDomainRemoveInactive(&driver->domains,
                                    vm);
2431 2432
        vm = NULL;
    }
2433

2434
endjob:
2435
    if (vm) {
2436
        if (ret != 0) {
2437
            if (header.was_running && virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
2438
                rc = qemuProcessStartCPUs(driver, vm, dom->conn,
2439 2440
                                          VIR_DOMAIN_RUNNING_SAVE_CANCELED,
                                          QEMU_ASYNC_JOB_SAVE);
2441
                if (rc < 0)
2442
                    VIR_WARN("Unable to resume guest CPUs after save failure");
2443
            }
2444
        }
2445
        if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
2446
            vm = NULL;
2447
    }
2448

2449
cleanup:
2450
    VIR_FORCE_CLOSE(fd);
2451
    virFileDirectFdFree(directFd);
2452
    VIR_FREE(xml);
2453
    if (ret != 0 && is_reg)
2454
        unlink(path);
2455 2456
    if (event)
        qemuDomainEventQueue(driver, event);
2457 2458
    if (vm)
        virDomainObjUnlock(vm);
2459
    return ret;
D
Daniel P. Berrange 已提交
2460 2461
}

2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
/* 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;
}

2478 2479 2480
static int
qemuDomainSaveFlags(virDomainPtr dom, const char *path, const char *dxml,
                    unsigned int flags)
2481 2482 2483
{
    struct qemud_driver *driver = dom->conn->privateData;
    int compressed;
2484 2485 2486
    int ret = -1;
    virDomainObjPtr vm = NULL;

2487
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE, -1);
2488

2489
    qemuDriverLock(driver);
2490 2491 2492 2493 2494 2495 2496 2497 2498

    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"));
2499
            goto cleanup;
2500
        }
2501 2502 2503 2504
        if (!qemudCompressProgramAvailable(compressed)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Compression program for image format "
                                    "in configuration file isn't available"));
2505
            goto cleanup;
2506
        }
2507 2508
    }

2509 2510 2511 2512 2513 2514 2515 2516 2517
    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;
    }

2518 2519 2520 2521 2522 2523
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2524
    ret = qemuDomainSaveInternal(driver, dom, vm, path, compressed,
2525 2526
                                 (flags & VIR_DOMAIN_SAVE_BYPASS_CACHE) != 0,
                                 dxml);
2527
    vm = NULL;
2528 2529 2530 2531 2532 2533 2534

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

    return ret;
2535 2536
}

2537 2538 2539 2540 2541 2542
static int
qemuDomainSave(virDomainPtr dom, const char *path)
{
    return qemuDomainSaveFlags(dom, path, NULL, 0);
}

2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563
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;

2564
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE, -1);
2565 2566 2567 2568 2569 2570 2571 2572

    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);
2573
        goto cleanup;
2574 2575
    }

2576 2577 2578 2579 2580 2581
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2582 2583
    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
2584
        goto cleanup;
2585

2586
    VIR_INFO("Saving state to %s", name);
2587 2588

    compressed = QEMUD_SAVE_FORMAT_RAW;
2589
    ret = qemuDomainSaveInternal(driver, dom, vm, name, compressed,
2590 2591
                                 (flags & VIR_DOMAIN_SAVE_BYPASS_CACHE) != 0,
                                 NULL);
2592
    vm = NULL;
2593 2594 2595 2596 2597

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
2598 2599 2600
    VIR_FREE(name);

    return ret;
2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
}

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

2611
    virCheckFlags(0, -1);
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644

    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;

2645
    virCheckFlags(0, -1);
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669

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

2671 2672 2673 2674
static int
doCoreDump(struct qemud_driver *driver,
           virDomainObjPtr vm,
           const char *path,
2675 2676
           enum qemud_save_formats compress,
           bool bypass_cache)
H
Hu Tao 已提交
2677 2678 2679
{
    int fd = -1;
    int ret = -1;
2680 2681
    virFileDirectFdPtr directFd = NULL;
    int directFlag = 0;
H
Hu Tao 已提交
2682 2683

    /* Create an empty file with appropriate ownership.  */
2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
    if (bypass_cache) {
        directFlag = virFileDirectFdFlag();
        if (directFlag < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("bypass cache unsupported by this system"));
            goto cleanup;
        }
    }
    if ((fd = open(path, O_CREAT | O_TRUNC | O_WRONLY | directFlag,
                   S_IRUSR | S_IWUSR)) < 0) {
H
Hu Tao 已提交
2694 2695 2696 2697 2698
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("failed to create '%s'"), path);
        goto cleanup;
    }

2699 2700 2701
    if (bypass_cache && (directFd = virFileDirectFdNew(&fd, path)) == NULL)
        goto cleanup;

2702
    if (qemuMigrationToFile(driver, vm, fd, 0, path,
2703 2704
                            qemuCompressProgramName(compress), true, false,
                            QEMU_ASYNC_JOB_DUMP) < 0)
2705 2706
        goto cleanup;

H
Hu Tao 已提交
2707 2708 2709 2710 2711 2712
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno,
                             _("unable to save file %s"),
                             path);
        goto cleanup;
    }
2713 2714
    if (virFileDirectFdClose(directFd) < 0)
        goto cleanup;
H
Hu Tao 已提交
2715

2716
    ret = 0;
H
Hu Tao 已提交
2717 2718

cleanup:
2719
    VIR_FORCE_CLOSE(fd);
2720
    virFileDirectFdClose(directFd);
H
Hu Tao 已提交
2721 2722 2723 2724 2725
    if (ret != 0)
        unlink(path);
    return ret;
}

2726 2727 2728 2729 2730
static enum qemud_save_formats
getCompressionType(struct qemud_driver *driver)
{
    int compress = QEMUD_SAVE_FORMAT_RAW;

2731 2732 2733 2734 2735 2736
    /*
     * 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);
2737 2738 2739
        /* Use "raw" as the format if the specified format is not valid,
         * or the compress program is not available.
         */
2740
        if (compress < 0) {
2741 2742
            VIR_WARN("%s", _("Invalid dump image format specified in "
                             "configuration file, using raw"));
2743
            return QEMUD_SAVE_FORMAT_RAW;
2744
        }
2745
        if (!qemudCompressProgramAvailable(compress)) {
2746 2747 2748
            VIR_WARN("%s", _("Compression program for dump image format "
                             "in configuration file isn't available, "
                             "using raw"));
2749
            return QEMUD_SAVE_FORMAT_RAW;
2750
        }
2751
    }
2752 2753 2754 2755 2756
    return compress;
}

static int qemudDomainCoreDump(virDomainPtr dom,
                               const char *path,
2757
                               unsigned int flags)
2758
{
2759 2760 2761
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int resume = 0, paused = 0;
H
Hu Tao 已提交
2762
    int ret = -1;
2763 2764
    virDomainEventPtr event = NULL;

2765
    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH | VIR_DUMP_BYPASS_CACHE, -1);
2766

P
Paolo Bonzini 已提交
2767 2768 2769 2770 2771 2772
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2773 2774
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
P
Paolo Bonzini 已提交
2775 2776 2777
        goto cleanup;
    }

2778 2779
    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             QEMU_ASYNC_JOB_DUMP) < 0)
2780 2781
        goto cleanup;

D
Daniel P. Berrange 已提交
2782
    if (!virDomainObjIsActive(vm)) {
2783 2784
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
2785
        goto endjob;
P
Paolo Bonzini 已提交
2786 2787
    }

P
Paolo Bonzini 已提交
2788 2789
    /* Migrate will always stop the VM, so the resume condition is
       independent of whether the stop command is issued.  */
J
Jiri Denemark 已提交
2790
    resume = virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING;
P
Paolo Bonzini 已提交
2791 2792

    /* Pause domain for non-live dump */
J
Jiri Denemark 已提交
2793 2794
    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
2795 2796
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_DUMP,
                                QEMU_ASYNC_JOB_DUMP) < 0)
2797
            goto endjob;
P
Paolo Bonzini 已提交
2798
        paused = 1;
2799 2800 2801 2802 2803 2804

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

2807 2808
    ret = doCoreDump(driver, vm, path, getCompressionType(driver),
                     (flags & VIR_DUMP_BYPASS_CACHE) != 0);
2809 2810 2811 2812
    if (ret < 0)
        goto endjob;

    paused = 1;
2813 2814

endjob:
2815
    if ((ret == 0) && (flags & VIR_DUMP_CRASH)) {
J
Jiri Denemark 已提交
2816
        qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_CRASHED);
2817
        virDomainAuditStop(vm, "crashed");
2818 2819 2820 2821 2822
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
    }

P
Paolo Bonzini 已提交
2823 2824 2825
    /* 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.  */
2826
    else if (resume && paused && virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
2827
        if (qemuProcessStartCPUs(driver, vm, dom->conn,
2828 2829
                                 VIR_DOMAIN_RUNNING_UNPAUSED,
                                 QEMU_ASYNC_JOB_DUMP) < 0) {
2830
            if (virGetLastError() == NULL)
2831 2832
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("resuming after dump failed"));
P
Paolo Bonzini 已提交
2833 2834
        }
    }
2835

2836
    if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
2837
        vm = NULL;
2838
    else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
2839 2840 2841 2842
        virDomainRemoveInactive(&driver->domains,
                                vm);
        vm = NULL;
    }
2843 2844

cleanup:
P
Paolo Bonzini 已提交
2845 2846
    if (vm)
        virDomainObjUnlock(vm);
2847 2848
    if (event)
        qemuDomainEventQueue(driver, event);
2849
    qemuDriverUnlock(driver);
P
Paolo Bonzini 已提交
2850 2851 2852
    return ret;
}

2853 2854 2855 2856
static char *
qemuDomainScreenshot(virDomainPtr dom,
                     virStreamPtr st,
                     unsigned int screen,
E
Eric Blake 已提交
2857
                     unsigned int flags)
2858 2859 2860 2861 2862 2863 2864
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    char *tmp = NULL;
    int tmp_fd = -1;
    char *ret = NULL;
E
Eric Blake 已提交
2865
    bool unlink_tmp = false;
2866

E
Eric Blake 已提交
2867 2868
    virCheckFlags(0, NULL);

2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882
    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;

2883
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909
        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 已提交
2910
    unlink_tmp = true;
2911

2912 2913
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm, tmp);

2914
    qemuDomainObjEnterMonitor(driver, vm);
2915
    if (qemuMonitorScreendump(priv->mon, tmp) < 0) {
2916
        qemuDomainObjExitMonitor(driver, vm);
2917 2918
        goto endjob;
    }
2919
    qemuDomainObjExitMonitor(driver, vm);
2920 2921 2922 2923 2924 2925

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

E
Eric Blake 已提交
2926
    if (virFDStreamOpenFile(st, tmp, 0, 0, O_RDONLY) < 0) {
2927 2928 2929 2930 2931 2932 2933 2934 2935
        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 已提交
2936 2937
    if (unlink_tmp)
        unlink(tmp);
E
Eric Blake 已提交
2938
    VIR_FREE(tmp);
2939

2940
    if (qemuDomainObjEndJob(driver, vm) == 0)
2941 2942 2943 2944 2945 2946 2947 2948
        vm = NULL;

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

H
Hu Tao 已提交
2949 2950 2951
static void processWatchdogEvent(void *data, void *opaque)
{
    int ret;
2952
    struct qemuDomainWatchdogEvent *wdEvent = data;
H
Hu Tao 已提交
2953 2954
    struct qemud_driver *driver = opaque;

W
Wen Congyang 已提交
2955 2956 2957
    qemuDriverLock(driver);
    virDomainObjLock(wdEvent->vm);

H
Hu Tao 已提交
2958 2959 2960 2961 2962
    switch (wdEvent->action) {
    case VIR_DOMAIN_WATCHDOG_ACTION_DUMP:
        {
            char *dumpfile;

E
Eric Blake 已提交
2963
            if (virAsprintf(&dumpfile, "%s/%s-%u",
H
Hu Tao 已提交
2964 2965
                            driver->autoDumpPath,
                            wdEvent->vm->def->name,
E
Eric Blake 已提交
2966 2967
                            (unsigned int)time(NULL)) < 0) {
                virReportOOMError();
W
Wen Congyang 已提交
2968
                goto unlock;
E
Eric Blake 已提交
2969
            }
H
Hu Tao 已提交
2970

2971 2972
            if (qemuDomainObjBeginAsyncJobWithDriver(driver, wdEvent->vm,
                                                     QEMU_ASYNC_JOB_DUMP) < 0) {
W
Wen Congyang 已提交
2973 2974 2975
                VIR_FREE(dumpfile);
                goto unlock;
            }
H
Hu Tao 已提交
2976 2977 2978 2979

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

2984
            ret = doCoreDump(driver, wdEvent->vm, dumpfile,
2985 2986
                             getCompressionType(driver),
                             driver->autoDumpBypassCache);
H
Hu Tao 已提交
2987 2988 2989 2990
            if (ret < 0)
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("Dump failed"));

J
Jiri Denemark 已提交
2991
            ret = qemuProcessStartCPUs(driver, wdEvent->vm, NULL,
2992 2993
                                       VIR_DOMAIN_RUNNING_UNPAUSED,
                                       QEMU_ASYNC_JOB_DUMP);
H
Hu Tao 已提交
2994 2995 2996 2997 2998 2999 3000 3001

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

            VIR_FREE(dumpfile);
        }
        break;
W
Wen Congyang 已提交
3002 3003
    default:
        goto unlock;
H
Hu Tao 已提交
3004 3005
    }

W
Wen Congyang 已提交
3006 3007 3008 3009
endjob:
    /* Safe to ignore value since ref count was incremented in
     * qemuProcessHandleWatchdog().
     */
3010
    ignore_value(qemuDomainObjEndAsyncJob(driver, wdEvent->vm));
W
Wen Congyang 已提交
3011 3012 3013 3014 3015

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

3019 3020 3021
static int qemudDomainHotplugVcpus(struct qemud_driver *driver,
                                   virDomainObjPtr vm,
                                   unsigned int nvcpus)
3022 3023
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
3024
    int i, rc = 1;
3025
    int ret = -1;
3026
    int oldvcpus = vm->def->vcpus;
E
Eric Blake 已提交
3027
    int vcpus = oldvcpus;
3028

3029
    qemuDomainObjEnterMonitor(driver, vm);
3030

3031 3032 3033
    /* 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 已提交
3034 3035
    if (nvcpus > vcpus) {
        for (i = vcpus ; i < nvcpus ; i++) {
3036 3037 3038 3039 3040 3041 3042
            /* Online new CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 1);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
3043
            vcpus++;
3044 3045
        }
    } else {
E
Eric Blake 已提交
3046
        for (i = vcpus - 1 ; i >= nvcpus ; i--) {
3047 3048 3049 3050 3051 3052 3053
            /* Offline old CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 0);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
3054
            vcpus--;
3055 3056 3057 3058 3059 3060
        }
    }

    ret = 0;

cleanup:
3061
    qemuDomainObjExitMonitor(driver, vm);
E
Eric Blake 已提交
3062
    vm->def->vcpus = vcpus;
3063
    virDomainAuditVcpu(vm, oldvcpus, nvcpus, "update", rc == 1);
3064 3065 3066 3067 3068 3069 3070 3071 3072
    return ret;

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


3073
static int
3074 3075
qemuDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                        unsigned int flags)
3076
{
3077 3078
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3079
    virDomainDefPtr persistentDef;
3080 3081
    const char * type;
    int max;
3082
    int ret = -1;
3083 3084
    bool isActive;
    bool maximum;
3085

3086 3087
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
3088 3089 3090 3091 3092
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

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

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

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

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

3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129
    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)) {
3130 3131
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("domain is not running"));
3132
        goto endjob;
3133 3134
    }

3135
    if (!vm->persistent && (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
3136 3137 3138 3139 3140
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot change persistent config of a transient domain"));
        goto endjob;
    }

3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153
    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;
    }

3154
    if (!maximum && vm->def->maxvcpus < max) {
3155 3156 3157
        max = vm->def->maxvcpus;
    }

3158 3159 3160 3161 3162 3163 3164
    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;
    }

3165 3166 3167
    if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
        goto endjob;

3168
    switch (flags) {
3169
    case VIR_DOMAIN_AFFECT_CONFIG:
3170 3171 3172 3173 3174 3175 3176
        if (maximum) {
            persistentDef->maxvcpus = nvcpus;
            if (nvcpus < persistentDef->vcpus)
                persistentDef->vcpus = nvcpus;
        } else {
            persistentDef->vcpus = nvcpus;
        }
3177 3178 3179
        ret = 0;
        break;

3180
    case VIR_DOMAIN_AFFECT_LIVE:
3181
        ret = qemudDomainHotplugVcpus(driver, vm, nvcpus);
3182 3183
        break;

3184
    case VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG:
3185
        ret = qemudDomainHotplugVcpus(driver, vm, nvcpus);
3186 3187 3188
        if (ret == 0) {
            persistentDef->vcpus = nvcpus;
        }
3189 3190
        break;
    }
3191

3192
    /* Save the persistent config to disk */
3193
    if (flags & VIR_DOMAIN_AFFECT_CONFIG)
3194 3195
        ret = virDomainSaveConfig(driver->configDir, persistentDef);

3196
endjob:
3197
    if (qemuDomainObjEndJob(driver, vm) == 0)
3198
        vm = NULL;
3199

3200
cleanup:
3201 3202
    if (vm)
        virDomainObjUnlock(vm);
3203
    return ret;
3204 3205
}

3206
static int
3207
qemuDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
3208
{
3209
    return qemuDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
3210 3211
}

3212 3213

static int
3214 3215 3216 3217 3218 3219
qemudDomainPinVcpuFlags(virDomainPtr dom,
                        unsigned int vcpu,
                        unsigned char *cpumap,
                        int maplen,
                        unsigned int flags) {

3220 3221
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3222
    virDomainDefPtr persistentDef = NULL;
3223
    int maxcpu, hostcpus;
3224
    virNodeInfo nodeinfo;
3225
    int ret = -1;
3226
    bool isActive;
3227
    qemuDomainObjPrivatePtr priv;
3228
    bool canResetting = true;
E
Eric Blake 已提交
3229
    int pcpu;
3230

3231 3232 3233
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

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

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

3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257
    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"));
3258
        goto cleanup;
3259 3260
    }

3261 3262 3263
    priv = vm->privateData;

    if (vcpu > (priv->nvcpupids-1)) {
3264 3265 3266
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("vcpu number out of range %d > %d"),
                        vcpu, priv->nvcpupids);
3267
        goto cleanup;
3268 3269
    }

3270 3271 3272 3273 3274 3275 3276 3277 3278
    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;
    }
3279

3280 3281 3282 3283 3284 3285 3286 3287 3288
    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 已提交
3289
    for (pcpu = 0; pcpu < hostcpus; pcpu++) {
3290 3291 3292 3293 3294
        if ((cpumap[pcpu/8] & (1 << (pcpu % 8))) == 0) {
            canResetting = false;
            break;
        }
    }
3295

3296
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307

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

3308
        if (canResetting) {
E
Eric Blake 已提交
3309
            if (virDomainVcpuPinDel(vm->def, vcpu) < 0) {
3310 3311 3312 3313 3314 3315
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to delete vcpupin xml of "
                                  "a running domain"));
                goto cleanup;
            }
        } else {
E
Eric Blake 已提交
3316
            if (virDomainVcpuPinAdd(vm->def, cpumap, maplen, vcpu) < 0) {
3317 3318 3319 3320 3321
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to update or add vcpupin xml of "
                                  "a running domain"));
                goto cleanup;
            }
3322 3323
        }

3324 3325
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
            goto cleanup;
3326
    }
3327

3328 3329
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {

3330
        if (canResetting) {
E
Eric Blake 已提交
3331
            if (virDomainVcpuPinDel(persistentDef, vcpu) < 0) {
3332 3333 3334 3335 3336 3337
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to delete vcpupin xml of "
                                  "a persistent domain"));
                goto cleanup;
            }
        } else {
E
Eric Blake 已提交
3338
            if (virDomainVcpuPinAdd(persistentDef, cpumap, maplen, vcpu) < 0) {
3339 3340 3341 3342 3343
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to update or add vcpupin xml of "
                                  "a persistent domain"));
                goto cleanup;
            }
3344
        }
3345

3346
        ret = virDomainSaveConfig(driver->configDir, persistentDef);
3347 3348 3349
        goto cleanup;
    }

3350
    ret = 0;
3351

3352
cleanup:
3353 3354
    if (vm)
        virDomainObjUnlock(vm);
3355
    return ret;
3356 3357
}

3358 3359 3360 3361 3362 3363 3364 3365 3366
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
    return qemudDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

3367
static int
E
Eric Blake 已提交
3368
qemudDomainGetVcpuPinInfo(virDomainPtr dom,
3369 3370 3371 3372 3373 3374
                          int ncpumaps,
                          unsigned char *cpumaps,
                          int maplen,
                          unsigned int flags) {

    struct qemud_driver *driver = dom->conn->privateData;
E
Eric Blake 已提交
3375
    virDomainObjPtr vm = NULL;
3376 3377 3378 3379 3380 3381
    virNodeInfo nodeinfo;
    virDomainDefPtr targetDef = NULL;
    int ret = -1;
    bool isActive;
    int maxcpu, hostcpus, vcpu, pcpu;
    int n;
E
Eric Blake 已提交
3382
    virDomainVcpuPinDefPtr *vcpupin_list;
3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477
    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;
    }

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

3478 3479 3480 3481 3482 3483
static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
3484 3485
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3486
    virNodeInfo nodeinfo;
3487
    int i, v, maxcpu, hostcpus;
3488
    int ret = -1;
3489
    qemuDomainObjPrivatePtr priv;
3490

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

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

D
Daniel P. Berrange 已提交
3503
    if (!virDomainObjIsActive(vm)) {
3504 3505 3506
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s",
                        _("cannot list vcpu pinning for an inactive domain"));
3507
        goto cleanup;
3508 3509
    }

3510 3511
    priv = vm->privateData;

3512
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
3513
        goto cleanup;
3514

3515
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
3516
    maxcpu = maplen * 8;
3517 3518
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
3519 3520

    /* Clamp to actual number of vcpus */
3521 3522
    if (maxinfo > priv->nvcpupids)
        maxinfo = priv->nvcpupids;
3523

3524 3525 3526 3527 3528 3529
    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;
3530

3531
                if (priv->vcpupids != NULL &&
3532 3533 3534
                    qemudGetProcessInfo(&(info[i].cpuTime),
                                        &(info[i].cpu),
                                        vm->pid,
3535
                                        priv->vcpupids[i]) < 0) {
3536
                    virReportSystemError(errno, "%s",
3537 3538 3539
                                         _("cannot get vCPU placement & pCPU time"));
                    goto cleanup;
                }
3540
            }
3541 3542
        }

3543 3544
        if (cpumaps != NULL) {
            memset(cpumaps, 0, maplen * maxinfo);
3545
            if (priv->vcpupids != NULL) {
3546 3547 3548
                for (v = 0 ; v < maxinfo ; v++) {
                    unsigned char *cpumap = VIR_GET_CPUMAP(cpumaps, maplen, v);

3549
                    if (virProcessInfoGetAffinity(priv->vcpupids[v],
3550
                                                  cpumap, maplen, maxcpu) < 0)
3551
                        goto cleanup;
3552
                }
3553
            } else {
3554 3555
                qemuReportError(VIR_ERR_NO_SUPPORT,
                                "%s", _("cpu affinity is not available"));
3556
                goto cleanup;
3557 3558 3559
            }
        }
    }
3560
    ret = maxinfo;
3561

3562
cleanup:
3563 3564
    if (vm)
        virDomainObjUnlock(vm);
3565
    return ret;
3566 3567 3568
}


3569 3570 3571
static int
qemudDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
3572 3573
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3574
    virDomainDefPtr def;
3575
    int ret = -1;
3576
    bool active;
3577

3578 3579
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
3580 3581
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

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

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

3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607
    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;
    }

3608
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3609
        if (!active) {
3610 3611 3612 3613 3614 3615
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("domain not active"));
            goto cleanup;
        }
        def = vm->def;
    } else {
3616 3617 3618 3619 3620
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("domain is transient"));
            goto cleanup;
        }
3621
        def = vm->newDef ? vm->newDef : vm->def;
3622 3623
    }

3624
    ret = (flags & VIR_DOMAIN_VCPU_MAXIMUM) ? def->maxvcpus : def->vcpus;
3625

3626
cleanup:
3627 3628
    if (vm)
        virDomainObjUnlock(vm);
3629 3630 3631
    return ret;
}

3632 3633 3634
static int
qemudDomainGetMaxVcpus(virDomainPtr dom)
{
3635
    return qemudDomainGetVcpusFlags(dom, (VIR_DOMAIN_AFFECT_LIVE |
3636 3637 3638
                                          VIR_DOMAIN_VCPU_MAXIMUM));
}

3639 3640 3641 3642 3643 3644 3645 3646 3647
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);

3648 3649
    memset(seclabel, 0, sizeof(*seclabel));

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

3658
    if (!virDomainVirtTypeToString(vm->def->virtType)) {
3659 3660 3661
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unknown virt type in domain definition '%d'"),
                        vm->def->virtType);
3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678
        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 已提交
3679
    if (virDomainObjIsActive(vm)) {
3680 3681
        if (virSecurityManagerGetProcessLabel(driver->securityManager,
                                              vm, seclabel) < 0) {
3682 3683 3684
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("Failed to get security label"));
            goto cleanup;
3685 3686 3687 3688 3689 3690 3691 3692
        }
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
3693
    qemuDriverUnlock(driver);
3694 3695 3696
    return ret;
}

3697 3698
static int qemudNodeGetSecurityModel(virConnectPtr conn,
                                     virSecurityModelPtr secmodel)
3699 3700 3701
{
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
    char *p;
3702
    int ret = 0;
3703

3704
    qemuDriverLock(driver);
3705 3706 3707 3708 3709
    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)
3710
        goto cleanup;
3711

3712 3713
    p = driver->caps->host.secModel.model;
    if (strlen(p) >= VIR_SECURITY_MODEL_BUFLEN-1) {
3714 3715 3716
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security model string exceeds max %d bytes"),
                        VIR_SECURITY_MODEL_BUFLEN-1);
3717 3718
        ret = -1;
        goto cleanup;
3719 3720 3721 3722 3723
    }
    strcpy(secmodel->model, p);

    p = driver->caps->host.secModel.doi;
    if (strlen(p) >= VIR_SECURITY_DOI_BUFLEN-1) {
3724 3725 3726
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security DOI string exceeds max %d bytes"),
                        VIR_SECURITY_DOI_BUFLEN-1);
3727 3728
        ret = -1;
        goto cleanup;
3729 3730
    }
    strcpy(secmodel->doi, p);
3731 3732 3733 3734

cleanup:
    qemuDriverUnlock(driver);
    return ret;
3735 3736
}

3737 3738 3739
/* Return -1 on failure, -2 if edit was specified but xmlin does not
 * represent any changes, and opened fd on all other success.  */
static int ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4)
3740 3741 3742
qemuDomainSaveImageOpen(struct qemud_driver *driver,
                        const char *path,
                        virDomainDefPtr *ret_def,
3743
                        struct qemud_save_header *ret_header,
3744
                        bool bypass_cache, virFileDirectFdPtr *directFd,
3745
                        const char *xmlin, bool edit)
J
Jiri Denemark 已提交
3746 3747
{
    int fd;
3748
    struct qemud_save_header header;
J
Jiri Denemark 已提交
3749 3750
    char *xml = NULL;
    virDomainDefPtr def = NULL;
3751
    int oflags = edit ? O_RDWR : O_RDONLY;
3752

3753
    if (bypass_cache) {
3754
        int directFlag = virFileDirectFdFlag();
3755 3756 3757 3758 3759
        if (directFlag < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("bypass cache unsupported by this system"));
            goto error;
        }
3760
        oflags |= directFlag;
3761
    }
3762
    if ((fd = virFileOpenAs(path, oflags, 0,
3763
                            getuid(), getgid(), 0)) < 0) {
3764 3765
        if ((fd != -EACCES && fd != -EPERM) ||
            driver->user == getuid()) {
3766 3767
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("cannot read domain image"));
J
Jiri Denemark 已提交
3768
            goto error;
3769 3770 3771
        }

        /* Opening as root failed, but qemu runs as a different user
3772
         * that might have better luck. */
3773
        if ((fd = virFileOpenAs(path, oflags, 0,
3774 3775 3776 3777
                                driver->user, driver->group,
                                VIR_FILE_OPEN_AS_UID)) < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("cannot read domain image"));
J
Jiri Denemark 已提交
3778
            goto error;
3779
        }
3780
    }
3781 3782
    if (bypass_cache && (*directFd = virFileDirectFdNew(&fd, path)) == NULL)
        goto error;
3783 3784

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
3785 3786
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read qemu header"));
J
Jiri Denemark 已提交
3787
        goto error;
3788 3789 3790
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
3791 3792
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("image magic is incorrect"));
J
Jiri Denemark 已提交
3793
        goto error;
3794 3795 3796
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3797 3798 3799 3800 3801
        /* convert endianess and try again */
        bswap_header(&header);
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3802 3803 3804
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("image version is not supported (%d > %d)"),
                        header.version, QEMUD_SAVE_VERSION);
J
Jiri Denemark 已提交
3805
        goto error;
3806 3807
    }

3808 3809 3810
    if (header.xml_len <= 0) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("invalid XML length: %d"), header.xml_len);
J
Jiri Denemark 已提交
3811
        goto error;
3812 3813
    }

3814 3815
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
        virReportOOMError();
J
Jiri Denemark 已提交
3816
        goto error;
3817 3818 3819
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
3820 3821
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read XML"));
J
Jiri Denemark 已提交
3822
        goto error;
3823 3824
    }

3825 3826 3827 3828 3829 3830 3831 3832 3833
    if (edit && STREQ(xml, xmlin)) {
        VIR_FREE(xml);
        if (VIR_CLOSE(fd) < 0) {
            virReportSystemError(errno, _("cannot close file: %s"), path);
            goto error;
        }
        return -2;
    }

3834
    /* Create a domain from this XML */
3835
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
3836
                                        QEMU_EXPECTED_VIRT_TYPES,
3837
                                        VIR_DOMAIN_XML_INACTIVE)))
J
Jiri Denemark 已提交
3838
        goto error;
3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852
    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;
    }
3853

J
Jiri Denemark 已提交
3854
    VIR_FREE(xml);
3855

J
Jiri Denemark 已提交
3856 3857
    *ret_def = def;
    *ret_header = header;
3858

J
Jiri Denemark 已提交
3859
    return fd;
3860

J
Jiri Denemark 已提交
3861 3862 3863
error:
    virDomainDefFree(def);
    VIR_FREE(xml);
3864
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
3865 3866 3867 3868

    return -1;
}

3869 3870 3871 3872 3873 3874 3875
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,
                           const char *path)
J
Jiri Denemark 已提交
3876 3877 3878 3879
{
    int ret = -1;
    virDomainEventPtr event;
    int intermediatefd = -1;
3880
    virCommandPtr cmd = NULL;
J
Jiri Denemark 已提交
3881 3882 3883

    if (header->version == 2) {
        const char *prog = qemudSaveCompressionTypeToString(header->compressed);
3884
        if (prog == NULL) {
3885 3886
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("Invalid compressed save format %d"),
J
Jiri Denemark 已提交
3887 3888
                            header->compressed);
            goto out;
3889
        }
3890

J
Jiri Denemark 已提交
3891
        if (header->compressed != QEMUD_SAVE_FORMAT_RAW) {
3892
            cmd = virCommandNewArgList(prog, "-dc", NULL);
3893 3894
            intermediatefd = *fd;
            *fd = -1;
3895 3896 3897 3898 3899

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

            if (virCommandRunAsync(cmd, NULL) < 0) {
3900 3901
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Failed to start decompression binary %s"),
3902
                                prog);
3903
                *fd = intermediatefd;
J
Jiri Denemark 已提交
3904
                goto out;
3905 3906 3907
            }
        }
    }
J
Jiri Denemark 已提交
3908

3909
    /* Set the migration source and start it up. */
3910 3911
    ret = qemuProcessStart(conn, driver, vm, "stdio", true,
                           false, *fd, path, VIR_VM_OP_RESTORE);
J
Jiri Denemark 已提交
3912

3913
    if (intermediatefd != -1) {
3914
        if (ret < 0) {
3915 3916 3917
            /* if there was an error setting up qemu, the intermediate
             * process will wait forever to write to stdout, so we
             * must manually kill it.
3918 3919
             */
            VIR_FORCE_CLOSE(intermediatefd);
3920
            VIR_FORCE_CLOSE(*fd);
3921 3922
        }

3923 3924
        if (virCommandWait(cmd, NULL) < 0)
            ret = -1;
3925
    }
3926
    VIR_FORCE_CLOSE(intermediatefd);
J
Jiri Denemark 已提交
3927

3928 3929 3930
    if (VIR_CLOSE(*fd) < 0) {
        virReportSystemError(errno, _("cannot close file: %s"), path);
        ret = -1;
3931
    }
J
Jiri Denemark 已提交
3932

3933
    if (ret < 0) {
3934
        virDomainAuditStart(vm, "restored", false);
J
Jiri Denemark 已提交
3935
        goto out;
3936
    }
3937

3938 3939 3940
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
3941
    virDomainAuditStart(vm, "restored", true);
J
Jiri Denemark 已提交
3942 3943 3944
    if (event)
        qemuDomainEventQueue(driver, event);

3945

3946
    /* If it was running before, resume it now. */
J
Jiri Denemark 已提交
3947
    if (header->was_running) {
J
Jiri Denemark 已提交
3948
        if (qemuProcessStartCPUs(driver, vm, conn,
3949 3950
                                 VIR_DOMAIN_RUNNING_RESTORED,
                                 QEMU_ASYNC_JOB_NONE) < 0) {
3951
            if (virGetLastError() == NULL)
3952 3953
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("failed to resume domain"));
J
Jiri Denemark 已提交
3954
            goto out;
3955
        }
3956 3957
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
J
Jiri Denemark 已提交
3958
            goto out;
3959
        }
3960
    }
J
Jiri Denemark 已提交
3961

3962
    ret = 0;
3963

J
Jiri Denemark 已提交
3964
out:
3965
    virCommandFree(cmd);
3966 3967
    if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
                                                 vm, path) < 0)
3968 3969
        VIR_WARN("failed to restore save state label on %s", path);

J
Jiri Denemark 已提交
3970 3971 3972
    return ret;
}

3973
static int
3974 3975 3976 3977
qemuDomainRestoreFlags(virConnectPtr conn,
                       const char *path,
                       const char *dxml,
                       unsigned int flags)
3978
{
J
Jiri Denemark 已提交
3979 3980 3981 3982 3983 3984
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    int fd = -1;
    int ret = -1;
    struct qemud_save_header header;
3985
    virFileDirectFdPtr directFd = NULL;
J
Jiri Denemark 已提交
3986

3987
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE, -1);
3988

J
Jiri Denemark 已提交
3989 3990
    qemuDriverLock(driver);

3991 3992
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header,
                                 (flags & VIR_DOMAIN_SAVE_BYPASS_CACHE) != 0,
3993
                                 &directFd, dxml, false);
J
Jiri Denemark 已提交
3994 3995 3996 3997 3998 3999 4000 4001 4002
    if (fd < 0)
        goto cleanup;

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

    if (!(vm = virDomainAssignDef(driver->caps,
                                  &driver->domains,
                                  def, true))) {
4003
        /* virDomainAssignDef already set the error */
J
Jiri Denemark 已提交
4004 4005 4006 4007
        goto cleanup;
    }
    def = NULL;

4008
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
J
Jiri Denemark 已提交
4009 4010
        goto cleanup;

4011
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path);
4012 4013
    if (virFileDirectFdClose(directFd) < 0)
        VIR_WARN("Failed to close %s", path);
J
Jiri Denemark 已提交
4014

4015
    if (qemuDomainObjEndJob(driver, vm) == 0)
4016
        vm = NULL;
J
Jiri Denemark 已提交
4017 4018 4019 4020
    else if (ret < 0 && !vm->persistent) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }
4021

4022 4023
cleanup:
    virDomainDefFree(def);
4024
    VIR_FORCE_CLOSE(fd);
4025
    virFileDirectFdFree(directFd);
4026 4027 4028
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
4029
    return ret;
D
Daniel P. Berrange 已提交
4030 4031
}

4032 4033 4034 4035 4036 4037 4038
static int
qemuDomainRestore(virConnectPtr conn,
                  const char *path)
{
    return qemuDomainRestoreFlags(conn, path, NULL, 0);
}

4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130
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,
                                 NULL, false);

    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;

    virCheckFlags(0, -1);

    qemuDriverLock(driver);

    fd = qemuDomainSaveImageOpen(driver, path, &def, &header, false, NULL,
                                 dxml, true);

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

    if (lseek(fd, sizeof(header), SEEK_SET) != sizeof(header)) {
        virReportSystemError(errno, _("cannot seek in '%s'"), path);
        goto cleanup;
    }
    if (safewrite(fd, xml, len) != len ||
        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;
}

4131 4132 4133 4134
static int
qemuDomainObjRestore(virConnectPtr conn,
                     struct qemud_driver *driver,
                     virDomainObjPtr vm,
4135 4136
                     const char *path,
                     bool bypass_cache)
J
Jiri Denemark 已提交
4137 4138 4139 4140 4141
{
    virDomainDefPtr def = NULL;
    int fd = -1;
    int ret = -1;
    struct qemud_save_header header;
4142
    virFileDirectFdPtr directFd = NULL;
J
Jiri Denemark 已提交
4143

4144
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header,
4145
                                 bypass_cache, &directFd, NULL, false);
J
Jiri Denemark 已提交
4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165
    if (fd < 0)
        goto cleanup;

    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;

4166
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path);
4167 4168
    if (virFileDirectFdClose(directFd) < 0)
        VIR_WARN("Failed to close %s", path);
J
Jiri Denemark 已提交
4169 4170 4171

cleanup:
    virDomainDefFree(def);
4172
    VIR_FORCE_CLOSE(fd);
4173
    virFileDirectFdFree(directFd);
J
Jiri Denemark 已提交
4174 4175 4176
    return ret;
}

D
Daniel P. Berrange 已提交
4177

4178
static char *qemuDomainGetXMLDesc(virDomainPtr dom,
4179 4180
                                  unsigned int flags)
{
4181 4182 4183
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;
4184 4185
    unsigned long balloon;
    int err;
4186

4187
    /* Flags checked by virDomainDefFormat */
4188

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

D
Daniel P. Berrange 已提交
4192
    if (!vm) {
4193 4194
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4195 4196
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4197
        goto cleanup;
D
Daniel P. Berrange 已提交
4198 4199
    }

4200 4201 4202 4203
    /* 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))) {
4204
        qemuDomainObjPrivatePtr priv = vm->privateData;
4205 4206
        /* Don't delay if someone's using the monitor, just use
         * existing most recent data instead */
4207
        if (!priv->job.active) {
4208
            if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_QUERY) < 0)
4209 4210
                goto cleanup;

4211
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
4212
            err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
4213
            qemuDomainObjExitMonitorWithDriver(driver, vm);
4214
            if (qemuDomainObjEndJob(driver, vm) == 0) {
4215 4216 4217
                vm = NULL;
                goto cleanup;
            }
4218 4219 4220
            if (err < 0)
                goto cleanup;
            if (err > 0)
4221
                vm->def->mem.cur_balloon = balloon;
4222 4223
            /* err == 0 indicates no balloon support, so ignore it */
        }
4224
    }
4225

4226
    ret = qemuDomainFormatXML(driver, vm, flags);
4227 4228

cleanup:
4229 4230
    if (vm)
        virDomainObjUnlock(vm);
4231
    qemuDriverUnlock(driver);
4232
    return ret;
D
Daniel P. Berrange 已提交
4233 4234 4235
}


4236 4237 4238
static char *qemuDomainXMLFromNative(virConnectPtr conn,
                                     const char *format,
                                     const char *config,
E
Eric Blake 已提交
4239 4240
                                     unsigned int flags)
{
4241
    struct qemud_driver *driver = conn->privateData;
4242 4243 4244
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
4245 4246
    virCheckFlags(0, NULL);

4247
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
4248 4249
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
4250 4251 4252
        goto cleanup;
    }

4253
    qemuDriverLock(driver);
4254 4255
    def = qemuParseCommandLineString(driver->caps, config,
                                     NULL, NULL, NULL);
4256
    qemuDriverUnlock(driver);
4257 4258 4259
    if (!def)
        goto cleanup;

4260 4261 4262 4263 4264 4265
    if (!def->name &&
        !(def->name = strdup("unnamed"))) {
        virReportOOMError();
        goto cleanup;
    }

4266
    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
4267 4268 4269 4270 4271 4272

cleanup:
    virDomainDefFree(def);
    return xml;
}

4273 4274 4275
static char *qemuDomainXMLToNative(virConnectPtr conn,
                                   const char *format,
                                   const char *xmlData,
E
Eric Blake 已提交
4276 4277
                                   unsigned int flags)
{
4278 4279
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
4280
    virDomainChrSourceDef monConfig;
4281
    virBitmapPtr qemuCaps = NULL;
E
Eric Blake 已提交
4282
    virCommandPtr cmd = NULL;
4283 4284 4285
    char *ret = NULL;
    int i;

E
Eric Blake 已提交
4286 4287
    virCheckFlags(0, NULL);

4288 4289
    qemuDriverLock(driver);

4290
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
4291 4292
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
4293 4294 4295
        goto cleanup;
    }

M
Matthias Bolte 已提交
4296 4297
    def = virDomainDefParseString(driver->caps, xmlData,
                                  QEMU_EXPECTED_VIRT_TYPES, 0);
4298 4299 4300
    if (!def)
        goto cleanup;

4301 4302
    /* Since we're just exporting args, we can't do bridge/network/direct
     * setups, since libvirt will normally create TAP/macvtap devices
4303 4304 4305 4306 4307
     * 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];
4308
        int bootIndex = net->bootIndex;
4309 4310 4311 4312
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            int actualType = virDomainNetGetActualType(net);
            const char *brname;

4313
            VIR_FREE(net->data.network.name);
4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346
            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);
4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365

            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;
        }
4366
        net->bootIndex = bootIndex;
4367 4368 4369 4370
    }
    for (i = 0 ; i < def->ngraphics ; i++) {
        if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
            def->graphics[i]->data.vnc.autoport)
4371
            def->graphics[i]->data.vnc.port = QEMU_VNC_PORT_MIN;
4372 4373
    }

4374
    if (qemuCapsExtractVersionInfo(def->emulator, def->os.arch,
4375
                                   NULL,
4376
                                   &qemuCaps) < 0)
4377 4378
        goto cleanup;

4379
    if (qemuProcessPrepareMonitorChr(driver, &monConfig, def->name) < 0)
4380
        goto cleanup;
4381

4382
    if (!(cmd = qemuBuildCommandLine(conn, driver, def,
4383
                                     &monConfig, false, qemuCaps,
4384
                                     NULL, -1, NULL, VIR_VM_OP_NO_OP)))
4385 4386
        goto cleanup;

E
Eric Blake 已提交
4387
    ret = virCommandToString(cmd);
4388 4389

cleanup:
4390
    qemuDriverUnlock(driver);
4391

4392
    qemuCapsFree(qemuCaps);
E
Eric Blake 已提交
4393
    virCommandFree(cmd);
4394 4395 4396 4397 4398
    virDomainDefFree(def);
    return ret;
}


4399
static int qemudListDefinedDomains(virConnectPtr conn,
4400
                            char **const names, int nnames) {
4401
    struct qemud_driver *driver = conn->privateData;
4402
    int n;
4403

4404
    qemuDriverLock(driver);
4405
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
4406
    qemuDriverUnlock(driver);
4407
    return n;
D
Daniel P. Berrange 已提交
4408 4409
}

4410
static int qemudNumDefinedDomains(virConnectPtr conn) {
4411
    struct qemud_driver *driver = conn->privateData;
4412
    int n;
4413

4414
    qemuDriverLock(driver);
4415
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
4416
    qemuDriverUnlock(driver);
4417

4418
    return n;
D
Daniel P. Berrange 已提交
4419 4420 4421
}


4422 4423 4424 4425 4426 4427 4428
static int
qemuDomainObjStart(virConnectPtr conn,
                   struct qemud_driver *driver,
                   virDomainObjPtr vm,
                   bool start_paused,
                   bool autodestroy,
                   bool bypass_cache)
J
Jiri Denemark 已提交
4429 4430 4431 4432 4433 4434
{
    int ret = -1;
    char *managed_save;

    /*
     * If there is a managed saved state restore it instead of starting
4435
     * from scratch. The old state is removed once the restoring succeeded.
J
Jiri Denemark 已提交
4436 4437
     */
    managed_save = qemuDomainManagedSavePath(driver, vm);
4438 4439 4440 4441

    if (!managed_save)
        goto cleanup;

E
Eric Blake 已提交
4442
    if (virFileExists(managed_save)) {
4443 4444
        ret = qemuDomainObjRestore(conn, driver, vm, managed_save,
                                   bypass_cache);
J
Jiri Denemark 已提交
4445

4446
        if ((ret == 0) && (unlink(managed_save) < 0))
J
Jiri Denemark 已提交
4447 4448
            VIR_WARN("Failed to remove the managed state %s", managed_save);

4449
        goto cleanup;
J
Jiri Denemark 已提交
4450 4451
    }

4452
    ret = qemuProcessStart(conn, driver, vm, NULL, start_paused,
4453
                           autodestroy, -1, NULL, VIR_VM_OP_CREATE);
4454
    virDomainAuditStart(vm, "booted", ret >= 0);
4455
    if (ret >= 0) {
J
Jiri Denemark 已提交
4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
        if (event)
            qemuDomainEventQueue(driver, event);
    }

cleanup:
    VIR_FREE(managed_save);
    return ret;
}

4469
static int
4470
qemuDomainStartWithFlags(virDomainPtr dom, unsigned int flags)
4471
{
4472 4473 4474
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
4475

4476
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
4477 4478
                  VIR_DOMAIN_START_AUTODESTROY |
                  VIR_DOMAIN_START_BYPASS_CACHE, -1);
4479

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

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

4491
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
4492 4493 4494
        goto cleanup;

    if (virDomainObjIsActive(vm)) {
4495 4496
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is already running"));
4497 4498 4499
        goto endjob;
    }

4500 4501 4502 4503
    if (qemuDomainObjStart(dom->conn, driver, vm,
                           (flags & VIR_DOMAIN_START_PAUSED) != 0,
                           (flags & VIR_DOMAIN_START_AUTODESTROY) != 0,
                           (flags & VIR_DOMAIN_START_BYPASS_CACHE) != 0) < 0)
4504 4505 4506
        goto endjob;

    ret = 0;
4507

4508
endjob:
4509
    if (qemuDomainObjEndJob(driver, vm) == 0)
4510
        vm = NULL;
4511

4512
cleanup:
4513 4514
    if (vm)
        virDomainObjUnlock(vm);
4515
    qemuDriverUnlock(driver);
4516
    return ret;
D
Daniel P. Berrange 已提交
4517 4518
}

4519
static int
4520
qemuDomainStart(virDomainPtr dom)
4521
{
4522
    return qemuDomainStartWithFlags(dom, 0);
4523 4524
}

4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539
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;

4540
        if (def->os.machine && STRNEQ(def->os.machine, machine->name))
4541 4542 4543
            continue;

        if (!(*canonical = strdup(machine->canonical))) {
4544
            virReportOOMError();
4545 4546 4547 4548 4549 4550 4551 4552 4553
            return -1;
        }

        break;
    }

    return 0;
}

4554 4555 4556 4557 4558 4559
static int
qemudCanonicalizeMachineDirect(virDomainDefPtr def, char **canonical)
{
    virCapsGuestMachinePtr *machines = NULL;
    int i, nmachines = 0;

4560
    if (qemuCapsProbeMachineTypes(def->emulator, &machines, &nmachines) < 0)
4561 4562 4563 4564 4565 4566
        return -1;

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

4567
        if (def->os.machine && STRNEQ(def->os.machine, machines[i]->name))
4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579
            continue;

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

    virCapabilitiesFreeMachines(machines, nmachines);

    return 0;
}

4580 4581
int
qemudCanonicalizeMachine(struct qemud_driver *driver, virDomainDefPtr def)
4582 4583 4584 4585 4586 4587
{
    char *canonical = NULL;
    int i;

    for (i = 0; i < driver->caps->nguests; i++) {
        virCapsGuestPtr guest = driver->caps->guests[i];
4588
        virCapsGuestDomainInfoPtr info;
4589 4590 4591
        int j;

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

4594 4595 4596 4597 4598 4599 4600 4601 4602
            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;
4603 4604
        }

4605 4606 4607 4608
        info = &guest->arch.defaultInfo;

        if (info->emulator && STREQ(info->emulator, def->emulator)) {
            if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
4609 4610 4611 4612
                return -1;
            goto out;
        }
    }
4613 4614 4615 4616

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

4617 4618 4619 4620 4621 4622 4623
out:
    if (canonical) {
        VIR_FREE(def->os.machine);
        def->os.machine = canonical;
    }
    return 0;
}
D
Daniel P. Berrange 已提交
4624

4625
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
4626
    struct qemud_driver *driver = conn->privateData;
4627
    virDomainDefPtr def;
4628
    virDomainObjPtr vm = NULL;
4629
    virDomainPtr dom = NULL;
4630
    virDomainEventPtr event = NULL;
4631
    int dupVM;
4632

4633
    qemuDriverLock(driver);
4634
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
4635
                                        QEMU_EXPECTED_VIRT_TYPES,
4636
                                        VIR_DOMAIN_XML_INACTIVE)))
4637
        goto cleanup;
4638

4639
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
4640 4641
        goto cleanup;

4642 4643
    if ((dupVM = virDomainObjIsDuplicate(&driver->domains, def, 0)) < 0)
        goto cleanup;
4644

4645
    if (qemudCanonicalizeMachine(driver, def) < 0)
4646 4647
        goto cleanup;

4648
    if (qemuDomainAssignPCIAddresses(def) < 0)
4649 4650
        goto cleanup;

4651
    if (!(vm = virDomainAssignDef(driver->caps,
4652
                                  &driver->domains,
4653
                                  def, false))) {
4654
        goto cleanup;
4655
    }
4656
    def = NULL;
4657
    vm->persistent = 1;
4658

4659
    if (virDomainSaveConfig(driver->configDir,
4660
                            vm->newDef ? vm->newDef : vm->def) < 0) {
4661
        VIR_INFO("Defining domain '%s'", vm->def->name);
4662 4663
        virDomainRemoveInactive(&driver->domains,
                                vm);
4664
        vm = NULL;
4665
        goto cleanup;
4666 4667
    }

4668 4669
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
4670
                                     !dupVM ?
4671 4672
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
4673

4674
    VIR_INFO("Creating domain '%s'", vm->def->name);
4675
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
4676
    if (dom) dom->id = vm->def->id;
4677 4678

cleanup:
4679
    virDomainDefFree(def);
4680 4681
    if (vm)
        virDomainObjUnlock(vm);
4682 4683
    if (event)
        qemuDomainEventQueue(driver, event);
4684
    qemuDriverUnlock(driver);
4685
    return dom;
D
Daniel P. Berrange 已提交
4686 4687
}

4688 4689 4690 4691
static int
qemuDomainUndefineFlags(virDomainPtr dom,
                         unsigned int flags)
{
4692 4693
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4694
    virDomainEventPtr event = NULL;
4695
    char *name = NULL;
4696
    int ret = -1;
D
Daniel P. Berrange 已提交
4697

4698 4699
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

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

D
Daniel P. Berrange 已提交
4703
    if (!vm) {
4704 4705
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4706 4707
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4708
        goto cleanup;
D
Daniel P. Berrange 已提交
4709 4710
    }

D
Daniel P. Berrange 已提交
4711
    if (virDomainObjIsActive(vm)) {
4712 4713
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot delete active domain"));
4714
        goto cleanup;
D
Daniel P. Berrange 已提交
4715 4716
    }

4717
    if (!vm->persistent) {
4718
        qemuReportError(VIR_ERR_OPERATION_INVALID,
4719
                        "%s", _("cannot undefine transient domain"));
4720
        goto cleanup;
4721 4722
    }

4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742
    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;
        }
    }

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

4746 4747 4748
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
4749

4750
    VIR_INFO("Undefining domain '%s'", vm->def->name);
4751 4752
    virDomainRemoveInactive(&driver->domains,
                            vm);
4753
    vm = NULL;
4754
    ret = 0;
D
Daniel P. Berrange 已提交
4755

4756
cleanup:
4757
    VIR_FREE(name);
4758 4759
    if (vm)
        virDomainObjUnlock(vm);
4760 4761
    if (event)
        qemuDomainEventQueue(driver, event);
4762
    qemuDriverUnlock(driver);
4763
    return ret;
D
Daniel P. Berrange 已提交
4764 4765
}

4766 4767 4768 4769 4770 4771
static int
qemudDomainUndefine(virDomainPtr dom)
{
    return qemuDomainUndefineFlags(dom, 0);
}

4772 4773 4774
static int
qemuDomainAttachDeviceDiskLive(struct qemud_driver *driver,
                               virDomainObjPtr vm,
4775
                               virDomainDeviceDefPtr dev)
4776 4777 4778 4779
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
    int ret = -1;
4780

4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800
    if (disk->driverName != NULL && !STREQ(disk->driverName, "qemu")) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("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:
4801
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, false);
4802 4803 4804 4805
        break;
    case VIR_DOMAIN_DISK_DEVICE_DISK:
        if (disk->bus == VIR_DOMAIN_DISK_BUS_USB)
            ret = qemuDomainAttachUsbMassstorageDevice(driver, vm,
4806
                                                       disk);
4807
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
4808
            ret = qemuDomainAttachPciDiskDevice(driver, vm, disk);
4809
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
4810
            ret = qemuDomainAttachSCSIDisk(driver, vm, disk);
4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836
        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,
4837
                                     virDomainDeviceDefPtr dev)
4838 4839 4840 4841 4842 4843
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
4844
        ret = qemuDomainAttachPciControllerDevice(driver, vm, cont);
4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857
        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,
4858
                           virDomainPtr dom)
4859 4860 4861 4862 4863 4864
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
4865
        qemuDomainObjCheckDiskTaint(driver, vm, dev->data.disk, -1);
4866
        ret = qemuDomainAttachDeviceDiskLive(driver, vm, dev);
4867 4868 4869 4870 4871
        if (!ret)
            dev->data.disk = NULL;
        break;

    case VIR_DOMAIN_DEVICE_CONTROLLER:
4872
        ret = qemuDomainAttachDeviceControllerLive(driver, vm, dev);
4873 4874 4875 4876
        if (!ret)
            dev->data.controller = NULL;
        break;

4877 4878 4879 4880 4881 4882 4883
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainAttachLease(driver, vm,
                                    dev->data.lease);
        if (ret == 0)
            dev->data.lease = NULL;
        break;

4884
    case VIR_DOMAIN_DEVICE_NET:
4885
        qemuDomainObjCheckNetTaint(driver, vm, dev->data.net, -1);
4886
        ret = qemuDomainAttachNetDevice(dom->conn, driver, vm,
4887
                                        dev->data.net);
4888 4889 4890 4891 4892 4893
        if (!ret)
            dev->data.net = NULL;
        break;

    case VIR_DOMAIN_DEVICE_HOSTDEV:
        ret = qemuDomainAttachHostDevice(driver, vm,
4894
                                         dev->data.hostdev);
4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911
        if (!ret)
            dev->data.hostdev = NULL;
        break;

    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,
4912
                               virDomainDeviceDefPtr dev)
4913 4914 4915 4916 4917 4918 4919
{
    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)
4920
            ret = qemuDomainDetachPciDiskDevice(driver, vm, dev);
4921
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
4922
            ret =  qemuDomainDetachDiskDevice(driver, vm, dev);
4923
        else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB)
4924
            ret = qemuDomainDetachDiskDevice(driver, vm, dev);
4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940
        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,
4941
                                     virDomainDeviceDefPtr dev)
4942 4943 4944 4945 4946 4947
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
4948
        ret = qemuDomainDetachPciControllerDevice(driver, vm, dev);
4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960
        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,
4961
                           virDomainPtr dom)
4962 4963 4964 4965 4966 4967
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
4968
        ret = qemuDomainDetachDeviceDiskLive(driver, vm, dev);
4969 4970
        break;
    case VIR_DOMAIN_DEVICE_CONTROLLER:
4971
        ret = qemuDomainDetachDeviceControllerLive(driver, vm, dev);
4972
        break;
4973 4974 4975
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainDetachLease(driver, vm, dev->data.lease);
        break;
4976
    case VIR_DOMAIN_DEVICE_NET:
4977
        ret = qemuDomainDetachNetDevice(driver, vm, dev);
4978 4979
        break;
    case VIR_DOMAIN_DEVICE_HOSTDEV:
4980
        ret = qemuDomainDetachHostDevice(driver, vm, dev);
4981 4982 4983 4984 4985 4986 4987 4988 4989 4990
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        "%s", _("This type of device cannot be hot unplugged"));
        break;
    }

    return ret;
}

4991 4992 4993 4994 4995 4996 4997 4998
static int
qemuDomainChangeDiskMediaLive(virDomainObjPtr vm,
                              virDomainDeviceDefPtr dev,
                              struct qemud_driver *driver,
                              bool force)
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
4999
    int ret = -1;
5000 5001 5002

    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup,
5003
                               vm->def->name, &cgroup, 0) != 0) {
5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015
            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:
5016
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, force);
5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048
        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:
5049
        ret = qemuDomainChangeDiskMediaLive(vm, dev, driver, force);
5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063
        break;
    case VIR_DOMAIN_DEVICE_GRAPHICS:
        ret = qemuDomainChangeGraphics(driver, vm, dev->data.graphics);
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("device type '%s' cannot be updated"),
                        virDomainDeviceTypeToString(dev->type));
        break;
    }

    return ret;
}

5064
static int
5065
qemuDomainAttachDeviceConfig(virDomainDefPtr vmdef,
5066 5067
                             virDomainDeviceDefPtr dev)
{
5068
    virDomainDiskDefPtr disk;
5069
    virDomainNetDefPtr net;
5070
    virDomainLeaseDefPtr lease;
5071

5072
    switch (dev->type) {
5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
        if (virDomainDiskIndexByName(vmdef, disk->dst) >= 0) {
            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;

5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109
    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;
5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125

    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;

5126 5127 5128 5129 5130 5131 5132 5133 5134 5135
    default:
         qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                         _("persistent attach of device is not supported"));
         return -1;
    }
    return 0;
}


static int
5136
qemuDomainDetachDeviceConfig(virDomainDefPtr vmdef,
5137 5138
                             virDomainDeviceDefPtr dev)
{
5139
    virDomainDiskDefPtr disk;
5140
    virDomainNetDefPtr net;
5141
    virDomainLeaseDefPtr lease;
5142

5143
    switch (dev->type) {
5144 5145 5146 5147 5148 5149 5150 5151
    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;
5152

5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163
    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;
5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174

    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;

5175 5176 5177 5178 5179 5180 5181 5182 5183
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("persistent detach of device is not supported"));
        return -1;
    }
    return 0;
}

static int
5184
qemuDomainUpdateDeviceConfig(virDomainDefPtr vmdef,
5185 5186
                             virDomainDeviceDefPtr dev)
{
5187 5188 5189
    virDomainDiskDefPtr orig, disk;
    int pos;

5190
    switch (dev->type) {
5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
        pos = virDomainDiskIndexByName(vmdef, disk->dst);
        if (pos < 0) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("target %s doesn't exists."), disk->dst);
            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;
5226 5227 5228 5229 5230 5231 5232 5233
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                         _("persistent update of device is not supported"));
        return -1;
    }
    return 0;
}

5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244
/* 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)
5245
{
5246
    struct qemud_driver *driver = dom->conn->privateData;
5247
    virDomainObjPtr vm = NULL;
5248
    virDomainDefPtr vmdef = NULL;
5249
    virDomainDeviceDefPtr dev = NULL;
5250
    bool force = (flags & VIR_DOMAIN_DEVICE_MODIFY_FORCE) != 0;
5251
    int ret = -1;
5252
    unsigned int affect;
5253

5254 5255
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
5256 5257 5258
                  (action == QEMU_DEVICE_UPDATE ?
                   VIR_DOMAIN_DEVICE_MODIFY_FORCE : 0), -1);

5259 5260
    affect = flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG);

5261 5262 5263 5264 5265 5266 5267
    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);
5268 5269 5270
        goto cleanup;
    }

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

5274
    if (virDomainObjIsActive(vm)) {
5275
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
5276
            flags |= VIR_DOMAIN_AFFECT_LIVE;
5277
    } else {
5278
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
5279
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
5280
        /* check consistency between flags and the vm state */
5281
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5282 5283 5284 5285 5286 5287
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s",
                            _("cannot do live update a device on "
                              "inactive domain"));
            goto endjob;
        }
5288
    }
5289

5290
    if ((flags & VIR_DOMAIN_AFFECT_CONFIG) && !vm->persistent) {
5291 5292 5293 5294
         qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("cannot modify device on transient domain"));
         goto endjob;
    }
5295

5296
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5297 5298 5299 5300 5301
        dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                      VIR_DOMAIN_XML_INACTIVE);
        if (dev == NULL)
            goto endjob;

5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320
        /* 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;
        }
5321

5322 5323 5324 5325 5326
        if (ret == -1)
            goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5327 5328 5329 5330
        /* 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);
5331 5332
        if (dev == NULL) {
            ret = -1;
5333
            goto endjob;
5334
        }
5335

5336 5337
        switch (action) {
        case QEMU_DEVICE_ATTACH:
5338
            ret = qemuDomainAttachDeviceLive(vm, dev, dom);
5339 5340
            break;
        case QEMU_DEVICE_DETACH:
5341
            ret = qemuDomainDetachDeviceLive(vm, dev, dom);
5342 5343
            break;
        case QEMU_DEVICE_UPDATE:
5344
            ret = qemuDomainUpdateDeviceLive(vm, dev, dom, force);
5345 5346 5347 5348
            break;
        default:
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("unknown domain modify action %d"), action);
5349
            ret = -1;
5350 5351
            break;
        }
5352 5353 5354

        if (ret == -1)
            goto endjob;
5355 5356
        /*
         * update domain status forcibly because the domain status may be
5357 5358
         * changed even if we failed to attach the device. For example,
         * a new controller may be created.
5359
         */
5360
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
5361
            ret = -1;
5362 5363
            goto endjob;
        }
5364
    }
5365

5366
    /* Finally, if no error until here, we can save config. */
5367
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5368 5369 5370 5371 5372 5373
        ret = virDomainSaveConfig(driver->configDir, vmdef);
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false);
            vmdef = NULL;
        }
    }
5374 5375

endjob:
5376
    if (qemuDomainObjEndJob(driver, vm) == 0)
5377 5378 5379
        vm = NULL;

cleanup:
5380
    virDomainDefFree(vmdef);
5381 5382 5383 5384
    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
5385 5386 5387
    return ret;
}

5388 5389 5390 5391 5392 5393
static int qemuDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_ATTACH);
}

5394 5395 5396
static int qemuDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainAttachDeviceFlags(dom, xml,
5397
                                       VIR_DOMAIN_AFFECT_LIVE);
5398
}
5399

5400

5401 5402 5403 5404
static int qemuDomainUpdateDeviceFlags(virDomainPtr dom,
                                       const char *xml,
                                       unsigned int flags)
{
5405
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_UPDATE);
5406 5407
}

5408 5409 5410
static int qemuDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
5411
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_DETACH);
5412 5413
}

5414 5415 5416
static int qemuDomainDetachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainDetachDeviceFlags(dom, xml,
5417
                                       VIR_DOMAIN_AFFECT_LIVE);
5418 5419
}

5420
static int qemudDomainGetAutostart(virDomainPtr dom,
5421
                                   int *autostart) {
5422 5423 5424
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
5425

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

5430
    if (!vm) {
5431 5432
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5433 5434
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5435
        goto cleanup;
5436 5437 5438
    }

    *autostart = vm->autostart;
5439
    ret = 0;
5440

5441
cleanup:
5442 5443
    if (vm)
        virDomainObjUnlock(vm);
5444
    return ret;
5445 5446
}

5447
static int qemudDomainSetAutostart(virDomainPtr dom,
5448
                                   int autostart) {
5449 5450
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
5451 5452
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
5453

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

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

5465
    if (!vm->persistent) {
5466
        qemuReportError(VIR_ERR_OPERATION_INVALID,
5467
                        "%s", _("cannot set autostart for transient domain"));
5468
        goto cleanup;
5469 5470
    }

5471 5472
    autostart = (autostart != 0);

5473
    if (vm->autostart != autostart) {
5474
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
5475
            goto cleanup;
5476
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
5477
            goto cleanup;
5478

5479
        if (autostart) {
5480 5481
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
5482 5483
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
5484 5485
                goto cleanup;
            }
5486

5487
            if (symlink(configFile, autostartLink) < 0) {
5488
                virReportSystemError(errno,
5489 5490
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
5491 5492 5493 5494
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
5495
                virReportSystemError(errno,
5496 5497
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
5498 5499
                goto cleanup;
            }
5500 5501
        }

5502
        vm->autostart = autostart;
5503
    }
5504
    ret = 0;
5505

5506 5507 5508
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
5509 5510
    if (vm)
        virDomainObjUnlock(vm);
5511
    qemuDriverUnlock(driver);
5512
    return ret;
5513 5514
}

5515

5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548
/*
 * 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;
}


5549 5550 5551 5552
static char *qemuGetSchedulerType(virDomainPtr dom,
                                  int *nparams)
{
    struct qemud_driver *driver = dom->conn->privateData;
5553
    char *ret = NULL;
5554
    int rc;
5555

5556
    qemuDriverLock(driver);
5557
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
5558 5559
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup CPU controller is not mounted"));
5560
        goto cleanup;
5561 5562
    }

5563 5564 5565 5566 5567 5568 5569 5570 5571
    if (nparams) {
        rc = qemuGetCpuBWStatus(driver->cgroup);
        if (rc < 0)
            goto cleanup;
        else if (rc == 0)
            *nparams = 1;
        else
            *nparams = 3;
    }
5572 5573 5574

    ret = strdup("posix");
    if (!ret)
5575
        virReportOOMError();
5576 5577 5578

cleanup:
    qemuDriverUnlock(driver);
5579 5580 5581
    return ret;
}

5582
static int qemuDomainSetBlkioParameters(virDomainPtr dom,
5583
                                         virTypedParameterPtr params,
5584 5585 5586 5587 5588 5589 5590
                                         int nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5591
    virDomainDefPtr persistentDef = NULL;
5592
    int ret = -1;
5593
    bool isActive;
5594

5595 5596
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5597 5598 5599 5600 5601 5602 5603 5604 5605 5606
    qemuDriverLock(driver);

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

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

5607 5608 5609 5610 5611 5612 5613
    isActive = virDomainObjIsActive(vm);

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

5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642
    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)) {
            qemuReportError(VIR_ERR_NO_SUPPORT, _("blkio cgroup isn't 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;
        }
    }

    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;
5643 5644 5645
    }

    ret = 0;
5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664
    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;
                }
5665

5666 5667 5668 5669 5670 5671 5672 5673 5674
                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);
5675 5676
                ret = -1;
            }
5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688
        }
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        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;
                }
5689

5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700
                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);
5701 5702 5703
                ret = -1;
            }
        }
A
Alex Jia 已提交
5704 5705 5706

        if (virDomainSaveConfig(driver->configDir, persistentDef) < 0)
            ret = -1;
5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717
    }

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

static int qemuDomainGetBlkioParameters(virDomainPtr dom,
5718
                                         virTypedParameterPtr params,
5719 5720 5721 5722 5723 5724 5725
                                         int *nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5726
    virDomainDefPtr persistentDef = NULL;
5727 5728 5729
    unsigned int val;
    int ret = -1;
    int rc;
5730
    bool isActive;
5731

5732 5733
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756
    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;
    }

    if ((*nparams) != QEMU_NB_BLKIO_PARAM) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
        goto cleanup;
    }

5757 5758 5759 5760 5761 5762 5763
    isActive = virDomainObjIsActive(vm);

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

5766 5767 5768 5769 5770 5771
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }
5772

5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
            qemuReportError(VIR_ERR_NO_SUPPORT, _("blkio cgroup isn't 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;
        }
    }

    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) {
        for (i = 0; i < *nparams; i++) {
            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,
                                    "%s", _("Field blkio weight too long for destination"));
                    goto cleanup;
                }
                param->value.ui = val;
                break;

            default:
                break;
                /* should not hit here */
5821
            }
5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838
        }
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        for (i = 0; i < *nparams; i++) {
            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,
                                    "%s", _("Field blkio weight too long for destination"));
                    goto cleanup;
                }
                param->value.ui = persistentDef->blkio.weight;
                break;
5839

5840 5841 5842 5843
            default:
                break;
                /* should not hit here */
            }
5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856
        }
    }

    ret = 0;

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

static int qemuDomainSetMemoryParameters(virDomainPtr dom,
5859
                                         virTypedParameterPtr params,
5860
                                         int nparams,
5861
                                         unsigned int flags)
5862 5863 5864
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
5865
    virDomainDefPtr persistentDef = NULL;
5866 5867 5868
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;
5869 5870
    bool isActive;

5871 5872
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883

    qemuDriverLock(driver);

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

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

5884 5885
    isActive = virDomainObjIsActive(vm);

5886
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
5887
        if (isActive)
5888
            flags = VIR_DOMAIN_AFFECT_LIVE;
5889
        else
5890
            flags = VIR_DOMAIN_AFFECT_CONFIG;
5891 5892
    }

5893
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912
        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;
        }
    }

5913
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5914 5915 5916 5917 5918 5919 5920
        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;
5921 5922 5923 5924
    }

    ret = 0;
    for (i = 0; i < nparams; i++) {
5925
        virTypedParameterPtr param = &params[i];
5926 5927 5928

        if (STREQ(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT)) {
            int rc;
5929
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
5930 5931 5932 5933 5934 5935
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for memory hard_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

5936
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5937 5938 5939 5940 5941 5942 5943 5944
                rc = virCgroupSetMemoryHardLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory hard_limit tunable"));
                    ret = -1;
                }
            }

5945
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5946
                persistentDef->mem.hard_limit = params[i].value.ul;
5947 5948 5949
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT)) {
            int rc;
5950
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
5951 5952 5953 5954 5955 5956
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for memory soft_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

5957
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5958 5959 5960 5961 5962 5963 5964 5965
                rc = virCgroupSetMemorySoftLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory soft_limit tunable"));
                    ret = -1;
                }
            }

5966
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5967
                persistentDef->mem.soft_limit = params[i].value.ul;
5968
            }
5969
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT)) {
5970
            int rc;
5971
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
5972 5973 5974 5975 5976 5977
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for swap_hard_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

5978
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5979 5980 5981 5982 5983 5984 5985
                rc = virCgroupSetMemSwapHardLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set swap_hard_limit tunable"));
                    ret = -1;
                }
            }
5986
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5987
                persistentDef->mem.swap_hard_limit = params[i].value.ul;
5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Memory tunable `%s' not implemented"), param->field);
            ret = -1;
        } else {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Parameter `%s' not supported"), param->field);
            ret = -1;
        }
    }

6000
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6001 6002
        if (virDomainSaveConfig(driver->configDir, persistentDef) < 0)
            ret = -1;
6003 6004
    }

6005 6006 6007 6008 6009 6010 6011 6012
cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

6013
static int qemuDomainGetMemoryParameters(virDomainPtr dom,
6014
                                         virTypedParameterPtr params,
6015
                                         int *nparams,
6016
                                         unsigned int flags)
6017 6018 6019 6020 6021
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6022
    virDomainDefPtr persistentDef = NULL;
6023
    unsigned long long val;
6024 6025
    int ret = -1;
    int rc;
6026
    bool isActive;
6027

6028 6029
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6030

6031
    qemuDriverLock(driver);
6032 6033 6034 6035 6036 6037 6038 6039 6040

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

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

6041 6042
    isActive = virDomainObjIsActive(vm);

6043
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
6044
        if (isActive)
6045
            flags = VIR_DOMAIN_AFFECT_LIVE;
6046
        else
6047
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6048 6049
    }

6050
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069
        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;
        }
    }

6070
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6071 6072 6073 6074 6075 6076 6077
        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;
6078 6079
    }

6080 6081 6082 6083 6084 6085 6086
    if ((*nparams) == 0) {
        /* Current number of memory parameters supported by cgroups */
        *nparams = QEMU_NB_MEM_PARAM;
        ret = 0;
        goto cleanup;
    }

6087
    if ((*nparams) < QEMU_NB_MEM_PARAM) {
6088 6089 6090 6091 6092
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
        goto cleanup;
    }

6093
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6094 6095 6096 6097
        for (i = 0; i < *nparams; i++) {
            virMemoryParameterPtr param = &params[i];
            val = 0;
            param->value.ul = 0;
6098
            param->type = VIR_TYPED_PARAM_ULLONG;
6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133

            switch (i) {
            case 0: /* fill memory hard limit here */
                if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT) == NULL) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                    "%s", _("Field memory hard limit too long for destination"));
                    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,
                                    "%s", _("Field memory soft limit too long for destination"));
                    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,
                                    "%s", _("Field swap hard limit too long for destination"));
                    goto cleanup;
                }
                param->value.ul = persistentDef->mem.swap_hard_limit;
                break;

            default:
                break;
                /* should not hit here */
            }
        }
        goto out;
6134 6135
    }

6136
    for (i = 0; i < QEMU_NB_MEM_PARAM; i++) {
6137
        virTypedParameterPtr param = &params[i];
6138 6139
        val = 0;
        param->value.ul = 0;
6140
        param->type = VIR_TYPED_PARAM_ULLONG;
6141

6142
        switch (i) {
6143 6144 6145 6146 6147
        case 0: /* fill memory hard limit here */
            rc = virCgroupGetMemoryHardLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory hard limit"));
6148
                goto cleanup;
6149 6150 6151 6152
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field memory hard limit too long for destination"));
6153
                goto cleanup;
6154 6155 6156 6157 6158 6159 6160 6161 6162
            }
            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"));
6163
                goto cleanup;
6164 6165 6166 6167
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field memory soft limit too long for destination"));
6168
                goto cleanup;
6169 6170 6171 6172 6173
            }
            param->value.ul = val;
            break;

        case 2: /* fill swap hard limit here */
6174
            rc = virCgroupGetMemSwapHardLimit(group, &val);
6175 6176 6177
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get swap hard limit"));
6178
                goto cleanup;
6179
            }
6180
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT) == NULL) {
6181 6182
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field swap hard limit too long for destination"));
6183
                goto cleanup;
6184 6185 6186 6187 6188 6189 6190 6191 6192 6193
            }
            param->value.ul = val;
            break;

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

6194
out:
6195
    *nparams = QEMU_NB_MEM_PARAM;
6196 6197
    ret = 0;

6198 6199 6200 6201 6202 6203 6204 6205 6206
cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

6207 6208 6209 6210 6211 6212 6213 6214
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 已提交
6215 6216 6217
    long long vm_quota = 0;
    long long old_quota = 0;
    unsigned long long old_period = 0;
6218 6219 6220 6221

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

W
Wen Congyang 已提交
6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240
    /* 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;
    }
6241

W
Wen Congyang 已提交
6242 6243 6244 6245 6246
    rc = virCgroupGetCpuCfsPeriod(cgroup, &old_period);
    if (rc < 0) {
        virReportSystemError(-rc, "%s",
                             _("unable to get cpu bandwidth period tunable"));
        goto cleanup;
6247 6248
    }

W
Wen Congyang 已提交
6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269
    /*
     * 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;
6270
        }
W
Wen Congyang 已提交
6271
    }
6272

W
Wen Congyang 已提交
6273 6274 6275 6276
    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)
6277 6278
            goto cleanup;

W
Wen Congyang 已提交
6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298
    /* 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);
        }
6299 6300
    }

W
Wen Congyang 已提交
6301 6302 6303 6304 6305 6306
    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;

6307 6308 6309 6310 6311 6312 6313
    return 0;

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

6314
static int qemuSetSchedulerParametersFlags(virDomainPtr dom,
6315
                                           virTypedParameterPtr params,
6316 6317
                                           int nparams,
                                           unsigned int flags)
6318 6319 6320 6321 6322
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6323
    virDomainDefPtr vmdef = NULL;
6324
    int ret = -1;
6325
    bool isActive;
6326
    int rc;
6327

6328 6329
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6330

6331
    qemuDriverLock(driver);
6332 6333 6334 6335

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

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

6341 6342
    isActive = virDomainObjIsActive(vm);

6343
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
6344
        if (isActive)
6345
            flags = VIR_DOMAIN_AFFECT_LIVE;
6346
        else
6347
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6348 6349
    }

6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360
    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;
6361 6362
    }

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

6383
    for (i = 0; i < nparams; i++) {
6384
        virTypedParameterPtr param = &params[i];
6385 6386

        if (STREQ(param->field, "cpu_shares")) {
6387
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
6388 6389
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for cpu_shares tunable, expected a 'ullong'"));
6390 6391 6392
                goto cleanup;
            }

6393
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6394 6395 6396 6397 6398 6399 6400 6401
                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;
6402
            }
6403

6404
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6405 6406
                vmdef->cputune.shares = params[i].value.ul;
            }
W
Wen Congyang 已提交
6407
        } else if (STREQ(param->field, "vcpu_period")) {
6408 6409
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
W
Wen Congyang 已提交
6410
                                _("invalid type for vcpu_period tunable,"
6411 6412 6413 6414 6415 6416 6417
                                  " expected a 'ullong'"));
                goto cleanup;
            }

            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
                rc = qemuSetVcpusBWLive(vm, group, params[i].value.ul, 0);
                if (rc != 0)
6418
                    goto cleanup;
6419 6420 6421 6422 6423 6424 6425 6426

                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;
            }
W
Wen Congyang 已提交
6427
        } else if (STREQ(param->field, "vcpu_quota")) {
6428 6429
            if (param->type != VIR_TYPED_PARAM_LLONG) {
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
W
Wen Congyang 已提交
6430
                                _("invalid type for vcpu_quota tunable,"
6431 6432 6433 6434 6435 6436 6437
                                  " expected a 'llong'"));
                goto cleanup;
            }

            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
                rc = qemuSetVcpusBWLive(vm, group, 0, params[i].value.l);
                if (rc != 0)
6438
                    goto cleanup;
6439 6440 6441 6442 6443 6444 6445

                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;
6446
            }
6447
        } else {
6448 6449
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Invalid parameter `%s'"), param->field);
6450 6451 6452
            goto cleanup;
        }
    }
6453

6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466
    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;
    }

6467 6468 6469
    ret = 0;

cleanup:
6470
    virDomainDefFree(vmdef);
6471 6472 6473
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
6474
    qemuDriverUnlock(driver);
6475 6476 6477
    return ret;
}

6478
static int qemuSetSchedulerParameters(virDomainPtr dom,
6479
                                      virTypedParameterPtr params,
6480 6481 6482 6483 6484
                                      int nparams)
{
    return qemuSetSchedulerParametersFlags(dom,
                                           params,
                                           nparams,
6485
                                           VIR_DOMAIN_AFFECT_LIVE);
6486 6487
}

6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552
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;
}

6553 6554 6555 6556 6557
static int
qemuGetSchedulerParametersFlags(virDomainPtr dom,
                                virTypedParameterPtr params,
                                int *nparams,
                                unsigned int flags)
6558 6559 6560 6561
{
    struct qemud_driver *driver = dom->conn->privateData;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6562 6563 6564
    unsigned long long shares;
    unsigned long long period;
    long long quota;
6565 6566
    int ret = -1;
    int rc;
6567
    bool isActive;
6568
    bool cpu_bw_status = false;
6569
    int saved_nparams = 0;
6570

6571 6572
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6573

6574 6575
    qemuDriverLock(driver);

6576 6577
    if ((flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)) ==
        (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)) {
6578 6579
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("cannot query live and config together"));
6580
        goto cleanup;
6581 6582
    }

6583
    if (*nparams < 1) {
6584 6585
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
6586
        goto cleanup;
6587 6588
    }

6589 6590 6591 6592 6593 6594 6595
    if (*nparams > 1) {
        rc = qemuGetCpuBWStatus(driver->cgroup);
        if (rc < 0)
            goto cleanup;
        cpu_bw_status = !!rc;
    }

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

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

6604 6605
    isActive = virDomainObjIsActive(vm);

6606
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
6607
        if (isActive)
6608
            flags = VIR_DOMAIN_AFFECT_LIVE;
6609
        else
6610
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6611 6612
    }

6613
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628
        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;
            }
6629 6630 6631 6632 6633
            shares = persistentDef->cputune.shares;
            if (*nparams > 1 && cpu_bw_status) {
                period = persistentDef->cputune.period;
                quota = persistentDef->cputune.quota;
            }
6634
        } else {
6635 6636 6637 6638 6639
            shares = vm->def->cputune.shares;
            if (*nparams > 1 && cpu_bw_status) {
                period = vm->def->cputune.period;
                quota = vm->def->cputune.quota;
            }
6640
        }
6641
        goto out;
6642 6643
    }

6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655
    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;
    }

6656
    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
6657 6658
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find cgroup for domain %s"), vm->def->name);
6659 6660 6661
        goto cleanup;
    }

6662
    rc = virCgroupGetCpuShares(group, &shares);
6663
    if (rc != 0) {
6664
        virReportSystemError(-rc, "%s",
6665 6666 6667
                             _("unable to get cpu shares tunable"));
        goto cleanup;
    }
6668 6669 6670 6671 6672 6673

    if (*nparams > 1 && cpu_bw_status) {
        rc = qemuGetVcpusBWLive(vm, group, &period, &quota);
        if (rc != 0)
            goto cleanup;
    }
6674
out:
6675
    params[0].value.ul = shares;
6676
    params[0].type = VIR_TYPED_PARAM_ULLONG;
C
Chris Lalancette 已提交
6677
    if (virStrcpyStatic(params[0].field, "cpu_shares") == NULL) {
6678 6679
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Field cpu_shares too long for destination"));
C
Chris Lalancette 已提交
6680 6681
        goto cleanup;
    }
6682

6683 6684 6685 6686 6687 6688
    saved_nparams++;

    if (cpu_bw_status) {
        if (*nparams > saved_nparams) {
            params[1].value.ul = period;
            params[1].type = VIR_TYPED_PARAM_ULLONG;
W
Wen Congyang 已提交
6689
            if (virStrcpyStatic(params[1].field, "vcpu_period") == NULL) {
6690 6691
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s",
W
Wen Congyang 已提交
6692
                                _("Field vcpu_period too long for destination"));
6693 6694 6695 6696 6697 6698 6699 6700
                goto cleanup;
            }
            saved_nparams++;
        }

        if (*nparams > saved_nparams) {
            params[2].value.ul = quota;
            params[2].type = VIR_TYPED_PARAM_LLONG;
W
Wen Congyang 已提交
6701
            if (virStrcpyStatic(params[2].field, "vcpu_quota") == NULL) {
6702 6703
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s",
W
Wen Congyang 已提交
6704
                                _("Field vcpu_quota too long for destination"));
6705 6706 6707 6708 6709 6710 6711 6712
                goto cleanup;
            }
            saved_nparams++;
        }
    }

    *nparams = saved_nparams;

6713 6714 6715 6716 6717 6718
    ret = 0;

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

6723 6724 6725 6726 6727 6728
static int
qemuGetSchedulerParameters(virDomainPtr dom,
                           virTypedParameterPtr params,
                           int *nparams)
{
    return qemuGetSchedulerParametersFlags(dom, params, nparams,
6729
                                           VIR_DOMAIN_AFFECT_CURRENT);
6730
}
6731

6732 6733 6734 6735 6736 6737 6738 6739 6740
/* 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
qemudDomainBlockStats (virDomainPtr dom,
                       const char *path,
                       struct _virDomainBlockStats *stats)
{
6741
    struct qemud_driver *driver = dom->conn->privateData;
6742
    int i, ret = -1;
6743
    virDomainObjPtr vm;
6744
    virDomainDiskDefPtr disk = NULL;
6745
    qemuDomainObjPrivatePtr priv;
6746

6747
    qemuDriverLock(driver);
6748
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6749
    qemuDriverUnlock(driver);
6750
    if (!vm) {
6751 6752
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
6753 6754
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
6755
        goto cleanup;
6756
    }
6757

6758 6759 6760 6761 6762 6763
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

6764 6765 6766 6767 6768 6769 6770 6771
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

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

6777
    if (!disk->info.alias) {
6778 6779
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("missing disk device alias name for %s"), disk->dst);
6780
        goto cleanup;
6781
    }
6782

6783
    priv = vm->privateData;
6784 6785
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
        goto cleanup;
6786

6787 6788 6789 6790 6791
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }
6792

6793
    qemuDomainObjEnterMonitor(driver, vm);
6794 6795 6796 6797 6798 6799 6800 6801
    ret = qemuMonitorGetBlockStatsInfo(priv->mon,
                                       disk->info.alias,
                                       &stats->rd_req,
                                       &stats->rd_bytes,
                                       &stats->wr_req,
                                       &stats->wr_bytes,
                                       &stats->errs);
    qemuDomainObjExitMonitor(driver, vm);
6802

6803
endjob:
6804 6805
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
6806

6807
cleanup:
6808 6809
    if (vm)
        virDomainObjUnlock(vm);
6810
    return ret;
6811 6812
}

6813
#ifdef __linux__
6814 6815 6816 6817 6818
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
6819 6820
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
6821
    int i;
6822
    int ret = -1;
6823

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

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

D
Daniel P. Berrange 已提交
6836
    if (!virDomainObjIsActive(vm)) {
6837 6838
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
6839
        goto cleanup;
6840 6841 6842
    }

    /* Check the path is one of the domain's network interfaces. */
6843 6844
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
6845 6846 6847 6848
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
6849 6850
    }

6851
    if (ret == 0)
6852
        ret = linuxDomainInterfaceStats(path, stats);
6853
    else
6854 6855
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path, '%s' is not a known interface"), path);
6856

6857
cleanup:
6858 6859
    if (vm)
        virDomainObjUnlock(vm);
6860 6861
    return ret;
}
6862
#else
6863 6864 6865 6866
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
6867
{
6868 6869
    qemuReportError(VIR_ERR_NO_SUPPORT,
                    "%s", __FUNCTION__);
6870 6871
    return -1;
}
6872
#endif
6873

6874 6875 6876
static int
qemudDomainMemoryStats (virDomainPtr dom,
                        struct _virDomainMemoryStat *stats,
6877 6878
                        unsigned int nr_stats,
                        unsigned int flags)
6879 6880 6881 6882 6883
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned int ret = -1;

6884 6885
    virCheckFlags(0, -1);

6886 6887 6888 6889 6890 6891 6892
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

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

6898
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
6899 6900
        goto cleanup;

6901 6902
    if (virDomainObjIsActive(vm)) {
        qemuDomainObjPrivatePtr priv = vm->privateData;
6903
        qemuDomainObjEnterMonitor(driver, vm);
6904
        ret = qemuMonitorGetMemoryStats(priv->mon, stats, nr_stats);
6905
        qemuDomainObjExitMonitor(driver, vm);
6906
    } else {
6907 6908
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
6909 6910
    }

6911
    if (qemuDomainObjEndJob(driver, vm) == 0)
6912 6913
        vm = NULL;

6914 6915 6916 6917 6918 6919
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

6920 6921 6922 6923 6924
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
E
Eric Blake 已提交
6925
                      unsigned int flags)
6926
{
6927 6928 6929
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
6930

E
Eric Blake 已提交
6931 6932
    virCheckFlags(0, -1);

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

6937
    if (!vm) {
6938 6939
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
6940 6941
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
6942
        goto cleanup;
6943 6944 6945
    }

    if (!path || path[0] == '\0') {
6946 6947
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("NULL or empty path"));
6948
        goto cleanup;
6949 6950 6951
    }

    /* Check the path belongs to this domain. */
6952 6953
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
6954 6955 6956 6957
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
6958 6959
    }

6960 6961 6962 6963 6964
    if (ret == 0) {
        ret = -1;
        /* The path is correct, now try to open it and get its size. */
        fd = open (path, O_RDONLY);
        if (fd == -1) {
6965 6966
            virReportSystemError(errno,
                                 _("%s: failed to open"), path);
6967 6968
            goto cleanup;
        }
6969

6970 6971 6972 6973 6974 6975
        /* 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) {
6976 6977
            virReportSystemError(errno,
                                 _("%s: failed to seek or read"), path);
6978 6979 6980 6981 6982
            goto cleanup;
        }

        ret = 0;
    } else {
6983 6984
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("invalid path"));
6985 6986
    }

6987
cleanup:
6988
    VIR_FORCE_CLOSE(fd);
6989 6990
    if (vm)
        virDomainObjUnlock(vm);
6991 6992 6993
    return ret;
}

R
Richard W.M. Jones 已提交
6994 6995 6996 6997 6998 6999
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
7000 7001
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
7002
    char *tmp = NULL;
R
Richard W.M. Jones 已提交
7003
    int fd = -1, ret = -1;
7004
    qemuDomainObjPrivatePtr priv;
R
Richard W.M. Jones 已提交
7005

7006 7007
    virCheckFlags(VIR_MEMORY_VIRTUAL | VIR_MEMORY_PHYSICAL, -1);

7008
    qemuDriverLock(driver);
7009
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7010
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
7011 7012

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

7020
    if (flags != VIR_MEMORY_VIRTUAL && flags != VIR_MEMORY_PHYSICAL) {
7021 7022
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("flags parameter must be VIR_MEMORY_VIRTUAL or VIR_MEMORY_PHYSICAL"));
7023
        goto cleanup;
R
Richard W.M. Jones 已提交
7024 7025
    }

7026
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
7027 7028
        goto cleanup;

D
Daniel P. Berrange 已提交
7029
    if (!virDomainObjIsActive(vm)) {
7030 7031
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
7032
        goto endjob;
R
Richard W.M. Jones 已提交
7033 7034
    }

7035
    if (virAsprintf(&tmp, "%s/qemu.mem.XXXXXX", driver->cacheDir) < 0) {
7036
        virReportOOMError();
7037
        goto endjob;
7038 7039
    }

R
Richard W.M. Jones 已提交
7040 7041
    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
7042 7043
        virReportSystemError(errno,
                             _("mkstemp(\"%s\") failed"), tmp);
7044
        goto endjob;
R
Richard W.M. Jones 已提交
7045 7046
    }

7047 7048
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm, tmp);

7049
    priv = vm->privateData;
7050
    qemuDomainObjEnterMonitor(driver, vm);
7051
    if (flags == VIR_MEMORY_VIRTUAL) {
7052
        if (qemuMonitorSaveVirtualMemory(priv->mon, offset, size, tmp) < 0) {
7053
            qemuDomainObjExitMonitor(driver, vm);
7054
            goto endjob;
7055
        }
7056
    } else {
7057
        if (qemuMonitorSavePhysicalMemory(priv->mon, offset, size, tmp) < 0) {
7058
            qemuDomainObjExitMonitor(driver, vm);
7059
            goto endjob;
7060
        }
R
Richard W.M. Jones 已提交
7061
    }
7062
    qemuDomainObjExitMonitor(driver, vm);
R
Richard W.M. Jones 已提交
7063 7064 7065

    /* Read the memory file into buffer. */
    if (saferead (fd, buffer, size) == (ssize_t) -1) {
7066 7067 7068
        virReportSystemError(errno,
                             _("failed to read temporary file "
                               "created with template %s"), tmp);
7069
        goto endjob;
R
Richard W.M. Jones 已提交
7070 7071 7072
    }

    ret = 0;
7073

7074
endjob:
7075
    if (qemuDomainObjEndJob(driver, vm) == 0)
7076
        vm = NULL;
7077

7078
cleanup:
7079
    VIR_FORCE_CLOSE(fd);
7080 7081
    if (tmp)
        unlink(tmp);
W
Wen Congyang 已提交
7082
    VIR_FREE(tmp);
7083 7084
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
7085 7086 7087
    return ret;
}

7088

7089 7090 7091 7092 7093 7094 7095 7096 7097
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;
7098
    virStorageFileMetadata *meta = NULL;
7099
    virDomainDiskDefPtr disk = NULL;
7100 7101
    struct stat sb;
    int i;
7102
    int format;
7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126

    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. */
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
            STREQ (vm->def->disks[i]->src, path)) {
7127
            disk = vm->def->disks[i];
7128 7129 7130 7131
            break;
        }
    }

7132
    if (!disk) {
7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path %s not assigned to domain"), path);
        goto cleanup;
    }

    /* The path is correct, now try to open it and get its size. */
    fd = open (path, O_RDONLY);
    if (fd == -1) {
        virReportSystemError(errno,
                             _("failed to open path '%s'"), path);
        goto cleanup;
    }

    /* Probe for magic formats */
7147 7148 7149 7150 7151 7152 7153 7154
    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 {
7155 7156 7157 7158 7159 7160 7161
        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);
7162
            goto cleanup;
7163
        }
7164 7165
    }

7166 7167 7168 7169 7170
    if (VIR_ALLOC(meta) < 0) {
        virReportOOMError();
        goto cleanup;
    }

7171 7172
    if (virStorageFileGetMetadataFromFD(path, fd,
                                        format,
7173
                                        meta) < 0)
7174 7175 7176 7177 7178 7179 7180 7181 7182 7183
        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)) {
7184
#ifndef WIN32
7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209
        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.
         */
        end = lseek (fd, 0, SEEK_END);
        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 */
7210 7211
    if (meta->capacity)
        info->capacity = meta->capacity;
7212

7213
    /* Set default value .. */
7214 7215
    info->allocation = info->physical;

7216 7217 7218
    /* ..but if guest is running & not using raw
       disk format and on a block device, then query
       highest allocated extent from QEMU */
7219
    if (disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
7220
        format != VIR_STORAGE_FILE_RAW &&
7221 7222
        S_ISBLK(sb.st_mode) &&
        virDomainObjIsActive(vm)) {
7223
        qemuDomainObjPrivatePtr priv = vm->privateData;
7224

7225 7226
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
            goto cleanup;
7227

7228
        if (virDomainObjIsActive(vm)) {
7229
            qemuDomainObjEnterMonitor(driver, vm);
7230 7231 7232 7233
            ret = qemuMonitorGetBlockExtent(priv->mon,
                                            disk->info.alias,
                                            &info->allocation);
            qemuDomainObjExitMonitor(driver, vm);
7234
        } else {
7235
            ret = 0;
7236
        }
7237 7238 7239

        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
7240 7241 7242
    } else {
        ret = 0;
    }
7243 7244

cleanup:
7245
    virStorageFileFreeMetadata(meta);
7246
    VIR_FORCE_CLOSE(fd);
7247 7248 7249 7250 7251 7252
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


7253
static int
7254 7255 7256 7257
qemuDomainEventRegister(virConnectPtr conn,
                        virConnectDomainEventCallback callback,
                        void *opaque,
                        virFreeCallback freecb)
7258
{
7259 7260 7261
    struct qemud_driver *driver = conn->privateData;
    int ret;

7262
    qemuDriverLock(driver);
7263 7264
    ret = virDomainEventCallbackListAdd(conn,
                                        driver->domainEventState->callbacks,
7265
                                        callback, opaque, freecb);
7266
    qemuDriverUnlock(driver);
7267

7268
    return ret;
7269 7270
}

7271

7272
static int
7273 7274
qemuDomainEventDeregister(virConnectPtr conn,
                          virConnectDomainEventCallback callback)
7275
{
7276 7277 7278
    struct qemud_driver *driver = conn->privateData;
    int ret;

7279
    qemuDriverLock(driver);
7280 7281 7282
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
7283
    qemuDriverUnlock(driver);
7284

7285
    return ret;
7286 7287
}

7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301

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,
7302
                                          driver->domainEventState->callbacks,
7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318
                                          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);
7319 7320 7321
    ret = virDomainEventStateDeregisterAny(conn,
                                           driver->domainEventState,
                                           callbackID);
7322 7323 7324 7325 7326 7327
    qemuDriverUnlock(driver);

    return ret;
}


7328 7329 7330
/*******************************************************************
 * Migration Protocol Version 2
 *******************************************************************/
D
Daniel Veillard 已提交
7331

C
Chris Lalancette 已提交
7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346
/* 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;
7347

7348
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
7349

7350 7351
    qemuDriverLock(driver);

C
Chris Lalancette 已提交
7352
    if (!dom_xml) {
7353 7354
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
C
Chris Lalancette 已提交
7355 7356 7357
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
7358
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
7359 7360 7361 7362
                         "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
        goto cleanup;
    }
    if (st == NULL) {
7363 7364
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("tunnelled migration requested but NULL stream passed"));
C
Chris Lalancette 已提交
7365 7366 7367
        goto cleanup;
    }

7368 7369 7370 7371 7372 7373 7374
    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

7375 7376 7377
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     NULL, 0, NULL, NULL, /* No cookies in v2 */
                                     st, dname, dom_xml);
7378

C
Chris Lalancette 已提交
7379
cleanup:
7380
    qemuDriverUnlock(driver);
C
Chris Lalancette 已提交
7381 7382 7383
    return ret;
}

D
Daniel Veillard 已提交
7384 7385 7386 7387
/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
7388
static int ATTRIBUTE_NONNULL (5)
D
Daniel Veillard 已提交
7389
qemudDomainMigratePrepare2 (virConnectPtr dconn,
7390 7391
                            char **cookie ATTRIBUTE_UNUSED,
                            int *cookielen ATTRIBUTE_UNUSED,
D
Daniel Veillard 已提交
7392 7393
                            const char *uri_in,
                            char **uri_out,
C
Chris Lalancette 已提交
7394
                            unsigned long flags,
D
Daniel Veillard 已提交
7395 7396 7397 7398
                            const char *dname,
                            unsigned long resource ATTRIBUTE_UNUSED,
                            const char *dom_xml)
{
7399
    struct qemud_driver *driver = dconn->privateData;
7400
    int ret = -1;
7401

7402
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
7403

7404
    *uri_out = NULL;
D
Daniel Veillard 已提交
7405

7406
    qemuDriverLock(driver);
7407 7408 7409 7410 7411 7412 7413 7414

    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 已提交
7415 7416 7417 7418
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
7419 7420
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Tunnelled migration requested but invalid RPC method called"));
C
Chris Lalancette 已提交
7421 7422 7423
        goto cleanup;
    }

D
Daniel Veillard 已提交
7424
    if (!dom_xml) {
7425 7426
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
7427
        goto cleanup;
D
Daniel Veillard 已提交
7428 7429
    }

7430 7431 7432 7433
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
7434
    ret = qemuMigrationPrepareDirect(driver, dconn,
7435
                                     NULL, 0, NULL, NULL, /* No cookies */
7436 7437
                                     uri_in, uri_out,
                                     dname, dom_xml);
D
Daniel Veillard 已提交
7438

7439 7440 7441 7442
cleanup:
    qemuDriverUnlock(driver);
    return ret;
}
C
Chris Lalancette 已提交
7443

D
Daniel Veillard 已提交
7444

7445 7446 7447
/* Perform is the second step, and it runs on the source host. */
static int
qemudDomainMigratePerform (virDomainPtr dom,
7448 7449
                           const char *cookie,
                           int cookielen,
7450 7451 7452 7453 7454 7455 7456 7457
                           const char *uri,
                           unsigned long flags,
                           const char *dname,
                           unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
7458
    const char *dconnuri = NULL;
7459

7460
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
7461

7462
    qemuDriverLock(driver);
7463 7464 7465 7466 7467 7468 7469
    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

7470
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel Veillard 已提交
7471
    if (!vm) {
7472 7473
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
7474 7475
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
7476
        goto cleanup;
D
Daniel Veillard 已提交
7477 7478
    }

7479 7480 7481 7482 7483
    if (flags & VIR_MIGRATE_PEER2PEER) {
        dconnuri = uri;
        uri = NULL;
    }

7484 7485 7486 7487 7488 7489
    /* 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
     */
7490
    ret = qemuMigrationPerform(driver, dom->conn, vm,
7491
                               NULL, dconnuri, uri, cookie, cookielen,
7492
                               NULL, NULL, /* No output cookies in v2 */
7493
                               flags, dname, resource, false);
7494

7495
cleanup:
7496
    qemuDriverUnlock(driver);
7497
    return ret;
D
Daniel Veillard 已提交
7498 7499
}

7500

D
Daniel Veillard 已提交
7501 7502 7503 7504 7505 7506 7507
/* 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 已提交
7508
                           unsigned long flags,
D
Daniel Veillard 已提交
7509 7510
                           int retcode)
{
7511 7512 7513
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
D
Daniel Veillard 已提交
7514

7515
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
C
Chris Lalancette 已提交
7516

7517
    qemuDriverLock(driver);
7518
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
7519
    if (!vm) {
7520 7521
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
7522
        goto cleanup;
D
Daniel Veillard 已提交
7523 7524
    }

7525 7526 7527 7528
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
7529
    dom = qemuMigrationFinish(driver, dconn, vm,
7530
                              NULL, 0, NULL, NULL, /* No cookies */
7531
                              flags, retcode, false);
7532

7533
cleanup:
7534
    qemuDriverUnlock(driver);
7535
    return dom;
D
Daniel Veillard 已提交
7536 7537
}

7538

7539 7540 7541 7542 7543 7544
/*******************************************************************
 * Migration Protocol Version 3
 *******************************************************************/

static char *
qemuDomainMigrateBegin3(virDomainPtr domain,
7545
                        const char *xmlin,
7546 7547 7548 7549 7550 7551 7552 7553 7554 7555
                        char **cookieout,
                        int *cookieoutlen,
                        unsigned long flags,
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    char *xml = NULL;

7556
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567

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

7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601
    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;
    }

    if (!(xml = qemuMigrationBegin(driver, vm, xmlin,
                                   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;
    }
7602 7603

cleanup:
7604 7605
    if (vm)
        virDomainObjUnlock(vm);
7606 7607
    qemuDriverUnlock(driver);
    return xml;
7608 7609 7610 7611 7612 7613 7614 7615 7616 7617

endjob:
    if ((flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        if (qemuMigrationJobFinish(driver, vm) == 0)
            vm = NULL;
    } else {
        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
    }
    goto cleanup;
7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635
}

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;

7636
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682

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

7683
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714

    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,
7715
                          const char *xmlin,
7716 7717 7718 7719
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
7720
                          const char *dconnuri,
7721 7722 7723 7724 7725 7726 7727 7728 7729
                          const char *uri,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

7730
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741

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

7742
    ret = qemuMigrationPerform(driver, dom->conn, vm, xmlin,
7743
                               dconnuri, uri, cookiein, cookieinlen,
7744
                               cookieout, cookieoutlen,
7745
                               flags, dname, resource, true);
7746 7747 7748 7749 7750 7751 7752

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}


7753
static virDomainPtr
7754 7755 7756 7757 7758 7759
qemuDomainMigrateFinish3(virConnectPtr dconn,
                         const char *dname,
                         const char *cookiein,
                         int cookieinlen,
                         char **cookieout,
                         int *cookieoutlen,
7760
                         const char *dconnuri ATTRIBUTE_UNUSED,
7761 7762
                         const char *uri ATTRIBUTE_UNUSED,
                         unsigned long flags,
7763
                         int cancelled)
7764 7765 7766
{
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
7767
    virDomainPtr dom = NULL;
7768

7769
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
7770 7771 7772 7773 7774 7775 7776 7777 7778

    qemuDriverLock(driver);
    vm = virDomainFindByName(&driver->domains, dname);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
        goto cleanup;
    }

7779 7780 7781 7782
    dom = qemuMigrationFinish(driver, dconn, vm,
                              cookiein, cookieinlen,
                              cookieout, cookieoutlen,
                              flags, cancelled, true);
7783 7784 7785

cleanup:
    qemuDriverUnlock(driver);
7786
    return dom;
7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798
}

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;
7799
    enum qemuMigrationJobPhase phase;
7800

7801
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812

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

7813
    if (!qemuMigrationJobIsActive(vm, QEMU_ASYNC_JOB_MIGRATION_OUT))
7814 7815
        goto cleanup;

7816 7817 7818 7819 7820 7821 7822
    if (cancelled)
        phase = QEMU_MIGRATION_PHASE_CONFIRM3_CANCELLED;
    else
        phase = QEMU_MIGRATION_PHASE_CONFIRM3;

    qemuMigrationJobStartPhase(driver, vm, phase);

7823 7824
    ret = qemuMigrationConfirm(driver, domain->conn, vm,
                               cookiein, cookieinlen,
7825 7826
                               flags, cancelled);

7827
    if (qemuMigrationJobFinish(driver, vm) == 0) {
7828 7829 7830 7831 7832 7833 7834 7835 7836
        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);
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }

7837
cleanup:
7838 7839
    if (vm)
        virDomainObjUnlock(vm);
7840 7841 7842 7843 7844
    qemuDriverUnlock(driver);
    return ret;
}


7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860
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;

7861
    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE);
7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878
    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) {
7879 7880
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("device %s is not a PCI device"), dev->name);
7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893
        goto out;
    }

    ret = 0;
out:
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
qemudNodeDeviceDettach (virNodeDevicePtr dev)
{
7894
    struct qemud_driver *driver = dev->conn->privateData;
7895 7896 7897 7898 7899 7900 7901
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

7902
    pci = pciGetDevice(domain, bus, slot, function);
7903 7904 7905
    if (!pci)
        return -1;

7906 7907
    qemuDriverLock(driver);
    if (pciDettachDevice(pci, driver->activePciHostdevs) < 0)
7908 7909 7910 7911
        goto out;

    ret = 0;
out:
7912
    qemuDriverUnlock(driver);
7913
    pciFreeDevice(pci);
7914 7915 7916 7917 7918 7919
    return ret;
}

static int
qemudNodeDeviceReAttach (virNodeDevicePtr dev)
{
7920
    struct qemud_driver *driver = dev->conn->privateData;
7921 7922 7923 7924 7925 7926 7927
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

7928
    pci = pciGetDevice(domain, bus, slot, function);
7929 7930 7931
    if (!pci)
        return -1;

7932 7933
    pciDeviceReAttachInit(pci);

7934 7935
    qemuDriverLock(driver);
    if (pciReAttachDevice(pci, driver->activePciHostdevs) < 0)
7936 7937 7938 7939
        goto out;

    ret = 0;
out:
7940
    qemuDriverUnlock(driver);
7941
    pciFreeDevice(pci);
7942 7943 7944 7945 7946 7947
    return ret;
}

static int
qemudNodeDeviceReset (virNodeDevicePtr dev)
{
7948
    struct qemud_driver *driver = dev->conn->privateData;
7949 7950 7951 7952 7953 7954 7955
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

7956
    pci = pciGetDevice(domain, bus, slot, function);
7957 7958 7959
    if (!pci)
        return -1;

7960 7961
    qemuDriverLock(driver);

7962
    if (pciResetDevice(pci, driver->activePciHostdevs, NULL) < 0)
7963 7964 7965 7966
        goto out;

    ret = 0;
out:
7967
    qemuDriverUnlock(driver);
7968
    pciFreeDevice(pci);
7969 7970 7971
    return ret;
}

7972 7973 7974
static int
qemuCPUCompare(virConnectPtr conn,
               const char *xmlDesc,
E
Eric Blake 已提交
7975
               unsigned int flags)
7976 7977 7978 7979
{
    struct qemud_driver *driver = conn->privateData;
    int ret = VIR_CPU_COMPARE_ERROR;

E
Eric Blake 已提交
7980 7981
    virCheckFlags(0, VIR_CPU_COMPARE_ERROR);

7982 7983 7984
    qemuDriverLock(driver);

    if (!driver->caps || !driver->caps->host.cpu) {
7985 7986
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        "%s", _("cannot get host CPU capabilities"));
7987 7988
    }
    else
7989
        ret = cpuCompareXML(driver->caps->host.cpu, xmlDesc);
7990 7991 7992 7993 7994 7995

    qemuDriverUnlock(driver);

    return ret;
}

7996

7997 7998 7999 8000
static char *
qemuCPUBaseline(virConnectPtr conn ATTRIBUTE_UNUSED,
                const char **xmlCPUs,
                unsigned int ncpus,
E
Eric Blake 已提交
8001
                unsigned int flags)
8002 8003 8004
{
    char *cpu;

E
Eric Blake 已提交
8005 8006
    virCheckFlags(0, NULL);

8007 8008 8009 8010 8011
    cpu = cpuBaselineXML(xmlCPUs, ncpus, NULL, 0);

    return cpu;
}

8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033

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)) {
8034
        if (priv->job.asyncJob) {
8035
            memcpy(info, &priv->job.info, sizeof(*info));
8036 8037 8038 8039 8040 8041

            /* 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 已提交
8042
            if (virTimeMs(&info->timeElapsed) < 0)
8043
                goto cleanup;
8044
            info->timeElapsed -= priv->job.start;
8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063
        } 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;
}


8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080
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;
    }

8081 8082
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_ABORT) < 0)
        goto cleanup;
8083

8084
    if (!virDomainObjIsActive(vm)) {
8085 8086
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
8087
        goto endjob;
8088 8089
    }

8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103
    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");
8104
    qemuDomainObjEnterMonitor(driver, vm);
8105 8106 8107 8108 8109 8110
    ret = qemuMonitorMigrateCancel(priv->mon);
    qemuDomainObjExitMonitor(driver, vm);

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
8111 8112 8113 8114 8115 8116 8117 8118

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


8119 8120 8121 8122 8123 8124 8125 8126 8127 8128
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;

8129
    virCheckFlags(0, -1);
8130 8131 8132

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
8133
    qemuDriverUnlock(driver);
8134 8135 8136 8137 8138 8139

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

8143 8144 8145
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
        goto cleanup;

8146 8147 8148
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
8149
        goto endjob;
8150 8151 8152 8153
    }

    priv = vm->privateData;

8154
    if (priv->job.asyncJob != QEMU_ASYNC_JOB_MIGRATION_OUT) {
8155 8156
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not being migrated"));
8157
        goto endjob;
8158 8159
    }

8160
    VIR_DEBUG("Setting migration downtime to %llums", downtime);
8161
    qemuDomainObjEnterMonitor(driver, vm);
8162 8163 8164 8165 8166 8167
    ret = qemuMonitorSetMigrationDowntime(priv->mon, downtime);
    qemuDomainObjExitMonitor(driver, vm);

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
8168 8169 8170 8171 8172 8173 8174

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

8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188
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);
8189
    qemuDriverUnlock(driver);
8190 8191 8192 8193 8194 8195

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

8199 8200 8201
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
        goto cleanup;

8202 8203 8204
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
8205
        goto endjob;
8206 8207 8208 8209
    }

    priv = vm->privateData;

8210
    if (priv->job.asyncJob != QEMU_ASYNC_JOB_MIGRATION_OUT) {
8211 8212
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not being migrated"));
8213
        goto endjob;
8214 8215
    }

8216
    VIR_DEBUG("Setting migration bandwidth to %luMbs", bandwidth);
8217
    qemuDomainObjEnterMonitor(driver, vm);
8218 8219 8220 8221 8222 8223
    ret = qemuMonitorSetMigrationSpeed(priv->mon, bandwidth);
    qemuDomainObjExitMonitor(driver, vm);

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
8224 8225 8226 8227 8228 8229 8230

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

C
Chris Lalancette 已提交
8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244
static char *qemuFindQemuImgBinary(void)
{
    char *ret;

    ret = virFindFileInPath("kvm-img");
    if (ret == NULL)
        ret = virFindFileInPath("qemu-img");
    if (ret == NULL)
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("unable to find kvm-img or qemu-img"));

    return ret;
}

8245 8246 8247
static int qemuDomainSnapshotWriteMetadata(virDomainObjPtr vm,
                                           virDomainSnapshotObjPtr snapshot,
                                           char *snapshotDir)
C
Chris Lalancette 已提交
8248 8249 8250 8251 8252 8253 8254 8255 8256
{
    int fd = -1;
    char *newxml = NULL;
    int ret = -1;
    char *snapDir = NULL;
    char *snapFile = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    virUUIDFormat(vm->def->uuid, uuidstr);
8257
    newxml = virDomainSnapshotDefFormat(uuidstr, snapshot->def, 1);
C
Chris Lalancette 已提交
8258 8259 8260 8261 8262 8263 8264 8265 8266
    if (newxml == NULL) {
        virReportOOMError();
        return -1;
    }

    if (virAsprintf(&snapDir, "%s/%s", snapshotDir, vm->def->name) < 0) {
        virReportOOMError();
        goto cleanup;
    }
8267 8268
    if (virFileMakePath(snapDir) < 0) {
        virReportSystemError(errno, _("cannot create snapshot directory '%s'"),
C
Chris Lalancette 已提交
8269 8270 8271 8272
                             snapDir);
        goto cleanup;
    }

8273
    if (virAsprintf(&snapFile, "%s/%s.xml", snapDir, snapshot->def->name) < 0) {
C
Chris Lalancette 已提交
8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294
        virReportOOMError();
        goto cleanup;
    }
    fd = open(snapFile, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR);
    if (fd < 0) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("failed to create snapshot file '%s'"), snapFile);
        goto cleanup;
    }
    if (safewrite(fd, newxml, strlen(newxml)) != strlen(newxml)) {
        virReportSystemError(errno, _("Failed to write snapshot data to %s"),
                             snapFile);
        goto cleanup;
    }

    ret = 0;

cleanup:
    VIR_FREE(snapFile);
    VIR_FREE(snapDir);
    VIR_FREE(newxml);
8295
    VIR_FORCE_CLOSE(fd);
C
Chris Lalancette 已提交
8296 8297 8298
    return ret;
}

8299 8300
static int qemuDomainSnapshotSetCurrentActive(virDomainObjPtr vm,
                                              char *snapshotDir)
C
Chris Lalancette 已提交
8301 8302 8303 8304
{
    if (vm->current_snapshot) {
        vm->current_snapshot->def->active = 1;

8305 8306
        return qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                               snapshotDir);
C
Chris Lalancette 已提交
8307 8308 8309 8310 8311
    }

    return 0;
}

8312 8313
static int qemuDomainSnapshotSetCurrentInactive(virDomainObjPtr vm,
                                                char *snapshotDir)
C
Chris Lalancette 已提交
8314 8315 8316 8317
{
    if (vm->current_snapshot) {
        vm->current_snapshot->def->active = 0;

8318 8319
        return qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                               snapshotDir);
C
Chris Lalancette 已提交
8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338
    }

    return 0;
}


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,
8339 8340
                            _("Disk '%s' does not support snapshotting"),
                            vm->def->disks[i]->src);
C
Chris Lalancette 已提交
8341 8342 8343 8344 8345 8346 8347
            return 0;
        }
    }

    return 1;
}

8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395
/* The domain is expected to be locked and inactive. */
static int
qemuDomainSnapshotCreateInactive(virDomainObjPtr vm,
                                 virDomainSnapshotObjPtr snap)
{
    const char *qemuimgarg[] = { NULL, "snapshot", "-c", NULL, NULL, NULL };
    int ret = -1;
    int i;

    qemuimgarg[0] = qemuFindQemuImgBinary();
    if (qemuimgarg[0] == NULL) {
        /* qemuFindQemuImgBinary set the error */
        goto cleanup;
    }

    qemuimgarg[3] = snap->def->name;

    for (i = 0; i < vm->def->ndisks; i++) {
        /* FIXME: we also need to handle LVM here */
        /* FIXME: if we fail halfway through this loop, we are in an
         * inconsistent state.  I'm not quite sure what to do about that
         */
        if (vm->def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
            if (!vm->def->disks[i]->driverType ||
                STRNEQ(vm->def->disks[i]->driverType, "qcow2")) {
                qemuReportError(VIR_ERR_OPERATION_INVALID,
                                _("Disk device '%s' does not support"
                                  " snapshotting"),
                                vm->def->disks[i]->info.alias);
                goto cleanup;
            }

            qemuimgarg[4] = vm->def->disks[i]->src;

            if (virRun(qemuimgarg, NULL) < 0)
                goto cleanup;
        }
    }

    ret = 0;

cleanup:
    VIR_FREE(qemuimgarg[0]);
    return ret;
}

/* The domain is expected to be locked and active. */
static int
8396 8397
qemuDomainSnapshotCreateActive(virConnectPtr conn,
                               struct qemud_driver *driver,
8398 8399 8400 8401 8402
                               virDomainObjPtr *vmptr,
                               virDomainSnapshotObjPtr snap)
{
    virDomainObjPtr vm = *vmptr;
    qemuDomainObjPrivatePtr priv = vm->privateData;
8403 8404
    bool resume = false;
    int ret = -1;
8405

8406
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
8407 8408
        return -1;

J
Jiri Denemark 已提交
8409
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
8410 8411 8412 8413
        /* 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.
         */
8414 8415
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_NONE) < 0)
8416 8417 8418 8419 8420 8421 8422 8423 8424 8425
            goto cleanup;

        resume = true;
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto cleanup;
        }
    }

8426
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
8427 8428 8429
    ret = qemuMonitorCreateSnapshot(priv->mon, snap->def->name);
    qemuDomainObjExitMonitorWithDriver(driver, vm);

8430 8431
cleanup:
    if (resume && virDomainObjIsActive(vm) &&
J
Jiri Denemark 已提交
8432
        qemuProcessStartCPUs(driver, vm, conn,
8433 8434
                             VIR_DOMAIN_RUNNING_UNPAUSED,
                             QEMU_ASYNC_JOB_NONE) < 0 &&
8435 8436 8437 8438 8439
        virGetLastError() == NULL) {
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("resuming after snapshot failed"));
    }

8440
    if (qemuDomainObjEndJob(driver, vm) == 0)
8441 8442 8443 8444 8445
        *vmptr = NULL;

    return ret;
}

C
Chris Lalancette 已提交
8446 8447
static virDomainSnapshotPtr qemuDomainSnapshotCreateXML(virDomainPtr domain,
                                                        const char *xmlDesc,
8448
                                                        unsigned int flags)
C
Chris Lalancette 已提交
8449 8450 8451 8452 8453 8454 8455 8456
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virDomainSnapshotDefPtr def;

8457 8458
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483
    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;
    }

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

    if (!(def = virDomainSnapshotDefParseString(xmlDesc, 1)))
        goto cleanup;

    if (!(snap = virDomainSnapshotAssignDef(&vm->snapshots, def)))
        goto cleanup;

J
Jiri Denemark 已提交
8484
    snap->def->state = virDomainObjGetState(vm, NULL);
8485

C
Chris Lalancette 已提交
8486 8487
    /* actually do the snapshot */
    if (!virDomainObjIsActive(vm)) {
8488
        if (qemuDomainSnapshotCreateInactive(vm, snap) < 0)
C
Chris Lalancette 已提交
8489 8490 8491
            goto cleanup;
    }
    else {
8492 8493
        if (qemuDomainSnapshotCreateActive(domain->conn, driver,
                                           &vm, snap) < 0)
8494
            goto cleanup;
C
Chris Lalancette 已提交
8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512
    }

    /* FIXME: if we fail after this point, there's not a whole lot we can
     * do; we've successfully taken the snapshot, and we are now running
     * on it, so we have to go forward the best we can
     */

    if (vm->current_snapshot) {
        def->parent = strdup(vm->current_snapshot->def->name);
        if (def->parent == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    }

    /* Now we set the new current_snapshot for the domain */
    vm->current_snapshot = snap;

8513 8514 8515
    if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                        driver->snapshotDir) < 0)
        /* qemuDomainSnapshotWriteMetadata set the error */
C
Chris Lalancette 已提交
8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528
        goto cleanup;

    snapshot = virGetDomainSnapshot(domain, snap->def->name);

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

static int qemuDomainSnapshotListNames(virDomainPtr domain, char **names,
                                       int nameslen,
8529
                                       unsigned int flags)
C
Chris Lalancette 已提交
8530 8531 8532 8533 8534
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

8535 8536
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556
    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;
    }

    n = virDomainSnapshotObjListGetNames(&vm->snapshots, names, nameslen);

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

static int qemuDomainSnapshotNum(virDomainPtr domain,
8557
                                 unsigned int flags)
C
Chris Lalancette 已提交
8558 8559 8560 8561 8562
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

8563 8564
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585
    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;
    }

    n = virDomainSnapshotObjListNum(&vm->snapshots);

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

static virDomainSnapshotPtr qemuDomainSnapshotLookupByName(virDomainPtr domain,
                                                           const char *name,
8586
                                                           unsigned int flags)
C
Chris Lalancette 已提交
8587 8588 8589 8590 8591 8592
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;

8593 8594
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621
    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,
8622
                                        unsigned int flags)
C
Chris Lalancette 已提交
8623 8624 8625 8626 8627
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

8628 8629
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649
    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;
}

static virDomainSnapshotPtr qemuDomainSnapshotCurrent(virDomainPtr domain,
8650
                                                      unsigned int flags)
C
Chris Lalancette 已提交
8651 8652 8653 8654 8655
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotPtr snapshot = NULL;

8656 8657
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682
    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;
}

8683 8684
static char *qemuDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                                          unsigned int flags)
C
Chris Lalancette 已提交
8685 8686 8687 8688 8689 8690 8691
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *xml = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

8692 8693
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720
    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;
    }

    xml = virDomainSnapshotDefFormat(uuidstr, snap->def, 0);

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

static int qemuDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
8721
                                      unsigned int flags)
C
Chris Lalancette 已提交
8722 8723 8724 8725 8726 8727 8728 8729 8730 8731
{
    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;
    qemuDomainObjPrivatePtr priv;
    int rc;

8732 8733
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752
    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;
    }

    vm->current_snapshot = snap;

8753
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
C
Chris Lalancette 已提交
8754 8755 8756 8757 8758 8759 8760
        goto cleanup;

    if (snap->def->state == VIR_DOMAIN_RUNNING
        || snap->def->state == VIR_DOMAIN_PAUSED) {

        if (virDomainObjIsActive(vm)) {
            priv = vm->privateData;
8761
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
C
Chris Lalancette 已提交
8762 8763 8764
            rc = qemuMonitorLoadSnapshot(priv->mon, snap->def->name);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            if (rc < 0)
8765
                goto endjob;
C
Chris Lalancette 已提交
8766 8767
        }
        else {
8768
            if (qemuDomainSnapshotSetCurrentActive(vm, driver->snapshotDir) < 0)
8769
                goto endjob;
C
Chris Lalancette 已提交
8770

8771
            rc = qemuProcessStart(snapshot->domain->conn, driver, vm, NULL,
8772
                                  false, false, -1, NULL, VIR_VM_OP_CREATE);
8773
            virDomainAuditStart(vm, "from-snapshot", rc >= 0);
8774
            if (qemuDomainSnapshotSetCurrentInactive(vm, driver->snapshotDir) < 0)
8775
                goto endjob;
C
Chris Lalancette 已提交
8776
            if (rc < 0)
8777
                goto endjob;
C
Chris Lalancette 已提交
8778 8779 8780 8781 8782
        }

        if (snap->def->state == VIR_DOMAIN_PAUSED) {
            /* qemu unconditionally starts the domain running again after
             * loadvm, so let's pause it to keep consistency
8783
             * XXX we should have used qemuProcessStart's start_paused instead
C
Chris Lalancette 已提交
8784
             */
J
Jiri Denemark 已提交
8785
            rc = qemuProcessStopCPUs(driver, vm,
8786 8787
                                     VIR_DOMAIN_PAUSED_FROM_SNAPSHOT,
                                     QEMU_ASYNC_JOB_NONE);
H
Hu Tao 已提交
8788
            if (rc < 0)
8789
                goto endjob;
J
Jiri Denemark 已提交
8790 8791 8792
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_FROM_SNAPSHOT);
C
Chris Lalancette 已提交
8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810
        }

        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT);
    }
    else {
        /* qemu is a little funny with running guests and the restoration
         * of snapshots.  If the snapshot was taken online,
         * then after a "loadvm" monitor command, the VM is set running
         * again.  If the snapshot was taken offline, then after a "loadvm"
         * monitor command the VM is left paused.  Unpausing it leads to
         * the memory state *before* the loadvm with the disk *after* the
         * loadvm, which obviously is bound to corrupt something.
         * Therefore we destroy the domain and set it to "off" in this case.
         */

        if (virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
8811
            qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT);
8812
            virDomainAuditStop(vm, "from-snapshot");
C
Chris Lalancette 已提交
8813 8814 8815
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STOPPED,
                                             VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT);
8816
            if (!vm->persistent) {
8817
                if (qemuDomainObjEndJob(driver, vm) > 0)
8818 8819
                    virDomainRemoveInactive(&driver->domains, vm);
                vm = NULL;
8820
                goto cleanup;
8821
            }
C
Chris Lalancette 已提交
8822 8823
        }

8824
        if (qemuDomainSnapshotSetCurrentActive(vm, driver->snapshotDir) < 0)
8825
            goto endjob;
C
Chris Lalancette 已提交
8826 8827 8828 8829
    }

    ret = 0;

8830
endjob:
8831
    if (vm && qemuDomainObjEndJob(driver, vm) == 0)
C
Chris Lalancette 已提交
8832 8833
        vm = NULL;

8834
cleanup:
C
Chris Lalancette 已提交
8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886
    if (event)
        qemuDomainEventQueue(driver, event);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);

    return ret;
}

static int qemuDomainSnapshotDiscard(struct qemud_driver *driver,
                                     virDomainObjPtr vm,
                                     virDomainSnapshotObjPtr snap)
{
    const char *qemuimgarg[] = { NULL, "snapshot", "-d", NULL, NULL, NULL };
    char *snapFile = NULL;
    int ret = -1;
    int i;
    qemuDomainObjPrivatePtr priv;
    virDomainSnapshotObjPtr parentsnap;

    if (!virDomainObjIsActive(vm)) {
        qemuimgarg[0] = qemuFindQemuImgBinary();
        if (qemuimgarg[0] == NULL)
            /* qemuFindQemuImgBinary set the error */
            goto cleanup;

        qemuimgarg[3] = snap->def->name;

        for (i = 0; i < vm->def->ndisks; i++) {
            /* FIXME: we also need to handle LVM here */
            if (vm->def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
                if (!vm->def->disks[i]->driverType ||
                    STRNEQ(vm->def->disks[i]->driverType, "qcow2")) {
                    /* we continue on even in the face of error, since other
                     * disks in this VM may have this snapshot in place
                     */
                    continue;
                }

                qemuimgarg[4] = vm->def->disks[i]->src;

                if (virRun(qemuimgarg, NULL) < 0) {
                    /* we continue on even in the face of error, since other
                     * disks in this VM may have this snapshot in place
                     */
                    continue;
                }
            }
        }
    }
    else {
        priv = vm->privateData;
8887
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
C
Chris Lalancette 已提交
8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936
        /* we continue on even in the face of error */
        qemuMonitorDeleteSnapshot(priv->mon, snap->def->name);
        qemuDomainObjExitMonitorWithDriver(driver, vm);
    }

    if (snap == vm->current_snapshot) {
        if (snap->def->parent) {
            parentsnap = virDomainSnapshotFindByName(&vm->snapshots,
                                                     snap->def->parent);
            if (!parentsnap) {
                qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                                _("no domain snapshot parent with matching name '%s'"),
                                snap->def->parent);
                goto cleanup;
            }

            /* Now we set the new current_snapshot for the domain */
            vm->current_snapshot = parentsnap;
        }
        else
            vm->current_snapshot = NULL;
    }

    if (virAsprintf(&snapFile, "%s/%s/%s.xml", driver->snapshotDir,
                    vm->def->name, snap->def->name) < 0) {
        virReportOOMError();
        goto cleanup;
    }
    unlink(snapFile);

    virDomainSnapshotObjListRemove(&vm->snapshots, snap);

    ret = 0;

cleanup:
    VIR_FREE(snapFile);
    VIR_FREE(qemuimgarg[0]);

    return ret;
}

struct snap_remove {
    struct qemud_driver *driver;
    virDomainObjPtr vm;
    char *parent;
    int err;
};

static void qemuDomainSnapshotDiscardChildren(void *payload,
8937
                                              const void *name ATTRIBUTE_UNUSED,
C
Chris Lalancette 已提交
8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958
                                              void *data)
{
    virDomainSnapshotObjPtr snap = payload;
    struct snap_remove *curr = data;
    struct snap_remove this;

    if (snap->def->parent && STREQ(snap->def->parent, curr->parent)) {
        this.driver = curr->driver;
        this.vm = curr->vm;
        this.parent = snap->def->name;
        this.err = 0;
        virHashForEach(curr->vm->snapshots.objs,
                       qemuDomainSnapshotDiscardChildren, &this);

        if (this.err)
            curr->err = this.err;
        else
            this.err = qemuDomainSnapshotDiscard(curr->driver, curr->vm, snap);
    }
}

8959 8960 8961 8962 8963 8964 8965 8966 8967
struct snap_reparent {
    struct qemud_driver *driver;
    virDomainSnapshotObjPtr snap;
    virDomainObjPtr vm;
    int err;
};

static void
qemuDomainSnapshotReparentChildren(void *payload,
8968
                                   const void *name ATTRIBUTE_UNUSED,
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
                                   void *data)
{
    virDomainSnapshotObjPtr snap = payload;
    struct snap_reparent *rep = data;

    if (rep->err < 0) {
        return;
    }

    if (snap->def->parent && STREQ(snap->def->parent, rep->snap->def->name)) {
        VIR_FREE(snap->def->parent);

        if (rep->snap->def->parent != NULL) {
            snap->def->parent = strdup(rep->snap->def->parent);

            if (snap->def->parent == NULL) {
                virReportOOMError();
                rep->err = -1;
                return;
            }
        }

        rep->err = qemuDomainSnapshotWriteMetadata(rep->vm, snap,
                                                   rep->driver->snapshotDir);
    }
}

C
Chris Lalancette 已提交
8996 8997 8998 8999 9000 9001 9002 9003 9004
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];
    struct snap_remove rem;
9005
    struct snap_reparent rep;
C
Chris Lalancette 已提交
9006

9007 9008
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

C
Chris Lalancette 已提交
9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025
    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;
    }

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

C
Chris Lalancette 已提交
9029 9030 9031 9032 9033 9034 9035 9036
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN) {
        rem.driver = driver;
        rem.vm = vm;
        rem.parent = snap->def->name;
        rem.err = 0;
        virHashForEach(vm->snapshots.objs, qemuDomainSnapshotDiscardChildren,
                       &rem);
        if (rem.err < 0)
9037
            goto endjob;
9038 9039 9040 9041 9042 9043 9044 9045 9046
    } else {
        rep.driver = driver;
        rep.snap = snap;
        rep.vm = vm;
        rep.err = 0;
        virHashForEach(vm->snapshots.objs, qemuDomainSnapshotReparentChildren,
                       &rep);
        if (rep.err < 0)
            goto endjob;
C
Chris Lalancette 已提交
9047 9048 9049 9050
    }

    ret = qemuDomainSnapshotDiscard(driver, vm, snap);

9051
endjob:
9052
    if (qemuDomainObjEndJob(driver, vm) == 0)
9053 9054
        vm = NULL;

C
Chris Lalancette 已提交
9055 9056 9057 9058 9059 9060
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
9061

9062 9063 9064 9065 9066 9067 9068
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;
9069
    bool hmp;
9070

9071
    virCheckFlags(VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP, -1);
9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090

    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;

9091
    qemuDomainObjTaint(driver, vm, VIR_DOMAIN_TAINT_CUSTOM_MONITOR, -1);
9092

9093 9094
    hmp = !!(flags & VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP);

9095
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
9096
        goto cleanup;
9097
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
9098
    ret = qemuMonitorArbitraryCommand(priv->mon, cmd, result, hmp);
9099
    qemuDomainObjExitMonitorWithDriver(driver, vm);
9100
    if (qemuDomainObjEndJob(driver, vm) == 0) {
9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111
        vm = NULL;
        goto cleanup;
    }

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

9112

9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 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 9166 9167
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;
    char *pidfile;

    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;

9168
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182
        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:
9183
    if (qemuDomainObjEndJob(driver, vm) == 0) {
9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198
        vm = NULL;
        goto cleanup;
    }

cleanup:
    virDomainDefFree(def);
    virDomainChrSourceDefFree(monConfig);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    VIR_FREE(pidfile);
    return dom;
}


9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254
static int
qemuDomainOpenConsole(virDomainPtr dom,
                      const char *devname,
                      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;
    }

    if (devname) {
        if (vm->def->console &&
            STREQ(devname, vm->def->console->info.alias))
            chr = vm->def->console;
        for (i = 0 ; !chr && i < vm->def->nserials ; i++) {
            if (STREQ(devname, vm->def->serials[i]->info.alias))
                chr = vm->def->serials[i];
        }
        for (i = 0 ; !chr && i < vm->def->nparallels ; i++) {
            if (STREQ(devname, vm->def->parallels[i]->info.alias))
                chr = vm->def->parallels[i];
        }
    } else {
        if (vm->def->console)
            chr = vm->def->console;
        else if (vm->def->nserials)
            chr = vm->def->serials[0];
    }

    if (!chr) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find character device %s"),
                        NULLSTR(devname));
        goto cleanup;
    }

9255
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
9256 9257 9258 9259 9260 9261
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"),
                        NULLSTR(devname));
        goto cleanup;
    }

9262
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
E
Eric Blake 已提交
9263
                            0, 0, O_RDWR) < 0)
9264 9265 9266 9267 9268 9269 9270 9271 9272 9273
        goto cleanup;

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

9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335
static const char *
qemuDiskPathToAlias(virDomainObjPtr vm, const char *path) {
    int i;
    char *ret = NULL;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        virDomainDiskDefPtr disk = vm->def->disks[i];

        if (disk->type != VIR_DOMAIN_DISK_TYPE_BLOCK &&
            disk->type != VIR_DOMAIN_DISK_TYPE_FILE)
            continue;

        if (disk->src != NULL && STREQ(disk->src, path)) {
            if (virAsprintf(&ret, "drive-%s", disk->info.alias) < 0) {
                virReportOOMError();
                return NULL;
            }
            break;
        }
    }

    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;
9336
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382
    priv = vm->privateData;
    ret = qemuMonitorBlockJob(priv->mon, device, bandwidth, info, mode);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
    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)
{
    virCheckFlags(0, -1);
    return qemuDomainBlockJobImpl(dom, path, bandwidth, NULL, BLOCK_JOB_PULL);
}
9383

9384
static virDriver qemuDriver = {
9385 9386
    .no = VIR_DRV_QEMU,
    .name = "QEMU",
9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404
    .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 */
9405 9406
    .domainShutdown = qemuDomainShutdown, /* 0.2.0 */
    .domainReboot = qemuDomainReboot, /* 0.9.3 */
9407 9408
    .domainDestroy = qemuDomainDestroy, /* 0.2.0 */
    .domainDestroyFlags = qemuDomainDestroyFlags, /* 0.9.4 */
9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419
    .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 */
9420
    .domainGetControlInfo = qemuDomainGetControlInfo, /* 0.9.3 */
9421 9422
    .domainSave = qemuDomainSave, /* 0.2.0 */
    .domainSaveFlags = qemuDomainSaveFlags, /* 0.9.4 */
9423
    .domainRestore = qemuDomainRestore, /* 0.2.0 */
9424
    .domainRestoreFlags = qemuDomainRestoreFlags, /* 0.9.4 */
9425 9426
    .domainSaveImageGetXMLDesc = qemuDomainSaveImageGetXMLDesc, /* 0.9.4 */
    .domainSaveImageDefineXML = qemuDomainSaveImageDefineXML, /* 0.9.4 */
9427 9428
    .domainCoreDump = qemudDomainCoreDump, /* 0.7.0 */
    .domainScreenshot = qemuDomainScreenshot, /* 0.9.2 */
9429 9430
    .domainSetVcpus = qemuDomainSetVcpus, /* 0.4.4 */
    .domainSetVcpusFlags = qemuDomainSetVcpusFlags, /* 0.8.5 */
9431 9432
    .domainGetVcpusFlags = qemudDomainGetVcpusFlags, /* 0.8.5 */
    .domainPinVcpu = qemudDomainPinVcpu, /* 0.4.4 */
9433
    .domainPinVcpuFlags = qemudDomainPinVcpuFlags, /* 0.9.3 */
E
Eric Blake 已提交
9434
    .domainGetVcpuPinInfo = qemudDomainGetVcpuPinInfo, /* 0.9.3 */
9435 9436 9437 9438 9439 9440 9441 9442 9443
    .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 */
9444 9445
    .domainCreate = qemuDomainStart, /* 0.2.0 */
    .domainCreateWithFlags = qemuDomainStartWithFlags, /* 0.8.2 */
9446 9447
    .domainDefineXML = qemudDomainDefine, /* 0.2.0 */
    .domainUndefine = qemudDomainUndefine, /* 0.2.0 */
9448
    .domainUndefineFlags = qemuDomainUndefineFlags, /* 0.9.4 */
9449 9450 9451 9452 9453 9454 9455 9456 9457
    .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 */
9458
    .domainGetSchedulerParametersFlags = qemuGetSchedulerParametersFlags, /* 0.9.2 */
9459
    .domainSetSchedulerParameters = qemuSetSchedulerParameters, /* 0.7.0 */
9460
    .domainSetSchedulerParametersFlags = qemuSetSchedulerParametersFlags, /* 0.9.2 */
9461 9462 9463 9464 9465 9466 9467
    .domainMigratePerform = qemudDomainMigratePerform, /* 0.5.0 */
    .domainBlockStats = qemudDomainBlockStats, /* 0.4.1 */
    .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 */
9468
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
9469
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505
    .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 */
    .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 */
    .domainSnapshotLookupByName = qemuDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = qemuDomainHasCurrentSnapshot, /* 0.8.0 */
    .domainSnapshotCurrent = qemuDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = qemuDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = qemuDomainSnapshotDelete, /* 0.8.0 */
    .qemuDomainMonitorCommand = qemuDomainMonitorCommand, /* 0.8.3 */
9506
    .qemuDomainAttach = qemuDomainAttach, /* 0.9.4 */
9507 9508
    .domainOpenConsole = qemuDomainOpenConsole, /* 0.8.6 */
    .domainInjectNMI = qemuDomainInjectNMI, /* 0.9.2 */
9509 9510 9511 9512 9513 9514
    .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 */
9515
    .domainSendKey = qemuDomainSendKey, /* 0.9.4 */
9516 9517 9518 9519
    .domainBlockJobAbort = qemuDomainBlockJobAbort, /* 0.9.4 */
    .domainGetBlockJobInfo = qemuDomainGetBlockJobInfo, /* 0.9.4 */
    .domainBlockJobSetSpeed = qemuDomainBlockJobSetSpeed, /* 0.9.4 */
    .domainBlockPull = qemuDomainBlockPull, /* 0.9.4 */
9520 9521 9522
};


9523
static virStateDriver qemuStateDriver = {
9524
    .name = "QEMU",
9525 9526 9527 9528
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
9529
};
9530

9531
static void
9532
qemuVMDriverLock(void) {
9533 9534 9535 9536 9537
    qemuDriverLock(qemu_driver);
};


static void
9538
qemuVMDriverUnlock(void) {
9539 9540 9541 9542
    qemuDriverUnlock(qemu_driver);
};


9543 9544 9545 9546 9547 9548 9549 9550 9551
static int
qemuVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                    virHashIterator iter, void *data)
{
    virHashForEach(qemu_driver->domains.objs, iter, data);

    return 0;
}

S
Stefan Berger 已提交
9552 9553
static virNWFilterCallbackDriver qemuCallbackDriver = {
    .name = "QEMU",
9554 9555 9556
    .vmFilterRebuild = qemuVMFilterRebuild,
    .vmDriverLock = qemuVMDriverLock,
    .vmDriverUnlock = qemuVMDriverUnlock,
S
Stefan Berger 已提交
9557 9558
};

9559
int qemuRegister(void) {
9560 9561
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
S
Stefan Berger 已提交
9562
    virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);
9563 9564
    return 0;
}