qemu_driver.c 258.5 KB
Newer Older
D
Daniel P. Berrange 已提交
1
/*
2
 * qemu_driver.c: core driver methods for managing qemu guests
D
Daniel P. Berrange 已提交
3
 *
4
 * Copyright (C) 2006-2011 Red Hat, Inc.
D
Daniel P. Berrange 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

24
#include <config.h>
25

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

48

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

#include "virterror_internal.h"
#include "logging.h"
#include "datatypes.h"
65
#include "buf.h"
66
#include "util.h"
67
#include "nodeinfo.h"
68
#include "stats_linux.h"
69
#include "capabilities.h"
70
#include "memory.h"
71
#include "uuid.h"
72
#include "domain_conf.h"
73 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
#include "locking/lock_manager.h"
90

91 92
#define VIR_FROM_THIS VIR_FROM_QEMU

93 94
#define QEMU_NB_MEM_PARAM  3

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

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

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

113
#define QEMU_NB_BLKIO_PARAM  1
114

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

117 118
static int qemudShutdown(void);

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

124
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
125

126
struct qemud_driver *qemu_driver = NULL;
127 128


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

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

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

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

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

166

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

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

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

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

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

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

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

215
    return 0;
216

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

223

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

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

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

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

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

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

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

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

268
    return caps;
269

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

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

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

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

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

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

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

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

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

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

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

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

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

356
    virResetLastError();
357

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

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

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

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

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

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

394 395 396 397 398 399
    /* Init domain events */
    qemu_driver->domainEventState = virDomainEventStateNew(qemuDomainEventFlush,
                                                           qemu_driver,
                                                           NULL,
                                                           true);
    if (!qemu_driver->domainEventState)
400
        goto error;
401

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

407 408 409
    /* read the host sysinfo */
    if (privileged)
        qemu_driver->hostsysinfo = virSysinfoRead();
410

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

416 417
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
            goto out_of_memory;
418

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

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

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

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

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

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

471 472 473 474 475
    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 已提交
476
    }
477 478 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
    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;
506 507
    }

508 509 510 511 512 513 514
    /* 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;
515

516
    VIR_FREE(base);
517

518 519 520 521 522
    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)));
523 524
    }

525 526 527 528
    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
        goto error;
    }
    VIR_FREE(driverConf);
529

530 531 532 533 534 535 536 537
    /* We should always at least have the 'nop' manager, so
     * NULLs here are a fatal error
     */
    if (!qemu_driver->lockManager) {
        VIR_ERROR(_("Missing lock manager implementation"));
        goto error;
    }

538 539
    if (qemuSecurityInit(qemu_driver) < 0)
        goto error;
540

541 542 543
    if ((qemu_driver->caps = qemuCreateCapabilities(NULL,
                                                    qemu_driver)) == NULL)
        goto error;
544

545
    if ((qemu_driver->activePciHostdevs = pciDeviceListNew()) == NULL)
546
        goto error;
547

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

575 576 577 578 579 580
    /* 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
581
     */
582 583 584 585 586
    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;
587

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

603
        qemu_driver->hugepage_path = mempath;
604
    }
605

606 607 608 609 610 611 612
    /* 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;
613

614 615 616
    conn = virConnectOpen(qemu_driver->privileged ?
                          "qemu:///system" :
                          "qemu:///session");
617

618
    qemuProcessReconnectAll(conn, qemu_driver);
619

620 621 622 623 624 625 626
    /* Then inactive persistent configs */
    if (virDomainLoadAllConfigs(qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->configDir,
                                qemu_driver->autostartDir,
                                0, NULL, NULL) < 0)
        goto error;
627

628

629 630
    virHashForEach(qemu_driver->domains.objs, qemuDomainSnapshotLoad,
                   qemu_driver->snapshotDir);
631

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

636 637 638 639
    qemuDriverUnlock(qemu_driver);

    qemuAutostartDomains(qemu_driver);

640 641
    if (conn)
        virConnectClose(conn);
642

643
    return 0;
644

645 646 647 648 649 650 651 652 653 654
out_of_memory:
    virReportOOMError();
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
    if (conn)
        virConnectClose(conn);
    VIR_FREE(base);
    VIR_FREE(driverConf);
    qemudShutdown();
655
    return -1;
656 657
}

658 659 660
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;
661

662 663 664 665 666 667 668
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
E
Eric Blake 已提交
669
    }
670
}
E
Eric Blake 已提交
671

672 673 674 675 676 677 678 679 680 681
/**
 * 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;
682

683 684 685 686 687 688 689
    qemuDriverLock(qemu_driver);
    virDomainLoadAllConfigs(qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
                            qemu_driver->autostartDir,
                            0, qemudNotifyLoadDomain, qemu_driver);
    qemuDriverUnlock(qemu_driver);
690

691
    qemuAutostartDomains(qemu_driver);
692

693 694
    return 0;
}
S
Stefan Berger 已提交
695

696 697 698 699 700 701 702 703 704 705 706
/**
 * 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;
707

708 709
    if (!qemu_driver)
        return 0;
710

711 712 713 714 715 716
    /* 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;
}
717

718 719 720 721 722 723 724 725
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
    int i;
726

727 728
    if (!qemu_driver)
        return -1;
729

730 731 732
    qemuDriverLock(qemu_driver);
    pciDeviceListFree(qemu_driver->activePciHostdevs);
    virCapabilitiesFree(qemu_driver->caps);
733

734 735
    virDomainObjListDeinit(&qemu_driver->domains);
    virBitmapFree(qemu_driver->reservedVNCPorts);
736

737
    virSysinfoDefFree(qemu_driver->hostsysinfo);
738

739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
    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);
759

760
    virSecurityManagerFree(qemu_driver->securityManager);
761

762
    ebtablesContextFree(qemu_driver->ebtables);
763

764 765 766 767
    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 已提交
768 769
    }

770
    /* Free domain callback list */
771
    virDomainEventStateFree(qemu_driver->domainEventState);
D
Daniel P. Berrange 已提交
772

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

776
    virCgroupFree(&qemu_driver->cgroup);
777

778 779
    virLockManagerPluginUnref(qemu_driver->lockManager);

780 781 782 783
    qemuDriverUnlock(qemu_driver);
    virMutexDestroy(&qemu_driver->lock);
    virThreadPoolFree(qemu_driver->workerPool);
    VIR_FREE(qemu_driver);
784

785
    return 0;
786 787
}

788 789 790 791 792 793 794

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


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

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

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

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

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

    return VIR_DRV_OPEN_SUCCESS;
}

static int qemudClose(virConnectPtr conn) {
857
    struct qemud_driver *driver = conn->privateData;
858 859

    /* Get rid of callbacks registered for this conn */
860
    qemuDriverLock(driver);
861 862
    virDomainEventCallbackListRemoveConn(conn,
                                         driver->domainEventState->callbacks);
863
    qemuDriverUnlock(driver);
864 865 866 867 868 869

    conn->privateData = NULL;

    return 0;
}

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

884
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
885
    return "QEMU";
886 887
}

888

889 890 891 892 893 894 895 896 897 898 899 900 901
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;
}


902 903 904 905
static int kvmGetMaxVCPUs(void) {
    int maxvcpus = 1;

    int r, fd;
906

907 908
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
909
        virReportSystemError(errno, _("Unable to open %s"), KVM_DEVICE);
910
        return -1;
911 912 913 914 915 916
    }

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

917
    VIR_FORCE_CLOSE(fd);
918 919 920 921
    return maxvcpus;
}


E
Eric Blake 已提交
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
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, "");
}

938
static int qemudGetMaxVCPUs(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
939 940 941
    if (!type)
        return 16;

942
    if (STRCASEEQ(type, "qemu"))
943 944
        return 16;

945
    if (STRCASEEQ(type, "kvm"))
946
        return kvmGetMaxVCPUs();
947

948
    if (STRCASEEQ(type, "kqemu"))
949
        return 1;
950

951 952
    qemuReportError(VIR_ERR_INVALID_ARG,
                    _("unknown type '%s'"), type);
953 954 955
    return -1;
}

956

957
static char *qemudGetCapabilities(virConnectPtr conn) {
958
    struct qemud_driver *driver = conn->privateData;
959
    virCapsPtr caps = NULL;
960
    char *xml = NULL;
961

962
    qemuDriverLock(driver);
963

964
    if ((caps = qemuCreateCapabilities(qemu_driver->caps,
965
                                       qemu_driver)) == NULL) {
966 967 968
        virCapabilitiesFree(caps);
        goto cleanup;
    }
969

970
    virCapabilitiesFree(qemu_driver->caps);
971 972 973
    qemu_driver->caps = caps;

    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
974
        virReportOOMError();
975 976

cleanup:
977
    qemuDriverUnlock(driver);
978

979
    return xml;
980 981 982
}


983 984 985 986 987
static int
qemudGetProcessInfo(unsigned long long *cpuTime, int *lastCpu, int pid,
                    int tid)
{
    char *proc;
D
Daniel P. Berrange 已提交
988
    FILE *pidinfo;
989
    unsigned long long usertime, systime;
990 991
    int cpu;
    int ret;
D
Daniel P. Berrange 已提交
992

993
    if (tid)
994
        ret = virAsprintf(&proc, "/proc/%d/task/%d/stat", pid, tid);
995
    else
996 997
        ret = virAsprintf(&proc, "/proc/%d/stat", pid);
    if (ret < 0)
D
Daniel P. Berrange 已提交
998 999 1000 1001
        return -1;

    if (!(pidinfo = fopen(proc, "r"))) {
        /* VM probably shut down, so fake 0 */
1002 1003 1004 1005
        if (cpuTime)
            *cpuTime = 0;
        if (lastCpu)
            *lastCpu = 0;
1006
        VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1007 1008
        return 0;
    }
1009
    VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1010

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

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
1032 1033 1034 1035 1036
    if (cpuTime)
        *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
    if (lastCpu)
        *lastCpu = cpu;

D
Daniel P. Berrange 已提交
1037

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

1041
    VIR_FORCE_FCLOSE(pidinfo);
D
Daniel P. Berrange 已提交
1042 1043 1044 1045 1046

    return 0;
}


1047
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1048
                                          int id) {
1049 1050 1051 1052
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1053
    qemuDriverLock(driver);
1054
    vm  = virDomainFindByID(&driver->domains, id);
1055
    qemuDriverUnlock(driver);
1056 1057

    if (!vm) {
1058 1059
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching id %d"), id);
1060
        goto cleanup;
1061 1062
    }

1063
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1064
    if (dom) dom->id = vm->def->id;
1065 1066

cleanup:
1067 1068
    if (vm)
        virDomainObjUnlock(vm);
1069 1070
    return dom;
}
1071

1072
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1073
                                            const unsigned char *uuid) {
1074 1075 1076
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1077

1078
    qemuDriverLock(driver);
1079
    vm = virDomainFindByUUID(&driver->domains, uuid);
1080 1081
    qemuDriverUnlock(driver);

1082
    if (!vm) {
1083 1084
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
1085 1086
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1087
        goto cleanup;
1088 1089
    }

1090
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1091
    if (dom) dom->id = vm->def->id;
1092 1093

cleanup:
1094 1095
    if (vm)
        virDomainObjUnlock(vm);
1096 1097
    return dom;
}
1098

1099
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1100
                                            const char *name) {
1101 1102 1103
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1104

1105
    qemuDriverLock(driver);
1106
    vm = virDomainFindByName(&driver->domains, name);
1107 1108
    qemuDriverUnlock(driver);

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

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

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

1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134

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 已提交
1135 1136 1137 1138
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
        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 已提交
1159 1160 1161 1162
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
        goto cleanup;
    }
    ret = obj->persistent;

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

1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
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 已提交
1183 1184 1185 1186
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1187 1188 1189 1190 1191 1192 1193 1194 1195
        goto cleanup;
    }
    ret = obj->updated;

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

1197
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1198 1199 1200
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

1201
    qemuDriverLock(driver);
1202
    if (qemuCapsExtractVersion(driver->caps, &driver->qemuVersion) < 0)
1203
        goto cleanup;
1204

1205
    *version = driver->qemuVersion;
1206 1207 1208
    ret = 0;

cleanup:
1209
    qemuDriverUnlock(driver);
1210
    return ret;
D
Daniel P. Berrange 已提交
1211 1212
}

1213
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1214
    struct qemud_driver *driver = conn->privateData;
1215
    int n;
1216

1217
    qemuDriverLock(driver);
1218
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1219
    qemuDriverUnlock(driver);
1220

1221
    return n;
D
Daniel P. Berrange 已提交
1222
}
1223

1224
static int qemudNumDomains(virConnectPtr conn) {
1225
    struct qemud_driver *driver = conn->privateData;
1226
    int n;
1227

1228
    qemuDriverLock(driver);
1229
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1230
    qemuDriverUnlock(driver);
1231

1232
    return n;
D
Daniel P. Berrange 已提交
1233
}
1234

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

1243
    virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);
1244

1245
    qemuDriverLock(driver);
1246
    if (!(def = virDomainDefParseString(driver->caps, xml,
1247
                                        VIR_DOMAIN_XML_INACTIVE)))
1248
        goto cleanup;
1249

1250
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
1251 1252
        goto cleanup;

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

1256 1257 1258
    if (qemudCanonicalizeMachine(driver, def) < 0)
        goto cleanup;

1259
    if (qemuDomainAssignPCIAddresses(def) < 0)
1260 1261
        goto cleanup;

1262
    if (!(vm = virDomainAssignDef(driver->caps,
1263
                                  &driver->domains,
1264
                                  def, false)))
1265 1266 1267
        goto cleanup;

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

1269 1270 1271
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup; /* XXXX free the 'vm' we created ? */

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

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

1288
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1289
    if (dom) dom->id = vm->def->id;
1290

1291 1292 1293
    if (vm &&
        qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1294

1295 1296
cleanup:
    virDomainDefFree(def);
1297 1298
    if (vm)
        virDomainObjUnlock(vm);
1299 1300
    if (event)
        qemuDomainEventQueue(driver, event);
1301
    qemuDriverUnlock(driver);
1302
    return dom;
D
Daniel P. Berrange 已提交
1303 1304 1305
}


1306
static int qemudDomainSuspend(virDomainPtr dom) {
1307 1308 1309
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1310
    virDomainEventPtr event = NULL;
1311
    qemuDomainObjPrivatePtr priv;
1312

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

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

    priv = vm->privateData;

1331
    if (priv->jobActive == QEMU_JOB_MIGRATION_OUT) {
J
Jiri Denemark 已提交
1332
        if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
            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"));
1346
            goto endjob;
1347
        }
J
Jiri Denemark 已提交
1348 1349
        if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
            if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_USER) < 0) {
1350
                goto endjob;
1351
            }
1352 1353 1354 1355 1356 1357 1358
            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 已提交
1359
    }
1360

1361
endjob:
1362 1363
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1364

1365
cleanup:
1366 1367
    if (vm)
        virDomainObjUnlock(vm);
1368

1369
    if (event)
1370
        qemuDomainEventQueue(driver, event);
1371
    qemuDriverUnlock(driver);
1372
    return ret;
D
Daniel P. Berrange 已提交
1373 1374 1375
}


1376
static int qemudDomainResume(virDomainPtr dom) {
1377 1378 1379
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1380
    virDomainEventPtr event = NULL;
1381

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

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

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

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

1417
endjob:
1418 1419
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1420

1421
cleanup:
1422 1423
    if (vm)
        virDomainObjUnlock(vm);
1424
    if (event)
1425
        qemuDomainEventQueue(driver, event);
1426
    qemuDriverUnlock(driver);
1427
    return ret;
D
Daniel P. Berrange 已提交
1428 1429 1430
}


1431
static int qemudDomainShutdown(virDomainPtr dom) {
1432 1433 1434
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1435
    qemuDomainObjPrivatePtr priv;
1436

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

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

1449 1450 1451
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
1452
    if (!virDomainObjIsActive(vm)) {
1453 1454
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1455
        goto endjob;
1456 1457
    }

1458
    priv = vm->privateData;
1459 1460 1461
    qemuDomainObjEnterMonitor(vm);
    ret = qemuMonitorSystemPowerdown(priv->mon);
    qemuDomainObjExitMonitor(vm);
1462

1463
endjob:
1464 1465
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1466

1467
cleanup:
1468 1469
    if (vm)
        virDomainObjUnlock(vm);
1470
    return ret;
1471 1472 1473
}


1474
static int qemudDomainDestroy(virDomainPtr dom) {
1475 1476 1477
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1478
    virDomainEventPtr event = NULL;
1479

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

1490 1491 1492 1493 1494 1495 1496
    /* Although qemuProcessStop does this already, there may
     * be an outstanding job active. We want to make sure we
     * can kill the process even if a job is active. Killing
     * it now means the job will be released
     */
    qemuProcessKill(vm);

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

D
Daniel P. Berrange 已提交
1500
    if (!virDomainObjIsActive(vm)) {
1501 1502
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1503
        goto endjob;
1504
    }
1505

J
Jiri Denemark 已提交
1506
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_DESTROYED);
1507 1508 1509
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1510
    qemuAuditDomainStop(vm, "destroyed");
1511

1512
    if (!vm->persistent) {
1513 1514 1515
        if (qemuDomainObjEndJob(vm) > 0)
            virDomainRemoveInactive(&driver->domains,
                                    vm);
1516 1517
        vm = NULL;
    }
1518 1519
    ret = 0;

1520
endjob:
1521 1522 1523
    if (vm &&
        qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1524

1525
cleanup:
1526 1527
    if (vm)
        virDomainObjUnlock(vm);
1528 1529
    if (event)
        qemuDomainEventQueue(driver, event);
1530
    qemuDriverUnlock(driver);
1531
    return ret;
D
Daniel P. Berrange 已提交
1532 1533 1534
}


1535
static char *qemudDomainGetOSType(virDomainPtr dom) {
1536 1537 1538
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1539

1540
    qemuDriverLock(driver);
1541
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1542
    qemuDriverUnlock(driver);
1543
    if (!vm) {
1544 1545
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1546 1547
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1548
        goto cleanup;
1549 1550
    }

1551
    if (!(type = strdup(vm->def->os.type)))
1552
        virReportOOMError();
1553 1554

cleanup:
1555 1556
    if (vm)
        virDomainObjUnlock(vm);
1557 1558 1559
    return type;
}

1560 1561
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
1562 1563 1564
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
1565

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

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

1578
    ret = vm->def->mem.max_balloon;
1579 1580

cleanup:
1581 1582
    if (vm)
        virDomainObjUnlock(vm);
1583
    return ret;
1584 1585
}

1586 1587
static int qemudDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
                                     unsigned int flags) {
1588
    struct qemud_driver *driver = dom->conn->privateData;
1589
    qemuDomainObjPrivatePtr priv;
1590
    virDomainObjPtr vm;
1591
    virDomainDefPtr persistentDef = NULL;
1592
    int ret = -1, r;
1593
    bool isActive;
1594

1595 1596
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
1597
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1598

1599
    qemuDriverLock(driver);
1600
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1601
    qemuDriverUnlock(driver);
1602
    if (!vm) {
1603 1604
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1605 1606
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1607
        goto cleanup;
1608 1609
    }

1610 1611 1612
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

1613 1614
    isActive = virDomainObjIsActive(vm);

1615
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
1616
        if (isActive)
1617
            flags = VIR_DOMAIN_AFFECT_LIVE;
1618
        else
1619
            flags = VIR_DOMAIN_AFFECT_CONFIG;
1620
    }
1621 1622
    if (flags == VIR_DOMAIN_MEM_MAXIMUM) {
        if (isActive)
1623
            flags = VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_MEM_MAXIMUM;
1624
        else
1625
            flags = VIR_DOMAIN_AFFECT_CONFIG | VIR_DOMAIN_MEM_MAXIMUM;
1626
    }
1627

1628
    if (!isActive && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
1629 1630 1631 1632 1633
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

1634
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
1635 1636 1637 1638 1639 1640 1641 1642
        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;
    }
1643

1644 1645 1646
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */

1647
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
1648 1649 1650
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot resize the maximum memory on an "
                              "active domain"));
1651
            goto endjob;
1652
        }
1653

1654
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
1655 1656
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
1657 1658 1659 1660
            persistentDef->mem.max_balloon = newmem;
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
1661 1662 1663
            goto endjob;
        }

1664 1665 1666 1667 1668 1669 1670 1671 1672
    } else {
        /* resize the current memory */

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

1673
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
            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;
            }
        }

1691
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
1692
            sa_assert(persistentDef);
1693 1694 1695 1696
            persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
            goto endjob;
        }
1697
    }
1698

