qemu_driver.c 218.1 KB
Newer Older
D
Daniel P. Berrange 已提交
1 2 3
/*
 * driver.c: core driver methods for managing qemu guests
 *
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>
D
Daniel P. Berrange 已提交
46

47

48 49
#include "qemu_driver.h"
#include "qemu_conf.h"
50
#include "qemu_capabilities.h"
51
#include "qemu_command.h"
52
#include "qemu_cgroup.h"
53
#include "qemu_hostdev.h"
54
#include "qemu_hotplug.h"
55
#include "qemu_monitor.h"
56
#include "qemu_bridge_filter.h"
57
#include "qemu_audit.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 "event.h"
65
#include "buf.h"
66
#include "util.h"
67
#include "nodeinfo.h"
68
#include "stats_linux.h"
69
#include "capabilities.h"
70
#include "memory.h"
71
#include "uuid.h"
72
#include "domain_conf.h"
73 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"
85
#include "files.h"
86
#include "fdstream.h"
87
#include "configmake.h"
H
Hu Tao 已提交
88
#include "threadpool.h"
89

90 91
#define VIR_FROM_THIS VIR_FROM_QEMU

92 93
#define QEMU_NB_MEM_PARAM  3

94 95 96
#if HAVE_LINUX_KVM_H
# include <linux/kvm.h>
#endif
97

98 99
/* device for kvm ioctls */
#define KVM_DEVICE "/dev/kvm"
100

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

112
#define QEMU_NB_BLKIO_PARAM  1
113 114

#define timeval_to_ms(tv)       (((tv).tv_sec * 1000ull) + ((tv).tv_usec / 1000))
H
Hu Tao 已提交
115 116 117

static void processWatchdogEvent(void *data, void *opaque);

118 119
static int qemudShutdown(void);

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

125
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
126

127
struct qemud_driver *qemu_driver = NULL;
128 129


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

135
static void
136
qemuAutostartDomain(void *payload, const void *name ATTRIBUTE_UNUSED, void *opaque)
137 138 139
{
    virDomainObjPtr vm = payload;
    struct qemuAutostartData *data = opaque;
140
    virErrorPtr err;
141 142

    virDomainObjLock(vm);
143 144 145 146 147 148 149 150 151
    virResetLastError();
    if (qemuDomainObjBeginJobWithDriver(data->driver, vm) < 0) {
        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) &&
152
            qemudDomainObjStart(data->conn, data->driver, vm, false) < 0) {
153
            err = virGetLastError();
154
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
155
                      vm->def->name,
156
                      err ? err->message : _("unknown error"));
157
        }
158 159 160

        if (qemuDomainObjEndJob(vm) == 0)
            vm = NULL;
161
    }
162 163 164

    if (vm)
        virDomainObjUnlock(vm);
165 166
}

167

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

182
    qemuDriverLock(driver);
183
    virHashForEach(driver->domains.objs, qemuAutostartDomain, &data);
184
    qemuDriverUnlock(driver);
185

186 187
    if (conn)
        virConnectClose(conn);
188 189
}

190
static int
191
qemuSecurityInit(struct qemud_driver *driver)
192
{
193 194 195 196
    virSecurityManagerPtr mgr = virSecurityManagerNew(driver->securityDriverName,
                                                      driver->allowDiskFormatProbing);
    if (!mgr)
        goto error;
D
Daniel Veillard 已提交
197

198 199 200 201 202 203 204
    if (driver->privileged) {
        virSecurityManagerPtr dac = virSecurityManagerNewDAC(driver->user,
                                                             driver->group,
                                                             driver->allowDiskFormatProbing,
                                                             driver->dynamicOwnership);
        if (!dac)
            goto error;
205

206
        if (!(driver->securityManager = virSecurityManagerNewStack(mgr,
E
Eric Blake 已提交
207 208 209
                                                                   dac))) {

            virSecurityManagerFree(dac);
210
            goto error;
E
Eric Blake 已提交
211
        }
212 213 214
    } else {
        driver->securityManager = mgr;
    }
D
Daniel Veillard 已提交
215

216
    return 0;
217

218 219 220 221 222
error:
    VIR_ERROR0(_("Failed to initialize security drivers"));
    virSecurityManagerFree(mgr);
    return -1;
}
223

224

225 226 227 228 229
static virCapsPtr
qemuCreateCapabilities(virCapsPtr oldcaps,
                       struct qemud_driver *driver)
{
    virCapsPtr caps;
230

231 232 233 234
    /* Basic host arch / guest machine capabilities */
    if (!(caps = qemuCapsInit(oldcaps))) {
        virReportOOMError();
        return NULL;
235 236
    }

237 238 239 240 241 242
    if (driver->allowDiskFormatProbing) {
        caps->defaultDiskDriverName = NULL;
        caps->defaultDiskDriverType = NULL;
    } else {
        caps->defaultDiskDriverName = "qemu";
        caps->defaultDiskDriverType = "raw";
243 244
    }

245 246
    qemuDomainSetPrivateDataHooks(caps);
    qemuDomainSetNamespaceHooks(caps);
247

248 249 250 251
    if (virGetHostUUID(caps->host.host_uuid)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot get the host uuid"));
        goto err_exit;
252
    }
253

254 255
    /* Security driver data */
    const char *doi, *model;
256

257 258 259 260 261 262 263
    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;
264
    }
265

266 267
    VIR_DEBUG("Initialized caps for security driver \"%s\" with "
              "DOI \"%s\"", model, doi);
268

269
    return caps;
270

271 272 273 274
no_memory:
    virReportOOMError();
err_exit:
    virCapabilitiesFree(caps);
275 276 277
    return NULL;
}

278
static void qemuDomainSnapshotLoad(void *payload,
279
                                   const void *name ATTRIBUTE_UNUSED,
280
                                   void *data)
281
{
282 283 284 285 286 287 288 289 290 291
    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];
292

293 294 295 296
    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);
297
        goto cleanup;
298 299
    }

300 301
    VIR_INFO("Scanning for snapshots for domain %s in %s", vm->def->name,
             snapDir);
302

303 304 305 306 307
    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)));
308
        goto cleanup;
309 310
    }

311 312 313
    while ((entry = readdir(dir))) {
        if (entry->d_name[0] == '.')
            continue;
314

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

319 320 321 322
        if (virAsprintf(&fullpath, "%s/%s", snapDir, entry->d_name) < 0) {
            VIR_ERROR0(_("Failed to allocate memory for path"));
            continue;
        }
323

324 325 326 327 328 329 330 331
        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;
        }
332

333 334 335 336 337 338 339 340
        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;
        }
341

342
        virDomainSnapshotAssignDef(&vm->snapshots, def);
343

344 345
        VIR_FREE(fullpath);
        VIR_FREE(xmlStr);
346 347
    }

348 349 350 351 352 353 354 355
    /* 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.
     */
356

357
    virResetLastError();
358

359 360 361 362
cleanup:
    if (dir)
        closedir(dir);
    VIR_FREE(snapDir);
363 364 365
    virDomainObjUnlock(vm);
}

366 367 368 369 370
/**
 * qemudStartup:
 *
 * Initialization function for the QEmu daemon
 */
371
static int
372 373 374 375 376
qemudStartup(int privileged) {
    char *base = NULL;
    char *driverConf = NULL;
    int rc;
    virConnectPtr conn = NULL;
377

378 379
    if (VIR_ALLOC(qemu_driver) < 0)
        return -1;
380

381 382 383 384
    if (virMutexInit(&qemu_driver->lock) < 0) {
        VIR_ERROR0(_("cannot initialize mutex"));
        VIR_FREE(qemu_driver);
        return -1;
385
    }
386 387
    qemuDriverLock(qemu_driver);
    qemu_driver->privileged = privileged;
388

389 390
    /* Don't have a dom0 so start from 1 */
    qemu_driver->nextvmid = 1;
391

392 393
    if (virDomainObjListInit(&qemu_driver->domains) < 0)
        goto out_of_memory;
394

395 396 397 398 399
    /* Init callback list */
    if (VIR_ALLOC(qemu_driver->domainEventCallbacks) < 0)
        goto out_of_memory;
    if (!(qemu_driver->domainEventQueue = virDomainEventQueueNew()))
        goto out_of_memory;
400

401 402 403
    if ((qemu_driver->domainEventTimer =
         virEventAddTimeout(-1, qemuDomainEventFlush, qemu_driver, NULL)) < 0)
        goto error;
404

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

410 411 412
    /* read the host sysinfo */
    if (privileged)
        qemu_driver->hostsysinfo = virSysinfoRead();
413

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

419 420
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
            goto out_of_memory;
421

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

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

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

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

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

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

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

511 512 513 514 515 516 517
    /* 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;
518

519
    VIR_FREE(base);
520

521 522 523 524 525
    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)));
526 527
    }

528 529 530 531
    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
        goto error;
    }
    VIR_FREE(driverConf);
532

533 534
    if (qemuSecurityInit(qemu_driver) < 0)
        goto error;
535

536 537 538
    if ((qemu_driver->caps = qemuCreateCapabilities(NULL,
                                                    qemu_driver)) == NULL)
        goto error;
539

540
    if ((qemu_driver->activePciHostdevs = pciDeviceListNew()) == NULL)
541
        goto error;
542

543 544 545 546 547 548
    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;
549
        }
550
        if (chown(qemu_driver->cacheDir, qemu_driver->user, qemu_driver->group) < 0) {
551
            virReportSystemError(errno,
552 553 554
                                 _("unable to set ownership of '%s' to %d:%d"),
                                 qemu_driver->cacheDir, qemu_driver->user, qemu_driver->group);
            goto error;
555
        }
556 557 558 559 560 561 562 563 564 565 566
        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;
567
        }
568
    }
569

570 571 572 573 574 575
    /* 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
576
     */
577 578 579 580 581
    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;
582

583 584 585 586 587
        if ((rc = virFileMakePath(mempath)) != 0) {
            virReportSystemError(rc,
                                 _("unable to create hugepage path %s"), mempath);
            VIR_FREE(mempath);
            goto error;
588
        }
589 590 591 592 593 594 595
        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 已提交
596
        }
E
Eric Blake 已提交
597

598
        qemu_driver->hugepage_path = mempath;
599
    }
600

601 602 603 604 605 606 607
    /* Get all the running persistent or transient configs first */
    if (virDomainLoadAllConfigs(qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->stateDir,
                                NULL,
                                1, NULL, NULL) < 0)
        goto error;
608

609 610 611
    conn = virConnectOpen(qemu_driver->privileged ?
                          "qemu:///system" :
                          "qemu:///session");
612

613
    qemuProcessReconnectAll(conn, qemu_driver);
614

615 616 617 618 619 620 621
    /* Then inactive persistent configs */
    if (virDomainLoadAllConfigs(qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->configDir,
                                qemu_driver->autostartDir,
                                0, NULL, NULL) < 0)
        goto error;
622

623

624 625
    virHashForEach(qemu_driver->domains.objs, qemuDomainSnapshotLoad,
                   qemu_driver->snapshotDir);
626

627
    qemuDriverUnlock(qemu_driver);
628

629
    qemuAutostartDomains(qemu_driver);
630

631 632 633
    qemu_driver->workerPool = virThreadPoolNew(0, 1, processWatchdogEvent, qemu_driver);
    if (!qemu_driver->workerPool)
        goto error;
634

635 636
    if (conn)
        virConnectClose(conn);
637

638
    return 0;
639

640 641 642 643 644 645 646 647 648 649
out_of_memory:
    virReportOOMError();
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
    if (conn)
        virConnectClose(conn);
    VIR_FREE(base);
    VIR_FREE(driverConf);
    qemudShutdown();
650
    return -1;
651 652
}

653 654 655
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;
656

657 658 659 660 661 662 663
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
E
Eric Blake 已提交
664
    }
665
}
E
Eric Blake 已提交
666

667 668 669 670 671 672 673 674 675 676
/**
 * 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;
677

678 679 680 681 682 683 684
    qemuDriverLock(qemu_driver);
    virDomainLoadAllConfigs(qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
                            qemu_driver->autostartDir,
                            0, qemudNotifyLoadDomain, qemu_driver);
    qemuDriverUnlock(qemu_driver);
685

686
    qemuAutostartDomains(qemu_driver);
687

688 689
    return 0;
}
S
Stefan Berger 已提交
690

691 692 693 694 695 696 697 698 699 700 701
/**
 * 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;
702

703 704
    if (!qemu_driver)
        return 0;
705

706 707 708 709 710 711
    /* 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;
}
712

713 714 715 716 717 718 719 720
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
    int i;
721

722 723
    if (!qemu_driver)
        return -1;
724

725 726 727
    qemuDriverLock(qemu_driver);
    pciDeviceListFree(qemu_driver->activePciHostdevs);
    virCapabilitiesFree(qemu_driver->caps);
728

729 730
    virDomainObjListDeinit(&qemu_driver->domains);
    virBitmapFree(qemu_driver->reservedVNCPorts);
731

732
    virSysinfoDefFree(qemu_driver->hostsysinfo);
733

734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
    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);
754

755
    virSecurityManagerFree(qemu_driver->securityManager);
756

757
    ebtablesContextFree(qemu_driver->ebtables);
758

759 760 761 762
    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 已提交
763 764
    }

765 766 767
    /* Free domain callback list */
    virDomainEventCallbackListFree(qemu_driver->domainEventCallbacks);
    virDomainEventQueueFree(qemu_driver->domainEventQueue);
768

769 770
    if (qemu_driver->domainEventTimer != -1)
        virEventRemoveTimeout(qemu_driver->domainEventTimer);
D
Daniel P. Berrange 已提交
771

772 773
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);
774

775
    virCgroupFree(&qemu_driver->cgroup);
776

777 778 779 780
    qemuDriverUnlock(qemu_driver);
    virMutexDestroy(&qemu_driver->lock);
    virThreadPoolFree(qemu_driver->workerPool);
    VIR_FREE(qemu_driver);
781

782
    return 0;
783 784
}

785 786 787 788 789 790 791

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


792
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
793
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
794
                                  int flags ATTRIBUTE_UNUSED) {
795
    if (conn->uri == NULL) {
796 797 798
        if (qemu_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

799
        conn->uri = xmlParseURI(qemu_driver->privileged ?
800 801
                                "qemu:///system" :
                                "qemu:///session");
802
        if (!conn->uri) {
803
            virReportOOMError();
804 805
            return VIR_DRV_OPEN_ERROR;
        }
806 807 808 809 810 811 812 813 814 815
    } 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;

816
        if (qemu_driver == NULL) {
817 818
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("qemu state driver is not active"));
819 820 821
            return VIR_DRV_OPEN_ERROR;
        }

822
        if (conn->uri->path == NULL) {
823 824 825 826 827
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("no QEMU URI path given, try %s"),
                            qemu_driver->privileged
                            ? "qemu:///system"
                            : "qemu:///session");
828 829 830
                return VIR_DRV_OPEN_ERROR;
        }

831
        if (qemu_driver->privileged) {
832 833
            if (STRNEQ (conn->uri->path, "/system") &&
                STRNEQ (conn->uri->path, "/session")) {
834 835 836
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("unexpected QEMU URI path '%s', try qemu:///system"),
                                conn->uri->path);
837 838 839 840
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
841 842 843
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("unexpected QEMU URI path '%s', try qemu:///session"),
                                conn->uri->path);
844 845 846
                return VIR_DRV_OPEN_ERROR;
            }
        }
847 848 849 850 851 852 853
    }
    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int qemudClose(virConnectPtr conn) {
854
    struct qemud_driver *driver = conn->privateData;
855 856

    /* Get rid of callbacks registered for this conn */
857
    qemuDriverLock(driver);
858
    virDomainEventCallbackListRemoveConn(conn, driver->domainEventCallbacks);
859
    qemuDriverUnlock(driver);
860 861 862 863 864 865

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
866 867 868 869 870
/* Which features are supported by this driver? */
static int
qemudSupportsFeature (virConnectPtr conn ATTRIBUTE_UNUSED, int feature)
{
    switch (feature) {
871 872 873 874 875
    case VIR_DRV_FEATURE_MIGRATION_V2:
    case VIR_DRV_FEATURE_MIGRATION_P2P:
        return 1;
    default:
        return 0;
D
Daniel Veillard 已提交
876 877 878
    }
}

879
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
880
    return "QEMU";
881 882
}

883

884 885 886 887 888 889 890 891 892 893 894 895 896
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;
}


897 898 899 900
static int kvmGetMaxVCPUs(void) {
    int maxvcpus = 1;

    int r, fd;
901

902 903
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
904
        virReportSystemError(errno, _("Unable to open %s"), KVM_DEVICE);
905
        return -1;
906 907 908 909 910 911
    }

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

912
    VIR_FORCE_CLOSE(fd);
913 914 915 916
    return maxvcpus;
}


E
Eric Blake 已提交
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
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, "");
}

933
static int qemudGetMaxVCPUs(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
934 935 936
    if (!type)
        return 16;

937
    if (STRCASEEQ(type, "qemu"))
938 939
        return 16;

940
    if (STRCASEEQ(type, "kvm"))
941
        return kvmGetMaxVCPUs();
942

943
    if (STRCASEEQ(type, "kqemu"))
944
        return 1;
945

946 947
    qemuReportError(VIR_ERR_INVALID_ARG,
                    _("unknown type '%s'"), type);
948 949 950
    return -1;
}

951

952
static char *qemudGetCapabilities(virConnectPtr conn) {
953
    struct qemud_driver *driver = conn->privateData;
954
    virCapsPtr caps = NULL;
955
    char *xml = NULL;
956

957
    qemuDriverLock(driver);
958

959
    if ((caps = qemuCreateCapabilities(qemu_driver->caps,
960
                                       qemu_driver)) == NULL) {
961 962 963
        virCapabilitiesFree(caps);
        goto cleanup;
    }
964

965
    virCapabilitiesFree(qemu_driver->caps);
966 967 968
    qemu_driver->caps = caps;

    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
969
        virReportOOMError();
970 971

cleanup:
972
    qemuDriverUnlock(driver);
973

974
    return xml;
975 976 977
}