1699
    ret = 0;
1700
endjob:
1701 1702
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1703

1704
cleanup:
1705 1706
    if (vm)
        virDomainObjUnlock(vm);
1707
    return ret;
1708 1709
}

1710 1711
static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem)
{
1712
    return qemudDomainSetMemoryFlags(dom, newmem, VIR_DOMAIN_AFFECT_LIVE);
1713 1714
}

1715 1716 1717 1718 1719
static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return qemudDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
static int qemuDomainInjectNMI(virDomainPtr domain, unsigned int flags)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, -1);

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

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

    priv = vm->privateData;

    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    ret = qemuMonitorInjectNMI(priv->mon);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
    if (qemuDomainObjEndJob(vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

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

1764
static int qemudDomainGetInfo(virDomainPtr dom,
1765 1766
                              virDomainInfoPtr info)
{
1767 1768 1769
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1770 1771
    int err;
    unsigned long balloon;
1772

1773
    qemuDriverLock(driver);
1774
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1775
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
1776
    if (!vm) {
1777 1778
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1779 1780
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1781
        goto cleanup;
D
Daniel P. Berrange 已提交
1782 1783
    }

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

D
Daniel P. Berrange 已提交
1786
    if (!virDomainObjIsActive(vm)) {
1787
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
1788
    } else {
1789
        if (qemudGetProcessInfo(&(info->cpuTime), NULL, vm->pid, 0) < 0) {
E
Eric Blake 已提交
1790 1791
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("cannot read cputime for domain"));
1792
            goto cleanup;
D
Daniel P. Berrange 已提交
1793 1794 1795
        }
    }

1796
    info->maxMem = vm->def->mem.max_balloon;
1797

D
Daniel P. Berrange 已提交
1798
    if (virDomainObjIsActive(vm)) {
1799
        qemuDomainObjPrivatePtr priv = vm->privateData;
1800 1801 1802

        if ((vm->def->memballoon != NULL) &&
            (vm->def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_NONE)) {
1803
            info->memory = vm->def->mem.max_balloon;
1804
        } else if (!priv->jobActive) {
1805 1806
            if (qemuDomainObjBeginJob(vm) < 0)
                goto cleanup;
1807 1808 1809 1810 1811 1812 1813 1814 1815
            if (!virDomainObjIsActive(vm))
                err = 0;
            else {
                qemuDomainObjEnterMonitor(vm);
                err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
                qemuDomainObjExitMonitor(vm);
            }
            if (qemuDomainObjEndJob(vm) == 0) {
                vm = NULL;
1816 1817 1818
                goto cleanup;
            }

1819 1820
            if (err < 0)
                goto cleanup;
1821 1822
            if (err == 0)
                /* Balloon not supported, so maxmem is always the allocation */
1823
                info->memory = vm->def->mem.max_balloon;
1824 1825 1826
            else
                info->memory = balloon;
        } else {
1827
            info->memory = vm->def->mem.cur_balloon;
1828
        }
1829
    } else {
1830
        info->memory = vm->def->mem.cur_balloon;
1831 1832
    }

1833
    info->nrVirtCpu = vm->def->vcpus;
1834 1835 1836
    ret = 0;

cleanup:
1837 1838
    if (vm)
        virDomainObjUnlock(vm);
1839
    return ret;
D
Daniel P. Berrange 已提交
1840 1841
}

1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865
static int
qemuDomainGetState(virDomainPtr dom,
                   int *state,
                   int *reason,
                   unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

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

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

J
Jiri Denemark 已提交
1866
    *state = virDomainObjGetState(vm, reason);
1867 1868 1869 1870 1871 1872 1873 1874
    ret = 0;

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

1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
static int
qemuDomainGetControlInfo(virDomainPtr dom,
                          virDomainControlInfoPtr info,
                          unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(0, -1);

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

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

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

    priv = vm->privateData;

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

    if (priv->monError) {
        info->state = VIR_DOMAIN_CONTROL_ERROR;
    } else if (priv->jobActive) {
        if (!priv->monStart) {
            info->state = VIR_DOMAIN_CONTROL_JOB;
            if (virTimeMs(&info->stateTime) < 0)
                goto cleanup;
            info->stateTime -= priv->jobStart;
        } else {
            info->state = VIR_DOMAIN_CONTROL_OCCUPIED;
            if (virTimeMs(&info->stateTime) < 0)
                goto cleanup;
            info->stateTime -= priv->monStart;
        }
    } else {
        info->state = VIR_DOMAIN_CONTROL_OK;
    }

    ret = 0;

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

D
Daniel P. Berrange 已提交
1935

1936
#define QEMUD_SAVE_MAGIC "LibvirtQemudSave"
1937 1938 1939
#define QEMUD_SAVE_VERSION 2

enum qemud_save_formats {
1940 1941 1942
    QEMUD_SAVE_FORMAT_RAW = 0,
    QEMUD_SAVE_FORMAT_GZIP = 1,
    QEMUD_SAVE_FORMAT_BZIP2 = 2,
1943 1944
    /*
     * Deprecated by xz and never used as part of a release
1945
     * QEMUD_SAVE_FORMAT_LZMA
1946 1947
     */
    QEMUD_SAVE_FORMAT_XZ = 3,
1948
    QEMUD_SAVE_FORMAT_LZOP = 4,
1949 1950 1951
    /* Note: add new members only at the end.
       These values are used in the on-disk format.
       Do not change or re-use numbers. */
1952 1953

    QEMUD_SAVE_FORMAT_LAST
1954
};
1955

1956 1957 1958 1959 1960
VIR_ENUM_DECL(qemudSaveCompression)
VIR_ENUM_IMPL(qemudSaveCompression, QEMUD_SAVE_FORMAT_LAST,
              "raw",
              "gzip",
              "bzip2",
1961 1962
              "xz",
              "lzop")
1963

1964 1965
struct qemud_save_header {
    char magic[sizeof(QEMUD_SAVE_MAGIC)-1];
1966 1967 1968 1969 1970
    uint32_t version;
    uint32_t xml_len;
    uint32_t was_running;
    uint32_t compressed;
    uint32_t unused[15];
1971 1972
};

1973 1974 1975 1976 1977 1978 1979 1980 1981
static inline void
bswap_header(struct qemud_save_header *hdr) {
    hdr->version = bswap_32(hdr->version);
    hdr->xml_len = bswap_32(hdr->xml_len);
    hdr->was_running = bswap_32(hdr->was_running);
    hdr->compressed = bswap_32(hdr->compressed);
}


1982
/* return -errno on failure, or 0 on success */
E
Eric Blake 已提交
1983 1984 1985 1986
static int
qemuDomainSaveHeader(int fd, const char *path, char *xml,
                     struct qemud_save_header *header)
{
1987 1988
    int ret = 0;

E
Eric Blake 已提交
1989
    if (safewrite(fd, header, sizeof(*header)) != sizeof(*header)) {
1990
        ret = -errno;
1991
        qemuReportError(VIR_ERR_OPERATION_FAILED,
1992
                        _("failed to write header to domain save file '%s'"),
E
Eric Blake 已提交
1993
                        path);
1994 1995 1996
        goto endjob;
    }

E
Eric Blake 已提交
1997
    if (safewrite(fd, xml, header->xml_len) != header->xml_len) {
1998
        ret = -errno;
1999
        qemuReportError(VIR_ERR_OPERATION_FAILED,
E
Eric Blake 已提交
2000
                         _("failed to write xml to '%s'"), path);
2001 2002 2003 2004 2005 2006
        goto endjob;
    }
endjob:
    return ret;
}

2007 2008 2009 2010 2011 2012 2013 2014 2015
/* Given a enum qemud_save_formats compression level, return the name
 * of the program to run, or NULL if no program is needed.  */
static const char *
qemuCompressProgramName(int compress)
{
    return (compress == QEMUD_SAVE_FORMAT_RAW ? NULL :
            qemudSaveCompressionTypeToString(compress));
}

2016 2017 2018
/* This internal function expects the driver lock to already be held on
 * entry and the vm must be active.
 */
2019 2020
static int qemudDomainSaveFlag(struct qemud_driver *driver, virDomainPtr dom,
                               virDomainObjPtr vm, const char *path,
2021
                               int compressed)
2022
{
2023
    char *xml = NULL;
2024
    struct qemud_save_header header;
2025
    bool bypassSecurityDriver = false;
2026
    int ret = -1;
2027
    int rc;
2028
    virDomainEventPtr event = NULL;
2029
    qemuDomainObjPrivatePtr priv;
2030
    struct stat sb;
2031
    bool is_reg = false;
2032
    unsigned long long offset;
2033
    int fd = -1;
2034 2035
    uid_t uid = getuid();
    gid_t gid = getgid();
2036 2037 2038 2039 2040

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

2041
    header.compressed = compressed;
2042

2043
    priv = vm->privateData;
2044

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

O
Osier Yang 已提交
2048 2049
    priv->jobActive = QEMU_JOB_SAVE;

2050 2051 2052
    memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
    priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;

2053
    /* Pause */
J
Jiri Denemark 已提交
2054
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
2055
        header.was_running = 1;
J
Jiri Denemark 已提交
2056
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE) < 0)
2057
            goto endjob;
2058 2059 2060 2061 2062 2063

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

    /* Get XML for the domain */
2067
    xml = virDomainDefFormat(vm->def, VIR_DOMAIN_XML_SECURE);
2068
    if (!xml) {
2069 2070
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to get domain xml"));
2071
        goto endjob;
2072 2073 2074
    }
    header.xml_len = strlen(xml) + 1;

2075 2076 2077 2078 2079 2080 2081 2082
    /* 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 */
2083
        is_reg = true;
2084
    } else {
2085
        is_reg = !!S_ISREG(sb.st_mode);
2086 2087 2088 2089 2090 2091 2092 2093
        /* If the path is regular local file which exists
         * already and dynamic_ownership is off, we don't
         * want to change it's ownership, just open it as-is */
        if (is_reg && !driver->dynamicOwnership &&
            virStorageFileIsSharedFS(path) == 0) {
            uid=sb.st_uid;
            gid=sb.st_gid;
        }
2094 2095
    }

2096 2097 2098 2099 2100
    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
2101 2102
     * it by padding the XML string with NULLs.
     */
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
    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;
    }
2116

2117
    /* Obtain the file handle.  */
2118

2119
    /* First try creating the file as root */
2120
    if (!is_reg) {
2121
        fd = open(path, O_WRONLY | O_TRUNC);
2122 2123
        if (fd < 0) {
            virReportSystemError(errno, _("unable to open %s"), path);
2124 2125
            goto endjob;
        }
2126
    } else {
2127 2128
        if ((fd = virFileOpenAs(path, O_CREAT|O_TRUNC|O_WRONLY,
                                S_IRUSR|S_IWUSR,
2129
                                uid, gid, 0)) < 0) {
2130
            /* If we failed as root, and the error was permission-denied
2131 2132
               (EACCES or EPERM), assume it's on a network-connected share
               where root access is restricted (eg, root-squashed NFS). If the
2133 2134 2135
               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 */
2136
            rc = fd;
2137
            if (((rc != -EACCES) && (rc != -EPERM)) ||
2138
                driver->user == getuid()) {
2139 2140
                virReportSystemError(-rc,
                                    _("Failed to create domain save file '%s'"),
2141 2142 2143
                                     path);
                goto endjob;
            }
2144

2145
            /* On Linux we can also verify the FS-type of the directory. */
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
            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:
2163
                   /* local file - log the error returned by virFileOpenAs */
2164
                   virReportSystemError(-rc,
2165
                                    _("Failed to create domain save file '%s'"),
2166 2167 2168
                                        path);
                   goto endjob;
                   break;
2169 2170 2171

            }

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

2174 2175 2176 2177
            if ((fd = virFileOpenAs(path, O_CREAT|O_TRUNC|O_WRONLY,
                                    S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP,
                                    driver->user, driver->group,
                                    VIR_FILE_OPEN_AS_UID)) < 0) {
2178 2179 2180
                virReportSystemError(-fd,
                                   _("Error from child process creating '%s'"),
                                     path);
2181 2182
                goto endjob;
            }
2183

2184 2185 2186
            /* 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 */
2187

2188
            bypassSecurityDriver = true;
2189
        }
2190
    }
2191

2192
    /* Write header to file, followed by XML */
E
Eric Blake 已提交
2193
    if (qemuDomainSaveHeader(fd, path, xml, &header) < 0) {
2194 2195 2196 2197
        VIR_FORCE_CLOSE(fd);
        goto endjob;
    }

2198
    /* Perform the migration */
2199
    if (qemuMigrationToFile(driver, vm, fd, offset, path,
2200 2201
                            qemuCompressProgramName(compressed),
                            is_reg, bypassSecurityDriver) < 0)
2202
        goto endjob;
2203 2204
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("unable to close %s"), path);
2205
        goto endjob;
2206 2207
    }

2208 2209
    ret = 0;

2210
    /* Shut it down */
J
Jiri Denemark 已提交
2211
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_SAVED);
2212
    qemuAuditDomainStop(vm, "saved");
2213 2214 2215
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2216
    if (!vm->persistent) {
2217 2218 2219
        if (qemuDomainObjEndJob(vm) > 0)
            virDomainRemoveInactive(&driver->domains,
                                    vm);
2220 2221
        vm = NULL;
    }
2222

2223
endjob:
2224
    if (vm) {
2225
        if (ret != 0) {
2226
            if (header.was_running && virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
2227 2228
                rc = qemuProcessStartCPUs(driver, vm, dom->conn,
                                          VIR_DOMAIN_RUNNING_SAVE_CANCELED);
2229
                if (rc < 0)
2230
                    VIR_WARN("Unable to resume guest CPUs after save failure");
2231
            }
2232
        }
2233
        if (qemuDomainObjEndJob(vm) == 0)
2234
            vm = NULL;
2235
    }
2236

2237
cleanup:
2238
    VIR_FORCE_CLOSE(fd);
2239
    VIR_FREE(xml);
2240
    if (ret != 0 && is_reg)
2241
        unlink(path);
2242 2243
    if (event)
        qemuDomainEventQueue(driver, event);
2244
    return ret;
D
Daniel P. Berrange 已提交
2245 2246
}

2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262
/* 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;
}

2263 2264 2265 2266
static int qemudDomainSave(virDomainPtr dom, const char *path)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int compressed;
2267 2268 2269 2270
    int ret = -1;
    virDomainObjPtr vm = NULL;

    qemuDriverLock(driver);
2271 2272 2273 2274 2275 2276 2277 2278 2279

    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"));
2280
            goto cleanup;
2281
        }
2282 2283 2284 2285
        if (!qemudCompressProgramAvailable(compressed)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Compression program for image format "
                                    "in configuration file isn't available"));
2286
            goto cleanup;
2287
        }
2288 2289
    }

2290 2291 2292 2293 2294 2295 2296 2297 2298
    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;
    }

2299 2300 2301 2302 2303 2304
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2305 2306 2307 2308 2309 2310 2311 2312
    ret = qemudDomainSaveFlag(driver, dom, vm, path, compressed);

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

    return ret;
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
}

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;

2336
    virCheckFlags(0, -1);
2337 2338 2339 2340 2341 2342 2343 2344

    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);
2345
        goto cleanup;
2346 2347
    }

2348 2349 2350 2351 2352 2353
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2354 2355
    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
2356
        goto cleanup;
2357

2358
    VIR_INFO("Saving state to %s", name);
2359 2360

    compressed = QEMUD_SAVE_FORMAT_RAW;
2361
    ret = qemudDomainSaveFlag(driver, dom, vm, name, compressed);
2362 2363 2364 2365 2366

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
2367 2368 2369
    VIR_FREE(name);

    return ret;
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
}

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

2380
    virCheckFlags(0, -1);
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413

    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;

2414
    virCheckFlags(0, -1);
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438

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

H
Hu Tao 已提交
2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
static int doCoreDump(struct qemud_driver *driver,
                      virDomainObjPtr vm,
                      const char *path,
                      enum qemud_save_formats compress)
{
    int fd = -1;
    int ret = -1;

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

2455
    if (qemuMigrationToFile(driver, vm, fd, 0, path,
2456 2457 2458
                            qemuCompressProgramName(compress), true, false) < 0)
        goto cleanup;

H
Hu Tao 已提交
2459 2460 2461 2462 2463 2464 2465
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno,
                             _("unable to save file %s"),
                             path);
        goto cleanup;
    }

2466
    ret = 0;
H
Hu Tao 已提交
2467 2468 2469 2470 2471 2472 2473

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

2474 2475 2476 2477 2478
static enum qemud_save_formats
getCompressionType(struct qemud_driver *driver)
{
    int compress = QEMUD_SAVE_FORMAT_RAW;

2479 2480 2481 2482 2483 2484 2485
    /*
     * 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) {
2486 2487 2488 2489
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("Invalid dump image format specified in "
                              "configuration file, using raw"));
            return QEMUD_SAVE_FORMAT_RAW;
2490
        }
2491 2492 2493
        if (!qemudCompressProgramAvailable(compress)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Compression program for dump image format "
2494 2495 2496
                                    "in configuration file isn't available, "
                                    "using raw"));
            return QEMUD_SAVE_FORMAT_RAW;
2497
        }
2498
    }
2499 2500 2501 2502 2503
    return compress;
}

static int qemudDomainCoreDump(virDomainPtr dom,
                               const char *path,
2504 2505
                               int flags)
{
2506 2507 2508
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int resume = 0, paused = 0;
H
Hu Tao 已提交
2509
    int ret = -1;
2510 2511 2512
    virDomainEventPtr event = NULL;
    qemuDomainObjPrivatePtr priv;

2513 2514
    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

P
Paolo Bonzini 已提交
2515 2516 2517 2518 2519 2520
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2521 2522
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
P
Paolo Bonzini 已提交
2523 2524
        goto cleanup;
    }
2525
    priv = vm->privateData;
P
Paolo Bonzini 已提交
2526

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

D
Daniel P. Berrange 已提交
2530
    if (!virDomainObjIsActive(vm)) {
2531 2532
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
2533
        goto endjob;
P
Paolo Bonzini 已提交
2534 2535
    }

O
Osier Yang 已提交
2536 2537
    priv->jobActive = QEMU_JOB_DUMP;

P
Paolo Bonzini 已提交
2538 2539
    /* Migrate will always stop the VM, so the resume condition is
       independent of whether the stop command is issued.  */
J
Jiri Denemark 已提交
2540
    resume = virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING;
P
Paolo Bonzini 已提交
2541 2542

    /* Pause domain for non-live dump */
J
Jiri Denemark 已提交
2543 2544 2545
    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_DUMP) < 0)
2546
            goto endjob;
P
Paolo Bonzini 已提交
2547
        paused = 1;
2548 2549 2550 2551 2552 2553

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

H
Hu Tao 已提交
2556
    ret = doCoreDump(driver, vm, path, getCompressionType(driver));
2557 2558 2559 2560
    if (ret < 0)
        goto endjob;

    paused = 1;
2561 2562

endjob:
2563
    if ((ret == 0) && (flags & VIR_DUMP_CRASH)) {
J
Jiri Denemark 已提交
2564
        qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_CRASHED);
2565
        qemuAuditDomainStop(vm, "crashed");
2566 2567 2568 2569 2570
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
    }

P
Paolo Bonzini 已提交
2571 2572 2573
    /* 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.  */
2574
    else if (resume && paused && virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
2575 2576
        if (qemuProcessStartCPUs(driver, vm, dom->conn,
                                 VIR_DOMAIN_RUNNING_UNPAUSED) < 0) {
2577
            if (virGetLastError() == NULL)
2578 2579
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("resuming after dump failed"));
P
Paolo Bonzini 已提交
2580 2581
        }
    }
2582

2583 2584
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
2585
    else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
2586 2587 2588 2589
        virDomainRemoveInactive(&driver->domains,
                                vm);
        vm = NULL;
    }
2590 2591

cleanup:
P
Paolo Bonzini 已提交
2592 2593
    if (vm)
        virDomainObjUnlock(vm);
2594 2595
    if (event)
        qemuDomainEventQueue(driver, event);
2596
    qemuDriverUnlock(driver);
P
Paolo Bonzini 已提交
2597 2598 2599
    return ret;
}

2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
static char *
qemuDomainScreenshot(virDomainPtr dom,
                     virStreamPtr st,
                     unsigned int screen,
                     unsigned int flags ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    char *tmp = NULL;
    int tmp_fd = -1;
    char *ret = NULL;

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

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

    priv = vm->privateData;

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

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

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

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

    if ((tmp_fd = mkstemp(tmp)) == -1) {
        virReportSystemError(errno, _("mkstemp(\"%s\") failed"), tmp);
        goto endjob;
    }

    qemuDomainObjEnterMonitor(vm);
    if (qemuMonitorScreendump(priv->mon, tmp) < 0) {
        qemuDomainObjExitMonitor(vm);
        goto endjob;
    }
    qemuDomainObjExitMonitor(vm);

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

    if (virFDStreamOpenFile(st, tmp, 0, 0, O_RDONLY, true) < 0) {
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("unable to open stream"));
        goto endjob;
    }

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

endjob:
    VIR_FORCE_CLOSE(tmp_fd);
    VIR_FREE(tmp);

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

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

H
Hu Tao 已提交
2688 2689 2690
static void processWatchdogEvent(void *data, void *opaque)
{
    int ret;
2691
    struct qemuDomainWatchdogEvent *wdEvent = data;
H
Hu Tao 已提交
2692 2693
    struct qemud_driver *driver = opaque;

W
Wen Congyang 已提交
2694 2695 2696
    qemuDriverLock(driver);
    virDomainObjLock(wdEvent->vm);

H
Hu Tao 已提交
2697 2698 2699 2700 2701
    switch (wdEvent->action) {
    case VIR_DOMAIN_WATCHDOG_ACTION_DUMP:
        {
            char *dumpfile;

E
Eric Blake 已提交
2702
            if (virAsprintf(&dumpfile, "%s/%s-%u",
H
Hu Tao 已提交
2703 2704
                            driver->autoDumpPath,
                            wdEvent->vm->def->name,
E
Eric Blake 已提交
2705 2706
                            (unsigned int)time(NULL)) < 0) {
                virReportOOMError();
W
Wen Congyang 已提交
2707
                goto unlock;
E
Eric Blake 已提交
2708
            }
H
Hu Tao 已提交
2709

W
Wen Congyang 已提交
2710 2711 2712 2713
            if (qemuDomainObjBeginJobWithDriver(driver, wdEvent->vm) < 0) {
                VIR_FREE(dumpfile);
                goto unlock;
            }
H
Hu Tao 已提交
2714 2715 2716 2717

            if (!virDomainObjIsActive(wdEvent->vm)) {
                qemuReportError(VIR_ERR_OPERATION_INVALID,
                                "%s", _("domain is not running"));
W
Wen Congyang 已提交
2718 2719
                VIR_FREE(dumpfile);
                goto endjob;
H
Hu Tao 已提交
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729
            }

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

J
Jiri Denemark 已提交
2730 2731
            ret = qemuProcessStartCPUs(driver, wdEvent->vm, NULL,
                                       VIR_DOMAIN_RUNNING_UNPAUSED);
H
Hu Tao 已提交
2732 2733 2734 2735 2736 2737 2738 2739

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

            VIR_FREE(dumpfile);
        }
        break;
W
Wen Congyang 已提交
2740 2741
    default:
        goto unlock;
H
Hu Tao 已提交
2742 2743
    }

W
Wen Congyang 已提交
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753
endjob:
    /* Safe to ignore value since ref count was incremented in
     * qemuProcessHandleWatchdog().
     */
    ignore_value(qemuDomainObjEndJob(wdEvent->vm));

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

2757 2758 2759
static int qemudDomainHotplugVcpus(virDomainObjPtr vm, unsigned int nvcpus)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2760
    int i, rc = 1;
2761
    int ret = -1;
2762
    int oldvcpus = vm->def->vcpus;
E
Eric Blake 已提交
2763
    int vcpus = oldvcpus;
2764

2765 2766
    qemuDomainObjEnterMonitor(vm);

2767 2768 2769
    /* 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 已提交
2770 2771
    if (nvcpus > vcpus) {
        for (i = vcpus ; i < nvcpus ; i++) {
2772 2773 2774 2775 2776 2777 2778
            /* Online new CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 1);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
2779
            vcpus++;
2780 2781
        }
    } else {
E
Eric Blake 已提交
2782
        for (i = vcpus - 1 ; i >= nvcpus ; i--) {
2783 2784 2785 2786 2787 2788 2789
            /* Offline old CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 0);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
2790
            vcpus--;
2791 2792 2793 2794 2795 2796
        }
    }

    ret = 0;

cleanup:
2797
    qemuDomainObjExitMonitor(vm);
E
Eric Blake 已提交
2798
    vm->def->vcpus = vcpus;
2799
    qemuAuditVcpu(vm, oldvcpus, nvcpus, "update", rc == 1);
2800 2801 2802 2803 2804 2805 2806 2807 2808
    return ret;

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


2809 2810 2811 2812
static int
qemudDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
2813 2814
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2815
    virDomainDefPtr persistentDef;
2816 2817
    const char * type;
    int max;
2818
    int ret = -1;
2819

2820 2821
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
2822 2823 2824 2825
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

    /* At least one of LIVE or CONFIG must be set.  MAXIMUM cannot be
     * mixed with LIVE.  */
2826 2827 2828
    if ((flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)) == 0 ||
        (flags & (VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_AFFECT_LIVE)) ==
         (VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_AFFECT_LIVE)) {
2829 2830 2831 2832 2833 2834 2835
        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);
2836 2837 2838
        return -1;
    }

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

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

2851 2852 2853
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

2854
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
2855 2856
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("domain is not running"));
2857
        goto endjob;
2858 2859
    }

2860
    if (!vm->persistent && (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
2861 2862 2863 2864 2865
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot change persistent config of a transient domain"));
        goto endjob;
    }

2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878
    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 已提交
2879
    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM) && vm->def->maxvcpus < max) {
2880 2881 2882
        max = vm->def->maxvcpus;
    }

2883 2884 2885 2886 2887 2888 2889
    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;
    }

2890 2891 2892
    if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
        goto endjob;

2893
    switch (flags) {
2894
    case VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_AFFECT_CONFIG:
2895 2896 2897
        persistentDef->maxvcpus = nvcpus;
        if (nvcpus < persistentDef->vcpus)
            persistentDef->vcpus = nvcpus;
2898 2899 2900
        ret = 0;
        break;

2901
    case VIR_DOMAIN_AFFECT_CONFIG:
2902
        persistentDef->vcpus = nvcpus;
2903 2904 2905
        ret = 0;
        break;

2906
    case VIR_DOMAIN_AFFECT_LIVE:
2907 2908 2909
        ret = qemudDomainHotplugVcpus(vm, nvcpus);
        break;

2910
    case VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG:
2911
        ret = qemudDomainHotplugVcpus(vm, nvcpus);
2912 2913 2914
        if (ret == 0) {
            persistentDef->vcpus = nvcpus;
        }
2915 2916
        break;
    }
2917

2918
    /* Save the persistent config to disk */
2919
    if (flags & VIR_DOMAIN_AFFECT_CONFIG)
2920 2921
        ret = virDomainSaveConfig(driver->configDir, persistentDef);

2922 2923 2924
endjob:
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
2925

2926
cleanup:
2927 2928
    if (vm)
        virDomainObjUnlock(vm);
2929
    return ret;
2930 2931
}

2932 2933 2934
static int
qemudDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
{
2935
    return qemudDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
2936 2937
}

2938 2939

static int
2940 2941 2942 2943 2944 2945
qemudDomainPinVcpuFlags(virDomainPtr dom,
                        unsigned int vcpu,
                        unsigned char *cpumap,
                        int maplen,
                        unsigned int flags) {

2946 2947
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2948
    virDomainDefPtr persistentDef = NULL;
2949
    int maxcpu, hostcpus;
2950
    virNodeInfo nodeinfo;
2951
    int ret = -1;
2952
    bool isActive;
2953
    qemuDomainObjPrivatePtr priv;
2954
    bool canResetting = true;
2955

2956 2957 2958
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

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

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

2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982
    isActive = virDomainObjIsActive(vm);
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
        if (isActive)
            flags = VIR_DOMAIN_AFFECT_LIVE;
        else
            flags = VIR_DOMAIN_AFFECT_CONFIG;
    }

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

2986 2987 2988
    priv = vm->privateData;

    if (vcpu > (priv->nvcpupids-1)) {
2989 2990 2991
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("vcpu number out of range %d > %d"),
                        vcpu, priv->nvcpupids);
2992
        goto cleanup;
2993 2994
    }

2995 2996 2997 2998 2999 3000 3001 3002 3003
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                   _("cannot change persistent config of a transient domain"));
            goto cleanup;
        }
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
            goto cleanup;
    }
3004

3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
        goto cleanup;
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
    maxcpu = maplen * 8;
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
    /* pinning to all physical cpus means resetting,
     * so check if we can reset setting.
     */
    for (int pcpu = 0; pcpu < hostcpus; pcpu++) {
        if ((cpumap[pcpu/8] & (1 << (pcpu % 8))) == 0) {
            canResetting = false;
            break;
        }
    }
3020

3021
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032

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

3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046
        if (canResetting) {
            if (virDomainVcpupinDel(vm->def, vcpu) < 0) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to delete vcpupin xml of "
                                  "a running domain"));
                goto cleanup;
            }
        } else {
            if (virDomainVcpupinAdd(vm->def, cpumap, maplen, vcpu) < 0) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to update or add vcpupin xml of "
                                  "a running domain"));
                goto cleanup;
            }
3047 3048
        }

3049
    }
3050

3051 3052
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {

3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066
        if (canResetting) {
            if (virDomainVcpupinDel(persistentDef, vcpu) < 0) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to delete vcpupin xml of "
                                  "a persistent domain"));
                goto cleanup;
            }
        } else {
            if (virDomainVcpupinAdd(persistentDef, cpumap, maplen, vcpu) < 0) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to update or add vcpupin xml of "
                                  "a persistent domain"));
                goto cleanup;
            }
3067
        }
3068

3069
        ret = virDomainSaveConfig(driver->configDir, persistentDef);
3070 3071 3072
        goto cleanup;
    }

3073
    ret = 0;
3074

3075
cleanup:
3076 3077
    if (vm)
        virDomainObjUnlock(vm);
3078
    return ret;
3079 3080
}

3081 3082 3083 3084 3085 3086 3087 3088 3089
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
    return qemudDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

3090 3091 3092 3093 3094 3095
static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
3096 3097
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3098
    virNodeInfo nodeinfo;
3099
    int i, v, maxcpu, hostcpus;
3100
    int ret = -1;
3101
    qemuDomainObjPrivatePtr priv;
3102

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

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

D
Daniel P. Berrange 已提交
3115
    if (!virDomainObjIsActive(vm)) {
3116 3117 3118
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s",
                        _("cannot list vcpu pinning for an inactive domain"));
3119
        goto cleanup;
3120 3121
    }

3122 3123
    priv = vm->privateData;

3124
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
3125
        goto cleanup;
3126

3127
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
3128
    maxcpu = maplen * 8;
3129 3130
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
3131 3132

    /* Clamp to actual number of vcpus */
3133 3134
    if (maxinfo > priv->nvcpupids)
        maxinfo = priv->nvcpupids;
3135

3136 3137 3138 3139 3140 3141
    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;
3142

3143
                if (priv->vcpupids != NULL &&
3144 3145 3146
                    qemudGetProcessInfo(&(info[i].cpuTime),
                                        &(info[i].cpu),
                                        vm->pid,
3147
                                        priv->vcpupids[i]) < 0) {
3148
                    virReportSystemError(errno, "%s",
3149 3150 3151
                                         _("cannot get vCPU placement & pCPU time"));
                    goto cleanup;
                }
3152
            }
3153 3154
        }

3155 3156
        if (cpumaps != NULL) {
            memset(cpumaps, 0, maplen * maxinfo);
3157
            if (priv->vcpupids != NULL) {
3158 3159 3160
                for (v = 0 ; v < maxinfo ; v++) {
                    unsigned char *cpumap = VIR_GET_CPUMAP(cpumaps, maplen, v);

3161
                    if (virProcessInfoGetAffinity(priv->vcpupids[v],
3162
                                                  cpumap, maplen, maxcpu) < 0)
3163
                        goto cleanup;
3164
                }
3165
            } else {
3166 3167
                qemuReportError(VIR_ERR_NO_SUPPORT,
                                "%s", _("cpu affinity is not available"));
3168
                goto cleanup;
3169 3170 3171
            }
        }
    }
3172
    ret = maxinfo;
3173

3174
cleanup:
3175 3176
    if (vm)
        virDomainObjUnlock(vm);
3177
    return ret;
3178 3179 3180
}


3181 3182 3183
static int
qemudDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
3184 3185
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3186
    virDomainDefPtr def;
3187
    int ret = -1;
3188

3189 3190
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
3191 3192 3193
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

    /* Exactly one of LIVE or CONFIG must be set.  */
3194
    if (!(flags & VIR_DOMAIN_AFFECT_LIVE) == !(flags & VIR_DOMAIN_AFFECT_CONFIG)) {
3195 3196
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid flag combination: (0x%x)"), flags);
3197 3198 3199
        return -1;
    }

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

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

3212
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3213 3214 3215 3216 3217 3218 3219 3220
        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;
3221 3222
    }

3223
    ret = (flags & VIR_DOMAIN_VCPU_MAXIMUM) ? def->maxvcpus : def->vcpus;
3224

3225
cleanup:
3226 3227
    if (vm)
        virDomainObjUnlock(vm);
3228 3229 3230
    return ret;
}

3231 3232 3233
static int
qemudDomainGetMaxVcpus(virDomainPtr dom)
{
3234
    return qemudDomainGetVcpusFlags(dom, (VIR_DOMAIN_AFFECT_LIVE |
3235 3236 3237
                                          VIR_DOMAIN_VCPU_MAXIMUM));
}

3238 3239 3240 3241 3242 3243 3244 3245 3246
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);

3247 3248
    memset(seclabel, 0, sizeof(*seclabel));

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

3257
    if (!virDomainVirtTypeToString(vm->def->virtType)) {
3258 3259 3260
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unknown virt type in domain definition '%d'"),
                        vm->def->virtType);
3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277
        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 已提交
3278
    if (virDomainObjIsActive(vm)) {
3279 3280
        if (virSecurityManagerGetProcessLabel(driver->securityManager,
                                              vm, seclabel) < 0) {
3281 3282 3283
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("Failed to get security label"));
            goto cleanup;
3284 3285 3286 3287 3288 3289 3290 3291
        }
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
3292
    qemuDriverUnlock(driver);
3293 3294 3295
    return ret;
}

3296 3297
static int qemudNodeGetSecurityModel(virConnectPtr conn,
                                     virSecurityModelPtr secmodel)
3298 3299 3300
{
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
    char *p;
3301
    int ret = 0;
3302

3303
    qemuDriverLock(driver);
3304 3305 3306 3307 3308
    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)
3309
        goto cleanup;
3310

3311 3312
    p = driver->caps->host.secModel.model;
    if (strlen(p) >= VIR_SECURITY_MODEL_BUFLEN-1) {
3313 3314 3315
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security model string exceeds max %d bytes"),
                        VIR_SECURITY_MODEL_BUFLEN-1);
3316 3317
        ret = -1;
        goto cleanup;
3318 3319 3320 3321 3322
    }
    strcpy(secmodel->model, p);

    p = driver->caps->host.secModel.doi;
    if (strlen(p) >= VIR_SECURITY_DOI_BUFLEN-1) {
3323 3324 3325
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security DOI string exceeds max %d bytes"),
                        VIR_SECURITY_DOI_BUFLEN-1);
3326 3327
        ret = -1;
        goto cleanup;
3328 3329
    }
    strcpy(secmodel->doi, p);
3330 3331 3332 3333

cleanup:
    qemuDriverUnlock(driver);
    return ret;
3334 3335
}

3336 3337 3338 3339 3340
static int ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4)
qemuDomainSaveImageOpen(struct qemud_driver *driver,
                        const char *path,
                        virDomainDefPtr *ret_def,
                        struct qemud_save_header *ret_header)
J
Jiri Denemark 已提交
3341 3342
{
    int fd;
3343
    struct qemud_save_header header;
J
Jiri Denemark 已提交
3344 3345
    char *xml = NULL;
    virDomainDefPtr def = NULL;
3346

3347 3348 3349
    if ((fd = virFileOpenAs(path, O_RDONLY, 0, getuid(), getgid(), 0)) < 0) {
        if ((fd != -EACCES && fd != -EPERM) ||
            driver->user == getuid()) {
3350 3351
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("cannot read domain image"));
J
Jiri Denemark 已提交
3352
            goto error;
3353 3354 3355
        }

        /* Opening as root failed, but qemu runs as a different user
3356 3357 3358 3359 3360 3361
         * that might have better luck. */
        if ((fd = virFileOpenAs(path, O_RDONLY, 0,
                                driver->user, driver->group,
                                VIR_FILE_OPEN_AS_UID)) < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("cannot read domain image"));
J
Jiri Denemark 已提交
3362
            goto error;
3363
        }
3364 3365 3366
    }

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
3367 3368
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read qemu header"));
J
Jiri Denemark 已提交
3369
        goto error;
3370 3371 3372
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
3373 3374
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("image magic is incorrect"));
J
Jiri Denemark 已提交
3375
        goto error;
3376 3377 3378
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3379 3380 3381 3382 3383
        /* convert endianess and try again */
        bswap_header(&header);
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3384 3385 3386
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("image version is not supported (%d > %d)"),
                        header.version, QEMUD_SAVE_VERSION);
J
Jiri Denemark 已提交
3387
        goto error;
3388 3389
    }

3390 3391 3392
    if (header.xml_len <= 0) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("invalid XML length: %d"), header.xml_len);
J
Jiri Denemark 已提交
3393
        goto error;
3394 3395
    }

3396 3397
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
        virReportOOMError();
J
Jiri Denemark 已提交
3398
        goto error;
3399 3400 3401
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
3402 3403
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read XML"));
J
Jiri Denemark 已提交
3404
        goto error;
3405 3406 3407
    }

    /* Create a domain from this XML */
3408
    if (!(def = virDomainDefParseString(driver->caps, xml,
3409
                                        VIR_DOMAIN_XML_INACTIVE)))
J
Jiri Denemark 已提交
3410
        goto error;
3411

J
Jiri Denemark 已提交
3412
    VIR_FREE(xml);
3413

J
Jiri Denemark 已提交
3414 3415
    *ret_def = def;
    *ret_header = header;
3416

J
Jiri Denemark 已提交
3417
    return fd;
3418

J
Jiri Denemark 已提交
3419 3420 3421
error:
    virDomainDefFree(def);
    VIR_FREE(xml);
3422
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
3423 3424 3425 3426

    return -1;
}

3427 3428 3429 3430 3431 3432 3433
static int ATTRIBUTE_NONNULL(4) ATTRIBUTE_NONNULL(5) ATTRIBUTE_NONNULL(6)
qemuDomainSaveImageStartVM(virConnectPtr conn,
                           struct qemud_driver *driver,
                           virDomainObjPtr vm,
                           int *fd,
                           const struct qemud_save_header *header,
                           const char *path)
J
Jiri Denemark 已提交
3434 3435 3436 3437
{
    int ret = -1;
    virDomainEventPtr event;
    int intermediatefd = -1;
3438
    virCommandPtr cmd = NULL;
J
Jiri Denemark 已提交
3439 3440 3441

    if (header->version == 2) {
        const char *prog = qemudSaveCompressionTypeToString(header->compressed);
3442
        if (prog == NULL) {
3443 3444
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("Invalid compressed save format %d"),
J
Jiri Denemark 已提交
3445 3446
                            header->compressed);
            goto out;
3447
        }
3448

J
Jiri Denemark 已提交
3449
        if (header->compressed != QEMUD_SAVE_FORMAT_RAW) {
3450
            cmd = virCommandNewArgList(prog, "-dc", NULL);
3451 3452
            intermediatefd = *fd;
            *fd = -1;
3453 3454 3455 3456 3457

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

            if (virCommandRunAsync(cmd, NULL) < 0) {
3458 3459
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Failed to start decompression binary %s"),
3460
                                prog);
3461
                *fd = intermediatefd;
J
Jiri Denemark 已提交
3462
                goto out;
3463 3464 3465
            }
        }
    }
J
Jiri Denemark 已提交
3466

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

3471
    if (intermediatefd != -1) {
3472
        if (ret < 0) {
3473 3474 3475
            /* if there was an error setting up qemu, the intermediate
             * process will wait forever to write to stdout, so we
             * must manually kill it.
3476 3477
             */
            VIR_FORCE_CLOSE(intermediatefd);
3478
            VIR_FORCE_CLOSE(*fd);
3479 3480
        }

3481 3482
        if (virCommandWait(cmd, NULL) < 0)
            ret = -1;
3483
    }
3484
    VIR_FORCE_CLOSE(intermediatefd);