978 979 980 981 982
static int
qemudGetProcessInfo(unsigned long long *cpuTime, int *lastCpu, int pid,
                    int tid)
{
    char *proc;
D
Daniel P. Berrange 已提交
983
    FILE *pidinfo;
984
    unsigned long long usertime, systime;
985 986
    int cpu;
    int ret;
D
Daniel P. Berrange 已提交
987

988
    if (tid)
989
        ret = virAsprintf(&proc, "/proc/%d/task/%d/stat", pid, tid);
990
    else
991 992
        ret = virAsprintf(&proc, "/proc/%d/stat", pid);
    if (ret < 0)
D
Daniel P. Berrange 已提交
993 994 995 996
        return -1;

    if (!(pidinfo = fopen(proc, "r"))) {
        /* VM probably shut down, so fake 0 */
997 998 999 1000
        if (cpuTime)
            *cpuTime = 0;
        if (lastCpu)
            *lastCpu = 0;
1001
        VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1002 1003
        return 0;
    }
1004
    VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1005

1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
    /* 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) {
1016
        VIR_FORCE_FCLOSE(pidinfo);
1017 1018
        VIR_WARN0("cannot parse process status data");
        errno = -EINVAL;
D
Daniel P. Berrange 已提交
1019 1020 1021 1022 1023 1024 1025 1026
        return -1;
    }

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
1027 1028 1029 1030 1031
    if (cpuTime)
        *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
    if (lastCpu)
        *lastCpu = cpu;

D
Daniel P. Berrange 已提交
1032

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

1036
    VIR_FORCE_FCLOSE(pidinfo);
D
Daniel P. Berrange 已提交
1037 1038 1039 1040 1041

    return 0;
}


1042
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1043
                                          int id) {
1044 1045 1046 1047
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1048
    qemuDriverLock(driver);
1049
    vm  = virDomainFindByID(&driver->domains, id);
1050
    qemuDriverUnlock(driver);
1051 1052

    if (!vm) {
1053 1054
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching id %d"), id);
1055
        goto cleanup;
1056 1057
    }

1058
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1059
    if (dom) dom->id = vm->def->id;
1060 1061

cleanup:
1062 1063
    if (vm)
        virDomainObjUnlock(vm);
1064 1065
    return dom;
}
1066

1067
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1068
                                            const unsigned char *uuid) {
1069 1070 1071
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1072

1073
    qemuDriverLock(driver);
1074
    vm = virDomainFindByUUID(&driver->domains, uuid);
1075 1076
    qemuDriverUnlock(driver);

1077
    if (!vm) {
1078 1079
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
1080 1081
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1082
        goto cleanup;
1083 1084
    }

1085
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1086
    if (dom) dom->id = vm->def->id;
1087 1088

cleanup:
1089 1090
    if (vm)
        virDomainObjUnlock(vm);
1091 1092
    return dom;
}
1093

1094
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1095
                                            const char *name) {
1096 1097 1098
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1099

1100
    qemuDriverLock(driver);
1101
    vm = virDomainFindByName(&driver->domains, name);
1102 1103
    qemuDriverUnlock(driver);

1104
    if (!vm) {
1105 1106
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), name);
1107
        goto cleanup;
1108 1109
    }

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

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

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129

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 已提交
1130 1131 1132 1133
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
        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 已提交
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
        goto cleanup;
    }
    ret = obj->persistent;

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

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
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 已提交
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
        goto cleanup;
    }
    ret = obj->updated;

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

1192
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1193 1194 1195
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

1196
    qemuDriverLock(driver);
1197
    if (qemuCapsExtractVersion(driver->caps, &driver->qemuVersion) < 0)
1198
        goto cleanup;
1199

1200
    *version = driver->qemuVersion;
1201 1202 1203
    ret = 0;

cleanup:
1204
    qemuDriverUnlock(driver);
1205
    return ret;
D
Daniel P. Berrange 已提交
1206 1207
}

1208
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1209
    struct qemud_driver *driver = conn->privateData;
1210
    int n;
1211

1212
    qemuDriverLock(driver);
1213
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1214
    qemuDriverUnlock(driver);
1215

1216
    return n;
D
Daniel P. Berrange 已提交
1217
}
1218

1219
static int qemudNumDomains(virConnectPtr conn) {
1220
    struct qemud_driver *driver = conn->privateData;
1221
    int n;
1222

1223
    qemuDriverLock(driver);
1224
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1225
    qemuDriverUnlock(driver);
1226

1227
    return n;
D
Daniel P. Berrange 已提交
1228
}
1229

1230
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
1231
                                      unsigned int flags) {
1232
    struct qemud_driver *driver = conn->privateData;
1233
    virDomainDefPtr def;
1234
    virDomainObjPtr vm = NULL;
1235
    virDomainPtr dom = NULL;
1236
    virDomainEventPtr event = NULL;
D
Daniel P. Berrange 已提交
1237

1238
    virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);
1239

1240
    qemuDriverLock(driver);
1241
    if (!(def = virDomainDefParseString(driver->caps, xml,
1242
                                        VIR_DOMAIN_XML_INACTIVE)))
1243
        goto cleanup;
1244

1245
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
1246 1247
        goto cleanup;

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

1251 1252 1253
    if (qemudCanonicalizeMachine(driver, def) < 0)
        goto cleanup;

1254
    if (qemuDomainAssignPCIAddresses(def) < 0)
1255 1256
        goto cleanup;

1257
    if (!(vm = virDomainAssignDef(driver->caps,
1258
                                  &driver->domains,
1259
                                  def, false)))
1260 1261 1262
        goto cleanup;

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

1264 1265 1266
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup; /* XXXX free the 'vm' we created ? */

1267 1268 1269
    if (qemuProcessStart(conn, driver, vm, NULL,
                         (flags & VIR_DOMAIN_START_PAUSED) != 0,
                         -1, NULL, VIR_VM_OP_CREATE) < 0) {
1270
        qemuAuditDomainStart(vm, "booted", false);
1271 1272 1273
        if (qemuDomainObjEndJob(vm) > 0)
            virDomainRemoveInactive(&driver->domains,
                                    vm);
1274
        vm = NULL;
1275
        goto cleanup;
D
Daniel P. Berrange 已提交
1276
    }
1277 1278 1279 1280

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
1281
    qemuAuditDomainStart(vm, "booted", true);
D
Daniel P. Berrange 已提交
1282

1283
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1284
    if (dom) dom->id = vm->def->id;
1285

1286 1287 1288
    if (vm &&
        qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1289

1290 1291
cleanup:
    virDomainDefFree(def);
1292 1293
    if (vm)
        virDomainObjUnlock(vm);
1294 1295
    if (event)
        qemuDomainEventQueue(driver, event);
1296
    qemuDriverUnlock(driver);
1297
    return dom;
D
Daniel P. Berrange 已提交
1298 1299 1300
}


1301
static int qemudDomainSuspend(virDomainPtr dom) {
1302 1303 1304
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1305
    virDomainEventPtr event = NULL;
1306
    qemuDomainObjPrivatePtr priv;
1307

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

D
Daniel P. Berrange 已提交
1311
    if (!vm) {
1312 1313
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1314 1315
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1316
        goto cleanup;
D
Daniel P. Berrange 已提交
1317
    }
D
Daniel P. Berrange 已提交
1318
    if (!virDomainObjIsActive(vm)) {
1319 1320
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1321
        goto cleanup;
D
Daniel P. Berrange 已提交
1322
    }
1323 1324 1325

    priv = vm->privateData;

1326
    if (priv->jobActive == QEMU_JOB_MIGRATION_OUT) {
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
        if (vm->state != VIR_DOMAIN_PAUSED) {
            VIR_DEBUG("Requesting domain pause on %s",
                      vm->def->name);
            priv->jobSignals |= QEMU_JOB_SIGNAL_SUSPEND;
        }
        ret = 0;
        goto cleanup;
    } else {
        if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
            goto cleanup;

        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
1341
            goto endjob;
1342
        }
1343
        if (vm->state != VIR_DOMAIN_PAUSED) {
1344
            if (qemuProcessStopCPUs(driver, vm) < 0) {
1345
                goto endjob;
1346
            }
1347 1348 1349 1350 1351 1352 1353
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_SUSPENDED,
                                             VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
        }
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
            goto endjob;
        ret = 0;
D
Daniel P. Berrange 已提交
1354
    }
1355

1356
endjob:
1357 1358
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1359

1360
cleanup:
1361 1362
    if (vm)
        virDomainObjUnlock(vm);
1363

1364
    if (event)
1365
        qemuDomainEventQueue(driver, event);
1366
    qemuDriverUnlock(driver);
1367
    return ret;
D
Daniel P. Berrange 已提交
1368 1369 1370
}


1371
static int qemudDomainResume(virDomainPtr dom) {
1372 1373 1374
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1375
    virDomainEventPtr event = NULL;
1376

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

D
Daniel P. Berrange 已提交
1380
    if (!vm) {
1381 1382
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1383 1384
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1385
        goto cleanup;
D
Daniel P. Berrange 已提交
1386
    }
1387 1388 1389 1390

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

D
Daniel P. Berrange 已提交
1391
    if (!virDomainObjIsActive(vm)) {
1392 1393
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1394
        goto endjob;
D
Daniel P. Berrange 已提交
1395
    }
1396
    if (vm->state == VIR_DOMAIN_PAUSED) {
1397
        if (qemuProcessStartCPUs(driver, vm, dom->conn) < 0) {
1398
            if (virGetLastError() == NULL)
1399 1400
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("resume operation failed"));
1401
            goto endjob;
1402
        }
1403 1404 1405
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
D
Daniel P. Berrange 已提交
1406
    }
1407
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
1408
        goto endjob;
1409 1410
    ret = 0;

1411
endjob:
1412 1413
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1414

1415
cleanup:
1416 1417
    if (vm)
        virDomainObjUnlock(vm);
1418
    if (event)
1419
        qemuDomainEventQueue(driver, event);
1420
    qemuDriverUnlock(driver);
1421
    return ret;
D
Daniel P. Berrange 已提交
1422 1423 1424
}


1425
static int qemudDomainShutdown(virDomainPtr dom) {
1426 1427 1428
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1429

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

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

1442 1443 1444
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
1445
    if (!virDomainObjIsActive(vm)) {
1446 1447
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1448
        goto endjob;
1449 1450
    }

1451
    qemuDomainObjPrivatePtr priv = vm->privateData;
1452 1453 1454
    qemuDomainObjEnterMonitor(vm);
    ret = qemuMonitorSystemPowerdown(priv->mon);
    qemuDomainObjExitMonitor(vm);
1455

1456
endjob:
1457 1458
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1459

1460
cleanup:
1461 1462
    if (vm)
        virDomainObjUnlock(vm);
1463
    return ret;
1464 1465 1466
}


1467
static int qemudDomainDestroy(virDomainPtr dom) {
1468 1469 1470
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1471
    virDomainEventPtr event = NULL;
1472

1473
    qemuDriverLock(driver);
1474
    vm  = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel P. Berrange 已提交
1475
    if (!vm) {
1476 1477
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1478 1479
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1480
        goto cleanup;
D
Daniel P. Berrange 已提交
1481
    }
1482 1483 1484 1485

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

D
Daniel P. Berrange 已提交
1486
    if (!virDomainObjIsActive(vm)) {
1487 1488
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1489
        goto endjob;
1490
    }
1491

1492
    qemuProcessStop(driver, vm, 0);
1493 1494 1495
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1496
    qemuAuditDomainStop(vm, "destroyed");
1497

1498
    if (!vm->persistent) {
1499 1500 1501
        if (qemuDomainObjEndJob(vm) > 0)
            virDomainRemoveInactive(&driver->domains,
                                    vm);
1502 1503
        vm = NULL;
    }
1504 1505
    ret = 0;

1506
endjob:
1507 1508 1509
    if (vm &&
        qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1510

1511
cleanup:
1512 1513
    if (vm)
        virDomainObjUnlock(vm);
1514 1515
    if (event)
        qemuDomainEventQueue(driver, event);
1516
    qemuDriverUnlock(driver);
1517
    return ret;
D
Daniel P. Berrange 已提交
1518 1519 1520
}


1521
static char *qemudDomainGetOSType(virDomainPtr dom) {
1522 1523 1524
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1525

1526
    qemuDriverLock(driver);
1527
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1528
    qemuDriverUnlock(driver);
1529
    if (!vm) {
1530 1531
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1532 1533
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1534
        goto cleanup;
1535 1536
    }

1537
    if (!(type = strdup(vm->def->os.type)))
1538
        virReportOOMError();
1539 1540

cleanup:
1541 1542
    if (vm)
        virDomainObjUnlock(vm);
1543 1544 1545
    return type;
}

1546 1547
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
1548 1549 1550
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
1551

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

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

1564
    ret = vm->def->mem.max_balloon;
1565 1566

cleanup:
1567 1568
    if (vm)
        virDomainObjUnlock(vm);
1569
    return ret;
1570 1571
}

1572 1573
static int qemudDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
                                     unsigned int flags) {
1574
    struct qemud_driver *driver = dom->conn->privateData;
1575
    qemuDomainObjPrivatePtr priv;
1576
    virDomainObjPtr vm;
1577
    virDomainDefPtr persistentDef = NULL;
1578
    int ret = -1, r;
1579

1580 1581 1582 1583 1584 1585 1586 1587
    virCheckFlags(VIR_DOMAIN_MEM_LIVE |
                  VIR_DOMAIN_MEM_CONFIG, -1);

    if ((flags & (VIR_DOMAIN_MEM_LIVE | VIR_DOMAIN_MEM_CONFIG)) == 0) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid flag combination: (0x%x)"), flags);
    }

1588
    qemuDriverLock(driver);
1589
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1590
    qemuDriverUnlock(driver);
1591
    if (!vm) {
1592 1593
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1594 1595
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1596
        goto cleanup;
1597 1598
    }

1599
    if (newmem > vm->def->mem.max_balloon) {
1600 1601
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("cannot set memory higher than max memory"));
1602
        goto cleanup;
1603 1604
    }

1605 1606 1607
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

1608
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_MEM_LIVE)) {
1609 1610 1611 1612 1613
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

1614 1615 1616 1617 1618 1619 1620 1621 1622
    if (flags & VIR_DOMAIN_MEM_CONFIG) {
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot change persistent config of a transient domain"));
            goto endjob;
        }
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
            goto endjob;
    }
1623

1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
    if (flags & VIR_DOMAIN_MEM_LIVE) {
        priv = vm->privateData;
        qemuDomainObjEnterMonitor(vm);
        r = qemuMonitorSetBalloon(priv->mon, newmem);
        qemuDomainObjExitMonitor(vm);
        qemuAuditMemory(vm, vm->def->mem.cur_balloon, newmem, "update", r == 1);
        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;
        }
    }

    if (flags& VIR_DOMAIN_MEM_CONFIG) {
        persistentDef->mem.cur_balloon = newmem;
        ret = virDomainSaveConfig(driver->configDir, persistentDef);
1644
        goto endjob;
1645
    }
1646

1647
    ret = 0;
1648
endjob:
1649 1650
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1651

1652
cleanup:
1653 1654
    if (vm)
        virDomainObjUnlock(vm);
1655
    return ret;
1656 1657
}

1658 1659 1660 1661
static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
    return qemudDomainSetMemoryFlags(dom, newmem, VIR_DOMAIN_MEM_LIVE);
}

1662
static int qemudDomainGetInfo(virDomainPtr dom,
1663
                              virDomainInfoPtr info) {
1664 1665 1666
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1667 1668
    int err;
    unsigned long balloon;
1669

1670
    qemuDriverLock(driver);
1671
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1672
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
1673
    if (!vm) {
1674 1675
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1676 1677
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1678
        goto cleanup;
D
Daniel P. Berrange 已提交
1679 1680
    }

1681
    info->state = vm->state;
D
Daniel P. Berrange 已提交
1682

D
Daniel P. Berrange 已提交
1683
    if (!virDomainObjIsActive(vm)) {
1684
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
1685
    } else {
1686
        if (qemudGetProcessInfo(&(info->cpuTime), NULL, vm->pid, 0) < 0) {
E
Eric Blake 已提交
1687 1688
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("cannot read cputime for domain"));
1689
            goto cleanup;
D
Daniel P. Berrange 已提交
1690 1691 1692
        }
    }

1693
    info->maxMem = vm->def->mem.max_balloon;
1694

D
Daniel P. Berrange 已提交
1695
    if (virDomainObjIsActive(vm)) {
1696
        qemuDomainObjPrivatePtr priv = vm->privateData;
1697 1698 1699

        if ((vm->def->memballoon != NULL) &&
            (vm->def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_NONE)) {
1700
            info->memory = vm->def->mem.max_balloon;
1701
        } else if (!priv->jobActive) {
1702 1703
            if (qemuDomainObjBeginJob(vm) < 0)
                goto cleanup;
1704 1705 1706 1707 1708 1709 1710 1711 1712
            if (!virDomainObjIsActive(vm))
                err = 0;
            else {
                qemuDomainObjEnterMonitor(vm);
                err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
                qemuDomainObjExitMonitor(vm);
            }
            if (qemuDomainObjEndJob(vm) == 0) {
                vm = NULL;
1713 1714 1715
                goto cleanup;
            }

1716 1717
            if (err < 0)
                goto cleanup;
1718 1719
            if (err == 0)
                /* Balloon not supported, so maxmem is always the allocation */
1720
                info->memory = vm->def->mem.max_balloon;
1721 1722 1723
            else
                info->memory = balloon;
        } else {
1724
            info->memory = vm->def->mem.cur_balloon;
1725
        }
1726
    } else {
1727
        info->memory = vm->def->mem.cur_balloon;
1728 1729
    }

1730
    info->nrVirtCpu = vm->def->vcpus;
1731 1732 1733
    ret = 0;

cleanup:
1734 1735
    if (vm)
        virDomainObjUnlock(vm);
1736
    return ret;
D
Daniel P. Berrange 已提交
1737 1738 1739
}


1740
#define QEMUD_SAVE_MAGIC "LibvirtQemudSave"
1741 1742 1743
#define QEMUD_SAVE_VERSION 2

enum qemud_save_formats {
1744 1745 1746
    QEMUD_SAVE_FORMAT_RAW = 0,
    QEMUD_SAVE_FORMAT_GZIP = 1,
    QEMUD_SAVE_FORMAT_BZIP2 = 2,
1747 1748
    /*
     * Deprecated by xz and never used as part of a release
1749
     * QEMUD_SAVE_FORMAT_LZMA
1750 1751
     */
    QEMUD_SAVE_FORMAT_XZ = 3,
1752
    QEMUD_SAVE_FORMAT_LZOP = 4,
1753 1754 1755
    /* Note: add new members only at the end.
       These values are used in the on-disk format.
       Do not change or re-use numbers. */
1756 1757

    QEMUD_SAVE_FORMAT_LAST
1758
};
1759

1760 1761 1762 1763 1764
VIR_ENUM_DECL(qemudSaveCompression)
VIR_ENUM_IMPL(qemudSaveCompression, QEMUD_SAVE_FORMAT_LAST,
              "raw",
              "gzip",
              "bzip2",
1765 1766
              "xz",
              "lzop")
1767

1768 1769 1770 1771 1772
struct qemud_save_header {
    char magic[sizeof(QEMUD_SAVE_MAGIC)-1];
    int version;
    int xml_len;
    int was_running;
1773 1774
    int compressed;
    int unused[15];
1775 1776
};

1777 1778 1779 1780 1781 1782 1783
struct fileOpHookData {
    virDomainPtr dom;
    const char *path;
    char *xml;
    struct qemud_save_header *header;
};

1784
/* return -errno on failure, or 0 on success */
1785 1786 1787 1788 1789
static int qemudDomainSaveFileOpHook(int fd, void *data) {
    struct fileOpHookData *hdata = data;
    int ret = 0;

    if (safewrite(fd, hdata->header, sizeof(*hdata->header)) != sizeof(*hdata->header)) {
1790
        ret = -errno;
1791
        qemuReportError(VIR_ERR_OPERATION_FAILED,
1792 1793
                        _("failed to write header to domain save file '%s'"),
                        hdata->path);
1794 1795 1796 1797
        goto endjob;
    }

    if (safewrite(fd, hdata->xml, hdata->header->xml_len) != hdata->header->xml_len) {
1798
        ret = -errno;
1799 1800 1801 1802 1803 1804 1805 1806
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                         _("failed to write xml to '%s'"), hdata->path);
        goto endjob;
    }
endjob:
    return ret;
}

1807 1808 1809
/* This internal function expects the driver lock to already be held on
 * entry and the vm must be active.
 */
1810 1811
static int qemudDomainSaveFlag(struct qemud_driver *driver, virDomainPtr dom,
                               virDomainObjPtr vm, const char *path,
1812
                               int compressed)