J
Jiri Denemark 已提交
3485

3486 3487 3488
    if (VIR_CLOSE(*fd) < 0) {
        virReportSystemError(errno, _("cannot close file: %s"), path);
        ret = -1;
3489
    }
J
Jiri Denemark 已提交
3490

3491
    if (ret < 0) {
3492
        qemuAuditDomainStart(vm, "restored", false);
J
Jiri Denemark 已提交
3493
        goto out;
3494
    }
3495

3496 3497 3498
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
3499
    qemuAuditDomainStart(vm, "restored", true);
J
Jiri Denemark 已提交
3500 3501 3502
    if (event)
        qemuDomainEventQueue(driver, event);

3503

3504
    /* If it was running before, resume it now. */
J
Jiri Denemark 已提交
3505
    if (header->was_running) {
J
Jiri Denemark 已提交
3506 3507
        if (qemuProcessStartCPUs(driver, vm, conn,
                                 VIR_DOMAIN_RUNNING_RESTORED) < 0) {
3508
            if (virGetLastError() == NULL)
3509 3510
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("failed to resume domain"));
J
Jiri Denemark 已提交
3511
            goto out;
3512
        }
3513 3514
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
J
Jiri Denemark 已提交
3515
            goto out;
3516
        }
3517
    }
J
Jiri Denemark 已提交
3518

3519
    ret = 0;
3520

J
Jiri Denemark 已提交
3521
out:
3522
    virCommandFree(cmd);
3523 3524
    if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
                                                 vm, path) < 0)
3525 3526
        VIR_WARN("failed to restore save state label on %s", path);

J
Jiri Denemark 已提交
3527 3528 3529
    return ret;
}

3530 3531 3532 3533
static int
qemuDomainRestore(virConnectPtr conn,
                  const char *path)
{
J
Jiri Denemark 已提交
3534 3535 3536 3537 3538 3539 3540 3541 3542
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    int fd = -1;
    int ret = -1;
    struct qemud_save_header header;

    qemuDriverLock(driver);

3543
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header);
J
Jiri Denemark 已提交
3544 3545 3546 3547 3548 3549 3550 3551 3552
    if (fd < 0)
        goto cleanup;

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

    if (!(vm = virDomainAssignDef(driver->caps,
                                  &driver->domains,
                                  def, true))) {
3553
        /* virDomainAssignDef already set the error */
J
Jiri Denemark 已提交
3554 3555 3556 3557 3558 3559 3560
        goto cleanup;
    }
    def = NULL;

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

3561
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path);
J
Jiri Denemark 已提交
3562 3563

    if (qemuDomainObjEndJob(vm) == 0)
3564
        vm = NULL;
J
Jiri Denemark 已提交
3565 3566 3567 3568
    else if (ret < 0 && !vm->persistent) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }
3569

3570 3571
cleanup:
    virDomainDefFree(def);
3572
    VIR_FORCE_CLOSE(fd);
3573 3574 3575
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
3576
    return ret;
D
Daniel P. Berrange 已提交
3577 3578
}

3579 3580 3581 3582 3583
static int
qemuDomainObjRestore(virConnectPtr conn,
                     struct qemud_driver *driver,
                     virDomainObjPtr vm,
                     const char *path)
J
Jiri Denemark 已提交
3584 3585 3586 3587 3588 3589
{
    virDomainDefPtr def = NULL;
    int fd = -1;
    int ret = -1;
    struct qemud_save_header header;

3590
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header);
J
Jiri Denemark 已提交
3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610
    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;

3611
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path);
J
Jiri Denemark 已提交
3612 3613 3614

cleanup:
    virDomainDefFree(def);
3615
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
3616 3617 3618
    return ret;
}

D
Daniel P. Berrange 已提交
3619

3620 3621
static char *qemuDomainGetXMLDesc(virDomainPtr dom,
                                  int flags) {
3622 3623 3624
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;
3625 3626
    unsigned long balloon;
    int err;
3627

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

D
Daniel P. Berrange 已提交
3631
    if (!vm) {
3632 3633
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3634 3635
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
3636
        goto cleanup;
D
Daniel P. Berrange 已提交
3637 3638
    }

3639 3640 3641 3642
    /* 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))) {
3643
        qemuDomainObjPrivatePtr priv = vm->privateData;
3644 3645 3646
        /* Don't delay if someone's using the monitor, just use
         * existing most recent data instead */
        if (!priv->jobActive) {
3647
            if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
3648 3649
                goto cleanup;

3650
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
3651
            err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
3652
            qemuDomainObjExitMonitorWithDriver(driver, vm);
3653 3654 3655 3656
            if (qemuDomainObjEndJob(vm) == 0) {
                vm = NULL;
                goto cleanup;
            }
3657 3658 3659
            if (err < 0)
                goto cleanup;
            if (err > 0)
3660
                vm->def->mem.cur_balloon = balloon;
3661 3662
            /* err == 0 indicates no balloon support, so ignore it */
        }
3663
    }
3664

3665
    ret = qemuDomainFormatXML(driver, vm, flags);
3666 3667

cleanup:
3668 3669
    if (vm)
        virDomainObjUnlock(vm);
3670
    qemuDriverUnlock(driver);
3671
    return ret;
D
Daniel P. Berrange 已提交
3672 3673 3674
}


3675 3676 3677 3678
static char *qemuDomainXMLFromNative(virConnectPtr conn,
                                     const char *format,
                                     const char *config,
                                     unsigned int flags ATTRIBUTE_UNUSED) {
3679
    struct qemud_driver *driver = conn->privateData;
3680 3681 3682 3683
    virDomainDefPtr def = NULL;
    char *xml = NULL;

    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
3684 3685
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
3686 3687 3688
        goto cleanup;
    }

3689
    qemuDriverLock(driver);
3690
    def = qemuParseCommandLineString(driver->caps, config);
3691
    qemuDriverUnlock(driver);
3692 3693 3694
    if (!def)
        goto cleanup;

3695
    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
3696 3697 3698 3699 3700 3701

cleanup:
    virDomainDefFree(def);
    return xml;
}

3702 3703 3704 3705 3706 3707
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;
3708
    virDomainChrSourceDef monConfig;
3709
    virBitmapPtr qemuCaps = NULL;
E
Eric Blake 已提交
3710
    virCommandPtr cmd = NULL;
3711 3712 3713
    char *ret = NULL;
    int i;

3714 3715
    qemuDriverLock(driver);

3716
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
3717 3718
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
3719 3720 3721
        goto cleanup;
    }

3722
    def = virDomainDefParseString(driver->caps, xmlData, 0);
3723 3724 3725
    if (!def)
        goto cleanup;

3726 3727
    /* Since we're just exporting args, we can't do bridge/network/direct
     * setups, since libvirt will normally create TAP/macvtap devices
3728 3729 3730 3731 3732
     * 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];
3733
        int bootIndex = net->bootIndex;
3734 3735
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK ||
            net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755
            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;
        }
3756
        net->bootIndex = bootIndex;
3757 3758 3759 3760
    }
    for (i = 0 ; i < def->ngraphics ; i++) {
        if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
            def->graphics[i]->data.vnc.autoport)
3761
            def->graphics[i]->data.vnc.port = QEMU_VNC_PORT_MIN;
3762 3763
    }

3764
    if (qemuCapsExtractVersionInfo(def->emulator, def->os.arch,
3765
                                   NULL,
3766
                                   &qemuCaps) < 0)
3767 3768
        goto cleanup;

3769
    if (qemuProcessPrepareMonitorChr(driver, &monConfig, def->name) < 0)
3770
        goto cleanup;
3771

3772
    if (!(cmd = qemuBuildCommandLine(conn, driver, def,
3773
                                     &monConfig, false, qemuCaps,
3774
                                     NULL, -1, NULL, VIR_VM_OP_NO_OP)))
3775 3776
        goto cleanup;

E
Eric Blake 已提交
3777
    ret = virCommandToString(cmd);
3778 3779

cleanup:
3780
    qemuDriverUnlock(driver);
3781

3782
    qemuCapsFree(qemuCaps);
E
Eric Blake 已提交
3783
    virCommandFree(cmd);
3784 3785 3786 3787 3788
    virDomainDefFree(def);
    return ret;
}


3789
static int qemudListDefinedDomains(virConnectPtr conn,
3790
                            char **const names, int nnames) {
3791
    struct qemud_driver *driver = conn->privateData;
3792
    int n;
3793

3794
    qemuDriverLock(driver);
3795
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
3796
    qemuDriverUnlock(driver);
3797
    return n;
D
Daniel P. Berrange 已提交
3798 3799
}

3800
static int qemudNumDefinedDomains(virConnectPtr conn) {
3801
    struct qemud_driver *driver = conn->privateData;
3802
    int n;
3803

3804
    qemuDriverLock(driver);
3805
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
3806
    qemuDriverUnlock(driver);
3807

3808
    return n;
D
Daniel P. Berrange 已提交
3809 3810 3811
}


J
Jiri Denemark 已提交
3812 3813
static int qemudDomainObjStart(virConnectPtr conn,
                               struct qemud_driver *driver,
3814 3815
                               virDomainObjPtr vm,
                               bool start_paused)
J
Jiri Denemark 已提交
3816 3817 3818 3819 3820 3821
{
    int ret = -1;
    char *managed_save;

    /*
     * If there is a managed saved state restore it instead of starting
3822
     * from scratch. The old state is removed once the restoring succeeded.
J
Jiri Denemark 已提交
3823 3824
     */
    managed_save = qemuDomainManagedSavePath(driver, vm);
3825 3826 3827 3828

    if (!managed_save)
        goto cleanup;

E
Eric Blake 已提交
3829
    if (virFileExists(managed_save)) {
3830
        ret = qemuDomainObjRestore(conn, driver, vm, managed_save);
J
Jiri Denemark 已提交
3831

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

3835
        goto cleanup;
J
Jiri Denemark 已提交
3836 3837
    }

3838 3839
    ret = qemuProcessStart(conn, driver, vm, NULL, start_paused, -1, NULL,
                           VIR_VM_OP_CREATE);
3840
    qemuAuditDomainStart(vm, "booted", ret >= 0);
3841
    if (ret >= 0) {
J
Jiri Denemark 已提交
3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854
        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;
}

3855 3856 3857
static int
qemudDomainStartWithFlags(virDomainPtr dom, unsigned int flags)
{
3858 3859 3860
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
3861

3862
    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);
3863

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

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

3875 3876 3877 3878
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

    if (virDomainObjIsActive(vm)) {
3879 3880
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is already running"));
3881 3882 3883
        goto endjob;
    }

3884 3885
    ret = qemudDomainObjStart(dom->conn, driver, vm,
                              (flags & VIR_DOMAIN_START_PAUSED) != 0);
3886

3887
endjob:
3888 3889
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
3890

3891
cleanup:
3892 3893
    if (vm)
        virDomainObjUnlock(vm);
3894
    qemuDriverUnlock(driver);
3895
    return ret;
D
Daniel P. Berrange 已提交
3896 3897
}

3898 3899 3900 3901 3902 3903
static int
qemudDomainStart(virDomainPtr dom)
{
    return qemudDomainStartWithFlags(dom, 0);
}

3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918
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;

3919
        if (STRNEQ(def->os.machine, machine->name))
3920 3921 3922
            continue;

        if (!(*canonical = strdup(machine->canonical))) {
3923
            virReportOOMError();
3924 3925 3926 3927 3928 3929 3930 3931 3932
            return -1;
        }

        break;
    }

    return 0;
}

3933 3934 3935 3936 3937 3938
static int
qemudCanonicalizeMachineDirect(virDomainDefPtr def, char **canonical)
{
    virCapsGuestMachinePtr *machines = NULL;
    int i, nmachines = 0;

3939
    if (qemuCapsProbeMachineTypes(def->emulator, &machines, &nmachines) < 0)
3940 3941 3942 3943 3944 3945
        return -1;

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

3946
        if (STRNEQ(def->os.machine, machines[i]->name))
3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958
            continue;

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

    virCapabilitiesFreeMachines(machines, nmachines);

    return 0;
}

3959 3960
int
qemudCanonicalizeMachine(struct qemud_driver *driver, virDomainDefPtr def)
3961 3962 3963 3964 3965 3966
{
    char *canonical = NULL;
    int i;

    for (i = 0; i < driver->caps->nguests; i++) {
        virCapsGuestPtr guest = driver->caps->guests[i];
3967
        virCapsGuestDomainInfoPtr info;
3968 3969 3970
        int j;

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

3973 3974 3975 3976 3977 3978 3979 3980 3981
            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;
3982 3983
        }

3984 3985 3986 3987
        info = &guest->arch.defaultInfo;

        if (info->emulator && STREQ(info->emulator, def->emulator)) {
            if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
3988 3989 3990 3991
                return -1;
            goto out;
        }
    }
3992 3993 3994 3995

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

3996 3997 3998 3999 4000 4001 4002
out:
    if (canonical) {
        VIR_FREE(def->os.machine);
        def->os.machine = canonical;
    }
    return 0;
}
D
Daniel P. Berrange 已提交
4003

4004
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
4005
    struct qemud_driver *driver = conn->privateData;
4006
    virDomainDefPtr def;
4007
    virDomainObjPtr vm = NULL;
4008
    virDomainPtr dom = NULL;
4009
    virDomainEventPtr event = NULL;
4010
    int dupVM;
4011

4012
    qemuDriverLock(driver);
4013
    if (!(def = virDomainDefParseString(driver->caps, xml,
4014
                                        VIR_DOMAIN_XML_INACTIVE)))
4015
        goto cleanup;
4016

4017
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
4018 4019
        goto cleanup;

4020 4021
    if ((dupVM = virDomainObjIsDuplicate(&driver->domains, def, 0)) < 0)
        goto cleanup;
4022

4023
    if (qemudCanonicalizeMachine(driver, def) < 0)
4024 4025
        goto cleanup;

4026
    if (qemuDomainAssignPCIAddresses(def) < 0)
4027 4028
        goto cleanup;

4029
    if (!(vm = virDomainAssignDef(driver->caps,
4030
                                  &driver->domains,
4031
                                  def, false))) {
4032
        goto cleanup;
4033
    }
4034
    def = NULL;
4035
    vm->persistent = 1;
4036

4037
    if (virDomainSaveConfig(driver->configDir,
4038
                            vm->newDef ? vm->newDef : vm->def) < 0) {
4039
        VIR_INFO("Defining domain '%s'", vm->def->name);
4040 4041
        virDomainRemoveInactive(&driver->domains,
                                vm);
4042
        vm = NULL;
4043
        goto cleanup;
4044 4045
    }

4046 4047
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
4048
                                     !dupVM ?
4049 4050
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
4051

4052
    VIR_INFO("Creating domain '%s'", vm->def->name);
4053
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
4054
    if (dom) dom->id = vm->def->id;
4055 4056

cleanup:
4057
    virDomainDefFree(def);
4058 4059
    if (vm)
        virDomainObjUnlock(vm);
4060 4061
    if (event)
        qemuDomainEventQueue(driver, event);
4062
    qemuDriverUnlock(driver);
4063
    return dom;
D
Daniel P. Berrange 已提交
4064 4065
}

4066
static int qemudDomainUndefine(virDomainPtr dom) {
4067 4068
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4069
    virDomainEventPtr event = NULL;
4070
    int ret = -1;
D
Daniel P. Berrange 已提交
4071

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

D
Daniel P. Berrange 已提交
4075
    if (!vm) {
4076 4077
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4078 4079
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4080
        goto cleanup;
D
Daniel P. Berrange 已提交
4081 4082
    }

D
Daniel P. Berrange 已提交
4083
    if (virDomainObjIsActive(vm)) {
4084 4085
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot delete active domain"));
4086
        goto cleanup;
D
Daniel P. Berrange 已提交
4087 4088
    }

4089
    if (!vm->persistent) {
4090
        qemuReportError(VIR_ERR_OPERATION_INVALID,
4091
                        "%s", _("cannot undefine transient domain"));
4092
        goto cleanup;
4093 4094
    }

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

4098 4099 4100
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
4101

4102
    VIR_INFO("Undefining domain '%s'", vm->def->name);
4103 4104
    virDomainRemoveInactive(&driver->domains,
                            vm);
4105
    vm = NULL;
4106
    ret = 0;
D
Daniel P. Berrange 已提交
4107

4108
cleanup:
4109 4110
    if (vm)
        virDomainObjUnlock(vm);
4111 4112
    if (event)
        qemuDomainEventQueue(driver, event);
4113
    qemuDriverUnlock(driver);
4114
    return ret;
D
Daniel P. Berrange 已提交
4115 4116
}

4117 4118 4119
static int
qemuDomainAttachDeviceDiskLive(struct qemud_driver *driver,
                               virDomainObjPtr vm,
4120
                               virDomainDeviceDefPtr dev)
4121 4122 4123 4124
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
    int ret = -1;
4125

4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145
    if (disk->driverName != NULL && !STREQ(disk->driverName, "qemu")) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unsupported driver name '%s' for disk '%s'"),
                        disk->driverName, disk->src);
        goto end;
    }

    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Unable to find cgroup for %s"),
                            vm->def->name);
            goto end;
        }
        if (qemuSetupDiskCgroup(driver, vm, cgroup, disk) < 0)
            goto end;
    }
    switch (disk->device)  {
    case VIR_DOMAIN_DISK_DEVICE_CDROM:
    case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
4146
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, false);
4147 4148 4149 4150
        break;
    case VIR_DOMAIN_DISK_DEVICE_DISK:
        if (disk->bus == VIR_DOMAIN_DISK_BUS_USB)
            ret = qemuDomainAttachUsbMassstorageDevice(driver, vm,
4151
                                                       disk);
4152
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
4153
            ret = qemuDomainAttachPciDiskDevice(driver, vm, disk);
4154
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
4155
            ret = qemuDomainAttachSCSIDisk(driver, vm, disk);
4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181
        else
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                            _("disk bus '%s' cannot be hotplugged."),
                            virDomainDiskBusTypeToString(disk->bus));
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("disk device type '%s' cannot be hotplugged"),
                        virDomainDiskDeviceTypeToString(disk->device));
        break;
    }

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

static int
qemuDomainAttachDeviceControllerLive(struct qemud_driver *driver,
                                     virDomainObjPtr vm,
4182
                                     virDomainDeviceDefPtr dev)
4183 4184 4185 4186 4187 4188
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
4189
        ret = qemuDomainAttachPciControllerDevice(driver, vm, cont);
4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("disk controller bus '%s' cannot be hotplugged."),
                        virDomainControllerTypeToString(cont->type));
        break;
    }
    return ret;
}

static int
qemuDomainAttachDeviceLive(virDomainObjPtr vm,
                           virDomainDeviceDefPtr dev,
4203
                           virDomainPtr dom)
4204 4205 4206 4207 4208 4209
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
4210
        qemuDomainObjCheckDiskTaint(driver, vm, dev->data.disk, -1);
4211
        ret = qemuDomainAttachDeviceDiskLive(driver, vm, dev);
4212 4213 4214 4215 4216
        if (!ret)
            dev->data.disk = NULL;
        break;

    case VIR_DOMAIN_DEVICE_CONTROLLER:
4217
        ret = qemuDomainAttachDeviceControllerLive(driver, vm, dev);
4218 4219 4220 4221
        if (!ret)
            dev->data.controller = NULL;
        break;

4222 4223 4224 4225 4226 4227 4228
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainAttachLease(driver, vm,
                                    dev->data.lease);
        if (ret == 0)
            dev->data.lease = NULL;
        break;

4229
    case VIR_DOMAIN_DEVICE_NET:
4230
        qemuDomainObjCheckNetTaint(driver, vm, dev->data.net, -1);
4231
        ret = qemuDomainAttachNetDevice(dom->conn, driver, vm,
4232
                                        dev->data.net);
4233 4234 4235 4236 4237 4238
        if (!ret)
            dev->data.net = NULL;
        break;

    case VIR_DOMAIN_DEVICE_HOSTDEV:
        ret = qemuDomainAttachHostDevice(driver, vm,
4239
                                         dev->data.hostdev);
4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256
        if (!ret)
            dev->data.hostdev = NULL;
        break;

    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("device type '%s' cannot be attached"),
                        virDomainDeviceTypeToString(dev->type));
        break;
    }

    return ret;
}

static int
qemuDomainDetachDeviceDiskLive(struct qemud_driver *driver,
                               virDomainObjPtr vm,
4257
                               virDomainDeviceDefPtr dev)
4258 4259 4260 4261 4262 4263 4264
{
    virDomainDiskDefPtr disk = dev->data.disk;
    int ret = -1;

    switch (disk->device) {
    case VIR_DOMAIN_DISK_DEVICE_DISK:
        if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
4265
            ret = qemuDomainDetachPciDiskDevice(driver, vm, dev);
4266
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
4267
            ret =  qemuDomainDetachDiskDevice(driver, vm, dev);
4268
        else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB)
4269
            ret = qemuDomainDetachDiskDevice(driver, vm, dev);
4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285
        else
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                            _("This type of disk cannot be hot unplugged"));
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("device type '%s' cannot be detached"),
                        virDomainDeviceTypeToString(dev->type));
        break;
    }
    return ret;
}

static int
qemuDomainDetachDeviceControllerLive(struct qemud_driver *driver,
                                     virDomainObjPtr vm,
4286
                                     virDomainDeviceDefPtr dev)
4287 4288 4289 4290 4291 4292
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
4293
        ret = qemuDomainDetachPciControllerDevice(driver, vm, dev);
4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305
        break;
    default :
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("disk controller bus '%s' cannot be hotunplugged."),
                        virDomainControllerTypeToString(cont->type));
    }
    return ret;
}

static int
qemuDomainDetachDeviceLive(virDomainObjPtr vm,
                           virDomainDeviceDefPtr dev,
4306
                           virDomainPtr dom)
4307 4308 4309 4310 4311 4312
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
4313
        ret = qemuDomainDetachDeviceDiskLive(driver, vm, dev);
4314 4315
        break;
    case VIR_DOMAIN_DEVICE_CONTROLLER:
4316
        ret = qemuDomainDetachDeviceControllerLive(driver, vm, dev);
4317
        break;
4318 4319 4320
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainDetachLease(driver, vm, dev->data.lease);
        break;
4321
    case VIR_DOMAIN_DEVICE_NET:
4322
        ret = qemuDomainDetachNetDevice(driver, vm, dev);
4323 4324
        break;
    case VIR_DOMAIN_DEVICE_HOSTDEV:
4325
        ret = qemuDomainDetachHostDevice(driver, vm, dev);
4326 4327 4328 4329 4330 4331 4332 4333 4334 4335
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        "%s", _("This type of device cannot be hot unplugged"));
        break;
    }

    return ret;
}

4336 4337 4338 4339 4340 4341 4342 4343
static int
qemuDomainChangeDiskMediaLive(virDomainObjPtr vm,
                              virDomainDeviceDefPtr dev,
                              struct qemud_driver *driver,
                              bool force)
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
4344
    int ret = -1;
4345 4346 4347

    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup,
4348
                               vm->def->name, &cgroup, 0) != 0) {
4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Unable to find cgroup for %s"),
                            vm->def->name);
            goto end;
        }
        if (qemuSetupDiskCgroup(driver, vm, cgroup, disk) < 0)
            goto end;
    }

    switch (disk->device) {
    case VIR_DOMAIN_DISK_DEVICE_CDROM:
    case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
4361
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, force);
4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393
        if (ret == 0)
            dev->data.disk = NULL;
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("disk bus '%s' cannot be updated."),
                        virDomainDiskBusTypeToString(disk->bus));
        break;
    }

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

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

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
4394
        ret = qemuDomainChangeDiskMediaLive(vm, dev, driver, force);
4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408
        break;
    case VIR_DOMAIN_DEVICE_GRAPHICS:
        ret = qemuDomainChangeGraphics(driver, vm, dev->data.graphics);
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("device type '%s' cannot be updated"),
                        virDomainDeviceTypeToString(dev->type));
        break;
    }

    return ret;
}

4409
static int
4410
qemuDomainAttachDeviceConfig(virDomainDefPtr vmdef,
4411 4412
                             virDomainDeviceDefPtr dev)
{
4413
    virDomainDiskDefPtr disk;
4414
    virDomainNetDefPtr net;
4415
    virDomainLeaseDefPtr lease;
4416

4417
    switch (dev->type) {
4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
        if (virDomainDiskIndexByName(vmdef, disk->dst) >= 0) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("target %s already exists."), disk->dst);
            return -1;
        }
        if (virDomainDiskInsert(vmdef, disk)) {
            virReportOOMError();
            return -1;
        }
        /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
        dev->data.disk = NULL;
        if (disk->bus != VIR_DOMAIN_DISK_BUS_VIRTIO)
            if (virDomainDefAddImplicitControllers(vmdef) < 0)
                return -1;
        if (qemuDomainAssignPCIAddresses(vmdef) < 0)
            return -1;
        break;

4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454
    case VIR_DOMAIN_DEVICE_NET:
        net = dev->data.net;
        if (virDomainNetIndexByMac(vmdef, net->mac) >= 0) {
            char macbuf[VIR_MAC_STRING_BUFLEN];
            virFormatMacAddr(net->mac, macbuf);
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("mac %s already exists"), macbuf);
            return -1;
        }
        if (virDomainNetInsert(vmdef, net)) {
            virReportOOMError();
            return -1;
        }
        dev->data.net = NULL;
        if (qemuDomainAssignPCIAddresses(vmdef) < 0)
            return -1;
        break;
4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470

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

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

4471 4472 4473 4474 4475 4476 4477 4478 4479 4480
    default:
         qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                         _("persistent attach of device is not supported"));
         return -1;
    }
    return 0;
}


static int
4481
qemuDomainDetachDeviceConfig(virDomainDefPtr vmdef,
4482 4483
                             virDomainDeviceDefPtr dev)
{
4484
    virDomainDiskDefPtr disk;
4485
    virDomainNetDefPtr net;
4486
    virDomainLeaseDefPtr lease;
4487

4488
    switch (dev->type) {
4489 4490 4491 4492 4493 4494 4495 4496
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
        if (virDomainDiskRemoveByName(vmdef, disk->dst)) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("no target device %s"), disk->dst);
            return -1;
        }
        break;
4497

4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508
    case VIR_DOMAIN_DEVICE_NET:
        net = dev->data.net;
        if (virDomainNetRemoveByMac(vmdef, net->mac)) {
            char macbuf[VIR_MAC_STRING_BUFLEN];

            virFormatMacAddr(net->mac, macbuf);
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("no nic of mac %s"), macbuf);
            return -1;
        }
        break;
4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519

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

4520 4521 4522 4523 4524 4525 4526 4527 4528
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("persistent detach of device is not supported"));
        return -1;
    }
    return 0;
}

static int
4529
qemuDomainUpdateDeviceConfig(virDomainDefPtr vmdef,
4530 4531
                             virDomainDeviceDefPtr dev)
{
4532 4533 4534
    virDomainDiskDefPtr orig, disk;
    int pos;

4535
    switch (dev->type) {
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
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
        pos = virDomainDiskIndexByName(vmdef, disk->dst);
        if (pos < 0) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("target %s doesn't exists."), disk->dst);
            return -1;
        }
        orig = vmdef->disks[pos];
        if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM) &&
            !(orig->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY)) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("this disk doesn't support update"));
            return -1;
        }
        /*
         * Update 'orig'
         * We allow updating src/type//driverType/cachemode/
         */
        VIR_FREE(orig->src);
        orig->src = disk->src;
        orig->type = disk->type;
        orig->cachemode = disk->cachemode;
        if (disk->driverName) {
            VIR_FREE(orig->driverName);
            orig->driverName = disk->driverName;
            disk->driverName = NULL;
        }
        if (disk->driverType) {
            VIR_FREE(orig->driverType);
            orig->driverType = disk->driverType;
            disk->driverType = NULL;
        }
        disk->src = NULL;
        break;
4571 4572 4573 4574 4575 4576 4577 4578
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                         _("persistent update of device is not supported"));
        return -1;
    }
    return 0;
}

4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589
/* Actions for qemuDomainModifyDeviceFlags */
enum {
    QEMU_DEVICE_ATTACH,
    QEMU_DEVICE_DETACH,
    QEMU_DEVICE_UPDATE,
};


static int
qemuDomainModifyDeviceFlags(virDomainPtr dom, const char *xml,
                            unsigned int flags, int action)
4590
{
4591
    struct qemud_driver *driver = dom->conn->privateData;
4592
    virDomainObjPtr vm = NULL;
4593
    virDomainDefPtr vmdef = NULL;
4594
    virDomainDeviceDefPtr dev = NULL;
4595
    bool force = (flags & VIR_DOMAIN_DEVICE_MODIFY_FORCE) != 0;
4596
    int ret = -1;
4597

4598 4599
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
4600 4601 4602
                  (action == QEMU_DEVICE_UPDATE ?
                   VIR_DOMAIN_DEVICE_MODIFY_FORCE : 0), -1);

4603 4604 4605 4606 4607 4608 4609
    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);
4610 4611 4612
        goto cleanup;
    }

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

4616
    if (virDomainObjIsActive(vm)) {
4617 4618
        if (flags == VIR_DOMAIN_AFFECT_CURRENT)
            flags |= VIR_DOMAIN_AFFECT_LIVE;
4619
    } else {
4620 4621
        if (flags == VIR_DOMAIN_AFFECT_CURRENT)
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
4622
        /* check consistency between flags and the vm state */
4623
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
4624 4625 4626 4627 4628 4629
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s",
                            _("cannot do live update a device on "
                              "inactive domain"));
            goto endjob;
        }
4630
    }
4631

4632
    if ((flags & VIR_DOMAIN_AFFECT_CONFIG) && !vm->persistent) {
4633 4634 4635 4636
         qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("cannot modify device on transient domain"));
         goto endjob;
    }
4637

4638
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
4639 4640 4641 4642 4643
        dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                      VIR_DOMAIN_XML_INACTIVE);
        if (dev == NULL)
            goto endjob;

4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664
        /* Make a copy for updated domain. */
        vmdef = virDomainObjCopyPersistentDef(driver->caps, vm);
        if (!vmdef)
            goto endjob;
        switch (action) {
        case QEMU_DEVICE_ATTACH:
            ret = qemuDomainAttachDeviceConfig(vmdef, dev);
            break;
        case QEMU_DEVICE_DETACH:
            ret = qemuDomainDetachDeviceConfig(vmdef, dev);
            break;
        case QEMU_DEVICE_UPDATE:
            ret = qemuDomainUpdateDeviceConfig(vmdef, dev);
            break;
        default:
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("unknown domain modify action %d"), action);
            break;
        }
    } else
        ret = 0;
4665

4666
    if (!ret && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
4667 4668 4669 4670 4671 4672 4673
        /* If dev exists it was created to modify the domain config. Free it. */
        virDomainDeviceDefFree(dev);
        dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                      VIR_DOMAIN_XML_INACTIVE);
        if (dev == NULL)
            goto endjob;

4674 4675
        switch (action) {
        case QEMU_DEVICE_ATTACH:
4676
            ret = qemuDomainAttachDeviceLive(vm, dev, dom);
4677 4678
            break;
        case QEMU_DEVICE_DETACH:
4679
            ret = qemuDomainDetachDeviceLive(vm, dev, dom);
4680 4681
            break;
        case QEMU_DEVICE_UPDATE:
4682
            ret = qemuDomainUpdateDeviceLive(vm, dev, dom, force);
4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697
            break;
        default:
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("unknown domain modify action %d"), action);
            break;
        }
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed. For example, a
         * For example, a new controller may be created.
         */
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
            ret = -1;
    }
    /* Finally, if no error until here, we can save config. */
4698
    if (!ret && (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
4699 4700 4701 4702 4703 4704
        ret = virDomainSaveConfig(driver->configDir, vmdef);
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false);
            vmdef = NULL;
        }
    }
4705 4706 4707 4708 4709 4710

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

cleanup:
4711
    virDomainDefFree(vmdef);
4712 4713 4714 4715
    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
4716 4717 4718
    return ret;
}

4719 4720 4721 4722 4723 4724
static int qemuDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_ATTACH);
}

4725 4726 4727
static int qemuDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainAttachDeviceFlags(dom, xml,
4728
                                       VIR_DOMAIN_AFFECT_LIVE);
4729
}
4730

4731

4732 4733 4734 4735
static int qemuDomainUpdateDeviceFlags(virDomainPtr dom,
                                       const char *xml,
                                       unsigned int flags)
{
4736
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_UPDATE);
4737 4738
}

4739 4740 4741
static int qemuDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
4742
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_DETACH);
4743 4744
}

4745 4746 4747
static int qemuDomainDetachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainDetachDeviceFlags(dom, xml,
4748
                                       VIR_DOMAIN_AFFECT_LIVE);
4749 4750
}

4751
static int qemudDomainGetAutostart(virDomainPtr dom,
4752
                                   int *autostart) {
4753 4754 4755
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
4756

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

4761
    if (!vm) {
4762 4763
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4764 4765
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4766
        goto cleanup;
4767 4768 4769
    }

    *autostart = vm->autostart;
4770
    ret = 0;
4771

4772
cleanup:
4773 4774
    if (vm)
        virDomainObjUnlock(vm);
4775
    return ret;
4776 4777
}

4778
static int qemudDomainSetAutostart(virDomainPtr dom,
4779
                                   int autostart) {
4780 4781
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4782 4783
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
4784

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

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

4796
    if (!vm->persistent) {
4797
        qemuReportError(VIR_ERR_OPERATION_INVALID,
4798
                        "%s", _("cannot set autostart for transient domain"));
4799
        goto cleanup;
4800 4801
    }

4802 4803
    autostart = (autostart != 0);

4804
    if (vm->autostart != autostart) {
4805
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
4806
            goto cleanup;
4807
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
4808
            goto cleanup;
4809

4810 4811
        if (autostart) {
            int err;
4812

4813
            if ((err = virFileMakePath(driver->autostartDir))) {
4814
                virReportSystemError(err,
4815 4816
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
4817 4818
                goto cleanup;
            }
4819

4820
            if (symlink(configFile, autostartLink) < 0) {
4821
                virReportSystemError(errno,
4822 4823
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
4824 4825 4826 4827
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
4828
                virReportSystemError(errno,
4829 4830
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
4831 4832
                goto cleanup;
            }
4833 4834
        }

4835
        vm->autostart = autostart;
4836
    }
4837
    ret = 0;
4838

4839 4840 4841
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
4842 4843
    if (vm)
        virDomainObjUnlock(vm);
4844
    qemuDriverUnlock(driver);
4845
    return ret;
4846 4847
}

4848 4849 4850 4851 4852

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

4855
    qemuDriverLock(driver);
4856
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
4857 4858
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup CPU controller is not mounted"));
4859
        goto cleanup;
4860 4861 4862 4863 4864 4865 4866
    }

    if (nparams)
        *nparams = 1;

    ret = strdup("posix");
    if (!ret)
4867
        virReportOOMError();
4868 4869 4870

cleanup:
    qemuDriverUnlock(driver);
4871 4872 4873
    return ret;
}

4874
static int qemuDomainSetBlkioParameters(virDomainPtr dom,
4875
                                         virTypedParameterPtr params,
4876 4877 4878 4879 4880 4881 4882
                                         int nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
4883
    virDomainDefPtr persistentDef = NULL;
4884
    int ret = -1;
4885
    bool isActive;
4886

4887 4888
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
4889 4890 4891 4892 4893 4894 4895 4896 4897 4898
    qemuDriverLock(driver);

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

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

4899 4900 4901 4902 4903 4904 4905
    isActive = virDomainObjIsActive(vm);

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

4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }

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

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

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

    ret = 0;
4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        for (i = 0; i < nparams; i++) {
            virTypedParameterPtr param = &params[i];

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

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

4958 4959 4960 4961 4962 4963 4964 4965 4966
                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);
4967 4968
                ret = -1;
            }
4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980
        }
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        for (i = 0; i < nparams; i++) {
            virTypedParameterPtr param = &params[i];

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

4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992
                if (params[i].value.ui > 1000 || params[i].value.ui < 100) {
                    qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                    _("out of blkio weight range."));
                    ret = -1;
                    continue;
                }

                persistentDef->blkio.weight = params[i].value.ui;
            } else {
                qemuReportError(VIR_ERR_INVALID_ARG,
                                _("Parameter `%s' not supported"), param->field);
4993 4994 4995
                ret = -1;
            }
        }
4996
        ret = virDomainSaveConfig(driver->configDir, persistentDef);
4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007
    }

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

static int qemuDomainGetBlkioParameters(virDomainPtr dom,
5008
                                         virTypedParameterPtr params,
5009 5010 5011 5012 5013 5014 5015
                                         int *nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5016
    virDomainDefPtr persistentDef = NULL;
5017 5018 5019
    unsigned int val;
    int ret = -1;
    int rc;
5020
    bool isActive;
5021

5022 5023
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046
    qemuDriverLock(driver);

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

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

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

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

5047 5048 5049 5050 5051 5052 5053
    isActive = virDomainObjIsActive(vm);

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

5056 5057 5058 5059 5060 5061
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }
5062

5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
            qemuReportError(VIR_ERR_NO_SUPPORT, _("blkio cgroup isn't mounted"));
            goto cleanup;
        }

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

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

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        for (i = 0; i < *nparams; i++) {
            virTypedParameterPtr param = &params[i];
            val = 0;
            param->value.ui = 0;
            param->type = VIR_TYPED_PARAM_UINT;

            switch (i) {
            case 0: /* fill blkio weight here */
                rc = virCgroupGetBlkioWeight(group, &val);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to get blkio weight"));
                    goto cleanup;
                }
                if (virStrcpyStatic(param->field, VIR_DOMAIN_BLKIO_WEIGHT) == NULL) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                    "%s", _("Field blkio weight too long for destination"));
                    goto cleanup;
                }
                param->value.ui = val;
                break;

            default:
                break;
                /* should not hit here */
5111
            }
5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128
        }
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        for (i = 0; i < *nparams; i++) {
            virTypedParameterPtr param = &params[i];
            val = 0;
            param->value.ui = 0;
            param->type = VIR_TYPED_PARAM_UINT;

            switch (i) {
            case 0: /* fill blkio weight here */
                if (virStrcpyStatic(param->field, VIR_DOMAIN_BLKIO_WEIGHT) == NULL) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                    "%s", _("Field blkio weight too long for destination"));
                    goto cleanup;
                }
                param->value.ui = persistentDef->blkio.weight;
                break;
5129

5130 5131 5132 5133
            default:
                break;
                /* should not hit here */
            }
5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146
        }
    }

    ret = 0;

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

static int qemuDomainSetMemoryParameters(virDomainPtr dom,
5149
                                         virTypedParameterPtr params,
5150
                                         int nparams,
5151
                                         unsigned int flags)
5152 5153 5154
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
5155
    virDomainDefPtr persistentDef = NULL;
5156 5157 5158
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;
5159 5160
    bool isActive;

5161 5162
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173

    qemuDriverLock(driver);

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

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

5174 5175
    isActive = virDomainObjIsActive(vm);

5176
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
5177
        if (isActive)
5178
            flags = VIR_DOMAIN_AFFECT_LIVE;
5179
        else
5180
            flags = VIR_DOMAIN_AFFECT_CONFIG;
5181 5182
    }

5183
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }

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

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

5203
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5204 5205 5206 5207 5208 5209 5210
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot change persistent config of a transient domain"));
            goto cleanup;
        }
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
            goto cleanup;
5211 5212 5213 5214
    }

    ret = 0;
    for (i = 0; i < nparams; i++) {
5215
        virTypedParameterPtr param = &params[i];
5216 5217 5218

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

5226
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5227 5228 5229 5230 5231 5232 5233 5234
                rc = virCgroupSetMemoryHardLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory hard_limit tunable"));
                    ret = -1;
                }
            }

5235
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5236
                persistentDef->mem.hard_limit = params[i].value.ul;
5237 5238 5239
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT)) {
            int rc;
5240
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
5241 5242 5243 5244 5245 5246
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for memory soft_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

5247
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5248 5249 5250 5251 5252 5253 5254 5255
                rc = virCgroupSetMemorySoftLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory soft_limit tunable"));
                    ret = -1;
                }
            }

5256
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5257
                persistentDef->mem.soft_limit = params[i].value.ul;
5258
            }
5259
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT)) {
5260
            int rc;
5261
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
5262 5263 5264 5265 5266 5267
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for swap_hard_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

5268
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5269 5270 5271 5272 5273 5274 5275
                rc = virCgroupSetMemSwapHardLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set swap_hard_limit tunable"));
                    ret = -1;
                }
            }
5276
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5277
                persistentDef->mem.swap_hard_limit = params[i].value.ul;
5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289
            }
        } 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;
        }
    }

5290
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5291 5292 5293
        ret = virDomainSaveConfig(driver->configDir, persistentDef);
    }

5294 5295 5296 5297 5298 5299 5300 5301
cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