1813
{
1814
    char *xml = NULL;
1815
    struct qemud_save_header header;
1816 1817
    struct fileOpHookData hdata;
    int bypassSecurityDriver = 0;
1818
    int ret = -1;
1819
    int rc;
1820
    virDomainEventPtr event = NULL;
1821
    qemuDomainObjPrivatePtr priv;
1822 1823
    struct stat sb;
    int is_reg = 0;
1824
    unsigned long long offset;
1825
    virCgroupPtr cgroup = NULL;
1826 1827 1828 1829 1830

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

1831
    header.compressed = compressed;
1832

1833
    priv = vm->privateData;
1834

1835 1836 1837
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

O
Osier Yang 已提交
1838 1839
    priv->jobActive = QEMU_JOB_SAVE;

1840 1841 1842
    memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
    priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;

1843 1844 1845
    /* Pause */
    if (vm->state == VIR_DOMAIN_RUNNING) {
        header.was_running = 1;
1846
        if (qemuProcessStopCPUs(driver, vm) < 0)
1847
            goto endjob;
1848 1849 1850 1851 1852 1853

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

    /* Get XML for the domain */
1857
    xml = virDomainDefFormat(vm->def, VIR_DOMAIN_XML_SECURE);
1858
    if (!xml) {
1859 1860
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to get domain xml"));
1861
        goto endjob;
1862 1863 1864
    }
    header.xml_len = strlen(xml) + 1;

1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
    /* 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 */
        is_reg = 1;
    } else {
        is_reg = S_ISREG(sb.st_mode);
    }

1878 1879 1880 1881 1882
    offset = sizeof(header) + header.xml_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
1883 1884
     * it by padding the XML string with NULLs.
     */
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
    if (offset % QEMU_MONITOR_MIGRATE_TO_FILE_BS) {
        unsigned long long pad =
            QEMU_MONITOR_MIGRATE_TO_FILE_BS -
            (offset % QEMU_MONITOR_MIGRATE_TO_FILE_BS);

        if (VIR_REALLOC_N(xml, header.xml_len + pad) < 0) {
            virReportOOMError();
            goto endjob;
        }
        memset(xml + header.xml_len, 0, pad);
        offset += pad;
        header.xml_len += pad;
    }
1898

1899 1900 1901 1902 1903 1904
    /* Setup hook data needed by virFileOperation hook function */
    hdata.dom = dom;
    hdata.path = path;
    hdata.xml = xml;
    hdata.header = &header;

1905 1906
    /* Write header to file, followed by XML */

1907
    /* First try creating the file as root */
1908 1909 1910 1911
    if (!is_reg) {
        int fd = open(path, O_WRONLY | O_TRUNC);
        if (fd < 0) {
            virReportSystemError(errno, _("unable to open %s"), path);
1912 1913
            goto endjob;
        }
1914
        if (qemudDomainSaveFileOpHook(fd, &hdata) < 0) {
1915
            VIR_FORCE_CLOSE(fd);
1916 1917
            goto endjob;
        }
1918
        if (VIR_CLOSE(fd) < 0) {
1919
            virReportSystemError(errno, _("unable to close %s"), path);
1920 1921
            goto endjob;
        }
1922 1923 1924 1925 1926
    } else {
        if ((rc = virFileOperation(path, O_CREAT|O_TRUNC|O_WRONLY,
                                  S_IRUSR|S_IWUSR,
                                  getuid(), getgid(),
                                  qemudDomainSaveFileOpHook, &hdata,
1927
                                  0)) < 0) {
1928
            /* If we failed as root, and the error was permission-denied
1929 1930
               (EACCES or EPERM), assume it's on a network-connected share
               where root access is restricted (eg, root-squashed NFS). If the
1931 1932 1933 1934
               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 */

1935
            if (((rc != -EACCES) && (rc != -EPERM)) ||
1936
                driver->user == getuid()) {
1937
                virReportSystemError(-rc, _("Failed to create domain save file '%s'"),
1938 1939 1940
                                     path);
                goto endjob;
            }
1941

1942
            /* On Linux we can also verify the FS-type of the directory. */
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
            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:
                   /* local file - log the error returned by virFileOperation */
1961
                   virReportSystemError(-rc,
1962 1963 1964 1965
                                        _("Failed to create domain save file '%s'"),
                                        path);
                   goto endjob;
                   break;
1966 1967 1968

            }

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

1971 1972 1973 1974
            if ((rc = virFileOperation(path, O_CREAT|O_TRUNC|O_WRONLY,
                                       S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP,
                                       driver->user, driver->group,
                                       qemudDomainSaveFileOpHook, &hdata,
1975 1976
                                       VIR_FILE_OP_AS_UID)) < 0) {
                virReportSystemError(-rc, _("Error from child process creating '%s'"),
1977
                                 path);
1978 1979
                goto endjob;
            }
1980

1981 1982 1983
            /* 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 */
1984

1985 1986
            bypassSecurityDriver = 1;
        }
1987
    }
1988

1989

1990 1991 1992 1993
    if (!is_reg &&
        qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) != 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
E
Eric Blake 已提交
1994
                            _("Unable to find cgroup for %s"),
1995 1996 1997
                            vm->def->name);
            goto endjob;
        }
1998 1999
        rc = virCgroupAllowDevicePath(cgroup, path,
                                      VIR_CGROUP_DEVICE_RW);
2000
        qemuAuditCgroupPath(vm, cgroup, "allow", path, "rw", rc);
2001
        if (rc < 0) {
2002 2003 2004 2005 2006 2007 2008
            virReportSystemError(-rc,
                                 _("Unable to allow device %s for %s"),
                                 path, vm->def->name);
            goto endjob;
        }
    }

2009
    if ((!bypassSecurityDriver) &&
2010 2011
        virSecurityManagerSetSavedStateLabel(driver->securityManager,
                                             vm, path) < 0)
2012 2013
        goto endjob;

2014 2015
    if (header.compressed == QEMUD_SAVE_FORMAT_RAW) {
        const char *args[] = { "cat", NULL };
M
Matthias Bolte 已提交
2016
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
2017 2018 2019
        rc = qemuMonitorMigrateToFile(priv->mon,
                                      QEMU_MONITOR_MIGRATE_BACKGROUND,
                                      args, path, offset);
M
Matthias Bolte 已提交
2020
        qemuDomainObjExitMonitorWithDriver(driver, vm);
2021
    } else {
2022
        const char *prog = qemudSaveCompressionTypeToString(header.compressed);
2023 2024 2025 2026 2027
        const char *args[] = {
            prog,
            "-c",
            NULL
        };
M
Matthias Bolte 已提交
2028
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
2029 2030 2031
        rc = qemuMonitorMigrateToFile(priv->mon,
                                      QEMU_MONITOR_MIGRATE_BACKGROUND,
                                      args, path, offset);
M
Matthias Bolte 已提交
2032
        qemuDomainObjExitMonitorWithDriver(driver, vm);
2033 2034
    }

2035 2036 2037
    if (rc < 0)
        goto endjob;

2038
    rc = qemuMigrationWaitForCompletion(driver, vm);
2039

2040
    if (rc < 0)
2041
        goto endjob;
2042

2043
    if ((!bypassSecurityDriver) &&
2044 2045
        virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
                                                 vm, path) < 0)
2046
        VIR_WARN("failed to restore save state label on %s", path);
2047

2048
    if (cgroup != NULL) {
2049 2050
        rc = virCgroupDenyDevicePath(cgroup, path,
                                     VIR_CGROUP_DEVICE_RWM);
2051
        qemuAuditCgroupPath(vm, cgroup, "deny", path, "rwm", rc);
2052
        if (rc < 0)
2053 2054
            VIR_WARN("Unable to deny device %s for %s %d",
                     path, vm->def->name, rc);
2055 2056
    }

2057 2058
    ret = 0;

2059
    /* Shut it down */
2060
    qemuProcessStop(driver, vm, 0);
2061
    qemuAuditDomainStop(vm, "saved");
2062 2063 2064
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2065
    if (!vm->persistent) {
2066 2067 2068
        if (qemuDomainObjEndJob(vm) > 0)
            virDomainRemoveInactive(&driver->domains,
                                    vm);
2069 2070
        vm = NULL;
    }
2071

2072
endjob:
2073
    if (vm) {
2074
        if (ret != 0) {
2075
            if (header.was_running && virDomainObjIsActive(vm)) {
2076
                rc = qemuProcessStartCPUs(driver, vm, dom->conn);
2077 2078 2079
                if (rc < 0)
                    VIR_WARN0("Unable to resume guest CPUs after save failure");
            }
2080

2081
            if (cgroup != NULL) {
2082 2083
                rc = virCgroupDenyDevicePath(cgroup, path,
                                             VIR_CGROUP_DEVICE_RWM);
2084
                qemuAuditCgroupPath(vm, cgroup, "deny", path, "rwm", rc);
2085
                if (rc < 0)
2086 2087
                    VIR_WARN("Unable to deny device %s for %s: %d",
                             path, vm->def->name, rc);
2088
            }
2089 2090

            if ((!bypassSecurityDriver) &&
2091 2092
                virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
                                                         vm, path) < 0)
2093
                VIR_WARN("failed to restore save state label on %s", path);
2094 2095
        }

2096
        if (qemuDomainObjEndJob(vm) == 0)
2097
            vm = NULL;
2098
    }
2099

2100 2101
cleanup:
    VIR_FREE(xml);
2102
    if (ret != 0 && is_reg)
2103
        unlink(path);
2104 2105
    if (event)
        qemuDomainEventQueue(driver, event);
2106
    virCgroupFree(&cgroup);
2107
    return ret;
D
Daniel P. Berrange 已提交
2108 2109
}

2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
/* 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;
}

2126 2127 2128 2129
static int qemudDomainSave(virDomainPtr dom, const char *path)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int compressed;
2130 2131 2132 2133
    int ret = -1;
    virDomainObjPtr vm = NULL;

    qemuDriverLock(driver);
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144

    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"));
            return -1;
        }
2145 2146 2147 2148 2149 2150
        if (!qemudCompressProgramAvailable(compressed)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Compression program for image format "
                                    "in configuration file isn't available"));
            return -1;
        }
2151 2152
    }

2153 2154 2155 2156 2157 2158 2159 2160 2161
    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;
    }

2162 2163 2164 2165 2166 2167
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2168 2169 2170 2171 2172 2173 2174 2175
    ret = qemudDomainSaveFlag(driver, dom, vm, path, compressed);

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

    return ret;
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
}

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;

2199
    virCheckFlags(0, -1);
2200 2201 2202 2203 2204 2205 2206 2207

    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);
2208
        goto cleanup;
2209 2210
    }

2211 2212 2213 2214 2215 2216
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2217 2218
    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
2219
        goto cleanup;
2220 2221 2222 2223

    VIR_DEBUG("Saving state to %s", name);

    compressed = QEMUD_SAVE_FORMAT_RAW;
2224
    ret = qemudDomainSaveFlag(driver, dom, vm, name, compressed);
2225 2226 2227 2228 2229

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
2230 2231 2232
    VIR_FREE(name);

    return ret;
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
}

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

2243
    virCheckFlags(0, -1);
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276

    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;

2277
    virCheckFlags(0, -1);
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301

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

H
Hu Tao 已提交
2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
static int doCoreDump(struct qemud_driver *driver,
                      virDomainObjPtr vm,
                      const char *path,
                      enum qemud_save_formats compress)
{
    int fd = -1;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    priv = vm->privateData;

    /* Create an empty file with appropriate ownership.  */
    if ((fd = open(path, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR)) < 0) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("failed to create '%s'"), path);
        goto cleanup;
    }

    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno,
                             _("unable to save file %s"),
                             path);
        goto cleanup;
    }

2328 2329
    if (virSecurityManagerSetSavedStateLabel(driver->securityManager,
                                             vm, path) < 0)
H
Hu Tao 已提交
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
        goto cleanup;

    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    if (compress == QEMUD_SAVE_FORMAT_RAW) {
        const char *args[] = {
            "cat",
            NULL,
        };
        ret = qemuMonitorMigrateToFile(priv->mon,
                                       QEMU_MONITOR_MIGRATE_BACKGROUND,
                                       args, path, 0);
    } else {
        const char *prog = qemudSaveCompressionTypeToString(compress);
        const char *args[] = {
            prog,
            "-c",
            NULL,
        };
        ret = qemuMonitorMigrateToFile(priv->mon,
                                       QEMU_MONITOR_MIGRATE_BACKGROUND,
                                       args, path, 0);
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);
    if (ret < 0)
        goto cleanup;

2356
    ret = qemuMigrationWaitForCompletion(driver, vm);
H
Hu Tao 已提交
2357 2358 2359 2360

    if (ret < 0)
        goto cleanup;

2361 2362
    if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
                                                 vm, path) < 0)
H
Hu Tao 已提交
2363 2364 2365 2366 2367 2368 2369 2370
        goto cleanup;

cleanup:
    if (ret != 0)
        unlink(path);
    return ret;
}

2371 2372 2373 2374 2375
static enum qemud_save_formats
getCompressionType(struct qemud_driver *driver)
{
    int compress = QEMUD_SAVE_FORMAT_RAW;

2376 2377 2378 2379 2380 2381 2382
    /*
     * 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);
        if (compress < 0) {
2383 2384 2385 2386
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("Invalid dump image format specified in "
                              "configuration file, using raw"));
            return QEMUD_SAVE_FORMAT_RAW;
2387
        }
2388 2389 2390
        if (!qemudCompressProgramAvailable(compress)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Compression program for dump image format "
2391 2392 2393
                                    "in configuration file isn't available, "
                                    "using raw"));
            return QEMUD_SAVE_FORMAT_RAW;
2394
        }
2395
    }
2396 2397 2398 2399 2400 2401 2402 2403 2404
    return compress;
}

static int qemudDomainCoreDump(virDomainPtr dom,
                               const char *path,
                               int flags ATTRIBUTE_UNUSED) {
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int resume = 0, paused = 0;
H
Hu Tao 已提交
2405
    int ret = -1;
2406 2407 2408
    virDomainEventPtr event = NULL;
    qemuDomainObjPrivatePtr priv;

P
Paolo Bonzini 已提交
2409 2410 2411 2412 2413 2414
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2415 2416
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
P
Paolo Bonzini 已提交
2417 2418
        goto cleanup;
    }
2419
    priv = vm->privateData;
P
Paolo Bonzini 已提交
2420

2421
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
2422 2423
        goto cleanup;

D
Daniel P. Berrange 已提交
2424
    if (!virDomainObjIsActive(vm)) {
2425 2426
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
2427
        goto endjob;
P
Paolo Bonzini 已提交
2428 2429
    }

O
Osier Yang 已提交
2430 2431
    priv->jobActive = QEMU_JOB_DUMP;

P
Paolo Bonzini 已提交
2432 2433
    /* Migrate will always stop the VM, so the resume condition is
       independent of whether the stop command is issued.  */
P
Paolo Bonzini 已提交
2434 2435 2436
    resume = (vm->state == VIR_DOMAIN_RUNNING);

    /* Pause domain for non-live dump */
P
Paolo Bonzini 已提交
2437
    if (!(flags & VIR_DUMP_LIVE) && vm->state == VIR_DOMAIN_RUNNING) {
2438
        if (qemuProcessStopCPUs(driver, vm) < 0)
2439
            goto endjob;
P
Paolo Bonzini 已提交
2440
        paused = 1;
2441 2442 2443 2444 2445 2446

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

H
Hu Tao 已提交
2449
    ret = doCoreDump(driver, vm, path, getCompressionType(driver));
2450 2451 2452 2453
    if (ret < 0)
        goto endjob;

    paused = 1;
2454 2455

endjob:
2456
    if ((ret == 0) && (flags & VIR_DUMP_CRASH)) {
2457
        qemuProcessStop(driver, vm, 0);
2458
        qemuAuditDomainStop(vm, "crashed");
2459 2460 2461 2462 2463
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
    }

P
Paolo Bonzini 已提交
2464 2465 2466
    /* 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.  */
2467
    else if (resume && paused && virDomainObjIsActive(vm)) {
2468
        if (qemuProcessStartCPUs(driver, vm, dom->conn) < 0) {
2469
            if (virGetLastError() == NULL)
2470 2471
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("resuming after dump failed"));
P
Paolo Bonzini 已提交
2472 2473
        }
    }
2474

2475 2476
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
2477
    else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
2478 2479 2480 2481
        virDomainRemoveInactive(&driver->domains,
                                vm);
        vm = NULL;
    }
2482 2483

cleanup:
P
Paolo Bonzini 已提交
2484 2485
    if (vm)
        virDomainObjUnlock(vm);
2486 2487
    if (event)
        qemuDomainEventQueue(driver, event);
2488
    qemuDriverUnlock(driver);
P
Paolo Bonzini 已提交
2489 2490 2491
    return ret;
}

H
Hu Tao 已提交
2492 2493 2494
static void processWatchdogEvent(void *data, void *opaque)
{
    int ret;
2495
    struct qemuDomainWatchdogEvent *wdEvent = data;
H
Hu Tao 已提交
2496 2497 2498 2499 2500 2501 2502
    struct qemud_driver *driver = opaque;

    switch (wdEvent->action) {
    case VIR_DOMAIN_WATCHDOG_ACTION_DUMP:
        {
            char *dumpfile;

E
Eric Blake 已提交
2503
            if (virAsprintf(&dumpfile, "%s/%s-%u",
H
Hu Tao 已提交
2504 2505
                            driver->autoDumpPath,
                            wdEvent->vm->def->name,
E
Eric Blake 已提交
2506 2507 2508 2509
                            (unsigned int)time(NULL)) < 0) {
                virReportOOMError();
                break;
            }
H
Hu Tao 已提交
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530

            qemuDriverLock(driver);
            virDomainObjLock(wdEvent->vm);

            if (qemuDomainObjBeginJobWithDriver(driver, wdEvent->vm) < 0)
                break;

            if (!virDomainObjIsActive(wdEvent->vm)) {
                qemuReportError(VIR_ERR_OPERATION_INVALID,
                                "%s", _("domain is not running"));
                break;
            }

            ret = doCoreDump(driver,
                             wdEvent->vm,
                             dumpfile,
                             getCompressionType(driver));
            if (ret < 0)
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("Dump failed"));

2531
            ret = qemuProcessStartCPUs(driver, wdEvent->vm, NULL);
H
Hu Tao 已提交
2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548

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

            if (qemuDomainObjEndJob(wdEvent->vm) > 0)
                virDomainObjUnlock(wdEvent->vm);

            qemuDriverUnlock(driver);

            VIR_FREE(dumpfile);
        }
        break;
    }

    VIR_FREE(wdEvent);
}
P
Paolo Bonzini 已提交
2549

2550 2551 2552
static int qemudDomainHotplugVcpus(virDomainObjPtr vm, unsigned int nvcpus)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2553
    int i, rc = 1;
2554
    int ret = -1;
2555
    int oldvcpus = vm->def->vcpus;
E
Eric Blake 已提交
2556
    int vcpus = oldvcpus;
2557

2558 2559
    qemuDomainObjEnterMonitor(vm);

2560 2561 2562
    /* 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 已提交
2563 2564
    if (nvcpus > vcpus) {
        for (i = vcpus ; i < nvcpus ; i++) {
2565 2566 2567 2568 2569 2570 2571
            /* Online new CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 1);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
2572
            vcpus++;
2573 2574
        }
    } else {
E
Eric Blake 已提交
2575
        for (i = vcpus - 1 ; i >= nvcpus ; i--) {
2576 2577 2578 2579 2580 2581 2582
            /* Offline old CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 0);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
2583
            vcpus--;
2584 2585 2586 2587 2588 2589
        }
    }

    ret = 0;

cleanup:
2590
    qemuDomainObjExitMonitor(vm);
E
Eric Blake 已提交
2591
    vm->def->vcpus = vcpus;
2592
    qemuAuditVcpu(vm, oldvcpus, nvcpus, "update", rc == 1);
2593 2594 2595 2596 2597 2598 2599 2600 2601
    return ret;

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


2602 2603 2604 2605
static int
qemudDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
2606 2607
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2608
    virDomainDefPtr persistentDef;
2609 2610
    const char * type;
    int max;
2611
    int ret = -1;
2612

2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

    /* At least one of LIVE or CONFIG must be set.  MAXIMUM cannot be
     * mixed with LIVE.  */
    if ((flags & (VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG)) == 0 ||
        (flags & (VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_LIVE)) ==
         (VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_LIVE)) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid flag combination: (0x%x)"), flags);
        return -1;
    }
    if (!nvcpus || (unsigned short) nvcpus != nvcpus) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("argument out of range: %d"), nvcpus);