5302
static int qemuDomainGetMemoryParameters(virDomainPtr dom,
5303
                                         virTypedParameterPtr params,
5304
                                         int *nparams,
5305
                                         unsigned int flags)
5306 5307 5308 5309 5310
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5311
    virDomainDefPtr persistentDef = NULL;
5312
    unsigned long long val;
5313 5314
    int ret = -1;
    int rc;
5315
    bool isActive;
5316

5317 5318
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5319

5320
    qemuDriverLock(driver);
5321 5322 5323 5324 5325 5326 5327 5328 5329

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

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

5330 5331
    isActive = virDomainObjIsActive(vm);

5332
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
5333
        if (isActive)
5334
            flags = VIR_DOMAIN_AFFECT_LIVE;
5335
        else
5336
            flags = VIR_DOMAIN_AFFECT_CONFIG;
5337 5338
    }

5339
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }

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

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

5359
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5360 5361 5362 5363 5364 5365 5366
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot change persistent config of a transient domain"));
            goto cleanup;
        }
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
            goto cleanup;
5367 5368
    }

5369 5370 5371 5372 5373 5374 5375
    if ((*nparams) == 0) {
        /* Current number of memory parameters supported by cgroups */
        *nparams = QEMU_NB_MEM_PARAM;
        ret = 0;
        goto cleanup;
    }

5376
    if ((*nparams) < QEMU_NB_MEM_PARAM) {
5377 5378 5379 5380 5381
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
        goto cleanup;
    }

5382
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5383 5384 5385 5386
        for (i = 0; i < *nparams; i++) {
            virMemoryParameterPtr param = &params[i];
            val = 0;
            param->value.ul = 0;
5387
            param->type = VIR_TYPED_PARAM_ULLONG;
5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422

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

            case 1: /* fill memory soft limit here */
                if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT) == NULL) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                    "%s", _("Field memory soft limit too long for destination"));
                    goto cleanup;
                }
                param->value.ul = persistentDef->mem.soft_limit;
                break;

            case 2: /* fill swap hard limit here */
                if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT) == NULL) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                    "%s", _("Field swap hard limit too long for destination"));
                    goto cleanup;
                }
                param->value.ul = persistentDef->mem.swap_hard_limit;
                break;

            default:
                break;
                /* should not hit here */
            }
        }
        goto out;
5423 5424
    }

5425
    for (i = 0; i < QEMU_NB_MEM_PARAM; i++) {
5426
        virTypedParameterPtr param = &params[i];
5427 5428
        val = 0;
        param->value.ul = 0;
5429
        param->type = VIR_TYPED_PARAM_ULLONG;
5430

5431
        switch (i) {
5432 5433 5434 5435 5436
        case 0: /* fill memory hard limit here */
            rc = virCgroupGetMemoryHardLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory hard limit"));
5437
                goto cleanup;
5438 5439 5440 5441
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field memory hard limit too long for destination"));
5442
                goto cleanup;
5443 5444 5445 5446 5447 5448 5449 5450 5451
            }
            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"));
5452
                goto cleanup;
5453 5454 5455 5456
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field memory soft limit too long for destination"));
5457
                goto cleanup;
5458 5459 5460 5461 5462
            }
            param->value.ul = val;
            break;

        case 2: /* fill swap hard limit here */
5463
            rc = virCgroupGetMemSwapHardLimit(group, &val);
5464 5465 5466
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get swap hard limit"));
5467
                goto cleanup;
5468
            }
5469
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT) == NULL) {
5470 5471
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field swap hard limit too long for destination"));
5472
                goto cleanup;
5473 5474 5475 5476 5477 5478 5479 5480 5481 5482
            }
            param->value.ul = val;
            break;

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

5483
out:
5484
    *nparams = QEMU_NB_MEM_PARAM;
5485 5486
    ret = 0;

5487 5488 5489 5490 5491 5492 5493 5494 5495
cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

5496
static int qemuSetSchedulerParametersFlags(virDomainPtr dom,
5497
                                           virTypedParameterPtr params,
5498 5499
                                           int nparams,
                                           unsigned int flags)
5500 5501 5502 5503 5504
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5505
    virDomainDefPtr persistentDef = NULL;
5506
    int ret = -1;
5507 5508
    bool isActive;

5509 5510
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5511

5512
    qemuDriverLock(driver);
5513 5514 5515 5516

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

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

5522 5523
    isActive = virDomainObjIsActive(vm);

5524
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
5525
        if (isActive)
5526
            flags = VIR_DOMAIN_AFFECT_LIVE;
5527
        else
5528
            flags = VIR_DOMAIN_AFFECT_CONFIG;
5529 5530
    }

5531
    if ((flags & VIR_DOMAIN_AFFECT_CONFIG) && !vm->persistent) {
5532 5533
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot change persistent config of a transient domain"));
5534 5535 5536
        goto cleanup;
    }

5537
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }

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

5557
    for (i = 0; i < nparams; i++) {
5558
        virTypedParameterPtr param = &params[i];
5559 5560 5561

        if (STREQ(param->field, "cpu_shares")) {
            int rc;
5562
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
5563 5564
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for cpu_shares tunable, expected a 'ullong'"));
5565 5566 5567
                goto cleanup;
            }

5568
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5569 5570 5571 5572 5573 5574 5575 5576
                rc = virCgroupSetCpuShares(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set cpu shares tunable"));
                    goto cleanup;
                }

                vm->def->cputune.shares = params[i].value.ul;
5577
            }
5578

5579
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593
                persistentDef = virDomainObjGetPersistentDef(driver->caps, vm);
                if (!persistentDef) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                    _("can't get persistentDef"));
                    goto cleanup;
                }
                persistentDef->cputune.shares = params[i].value.ul;
                rc = virDomainSaveConfig(driver->configDir, persistentDef);
                if (rc) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                    _("can't save config"));
                    goto cleanup;
                }
            }