2629 2630 2631
        return -1;
    }

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

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

2644 2645 2646
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

2647
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
2648 2649
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("domain is not running"));
2650
        goto endjob;
2651 2652
    }

2653 2654 2655 2656 2657 2658
    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot change persistent config of a transient domain"));
        goto endjob;
    }

2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671
    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;
    }

C
Cole Robinson 已提交
2672
    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM) && vm->def->maxvcpus < max) {
2673 2674 2675
        max = vm->def->maxvcpus;
    }

2676 2677 2678 2679 2680 2681 2682
    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;
    }

2683 2684 2685
    if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
        goto endjob;

2686 2687
    switch (flags) {
    case VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_CONFIG:
2688 2689 2690
        persistentDef->maxvcpus = nvcpus;
        if (nvcpus < persistentDef->vcpus)
            persistentDef->vcpus = nvcpus;
2691 2692 2693 2694
        ret = 0;
        break;

    case VIR_DOMAIN_VCPU_CONFIG:
2695
        persistentDef->vcpus = nvcpus;
2696 2697 2698 2699 2700 2701 2702 2703 2704
        ret = 0;
        break;

    case VIR_DOMAIN_VCPU_LIVE:
        ret = qemudDomainHotplugVcpus(vm, nvcpus);
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
        ret = qemudDomainHotplugVcpus(vm, nvcpus);
2705 2706 2707
        if (ret == 0) {
            persistentDef->vcpus = nvcpus;
        }
2708 2709
        break;
    }
2710

2711 2712 2713 2714
    /* Save the persistent config to disk */
    if (flags & VIR_DOMAIN_VCPU_CONFIG)
        ret = virDomainSaveConfig(driver->configDir, persistentDef);

2715 2716 2717
endjob:
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
2718

2719
cleanup:
2720 2721
    if (vm)
        virDomainObjUnlock(vm);
2722
    return ret;
2723 2724
}

2725 2726 2727 2728 2729 2730
static int
qemudDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
{
    return qemudDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_VCPU_LIVE);
}

2731 2732 2733 2734 2735 2736

static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
2737 2738
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2739
    int maxcpu, hostcpus;
2740
    virNodeInfo nodeinfo;
2741
    int ret = -1;
2742
    qemuDomainObjPrivatePtr priv;
2743

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

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

D
Daniel P. Berrange 已提交
2756
    if (!virDomainObjIsActive(vm)) {
2757 2758
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s",_("cannot pin vcpus on an inactive domain"));
2759
        goto cleanup;
2760 2761
    }

2762 2763 2764
    priv = vm->privateData;

    if (vcpu > (priv->nvcpupids-1)) {
2765 2766 2767
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("vcpu number out of range %d > %d"),
                        vcpu, priv->nvcpupids);
2768
        goto cleanup;
2769 2770
    }

2771
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
2772
        goto cleanup;
2773

2774
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
2775
    maxcpu = maplen * 8;
2776 2777
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
2778

2779 2780
    if (priv->vcpupids != NULL) {
        if (virProcessInfoSetAffinity(priv->vcpupids[vcpu],
2781
                                      cpumap, maplen, maxcpu) < 0)
2782
            goto cleanup;
2783
    } else {
2784 2785
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        "%s", _("cpu affinity is not supported"));
2786
        goto cleanup;
2787
    }
2788
    ret = 0;
2789

2790
cleanup:
2791 2792
    if (vm)
        virDomainObjUnlock(vm);
2793
    return ret;
2794 2795 2796 2797 2798 2799 2800 2801
}

static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
2802 2803
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2804
    virNodeInfo nodeinfo;
2805
    int i, v, maxcpu, hostcpus;
2806
    int ret = -1;
2807
    qemuDomainObjPrivatePtr priv;
2808

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

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

D
Daniel P. Berrange 已提交
2821
    if (!virDomainObjIsActive(vm)) {
2822 2823 2824
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s",
                        _("cannot list vcpu pinning for an inactive domain"));
2825
        goto cleanup;
2826 2827
    }

2828 2829
    priv = vm->privateData;

2830
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
2831
        goto cleanup;
2832

2833
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
2834
    maxcpu = maplen * 8;
2835 2836
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
2837 2838

    /* Clamp to actual number of vcpus */
2839 2840
    if (maxinfo > priv->nvcpupids)
        maxinfo = priv->nvcpupids;
2841

2842 2843 2844 2845 2846 2847
    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;
2848

2849
                if (priv->vcpupids != NULL &&
2850 2851 2852
                    qemudGetProcessInfo(&(info[i].cpuTime),
                                        &(info[i].cpu),
                                        vm->pid,
2853
                                        priv->vcpupids[i]) < 0) {
2854
                    virReportSystemError(errno, "%s",
2855 2856 2857
                                         _("cannot get vCPU placement & pCPU time"));
                    goto cleanup;
                }
2858
            }
2859 2860
        }

2861 2862
        if (cpumaps != NULL) {
            memset(cpumaps, 0, maplen * maxinfo);
2863
            if (priv->vcpupids != NULL) {
2864 2865 2866
                for (v = 0 ; v < maxinfo ; v++) {
                    unsigned char *cpumap = VIR_GET_CPUMAP(cpumaps, maplen, v);

2867
                    if (virProcessInfoGetAffinity(priv->vcpupids[v],
2868
                                                  cpumap, maplen, maxcpu) < 0)
2869
                        goto cleanup;
2870
                }
2871
            } else {
2872 2873
                qemuReportError(VIR_ERR_NO_SUPPORT,
                                "%s", _("cpu affinity is not available"));
2874
                goto cleanup;
2875 2876 2877
            }
        }
    }
2878
    ret = maxinfo;
2879

2880
cleanup:
2881 2882
    if (vm)
        virDomainObjUnlock(vm);
2883
    return ret;
2884 2885 2886
}


2887 2888 2889
static int
qemudDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
2890 2891
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2892
    virDomainDefPtr def;
2893
    int ret = -1;
2894

2895 2896 2897 2898 2899 2900 2901 2902
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

    /* Exactly one of LIVE or CONFIG must be set.  */
    if (!(flags & VIR_DOMAIN_VCPU_LIVE) == !(flags & VIR_DOMAIN_VCPU_CONFIG)) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid flag combination: (0x%x)"), flags);
2903 2904 2905
        return -1;
    }

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

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

2918 2919 2920 2921 2922 2923 2924 2925 2926
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("domain not active"));
            goto cleanup;
        }
        def = vm->def;
    } else {
        def = vm->newDef ? vm->newDef : vm->def;
2927 2928
    }

2929
    ret = (flags & VIR_DOMAIN_VCPU_MAXIMUM) ? def->maxvcpus : def->vcpus;
2930

2931
cleanup:
2932 2933
    if (vm)
        virDomainObjUnlock(vm);
2934 2935 2936
    return ret;
}

2937 2938 2939 2940 2941 2942 2943
static int
qemudDomainGetMaxVcpus(virDomainPtr dom)
{
    return qemudDomainGetVcpusFlags(dom, (VIR_DOMAIN_VCPU_LIVE |
                                          VIR_DOMAIN_VCPU_MAXIMUM));
}

2944 2945 2946 2947 2948 2949 2950 2951 2952
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);

2953 2954
    memset(seclabel, 0, sizeof(*seclabel));

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

2963
    if (!virDomainVirtTypeToString(vm->def->virtType)) {
2964 2965 2966
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unknown virt type in domain definition '%d'"),
                        vm->def->virtType);
2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983
        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 已提交
2984
    if (virDomainObjIsActive(vm)) {
2985 2986
        if (virSecurityManagerGetProcessLabel(driver->securityManager,
                                              vm, seclabel) < 0) {
2987 2988 2989
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("Failed to get security label"));
            goto cleanup;
2990 2991 2992 2993 2994 2995 2996 2997
        }
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
2998
    qemuDriverUnlock(driver);
2999 3000 3001
    return ret;
}

3002 3003
static int qemudNodeGetSecurityModel(virConnectPtr conn,
                                     virSecurityModelPtr secmodel)
3004 3005 3006
{
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
    char *p;
3007
    int ret = 0;
3008

3009
    qemuDriverLock(driver);
3010 3011 3012 3013 3014
    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)
3015
        goto cleanup;
3016

3017 3018
    p = driver->caps->host.secModel.model;
    if (strlen(p) >= VIR_SECURITY_MODEL_BUFLEN-1) {
3019 3020 3021
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security model string exceeds max %d bytes"),
                        VIR_SECURITY_MODEL_BUFLEN-1);
3022 3023
        ret = -1;
        goto cleanup;
3024 3025 3026 3027 3028
    }
    strcpy(secmodel->model, p);

    p = driver->caps->host.secModel.doi;
    if (strlen(p) >= VIR_SECURITY_DOI_BUFLEN-1) {
3029 3030 3031
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security DOI string exceeds max %d bytes"),
                        VIR_SECURITY_DOI_BUFLEN-1);
3032 3033
        ret = -1;
        goto cleanup;
3034 3035
    }
    strcpy(secmodel->doi, p);
3036 3037 3038 3039

cleanup:
    qemuDriverUnlock(driver);
    return ret;
3040 3041
}

3042 3043 3044 3045 3046 3047
/* qemudOpenAsUID() - pipe/fork/setuid/open a file, and return the
   pipe fd to caller, so that it can read from the file. Also return
   the pid of the child process, so the caller can wait for it to exit
   after it's finished reading (to avoid a zombie, if nothing
   else). */

3048 3049 3050
static int
qemudOpenAsUID(const char *path, uid_t uid, gid_t gid, pid_t *child_pid)
{
3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077
    int pipefd[2];
    int fd = -1;

    *child_pid = -1;

    if (pipe(pipefd) < 0) {
        virReportSystemError(errno,
                             _("failed to create pipe to read '%s'"),
                             path);
        pipefd[0] = pipefd[1] = -1;
        goto parent_cleanup;
    }

    int forkRet = virFork(child_pid);

    if (*child_pid < 0) {
        virReportSystemError(errno,
                             _("failed to fork child to read '%s'"),
                             path);
        goto parent_cleanup;
    }

    if (*child_pid > 0) {

        /* parent */

        /* parent doesn't need the write side of the pipe */
3078
        VIR_FORCE_CLOSE(pipefd[1]);
3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089

        if (forkRet < 0) {
            virReportSystemError(errno,
                                 _("failed in parent after forking child to read '%s'"),
                                 path);
            goto parent_cleanup;
        }
        /* caller gets the read side of the pipe */
        fd = pipefd[0];
        pipefd[0] = -1;
parent_cleanup:
3090 3091
        VIR_FORCE_CLOSE(pipefd[0]);
        VIR_FORCE_CLOSE(pipefd[1]);
3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115
        if ((fd < 0) && (*child_pid > 0)) {
            /* a child process was started and subsequently an error
               occurred in the parent, so we need to wait for it to
               exit, but its status is inconsequential. */
            while ((waitpid(*child_pid, NULL, 0) == -1)
                   && (errno == EINTR)) {
                /* empty */
            }
            *child_pid = -1;
        }
        return fd;
    }

    /* child */

    /* setuid to the qemu user, then open the file, read it,
       and stuff it into the pipe for the parent process to
       read */
    int exit_code;
    char *buf = NULL;
    size_t bufsize = 1024 * 1024;
    int bytesread;

    /* child doesn't need the read side of the pipe */
3116
    VIR_FORCE_CLOSE(pipefd[0]);
3117 3118 3119 3120 3121 3122 3123 3124 3125

    if (forkRet < 0) {
        exit_code = errno;
        virReportSystemError(errno,
                             _("failed in child after forking to read '%s'"),
                             path);
        goto child_cleanup;
    }

3126 3127 3128
    if (virSetUIDGID(uid, gid) < 0) {
       exit_code = errno;
       goto child_cleanup;
3129 3130
    }

3131 3132 3133 3134 3135 3136 3137 3138
    if ((fd = open(path, O_RDONLY)) < 0) {
        exit_code = errno;
        virReportSystemError(errno,
                             _("cannot open '%s' as uid %d"),
                             path, uid);
        goto child_cleanup;
    }

3139 3140 3141 3142 3143 3144
    if (VIR_ALLOC_N(buf, bufsize) < 0) {
        exit_code = ENOMEM;
        virReportOOMError();
        goto child_cleanup;
    }

3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164
    /* read from fd and write to pipefd[1] until EOF */
    do {
        if ((bytesread = saferead(fd, buf, bufsize)) < 0) {
            exit_code = errno;
            virReportSystemError(errno,
                                 _("child failed reading from '%s'"),
                                 path);
            goto child_cleanup;
        }
        if (safewrite(pipefd[1], buf, bytesread) != bytesread) {
            exit_code = errno;
            virReportSystemError(errno, "%s",
                                 _("child failed writing to pipe"));
            goto child_cleanup;
        }
    } while (bytesread > 0);
    exit_code = 0;

child_cleanup:
    VIR_FREE(buf);
3165 3166
    VIR_FORCE_CLOSE(fd);
    VIR_FORCE_CLOSE(pipefd[1]);
3167 3168 3169
    _exit(exit_code);
}

J
Jiri Denemark 已提交
3170 3171 3172 3173
static int qemudDomainSaveImageClose(int fd, pid_t read_pid, int *status)
{
    int ret = 0;

3174 3175 3176 3177
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, "%s",
                             _("cannot close file"));
    }
J
Jiri Denemark 已提交
3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193

    if (read_pid != -1) {
        /* reap the process that read the file */
        while ((ret = waitpid(read_pid, status, 0)) == -1
               && errno == EINTR) {
            /* empty */
        }
    } else if (status) {
        *status = 0;
    }

    return ret;
}

static int ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4) ATTRIBUTE_NONNULL(5)
qemudDomainSaveImageOpen(struct qemud_driver *driver,
3194 3195 3196 3197
                         const char *path,
                         virDomainDefPtr *ret_def,
                         struct qemud_save_header *ret_header,
                         pid_t *ret_read_pid)
J
Jiri Denemark 已提交
3198 3199
{
    int fd;
3200
    pid_t read_pid = -1;
3201
    struct qemud_save_header header;
J
Jiri Denemark 已提交
3202 3203
    char *xml = NULL;
    virDomainDefPtr def = NULL;
3204 3205

    if ((fd = open(path, O_RDONLY)) < 0) {
3206 3207 3208
        if ((driver->user == 0) || (getuid() != 0)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("cannot read domain image"));
J
Jiri Denemark 已提交
3209
            goto error;
3210 3211 3212 3213 3214 3215
        }

        /* Opening as root failed, but qemu runs as a different user
           that might have better luck. Create a pipe, then fork a
           child process to run as the qemu user, which will hopefully
           have the necessary authority to read the file. */
3216 3217
        if ((fd = qemudOpenAsUID(path,
                                 driver->user, driver->group, &read_pid)) < 0) {
3218
            /* error already reported */
J
Jiri Denemark 已提交
3219
            goto error;
3220
        }
3221 3222 3223
    }

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
3224 3225
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read qemu header"));
J
Jiri Denemark 已提交
3226
        goto error;
3227 3228 3229
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
3230 3231
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("image magic is incorrect"));
J
Jiri Denemark 已提交
3232
        goto error;
3233 3234 3235
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3236 3237 3238
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("image version is not supported (%d > %d)"),
                        header.version, QEMUD_SAVE_VERSION);
J
Jiri Denemark 已提交
3239
        goto error;
3240 3241
    }

3242 3243 3244
    if (header.xml_len <= 0) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("invalid XML length: %d"), header.xml_len);
J
Jiri Denemark 已提交
3245
        goto error;
3246 3247
    }

3248 3249
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
        virReportOOMError();
J
Jiri Denemark 已提交
3250
        goto error;
3251 3252 3253
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
3254 3255
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read XML"));
J
Jiri Denemark 已提交
3256
        goto error;
3257 3258 3259
    }

    /* Create a domain from this XML */
3260
    if (!(def = virDomainDefParseString(driver->caps, xml,
3261
                                        VIR_DOMAIN_XML_INACTIVE)))
J
Jiri Denemark 已提交
3262
        goto error;
3263

J
Jiri Denemark 已提交
3264
    VIR_FREE(xml);
3265

J
Jiri Denemark 已提交
3266 3267 3268
    *ret_def = def;
    *ret_header = header;
    *ret_read_pid = read_pid;
3269

J
Jiri Denemark 已提交
3270
    return fd;
3271

J
Jiri Denemark 已提交
3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283
error:
    virDomainDefFree(def);
    VIR_FREE(xml);
    qemudDomainSaveImageClose(fd, read_pid, NULL);

    return -1;
}

static int ATTRIBUTE_NONNULL(6)
qemudDomainSaveImageStartVM(virConnectPtr conn,
                            struct qemud_driver *driver,
                            virDomainObjPtr vm,
3284 3285
                            int *fd,
                            pid_t *read_pid,
J
Jiri Denemark 已提交
3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297
                            const struct qemud_save_header *header,
                            const char *path)
{
    int ret = -1;
    virDomainEventPtr event;
    int intermediatefd = -1;
    pid_t intermediate_pid = -1;
    int childstat;
    int wait_ret;
    int status;

    if (header->version == 2) {
3298
        const char *intermediate_argv[3] = { NULL, "-dc", NULL };
J
Jiri Denemark 已提交
3299
        const char *prog = qemudSaveCompressionTypeToString(header->compressed);
3300
        if (prog == NULL) {
3301 3302
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("Invalid compressed save format %d"),
J
Jiri Denemark 已提交
3303 3304
                            header->compressed);
            goto out;
3305
        }
3306

J
Jiri Denemark 已提交
3307
        if (header->compressed != QEMUD_SAVE_FORMAT_RAW) {
3308
            intermediate_argv[0] = prog;
3309 3310
            intermediatefd = *fd;
            *fd = -1;
3311
            if (virExec(intermediate_argv, NULL, NULL,
3312
                        &intermediate_pid, intermediatefd, fd, NULL, 0) < 0) {
3313 3314 3315
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Failed to start decompression binary %s"),
                                intermediate_argv[0]);
3316
                *fd = intermediatefd;
J
Jiri Denemark 已提交
3317
                goto out;
3318 3319 3320
            }
        }
    }
J
Jiri Denemark 已提交
3321

3322
    /* Set the migration source and start it up. */
3323
    ret = qemuProcessStart(conn, driver, vm, "stdio", true, *fd, path,
3324
                           VIR_VM_OP_RESTORE);
J
Jiri Denemark 已提交
3325

3326
    if (intermediate_pid != -1) {
3327 3328 3329 3330 3331
        if (ret < 0) {
            /* if there was an error setting up qemu, the intermediate process will
             * wait forever to write to stdout, so we must manually kill it.
             */
            VIR_FORCE_CLOSE(intermediatefd);
3332
            VIR_FORCE_CLOSE(*fd);
3333 3334 3335
            kill(intermediate_pid, SIGTERM);
        }

3336 3337
        /* Wait for intermediate process to exit */
        while (waitpid(intermediate_pid, &childstat, 0) == -1 &&
J
Jiri Denemark 已提交
3338 3339 3340
               errno == EINTR) {
            /* empty */
        }
3341
    }
3342
    VIR_FORCE_CLOSE(intermediatefd);
J
Jiri Denemark 已提交
3343

3344 3345 3346
    wait_ret = qemudDomainSaveImageClose(*fd, *read_pid, &status);
    *fd = -1;
    if (*read_pid != -1) {
3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366
        if (wait_ret == -1) {
            virReportSystemError(errno,
                                 _("failed to wait for process reading '%s'"),
                                 path);
            ret = -1;
        } else if (!WIFEXITED(status)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("child process exited abnormally reading '%s'"),
                            path);
            ret = -1;
        } else {
            int exit_status = WEXITSTATUS(status);
            if (exit_status != 0) {
                virReportSystemError(exit_status,
                                     _("child process returned error reading '%s'"),
                                     path);
                ret = -1;
            }
        }
    }
3367
    *read_pid = -1;
J
Jiri Denemark 已提交
3368

3369
    if (ret < 0) {
3370
        qemuAuditDomainStart(vm, "restored", false);
J
Jiri Denemark 已提交
3371
        goto out;
3372
    }
3373

3374 3375 3376
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
3377
    qemuAuditDomainStart(vm, "restored", true);
J
Jiri Denemark 已提交
3378 3379 3380
    if (event)
        qemuDomainEventQueue(driver, event);

3381

3382
    /* If it was running before, resume it now. */
J
Jiri Denemark 已提交
3383
    if (header->was_running) {
3384
        if (qemuProcessStartCPUs(driver, vm, conn) < 0) {
3385
            if (virGetLastError() == NULL)
3386 3387
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("failed to resume domain"));
J
Jiri Denemark 已提交
3388
            goto out;
3389
        }
3390 3391
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
J
Jiri Denemark 已提交
3392
            goto out;
3393
        }
3394
    }
J
Jiri Denemark 已提交
3395

3396
    ret = 0;
3397

J
Jiri Denemark 已提交
3398
out:
3399 3400
    if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
                                                 vm, path) < 0)
3401 3402
        VIR_WARN("failed to restore save state label on %s", path);

J
Jiri Denemark 已提交
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
    return ret;
}

static int qemudDomainRestore(virConnectPtr conn,
                              const char *path) {
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    int fd = -1;
    pid_t read_pid = -1;
    int ret = -1;
    struct qemud_save_header header;

    qemuDriverLock(driver);

    fd = qemudDomainSaveImageOpen(driver, path, &def, &header, &read_pid);
    if (fd < 0)
        goto cleanup;

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

    if (!(vm = virDomainAssignDef(driver->caps,
                                  &driver->domains,
                                  def, true))) {
3428
        /* virDomainAssignDef already set the error */
J
Jiri Denemark 已提交
3429 3430 3431 3432 3433 3434 3435
        goto cleanup;
    }
    def = NULL;

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

3436 3437
    ret = qemudDomainSaveImageStartVM(conn, driver, vm, &fd,
                                      &read_pid, &header, path);
J
Jiri Denemark 已提交
3438 3439

    if (qemuDomainObjEndJob(vm) == 0)
3440
        vm = NULL;
J
Jiri Denemark 已提交
3441 3442 3443 3444
    else if (ret < 0 && !vm->persistent) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }
3445

3446 3447
cleanup:
    virDomainDefFree(def);
J
Jiri Denemark 已提交
3448
    qemudDomainSaveImageClose(fd, read_pid, NULL);
3449 3450 3451
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
3452
    return ret;
D
Daniel P. Berrange 已提交
3453 3454
}

J
Jiri Denemark 已提交
3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486
static int qemudDomainObjRestore(virConnectPtr conn,
                                 struct qemud_driver *driver,
                                 virDomainObjPtr vm,
                                 const char *path)
{
    virDomainDefPtr def = NULL;
    int fd = -1;
    pid_t read_pid = -1;
    int ret = -1;
    struct qemud_save_header header;

    fd = qemudDomainSaveImageOpen(driver, path, &def, &header, &read_pid);
    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;

3487 3488
    ret = qemudDomainSaveImageStartVM(conn, driver, vm, &fd,
                                      &read_pid, &header, path);
J
Jiri Denemark 已提交
3489 3490 3491 3492 3493 3494 3495

cleanup:
    virDomainDefFree(def);
    qemudDomainSaveImageClose(fd, read_pid, NULL);
    return ret;
}

D
Daniel P. Berrange 已提交
3496

3497
static char *qemudDomainDumpXML(virDomainPtr dom,
3498
                                int flags) {
3499 3500 3501
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;
3502 3503
    unsigned long balloon;
    int err;
3504

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

D
Daniel P. Berrange 已提交
3508
    if (!vm) {
3509 3510
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3511 3512
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
3513
        goto cleanup;
D
Daniel P. Berrange 已提交
3514 3515
    }

3516 3517 3518 3519
    /* 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))) {
3520
        qemuDomainObjPrivatePtr priv = vm->privateData;
3521 3522 3523
        /* Don't delay if someone's using the monitor, just use
         * existing most recent data instead */
        if (!priv->jobActive) {
3524
            if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
3525 3526
                goto cleanup;

3527
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
3528
            err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
3529
            qemuDomainObjExitMonitorWithDriver(driver, vm);
3530 3531 3532 3533
            if (qemuDomainObjEndJob(vm) == 0) {
                vm = NULL;
                goto cleanup;
            }
3534 3535 3536
            if (err < 0)
                goto cleanup;
            if (err > 0)
3537
                vm->def->mem.cur_balloon = balloon;
3538 3539
            /* err == 0 indicates no balloon support, so ignore it */
        }
3540
    }
3541

3542
    ret = qemuDomainFormatXML(driver, vm, flags);
3543 3544

cleanup:
3545 3546
    if (vm)
        virDomainObjUnlock(vm);
3547
    qemuDriverUnlock(driver);
3548
    return ret;
D
Daniel P. Berrange 已提交
3549 3550 3551
}


3552 3553 3554 3555
static char *qemuDomainXMLFromNative(virConnectPtr conn,
                                     const char *format,
                                     const char *config,
                                     unsigned int flags ATTRIBUTE_UNUSED) {
3556
    struct qemud_driver *driver = conn->privateData;
3557 3558 3559 3560
    virDomainDefPtr def = NULL;
    char *xml = NULL;

    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
3561 3562
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
3563 3564 3565
        goto cleanup;
    }

3566
    qemuDriverLock(driver);
3567
    def = qemuParseCommandLineString(driver->caps, config);
3568
    qemuDriverUnlock(driver);
3569 3570 3571
    if (!def)
        goto cleanup;

3572
    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
3573 3574 3575 3576 3577 3578

cleanup:
    virDomainDefFree(def);
    return xml;
}

3579 3580 3581 3582 3583 3584
static char *qemuDomainXMLToNative(virConnectPtr conn,
                                   const char *format,
                                   const char *xmlData,
                                   unsigned int flags ATTRIBUTE_UNUSED) {
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
3585
    virDomainChrSourceDef monConfig;
3586
    virBitmapPtr qemuCaps = NULL;
E
Eric Blake 已提交
3587
    virCommandPtr cmd = NULL;
3588 3589 3590
    char *ret = NULL;
    int i;

3591 3592
    qemuDriverLock(driver);

3593
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
3594 3595
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
3596 3597 3598
        goto cleanup;
    }

3599
    def = virDomainDefParseString(driver->caps, xmlData, 0);
3600 3601 3602
    if (!def)
        goto cleanup;

3603 3604
    /* Since we're just exporting args, we can't do bridge/network/direct
     * setups, since libvirt will normally create TAP/macvtap devices
3605 3606 3607 3608 3609
     * 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];
3610
        int bootIndex = net->bootIndex;
3611 3612
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK ||
            net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632
            VIR_FREE(net->data.network.name);

            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;
        }
3633
        net->bootIndex = bootIndex;
3634 3635 3636 3637
    }
    for (i = 0 ; i < def->ngraphics ; i++) {
        if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
            def->graphics[i]->data.vnc.autoport)
3638
            def->graphics[i]->data.vnc.port = QEMU_VNC_PORT_MIN;
3639 3640
    }

3641
    if (qemuCapsExtractVersionInfo(def->emulator, def->os.arch,
3642
                                   NULL,
3643
                                   &qemuCaps) < 0)
3644 3645
        goto cleanup;

3646
    if (qemuProcessPrepareMonitorChr(driver, &monConfig, def->name) < 0)
3647
        goto cleanup;
3648

3649
    if (!(cmd = qemuBuildCommandLine(conn, driver, def,
3650
                                     &monConfig, false, qemuCaps,
3651
                                     NULL, -1, NULL, VIR_VM_OP_NO_OP)))
3652 3653
        goto cleanup;

E
Eric Blake 已提交
3654
    ret = virCommandToString(cmd);
3655 3656

cleanup:
3657
    qemuDriverUnlock(driver);
3658

3659
    qemuCapsFree(qemuCaps);
E
Eric Blake 已提交
3660
    virCommandFree(cmd);
3661 3662 3663 3664 3665
    virDomainDefFree(def);
    return ret;
}


3666
static int qemudListDefinedDomains(virConnectPtr conn,
3667
                            char **const names, int nnames) {
3668
    struct qemud_driver *driver = conn->privateData;
3669
    int n;
3670

3671
    qemuDriverLock(driver);
3672
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
3673
    qemuDriverUnlock(driver);
3674
    return n;
D
Daniel P. Berrange 已提交
3675 3676
}

3677
static int qemudNumDefinedDomains(virConnectPtr conn) {
3678
    struct qemud_driver *driver = conn->privateData;
3679
    int n;
3680

3681
    qemuDriverLock(driver);
3682
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
3683
    qemuDriverUnlock(driver);
3684

3685
    return n;
D
Daniel P. Berrange 已提交
3686 3687 3688
}


J
Jiri Denemark 已提交
3689 3690
static int qemudDomainObjStart(virConnectPtr conn,
                               struct qemud_driver *driver,
3691 3692
                               virDomainObjPtr vm,
                               bool start_paused)
J
Jiri Denemark 已提交
3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712
{
    int ret = -1;
    char *managed_save;

    /*
     * If there is a managed saved state restore it instead of starting
     * from scratch. In any case the old state is removed.
     */
    managed_save = qemuDomainManagedSavePath(driver, vm);
    if ((managed_save) && (virFileExists(managed_save))) {
        ret = qemudDomainObjRestore(conn, driver, vm, managed_save);

        if (unlink(managed_save) < 0) {
            VIR_WARN("Failed to remove the managed state %s", managed_save);
        }

        if (ret == 0)
            goto cleanup;
    }

3713 3714
    ret = qemuProcessStart(conn, driver, vm, NULL, start_paused, -1, NULL,
                           VIR_VM_OP_CREATE);
3715
    qemuAuditDomainStart(vm, "booted", ret >= 0);
3716
    if (ret >= 0) {
J
Jiri Denemark 已提交
3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729
        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;
}

3730 3731 3732
static int
qemudDomainStartWithFlags(virDomainPtr dom, unsigned int flags)
{
3733 3734 3735
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
3736

3737
    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);
3738

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

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

3750 3751 3752 3753
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

    if (virDomainObjIsActive(vm)) {
3754 3755
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is already running"));
3756 3757 3758
        goto endjob;
    }

3759 3760
    ret = qemudDomainObjStart(dom->conn, driver, vm,
                              (flags & VIR_DOMAIN_START_PAUSED) != 0);
3761

3762
endjob:
3763 3764
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
3765

3766
cleanup:
3767 3768
    if (vm)
        virDomainObjUnlock(vm);
3769
    qemuDriverUnlock(driver);
3770
    return ret;
D
Daniel P. Berrange 已提交
3771 3772
}

3773 3774 3775 3776 3777 3778
static int
qemudDomainStart(virDomainPtr dom)
{
    return qemudDomainStartWithFlags(dom, 0);
}

3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793
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;

3794
        if (STRNEQ(def->os.machine, machine->name))
3795 3796 3797
            continue;

        if (!(*canonical = strdup(machine->canonical))) {
3798
            virReportOOMError();
3799 3800 3801 3802 3803 3804 3805 3806 3807
            return -1;
        }

        break;
    }

    return 0;
}

3808 3809 3810 3811 3812 3813
static int
qemudCanonicalizeMachineDirect(virDomainDefPtr def, char **canonical)
{
    virCapsGuestMachinePtr *machines = NULL;
    int i, nmachines = 0;

3814
    if (qemuCapsProbeMachineTypes(def->emulator, &machines, &nmachines) < 0)
3815 3816 3817 3818 3819 3820
        return -1;

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

3821
        if (STRNEQ(def->os.machine, machines[i]->name))
3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833
            continue;

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

    virCapabilitiesFreeMachines(machines, nmachines);

    return 0;
}

3834 3835
int
qemudCanonicalizeMachine(struct qemud_driver *driver, virDomainDefPtr def)
3836 3837 3838 3839 3840 3841
{
    char *canonical = NULL;
    int i;

    for (i = 0; i < driver->caps->nguests; i++) {
        virCapsGuestPtr guest = driver->caps->guests[i];
3842
        virCapsGuestDomainInfoPtr info;
3843 3844 3845
        int j;

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

3848 3849 3850 3851 3852 3853 3854 3855 3856
            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;
3857 3858
        }

3859 3860 3861 3862
        info = &guest->arch.defaultInfo;

        if (info->emulator && STREQ(info->emulator, def->emulator)) {
            if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
3863 3864 3865 3866
                return -1;
            goto out;
        }
    }
3867 3868 3869 3870

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

3871 3872 3873 3874 3875 3876 3877
out:
    if (canonical) {
        VIR_FREE(def->os.machine);
        def->os.machine = canonical;
    }
    return 0;
}
D
Daniel P. Berrange 已提交
3878

3879
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
3880
    struct qemud_driver *driver = conn->privateData;
3881
    virDomainDefPtr def;
3882
    virDomainObjPtr vm = NULL;
3883
    virDomainPtr dom = NULL;
3884
    virDomainEventPtr event = NULL;
3885
    int dupVM;
3886

3887
    qemuDriverLock(driver);
3888
    if (!(def = virDomainDefParseString(driver->caps, xml,
3889
                                        VIR_DOMAIN_XML_INACTIVE)))
3890
        goto cleanup;
3891

3892
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
3893 3894
        goto cleanup;

3895 3896
    if ((dupVM = virDomainObjIsDuplicate(&driver->domains, def, 0)) < 0)
        goto cleanup;
3897

3898
    if (qemudCanonicalizeMachine(driver, def) < 0)
3899 3900
        goto cleanup;

3901
    if (qemuDomainAssignPCIAddresses(def) < 0)
3902 3903
        goto cleanup;

3904
    if (!(vm = virDomainAssignDef(driver->caps,
3905
                                  &driver->domains,
3906
                                  def, false))) {
3907
        goto cleanup;
3908
    }
3909
    def = NULL;
3910
    vm->persistent = 1;
3911

3912
    if (virDomainSaveConfig(driver->configDir,
3913
                            vm->newDef ? vm->newDef : vm->def) < 0) {
3914 3915
        virDomainRemoveInactive(&driver->domains,
                                vm);
3916
        vm = NULL;
3917
        goto cleanup;
3918 3919
    }

3920 3921
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
3922
                                     !dupVM ?
3923 3924
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
3925

3926
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
3927
    if (dom) dom->id = vm->def->id;
3928 3929

cleanup:
3930
    virDomainDefFree(def);
3931 3932
    if (vm)
        virDomainObjUnlock(vm);
3933 3934
    if (event)
        qemuDomainEventQueue(driver, event);
3935
    qemuDriverUnlock(driver);
3936
    return dom;
D
Daniel P. Berrange 已提交
3937 3938
}

3939
static int qemudDomainUndefine(virDomainPtr dom) {
3940 3941
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3942
    virDomainEventPtr event = NULL;
3943
    int ret = -1;
D
Daniel P. Berrange 已提交
3944

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

D
Daniel P. Berrange 已提交
3948
    if (!vm) {
3949 3950
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3951 3952
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
3953
        goto cleanup;
D
Daniel P. Berrange 已提交
3954 3955
    }

D
Daniel P. Berrange 已提交
3956
    if (virDomainObjIsActive(vm)) {
3957 3958
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot delete active domain"));
3959
        goto cleanup;
D
Daniel P. Berrange 已提交
3960 3961
    }

3962
    if (!vm->persistent) {
3963
        qemuReportError(VIR_ERR_OPERATION_INVALID,
3964
                        "%s", _("cannot undefine transient domain"));
3965
        goto cleanup;
3966 3967
    }

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

3971 3972 3973
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
3974

3975 3976
    virDomainRemoveInactive(&driver->domains,
                            vm);
3977
    vm = NULL;
3978
    ret = 0;
D
Daniel P. Berrange 已提交
3979

3980
cleanup:
3981 3982
    if (vm)
        virDomainObjUnlock(vm);
3983 3984
    if (event)
        qemuDomainEventQueue(driver, event);
3985
    qemuDriverUnlock(driver);
3986
    return ret;
D
Daniel P. Berrange 已提交
3987 3988
}

3989

3990 3991
static int qemudDomainAttachDevice(virDomainPtr dom,
                                   const char *xml)
3992
{
3993 3994 3995
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
3996
    virBitmapPtr qemuCaps = NULL;
3997
    virCgroupPtr cgroup = NULL;
3998
    int ret = -1;
3999

4000 4001 4002 4003 4004 4005 4006
    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);
4007 4008 4009
        goto cleanup;
    }

4010 4011
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;
4012

4013 4014 4015 4016 4017
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot attach device on inactive domain"));
        goto endjob;
    }
4018

4019 4020 4021 4022
    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL)
        goto endjob;
4023

4024
    if (qemuCapsExtractVersionInfo(vm->def->emulator, vm->def->os.arch,
4025
                                   NULL,
4026
                                   &qemuCaps) < 0)
4027
        goto endjob;
4028

4029
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
4030 4031 4032 4033 4034 4035 4036 4037
        if (dev->data.disk->driverName != NULL &&
            !STREQ(dev->data.disk->driverName, "qemu")) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("unsupported driver name '%s' for disk '%s'"),
                            dev->data.disk->driverName, dev->data.disk->src);
            goto endjob;
        }

4038 4039 4040
        if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
            if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) !=0 ) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
E
Eric Blake 已提交
4041
                                _("Unable to find cgroup for %s"),
4042 4043 4044
                                vm->def->name);
                goto endjob;
            }
4045
            if (qemuSetupDiskCgroup(driver, vm, cgroup, dev->data.disk) < 0)
4046
                goto endjob;
4047 4048
        }

4049 4050 4051 4052 4053
        switch (dev->data.disk->device) {
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
        case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
            ret = qemuDomainChangeEjectableMedia(driver, vm,
                                                 dev->data.disk,
4054
                                                 qemuCaps,
4055 4056 4057 4058
                                                 false);
            if (ret == 0)
                dev->data.disk = NULL;
            break;
4059

4060 4061 4062
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
                ret = qemuDomainAttachUsbMassstorageDevice(driver, vm,
4063
                                                           dev->data.disk, qemuCaps);
4064 4065 4066 4067
                if (ret == 0)
                    dev->data.disk = NULL;
            } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
                ret = qemuDomainAttachPciDiskDevice(driver, vm,
4068
                                                    dev->data.disk, qemuCaps);
4069 4070 4071 4072
                if (ret == 0)
                    dev->data.disk = NULL;
            } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI) {
                ret = qemuDomainAttachSCSIDisk(driver, vm,
4073
                                               dev->data.disk, qemuCaps);
4074 4075 4076 4077 4078 4079 4080 4081 4082
                if (ret == 0)
                    dev->data.disk = NULL;
            } else {
                qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                _("disk bus '%s' cannot be hotplugged."),
                                virDomainDiskBusTypeToString(dev->data.disk->bus));
                /* fallthrough */
            }
            break;
4083

4084 4085 4086 4087 4088
        default:
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                            _("disk device type '%s' cannot be hotplugged"),
                            virDomainDiskDeviceTypeToString(dev->data.disk->device));
            /* Fallthrough */
4089
        }
4090
        if (ret != 0 && cgroup) {
4091
            if (qemuTeardownDiskCgroup(driver, vm, cgroup, dev->data.disk) < 0)
4092 4093
                VIR_WARN("Failed to teardown cgroup for disk path %s",
                         NULLSTR(dev->data.disk->src));
4094
        }