5594
        } else {
5595 5596
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Invalid parameter `%s'"), param->field);
5597 5598 5599
            goto cleanup;
        }
    }
5600

5601 5602 5603 5604 5605 5606
    ret = 0;

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

5611
static int qemuSetSchedulerParameters(virDomainPtr dom,
5612
                                      virTypedParameterPtr params,
5613 5614 5615 5616 5617
                                      int nparams)
{
    return qemuSetSchedulerParametersFlags(dom,
                                           params,
                                           nparams,
5618
                                           VIR_DOMAIN_AFFECT_LIVE);
5619 5620
}

5621 5622 5623 5624 5625
static int
qemuGetSchedulerParametersFlags(virDomainPtr dom,
                                virTypedParameterPtr params,
                                int *nparams,
                                unsigned int flags)
5626 5627 5628 5629 5630 5631 5632
{
    struct qemud_driver *driver = dom->conn->privateData;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    unsigned long long val;
    int ret = -1;
    int rc;
5633
    bool isActive;
5634

5635 5636
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5637

5638 5639
    if ((flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)) ==
        (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)) {
5640 5641
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("cannot query live and config together"));
5642
        goto cleanup;
5643 5644
    }

5645
    if (*nparams < 1) {
5646 5647
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
5648
        goto cleanup;
5649 5650
    }

5651
    qemuDriverLock(driver);
5652 5653 5654
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

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

5660 5661
    isActive = virDomainObjIsActive(vm);

5662
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
5663
        if (isActive)
5664
            flags = VIR_DOMAIN_AFFECT_LIVE;
5665
        else
5666
            flags = VIR_DOMAIN_AFFECT_CONFIG;
5667 5668
    }

5669
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot query persistent config of a transient domain"));
            goto cleanup;
        }

        if (isActive) {
            virDomainDefPtr persistentDef;

            persistentDef = virDomainObjGetPersistentDef(driver->caps, vm);
            if (!persistentDef) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("can't get persistentDef"));
                goto cleanup;
            }
            val = persistentDef->cputune.shares;
        } else {
            val = vm->def->cputune.shares;
        }
5689
        goto out;
5690 5691
    }

5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703
    if (!isActive) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("domain is not running"));
        goto cleanup;
    }

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

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

    rc = virCgroupGetCpuShares(group, &val);
    if (rc != 0) {
5712
        virReportSystemError(-rc, "%s",
5713 5714 5715
                             _("unable to get cpu shares tunable"));
        goto cleanup;
    }
5716
out:
5717
    params[0].value.ul = val;
5718
    params[0].type = VIR_TYPED_PARAM_ULLONG;
C
Chris Lalancette 已提交
5719
    if (virStrcpyStatic(params[0].field, "cpu_shares") == NULL) {
5720 5721
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Field cpu_shares too long for destination"));
C
Chris Lalancette 已提交
5722 5723
        goto cleanup;
    }
5724

5725
    *nparams = 1;
5726 5727 5728 5729 5730 5731
    ret = 0;

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

5736 5737 5738 5739 5740 5741
static int
qemuGetSchedulerParameters(virDomainPtr dom,
                           virTypedParameterPtr params,
                           int *nparams)
{
    return qemuGetSchedulerParametersFlags(dom, params, nparams,
5742
                                           VIR_DOMAIN_AFFECT_CURRENT);
5743
}
5744

5745 5746 5747 5748 5749 5750 5751 5752 5753
/* 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)
{
5754
    struct qemud_driver *driver = dom->conn->privateData;
5755
    int i, ret = -1;
5756
    virDomainObjPtr vm;
5757
    virDomainDiskDefPtr disk = NULL;
5758
    qemuDomainObjPrivatePtr priv;
5759

5760
    qemuDriverLock(driver);
5761
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5762
    qemuDriverUnlock(driver);
5763
    if (!vm) {
5764 5765
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5766 5767
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5768
        goto cleanup;
5769
    }
5770

5771 5772 5773 5774 5775 5776
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

5777 5778 5779 5780 5781 5782 5783 5784
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

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

5790
    if (!disk->info.alias) {
5791 5792
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("missing disk device alias name for %s"), disk->dst);
5793
        goto cleanup;
5794
    }
5795

5796
    priv = vm->privateData;
5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831
    if ((priv->jobActive == QEMU_JOB_MIGRATION_OUT)
        || (priv->jobActive == QEMU_JOB_SAVE)) {
        virDomainObjRef(vm);
        while (priv->jobSignals & QEMU_JOB_SIGNAL_BLKSTAT)
            ignore_value(virCondWait(&priv->signalCond, &vm->lock));

        priv->jobSignalsData.statDevName = disk->info.alias;
        priv->jobSignalsData.blockStat = stats;
        priv->jobSignalsData.statRetCode = &ret;
        priv->jobSignals |= QEMU_JOB_SIGNAL_BLKSTAT;

        while (priv->jobSignals & QEMU_JOB_SIGNAL_BLKSTAT)
            ignore_value(virCondWait(&priv->signalCond, &vm->lock));

        if (virDomainObjUnref(vm) == 0)
            vm = NULL;
    } else {
        if (qemuDomainObjBeginJob(vm) < 0)
            goto cleanup;

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

        qemuDomainObjEnterMonitor(vm);
        ret = qemuMonitorGetBlockStatsInfo(priv->mon,
                                           disk->info.alias,
                                           &stats->rd_req,
                                           &stats->rd_bytes,
                                           &stats->wr_req,
                                           &stats->wr_bytes,
                                           &stats->errs);
        qemuDomainObjExitMonitor(vm);
5832

5833
endjob:
5834 5835 5836
        if (qemuDomainObjEndJob(vm) == 0)
            vm = NULL;
    }
5837

5838
cleanup:
5839 5840
    if (vm)
        virDomainObjUnlock(vm);
5841
    return ret;
5842 5843
}

5844
#ifdef __linux__
5845 5846 5847 5848 5849
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
5850 5851
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
5852
    int i;
5853
    int ret = -1;
5854

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

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

D
Daniel P. Berrange 已提交
5867
    if (!virDomainObjIsActive(vm)) {
5868 5869
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
5870
        goto cleanup;
5871 5872 5873
    }

    /* Check the path is one of the domain's network interfaces. */
5874 5875
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
5876 5877 5878 5879
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
5880 5881
    }

5882
    if (ret == 0)
5883
        ret = linuxDomainInterfaceStats(path, stats);
5884
    else
5885 5886
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path, '%s' is not a known interface"), path);
5887

5888
cleanup:
5889 5890
    if (vm)
        virDomainObjUnlock(vm);
5891 5892
    return ret;
}
5893
#else
5894 5895 5896 5897
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
5898
{
5899 5900
    qemuReportError(VIR_ERR_NO_SUPPORT,
                    "%s", __FUNCTION__);
5901 5902
    return -1;
}
5903
#endif
5904

5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920
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);
5921 5922
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5923 5924 5925
        goto cleanup;
    }

5926 5927 5928
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

5929 5930 5931
    if (virDomainObjIsActive(vm)) {
        qemuDomainObjPrivatePtr priv = vm->privateData;
        qemuDomainObjEnterMonitor(vm);
5932
        ret = qemuMonitorGetMemoryStats(priv->mon, stats, nr_stats);
5933 5934
        qemuDomainObjExitMonitor(vm);
    } else {
5935 5936
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
5937 5938
    }

5939 5940 5941
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;

5942 5943 5944 5945 5946 5947
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

5948 5949 5950 5951 5952 5953 5954
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
                      unsigned int flags ATTRIBUTE_UNUSED)
{
5955 5956 5957
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
5958

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

5963
    if (!vm) {
5964 5965
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5966 5967
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5968
        goto cleanup;
5969 5970 5971
    }

    if (!path || path[0] == '\0') {
5972 5973
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("NULL or empty path"));
5974
        goto cleanup;
5975 5976 5977
    }

    /* Check the path belongs to this domain. */
5978 5979
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
5980 5981 5982 5983
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
5984 5985
    }

5986 5987 5988 5989 5990
    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) {
5991 5992
            virReportSystemError(errno,
                                 _("%s: failed to open"), path);
5993 5994
            goto cleanup;
        }
5995

5996 5997 5998 5999 6000 6001
        /* 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) {
6002 6003
            virReportSystemError(errno,
                                 _("%s: failed to seek or read"), path);
6004 6005 6006 6007 6008
            goto cleanup;
        }

        ret = 0;
    } else {
6009 6010
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("invalid path"));
6011 6012
    }

6013
cleanup:
6014
    VIR_FORCE_CLOSE(fd);
6015 6016
    if (vm)
        virDomainObjUnlock(vm);
6017 6018 6019
    return ret;
}

R
Richard W.M. Jones 已提交
6020 6021 6022 6023 6024 6025
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
6026 6027
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
6028
    char *tmp = NULL;
R
Richard W.M. Jones 已提交
6029
    int fd = -1, ret = -1;
6030
    qemuDomainObjPrivatePtr priv;
R
Richard W.M. Jones 已提交
6031

6032
    qemuDriverLock(driver);
6033
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6034
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
6035 6036

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

6044
    if (flags != VIR_MEMORY_VIRTUAL && flags != VIR_MEMORY_PHYSICAL) {
6045 6046
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("flags parameter must be VIR_MEMORY_VIRTUAL or VIR_MEMORY_PHYSICAL"));
6047
        goto cleanup;
R
Richard W.M. Jones 已提交
6048 6049
    }

6050 6051 6052
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
6053
    if (!virDomainObjIsActive(vm)) {
6054 6055
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
6056
        goto endjob;
R
Richard W.M. Jones 已提交
6057 6058
    }

6059
    if (virAsprintf(&tmp, "%s/qemu.mem.XXXXXX", driver->cacheDir) < 0) {
6060
        virReportOOMError();
6061
        goto endjob;
6062 6063
    }

R
Richard W.M. Jones 已提交
6064 6065
    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
6066 6067
        virReportSystemError(errno,
                             _("mkstemp(\"%s\") failed"), tmp);
6068
        goto endjob;
R
Richard W.M. Jones 已提交
6069 6070
    }

6071 6072
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm, tmp);

6073
    priv = vm->privateData;
6074
    qemuDomainObjEnterMonitor(vm);
6075
    if (flags == VIR_MEMORY_VIRTUAL) {
6076 6077
        if (qemuMonitorSaveVirtualMemory(priv->mon, offset, size, tmp) < 0) {
            qemuDomainObjExitMonitor(vm);
6078
            goto endjob;
6079
        }
6080
    } else {
6081 6082
        if (qemuMonitorSavePhysicalMemory(priv->mon, offset, size, tmp) < 0) {
            qemuDomainObjExitMonitor(vm);
6083
            goto endjob;
6084
        }
R
Richard W.M. Jones 已提交
6085
    }
6086
    qemuDomainObjExitMonitor(vm);
R
Richard W.M. Jones 已提交
6087 6088 6089

    /* Read the memory file into buffer. */
    if (saferead (fd, buffer, size) == (ssize_t) -1) {
6090 6091 6092
        virReportSystemError(errno,
                             _("failed to read temporary file "
                               "created with template %s"), tmp);
6093
        goto endjob;
R
Richard W.M. Jones 已提交
6094 6095 6096
    }

    ret = 0;
6097

6098
endjob:
6099 6100
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
6101

6102
cleanup:
6103
    VIR_FORCE_CLOSE(fd);
6104 6105
    if (tmp)
        unlink(tmp);
W
Wen Congyang 已提交
6106
    VIR_FREE(tmp);
6107 6108
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
6109 6110 6111
    return ret;
}

6112

6113 6114 6115 6116 6117 6118 6119 6120 6121 6122
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;
6123
    virDomainDiskDefPtr disk = NULL;
6124 6125
    struct stat sb;
    int i;
6126
    int format;
6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150

    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)) {
6151
            disk = vm->def->disks[i];
6152 6153 6154 6155
            break;
        }
    }

6156
    if (!disk) {
6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170
        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 */
6171 6172 6173 6174 6175 6176 6177 6178
    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 {
6179 6180 6181 6182 6183 6184 6185
        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);
6186
            goto cleanup;
6187
        }
6188 6189 6190 6191 6192
    }

    if (virStorageFileGetMetadataFromFD(path, fd,
                                        format,
                                        &meta) < 0)
6193 6194 6195 6196 6197 6198 6199 6200 6201 6202
        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)) {
6203
#ifndef WIN32
6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231
        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;

6232
    /* Set default value .. */
6233 6234
    info->allocation = info->physical;

6235 6236 6237
    /* ..but if guest is running & not using raw
       disk format and on a block device, then query
       highest allocated extent from QEMU */
6238
    if (disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
6239
        format != VIR_STORAGE_FILE_RAW &&
6240 6241
        S_ISBLK(sb.st_mode) &&
        virDomainObjIsActive(vm)) {
6242
        qemuDomainObjPrivatePtr priv = vm->privateData;
6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263

        if ((priv->jobActive == QEMU_JOB_MIGRATION_OUT)
            || (priv->jobActive == QEMU_JOB_SAVE)) {
            virDomainObjRef(vm);
            while (priv->jobSignals & QEMU_JOB_SIGNAL_BLKINFO)
                ignore_value(virCondWait(&priv->signalCond, &vm->lock));

            priv->jobSignalsData.infoDevName = disk->info.alias;
            priv->jobSignalsData.blockInfo = info;
            priv->jobSignalsData.infoRetCode = &ret;
            priv->jobSignals |= QEMU_JOB_SIGNAL_BLKINFO;

            while (priv->jobSignals & QEMU_JOB_SIGNAL_BLKINFO)
                ignore_value(virCondWait(&priv->signalCond, &vm->lock));

            if (virDomainObjUnref(vm) == 0)
                vm = NULL;
        } else {
            if (qemuDomainObjBeginJob(vm) < 0)
                goto cleanup;

6264 6265 6266 6267 6268 6269 6270 6271
            if (virDomainObjIsActive(vm)) {
                qemuDomainObjEnterMonitor(vm);
                ret = qemuMonitorGetBlockExtent(priv->mon,
                                                disk->info.alias,
                                                &info->allocation);
                qemuDomainObjExitMonitor(vm);
            } else {
                ret = 0;
6272 6273 6274 6275 6276
            }

            if (qemuDomainObjEndJob(vm) == 0)
                vm = NULL;
        }
6277 6278 6279
    } else {
        ret = 0;
    }
6280 6281

cleanup:
6282
    VIR_FORCE_CLOSE(fd);
6283 6284 6285 6286 6287 6288
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


6289
static int
6290 6291 6292 6293
qemuDomainEventRegister(virConnectPtr conn,
                        virConnectDomainEventCallback callback,
                        void *opaque,
                        virFreeCallback freecb)
6294
{
6295 6296 6297
    struct qemud_driver *driver = conn->privateData;
    int ret;

6298
    qemuDriverLock(driver);
6299 6300
    ret = virDomainEventCallbackListAdd(conn,
                                        driver->domainEventState->callbacks,
6301
                                        callback, opaque, freecb);
6302
    qemuDriverUnlock(driver);
6303

6304
    return ret;
6305 6306
}

6307

6308
static int
6309 6310
qemuDomainEventDeregister(virConnectPtr conn,
                          virConnectDomainEventCallback callback)
6311
{
6312 6313 6314
    struct qemud_driver *driver = conn->privateData;
    int ret;

6315
    qemuDriverLock(driver);
6316 6317 6318
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
6319
    qemuDriverUnlock(driver);
6320

6321
    return ret;
6322 6323
}

6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337

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,
6338
                                          driver->domainEventState->callbacks,
6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354
                                          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);
6355 6356 6357
    ret = virDomainEventStateDeregisterAny(conn,
                                           driver->domainEventState,
                                           callbackID);
6358 6359 6360 6361 6362 6363
    qemuDriverUnlock(driver);

    return ret;
}


6364 6365 6366
/*******************************************************************
 * Migration Protocol Version 2
 *******************************************************************/
D
Daniel Veillard 已提交
6367

C
Chris Lalancette 已提交
6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382
/* 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;
6383

6384 6385 6386 6387 6388 6389 6390 6391 6392
    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);

6393 6394
    qemuDriverLock(driver);

C
Chris Lalancette 已提交
6395
    if (!dom_xml) {
6396 6397
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
C
Chris Lalancette 已提交
6398 6399 6400
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
6401
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
6402 6403 6404 6405
                         "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
        goto cleanup;
    }
    if (st == NULL) {
6406 6407
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("tunnelled migration requested but NULL stream passed"));
C
Chris Lalancette 已提交
6408 6409 6410
        goto cleanup;
    }

6411 6412 6413 6414 6415 6416 6417
    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

6418 6419 6420
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     NULL, 0, NULL, NULL, /* No cookies in v2 */
                                     st, dname, dom_xml);
6421

C
Chris Lalancette 已提交
6422
cleanup:
6423
    qemuDriverUnlock(driver);
C
Chris Lalancette 已提交
6424 6425 6426
    return ret;
}

D
Daniel Veillard 已提交
6427 6428 6429 6430
/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
6431
static int ATTRIBUTE_NONNULL (5)
D
Daniel Veillard 已提交
6432
qemudDomainMigratePrepare2 (virConnectPtr dconn,
6433 6434
                            char **cookie ATTRIBUTE_UNUSED,
                            int *cookielen ATTRIBUTE_UNUSED,
D
Daniel Veillard 已提交
6435 6436
                            const char *uri_in,
                            char **uri_out,
C
Chris Lalancette 已提交
6437
                            unsigned long flags,
D
Daniel Veillard 已提交
6438 6439 6440 6441
                            const char *dname,
                            unsigned long resource ATTRIBUTE_UNUSED,
                            const char *dom_xml)
{
6442
    struct qemud_driver *driver = dconn->privateData;
6443
    int ret = -1;
6444

C
Chris Lalancette 已提交
6445 6446 6447 6448 6449 6450 6451 6452 6453
    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);

6454
    *uri_out = NULL;
D
Daniel Veillard 已提交
6455

6456
    qemuDriverLock(driver);
6457 6458 6459 6460 6461 6462 6463 6464

    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

C
Chris Lalancette 已提交
6465 6466 6467 6468
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
6469 6470
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Tunnelled migration requested but invalid RPC method called"));
C
Chris Lalancette 已提交
6471 6472 6473
        goto cleanup;
    }

D
Daniel Veillard 已提交
6474
    if (!dom_xml) {
6475 6476
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
6477
        goto cleanup;
D
Daniel Veillard 已提交
6478 6479
    }

6480 6481 6482 6483
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
6484
    ret = qemuMigrationPrepareDirect(driver, dconn,
6485
                                     NULL, 0, NULL, NULL, /* No cookies */
6486 6487
                                     uri_in, uri_out,
                                     dname, dom_xml);
D
Daniel Veillard 已提交
6488

6489 6490 6491 6492
cleanup:
    qemuDriverUnlock(driver);
    return ret;
}
C
Chris Lalancette 已提交
6493

D
Daniel Veillard 已提交
6494

6495 6496 6497
/* Perform is the second step, and it runs on the source host. */
static int
qemudDomainMigratePerform (virDomainPtr dom,
6498 6499
                           const char *cookie,
                           int cookielen,
6500 6501 6502 6503 6504 6505 6506 6507
                           const char *uri,
                           unsigned long flags,
                           const char *dname,
                           unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
6508
    const char *dconnuri = NULL;
6509

6510 6511 6512 6513 6514 6515 6516 6517
    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 已提交
6518

6519
    qemuDriverLock(driver);
6520 6521 6522 6523 6524 6525 6526
    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

6527
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel Veillard 已提交
6528
    if (!vm) {
6529 6530
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
6531 6532
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
6533
        goto cleanup;
D
Daniel Veillard 已提交
6534 6535
    }

6536 6537 6538 6539 6540
    if (flags & VIR_MIGRATE_PEER2PEER) {
        dconnuri = uri;
        uri = NULL;
    }

6541 6542 6543 6544 6545 6546
    /* Do not output cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd.
     *
     * Consume any cookie we were able to decode though
     */
6547
    ret = qemuMigrationPerform(driver, dom->conn, vm,
6548
                               NULL, dconnuri, uri, cookie, cookielen,
6549
                               NULL, NULL, /* No output cookies in v2 */
6550
                               flags, dname, resource, false);
6551

6552
cleanup:
6553
    qemuDriverUnlock(driver);
6554
    return ret;
D
Daniel Veillard 已提交
6555 6556
}

6557

D
Daniel Veillard 已提交
6558 6559 6560 6561 6562 6563 6564
/* 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 已提交
6565
                           unsigned long flags,
D
Daniel Veillard 已提交
6566 6567
                           int retcode)
{
6568 6569 6570
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
D
Daniel Veillard 已提交
6571

C
Chris Lalancette 已提交
6572 6573 6574 6575 6576 6577 6578 6579 6580
    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);

6581
    qemuDriverLock(driver);
6582
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
6583
    if (!vm) {
6584 6585
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
6586
        goto cleanup;
D
Daniel Veillard 已提交
6587 6588
    }

6589 6590 6591 6592
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
6593
    dom = qemuMigrationFinish(driver, dconn, vm,
6594
                              NULL, 0, NULL, NULL, /* No cookies */
6595
                              flags, retcode, false);
6596

6597
cleanup:
6598
    qemuDriverUnlock(driver);
6599
    return dom;
D
Daniel Veillard 已提交
6600 6601
}

6602

6603 6604 6605 6606 6607 6608
/*******************************************************************
 * Migration Protocol Version 3
 *******************************************************************/

static char *
qemuDomainMigrateBegin3(virDomainPtr domain,
6609
                        const char *xmlin,
6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638
                        char **cookieout,
                        int *cookieoutlen,
                        unsigned long flags,
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    char *xml = NULL;

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

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

6639
    xml = qemuMigrationBegin(driver, vm, xmlin,
6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 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
                             cookieout, cookieoutlen);

cleanup:
    qemuDriverUnlock(driver);
    return xml;
}

static int
qemuDomainMigratePrepare3(virConnectPtr dconn,
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
                          const char *uri_in,
                          char **uri_out,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource ATTRIBUTE_UNUSED,
                          const char *dom_xml)
{
    struct qemud_driver *driver = dconn->privateData;
    int ret = -1;

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

    *uri_out = NULL;

    qemuDriverLock(driver);
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Tunnelled migration requested but invalid RPC method called"));
        goto cleanup;
    }

    if (!dom_xml) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
        goto cleanup;
    }

    ret = qemuMigrationPrepareDirect(driver, dconn,
                                     cookiein, cookieinlen,
                                     cookieout, cookieoutlen,
                                     uri_in, uri_out,
                                     dname, dom_xml);

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}


static int
qemuDomainMigratePrepareTunnel3(virConnectPtr dconn,
                                virStreamPtr st,
                                const char *cookiein,
                                int cookieinlen,
                                char **cookieout,
                                int *cookieoutlen,
                                unsigned long flags,
                                const char *dname,
                                unsigned long resource ATTRIBUTE_UNUSED,
                                const char *dom_xml)
{
    struct qemud_driver *driver = dconn->privateData;
    int ret = -1;

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

    if (!dom_xml) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                         "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
        goto cleanup;
    }
    if (st == NULL) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("tunnelled migration requested but NULL stream passed"));
        goto cleanup;
    }

    qemuDriverLock(driver);
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     cookiein, cookieinlen,
                                     cookieout, cookieoutlen,
                                     st, dname, dom_xml);
    qemuDriverUnlock(driver);

cleanup:
    return ret;
}


static int
qemuDomainMigratePerform3(virDomainPtr dom,
6756
                          const char *xmlin,
6757 6758 6759 6760
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
6761
                          const char *dconnuri,
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
                          const char *uri,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

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

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

6790
    ret = qemuMigrationPerform(driver, dom->conn, vm, xmlin,
6791
                               dconnuri, uri, cookiein, cookieinlen,
6792
                               cookieout, cookieoutlen,
6793
                               flags, dname, resource, true);
6794 6795 6796 6797 6798 6799 6800

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}


6801
static virDomainPtr
6802 6803 6804 6805 6806 6807
qemuDomainMigrateFinish3(virConnectPtr dconn,
                         const char *dname,
                         const char *cookiein,
                         int cookieinlen,
                         char **cookieout,
                         int *cookieoutlen,
6808
                         const char *dconnuri ATTRIBUTE_UNUSED,
6809 6810
                         const char *uri ATTRIBUTE_UNUSED,
                         unsigned long flags,
6811
                         int cancelled)
6812 6813 6814
{
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
6815
    virDomainPtr dom = NULL;
6816 6817 6818 6819 6820 6821 6822 6823

    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 |
6824
                  VIR_MIGRATE_NON_SHARED_INC, NULL);
6825 6826 6827 6828 6829 6830 6831 6832 6833

    qemuDriverLock(driver);
    vm = virDomainFindByName(&driver->domains, dname);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
        goto cleanup;
    }

6834 6835 6836 6837
    dom = qemuMigrationFinish(driver, dconn, vm,
                              cookiein, cookieinlen,
                              cookieout, cookieoutlen,
                              flags, cancelled, true);
6838 6839 6840

cleanup:
    qemuDriverUnlock(driver);
6841
    return dom;
6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873
}

static int
qemuDomainMigrateConfirm3(virDomainPtr domain,
                          const char *cookiein,
                          int cookieinlen,
                          unsigned long flags,
                          int cancelled)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

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

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

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

6877 6878
    ret = qemuMigrationConfirm(driver, domain->conn, vm,
                               cookiein, cookieinlen,
6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890
                               flags, cancelled);

    if (qemuDomainObjEndJob(vm) == 0) {
        vm = NULL;
    } else if (!virDomainObjIsActive(vm) &&
               (!vm->persistent || (flags & VIR_MIGRATE_UNDEFINE_SOURCE))) {
        if (flags & VIR_MIGRATE_UNDEFINE_SOURCE)
            virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm);
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }

6891
cleanup:
6892 6893
    if (vm)
        virDomainObjUnlock(vm);
6894 6895 6896 6897 6898
    qemuDriverUnlock(driver);
    return ret;
}


6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914
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;

6915
    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE);
6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932
    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) {
6933 6934
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("device %s is not a PCI device"), dev->name);
6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947
        goto out;
    }

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

static int
qemudNodeDeviceDettach (virNodeDevicePtr dev)
{
6948
    struct qemud_driver *driver = dev->conn->privateData;
6949 6950 6951 6952 6953 6954 6955
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

6956
    pci = pciGetDevice(domain, bus, slot, function);
6957 6958 6959
    if (!pci)
        return -1;

6960 6961
    qemuDriverLock(driver);
    if (pciDettachDevice(pci, driver->activePciHostdevs) < 0)
6962 6963 6964 6965
        goto out;

    ret = 0;
out:
6966
    qemuDriverUnlock(driver);
6967
    pciFreeDevice(pci);
6968 6969 6970 6971 6972 6973
    return ret;
}

static int
qemudNodeDeviceReAttach (virNodeDevicePtr dev)
{
6974
    struct qemud_driver *driver = dev->conn->privateData;
6975 6976 6977 6978 6979 6980 6981
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

6982
    pci = pciGetDevice(domain, bus, slot, function);
6983 6984 6985
    if (!pci)
        return -1;

6986 6987
    qemuDriverLock(driver);
    if (pciReAttachDevice(pci, driver->activePciHostdevs) < 0)
6988 6989 6990 6991
        goto out;

    ret = 0;
out:
6992
    qemuDriverUnlock(driver);
6993
    pciFreeDevice(pci);
6994 6995 6996 6997 6998 6999
    return ret;
}

static int
qemudNodeDeviceReset (virNodeDevicePtr dev)
{
7000
    struct qemud_driver *driver = dev->conn->privateData;
7001 7002 7003 7004 7005 7006 7007
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

7008
    pci = pciGetDevice(domain, bus, slot, function);
7009 7010 7011
    if (!pci)
        return -1;

7012 7013
    qemuDriverLock(driver);

7014
    if (pciResetDevice(pci, driver->activePciHostdevs, NULL) < 0)
7015 7016 7017 7018
        goto out;

    ret = 0;
out:
7019
    qemuDriverUnlock(driver);
7020
    pciFreeDevice(pci);
7021 7022 7023
    return ret;
}

7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034
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) {
7035 7036
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        "%s", _("cannot get host CPU capabilities"));
7037 7038
    }
    else
7039
        ret = cpuCompareXML(driver->caps->host.cpu, xmlDesc);
7040 7041 7042 7043 7044 7045

    qemuDriverUnlock(driver);

    return ret;
}

7046

7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059
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;
}

7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083

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) {
            memcpy(info, &priv->jobInfo, sizeof(*info));
7084 7085 7086 7087 7088 7089

            /* Refresh elapsed time again just to ensure it
             * is fully updated. This is primarily for benefit
             * of incoming migration which we don't currently
             * monitor actively in the background thread
             */
J
Jiri Denemark 已提交
7090
            if (virTimeMs(&info->timeElapsed) < 0)
7091
                goto cleanup;
J
Jiri Denemark 已提交
7092
            info->timeElapsed -= priv->jobStart;
7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111
        } 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;
}


7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133
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);
7134
            priv->jobSignals |= QEMU_JOB_SIGNAL_CANCEL;
7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154
        } 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;
}


7155 7156 7157 7158 7159 7160 7161 7162 7163 7164
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;

7165
    virCheckFlags(0, -1);
7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185

    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;

7186
    if (priv->jobActive != QEMU_JOB_MIGRATION_OUT) {
7187 7188 7189 7190 7191 7192 7193
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not being migrated"));
        goto cleanup;
    }

    VIR_DEBUG("Requesting migration downtime change to %llums", downtime);
    priv->jobSignalsData.migrateDowntime = downtime;
7194
    priv->jobSignals |= QEMU_JOB_SIGNAL_MIGRATE_DOWNTIME;
7195 7196 7197 7198 7199 7200 7201 7202 7203
    ret = 0;

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

7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242
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->jobSignalsData.migrateBandwidth = bandwidth;
7243
    priv->jobSignals |= QEMU_JOB_SIGNAL_MIGRATE_SPEED;
7244 7245 7246 7247 7248 7249 7250 7251 7252
    ret = 0;

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

C
Chris Lalancette 已提交
7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266
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;
}

7267 7268 7269
static int qemuDomainSnapshotWriteMetadata(virDomainObjPtr vm,
                                           virDomainSnapshotObjPtr snapshot,
                                           char *snapshotDir)
C
Chris Lalancette 已提交
7270 7271 7272 7273 7274 7275 7276 7277 7278 7279
{
    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);
7280
    newxml = virDomainSnapshotDefFormat(uuidstr, snapshot->def, 1);
C
Chris Lalancette 已提交
7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296
    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;
    }

7297
    if (virAsprintf(&snapFile, "%s/%s.xml", snapDir, snapshot->def->name) < 0) {
C
Chris Lalancette 已提交
7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318
        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);
7319
    VIR_FORCE_CLOSE(fd);
C
Chris Lalancette 已提交
7320 7321 7322
    return ret;
}

7323 7324
static int qemuDomainSnapshotSetCurrentActive(virDomainObjPtr vm,
                                              char *snapshotDir)
C
Chris Lalancette 已提交
7325 7326 7327 7328
{
    if (vm->current_snapshot) {
        vm->current_snapshot->def->active = 1;

7329 7330
        return qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                               snapshotDir);
C
Chris Lalancette 已提交
7331 7332 7333 7334 7335
    }

    return 0;
}

7336 7337
static int qemuDomainSnapshotSetCurrentInactive(virDomainObjPtr vm,
                                                char *snapshotDir)
C
Chris Lalancette 已提交
7338 7339 7340 7341
{
    if (vm->current_snapshot) {
        vm->current_snapshot->def->active = 0;

7342 7343
        return qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                               snapshotDir);
C
Chris Lalancette 已提交
7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362
    }

    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,
7363 7364
                            _("Disk '%s' does not support snapshotting"),
                            vm->def->disks[i]->src);
C
Chris Lalancette 已提交
7365 7366 7367 7368 7369 7370 7371
            return 0;
        }
    }

    return 1;
}

7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419
/* 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
7420 7421
qemuDomainSnapshotCreateActive(virConnectPtr conn,
                               struct qemud_driver *driver,
7422 7423 7424 7425 7426
                               virDomainObjPtr *vmptr,
                               virDomainSnapshotObjPtr snap)
{
    virDomainObjPtr vm = *vmptr;
    qemuDomainObjPrivatePtr priv = vm->privateData;
7427 7428
    bool resume = false;
    int ret = -1;
7429 7430 7431 7432

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

J
Jiri Denemark 已提交
7433
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
7434 7435 7436 7437
        /* 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.
         */
J
Jiri Denemark 已提交
7438
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE) < 0)
7439 7440 7441 7442 7443 7444 7445 7446 7447 7448
            goto cleanup;

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

7449 7450 7451 7452
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    ret = qemuMonitorCreateSnapshot(priv->mon, snap->def->name);
    qemuDomainObjExitMonitorWithDriver(driver, vm);

7453 7454
cleanup:
    if (resume && virDomainObjIsActive(vm) &&
J
Jiri Denemark 已提交
7455 7456
        qemuProcessStartCPUs(driver, vm, conn,
                             VIR_DOMAIN_RUNNING_UNPAUSED) < 0 &&
7457 7458 7459 7460 7461
        virGetLastError() == NULL) {
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("resuming after snapshot failed"));
    }

7462 7463 7464 7465 7466 7467
    if (qemuDomainObjEndJob(vm) == 0)
        *vmptr = NULL;

    return ret;
}

C
Chris Lalancette 已提交
7468 7469
static virDomainSnapshotPtr qemuDomainSnapshotCreateXML(virDomainPtr domain,
                                                        const char *xmlDesc,
7470
                                                        unsigned int flags)
C
Chris Lalancette 已提交
7471 7472 7473 7474 7475 7476 7477 7478
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virDomainSnapshotDefPtr def;

7479 7480
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505
    qemuDriverLock(driver);
    virUUIDFormat(domain->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    /* in a perfect world, we would allow qemu to tell us this.  The problem
     * is that qemu only does this check device-by-device; so if you had a
     * domain that booted from a large qcow2 device, but had a secondary raw
     * device attached, you wouldn't find out that you can't snapshot your
     * guest until *after* it had spent the time to snapshot the boot device.
     * This is probably a bug in qemu, but we'll work around it here for now.
     */
    if (!qemuDomainSnapshotIsAllowed(vm))
        goto cleanup;

    if (!(def = virDomainSnapshotDefParseString(xmlDesc, 1)))
        goto cleanup;

    if (!(snap = virDomainSnapshotAssignDef(&vm->snapshots, def)))
        goto cleanup;

J
Jiri Denemark 已提交
7506
    snap->def->state = virDomainObjGetState(vm, NULL);
7507

C
Chris Lalancette 已提交
7508 7509
    /* actually do the snapshot */
    if (!virDomainObjIsActive(vm)) {
7510
        if (qemuDomainSnapshotCreateInactive(vm, snap) < 0)
C
Chris Lalancette 已提交
7511 7512 7513
            goto cleanup;
    }
    else {
7514 7515
        if (qemuDomainSnapshotCreateActive(domain->conn, driver,
                                           &vm, snap) < 0)
7516
            goto cleanup;
C
Chris Lalancette 已提交
7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534
    }

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

7535 7536 7537
    if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                        driver->snapshotDir) < 0)
        /* qemuDomainSnapshotWriteMetadata set the error */
C
Chris Lalancette 已提交
7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550
        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,
7551
                                       unsigned int flags)
C
Chris Lalancette 已提交
7552 7553 7554 7555 7556
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

7557 7558
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578
    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,
7579
                                 unsigned int flags)
C
Chris Lalancette 已提交
7580 7581 7582 7583 7584
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

7585 7586
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607
    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,
7608
                                                           unsigned int flags)
C
Chris Lalancette 已提交
7609 7610 7611 7612 7613 7614
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;

7615 7616
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643
    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,
7644
                                        unsigned int flags)
C
Chris Lalancette 已提交
7645 7646 7647 7648 7649
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

7650 7651
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671
    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,
7672
                                                      unsigned int flags)
C
Chris Lalancette 已提交
7673 7674 7675 7676 7677
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotPtr snapshot = NULL;

7678 7679
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704
    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;
}

7705 7706
static char *qemuDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                                          unsigned int flags)
C
Chris Lalancette 已提交
7707 7708 7709 7710 7711 7712 7713
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *xml = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

7714 7715
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742
    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,
7743
                                      unsigned int flags)
C
Chris Lalancette 已提交
7744 7745 7746 7747 7748 7749 7750 7751 7752 7753
{
    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;

7754 7755
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786
    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)
7787
                goto endjob;
C
Chris Lalancette 已提交
7788 7789
        }
        else {
7790
            if (qemuDomainSnapshotSetCurrentActive(vm, driver->snapshotDir) < 0)
7791
                goto endjob;
C
Chris Lalancette 已提交
7792

7793 7794
            rc = qemuProcessStart(snapshot->domain->conn, driver, vm, NULL,
                                  false, -1, NULL, VIR_VM_OP_CREATE);
7795
            qemuAuditDomainStart(vm, "from-snapshot", rc >= 0);
7796
            if (qemuDomainSnapshotSetCurrentInactive(vm, driver->snapshotDir) < 0)
7797
                goto endjob;
C
Chris Lalancette 已提交
7798
            if (rc < 0)
7799
                goto endjob;
C
Chris Lalancette 已提交
7800 7801 7802 7803 7804 7805
        }

        if (snap->def->state == VIR_DOMAIN_PAUSED) {
            /* qemu unconditionally starts the domain running again after
             * loadvm, so let's pause it to keep consistency
             */
J
Jiri Denemark 已提交
7806 7807
            rc = qemuProcessStopCPUs(driver, vm,
                                     VIR_DOMAIN_PAUSED_FROM_SNAPSHOT);
H
Hu Tao 已提交
7808
            if (rc < 0)
7809
                goto endjob;
J
Jiri Denemark 已提交
7810 7811 7812
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_FROM_SNAPSHOT);
C
Chris Lalancette 已提交
7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830
        }

        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT);
    }
    else {
        /* qemu is a little funny with running guests and the restoration
         * of snapshots.  If the snapshot was taken online,
         * then after a "loadvm" monitor command, the VM is set running
         * again.  If the snapshot was taken offline, then after a "loadvm"
         * monitor command the VM is left paused.  Unpausing it leads to
         * the memory state *before* the loadvm with the disk *after* the
         * loadvm, which obviously is bound to corrupt something.
         * Therefore we destroy the domain and set it to "off" in this case.
         */

        if (virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
7831
            qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT);
7832
            qemuAuditDomainStop(vm, "from-snapshot");
C
Chris Lalancette 已提交
7833 7834 7835
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STOPPED,
                                             VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT);
7836 7837 7838 7839
            if (!vm->persistent) {
                if (qemuDomainObjEndJob(vm) > 0)
                    virDomainRemoveInactive(&driver->domains, vm);
                vm = NULL;
7840
                goto cleanup;
7841
            }
C
Chris Lalancette 已提交
7842 7843
        }

7844
        if (qemuDomainSnapshotSetCurrentActive(vm, driver->snapshotDir) < 0)
7845
            goto endjob;
C
Chris Lalancette 已提交
7846 7847 7848 7849
    }

    ret = 0;

7850
endjob:
C
Chris Lalancette 已提交
7851 7852 7853
    if (vm && qemuDomainObjEndJob(vm) == 0)
        vm = NULL;

7854
cleanup:
C
Chris Lalancette 已提交
7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956
    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,
7957
                                              const void *name ATTRIBUTE_UNUSED,
C
Chris Lalancette 已提交
7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978
                                              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);
    }
}

7979 7980 7981 7982 7983 7984 7985 7986 7987
struct snap_reparent {
    struct qemud_driver *driver;
    virDomainSnapshotObjPtr snap;
    virDomainObjPtr vm;
    int err;
};

static void
qemuDomainSnapshotReparentChildren(void *payload,
7988
                                   const void *name ATTRIBUTE_UNUSED,
7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015
                                   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 已提交
8016 8017 8018 8019 8020 8021 8022 8023 8024
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;
8025
    struct snap_reparent rep;
C
Chris Lalancette 已提交
8026

8027 8028
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

C
Chris Lalancette 已提交
8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045
    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;
    }

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

C
Chris Lalancette 已提交
8049 8050 8051 8052 8053 8054 8055 8056
    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)
8057
            goto endjob;
8058 8059 8060 8061 8062 8063 8064 8065 8066
    } 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 已提交
8067 8068 8069 8070
    }

    ret = qemuDomainSnapshotDiscard(driver, vm, snap);

8071 8072 8073 8074
endjob:
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;

C
Chris Lalancette 已提交
8075 8076 8077 8078 8079 8080
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
8081

8082 8083 8084 8085 8086 8087 8088
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;
8089
    bool hmp;
8090

8091
    virCheckFlags(VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP, -1);
8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110

    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;

8111
    qemuDomainObjTaint(driver, vm, VIR_DOMAIN_TAINT_CUSTOM_MONITOR, -1);
8112

8113 8114
    hmp = !!(flags & VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP);

8115 8116 8117
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
8118
    ret = qemuMonitorArbitraryCommand(priv->mon, cmd, result, hmp);
8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131
    qemuDomainObjExitMonitorWithDriver(driver, vm);
    if (qemuDomainObjEndJob(vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

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

8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188

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

8189
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
8190 8191 8192 8193 8194 8195
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"),
                        NULLSTR(devname));
        goto cleanup;
    }

8196 8197
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
                            0, 0, O_RDWR, false) < 0)
8198 8199 8200 8201 8202 8203 8204 8205 8206 8207
        goto cleanup;

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

8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315
static const char *
qemuDiskPathToAlias(virDomainObjPtr vm, const char *path) {
    int i;
    char *ret = NULL;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        virDomainDiskDefPtr disk = vm->def->disks[i];

        if (disk->type != VIR_DOMAIN_DISK_TYPE_BLOCK &&
            disk->type != VIR_DOMAIN_DISK_TYPE_FILE)
            continue;

        if (disk->src != NULL && STREQ(disk->src, path)) {
            if (virAsprintf(&ret, "drive-%s", disk->info.alias) < 0) {
                virReportOOMError();
                return NULL;
            }
            break;
        }
    }

    if (!ret) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("No device found for specified path"));
    }
    return ret;
}

static int
qemuDomainBlockPullImpl(virDomainPtr dom, const char *path,
                        virDomainBlockPullInfoPtr info,
                        int mode)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    qemuDomainObjPrivatePtr priv;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    const char *device = NULL;
    int ret = -1;

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

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

    device = qemuDiskPathToAlias(vm, path);
    if (!device) {
        goto cleanup;
    }

    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    priv = vm->privateData;
    ret = qemuMonitorBlockPull(priv->mon, device, info, mode);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
    if (qemuDomainObjEndJob(vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

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

static int
qemuDomainBlockPull(virDomainPtr dom, const char *path,
                    virDomainBlockPullInfoPtr info, unsigned int flags)
{
    virCheckFlags(0, -1);
    return qemuDomainBlockPullImpl(dom, path, info, BLOCK_PULL_MODE_ONE);
}

static int
qemuDomainBlockPullAll(virDomainPtr dom, const char *path, unsigned int flags)
{
    virCheckFlags(0, -1);
    return qemuDomainBlockPullImpl(dom, path, NULL, BLOCK_PULL_MODE_ALL);
}

static int
qemuDomainBlockPullAbort(virDomainPtr dom, const char *path, unsigned int flags)
{
    virCheckFlags(0, -1);
    return qemuDomainBlockPullImpl(dom, path, NULL, BLOCK_PULL_MODE_ABORT);
}

static int
qemuDomainGetBlockPullInfo(virDomainPtr dom, const char *path,
                           virDomainBlockPullInfoPtr info, unsigned int flags)
{
    virCheckFlags(0, -1);
    return qemuDomainBlockPullImpl(dom, path, info, BLOCK_PULL_MODE_INFO);
}
8316

8317
static virDriver qemuDriver = {
8318 8319
    .no = VIR_DRV_QEMU,
    .name = "QEMU",
8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350
    .open = qemudOpen, /* 0.2.0 */
    .close = qemudClose, /* 0.2.0 */
    .supports_feature = qemudSupportsFeature, /* 0.5.0 */
    .type = qemudGetType, /* 0.2.0 */
    .version = qemudGetVersion, /* 0.2.0 */
    .getHostname = virGetHostname, /* 0.3.3 */
    .getSysinfo = qemuGetSysinfo, /* 0.8.8 */
    .getMaxVcpus = qemudGetMaxVCPUs, /* 0.2.1 */
    .nodeGetInfo = nodeGetInfo, /* 0.2.0 */
    .getCapabilities = qemudGetCapabilities, /* 0.2.1 */
    .listDomains = qemudListDomains, /* 0.2.0 */
    .numOfDomains = qemudNumDomains, /* 0.2.0 */
    .domainCreateXML = qemudDomainCreate, /* 0.2.0 */
    .domainLookupByID = qemudDomainLookupByID, /* 0.2.0 */
    .domainLookupByUUID = qemudDomainLookupByUUID, /* 0.2.0 */
    .domainLookupByName = qemudDomainLookupByName, /* 0.2.0 */
    .domainSuspend = qemudDomainSuspend, /* 0.2.0 */
    .domainResume = qemudDomainResume, /* 0.2.0 */
    .domainShutdown = qemudDomainShutdown, /* 0.2.0 */
    .domainDestroy = qemudDomainDestroy, /* 0.2.0 */
    .domainGetOSType = qemudDomainGetOSType, /* 0.2.2 */
    .domainGetMaxMemory = qemudDomainGetMaxMemory, /* 0.4.2 */
    .domainSetMaxMemory = qemudDomainSetMaxMemory, /* 0.4.2 */
    .domainSetMemory = qemudDomainSetMemory, /* 0.4.2 */
    .domainSetMemoryFlags = qemudDomainSetMemoryFlags, /* 0.9.0 */
    .domainSetMemoryParameters = qemuDomainSetMemoryParameters, /* 0.8.5 */
    .domainGetMemoryParameters = qemuDomainGetMemoryParameters, /* 0.8.5 */
    .domainSetBlkioParameters = qemuDomainSetBlkioParameters, /* 0.9.0 */
    .domainGetBlkioParameters = qemuDomainGetBlkioParameters, /* 0.9.0 */
    .domainGetInfo = qemudDomainGetInfo, /* 0.2.0 */
    .domainGetState = qemuDomainGetState, /* 0.9.2 */
8351
    .domainGetControlInfo = qemuDomainGetControlInfo, /* 0.9.3 */
8352 8353 8354 8355 8356 8357 8358 8359
    .domainSave = qemudDomainSave, /* 0.2.0 */
    .domainRestore = qemuDomainRestore, /* 0.2.0 */
    .domainCoreDump = qemudDomainCoreDump, /* 0.7.0 */
    .domainScreenshot = qemuDomainScreenshot, /* 0.9.2 */
    .domainSetVcpus = qemudDomainSetVcpus, /* 0.4.4 */
    .domainSetVcpusFlags = qemudDomainSetVcpusFlags, /* 0.8.5 */
    .domainGetVcpusFlags = qemudDomainGetVcpusFlags, /* 0.8.5 */
    .domainPinVcpu = qemudDomainPinVcpu, /* 0.4.4 */
8360
    .domainPinVcpuFlags = qemudDomainPinVcpuFlags, /* 0.9.3 */
8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382
    .domainGetVcpus = qemudDomainGetVcpus, /* 0.4.4 */
    .domainGetMaxVcpus = qemudDomainGetMaxVcpus, /* 0.4.4 */
    .domainGetSecurityLabel = qemudDomainGetSecurityLabel, /* 0.6.1 */
    .nodeGetSecurityModel = qemudNodeGetSecurityModel, /* 0.6.1 */
    .domainGetXMLDesc = qemuDomainGetXMLDesc, /* 0.2.0 */
    .domainXMLFromNative = qemuDomainXMLFromNative, /* 0.6.4 */
    .domainXMLToNative = qemuDomainXMLToNative, /* 0.6.4 */
    .listDefinedDomains = qemudListDefinedDomains, /* 0.2.0 */
    .numOfDefinedDomains = qemudNumDefinedDomains, /* 0.2.0 */
    .domainCreate = qemudDomainStart, /* 0.2.0 */
    .domainCreateWithFlags = qemudDomainStartWithFlags, /* 0.8.2 */
    .domainDefineXML = qemudDomainDefine, /* 0.2.0 */
    .domainUndefine = qemudDomainUndefine, /* 0.2.0 */
    .domainAttachDevice = qemuDomainAttachDevice, /* 0.4.1 */
    .domainAttachDeviceFlags = qemuDomainAttachDeviceFlags, /* 0.7.7 */
    .domainDetachDevice = qemuDomainDetachDevice, /* 0.5.0 */
    .domainDetachDeviceFlags = qemuDomainDetachDeviceFlags, /* 0.7.7 */
    .domainUpdateDeviceFlags = qemuDomainUpdateDeviceFlags, /* 0.8.0 */
    .domainGetAutostart = qemudDomainGetAutostart, /* 0.2.1 */
    .domainSetAutostart = qemudDomainSetAutostart, /* 0.2.1 */
    .domainGetSchedulerType = qemuGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = qemuGetSchedulerParameters, /* 0.7.0 */
8383
    .domainGetSchedulerParametersFlags = qemuGetSchedulerParametersFlags, /* 0.9.2 */
8384
    .domainSetSchedulerParameters = qemuSetSchedulerParameters, /* 0.7.0 */
8385
    .domainSetSchedulerParametersFlags = qemuSetSchedulerParametersFlags, /* 0.9.2 */
8386 8387 8388 8389 8390 8391 8392
    .domainMigratePerform = qemudDomainMigratePerform, /* 0.5.0 */
    .domainBlockStats = qemudDomainBlockStats, /* 0.4.1 */
    .domainInterfaceStats = qemudDomainInterfaceStats, /* 0.4.1 */
    .domainMemoryStats = qemudDomainMemoryStats, /* 0.7.5 */
    .domainBlockPeek = qemudDomainBlockPeek, /* 0.4.4 */
    .domainMemoryPeek = qemudDomainMemoryPeek, /* 0.4.4 */
    .domainGetBlockInfo = qemuDomainGetBlockInfo, /* 0.8.1 */
8393
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
8394
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432
    .nodeGetCellsFreeMemory = nodeGetCellsFreeMemory, /* 0.4.4 */
    .nodeGetFreeMemory = nodeGetFreeMemory, /* 0.4.4 */
    .domainEventRegister = qemuDomainEventRegister, /* 0.5.0 */
    .domainEventDeregister = qemuDomainEventDeregister, /* 0.5.0 */
    .domainMigratePrepare2 = qemudDomainMigratePrepare2, /* 0.5.0 */
    .domainMigrateFinish2 = qemudDomainMigrateFinish2, /* 0.5.0 */
    .nodeDeviceDettach = qemudNodeDeviceDettach, /* 0.6.1 */
    .nodeDeviceReAttach = qemudNodeDeviceReAttach, /* 0.6.1 */
    .nodeDeviceReset = qemudNodeDeviceReset, /* 0.6.1 */
    .domainMigratePrepareTunnel = qemudDomainMigratePrepareTunnel, /* 0.7.2 */
    .isEncrypted = qemuIsEncrypted, /* 0.7.3 */
    .isSecure = qemuIsSecure, /* 0.7.3 */
    .domainIsActive = qemuDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = qemuDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = qemuDomainIsUpdated, /* 0.8.6 */
    .cpuCompare = qemuCPUCompare, /* 0.7.5 */
    .cpuBaseline = qemuCPUBaseline, /* 0.7.7 */
    .domainGetJobInfo = qemuDomainGetJobInfo, /* 0.7.7 */
    .domainAbortJob = qemuDomainAbortJob, /* 0.7.7 */
    .domainMigrateSetMaxDowntime = qemuDomainMigrateSetMaxDowntime, /* 0.8.0 */
    .domainMigrateSetMaxSpeed = qemuDomainMigrateSetMaxSpeed, /* 0.9.0 */
    .domainEventRegisterAny = qemuDomainEventRegisterAny, /* 0.8.0 */
    .domainEventDeregisterAny = qemuDomainEventDeregisterAny, /* 0.8.0 */
    .domainManagedSave = qemuDomainManagedSave, /* 0.8.0 */
    .domainHasManagedSaveImage = qemuDomainHasManagedSaveImage, /* 0.8.0 */
    .domainManagedSaveRemove = qemuDomainManagedSaveRemove, /* 0.8.0 */
    .domainSnapshotCreateXML = qemuDomainSnapshotCreateXML, /* 0.8.0 */
    .domainSnapshotGetXMLDesc = qemuDomainSnapshotGetXMLDesc, /* 0.8.0 */
    .domainSnapshotNum = qemuDomainSnapshotNum, /* 0.8.0 */
    .domainSnapshotListNames = qemuDomainSnapshotListNames, /* 0.8.0 */
    .domainSnapshotLookupByName = qemuDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = qemuDomainHasCurrentSnapshot, /* 0.8.0 */
    .domainSnapshotCurrent = qemuDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = qemuDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = qemuDomainSnapshotDelete, /* 0.8.0 */
    .qemuDomainMonitorCommand = qemuDomainMonitorCommand, /* 0.8.3 */
    .domainOpenConsole = qemuDomainOpenConsole, /* 0.8.6 */
    .domainInjectNMI = qemuDomainInjectNMI, /* 0.9.2 */
8433 8434 8435 8436 8437 8438
    .domainMigrateBegin3 = qemuDomainMigrateBegin3, /* 0.9.2 */
    .domainMigratePrepare3 = qemuDomainMigratePrepare3, /* 0.9.2 */
    .domainMigratePrepareTunnel3 = qemuDomainMigratePrepareTunnel3, /* 0.9.2 */
    .domainMigratePerform3 = qemuDomainMigratePerform3, /* 0.9.2 */
    .domainMigrateFinish3 = qemuDomainMigrateFinish3, /* 0.9.2 */
    .domainMigrateConfirm3 = qemuDomainMigrateConfirm3, /* 0.9.2 */
8439 8440 8441 8442
    .domainBlockPull = qemuDomainBlockPull, /* 0.9.3 */
    .domainBlockPullAll = qemuDomainBlockPullAll, /* 0.9.3 */
    .domainBlockPullAbort = qemuDomainBlockPullAbort, /* 0.9.3 */
    .domainGetBlockPullInfo = qemuDomainGetBlockPullInfo, /* 0.9.3 */
8443 8444 8445
};


8446
static virStateDriver qemuStateDriver = {
8447
    .name = "QEMU",
8448 8449 8450 8451
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
8452
};
8453

8454
static void
8455
qemuVMDriverLock(void) {
8456 8457 8458 8459 8460
    qemuDriverLock(qemu_driver);
};


static void
8461
qemuVMDriverUnlock(void) {
8462 8463 8464 8465
    qemuDriverUnlock(qemu_driver);
};


8466 8467 8468 8469 8470 8471 8472 8473 8474
static int
qemuVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                    virHashIterator iter, void *data)
{
    virHashForEach(qemu_driver->domains.objs, iter, data);

    return 0;
}

S
Stefan Berger 已提交
8475 8476
static virNWFilterCallbackDriver qemuCallbackDriver = {
    .name = "QEMU",
8477 8478 8479
    .vmFilterRebuild = qemuVMFilterRebuild,
    .vmDriverLock = qemuVMDriverLock,
    .vmDriverUnlock = qemuVMDriverUnlock,
S
Stefan Berger 已提交
8480 8481
};

8482
int qemuRegister(void) {
8483 8484
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
S
Stefan Berger 已提交
8485
    virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);
8486 8487
    return 0;
}