4095 4096 4097
    } else if (dev->type == VIR_DOMAIN_DEVICE_CONTROLLER) {
        if (dev->data.controller->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI) {
            ret = qemuDomainAttachPciControllerDevice(driver, vm,
4098
                                                      dev->data.controller, qemuCaps);
4099 4100 4101 4102 4103 4104 4105
            if (ret == 0)
                dev->data.controller = NULL;
        } else {
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                            _("disk controller bus '%s' cannot be hotplugged."),
                            virDomainControllerTypeToString(dev->data.controller->type));
            /* fallthrough */
4106
        }
4107 4108
    } else if (dev->type == VIR_DOMAIN_DEVICE_NET) {
        ret = qemuDomainAttachNetDevice(dom->conn, driver, vm,
4109
                                        dev->data.net, qemuCaps);
4110 4111 4112 4113
        if (ret == 0)
            dev->data.net = NULL;
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV) {
        ret = qemuDomainAttachHostDevice(driver, vm,
4114
                                         dev->data.hostdev, qemuCaps);
4115 4116
        if (ret == 0)
            dev->data.hostdev = NULL;
4117
    } else {
4118 4119 4120 4121
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("device type '%s' cannot be attached"),
                        virDomainDeviceTypeToString(dev->type));
        goto endjob;
4122 4123
    }

4124 4125 4126 4127 4128
    /* update domain status forcibly because the domain status may be changed
     * even if we attach the device failed. For example, a new controller may
     * be created.
     */
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
4129 4130 4131 4132 4133 4134 4135 4136 4137 4138
        ret = -1;

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

cleanup:
    if (cgroup)
        virCgroupFree(&cgroup);

4139
    qemuCapsFree(qemuCaps);
4140 4141 4142 4143
    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
4144 4145 4146
    return ret;
}

4147 4148 4149 4150 4151 4152 4153 4154
static int qemudDomainAttachDeviceFlags(virDomainPtr dom,
                                        const char *xml,
                                        unsigned int flags) {
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }
4155

4156 4157
    return qemudDomainAttachDevice(dom, xml);
}
4158

4159

4160 4161 4162 4163 4164 4165 4166
static int qemuDomainUpdateDeviceFlags(virDomainPtr dom,
                                       const char *xml,
                                       unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
4167
    virBitmapPtr qemuCaps = NULL;
4168 4169 4170
    virCgroupPtr cgroup = NULL;
    int ret = -1;
    bool force = (flags & VIR_DOMAIN_DEVICE_MODIFY_FORCE) != 0;
4171

4172 4173 4174 4175
    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_CURRENT |
                  VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG |
                  VIR_DOMAIN_DEVICE_MODIFY_FORCE, -1);
4176

4177 4178 4179
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify the persistent configuration of a domain"));
4180 4181 4182
        return -1;
    }

4183 4184 4185 4186 4187 4188 4189 4190
    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;
4191 4192
    }

4193 4194 4195 4196 4197 4198 4199
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot attach device on inactive domain"));
        goto endjob;
4200 4201
    }

4202 4203 4204 4205 4206
    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL)
        goto endjob;

4207
    if (qemuCapsExtractVersionInfo(vm->def->emulator, vm->def->os.arch,
4208
                                   NULL,
4209
                                   &qemuCaps) < 0)
4210
        goto endjob;
4211

4212 4213 4214 4215 4216
    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
        if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
            if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) !=0 ) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
E
Eric Blake 已提交
4217
                                _("Unable to find cgroup for %s"),
4218 4219 4220
                                vm->def->name);
                goto endjob;
            }
4221
            if (qemuSetupDiskCgroup(driver, vm, cgroup, dev->data.disk) < 0)
4222
                goto endjob;
4223 4224
        }

4225 4226 4227 4228 4229
        switch (dev->data.disk->device) {
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
        case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
            ret = qemuDomainChangeEjectableMedia(driver, vm,
                                                 dev->data.disk,
4230
                                                 qemuCaps,
4231 4232 4233 4234
                                                 force);
            if (ret == 0)
                dev->data.disk = NULL;
            break;
4235

4236

4237 4238 4239 4240 4241 4242
        default:
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                            _("disk bus '%s' cannot be updated."),
                            virDomainDiskBusTypeToString(dev->data.disk->bus));
            break;
        }
4243

4244
        if (ret != 0 && cgroup) {
4245
            if (qemuTeardownDiskCgroup(driver, vm, cgroup, dev->data.disk) < 0)
4246 4247 4248
                VIR_WARN("Failed to teardown cgroup for disk path %s",
                         NULLSTR(dev->data.disk->src));
        }
4249
        break;
4250 4251 4252

    case VIR_DOMAIN_DEVICE_GRAPHICS:
        ret = qemuDomainChangeGraphics(driver, vm, dev->data.graphics);
4253
        break;
4254

4255
    default:
4256
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4257 4258
                        _("device type '%s' cannot be updated"),
                        virDomainDeviceTypeToString(dev->type));
4259
        break;
4260 4261
    }

4262 4263 4264 4265 4266 4267 4268 4269 4270 4271
    if (!ret && virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
        ret = -1;

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

cleanup:
    if (cgroup)
        virCgroupFree(&cgroup);
4272

4273
    qemuCapsFree(qemuCaps);
4274 4275 4276 4277
    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
4278 4279 4280
    return ret;
}

4281

4282 4283
static int qemudDomainDetachDevice(virDomainPtr dom,
                                   const char *xml) {
4284 4285
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4286
    virBitmapPtr qemuCaps = NULL;
4287 4288
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;
4289

4290
    qemuDriverLock(driver);
4291
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4292
    if (!vm) {
4293 4294
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4295 4296
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4297
        goto cleanup;
4298 4299
    }

4300 4301 4302
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
4303
    if (!virDomainObjIsActive(vm)) {
4304 4305
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot detach device on inactive domain"));
4306
        goto endjob;
4307 4308
    }

4309
    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
4310
                                  VIR_DOMAIN_XML_INACTIVE);
4311
    if (dev == NULL)
4312
        goto endjob;
4313

4314
    if (qemuCapsExtractVersionInfo(vm->def->emulator, vm->def->os.arch,
4315
                                   NULL,
4316
                                   &qemuCaps) < 0)
4317
        goto endjob;
4318 4319

    if (dev->type == VIR_DOMAIN_DEVICE_DISK &&
4320 4321
        dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
        if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
4322
            ret = qemuDomainDetachPciDiskDevice(driver, vm, dev, qemuCaps);
4323 4324
        }
        else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI) {
4325
            ret = qemuDomainDetachDiskDevice(driver, vm, dev, qemuCaps);
W
Wen Congyang 已提交
4326 4327
        } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
            ret = qemuDomainDetachDiskDevice(driver, vm, dev, qemuCaps);
4328 4329
        }
        else {
4330
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
4331 4332
                            _("This type of disk cannot be hot unplugged"));
        }
4333
    } else if (dev->type == VIR_DOMAIN_DEVICE_NET) {
4334
        ret = qemuDomainDetachNetDevice(driver, vm, dev, qemuCaps);
4335 4336
    } else if (dev->type == VIR_DOMAIN_DEVICE_CONTROLLER) {
        if (dev->data.controller->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI) {
4337
            ret = qemuDomainDetachPciControllerDevice(driver, vm, dev,
4338
                                                      qemuCaps);
4339
        } else {
4340
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4341 4342
                            _("disk controller bus '%s' cannot be hotunplugged."),
                            virDomainControllerTypeToString(dev->data.controller->type));
4343 4344
            /* fallthrough */
        }
4345
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV) {
4346
        ret = qemuDomainDetachHostDevice(driver, vm, dev, qemuCaps);
4347
    } else {
4348
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
4349
                        "%s", _("This type of device cannot be hot unplugged"));
4350
    }
4351

4352
    if (!ret && virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
4353 4354
        ret = -1;

4355
endjob:
4356 4357
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
4358

4359
cleanup:
4360
    qemuCapsFree(qemuCaps);
4361
    virDomainDeviceDefFree(dev);
4362 4363
    if (vm)
        virDomainObjUnlock(vm);
4364
    qemuDriverUnlock(driver);
4365 4366 4367
    return ret;
}

4368 4369 4370 4371
static int qemudDomainDetachDeviceFlags(virDomainPtr dom,
                                        const char *xml,
                                        unsigned int flags) {
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
4372 4373
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify the persistent configuration of a domain"));
4374 4375 4376 4377 4378 4379
        return -1;
    }

    return qemudDomainDetachDevice(dom, xml);
}

4380
static int qemudDomainGetAutostart(virDomainPtr dom,
4381
                                   int *autostart) {
4382 4383 4384
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
4385

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

4390
    if (!vm) {
4391 4392
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4393 4394
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4395
        goto cleanup;
4396 4397 4398
    }

    *autostart = vm->autostart;
4399
    ret = 0;
4400

4401
cleanup:
4402 4403
    if (vm)
        virDomainObjUnlock(vm);
4404
    return ret;
4405 4406
}

4407
static int qemudDomainSetAutostart(virDomainPtr dom,
4408
                                   int autostart) {
4409 4410
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4411 4412
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
4413

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

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

4425
    if (!vm->persistent) {
4426
        qemuReportError(VIR_ERR_OPERATION_INVALID,
4427
                        "%s", _("cannot set autostart for transient domain"));
4428
        goto cleanup;
4429 4430
    }

4431 4432
    autostart = (autostart != 0);

4433
    if (vm->autostart != autostart) {
4434
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
4435
            goto cleanup;
4436
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
4437
            goto cleanup;
4438

4439 4440
        if (autostart) {
            int err;
4441

4442
            if ((err = virFileMakePath(driver->autostartDir))) {
4443
                virReportSystemError(err,
4444 4445
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
4446 4447
                goto cleanup;
            }
4448

4449
            if (symlink(configFile, autostartLink) < 0) {
4450
                virReportSystemError(errno,
4451 4452
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
4453 4454 4455 4456
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
4457
                virReportSystemError(errno,
4458 4459
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
4460 4461
                goto cleanup;
            }
4462 4463
        }

4464
        vm->autostart = autostart;
4465
    }
4466
    ret = 0;
4467

4468 4469 4470
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
4471 4472
    if (vm)
        virDomainObjUnlock(vm);
4473
    qemuDriverUnlock(driver);
4474
    return ret;
4475 4476
}

4477 4478 4479 4480 4481

static char *qemuGetSchedulerType(virDomainPtr dom,
                                  int *nparams)
{
    struct qemud_driver *driver = dom->conn->privateData;
4482
    char *ret = NULL;
4483

4484
    qemuDriverLock(driver);
4485
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
4486 4487
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup CPU controller is not mounted"));
4488
        goto cleanup;
4489 4490 4491 4492 4493 4494 4495
    }

    if (nparams)
        *nparams = 1;

    ret = strdup("posix");
    if (!ret)
4496
        virReportOOMError();
4497 4498 4499

cleanup:
    qemuDriverUnlock(driver);
4500 4501 4502
    return ret;
}

4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661
static int qemuDomainSetBlkioParameters(virDomainPtr dom,
                                         virBlkioParameterPtr params,
                                         int nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);
    qemuDriverLock(driver);
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
        qemuReportError(VIR_ERR_NO_SUPPORT, _("blkio cgroup isn't mounted"));
        goto cleanup;
    }

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

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

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

    ret = 0;
    for (i = 0; i < nparams; i++) {
        virBlkioParameterPtr param = &params[i];

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

            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);
            ret = -1;
        }
    }

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

static int qemuDomainGetBlkioParameters(virDomainPtr dom,
                                         virBlkioParameterPtr params,
                                         int *nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    unsigned int val;
    int ret = -1;
    int rc;

    virCheckFlags(0, -1);
    qemuDriverLock(driver);

    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
        qemuReportError(VIR_ERR_NO_SUPPORT, _("blkio cgroup isn't mounted"));
        goto cleanup;
    }

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

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

    for (i = 0; i < *nparams; i++) {
        virBlkioParameterPtr param = &params[i];
        val = 0;
        param->value.ui = 0;
        param->type = VIR_DOMAIN_BLKIO_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 */
        }
    }

    ret = 0;

cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675

static int qemuDomainSetMemoryParameters(virDomainPtr dom,
                                         virMemoryParameterPtr params,
                                         int nparams,
                                         unsigned int flags ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;

    qemuDriverLock(driver);
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
4676 4677
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup memory controller is not mounted"));
4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728
        goto cleanup;
    }

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

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

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

    ret = 0;
    for (i = 0; i < nparams; i++) {
        virMemoryParameterPtr param = &params[i];

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

            rc = virCgroupSetMemoryHardLimit(group, params[i].value.ul);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to set memory hard_limit tunable"));
                ret = -1;
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT)) {
            int rc;
            if (param->type != VIR_DOMAIN_MEMORY_PARAM_ULLONG) {
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for memory soft_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

            rc = virCgroupSetMemorySoftLimit(group, params[i].value.ul);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to set memory soft_limit tunable"));
                ret = -1;
            }
4729
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT)) {
4730 4731 4732 4733 4734 4735 4736 4737
            int rc;
            if (param->type != VIR_DOMAIN_MEMORY_PARAM_ULLONG) {
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for swap_hard_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

4738
            rc = virCgroupSetMemSwapHardLimit(group, params[i].value.ul);
4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to set swap_hard_limit tunable"));
                ret = -1;
            }
        } 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;
        }
    }

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

4763 4764 4765 4766 4767 4768 4769 4770 4771
static int qemuDomainGetMemoryParameters(virDomainPtr dom,
                                         virMemoryParameterPtr params,
                                         int *nparams,
                                         unsigned int flags ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
4772
    unsigned long long val;
4773 4774 4775 4776 4777 4778
    int ret = -1;
    int rc;

    qemuDriverLock(driver);

    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
4779 4780
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup memory controller is not mounted"));
4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822
        goto cleanup;
    }

    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 memory parameters supported by cgroups */
        *nparams = QEMU_NB_MEM_PARAM;
        ret = 0;
        goto cleanup;
    }

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

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

    for (i = 0; i < *nparams; i++) {
        virMemoryParameterPtr param = &params[i];
        val = 0;
        param->value.ul = 0;
        param->type = VIR_DOMAIN_MEMORY_PARAM_ULLONG;

        switch(i) {
        case 0: /* fill memory hard limit here */
            rc = virCgroupGetMemoryHardLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory hard limit"));
4823
                goto cleanup;
4824 4825 4826 4827
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field memory hard limit too long for destination"));
4828
                goto cleanup;
4829 4830 4831 4832 4833 4834 4835 4836 4837
            }
            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"));
4838
                goto cleanup;
4839 4840 4841 4842
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field memory soft limit too long for destination"));
4843
                goto cleanup;
4844 4845 4846 4847 4848
            }
            param->value.ul = val;
            break;

        case 2: /* fill swap hard limit here */
4849
            rc = virCgroupGetMemSwapHardLimit(group, &val);
4850 4851 4852
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get swap hard limit"));
4853
                goto cleanup;
4854
            }
4855
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT) == NULL) {
4856 4857
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field swap hard limit too long for destination"));
4858
                goto cleanup;
4859 4860 4861 4862 4863 4864 4865 4866 4867 4868
            }
            param->value.ul = val;
            break;

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

4869 4870
    ret = 0;

4871 4872 4873 4874 4875 4876 4877 4878 4879
cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

4880 4881 4882 4883 4884 4885 4886 4887 4888 4889
static int qemuSetSchedulerParameters(virDomainPtr dom,
                                      virSchedParameterPtr params,
                                      int nparams)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;

4890
    qemuDriverLock(driver);
4891
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
4892 4893
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup CPU controller is not mounted"));
4894
        goto cleanup;
4895 4896 4897 4898 4899
    }

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

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

    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
4906 4907
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find cgroup for domain %s"), vm->def->name);
4908 4909 4910 4911 4912 4913 4914 4915 4916
        goto cleanup;
    }

    for (i = 0; i < nparams; i++) {
        virSchedParameterPtr param = &params[i];

        if (STREQ(param->field, "cpu_shares")) {
            int rc;
            if (param->type != VIR_DOMAIN_SCHED_FIELD_ULLONG) {
4917 4918
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for cpu_shares tunable, expected a 'ullong'"));
4919 4920 4921 4922 4923
                goto cleanup;
            }

            rc = virCgroupSetCpuShares(group, params[i].value.ul);
            if (rc != 0) {
4924
                virReportSystemError(-rc, "%s",
4925 4926 4927 4928
                                     _("unable to set cpu shares tunable"));
                goto cleanup;
            }
        } else {
4929 4930
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Invalid parameter `%s'"), param->field);
4931 4932 4933 4934 4935 4936 4937 4938 4939
            goto cleanup;
        }
    }
    ret = 0;

cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
4940
    qemuDriverUnlock(driver);
4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954
    return ret;
}

static int qemuGetSchedulerParameters(virDomainPtr dom,
                                      virSchedParameterPtr params,
                                      int *nparams)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    unsigned long long val;
    int ret = -1;
    int rc;

4955
    qemuDriverLock(driver);
4956
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
4957 4958
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup CPU controller is not mounted"));
4959
        goto cleanup;
4960 4961 4962
    }

    if ((*nparams) != 1) {
4963 4964
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
4965
        goto cleanup;
4966 4967 4968 4969 4970
    }

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

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

    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
4977 4978
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find cgroup for domain %s"), vm->def->name);
4979 4980 4981 4982 4983
        goto cleanup;
    }

    rc = virCgroupGetCpuShares(group, &val);
    if (rc != 0) {
4984
        virReportSystemError(-rc, "%s",
4985 4986 4987 4988 4989
                             _("unable to get cpu shares tunable"));
        goto cleanup;
    }
    params[0].value.ul = val;
    params[0].type = VIR_DOMAIN_SCHED_FIELD_ULLONG;
C
Chris Lalancette 已提交
4990
    if (virStrcpyStatic(params[0].field, "cpu_shares") == NULL) {
4991 4992
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Field cpu_shares too long for destination"));
C
Chris Lalancette 已提交
4993 4994
        goto cleanup;
    }
4995 4996 4997 4998 4999 5000 5001

    ret = 0;

cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
5002
    qemuDriverUnlock(driver);
5003 5004 5005 5006
    return ret;
}


5007 5008 5009 5010 5011 5012 5013 5014 5015
/* 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)
{
5016
    struct qemud_driver *driver = dom->conn->privateData;
5017
    int i, ret = -1;
5018
    virDomainObjPtr vm;
5019
    virDomainDiskDefPtr disk = NULL;
5020

5021
    qemuDriverLock(driver);
5022
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5023
    qemuDriverUnlock(driver);
5024
    if (!vm) {
5025 5026
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5027 5028
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5029
        goto cleanup;
5030
    }
5031 5032 5033 5034

    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
5035
    if (!virDomainObjIsActive (vm)) {
5036 5037
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
5038
        goto endjob;
5039 5040
    }

5041 5042 5043 5044 5045 5046 5047 5048
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

    if (!disk) {
5049 5050
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path: %s"), path);
5051
        goto endjob;
5052 5053
    }

5054
    if (!disk->info.alias) {
5055 5056
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("missing disk device alias name for %s"), disk->dst);
5057
        goto endjob;
5058
    }
5059

5060
    qemuDomainObjPrivatePtr priv = vm->privateData;
5061 5062
    qemuDomainObjEnterMonitor(vm);
    ret = qemuMonitorGetBlockStatsInfo(priv->mon,
5063
                                       disk->info.alias,
5064 5065 5066 5067 5068 5069
                                       &stats->rd_req,
                                       &stats->rd_bytes,
                                       &stats->wr_req,
                                       &stats->wr_bytes,
                                       &stats->errs);
    qemuDomainObjExitMonitor(vm);
5070

5071
endjob:
5072 5073
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
5074

5075
cleanup:
5076 5077
    if (vm)
        virDomainObjUnlock(vm);
5078
    return ret;
5079 5080
}

5081
#ifdef __linux__
5082 5083 5084 5085 5086
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
5087 5088
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
5089
    int i;
5090
    int ret = -1;
5091

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

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

D
Daniel P. Berrange 已提交
5104
    if (!virDomainObjIsActive(vm)) {
5105 5106
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
5107
        goto cleanup;
5108 5109 5110
    }

    /* Check the path is one of the domain's network interfaces. */
5111 5112
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
5113 5114 5115 5116
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
5117 5118
    }

5119
    if (ret == 0)
5120
        ret = linuxDomainInterfaceStats(path, stats);
5121
    else
5122 5123
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path, '%s' is not a known interface"), path);
5124

5125
cleanup:
5126 5127
    if (vm)
        virDomainObjUnlock(vm);
5128 5129
    return ret;
}
5130
#else
5131 5132 5133 5134
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
5135
{
5136 5137
    qemuReportError(VIR_ERR_NO_SUPPORT,
                    "%s", __FUNCTION__);
5138 5139
    return -1;
}
5140
#endif
5141

5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157
static int
qemudDomainMemoryStats (virDomainPtr dom,
                        struct _virDomainMemoryStat *stats,
                        unsigned int nr_stats)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned int ret = -1;

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

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

5163 5164 5165
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

5166 5167 5168
    if (virDomainObjIsActive(vm)) {
        qemuDomainObjPrivatePtr priv = vm->privateData;
        qemuDomainObjEnterMonitor(vm);
5169
        ret = qemuMonitorGetMemoryStats(priv->mon, stats, nr_stats);
5170 5171
        qemuDomainObjExitMonitor(vm);
    } else {
5172 5173
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
5174 5175
    }

5176 5177 5178
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;

5179 5180 5181 5182 5183 5184
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

5185 5186 5187 5188 5189 5190 5191
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
                      unsigned int flags ATTRIBUTE_UNUSED)
{
5192 5193 5194
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
5195

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

5200
    if (!vm) {
5201 5202
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5203 5204
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5205
        goto cleanup;
5206 5207 5208
    }

    if (!path || path[0] == '\0') {
5209 5210
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("NULL or empty path"));
5211
        goto cleanup;
5212 5213 5214
    }

    /* Check the path belongs to this domain. */
5215 5216
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
5217 5218 5219 5220
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
5221 5222
    }

5223 5224 5225 5226 5227
    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) {
5228 5229
            virReportSystemError(errno,
                                 _("%s: failed to open"), path);
5230 5231
            goto cleanup;
        }
5232

5233 5234 5235 5236 5237 5238
        /* 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) {
5239 5240
            virReportSystemError(errno,
                                 _("%s: failed to seek or read"), path);
5241 5242 5243 5244 5245
            goto cleanup;
        }

        ret = 0;
    } else {
5246 5247
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("invalid path"));
5248 5249
    }

5250
cleanup:
5251
    VIR_FORCE_CLOSE(fd);
5252 5253
    if (vm)
        virDomainObjUnlock(vm);
5254 5255 5256
    return ret;
}

R
Richard W.M. Jones 已提交
5257 5258 5259 5260 5261 5262
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
5263 5264
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
5265
    char *tmp = NULL;
R
Richard W.M. Jones 已提交
5266 5267
    int fd = -1, ret = -1;

5268
    qemuDriverLock(driver);
5269
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5270
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
5271 5272

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

5280
    if (flags != VIR_MEMORY_VIRTUAL && flags != VIR_MEMORY_PHYSICAL) {
5281 5282
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("flags parameter must be VIR_MEMORY_VIRTUAL or VIR_MEMORY_PHYSICAL"));
5283
        goto cleanup;
R
Richard W.M. Jones 已提交
5284 5285
    }

5286 5287 5288
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
5289
    if (!virDomainObjIsActive(vm)) {
5290 5291
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
5292
        goto endjob;
R
Richard W.M. Jones 已提交
5293 5294
    }

5295
    if (virAsprintf(&tmp, "%s/qemu.mem.XXXXXX", driver->cacheDir) < 0) {
5296
        virReportOOMError();
5297
        goto endjob;
5298 5299
    }

R
Richard W.M. Jones 已提交
5300 5301
    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
5302 5303
        virReportSystemError(errno,
                             _("mkstemp(\"%s\") failed"), tmp);
5304
        goto endjob;
R
Richard W.M. Jones 已提交
5305 5306
    }

5307
    qemuDomainObjPrivatePtr priv = vm->privateData;
5308
    qemuDomainObjEnterMonitor(vm);
5309
    if (flags == VIR_MEMORY_VIRTUAL) {
5310 5311
        if (qemuMonitorSaveVirtualMemory(priv->mon, offset, size, tmp) < 0) {
            qemuDomainObjExitMonitor(vm);
5312
            goto endjob;
5313
        }
5314
    } else {
5315 5316
        if (qemuMonitorSavePhysicalMemory(priv->mon, offset, size, tmp) < 0) {
            qemuDomainObjExitMonitor(vm);
5317
            goto endjob;
5318
        }
R
Richard W.M. Jones 已提交
5319
    }
5320
    qemuDomainObjExitMonitor(vm);
R
Richard W.M. Jones 已提交
5321 5322 5323

    /* Read the memory file into buffer. */
    if (saferead (fd, buffer, size) == (ssize_t) -1) {
5324 5325 5326
        virReportSystemError(errno,
                             _("failed to read temporary file "
                               "created with template %s"), tmp);
5327
        goto endjob;
R
Richard W.M. Jones 已提交
5328 5329 5330
    }

    ret = 0;
5331

5332
endjob:
5333 5334
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
5335

5336
cleanup:
5337
    VIR_FREE(tmp);
5338
    VIR_FORCE_CLOSE(fd);
R
Richard W.M. Jones 已提交
5339
    unlink (tmp);
5340 5341
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
5342 5343 5344
    return ret;
}

5345

5346 5347 5348 5349 5350 5351 5352 5353 5354 5355
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;
    virStorageFileMetadata meta;
5356
    virDomainDiskDefPtr disk = NULL;
5357 5358
    struct stat sb;
    int i;
5359
    int format;
5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383

    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)) {
5384
            disk = vm->def->disks[i];
5385 5386 5387 5388
            break;
        }
    }

5389
    if (!disk) {
5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403
        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 */
5404 5405 5406 5407 5408 5409 5410 5411
    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 {
5412 5413 5414 5415 5416 5417 5418
        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);
5419
            goto cleanup;
5420
        }
5421 5422 5423 5424 5425
    }

    if (virStorageFileGetMetadataFromFD(path, fd,
                                        format,
                                        &meta) < 0)
5426 5427 5428 5429 5430 5431 5432 5433 5434 5435
        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)) {
5436
#ifndef WIN32
5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464
        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 */
    if (meta.capacity)
        info->capacity = meta.capacity;

5465
    /* Set default value .. */
5466 5467
    info->allocation = info->physical;

5468 5469 5470
    /* ..but if guest is running & not using raw
       disk format and on a block device, then query
       highest allocated extent from QEMU */
5471
    if (disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
5472
        format != VIR_STORAGE_FILE_RAW &&
5473 5474 5475 5476
        S_ISBLK(sb.st_mode)) {
        qemuDomainObjPrivatePtr priv = vm->privateData;
        if (qemuDomainObjBeginJob(vm) < 0)
            goto cleanup;
5477 5478 5479 5480 5481 5482 5483 5484 5485
        if (!virDomainObjIsActive(vm))
            ret = 0;
        else {
            qemuDomainObjEnterMonitor(vm);
            ret = qemuMonitorGetBlockExtent(priv->mon,
                                            disk->info.alias,
                                            &info->allocation);
            qemuDomainObjExitMonitor(vm);
        }
5486 5487 5488 5489 5490 5491

        if (qemuDomainObjEndJob(vm) == 0)
            vm = NULL;
    } else {
        ret = 0;
    }
5492 5493

cleanup:
5494
    VIR_FORCE_CLOSE(fd);
5495 5496 5497 5498 5499 5500
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


5501
static int
5502 5503 5504 5505
qemuDomainEventRegister(virConnectPtr conn,
                        virConnectDomainEventCallback callback,
                        void *opaque,
                        virFreeCallback freecb)
5506
{
5507 5508 5509
    struct qemud_driver *driver = conn->privateData;
    int ret;

5510
    qemuDriverLock(driver);
5511 5512
    ret = virDomainEventCallbackListAdd(conn, driver->domainEventCallbacks,
                                        callback, opaque, freecb);
5513
    qemuDriverUnlock(driver);
5514

5515
    return ret;
5516 5517
}

5518

5519
static int
5520 5521
qemuDomainEventDeregister(virConnectPtr conn,
                          virConnectDomainEventCallback callback)
5522
{
5523 5524 5525
    struct qemud_driver *driver = conn->privateData;
    int ret;

5526
    qemuDriverLock(driver);
5527 5528 5529 5530 5531 5532
    if (driver->domainEventDispatching)
        ret = virDomainEventCallbackListMarkDelete(conn, driver->domainEventCallbacks,
                                                   callback);
    else
        ret = virDomainEventCallbackListRemove(conn, driver->domainEventCallbacks,
                                               callback);
5533
    qemuDriverUnlock(driver);
5534

5535
    return ret;
5536 5537
}

5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580

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,
                                          driver->domainEventCallbacks,
                                          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);
    if (driver->domainEventDispatching)
        ret = virDomainEventCallbackListMarkDeleteID(conn, driver->domainEventCallbacks,
                                                     callbackID);
    else
        ret = virDomainEventCallbackListRemoveID(conn, driver->domainEventCallbacks,
                                                 callbackID);
    qemuDriverUnlock(driver);

    return ret;
}


D
Daniel Veillard 已提交
5581 5582
/* Migration support. */

C
Chris Lalancette 已提交
5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597
/* 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;
5598

C
Chris Lalancette 已提交
5599
    if (!dom_xml) {
5600 5601
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
C
Chris Lalancette 已提交
5602 5603 5604
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
5605
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
5606 5607 5608 5609
                         "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
        goto cleanup;
    }
    if (st == NULL) {
5610 5611
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("tunnelled migration requested but NULL stream passed"));
C
Chris Lalancette 已提交
5612 5613 5614
        goto cleanup;
    }

5615 5616 5617 5618
    qemuDriverLock(driver);
    ret = qemuMigrationPrepareTunnel(driver, dconn, st,
                                     dname, dom_xml);
    qemuDriverUnlock(driver);
5619

C
Chris Lalancette 已提交
5620 5621 5622 5623
cleanup:
    return ret;
}

D
Daniel Veillard 已提交
5624 5625 5626 5627
/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
5628
static int ATTRIBUTE_NONNULL (5)
D
Daniel Veillard 已提交
5629 5630 5631 5632 5633
qemudDomainMigratePrepare2 (virConnectPtr dconn,
                            char **cookie ATTRIBUTE_UNUSED,
                            int *cookielen ATTRIBUTE_UNUSED,
                            const char *uri_in,
                            char **uri_out,
C
Chris Lalancette 已提交
5634
                            unsigned long flags,
D
Daniel Veillard 已提交
5635 5636 5637 5638
                            const char *dname,
                            unsigned long resource ATTRIBUTE_UNUSED,
                            const char *dom_xml)
{
5639
    struct qemud_driver *driver = dconn->privateData;
5640
    int ret = -1;
5641

C
Chris Lalancette 已提交
5642 5643 5644 5645 5646 5647 5648 5649 5650
    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, -1);

5651
    *uri_out = NULL;
D
Daniel Veillard 已提交
5652

5653
    qemuDriverLock(driver);
C
Chris Lalancette 已提交
5654 5655 5656 5657
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
5658 5659
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Tunnelled migration requested but invalid RPC method called"));
C
Chris Lalancette 已提交
5660 5661 5662
        goto cleanup;
    }

D
Daniel Veillard 已提交
5663
    if (!dom_xml) {
5664 5665
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
5666
        goto cleanup;
D
Daniel Veillard 已提交
5667 5668
    }

5669 5670 5671
    ret = qemuMigrationPrepareDirect(driver, dconn,
                                     uri_in, uri_out,
                                     dname, dom_xml);
D
Daniel Veillard 已提交
5672

5673 5674 5675 5676
cleanup:
    qemuDriverUnlock(driver);
    return ret;
}
C
Chris Lalancette 已提交
5677

D
Daniel Veillard 已提交
5678

5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691
/* Perform is the second step, and it runs on the source host. */
static int
qemudDomainMigratePerform (virDomainPtr dom,
                           const char *cookie ATTRIBUTE_UNUSED,
                           int cookielen ATTRIBUTE_UNUSED,
                           const char *uri,
                           unsigned long flags,
                           const char *dname,
                           unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
5692

5693 5694 5695 5696 5697 5698 5699 5700
    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, -1);
C
Chris Lalancette 已提交
5701

5702
    qemuDriverLock(driver);
5703
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel Veillard 已提交
5704
    if (!vm) {
5705 5706
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5707 5708
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5709
        goto cleanup;
D
Daniel Veillard 已提交
5710 5711
    }

5712 5713 5714
    ret = qemuMigrationPerform(driver, dom->conn, vm,
                               uri, flags,
                               dname, resource);
5715

5716
cleanup:
5717
    qemuDriverUnlock(driver);
5718
    return ret;
D
Daniel Veillard 已提交
5719 5720
}

5721

D
Daniel Veillard 已提交
5722 5723 5724 5725 5726 5727 5728
/* 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 已提交
5729
                           unsigned long flags,
D
Daniel Veillard 已提交
5730 5731
                           int retcode)
{
5732 5733 5734
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
5735
    virErrorPtr orig_err;
D
Daniel Veillard 已提交
5736

C
Chris Lalancette 已提交
5737 5738 5739 5740 5741 5742 5743 5744 5745
    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, NULL);

5746 5747 5748
    /* Migration failed. Save the current error so nothing squashes it */
    orig_err = virSaveLastError();

5749
    qemuDriverLock(driver);
5750
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
5751
    if (!vm) {
5752 5753
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
5754
        goto cleanup;
D
Daniel Veillard 已提交
5755 5756
    }

5757
    dom = qemuMigrationFinish(driver, dconn, vm, flags, retcode);
5758

5759
cleanup:
5760 5761 5762 5763
    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }
5764
    qemuDriverUnlock(driver);
5765
    return dom;
D
Daniel Veillard 已提交
5766 5767
}

5768

5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784
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;

5785
    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE);
5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802
    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) {
5803 5804
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("device %s is not a PCI device"), dev->name);
5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817
        goto out;
    }

    ret = 0;
out:
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
qemudNodeDeviceDettach (virNodeDevicePtr dev)
{
5818
    struct qemud_driver *driver = dev->conn->privateData;
5819 5820 5821 5822 5823 5824 5825
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

5826
    pci = pciGetDevice(domain, bus, slot, function);
5827 5828 5829
    if (!pci)
        return -1;

5830 5831
    qemuDriverLock(driver);
    if (pciDettachDevice(pci, driver->activePciHostdevs) < 0)
5832 5833 5834 5835
        goto out;

    ret = 0;
out:
5836
    qemuDriverUnlock(driver);
5837
    pciFreeDevice(pci);
5838 5839 5840 5841 5842 5843
    return ret;
}

static int
qemudNodeDeviceReAttach (virNodeDevicePtr dev)
{
5844
    struct qemud_driver *driver = dev->conn->privateData;
5845 5846 5847 5848 5849 5850 5851
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

5852
    pci = pciGetDevice(domain, bus, slot, function);
5853 5854 5855
    if (!pci)
        return -1;

5856 5857
    qemuDriverLock(driver);
    if (pciReAttachDevice(pci, driver->activePciHostdevs) < 0)
5858 5859 5860 5861
        goto out;

    ret = 0;
out:
5862
    qemuDriverUnlock(driver);
5863
    pciFreeDevice(pci);
5864 5865 5866 5867 5868 5869
    return ret;
}

static int
qemudNodeDeviceReset (virNodeDevicePtr dev)
{
5870
    struct qemud_driver *driver = dev->conn->privateData;
5871 5872 5873 5874 5875 5876 5877
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

5878
    pci = pciGetDevice(domain, bus, slot, function);
5879 5880 5881
    if (!pci)
        return -1;

5882 5883
    qemuDriverLock(driver);

5884
    if (pciResetDevice(pci, driver->activePciHostdevs, NULL) < 0)
5885 5886 5887 5888
        goto out;

    ret = 0;
out:
5889
    qemuDriverUnlock(driver);
5890
    pciFreeDevice(pci);
5891 5892 5893
    return ret;
}

5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904
static int
qemuCPUCompare(virConnectPtr conn,
               const char *xmlDesc,
               unsigned int flags ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = conn->privateData;
    int ret = VIR_CPU_COMPARE_ERROR;

    qemuDriverLock(driver);

    if (!driver->caps || !driver->caps->host.cpu) {
5905 5906
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        "%s", _("cannot get host CPU capabilities"));
5907 5908
    }
    else
5909
        ret = cpuCompareXML(driver->caps->host.cpu, xmlDesc);
5910 5911 5912 5913 5914 5915

    qemuDriverUnlock(driver);

    return ret;
}

5916

5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929
static char *
qemuCPUBaseline(virConnectPtr conn ATTRIBUTE_UNUSED,
                const char **xmlCPUs,
                unsigned int ncpus,
                unsigned int flags ATTRIBUTE_UNUSED)
{
    char *cpu;

    cpu = cpuBaselineXML(xmlCPUs, ncpus, NULL, 0);

    return cpu;
}

5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952

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)) {
        if (priv->jobActive) {
5953 5954
            struct timeval now;

5955
            memcpy(info, &priv->jobInfo, sizeof(*info));
5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966

            /* 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
             */
            if (gettimeofday(&now, NULL) < 0) {
                virReportSystemError(errno, "%s",
                                     _("cannot get time of day"));
                goto cleanup;
            }
5967
            info->timeElapsed = timeval_to_ms(now) - priv->jobStart;
5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986
        } 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;
}


5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008
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;
    }

    priv = vm->privateData;

    if (virDomainObjIsActive(vm)) {
        if (priv->jobActive) {
            VIR_DEBUG("Requesting cancellation of job on vm %s", vm->def->name);
6009
            priv->jobSignals |= QEMU_JOB_SIGNAL_CANCEL;
6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029
        } else {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("no job is active on the domain"));
            goto cleanup;
        }
    } else {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

    ret = 0;

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


6030 6031 6032 6033 6034 6035 6036 6037 6038 6039
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;

6040
    virCheckFlags(0, -1);
6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060

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

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

    priv = vm->privateData;

6061
    if (priv->jobActive != QEMU_JOB_MIGRATION_OUT) {
6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not being migrated"));
        goto cleanup;
    }

    VIR_DEBUG("Requesting migration downtime change to %llums", downtime);
    priv->jobSignals |= QEMU_JOB_SIGNAL_MIGRATE_DOWNTIME;
    priv->jobSignalsData.migrateDowntime = downtime;
    ret = 0;

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

6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 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
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);

    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;

    if (priv->jobActive != QEMU_JOB_MIGRATION_OUT) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not being migrated"));
        goto cleanup;
    }

    VIR_DEBUG("Requesting migration speed change to %luMbs", bandwidth);
    priv->jobSignals |= QEMU_JOB_SIGNAL_MIGRATE_SPEED;
    priv->jobSignalsData.migrateBandwidth = bandwidth;
    ret = 0;

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

C
Chris Lalancette 已提交
6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141
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;
}

6142 6143 6144
static int qemuDomainSnapshotWriteMetadata(virDomainObjPtr vm,
                                           virDomainSnapshotObjPtr snapshot,
                                           char *snapshotDir)
C
Chris Lalancette 已提交
6145 6146 6147 6148 6149 6150 6151 6152 6153 6154
{
    int fd = -1;
    char *newxml = NULL;
    int ret = -1;
    char *snapDir = NULL;
    char *snapFile = NULL;
    int err;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    virUUIDFormat(vm->def->uuid, uuidstr);
6155
    newxml = virDomainSnapshotDefFormat(uuidstr, snapshot->def, 1);
C
Chris Lalancette 已提交
6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171
    if (newxml == NULL) {
        virReportOOMError();
        return -1;
    }

    if (virAsprintf(&snapDir, "%s/%s", snapshotDir, vm->def->name) < 0) {
        virReportOOMError();
        goto cleanup;
    }
    err = virFileMakePath(snapDir);
    if (err < 0) {
        virReportSystemError(err, _("cannot create snapshot directory '%s'"),
                             snapDir);
        goto cleanup;
    }

6172
    if (virAsprintf(&snapFile, "%s/%s.xml", snapDir, snapshot->def->name) < 0) {
C
Chris Lalancette 已提交
6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193
        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);
6194
    VIR_FORCE_CLOSE(fd);
C
Chris Lalancette 已提交
6195 6196 6197
    return ret;
}

6198 6199
static int qemuDomainSnapshotSetCurrentActive(virDomainObjPtr vm,
                                              char *snapshotDir)
C
Chris Lalancette 已提交
6200 6201 6202 6203
{
    if (vm->current_snapshot) {
        vm->current_snapshot->def->active = 1;

6204 6205
        return qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                               snapshotDir);
C
Chris Lalancette 已提交
6206 6207 6208 6209 6210
    }

    return 0;
}

6211 6212
static int qemuDomainSnapshotSetCurrentInactive(virDomainObjPtr vm,
                                                char *snapshotDir)
C
Chris Lalancette 已提交
6213 6214 6215 6216
{
    if (vm->current_snapshot) {
        vm->current_snapshot->def->active = 0;

6217 6218
        return qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                               snapshotDir);
C
Chris Lalancette 已提交
6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237
    }

    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,
6238 6239
                            _("Disk '%s' does not support snapshotting"),
                            vm->def->disks[i]->src);
C
Chris Lalancette 已提交
6240 6241 6242 6243 6244 6245 6246
            return 0;
        }
    }

    return 1;
}

6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294
/* 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
6295 6296
qemuDomainSnapshotCreateActive(virConnectPtr conn,
                               struct qemud_driver *driver,
6297 6298 6299 6300 6301
                               virDomainObjPtr *vmptr,
                               virDomainSnapshotObjPtr snap)
{
    virDomainObjPtr vm = *vmptr;
    qemuDomainObjPrivatePtr priv = vm->privateData;
6302 6303
    bool resume = false;
    int ret = -1;
6304 6305 6306 6307

    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        return -1;

6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323
    if (vm->state == VIR_DOMAIN_RUNNING) {
        /* 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.
         */
        if (qemuProcessStopCPUs(driver, vm) < 0)
            goto cleanup;

        resume = true;
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto cleanup;
        }
    }

6324 6325 6326 6327
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    ret = qemuMonitorCreateSnapshot(priv->mon, snap->def->name);
    qemuDomainObjExitMonitorWithDriver(driver, vm);

6328 6329 6330 6331 6332 6333 6334 6335
cleanup:
    if (resume && virDomainObjIsActive(vm) &&
        qemuProcessStartCPUs(driver, vm, conn) < 0 &&
        virGetLastError() == NULL) {
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("resuming after snapshot failed"));
    }

6336 6337 6338 6339 6340 6341
    if (qemuDomainObjEndJob(vm) == 0)
        *vmptr = NULL;

    return ret;
}

C
Chris Lalancette 已提交
6342 6343
static virDomainSnapshotPtr qemuDomainSnapshotCreateXML(virDomainPtr domain,
                                                        const char *xmlDesc,
6344
                                                        unsigned int flags)
C
Chris Lalancette 已提交
6345 6346 6347 6348 6349 6350 6351 6352
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virDomainSnapshotDefPtr def;

6353 6354
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379
    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;

6380 6381
    snap->def->state = vm->state;

C
Chris Lalancette 已提交
6382 6383
    /* actually do the snapshot */
    if (!virDomainObjIsActive(vm)) {
6384
        if (qemuDomainSnapshotCreateInactive(vm, snap) < 0)
C
Chris Lalancette 已提交
6385 6386 6387
            goto cleanup;
    }
    else {
6388 6389
        if (qemuDomainSnapshotCreateActive(domain->conn, driver,
                                           &vm, snap) < 0)
6390
            goto cleanup;
C
Chris Lalancette 已提交
6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408
    }

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

6409 6410 6411
    if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                        driver->snapshotDir) < 0)
        /* qemuDomainSnapshotWriteMetadata set the error */
C
Chris Lalancette 已提交
6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424
        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,
6425
                                       unsigned int flags)
C
Chris Lalancette 已提交
6426 6427 6428 6429 6430
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

6431 6432
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452
    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,
6453
                                 unsigned int flags)
C
Chris Lalancette 已提交
6454 6455 6456 6457 6458
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

6459 6460
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481
    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,
6482
                                                           unsigned int flags)
C
Chris Lalancette 已提交
6483 6484 6485 6486 6487 6488
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;

6489 6490
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
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
    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,
6518
                                        unsigned int flags)
C
Chris Lalancette 已提交
6519 6520 6521 6522 6523
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

6524 6525
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545
    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,
6546
                                                      unsigned int flags)
C
Chris Lalancette 已提交
6547 6548 6549 6550 6551
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotPtr snapshot = NULL;

6552 6553
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579
    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;
}

static char *qemuDomainSnapshotDumpXML(virDomainSnapshotPtr snapshot,
6580
                                       unsigned int flags)
C
Chris Lalancette 已提交
6581 6582 6583 6584 6585 6586 6587
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *xml = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

6588 6589
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616
    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,
6617
                                      unsigned int flags)
C
Chris Lalancette 已提交
6618 6619 6620 6621 6622 6623 6624 6625 6626 6627
{
    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;

6628 6629
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660
    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;

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

    if (snap->def->state == VIR_DOMAIN_RUNNING
        || snap->def->state == VIR_DOMAIN_PAUSED) {

        if (virDomainObjIsActive(vm)) {
            priv = vm->privateData;
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
            rc = qemuMonitorLoadSnapshot(priv->mon, snap->def->name);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            if (rc < 0)
6661
                goto endjob;
C
Chris Lalancette 已提交
6662 6663
        }
        else {
6664
            if (qemuDomainSnapshotSetCurrentActive(vm, driver->snapshotDir) < 0)
6665
                goto endjob;
C
Chris Lalancette 已提交
6666

6667 6668
            rc = qemuProcessStart(snapshot->domain->conn, driver, vm, NULL,
                                  false, -1, NULL, VIR_VM_OP_CREATE);
6669
            qemuAuditDomainStart(vm, "from-snapshot", rc >= 0);
6670
            if (qemuDomainSnapshotSetCurrentInactive(vm, driver->snapshotDir) < 0)
6671
                goto endjob;
C
Chris Lalancette 已提交
6672
            if (rc < 0)
6673
                goto endjob;
C
Chris Lalancette 已提交
6674 6675 6676 6677 6678 6679
        }

        if (snap->def->state == VIR_DOMAIN_PAUSED) {
            /* qemu unconditionally starts the domain running again after
             * loadvm, so let's pause it to keep consistency
             */
6680
            rc = qemuProcessStopCPUs(driver, vm);
H
Hu Tao 已提交
6681
            if (rc < 0)
6682
                goto endjob;
C
Chris Lalancette 已提交
6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700
        }

        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)) {
6701
            qemuProcessStop(driver, vm, 0);
6702
            qemuAuditDomainStop(vm, "from-snapshot");
C
Chris Lalancette 已提交
6703 6704 6705
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STOPPED,
                                             VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT);
6706 6707 6708 6709
            if (!vm->persistent) {
                if (qemuDomainObjEndJob(vm) > 0)
                    virDomainRemoveInactive(&driver->domains, vm);
                vm = NULL;
6710
                goto cleanup;
6711
            }
C
Chris Lalancette 已提交
6712 6713
        }

6714
        if (qemuDomainSnapshotSetCurrentActive(vm, driver->snapshotDir) < 0)
6715
            goto endjob;
C
Chris Lalancette 已提交
6716 6717 6718 6719 6720 6721
    }

    vm->state = snap->def->state;

    ret = 0;

6722
endjob:
C
Chris Lalancette 已提交
6723 6724 6725
    if (vm && qemuDomainObjEndJob(vm) == 0)
        vm = NULL;

6726
cleanup:
C
Chris Lalancette 已提交
6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828
    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;
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
        /* 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,
6829
                                              const void *name ATTRIBUTE_UNUSED,
C
Chris Lalancette 已提交
6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850
                                              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);
    }
}

6851 6852 6853 6854 6855 6856 6857 6858 6859
struct snap_reparent {
    struct qemud_driver *driver;
    virDomainSnapshotObjPtr snap;
    virDomainObjPtr vm;
    int err;
};

static void
qemuDomainSnapshotReparentChildren(void *payload,
6860
                                   const void *name ATTRIBUTE_UNUSED,
6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887
                                   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 已提交
6888 6889 6890 6891 6892 6893 6894 6895 6896
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;
6897
    struct snap_reparent rep;
C
Chris Lalancette 已提交
6898

6899 6900
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

C
Chris Lalancette 已提交
6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917
    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;
    }

6918 6919 6920
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

C
Chris Lalancette 已提交
6921 6922 6923 6924 6925 6926 6927 6928
    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)
6929
            goto endjob;
6930 6931 6932 6933 6934 6935 6936 6937 6938
    } 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 已提交
6939 6940 6941 6942
    }

    ret = qemuDomainSnapshotDiscard(driver, vm, snap);

6943 6944 6945 6946
endjob:
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;

C
Chris Lalancette 已提交
6947 6948 6949 6950 6951 6952
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
6953

6954 6955 6956 6957 6958 6959 6960
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;
6961
    bool hmp;
6962

6963
    virCheckFlags(VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP, -1);
6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988

    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;

    if (!priv->monitor_warned) {
        VIR_INFO("Qemu monitor command '%s' executed; libvirt results may be unpredictable!",
                 cmd);
        priv->monitor_warned = 1;
    }

6989 6990
    hmp = !!(flags & VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP);

6991 6992 6993
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
6994
    ret = qemuMonitorArbitraryCommand(priv->mon, cmd, result, hmp);
6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007
    qemuDomainObjExitMonitorWithDriver(driver, vm);
    if (qemuDomainObjEndJob(vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

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

7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064

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

7065
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
7066 7067 7068 7069 7070 7071
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"),
                        NULLSTR(devname));
        goto cleanup;
    }

7072
    if (virFDStreamOpenFile(st, chr->source.data.file.path, O_RDWR) < 0)
7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083
        goto cleanup;

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


7084 7085 7086 7087 7088
static virDriver qemuDriver = {
    VIR_DRV_QEMU,
    "QEMU",
    qemudOpen, /* open */
    qemudClose, /* close */
D
Daniel Veillard 已提交
7089
    qemudSupportsFeature, /* supports_feature */
7090 7091
    qemudGetType, /* type */
    qemudGetVersion, /* version */
7092
    NULL, /* libvirtVersion (impl. in libvirt.c) */
7093
    virGetHostname, /* getHostname */
E
Eric Blake 已提交
7094
    qemuGetSysinfo, /* getSysinfo */
7095
    qemudGetMaxVCPUs, /* getMaxVcpus */
7096
    nodeGetInfo, /* nodeGetInfo */
7097 7098 7099
    qemudGetCapabilities, /* getCapabilities */
    qemudListDomains, /* listDomains */
    qemudNumDomains, /* numOfDomains */
7100
    qemudDomainCreate, /* domainCreateXML */
7101 7102 7103 7104 7105
    qemudDomainLookupByID, /* domainLookupByID */
    qemudDomainLookupByUUID, /* domainLookupByUUID */
    qemudDomainLookupByName, /* domainLookupByName */
    qemudDomainSuspend, /* domainSuspend */
    qemudDomainResume, /* domainResume */
7106
    qemudDomainShutdown, /* domainShutdown */
7107 7108 7109
    NULL, /* domainReboot */
    qemudDomainDestroy, /* domainDestroy */
    qemudDomainGetOSType, /* domainGetOSType */
7110
    qemudDomainGetMaxMemory, /* domainGetMaxMemory */
7111
    NULL, /* domainSetMaxMemory */
7112
    qemudDomainSetMemory, /* domainSetMemory */
7113
    qemudDomainSetMemoryFlags, /* domainSetMemoryFlags */
7114 7115
    qemuDomainSetMemoryParameters, /* domainSetMemoryParameters */
    qemuDomainGetMemoryParameters, /* domainGetMemoryParameters */
7116 7117
    qemuDomainSetBlkioParameters, /* domainSetBlkioParameters */
    qemuDomainGetBlkioParameters, /* domainGetBlkioParameters */
7118 7119 7120
    qemudDomainGetInfo, /* domainGetInfo */
    qemudDomainSave, /* domainSave */
    qemudDomainRestore, /* domainRestore */
P
Paolo Bonzini 已提交
7121
    qemudDomainCoreDump, /* domainCoreDump */
7122
    qemudDomainSetVcpus, /* domainSetVcpus */
7123 7124
    qemudDomainSetVcpusFlags, /* domainSetVcpusFlags */
    qemudDomainGetVcpusFlags, /* domainGetVcpusFlags */
7125 7126
    qemudDomainPinVcpu, /* domainPinVcpu */
    qemudDomainGetVcpus, /* domainGetVcpus */
7127
    qemudDomainGetMaxVcpus, /* domainGetMaxVcpus */
7128 7129
    qemudDomainGetSecurityLabel, /* domainGetSecurityLabel */
    qemudNodeGetSecurityModel, /* nodeGetSecurityModel */
7130
    qemudDomainDumpXML, /* domainDumpXML */
7131
    qemuDomainXMLFromNative, /* domainXmlFromNative */
7132
    qemuDomainXMLToNative, /* domainXMLToNative */
7133 7134
    qemudListDefinedDomains, /* listDefinedDomains */
    qemudNumDefinedDomains, /* numOfDefinedDomains */
7135
    qemudDomainStart, /* domainCreate */
7136
    qemudDomainStartWithFlags, /* domainCreateWithFlags */
7137 7138
    qemudDomainDefine, /* domainDefineXML */
    qemudDomainUndefine, /* domainUndefine */
7139
    qemudDomainAttachDevice, /* domainAttachDevice */
7140
    qemudDomainAttachDeviceFlags, /* domainAttachDeviceFlags */
7141
    qemudDomainDetachDevice, /* domainDetachDevice */
7142
    qemudDomainDetachDeviceFlags, /* domainDetachDeviceFlags */
7143
    qemuDomainUpdateDeviceFlags, /* domainUpdateDeviceFlags */
7144 7145
    qemudDomainGetAutostart, /* domainGetAutostart */
    qemudDomainSetAutostart, /* domainSetAutostart */
7146 7147 7148
    qemuGetSchedulerType, /* domainGetSchedulerType */
    qemuGetSchedulerParameters, /* domainGetSchedulerParameters */
    qemuSetSchedulerParameters, /* domainSetSchedulerParameters */
D
Daniel Veillard 已提交
7149 7150
    NULL, /* domainMigratePrepare (v1) */
    qemudDomainMigratePerform, /* domainMigratePerform */
7151
    NULL, /* domainMigrateFinish */
7152
    qemudDomainBlockStats, /* domainBlockStats */
7153
    qemudDomainInterfaceStats, /* domainInterfaceStats */
7154
    qemudDomainMemoryStats, /* domainMemoryStats */
7155
    qemudDomainBlockPeek, /* domainBlockPeek */
R
Richard W.M. Jones 已提交
7156
    qemudDomainMemoryPeek, /* domainMemoryPeek */
7157
    qemuDomainGetBlockInfo, /* domainGetBlockInfo */
7158 7159
    nodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    nodeGetFreeMemory,  /* getFreeMemory */
7160 7161
    qemuDomainEventRegister, /* domainEventRegister */
    qemuDomainEventDeregister, /* domainEventDeregister */
D
Daniel Veillard 已提交
7162 7163
    qemudDomainMigratePrepare2, /* domainMigratePrepare2 */
    qemudDomainMigrateFinish2, /* domainMigrateFinish2 */
7164 7165 7166
    qemudNodeDeviceDettach, /* nodeDeviceDettach */
    qemudNodeDeviceReAttach, /* nodeDeviceReAttach */
    qemudNodeDeviceReset, /* nodeDeviceReset */
C
Chris Lalancette 已提交
7167
    qemudDomainMigratePrepareTunnel, /* domainMigratePrepareTunnel */
7168 7169 7170 7171
    qemuIsEncrypted, /* isEncrypted */
    qemuIsSecure, /* isSecure */
    qemuDomainIsActive, /* domainIsActive */
    qemuDomainIsPersistent, /* domainIsPersistent */
7172
    qemuDomainIsUpdated, /* domainIsUpdated */
7173
    qemuCPUCompare, /* cpuCompare */
7174
    qemuCPUBaseline, /* cpuBaseline */
7175
    qemuDomainGetJobInfo, /* domainGetJobInfo */
7176
    qemuDomainAbortJob, /* domainAbortJob */
7177
    qemuDomainMigrateSetMaxDowntime, /* domainMigrateSetMaxDowntime */
7178
    qemuDomainMigrateSetMaxSpeed, /* domainMigrateSetMaxSpeed */
7179 7180
    qemuDomainEventRegisterAny, /* domainEventRegisterAny */
    qemuDomainEventDeregisterAny, /* domainEventDeregisterAny */
7181 7182 7183
    qemuDomainManagedSave, /* domainManagedSave */
    qemuDomainHasManagedSaveImage, /* domainHasManagedSaveImage */
    qemuDomainManagedSaveRemove, /* domainManagedSaveRemove */
C
Chris Lalancette 已提交
7184 7185 7186 7187 7188 7189 7190 7191 7192
    qemuDomainSnapshotCreateXML, /* domainSnapshotCreateXML */
    qemuDomainSnapshotDumpXML, /* domainSnapshotDumpXML */
    qemuDomainSnapshotNum, /* domainSnapshotNum */
    qemuDomainSnapshotListNames, /* domainSnapshotListNames */
    qemuDomainSnapshotLookupByName, /* domainSnapshotLookupByName */
    qemuDomainHasCurrentSnapshot, /* domainHasCurrentSnapshot */
    qemuDomainSnapshotCurrent, /* domainSnapshotCurrent */
    qemuDomainRevertToSnapshot, /* domainRevertToSnapshot */
    qemuDomainSnapshotDelete, /* domainSnapshotDelete */
7193
    qemuDomainMonitorCommand, /* qemuDomainMonitorCommand */
7194
    qemuDomainOpenConsole, /* domainOpenConsole */
7195 7196 7197
};


7198
static virStateDriver qemuStateDriver = {
7199
    .name = "QEMU",
7200 7201 7202 7203
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
7204
};
7205

7206
static void
7207
qemuVMDriverLock(void) {
7208 7209 7210 7211 7212
    qemuDriverLock(qemu_driver);
};


static void
7213
qemuVMDriverUnlock(void) {
7214 7215 7216 7217
    qemuDriverUnlock(qemu_driver);
};


7218 7219 7220 7221 7222 7223 7224 7225 7226
static int
qemuVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                    virHashIterator iter, void *data)
{
    virHashForEach(qemu_driver->domains.objs, iter, data);

    return 0;
}

S
Stefan Berger 已提交
7227 7228
static virNWFilterCallbackDriver qemuCallbackDriver = {
    .name = "QEMU",
7229 7230 7231
    .vmFilterRebuild = qemuVMFilterRebuild,
    .vmDriverLock = qemuVMDriverLock,
    .vmDriverUnlock = qemuVMDriverUnlock,
S
Stefan Berger 已提交
7232 7233
};

7234
int qemuRegister(void) {
7235 7236
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
S
Stefan Berger 已提交
7237
    virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);
7238 7239
    return 0;
}