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

24
#include <config.h>
25

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

48

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

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

92 93
#define VIR_FROM_THIS VIR_FROM_QEMU

94 95
#define QEMU_NB_MEM_PARAM  3

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

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

103 104 105 106 107 108 109 110 111 112 113
/* add definitions missing in older linux/kvm.h */
#ifndef KVMIO
# define KVMIO 0xAE
#endif
#ifndef KVM_CHECK_EXTENSION
# define KVM_CHECK_EXTENSION       _IO(KVMIO,   0x03)
#endif
#ifndef KVM_CAP_NR_VCPUS
# define KVM_CAP_NR_VCPUS 9       /* returns max vcpus per vm */
#endif

114
#define QEMU_NB_BLKIO_PARAM  1
115

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

118 119
static int qemudShutdown(void);

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

125
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
126

127
struct qemud_driver *qemu_driver = NULL;
128 129


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

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

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

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

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

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

173

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

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

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

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

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

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

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

222
    return 0;
223

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

230

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

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

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

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

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

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

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

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

275
    return caps;
276

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

284
static void qemuDomainSnapshotLoad(void *payload,
285
                                   const void *name ATTRIBUTE_UNUSED,
286
                                   void *data)
287
{
288 289 290 291 292 293 294 295 296
    virDomainObjPtr vm = (virDomainObjPtr)payload;
    char *baseDir = (char *)data;
    char *snapDir = NULL;
    DIR *dir = NULL;
    struct dirent *entry;
    char *xmlStr;
    int ret;
    char *fullpath;
    virDomainSnapshotDefPtr def = NULL;
297
    virDomainSnapshotObjPtr snap = NULL;
298
    virDomainSnapshotObjPtr current = NULL;
299
    char ebuf[1024];
300

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

308 309
    VIR_INFO("Scanning for snapshots for domain %s in %s", vm->def->name,
             snapDir);
310

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

319 320 321
    while ((entry = readdir(dir))) {
        if (entry->d_name[0] == '.')
            continue;
322

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

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

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

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

351 352 353
        snap = virDomainSnapshotAssignDef(&vm->snapshots, def);
        if (snap == NULL) {
            virDomainSnapshotDefFree(def);
354 355 356 357
        } else if (snap->def->current) {
            current = snap;
            if (!vm->current_snapshot)
                vm->current_snapshot = snap;
358
        }
359

360 361
        VIR_FREE(fullpath);
        VIR_FREE(xmlStr);
362 363
    }

364 365 366 367 368 369
    if (vm->current_snapshot != current) {
        VIR_ERROR(_("Too many snapshots claiming to be current for domain %s"),
                  vm->def->name);
        vm->current_snapshot = NULL;
    }

370 371 372 373 374 375 376 377
    /* 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.
     */
378

379
    virResetLastError();
380

381 382 383 384
cleanup:
    if (dir)
        closedir(dir);
    VIR_FREE(snapDir);
385 386 387
    virDomainObjUnlock(vm);
}

388 389 390 391 392
/**
 * qemudStartup:
 *
 * Initialization function for the QEmu daemon
 */
393
static int
394 395 396 397 398
qemudStartup(int privileged) {
    char *base = NULL;
    char *driverConf = NULL;
    int rc;
    virConnectPtr conn = NULL;
399

400 401
    if (VIR_ALLOC(qemu_driver) < 0)
        return -1;
402

403
    if (virMutexInit(&qemu_driver->lock) < 0) {
404
        VIR_ERROR(_("cannot initialize mutex"));
405 406
        VIR_FREE(qemu_driver);
        return -1;
407
    }
408 409
    qemuDriverLock(qemu_driver);
    qemu_driver->privileged = privileged;
410

411 412
    /* Don't have a dom0 so start from 1 */
    qemu_driver->nextvmid = 1;
413

414 415
    if (virDomainObjListInit(&qemu_driver->domains) < 0)
        goto out_of_memory;
416

417 418 419 420 421 422
    /* Init domain events */
    qemu_driver->domainEventState = virDomainEventStateNew(qemuDomainEventFlush,
                                                           qemu_driver,
                                                           NULL,
                                                           true);
    if (!qemu_driver->domainEventState)
423
        goto error;
424

425 426 427 428
    /* Allocate bitmap for vnc port reservation */
    if ((qemu_driver->reservedVNCPorts =
         virBitmapAlloc(QEMU_VNC_PORT_MAX - QEMU_VNC_PORT_MIN)) == NULL)
        goto out_of_memory;
429

430 431 432
    /* read the host sysinfo */
    if (privileged)
        qemu_driver->hostsysinfo = virSysinfoRead();
433

434 435 436 437
    if (privileged) {
        if (virAsprintf(&qemu_driver->logDir,
                        "%s/log/libvirt/qemu", LOCALSTATEDIR) == -1)
            goto out_of_memory;
438

439 440
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
            goto out_of_memory;
441

442 443 444
        if (virAsprintf(&qemu_driver->stateDir,
                      "%s/run/libvirt/qemu", LOCALSTATEDIR) == -1)
            goto out_of_memory;
445

446 447 448
        if (virAsprintf(&qemu_driver->libDir,
                      "%s/lib/libvirt/qemu", LOCALSTATEDIR) == -1)
            goto out_of_memory;
449

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
        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;
467

468 469 470 471 472
        if (virAsprintf(&qemu_driver->logDir,
                        "%s/.libvirt/qemu/log", userdir) == -1) {
            VIR_FREE(userdir);
            goto out_of_memory;
        }
473

474 475 476 477 478
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1) {
            VIR_FREE(userdir);
            goto out_of_memory;
        }
        VIR_FREE(userdir);
479

480 481 482 483 484 485 486 487 488 489 490 491
        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;
492
    }
H
Hu Tao 已提交
493

494
    if (virFileMakePath(qemu_driver->stateDir) < 0) {
495 496 497 498
        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 已提交
499
    }
500
    if (virFileMakePath(qemu_driver->libDir) < 0) {
501 502 503 504 505
        char ebuf[1024];
        VIR_ERROR(_("Failed to create lib dir '%s': %s"),
                  qemu_driver->libDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
506
    if (virFileMakePath(qemu_driver->cacheDir) < 0) {
507 508 509 510 511
        char ebuf[1024];
        VIR_ERROR(_("Failed to create cache dir '%s': %s"),
                  qemu_driver->cacheDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
512
    if (virFileMakePath(qemu_driver->saveDir) < 0) {
513 514 515 516 517
        char ebuf[1024];
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
                  qemu_driver->saveDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
518
    if (virFileMakePath(qemu_driver->snapshotDir) < 0) {
519 520 521 522 523
        char ebuf[1024];
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
                  qemu_driver->snapshotDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
524
    if (virFileMakePath(qemu_driver->autoDumpPath) < 0) {
525 526 527 528
        char ebuf[1024];
        VIR_ERROR(_("Failed to create dump dir '%s': %s"),
                  qemu_driver->autoDumpPath, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
529 530
    }

531 532 533 534 535 536 537
    /* 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;
538

539
    VIR_FREE(base);
540

541 542 543 544 545
    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)));
546 547
    }

548 549 550 551
    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
        goto error;
    }
    VIR_FREE(driverConf);
552

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

561 562
    if (qemuSecurityInit(qemu_driver) < 0)
        goto error;
563

564 565 566
    if ((qemu_driver->caps = qemuCreateCapabilities(NULL,
                                                    qemu_driver)) == NULL)
        goto error;
567

568
    if ((qemu_driver->activePciHostdevs = pciDeviceListNew()) == NULL)
569
        goto error;
570

571 572 573 574 575 576
    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;
577
        }
578
        if (chown(qemu_driver->cacheDir, qemu_driver->user, qemu_driver->group) < 0) {
579
            virReportSystemError(errno,
580 581 582
                                 _("unable to set ownership of '%s' to %d:%d"),
                                 qemu_driver->cacheDir, qemu_driver->user, qemu_driver->group);
            goto error;
583
        }
584 585 586 587 588 589 590 591 592 593 594
        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;
595
        }
596
    }
597

598 599 600 601 602 603
    /* 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
604
     */
605 606 607 608 609
    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;
610

611 612
        if (virFileMakePath(mempath) < 0) {
            virReportSystemError(errno,
613 614 615
                                 _("unable to create hugepage path %s"), mempath);
            VIR_FREE(mempath);
            goto error;
616
        }
617 618 619 620 621 622 623
        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 已提交
624
        }
E
Eric Blake 已提交
625

626
        qemu_driver->hugepage_path = mempath;
627
    }
628

629 630 631
    if (qemuProcessAutoDestroyInit(qemu_driver) < 0)
        goto error;

632 633 634 635 636
    /* Get all the running persistent or transient configs first */
    if (virDomainLoadAllConfigs(qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->stateDir,
                                NULL,
M
Matthias Bolte 已提交
637 638
                                1, QEMU_EXPECTED_VIRT_TYPES,
                                NULL, NULL) < 0)
639
        goto error;
640

641 642 643
    conn = virConnectOpen(qemu_driver->privileged ?
                          "qemu:///system" :
                          "qemu:///session");
644

645
    qemuProcessReconnectAll(conn, qemu_driver);
646

647 648 649 650 651
    /* Then inactive persistent configs */
    if (virDomainLoadAllConfigs(qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->configDir,
                                qemu_driver->autostartDir,
M
Matthias Bolte 已提交
652 653
                                0, QEMU_EXPECTED_VIRT_TYPES,
                                NULL, NULL) < 0)
654
        goto error;
655

656

657 658
    virHashForEach(qemu_driver->domains.objs, qemuDomainSnapshotLoad,
                   qemu_driver->snapshotDir);
659

660 661 662
    qemu_driver->workerPool = virThreadPoolNew(0, 1, processWatchdogEvent, qemu_driver);
    if (!qemu_driver->workerPool)
        goto error;
663

664 665 666 667
    qemuDriverUnlock(qemu_driver);

    qemuAutostartDomains(qemu_driver);

668 669
    if (conn)
        virConnectClose(conn);
670

671
    return 0;
672

673 674 675 676 677 678 679 680 681 682
out_of_memory:
    virReportOOMError();
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
    if (conn)
        virConnectClose(conn);
    VIR_FREE(base);
    VIR_FREE(driverConf);
    qemudShutdown();
683
    return -1;
684 685
}

686 687 688
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;
689

690 691 692 693 694 695 696
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
E
Eric Blake 已提交
697
    }
698
}
E
Eric Blake 已提交
699

700 701 702 703 704 705 706 707 708 709
/**
 * 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;
710

711 712 713 714 715
    qemuDriverLock(qemu_driver);
    virDomainLoadAllConfigs(qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
                            qemu_driver->autostartDir,
M
Matthias Bolte 已提交
716 717
                            0, QEMU_EXPECTED_VIRT_TYPES,
                            qemudNotifyLoadDomain, qemu_driver);
718
    qemuDriverUnlock(qemu_driver);
719

720
    qemuAutostartDomains(qemu_driver);
721

722 723
    return 0;
}
S
Stefan Berger 已提交
724

725 726 727 728 729 730 731 732 733 734 735
/**
 * 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;
736

737 738
    if (!qemu_driver)
        return 0;
739

740 741 742 743 744 745
    /* 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;
}
746

747 748 749 750 751 752 753 754
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
    int i;
755

756 757
    if (!qemu_driver)
        return -1;
758

759 760 761
    qemuDriverLock(qemu_driver);
    pciDeviceListFree(qemu_driver->activePciHostdevs);
    virCapabilitiesFree(qemu_driver->caps);
762

763 764
    virDomainObjListDeinit(&qemu_driver->domains);
    virBitmapFree(qemu_driver->reservedVNCPorts);
765

766
    virSysinfoDefFree(qemu_driver->hostsysinfo);
767

768 769
    qemuProcessAutoDestroyShutdown(qemu_driver);

770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
    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);
790

791
    virSecurityManagerFree(qemu_driver->securityManager);
792

793
    ebtablesContextFree(qemu_driver->ebtables);
794

795 796 797 798
    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 已提交
799 800
    }

801
    /* Free domain callback list */
802
    virDomainEventStateFree(qemu_driver->domainEventState);
D
Daniel P. Berrange 已提交
803

804 805
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);
806

807
    virCgroupFree(&qemu_driver->cgroup);
808

809 810
    virLockManagerPluginUnref(qemu_driver->lockManager);

811 812 813 814
    qemuDriverUnlock(qemu_driver);
    virMutexDestroy(&qemu_driver->lock);
    virThreadPoolFree(qemu_driver->workerPool);
    VIR_FREE(qemu_driver);
815

816
    return 0;
817 818
}

819

820
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
821
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
822
                                  unsigned int flags)
823
{
E
Eric Blake 已提交
824 825
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

826
    if (conn->uri == NULL) {
827 828 829
        if (qemu_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

830
        conn->uri = xmlParseURI(qemu_driver->privileged ?
831 832
                                "qemu:///system" :
                                "qemu:///session");
833
        if (!conn->uri) {
834
            virReportOOMError();
835 836
            return VIR_DRV_OPEN_ERROR;
        }
837 838 839 840 841 842 843 844 845 846
    } 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;

847
        if (qemu_driver == NULL) {
848 849
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("qemu state driver is not active"));
850 851 852
            return VIR_DRV_OPEN_ERROR;
        }

853
        if (conn->uri->path == NULL) {
854 855 856 857 858
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("no QEMU URI path given, try %s"),
                            qemu_driver->privileged
                            ? "qemu:///system"
                            : "qemu:///session");
859 860 861
                return VIR_DRV_OPEN_ERROR;
        }

862
        if (qemu_driver->privileged) {
863 864
            if (STRNEQ (conn->uri->path, "/system") &&
                STRNEQ (conn->uri->path, "/session")) {
865 866 867
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("unexpected QEMU URI path '%s', try qemu:///system"),
                                conn->uri->path);
868 869 870 871
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
872 873 874
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("unexpected QEMU URI path '%s', try qemu:///session"),
                                conn->uri->path);
875 876 877
                return VIR_DRV_OPEN_ERROR;
            }
        }
878 879 880 881 882 883 884
    }
    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int qemudClose(virConnectPtr conn) {
885
    struct qemud_driver *driver = conn->privateData;
886 887

    /* Get rid of callbacks registered for this conn */
888
    qemuDriverLock(driver);
889 890
    virDomainEventCallbackListRemoveConn(conn,
                                         driver->domainEventState->callbacks);
891
    qemuProcessAutoDestroyRun(driver, conn);
892
    qemuDriverUnlock(driver);
893 894 895 896 897 898

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
899 900 901 902 903
/* Which features are supported by this driver? */
static int
qemudSupportsFeature (virConnectPtr conn ATTRIBUTE_UNUSED, int feature)
{
    switch (feature) {
904
    case VIR_DRV_FEATURE_MIGRATION_V2:
905
    case VIR_DRV_FEATURE_MIGRATION_V3:
906
    case VIR_DRV_FEATURE_MIGRATION_P2P:
907
    case VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION:
908 909 910
        return 1;
    default:
        return 0;
D
Daniel Veillard 已提交
911 912 913
    }
}

914
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
915
    return "QEMU";
916 917
}

918

919 920 921 922 923 924 925 926 927 928 929 930 931
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;
}


932 933 934 935
static int kvmGetMaxVCPUs(void) {
    int maxvcpus = 1;

    int r, fd;
936

937 938
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
939
        virReportSystemError(errno, _("Unable to open %s"), KVM_DEVICE);
940
        return -1;
941 942 943 944 945 946
    }

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

947
    VIR_FORCE_CLOSE(fd);
948 949 950 951
    return maxvcpus;
}


E
Eric Blake 已提交
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
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, "");
}

968
static int qemudGetMaxVCPUs(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
969 970 971
    if (!type)
        return 16;

972
    if (STRCASEEQ(type, "qemu"))
973 974
        return 16;

975
    if (STRCASEEQ(type, "kvm"))
976
        return kvmGetMaxVCPUs();
977

978
    if (STRCASEEQ(type, "kqemu"))
979
        return 1;
980

981 982
    qemuReportError(VIR_ERR_INVALID_ARG,
                    _("unknown type '%s'"), type);
983 984 985
    return -1;
}

986

987
static char *qemudGetCapabilities(virConnectPtr conn) {
988
    struct qemud_driver *driver = conn->privateData;
989
    virCapsPtr caps = NULL;
990
    char *xml = NULL;
991

992
    qemuDriverLock(driver);
993

994
    if ((caps = qemuCreateCapabilities(qemu_driver->caps,
995
                                       qemu_driver)) == NULL) {
996 997 998
        virCapabilitiesFree(caps);
        goto cleanup;
    }
999

1000
    virCapabilitiesFree(qemu_driver->caps);
1001 1002 1003
    qemu_driver->caps = caps;

    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1004
        virReportOOMError();
1005 1006

cleanup:
1007
    qemuDriverUnlock(driver);
1008

1009
    return xml;
1010 1011 1012
}


1013 1014 1015 1016 1017
static int
qemudGetProcessInfo(unsigned long long *cpuTime, int *lastCpu, int pid,
                    int tid)
{
    char *proc;
D
Daniel P. Berrange 已提交
1018
    FILE *pidinfo;
1019
    unsigned long long usertime, systime;
1020 1021
    int cpu;
    int ret;
D
Daniel P. Berrange 已提交
1022

1023
    if (tid)
1024
        ret = virAsprintf(&proc, "/proc/%d/task/%d/stat", pid, tid);
1025
    else
1026 1027
        ret = virAsprintf(&proc, "/proc/%d/stat", pid);
    if (ret < 0)
D
Daniel P. Berrange 已提交
1028 1029 1030 1031
        return -1;

    if (!(pidinfo = fopen(proc, "r"))) {
        /* VM probably shut down, so fake 0 */
1032 1033 1034 1035
        if (cpuTime)
            *cpuTime = 0;
        if (lastCpu)
            *lastCpu = 0;
1036
        VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1037 1038
        return 0;
    }
1039
    VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1040

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
    /* 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) {
1051
        VIR_FORCE_FCLOSE(pidinfo);
1052
        VIR_WARN("cannot parse process status data");
1053
        errno = -EINVAL;
D
Daniel P. Berrange 已提交
1054 1055 1056 1057 1058 1059 1060 1061
        return -1;
    }

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
1062 1063 1064 1065 1066
    if (cpuTime)
        *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
    if (lastCpu)
        *lastCpu = cpu;

D
Daniel P. Berrange 已提交
1067

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

1071
    VIR_FORCE_FCLOSE(pidinfo);
D
Daniel P. Berrange 已提交
1072 1073 1074 1075 1076

    return 0;
}


1077
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1078
                                          int id) {
1079 1080 1081 1082
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1083
    qemuDriverLock(driver);
1084
    vm  = virDomainFindByID(&driver->domains, id);
1085
    qemuDriverUnlock(driver);
1086 1087

    if (!vm) {
1088 1089
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching id %d"), id);
1090
        goto cleanup;
1091 1092
    }

1093
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1094
    if (dom) dom->id = vm->def->id;
1095 1096

cleanup:
1097 1098
    if (vm)
        virDomainObjUnlock(vm);
1099 1100
    return dom;
}
1101

1102
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1103
                                            const unsigned char *uuid) {
1104 1105 1106
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1107

1108
    qemuDriverLock(driver);
1109
    vm = virDomainFindByUUID(&driver->domains, uuid);
1110 1111
    qemuDriverUnlock(driver);

1112
    if (!vm) {
1113 1114
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
1115 1116
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1117
        goto cleanup;
1118 1119
    }

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

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

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

1135
    qemuDriverLock(driver);
1136
    vm = virDomainFindByName(&driver->domains, name);
1137 1138
    qemuDriverUnlock(driver);

1139
    if (!vm) {
1140 1141
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), name);
1142
        goto cleanup;
1143 1144
    }

1145
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1146
    if (dom) dom->id = vm->def->id;
1147 1148

cleanup:
1149 1150
    if (vm)
        virDomainObjUnlock(vm);
1151 1152 1153
    return dom;
}

1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164

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 已提交
1165 1166 1167 1168
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
        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 已提交
1189 1190 1191 1192
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
        goto cleanup;
    }
    ret = obj->persistent;

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

1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
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 已提交
1213 1214 1215 1216
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1217 1218 1219 1220 1221 1222 1223 1224 1225
        goto cleanup;
    }
    ret = obj->updated;

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

1227
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1228 1229 1230
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

1231
    qemuDriverLock(driver);
1232
    if (qemuCapsExtractVersion(driver->caps, &driver->qemuVersion) < 0)
1233
        goto cleanup;
1234

1235
    *version = driver->qemuVersion;
1236 1237 1238
    ret = 0;

cleanup:
1239
    qemuDriverUnlock(driver);
1240
    return ret;
D
Daniel P. Berrange 已提交
1241 1242
}

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

1247
    qemuDriverLock(driver);
1248
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1249
    qemuDriverUnlock(driver);
1250

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

1254
static int qemudNumDomains(virConnectPtr conn) {
1255
    struct qemud_driver *driver = conn->privateData;
1256
    int n;
1257

1258
    qemuDriverLock(driver);
1259
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1260
    qemuDriverUnlock(driver);
1261

1262
    return n;
D
Daniel P. Berrange 已提交
1263
}
1264

1265
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
1266
                                      unsigned int flags) {
1267
    struct qemud_driver *driver = conn->privateData;
1268
    virDomainDefPtr def;
1269
    virDomainObjPtr vm = NULL;
1270
    virDomainPtr dom = NULL;
1271
    virDomainEventPtr event = NULL;
D
Daniel P. Berrange 已提交
1272

1273 1274
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
                  VIR_DOMAIN_START_AUTODESTROY, NULL);
1275

1276
    qemuDriverLock(driver);
1277
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1278
                                        QEMU_EXPECTED_VIRT_TYPES,
1279
                                        VIR_DOMAIN_XML_INACTIVE)))
1280
        goto cleanup;
1281

1282
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
1283 1284
        goto cleanup;

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

1288 1289 1290
    if (qemudCanonicalizeMachine(driver, def) < 0)
        goto cleanup;

1291
    if (qemuDomainAssignPCIAddresses(def) < 0)
1292 1293
        goto cleanup;

1294
    if (!(vm = virDomainAssignDef(driver->caps,
1295
                                  &driver->domains,
1296
                                  def, false)))
1297 1298 1299
        goto cleanup;

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

1301
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
1302 1303
        goto cleanup; /* XXXX free the 'vm' we created ? */

1304 1305
    if (qemuProcessStart(conn, driver, vm, NULL,
                         (flags & VIR_DOMAIN_START_PAUSED) != 0,
1306
                         (flags & VIR_DOMAIN_START_AUTODESTROY) != 0,
1307
                         -1, NULL, NULL, VIR_VM_OP_CREATE) < 0) {
1308
        virDomainAuditStart(vm, "booted", false);
1309
        if (qemuDomainObjEndJob(driver, vm) > 0)
1310 1311
            virDomainRemoveInactive(&driver->domains,
                                    vm);
1312
        vm = NULL;
1313
        goto cleanup;
D
Daniel P. Berrange 已提交
1314
    }
1315 1316 1317 1318

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

1321
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1322
    if (dom) dom->id = vm->def->id;
1323

1324
    if (vm &&
1325
        qemuDomainObjEndJob(driver, vm) == 0)
1326
        vm = NULL;
1327

1328 1329
cleanup:
    virDomainDefFree(def);
1330 1331
    if (vm)
        virDomainObjUnlock(vm);
1332 1333
    if (event)
        qemuDomainEventQueue(driver, event);
1334
    qemuDriverUnlock(driver);
1335
    return dom;
D
Daniel P. Berrange 已提交
1336 1337 1338
}


1339
static int qemudDomainSuspend(virDomainPtr dom) {
1340 1341 1342
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1343
    virDomainEventPtr event = NULL;
1344
    qemuDomainObjPrivatePtr priv;
1345 1346
    virDomainPausedReason reason;
    int eventDetail;
1347

1348
    qemuDriverLock(driver);
1349
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1350

D
Daniel P. Berrange 已提交
1351
    if (!vm) {
1352 1353
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1354 1355
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1356
        goto cleanup;
D
Daniel P. Berrange 已提交
1357
    }
D
Daniel P. Berrange 已提交
1358
    if (!virDomainObjIsActive(vm)) {
1359 1360
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1361
        goto cleanup;
D
Daniel P. Berrange 已提交
1362
    }
1363 1364 1365

    priv = vm->privateData;

1366
    if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_OUT) {
1367 1368
        reason = VIR_DOMAIN_PAUSED_MIGRATION;
        eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED;
1369
    } else {
1370 1371 1372
        reason = VIR_DOMAIN_PAUSED_USER;
        eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_PAUSED;
    }
1373

1374 1375 1376 1377 1378 1379 1380 1381 1382
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_SUSPEND) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }
    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
1383
        if (qemuProcessStopCPUs(driver, vm, reason, QEMU_ASYNC_JOB_NONE) < 0) {
1384
            goto endjob;
1385
        }
1386 1387 1388
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         eventDetail);
D
Daniel P. Berrange 已提交
1389
    }
1390 1391 1392
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
        goto endjob;
    ret = 0;
1393

1394
endjob:
1395
    if (qemuDomainObjEndJob(driver, vm) == 0)
1396
        vm = NULL;
1397

1398
cleanup:
1399 1400
    if (vm)
        virDomainObjUnlock(vm);
1401

1402
    if (event)
1403
        qemuDomainEventQueue(driver, event);
1404
    qemuDriverUnlock(driver);
1405
    return ret;
D
Daniel P. Berrange 已提交
1406 1407 1408
}


1409
static int qemudDomainResume(virDomainPtr dom) {
1410 1411 1412
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1413
    virDomainEventPtr event = NULL;
1414

1415
    qemuDriverLock(driver);
1416
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1417

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

1426
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
1427 1428
        goto cleanup;

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

1451
endjob:
1452
    if (qemuDomainObjEndJob(driver, vm) == 0)
1453
        vm = NULL;
1454

1455
cleanup:
1456 1457
    if (vm)
        virDomainObjUnlock(vm);
1458
    if (event)
1459
        qemuDomainEventQueue(driver, event);
1460
    qemuDriverUnlock(driver);
1461
    return ret;
D
Daniel P. Berrange 已提交
1462 1463 1464
}


1465
static int qemuDomainShutdown(virDomainPtr dom) {
1466 1467 1468
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1469
    qemuDomainObjPrivatePtr priv;
1470

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

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

1483
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1484 1485
        goto cleanup;

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

1492
    priv = vm->privateData;
1493
    qemuDomainObjEnterMonitor(driver, vm);
1494
    ret = qemuMonitorSystemPowerdown(priv->mon);
1495
    qemuDomainObjExitMonitor(driver, vm);
1496

1497 1498
    priv->fakeReboot = false;

1499
endjob:
1500
    if (qemuDomainObjEndJob(driver, vm) == 0)
1501
        vm = NULL;
1502

1503
cleanup:
1504 1505
    if (vm)
        virDomainObjUnlock(vm);
1506
    return ret;
1507 1508 1509
}


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

    virCheckFlags(0, -1);

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

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

#if HAVE_YAJL
1533 1534
    priv = vm->privateData;

1535
    if (qemuCapsGet(priv->qemuCaps, QEMU_CAPS_MONITOR_JSON)) {
1536
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1537 1538 1539 1540 1541 1542 1543 1544
            goto cleanup;

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

1545
        qemuDomainObjEnterMonitor(driver, vm);
1546
        ret = qemuMonitorSystemPowerdown(priv->mon);
1547
        qemuDomainObjExitMonitor(driver, vm);
1548 1549 1550 1551

        priv->fakeReboot = true;

    endjob:
1552
        if (qemuDomainObjEndJob(driver, vm) == 0)
1553 1554 1555
            vm = NULL;
    } else {
#endif
1556
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
                        _("Reboot is not supported without the JSON monitor"));
#if HAVE_YAJL
    }
#endif

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


1569 1570 1571 1572
static int
qemuDomainDestroyFlags(virDomainPtr dom,
                       unsigned int flags)
{
1573 1574 1575
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1576
    virDomainEventPtr event = NULL;
1577
    qemuDomainObjPrivatePtr priv;
1578

1579 1580
    virCheckFlags(0, -1);

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

1591 1592 1593
    priv = vm->privateData;
    priv->fakeReboot = false;

1594 1595 1596 1597 1598 1599 1600
    /* 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);

1601
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_DESTROY) < 0)
1602 1603
        goto cleanup;

D
Daniel P. Berrange 已提交
1604
    if (!virDomainObjIsActive(vm)) {
1605 1606
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1607
        goto endjob;
1608
    }
1609

J
Jiri Denemark 已提交
1610
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_DESTROYED);
1611 1612 1613
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1614
    virDomainAuditStop(vm, "destroyed");
1615

1616
    if (!vm->persistent) {
1617
        if (qemuDomainObjEndJob(driver, vm) > 0)
1618 1619
            virDomainRemoveInactive(&driver->domains,
                                    vm);
1620 1621
        vm = NULL;
    }
1622 1623
    ret = 0;

1624
endjob:
1625
    if (vm &&
1626
        qemuDomainObjEndJob(driver, vm) == 0)
1627
        vm = NULL;
1628

1629
cleanup:
1630 1631
    if (vm)
        virDomainObjUnlock(vm);
1632 1633
    if (event)
        qemuDomainEventQueue(driver, event);
1634
    qemuDriverUnlock(driver);
1635
    return ret;
D
Daniel P. Berrange 已提交
1636 1637
}

1638 1639 1640 1641 1642
static int
qemuDomainDestroy(virDomainPtr dom)
{
    return qemuDomainDestroyFlags(dom, 0);
}
D
Daniel P. Berrange 已提交
1643

1644
static char *qemudDomainGetOSType(virDomainPtr dom) {
1645 1646 1647
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1648

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

1660
    if (!(type = strdup(vm->def->os.type)))
1661
        virReportOOMError();
1662 1663

cleanup:
1664 1665
    if (vm)
        virDomainObjUnlock(vm);
1666 1667 1668
    return type;
}

1669 1670
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
1671 1672 1673
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
1674

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

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

1687
    ret = vm->def->mem.max_balloon;
1688 1689

cleanup:
1690 1691
    if (vm)
        virDomainObjUnlock(vm);
1692
    return ret;
1693 1694
}

1695 1696
static int qemudDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
                                     unsigned int flags) {
1697
    struct qemud_driver *driver = dom->conn->privateData;
1698
    qemuDomainObjPrivatePtr priv;
1699
    virDomainObjPtr vm;
1700
    virDomainDefPtr persistentDef = NULL;
1701
    int ret = -1, r;
1702
    bool isActive;
1703

1704 1705
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
1706
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1707

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

1719
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1720 1721
        goto cleanup;

1722 1723
    isActive = virDomainObjIsActive(vm);

1724
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
1725
        if (isActive)
1726
            flags = VIR_DOMAIN_AFFECT_LIVE;
1727
        else
1728
            flags = VIR_DOMAIN_AFFECT_CONFIG;
1729
    }
1730 1731
    if (flags == VIR_DOMAIN_MEM_MAXIMUM) {
        if (isActive)
1732
            flags = VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_MEM_MAXIMUM;
1733
        else
1734
            flags = VIR_DOMAIN_AFFECT_CONFIG | VIR_DOMAIN_MEM_MAXIMUM;
1735
    }
1736

1737
    if (!isActive && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
1738 1739 1740 1741 1742
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

1743
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
1744 1745 1746 1747 1748 1749 1750 1751
        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;
    }
1752

1753 1754 1755
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */

1756
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
1757 1758 1759
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot resize the maximum memory on an "
                              "active domain"));
1760
            goto endjob;
1761
        }
1762

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

1773 1774 1775 1776 1777 1778 1779 1780 1781
    } 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;
        }

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

1800
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
1801
            sa_assert(persistentDef);
1802 1803 1804 1805
            persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
            goto endjob;
        }
1806
    }
1807

1808
    ret = 0;
1809
endjob:
1810
    if (qemuDomainObjEndJob(driver, vm) == 0)
1811
        vm = NULL;
1812

1813
cleanup:
1814 1815
    if (vm)
        virDomainObjUnlock(vm);
1816
    return ret;
1817 1818
}

1819 1820
static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem)
{
1821
    return qemudDomainSetMemoryFlags(dom, newmem, VIR_DOMAIN_AFFECT_LIVE);
1822 1823
}

1824 1825 1826 1827 1828
static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return qemudDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
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;

1856
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
1857
        goto cleanup;
1858
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
1859 1860
    ret = qemuMonitorInjectNMI(priv->mon);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
1861
    if (qemuDomainObjEndJob(driver, vm) == 0) {
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
        vm = NULL;
        goto cleanup;
    }

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

1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
static int qemuDomainSendKey(virDomainPtr domain,
                             unsigned int codeset,
                             unsigned int holdtime,
                             unsigned int *keycodes,
                             int nkeycodes,
                             unsigned int flags)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, -1);

1887 1888
    /* translate the keycode to RFB for qemu driver */
    if (codeset != VIR_KEYCODE_SET_RFB) {
1889 1890 1891 1892
        int i;
        int keycode;

        for (i = 0; i < nkeycodes; i++) {
1893
            keycode = virKeycodeValueTranslate(codeset, VIR_KEYCODE_SET_RFB,
1894 1895 1896
                                               keycodes[i]);
            if (keycode < 0) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
1897
             _("cannot translate keycode %u of %s codeset to rfb keycode"),
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
                                keycodes[i],
                                virKeycodeSetTypeToString(codeset));
                return -1;
            }
            keycodes[i] = keycode;
        }
    }

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

    priv = vm->privateData;

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

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

1927
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
    ret = qemuMonitorSendKey(priv->mon, holdtime, keycodes, nkeycodes);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
    if (qemuDomainObjEndJob(driver, vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

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

1942
static int qemudDomainGetInfo(virDomainPtr dom,
1943 1944
                              virDomainInfoPtr info)
{
1945 1946 1947
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1948 1949
    int err;
    unsigned long balloon;
1950

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

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

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

1974
    info->maxMem = vm->def->mem.max_balloon;
1975

D
Daniel P. Berrange 已提交
1976
    if (virDomainObjIsActive(vm)) {
1977
        qemuDomainObjPrivatePtr priv = vm->privateData;
1978 1979 1980

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

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

2011
    info->nrVirtCpu = vm->def->vcpus;
2012 2013 2014
    ret = 0;

cleanup:
2015 2016
    if (vm)
        virDomainObjUnlock(vm);
2017
    return ret;
D
Daniel P. Berrange 已提交
2018 2019
}

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

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

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

E
Eric Blake 已提交
2114 2115
#define QEMUD_SAVE_MAGIC   "LibvirtQemudSave"
#define QEMUD_SAVE_PARTIAL "LibvirtQemudPart"
2116 2117
#define QEMUD_SAVE_VERSION 2

E
Eric Blake 已提交
2118 2119
verify(sizeof(QEMUD_SAVE_MAGIC) == sizeof(QEMUD_SAVE_PARTIAL));

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

    QEMUD_SAVE_FORMAT_LAST
2135
};
2136

2137 2138 2139 2140 2141
VIR_ENUM_DECL(qemudSaveCompression)
VIR_ENUM_IMPL(qemudSaveCompression, QEMUD_SAVE_FORMAT_LAST,
              "raw",
              "gzip",
              "bzip2",
2142 2143
              "xz",
              "lzop")
2144

2145 2146
struct qemud_save_header {
    char magic[sizeof(QEMUD_SAVE_MAGIC)-1];
2147 2148 2149 2150 2151
    uint32_t version;
    uint32_t xml_len;
    uint32_t was_running;
    uint32_t compressed;
    uint32_t unused[15];
2152 2153
};

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


2163
/* return -errno on failure, or 0 on success */
E
Eric Blake 已提交
2164 2165 2166 2167
static int
qemuDomainSaveHeader(int fd, const char *path, char *xml,
                     struct qemud_save_header *header)
{
2168 2169
    int ret = 0;

E
Eric Blake 已提交
2170
    if (safewrite(fd, header, sizeof(*header)) != sizeof(*header)) {
2171
        ret = -errno;
2172
        qemuReportError(VIR_ERR_OPERATION_FAILED,
2173
                        _("failed to write header to domain save file '%s'"),
E
Eric Blake 已提交
2174
                        path);
2175 2176 2177
        goto endjob;
    }

E
Eric Blake 已提交
2178
    if (safewrite(fd, xml, header->xml_len) != header->xml_len) {
2179
        ret = -errno;
2180
        qemuReportError(VIR_ERR_OPERATION_FAILED,
E
Eric Blake 已提交
2181
                         _("failed to write xml to '%s'"), path);
2182 2183 2184 2185 2186 2187
        goto endjob;
    }
endjob:
    return ret;
}

2188 2189 2190 2191 2192 2193 2194 2195 2196
/* Given a enum qemud_save_formats compression level, return the name
 * of the program to run, or NULL if no program is needed.  */
static const char *
qemuCompressProgramName(int compress)
{
    return (compress == QEMUD_SAVE_FORMAT_RAW ? NULL :
            qemudSaveCompressionTypeToString(compress));
}

E
Eric Blake 已提交
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
/* Internal function to properly create or open existing files, with
 * ownership affected by qemu driver setup.  */
static int
qemuOpenFile(struct qemud_driver *driver, const char *path, int oflags,
             bool *needUnlink, bool *bypassSecurityDriver)
{
    struct stat sb;
    bool is_reg = true;
    bool need_unlink = false;
    bool bypass_security = false;
    int fd = -1;
    uid_t uid = getuid();
    gid_t gid = getgid();

    /* path might be a pre-existing block dev, in which case
     * we need to skip the create step, and also avoid unlink
     * in the failure case */
    if (oflags & O_CREAT) {
        need_unlink = true;
        if (stat(path, &sb) == 0) {
            is_reg = !!S_ISREG(sb.st_mode);
            /* If the path is regular file which exists
             * already and dynamic_ownership is off, we don't
             * want to change it's ownership, just open it as-is */
            if (is_reg && !driver->dynamicOwnership) {
                uid = sb.st_uid;
                gid = sb.st_gid;
            }
        }
    }

    /* First try creating the file as root */
    if (!is_reg) {
        fd = open(path, oflags & ~O_CREAT);
        if (fd < 0) {
            virReportSystemError(errno, _("unable to open %s"), path);
            goto cleanup;
        }
    } else {
        if ((fd = virFileOpenAs(path, oflags, S_IRUSR | S_IWUSR,
                                uid, gid, 0)) < 0) {
            /* If we failed as root, and the error was permission-denied
               (EACCES or EPERM), assume it's on a network-connected share
               where root access is restricted (eg, root-squashed NFS). If the
               qemu user (driver->user) is non-root, just set a flag to
               bypass security driver shenanigans, and retry the operation
               after doing setuid to qemu user */
            if ((fd != -EACCES && fd != -EPERM) ||
                driver->user == getuid()) {
                virReportSystemError(-fd,
                                     _("Failed to create file '%s'"),
                                     path);
                goto cleanup;
            }

            /* On Linux we can also verify the FS-type of the directory. */
            switch (virStorageFileIsSharedFS(path)) {
                case 1:
                   /* it was on a network share, so we'll continue
                    * as outlined above
                    */
                   break;

                case -1:
                   virReportSystemError(errno,
                                        _("Failed to create file "
                                          "'%s': couldn't determine fs type"),
                                        path);
                   goto cleanup;

                case 0:
                default:
                   /* local file - log the error returned by virFileOpenAs */
                   virReportSystemError(-fd,
                                        _("Failed to create file '%s'"),
                                        path);
                   goto cleanup;
            }

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

            if ((fd = virFileOpenAs(path, oflags,
                                    S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP,
                                    driver->user, driver->group,
                                    VIR_FILE_OPEN_AS_UID)) < 0) {
                virReportSystemError(-fd,
                                   _("Error from child process creating '%s'"),
                                     path);
                goto cleanup;
            }

            /* Since we had to setuid to create the file, and the fstype
               is NFS, we assume it's a root-squashing NFS share, and that
               the security driver stuff would have failed anyway */

            bypass_security = true;
        }
    }
cleanup:
    if (needUnlink)
        *needUnlink = need_unlink;
    if (bypassSecurityDriver)
        *bypassSecurityDriver = bypass_security;

    return fd;
}

2304
/* This internal function expects the driver lock to already be held on
2305 2306 2307 2308
 * entry and the vm must be active + locked. Vm will be unlocked and
 * potentially free'd after this returns (eg transient VMs are freed
 * shutdown). So 'vm' must not be referenced by the caller after
 * this returns (whether returning success or failure).
2309
 */
2310 2311 2312
static int
qemuDomainSaveInternal(struct qemud_driver *driver, virDomainPtr dom,
                       virDomainObjPtr vm, const char *path,
2313
                       int compressed, bool bypass_cache, const char *xmlin)
2314
{
2315
    char *xml = NULL;
2316
    struct qemud_save_header header;
2317
    bool bypassSecurityDriver = false;
2318
    int ret = -1;
2319
    int rc;
2320
    virDomainEventPtr event = NULL;
2321
    qemuDomainObjPrivatePtr priv;
E
Eric Blake 已提交
2322
    bool needUnlink = false;
2323
    size_t len;
2324
    unsigned long long offset;
2325
    unsigned long long pad;
2326
    int fd = -1;
2327 2328
    int directFlag = 0;
    virFileDirectFdPtr directFd = NULL;
2329

2330 2331 2332
    if (qemuProcessAutoDestroyActive(driver, vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is marked for auto destroy"));
2333
        goto cleanup;
2334 2335
    }

2336
    memset(&header, 0, sizeof(header));
E
Eric Blake 已提交
2337
    memcpy(header.magic, QEMUD_SAVE_PARTIAL, sizeof(header.magic));
2338 2339
    header.version = QEMUD_SAVE_VERSION;

2340
    header.compressed = compressed;
2341

2342
    priv = vm->privateData;
2343

2344 2345
    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             QEMU_ASYNC_JOB_SAVE) < 0)
2346 2347
        goto cleanup;

2348 2349
    memset(&priv->job.info, 0, sizeof(priv->job.info));
    priv->job.info.type = VIR_DOMAIN_JOB_UNBOUNDED;
2350

2351
    /* Pause */
J
Jiri Denemark 已提交
2352
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
2353
        header.was_running = 1;
2354 2355
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_SAVE) < 0)
2356
            goto endjob;
2357 2358 2359 2360 2361 2362

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

2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
    /* Get XML for the domain.  Restore needs only the inactive xml,
     * including secure.  We should get the same result whether xmlin
     * is NULL or whether it was the live xml of the domain moments
     * before.  */
    if (xmlin) {
        virDomainDefPtr def = NULL;

        if (!(def = virDomainDefParseString(driver->caps, xmlin,
                                            QEMU_EXPECTED_VIRT_TYPES,
                                            VIR_DOMAIN_XML_INACTIVE))) {
            goto endjob;
        }
        if (!virDomainDefCheckABIStability(vm->def, def)) {
            virDomainDefFree(def);
            goto endjob;
        }
        xml = virDomainDefFormat(def, (VIR_DOMAIN_XML_INACTIVE |
                                       VIR_DOMAIN_XML_SECURE));
    } else {
        xml = virDomainDefFormat(vm->def, (VIR_DOMAIN_XML_INACTIVE |
                                           VIR_DOMAIN_XML_SECURE));
    }
2387
    if (!xml) {
2388 2389
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to get domain xml"));
2390
        goto endjob;
2391
    }
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411
    len = strlen(xml) + 1;
    offset = sizeof(header) + len;

    /* Due to way we append QEMU state on our header with dd,
     * we need to ensure there's a 512 byte boundary. Unfortunately
     * we don't have an explicit offset in the header, so we fake
     * it by padding the XML string with NUL bytes.  Additionally,
     * we want to ensure that virDomainSaveImageDefineXML can supply
     * slightly larger XML, so we add a miminum padding prior to
     * rounding out to page boundaries.
     */
    pad = 1024;
    pad += (QEMU_MONITOR_MIGRATE_TO_FILE_BS -
            ((offset + pad) % QEMU_MONITOR_MIGRATE_TO_FILE_BS));
    if (VIR_EXPAND_N(xml, len, pad) < 0) {
        virReportOOMError();
        goto endjob;
    }
    offset += pad;
    header.xml_len = len;
2412

2413
    /* Obtain the file handle.  */
2414 2415 2416 2417 2418
    if (bypass_cache) {
        directFlag = virFileDirectFdFlag();
        if (directFlag < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("bypass cache unsupported by this system"));
E
Eric Blake 已提交
2419
            goto cleanup;
2420
        }
2421
    }
E
Eric Blake 已提交
2422 2423 2424 2425
    fd = qemuOpenFile(driver, path, O_WRONLY | O_TRUNC | O_CREAT | directFlag,
                      &needUnlink, &bypassSecurityDriver);
    if (fd < 0)
        goto endjob;
2426 2427 2428
    if (bypass_cache && (directFd = virFileDirectFdNew(&fd, path)) == NULL)
        goto endjob;

2429
    /* Write header to file, followed by XML */
E
Eric Blake 已提交
2430
    if (qemuDomainSaveHeader(fd, path, xml, &header) < 0) {
2431 2432 2433 2434
        VIR_FORCE_CLOSE(fd);
        goto endjob;
    }

2435
    /* Perform the migration */
2436
    if (qemuMigrationToFile(driver, vm, fd, offset, path,
2437
                            qemuCompressProgramName(compressed),
E
Eric Blake 已提交
2438
                            bypassSecurityDriver,
2439
                            QEMU_ASYNC_JOB_SAVE) < 0)
2440
        goto endjob;
E
Eric Blake 已提交
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467

    /* Touch up file header to mark image complete.  */
    if (bypass_cache) {
        /* Reopen the file to touch up the header, since we aren't set
         * up to seek backwards on directFd.  The reopened fd will
         * trigger a single page of file system cache pollution, but
         * that's acceptable.  */
        if (VIR_CLOSE(fd) < 0) {
            virReportSystemError(errno, _("unable to close %s"), path);
            goto endjob;
        }
        if (virFileDirectFdClose(directFd) < 0)
            goto endjob;
        fd = qemuOpenFile(driver, path, O_WRONLY, NULL, NULL);
        if (fd < 0)
            goto endjob;
    } else {
        if (lseek(fd, 0, SEEK_SET) != 0) {
            virReportSystemError(errno, _("unable to seek %s"), path);
            goto endjob;
        }
    }
    memcpy(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic));
    if (safewrite(fd, &header, sizeof(header)) != sizeof(header)) {
        virReportSystemError(errno, _("unable to write %s"), path);
        goto endjob;
    }
2468 2469
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("unable to close %s"), path);
2470
        goto endjob;
2471 2472
    }

2473 2474
    ret = 0;

2475
    /* Shut it down */
J
Jiri Denemark 已提交
2476
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_SAVED);
2477
    virDomainAuditStop(vm, "saved");
2478 2479 2480
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2481
    if (!vm->persistent) {
2482
        if (qemuDomainObjEndAsyncJob(driver, vm) > 0)
2483 2484
            virDomainRemoveInactive(&driver->domains,
                                    vm);
2485 2486
        vm = NULL;
    }
2487

2488
endjob:
2489
    if (vm) {
2490
        if (ret != 0) {
2491
            if (header.was_running && virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
2492
                rc = qemuProcessStartCPUs(driver, vm, dom->conn,
2493 2494
                                          VIR_DOMAIN_RUNNING_SAVE_CANCELED,
                                          QEMU_ASYNC_JOB_SAVE);
2495
                if (rc < 0)
2496
                    VIR_WARN("Unable to resume guest CPUs after save failure");
2497
            }
2498
        }
2499
        if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
2500
            vm = NULL;
2501
    }
2502

2503
cleanup:
2504
    VIR_FORCE_CLOSE(fd);
2505
    virFileDirectFdFree(directFd);
2506
    VIR_FREE(xml);
E
Eric Blake 已提交
2507
    if (ret != 0 && needUnlink)
2508
        unlink(path);
2509 2510
    if (event)
        qemuDomainEventQueue(driver, event);
2511 2512
    if (vm)
        virDomainObjUnlock(vm);
2513
    return ret;
D
Daniel P. Berrange 已提交
2514 2515
}

2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
/* 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;
}

2532 2533 2534
static int
qemuDomainSaveFlags(virDomainPtr dom, const char *path, const char *dxml,
                    unsigned int flags)
2535 2536 2537
{
    struct qemud_driver *driver = dom->conn->privateData;
    int compressed;
2538 2539 2540
    int ret = -1;
    virDomainObjPtr vm = NULL;

2541
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE, -1);
2542

2543
    qemuDriverLock(driver);
2544 2545 2546 2547 2548 2549 2550 2551 2552

    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"));
2553
            goto cleanup;
2554
        }
2555 2556 2557 2558
        if (!qemudCompressProgramAvailable(compressed)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Compression program for image format "
                                    "in configuration file isn't available"));
2559
            goto cleanup;
2560
        }
2561 2562
    }

2563 2564 2565 2566 2567 2568 2569 2570 2571
    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;
    }

2572 2573 2574 2575 2576 2577
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2578
    ret = qemuDomainSaveInternal(driver, dom, vm, path, compressed,
2579 2580
                                 (flags & VIR_DOMAIN_SAVE_BYPASS_CACHE) != 0,
                                 dxml);
2581
    vm = NULL;
2582 2583 2584 2585 2586 2587 2588

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

    return ret;
2589 2590
}

2591 2592 2593 2594 2595 2596
static int
qemuDomainSave(virDomainPtr dom, const char *path)
{
    return qemuDomainSaveFlags(dom, path, NULL, 0);
}

2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617
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;

2618
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE, -1);
2619 2620 2621 2622 2623 2624 2625 2626

    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);
2627
        goto cleanup;
2628 2629
    }

2630 2631 2632 2633 2634
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }
2635 2636 2637 2638 2639
    if (!vm->persistent) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot do managed save for transient domain"));
        goto cleanup;
    }
2640

2641 2642
    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
2643
        goto cleanup;
2644

2645
    VIR_INFO("Saving state to %s", name);
2646 2647

    compressed = QEMUD_SAVE_FORMAT_RAW;
2648
    ret = qemuDomainSaveInternal(driver, dom, vm, name, compressed,
2649 2650
                                 (flags & VIR_DOMAIN_SAVE_BYPASS_CACHE) != 0,
                                 NULL);
2651
    vm = NULL;
2652 2653 2654 2655 2656

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
2657 2658 2659
    VIR_FREE(name);

    return ret;
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669
}

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

2670
    virCheckFlags(0, -1);
2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703

    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;

2704
    virCheckFlags(0, -1);
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728

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

2730 2731 2732 2733
static int
doCoreDump(struct qemud_driver *driver,
           virDomainObjPtr vm,
           const char *path,
2734 2735
           enum qemud_save_formats compress,
           bool bypass_cache)
H
Hu Tao 已提交
2736 2737 2738
{
    int fd = -1;
    int ret = -1;
2739 2740
    virFileDirectFdPtr directFd = NULL;
    int directFlag = 0;
H
Hu Tao 已提交
2741 2742

    /* Create an empty file with appropriate ownership.  */
2743 2744 2745 2746 2747 2748 2749 2750
    if (bypass_cache) {
        directFlag = virFileDirectFdFlag();
        if (directFlag < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("bypass cache unsupported by this system"));
            goto cleanup;
        }
    }
E
Eric Blake 已提交
2751 2752 2753 2754 2755 2756
    /* Core dumps usually imply last-ditch analysis efforts are
     * desired, so we intentionally do not unlink even if a file was
     * created.  */
    if ((fd = qemuOpenFile(driver, path,
                           O_CREAT | O_TRUNC | O_WRONLY | directFlag,
                           NULL, NULL)) < 0)
H
Hu Tao 已提交
2757 2758
        goto cleanup;

2759 2760 2761
    if (bypass_cache && (directFd = virFileDirectFdNew(&fd, path)) == NULL)
        goto cleanup;

2762
    if (qemuMigrationToFile(driver, vm, fd, 0, path,
E
Eric Blake 已提交
2763
                            qemuCompressProgramName(compress), false,
2764
                            QEMU_ASYNC_JOB_DUMP) < 0)
2765 2766
        goto cleanup;

H
Hu Tao 已提交
2767 2768 2769 2770 2771 2772
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno,
                             _("unable to save file %s"),
                             path);
        goto cleanup;
    }
2773 2774
    if (virFileDirectFdClose(directFd) < 0)
        goto cleanup;
H
Hu Tao 已提交
2775

2776
    ret = 0;
H
Hu Tao 已提交
2777 2778

cleanup:
2779
    VIR_FORCE_CLOSE(fd);
2780
    virFileDirectFdFree(directFd);
H
Hu Tao 已提交
2781 2782 2783 2784 2785
    if (ret != 0)
        unlink(path);
    return ret;
}

2786 2787 2788 2789 2790
static enum qemud_save_formats
getCompressionType(struct qemud_driver *driver)
{
    int compress = QEMUD_SAVE_FORMAT_RAW;

2791 2792 2793 2794 2795 2796
    /*
     * 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);
2797 2798 2799
        /* Use "raw" as the format if the specified format is not valid,
         * or the compress program is not available.
         */
2800
        if (compress < 0) {
2801 2802
            VIR_WARN("%s", _("Invalid dump image format specified in "
                             "configuration file, using raw"));
2803
            return QEMUD_SAVE_FORMAT_RAW;
2804
        }
2805
        if (!qemudCompressProgramAvailable(compress)) {
2806 2807 2808
            VIR_WARN("%s", _("Compression program for dump image format "
                             "in configuration file isn't available, "
                             "using raw"));
2809
            return QEMUD_SAVE_FORMAT_RAW;
2810
        }
2811
    }
2812 2813 2814 2815 2816
    return compress;
}

static int qemudDomainCoreDump(virDomainPtr dom,
                               const char *path,
2817
                               unsigned int flags)
2818
{
2819 2820 2821
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int resume = 0, paused = 0;
H
Hu Tao 已提交
2822
    int ret = -1;
2823 2824
    virDomainEventPtr event = NULL;

2825
    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH | VIR_DUMP_BYPASS_CACHE, -1);
2826

P
Paolo Bonzini 已提交
2827 2828 2829 2830 2831 2832
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2833 2834
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
P
Paolo Bonzini 已提交
2835 2836 2837
        goto cleanup;
    }

2838 2839
    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             QEMU_ASYNC_JOB_DUMP) < 0)
2840 2841
        goto cleanup;

D
Daniel P. Berrange 已提交
2842
    if (!virDomainObjIsActive(vm)) {
2843 2844
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
2845
        goto endjob;
P
Paolo Bonzini 已提交
2846 2847
    }

P
Paolo Bonzini 已提交
2848 2849
    /* Migrate will always stop the VM, so the resume condition is
       independent of whether the stop command is issued.  */
J
Jiri Denemark 已提交
2850
    resume = virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING;
P
Paolo Bonzini 已提交
2851 2852

    /* Pause domain for non-live dump */
J
Jiri Denemark 已提交
2853 2854
    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
2855 2856
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_DUMP,
                                QEMU_ASYNC_JOB_DUMP) < 0)
2857
            goto endjob;
P
Paolo Bonzini 已提交
2858
        paused = 1;
2859 2860 2861 2862 2863 2864

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

2867 2868
    ret = doCoreDump(driver, vm, path, getCompressionType(driver),
                     (flags & VIR_DUMP_BYPASS_CACHE) != 0);
2869 2870 2871 2872
    if (ret < 0)
        goto endjob;

    paused = 1;
2873 2874

endjob:
2875
    if ((ret == 0) && (flags & VIR_DUMP_CRASH)) {
J
Jiri Denemark 已提交
2876
        qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_CRASHED);
2877
        virDomainAuditStop(vm, "crashed");
2878 2879 2880 2881 2882
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
    }

P
Paolo Bonzini 已提交
2883 2884 2885
    /* 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.  */
2886
    else if (resume && paused && virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
2887
        if (qemuProcessStartCPUs(driver, vm, dom->conn,
2888 2889
                                 VIR_DOMAIN_RUNNING_UNPAUSED,
                                 QEMU_ASYNC_JOB_DUMP) < 0) {
2890
            if (virGetLastError() == NULL)
2891 2892
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("resuming after dump failed"));
P
Paolo Bonzini 已提交
2893 2894
        }
    }
2895

2896
    if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
2897
        vm = NULL;
2898
    else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
2899 2900 2901 2902
        virDomainRemoveInactive(&driver->domains,
                                vm);
        vm = NULL;
    }
2903 2904

cleanup:
P
Paolo Bonzini 已提交
2905 2906
    if (vm)
        virDomainObjUnlock(vm);
2907 2908
    if (event)
        qemuDomainEventQueue(driver, event);
2909
    qemuDriverUnlock(driver);
P
Paolo Bonzini 已提交
2910 2911 2912
    return ret;
}

2913 2914 2915 2916
static char *
qemuDomainScreenshot(virDomainPtr dom,
                     virStreamPtr st,
                     unsigned int screen,
E
Eric Blake 已提交
2917
                     unsigned int flags)
2918 2919 2920 2921 2922 2923 2924
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    char *tmp = NULL;
    int tmp_fd = -1;
    char *ret = NULL;
E
Eric Blake 已提交
2925
    bool unlink_tmp = false;
2926

E
Eric Blake 已提交
2927 2928
    virCheckFlags(0, NULL);

2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942
    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;

2943
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969
        goto cleanup;

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

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

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

    if ((tmp_fd = mkstemp(tmp)) == -1) {
        virReportSystemError(errno, _("mkstemp(\"%s\") failed"), tmp);
        goto endjob;
    }
E
Eric Blake 已提交
2970
    unlink_tmp = true;
2971

2972 2973
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm, tmp);

2974
    qemuDomainObjEnterMonitor(driver, vm);
2975
    if (qemuMonitorScreendump(priv->mon, tmp) < 0) {
2976
        qemuDomainObjExitMonitor(driver, vm);
2977 2978
        goto endjob;
    }
2979
    qemuDomainObjExitMonitor(driver, vm);
2980 2981 2982 2983 2984 2985

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

E
Eric Blake 已提交
2986
    if (virFDStreamOpenFile(st, tmp, 0, 0, O_RDONLY) < 0) {
2987 2988 2989 2990 2991 2992 2993 2994 2995
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("unable to open stream"));
        goto endjob;
    }

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

endjob:
    VIR_FORCE_CLOSE(tmp_fd);
E
Eric Blake 已提交
2996 2997
    if (unlink_tmp)
        unlink(tmp);
E
Eric Blake 已提交
2998
    VIR_FREE(tmp);
2999

3000
    if (qemuDomainObjEndJob(driver, vm) == 0)
3001 3002 3003 3004 3005 3006 3007 3008
        vm = NULL;

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

H
Hu Tao 已提交
3009 3010 3011
static void processWatchdogEvent(void *data, void *opaque)
{
    int ret;
3012
    struct qemuDomainWatchdogEvent *wdEvent = data;
H
Hu Tao 已提交
3013 3014
    struct qemud_driver *driver = opaque;

W
Wen Congyang 已提交
3015 3016 3017
    qemuDriverLock(driver);
    virDomainObjLock(wdEvent->vm);

H
Hu Tao 已提交
3018 3019 3020 3021 3022
    switch (wdEvent->action) {
    case VIR_DOMAIN_WATCHDOG_ACTION_DUMP:
        {
            char *dumpfile;

E
Eric Blake 已提交
3023
            if (virAsprintf(&dumpfile, "%s/%s-%u",
H
Hu Tao 已提交
3024 3025
                            driver->autoDumpPath,
                            wdEvent->vm->def->name,
E
Eric Blake 已提交
3026 3027
                            (unsigned int)time(NULL)) < 0) {
                virReportOOMError();
W
Wen Congyang 已提交
3028
                goto unlock;
E
Eric Blake 已提交
3029
            }
H
Hu Tao 已提交
3030

3031 3032
            if (qemuDomainObjBeginAsyncJobWithDriver(driver, wdEvent->vm,
                                                     QEMU_ASYNC_JOB_DUMP) < 0) {
W
Wen Congyang 已提交
3033 3034 3035
                VIR_FREE(dumpfile);
                goto unlock;
            }
H
Hu Tao 已提交
3036 3037 3038 3039

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

3044
            ret = doCoreDump(driver, wdEvent->vm, dumpfile,
3045 3046
                             getCompressionType(driver),
                             driver->autoDumpBypassCache);
H
Hu Tao 已提交
3047 3048 3049 3050
            if (ret < 0)
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("Dump failed"));

J
Jiri Denemark 已提交
3051
            ret = qemuProcessStartCPUs(driver, wdEvent->vm, NULL,
3052 3053
                                       VIR_DOMAIN_RUNNING_UNPAUSED,
                                       QEMU_ASYNC_JOB_DUMP);
H
Hu Tao 已提交
3054 3055 3056 3057 3058 3059 3060 3061

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

            VIR_FREE(dumpfile);
        }
        break;
W
Wen Congyang 已提交
3062 3063
    default:
        goto unlock;
H
Hu Tao 已提交
3064 3065
    }

W
Wen Congyang 已提交
3066 3067 3068 3069
endjob:
    /* Safe to ignore value since ref count was incremented in
     * qemuProcessHandleWatchdog().
     */
3070
    ignore_value(qemuDomainObjEndAsyncJob(driver, wdEvent->vm));
W
Wen Congyang 已提交
3071 3072 3073 3074 3075

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

3079 3080 3081
static int qemudDomainHotplugVcpus(struct qemud_driver *driver,
                                   virDomainObjPtr vm,
                                   unsigned int nvcpus)
3082 3083
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
3084
    int i, rc = 1;
3085
    int ret = -1;
3086
    int oldvcpus = vm->def->vcpus;
E
Eric Blake 已提交
3087
    int vcpus = oldvcpus;
3088

3089
    qemuDomainObjEnterMonitor(driver, vm);
3090

3091 3092 3093
    /* 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 已提交
3094 3095
    if (nvcpus > vcpus) {
        for (i = vcpus ; i < nvcpus ; i++) {
3096 3097 3098 3099 3100 3101 3102
            /* Online new CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 1);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
3103
            vcpus++;
3104 3105
        }
    } else {
E
Eric Blake 已提交
3106
        for (i = vcpus - 1 ; i >= nvcpus ; i--) {
3107 3108 3109 3110 3111 3112 3113
            /* Offline old CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 0);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
3114
            vcpus--;
3115 3116 3117 3118 3119 3120
        }
    }

    ret = 0;

cleanup:
3121
    qemuDomainObjExitMonitor(driver, vm);
E
Eric Blake 已提交
3122
    vm->def->vcpus = vcpus;
3123
    virDomainAuditVcpu(vm, oldvcpus, nvcpus, "update", rc == 1);
3124 3125 3126 3127 3128 3129 3130 3131 3132
    return ret;

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


3133
static int
3134 3135
qemuDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                        unsigned int flags)
3136
{
3137 3138
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3139
    virDomainDefPtr persistentDef;
3140 3141
    const char * type;
    int max;
3142
    int ret = -1;
3143 3144
    bool isActive;
    bool maximum;
3145

3146 3147
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
3148 3149 3150 3151 3152
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

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

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

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

3168
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
3169 3170
        goto cleanup;

3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189
    isActive = virDomainObjIsActive(vm);
    maximum = (flags & VIR_DOMAIN_VCPU_MAXIMUM) != 0;
    flags &= ~VIR_DOMAIN_VCPU_MAXIMUM;

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

    /* MAXIMUM cannot be mixed with LIVE.  */
    if (maximum && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("cannot adjust maximum on running domain"));
        goto endjob;
    }

    if (!isActive && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
3190 3191
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("domain is not running"));
3192
        goto endjob;
3193 3194
    }

3195
    if (!vm->persistent && (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
3196 3197 3198 3199 3200
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot change persistent config of a transient domain"));
        goto endjob;
    }

3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213
    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;
    }

3214
    if (!maximum && vm->def->maxvcpus < max) {
3215 3216 3217
        max = vm->def->maxvcpus;
    }

3218 3219 3220 3221 3222 3223 3224
    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;
    }

3225 3226 3227
    if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
        goto endjob;

3228
    switch (flags) {
3229
    case VIR_DOMAIN_AFFECT_CONFIG:
3230 3231 3232 3233 3234 3235 3236
        if (maximum) {
            persistentDef->maxvcpus = nvcpus;
            if (nvcpus < persistentDef->vcpus)
                persistentDef->vcpus = nvcpus;
        } else {
            persistentDef->vcpus = nvcpus;
        }
3237 3238 3239
        ret = 0;
        break;

3240
    case VIR_DOMAIN_AFFECT_LIVE:
3241
        ret = qemudDomainHotplugVcpus(driver, vm, nvcpus);
3242 3243
        break;

3244
    case VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG:
3245
        ret = qemudDomainHotplugVcpus(driver, vm, nvcpus);
3246 3247 3248
        if (ret == 0) {
            persistentDef->vcpus = nvcpus;
        }
3249 3250
        break;
    }
3251

3252
    /* Save the persistent config to disk */
3253
    if (flags & VIR_DOMAIN_AFFECT_CONFIG)
3254 3255
        ret = virDomainSaveConfig(driver->configDir, persistentDef);

3256
endjob:
3257
    if (qemuDomainObjEndJob(driver, vm) == 0)
3258
        vm = NULL;
3259

3260
cleanup:
3261 3262
    if (vm)
        virDomainObjUnlock(vm);
3263
    return ret;
3264 3265
}

3266
static int
3267
qemuDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
3268
{
3269
    return qemuDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
3270 3271
}

3272 3273

static int
3274 3275 3276 3277 3278 3279
qemudDomainPinVcpuFlags(virDomainPtr dom,
                        unsigned int vcpu,
                        unsigned char *cpumap,
                        int maplen,
                        unsigned int flags) {

3280 3281
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3282
    virDomainDefPtr persistentDef = NULL;
3283
    int maxcpu, hostcpus;
3284
    virNodeInfo nodeinfo;
3285
    int ret = -1;
3286
    bool isActive;
3287
    qemuDomainObjPrivatePtr priv;
3288
    bool canResetting = true;
E
Eric Blake 已提交
3289
    int pcpu;
3290

3291 3292 3293
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

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

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

3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317
    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"));
3318
        goto cleanup;
3319 3320
    }

3321 3322 3323
    priv = vm->privateData;

    if (vcpu > (priv->nvcpupids-1)) {
3324 3325 3326
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("vcpu number out of range %d > %d"),
                        vcpu, priv->nvcpupids);
3327
        goto cleanup;
3328 3329
    }

3330 3331 3332 3333 3334 3335 3336 3337 3338
    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;
    }
3339

3340 3341 3342 3343 3344 3345 3346 3347 3348
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
        goto cleanup;
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
    maxcpu = maplen * 8;
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
    /* pinning to all physical cpus means resetting,
     * so check if we can reset setting.
     */
E
Eric Blake 已提交
3349
    for (pcpu = 0; pcpu < hostcpus; pcpu++) {
3350 3351 3352 3353 3354
        if ((cpumap[pcpu/8] & (1 << (pcpu % 8))) == 0) {
            canResetting = false;
            break;
        }
    }
3355

3356
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3357 3358 3359 3360 3361 3362

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

3368
        if (canResetting) {
E
Eric Blake 已提交
3369
            if (virDomainVcpuPinDel(vm->def, vcpu) < 0) {
3370 3371 3372 3373 3374 3375
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to delete vcpupin xml of "
                                  "a running domain"));
                goto cleanup;
            }
        } else {
E
Eric Blake 已提交
3376
            if (virDomainVcpuPinAdd(vm->def, cpumap, maplen, vcpu) < 0) {
3377 3378 3379 3380 3381
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to update or add vcpupin xml of "
                                  "a running domain"));
                goto cleanup;
            }
3382 3383
        }

3384 3385
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
            goto cleanup;
3386
    }
3387

3388 3389
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {

3390
        if (canResetting) {
E
Eric Blake 已提交
3391
            if (virDomainVcpuPinDel(persistentDef, vcpu) < 0) {
3392 3393 3394 3395 3396 3397
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to delete vcpupin xml of "
                                  "a persistent domain"));
                goto cleanup;
            }
        } else {
E
Eric Blake 已提交
3398
            if (virDomainVcpuPinAdd(persistentDef, cpumap, maplen, vcpu) < 0) {
3399 3400 3401 3402 3403
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to update or add vcpupin xml of "
                                  "a persistent domain"));
                goto cleanup;
            }
3404
        }
3405

3406
        ret = virDomainSaveConfig(driver->configDir, persistentDef);
3407 3408 3409
        goto cleanup;
    }

3410
    ret = 0;
3411

3412
cleanup:
3413 3414
    if (vm)
        virDomainObjUnlock(vm);
3415
    return ret;
3416 3417
}

3418 3419 3420 3421 3422 3423 3424 3425 3426
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
    return qemudDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

3427
static int
E
Eric Blake 已提交
3428
qemudDomainGetVcpuPinInfo(virDomainPtr dom,
3429 3430 3431 3432 3433 3434
                          int ncpumaps,
                          unsigned char *cpumaps,
                          int maplen,
                          unsigned int flags) {

    struct qemud_driver *driver = dom->conn->privateData;
E
Eric Blake 已提交
3435
    virDomainObjPtr vm = NULL;
3436 3437 3438 3439 3440 3441
    virNodeInfo nodeinfo;
    virDomainDefPtr targetDef = NULL;
    int ret = -1;
    bool isActive;
    int maxcpu, hostcpus, vcpu, pcpu;
    int n;
E
Eric Blake 已提交
3442
    virDomainVcpuPinDefPtr *vcpupin_list;
3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494
    char *cpumask = NULL;
    unsigned char *cpumap;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

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

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

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

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

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

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

3495 3496 3497
    /* Coverity didn't realize that targetDef must be set if we got here.  */
    sa_assert(targetDef);

3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
        goto cleanup;
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
    maxcpu = maplen * 8;
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;

    /* Clamp to actual number of vcpus */
    if (ncpumaps > targetDef->vcpus)
        ncpumaps = targetDef->vcpus;

    if (ncpumaps < 1) {
        goto cleanup;
    }

    /* initialize cpumaps */
    memset(cpumaps, 0xff, maplen * ncpumaps);
    if (maxcpu % 8) {
        for (vcpu = 0; vcpu < ncpumaps; vcpu++) {
            cpumap = VIR_GET_CPUMAP(cpumaps, maplen, vcpu);
            cpumap[maplen - 1] &= (1 << maxcpu % 8) - 1;
        }
    }

    /* if vcpupin setting exists, there are unused physical cpus */
    for (n = 0; n < targetDef->cputune.nvcpupin; n++) {
        vcpupin_list = targetDef->cputune.vcpupin;
        vcpu = vcpupin_list[n]->vcpuid;
        cpumask = vcpupin_list[n]->cpumask;
        cpumap = VIR_GET_CPUMAP(cpumaps, maplen, vcpu);
        for (pcpu = 0; pcpu < maxcpu; pcpu++) {
            if (cpumask[pcpu] == 0)
                VIR_UNUSE_CPU(cpumap, pcpu);
        }
    }
    ret = ncpumaps;

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

3541 3542 3543 3544 3545 3546
static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
3547 3548
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3549
    virNodeInfo nodeinfo;
3550
    int i, v, maxcpu, hostcpus;
3551
    int ret = -1;
3552
    qemuDomainObjPrivatePtr priv;
3553

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

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

D
Daniel P. Berrange 已提交
3566
    if (!virDomainObjIsActive(vm)) {
3567 3568 3569
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s",
                        _("cannot list vcpu pinning for an inactive domain"));
3570
        goto cleanup;
3571 3572
    }

3573 3574
    priv = vm->privateData;

3575
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
3576
        goto cleanup;
3577

3578
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
3579
    maxcpu = maplen * 8;
3580 3581
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
3582 3583

    /* Clamp to actual number of vcpus */
3584 3585
    if (maxinfo > priv->nvcpupids)
        maxinfo = priv->nvcpupids;
3586

3587 3588 3589 3590 3591 3592
    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;
3593

3594
                if (priv->vcpupids != NULL &&
3595 3596 3597
                    qemudGetProcessInfo(&(info[i].cpuTime),
                                        &(info[i].cpu),
                                        vm->pid,
3598
                                        priv->vcpupids[i]) < 0) {
3599
                    virReportSystemError(errno, "%s",
3600 3601 3602
                                         _("cannot get vCPU placement & pCPU time"));
                    goto cleanup;
                }
3603
            }
3604 3605
        }

3606 3607
        if (cpumaps != NULL) {
            memset(cpumaps, 0, maplen * maxinfo);
3608
            if (priv->vcpupids != NULL) {
3609 3610 3611
                for (v = 0 ; v < maxinfo ; v++) {
                    unsigned char *cpumap = VIR_GET_CPUMAP(cpumaps, maplen, v);

3612
                    if (virProcessInfoGetAffinity(priv->vcpupids[v],
3613
                                                  cpumap, maplen, maxcpu) < 0)
3614
                        goto cleanup;
3615
                }
3616
            } else {
3617
                qemuReportError(VIR_ERR_OPERATION_INVALID,
3618
                                "%s", _("cpu affinity is not available"));
3619
                goto cleanup;
3620 3621 3622
            }
        }
    }
3623
    ret = maxinfo;
3624

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


3632 3633 3634
static int
qemudDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
3635 3636
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3637
    virDomainDefPtr def;
3638
    int ret = -1;
3639
    bool active;
3640

3641 3642
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
3643 3644
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

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

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

3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670
    active = virDomainObjIsActive(vm);

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

3671
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3672
        if (!active) {
3673 3674 3675 3676 3677 3678
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("domain not active"));
            goto cleanup;
        }
        def = vm->def;
    } else {
3679 3680 3681 3682 3683
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("domain is transient"));
            goto cleanup;
        }
3684
        def = vm->newDef ? vm->newDef : vm->def;
3685 3686
    }

3687
    ret = (flags & VIR_DOMAIN_VCPU_MAXIMUM) ? def->maxvcpus : def->vcpus;
3688

3689
cleanup:
3690 3691
    if (vm)
        virDomainObjUnlock(vm);
3692 3693 3694
    return ret;
}

3695 3696 3697
static int
qemudDomainGetMaxVcpus(virDomainPtr dom)
{
3698
    return qemudDomainGetVcpusFlags(dom, (VIR_DOMAIN_AFFECT_LIVE |
3699 3700 3701
                                          VIR_DOMAIN_VCPU_MAXIMUM));
}

3702 3703 3704 3705 3706 3707 3708 3709 3710
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);

3711 3712
    memset(seclabel, 0, sizeof(*seclabel));

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

3721
    if (!virDomainVirtTypeToString(vm->def->virtType)) {
3722 3723 3724
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unknown virt type in domain definition '%d'"),
                        vm->def->virtType);
3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741
        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 已提交
3742
    if (virDomainObjIsActive(vm)) {
3743 3744
        if (virSecurityManagerGetProcessLabel(driver->securityManager,
                                              vm, seclabel) < 0) {
3745 3746 3747
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("Failed to get security label"));
            goto cleanup;
3748 3749 3750 3751 3752 3753 3754 3755
        }
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
3756
    qemuDriverUnlock(driver);
3757 3758 3759
    return ret;
}

3760 3761
static int qemudNodeGetSecurityModel(virConnectPtr conn,
                                     virSecurityModelPtr secmodel)
3762 3763 3764
{
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
    char *p;
3765
    int ret = 0;
3766

3767
    qemuDriverLock(driver);
3768 3769 3770 3771 3772
    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)
3773
        goto cleanup;
3774

3775 3776
    p = driver->caps->host.secModel.model;
    if (strlen(p) >= VIR_SECURITY_MODEL_BUFLEN-1) {
3777 3778 3779
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security model string exceeds max %d bytes"),
                        VIR_SECURITY_MODEL_BUFLEN-1);
3780 3781
        ret = -1;
        goto cleanup;
3782 3783 3784 3785 3786
    }
    strcpy(secmodel->model, p);

    p = driver->caps->host.secModel.doi;
    if (strlen(p) >= VIR_SECURITY_DOI_BUFLEN-1) {
3787 3788 3789
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security DOI string exceeds max %d bytes"),
                        VIR_SECURITY_DOI_BUFLEN-1);
3790 3791
        ret = -1;
        goto cleanup;
3792 3793
    }
    strcpy(secmodel->doi, p);
3794 3795 3796 3797

cleanup:
    qemuDriverUnlock(driver);
    return ret;
3798 3799
}

E
Eric Blake 已提交
3800 3801 3802
/* Return -1 on most failures after raising error, -2 if edit was specified
 * but xmlin does not represent any changes (no error raised), -3 if corrupt
 * image was unlinked (no error raised), and opened fd on success.  */
3803
static int ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4)
3804 3805 3806
qemuDomainSaveImageOpen(struct qemud_driver *driver,
                        const char *path,
                        virDomainDefPtr *ret_def,
3807
                        struct qemud_save_header *ret_header,
3808
                        bool bypass_cache, virFileDirectFdPtr *directFd,
E
Eric Blake 已提交
3809
                        const char *xmlin, bool edit, bool unlink_corrupt)
J
Jiri Denemark 已提交
3810 3811
{
    int fd;
3812
    struct qemud_save_header header;
J
Jiri Denemark 已提交
3813 3814
    char *xml = NULL;
    virDomainDefPtr def = NULL;
3815
    int oflags = edit ? O_RDWR : O_RDONLY;
3816

3817
    if (bypass_cache) {
3818
        int directFlag = virFileDirectFdFlag();
3819 3820 3821 3822 3823
        if (directFlag < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("bypass cache unsupported by this system"));
            goto error;
        }
3824
        oflags |= directFlag;
3825
    }
3826

E
Eric Blake 已提交
3827 3828
    if ((fd = qemuOpenFile(driver, path, oflags, NULL, NULL)) < 0)
        goto error;
3829 3830
    if (bypass_cache && (*directFd = virFileDirectFdNew(&fd, path)) == NULL)
        goto error;
3831 3832

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
3833 3834
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read qemu header"));
J
Jiri Denemark 已提交
3835
        goto error;
3836 3837 3838
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
E
Eric Blake 已提交
3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854
        const char *msg = _("image magic is incorrect");

        if (memcmp(header.magic, QEMUD_SAVE_PARTIAL,
                   sizeof(header.magic)) == 0) {
            msg = _("save image is incomplete");
            if (unlink_corrupt) {
                if (VIR_CLOSE(fd) < 0 || unlink(path) < 0) {
                    virReportSystemError(errno,
                                         _("cannot remove corrupt file: %s"),
                                         path);
                    goto error;
                }
                return -3;
            }
        }
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s", msg);
J
Jiri Denemark 已提交
3855
        goto error;
3856 3857 3858
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3859 3860 3861 3862 3863
        /* convert endianess and try again */
        bswap_header(&header);
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3864 3865 3866
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("image version is not supported (%d > %d)"),
                        header.version, QEMUD_SAVE_VERSION);
J
Jiri Denemark 已提交
3867
        goto error;
3868 3869
    }

3870 3871 3872
    if (header.xml_len <= 0) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("invalid XML length: %d"), header.xml_len);
J
Jiri Denemark 已提交
3873
        goto error;
3874 3875
    }

3876 3877
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
        virReportOOMError();
J
Jiri Denemark 已提交
3878
        goto error;
3879 3880 3881
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
3882 3883
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read XML"));
J
Jiri Denemark 已提交
3884
        goto error;
3885 3886
    }

3887 3888 3889 3890 3891 3892 3893 3894 3895
    if (edit && STREQ(xml, xmlin)) {
        VIR_FREE(xml);
        if (VIR_CLOSE(fd) < 0) {
            virReportSystemError(errno, _("cannot close file: %s"), path);
            goto error;
        }
        return -2;
    }

3896
    /* Create a domain from this XML */
3897
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
3898
                                        QEMU_EXPECTED_VIRT_TYPES,
3899
                                        VIR_DOMAIN_XML_INACTIVE)))
J
Jiri Denemark 已提交
3900
        goto error;
3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914
    if (xmlin) {
        virDomainDefPtr def2 = NULL;

        if (!(def2 = virDomainDefParseString(driver->caps, xmlin,
                                             QEMU_EXPECTED_VIRT_TYPES,
                                             VIR_DOMAIN_XML_INACTIVE)))
            goto error;
        if (!virDomainDefCheckABIStability(def, def2)) {
            virDomainDefFree(def2);
            goto error;
        }
        virDomainDefFree(def);
        def = def2;
    }
3915

J
Jiri Denemark 已提交
3916
    VIR_FREE(xml);
3917

J
Jiri Denemark 已提交
3918 3919
    *ret_def = def;
    *ret_header = header;
3920

J
Jiri Denemark 已提交
3921
    return fd;
3922

J
Jiri Denemark 已提交
3923 3924 3925
error:
    virDomainDefFree(def);
    VIR_FREE(xml);
3926
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
3927 3928 3929 3930

    return -1;
}

3931 3932 3933 3934 3935 3936 3937
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 已提交
3938 3939 3940 3941
{
    int ret = -1;
    virDomainEventPtr event;
    int intermediatefd = -1;
3942
    virCommandPtr cmd = NULL;
J
Jiri Denemark 已提交
3943 3944 3945

    if (header->version == 2) {
        const char *prog = qemudSaveCompressionTypeToString(header->compressed);
3946
        if (prog == NULL) {
3947 3948
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("Invalid compressed save format %d"),
J
Jiri Denemark 已提交
3949 3950
                            header->compressed);
            goto out;
3951
        }
3952

J
Jiri Denemark 已提交
3953
        if (header->compressed != QEMUD_SAVE_FORMAT_RAW) {
3954
            cmd = virCommandNewArgList(prog, "-dc", NULL);
3955 3956
            intermediatefd = *fd;
            *fd = -1;
3957 3958 3959 3960 3961

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

            if (virCommandRunAsync(cmd, NULL) < 0) {
3962 3963
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Failed to start decompression binary %s"),
3964
                                prog);
3965
                *fd = intermediatefd;
J
Jiri Denemark 已提交
3966
                goto out;
3967 3968 3969
            }
        }
    }
J
Jiri Denemark 已提交
3970

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

3975
    if (intermediatefd != -1) {
3976
        if (ret < 0) {
3977 3978 3979
            /* if there was an error setting up qemu, the intermediate
             * process will wait forever to write to stdout, so we
             * must manually kill it.
3980 3981
             */
            VIR_FORCE_CLOSE(intermediatefd);
3982
            VIR_FORCE_CLOSE(*fd);
3983 3984
        }

3985 3986
        if (virCommandWait(cmd, NULL) < 0)
            ret = -1;
3987
    }
3988
    VIR_FORCE_CLOSE(intermediatefd);
J
Jiri Denemark 已提交
3989

3990 3991 3992
    if (VIR_CLOSE(*fd) < 0) {
        virReportSystemError(errno, _("cannot close file: %s"), path);
        ret = -1;
3993
    }
J
Jiri Denemark 已提交
3994

3995
    if (ret < 0) {
3996
        virDomainAuditStart(vm, "restored", false);
J
Jiri Denemark 已提交
3997
        goto out;
3998
    }
3999

4000 4001 4002
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
4003
    virDomainAuditStart(vm, "restored", true);
J
Jiri Denemark 已提交
4004 4005 4006
    if (event)
        qemuDomainEventQueue(driver, event);

4007

4008
    /* If it was running before, resume it now. */
J
Jiri Denemark 已提交
4009
    if (header->was_running) {
J
Jiri Denemark 已提交
4010
        if (qemuProcessStartCPUs(driver, vm, conn,
4011 4012
                                 VIR_DOMAIN_RUNNING_RESTORED,
                                 QEMU_ASYNC_JOB_NONE) < 0) {
4013
            if (virGetLastError() == NULL)
4014 4015
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("failed to resume domain"));
J
Jiri Denemark 已提交
4016
            goto out;
4017
        }
4018 4019
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
J
Jiri Denemark 已提交
4020
            goto out;
4021
        }
4022
    }
J
Jiri Denemark 已提交
4023

4024
    ret = 0;
4025

J
Jiri Denemark 已提交
4026
out:
4027
    virCommandFree(cmd);
4028 4029
    if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
                                                 vm, path) < 0)
4030 4031
        VIR_WARN("failed to restore save state label on %s", path);

J
Jiri Denemark 已提交
4032 4033 4034
    return ret;
}

4035
static int
4036 4037 4038 4039
qemuDomainRestoreFlags(virConnectPtr conn,
                       const char *path,
                       const char *dxml,
                       unsigned int flags)
4040
{
J
Jiri Denemark 已提交
4041 4042 4043 4044 4045 4046
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    int fd = -1;
    int ret = -1;
    struct qemud_save_header header;
4047
    virFileDirectFdPtr directFd = NULL;
J
Jiri Denemark 已提交
4048

4049
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE, -1);
4050

J
Jiri Denemark 已提交
4051 4052
    qemuDriverLock(driver);

4053 4054
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header,
                                 (flags & VIR_DOMAIN_SAVE_BYPASS_CACHE) != 0,
E
Eric Blake 已提交
4055
                                 &directFd, dxml, false, false);
J
Jiri Denemark 已提交
4056 4057 4058 4059 4060 4061 4062 4063 4064
    if (fd < 0)
        goto cleanup;

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

    if (!(vm = virDomainAssignDef(driver->caps,
                                  &driver->domains,
                                  def, true))) {
4065
        /* virDomainAssignDef already set the error */
J
Jiri Denemark 已提交
4066 4067 4068 4069
        goto cleanup;
    }
    def = NULL;

4070
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
J
Jiri Denemark 已提交
4071 4072
        goto cleanup;

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

4077
    if (qemuDomainObjEndJob(driver, vm) == 0)
4078
        vm = NULL;
J
Jiri Denemark 已提交
4079 4080 4081 4082
    else if (ret < 0 && !vm->persistent) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }
4083

4084 4085
cleanup:
    virDomainDefFree(def);
4086
    VIR_FORCE_CLOSE(fd);
4087
    virFileDirectFdFree(directFd);
4088 4089 4090
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
4091
    return ret;
D
Daniel P. Berrange 已提交
4092 4093
}

4094 4095 4096 4097 4098 4099 4100
static int
qemuDomainRestore(virConnectPtr conn,
                  const char *path)
{
    return qemuDomainRestoreFlags(conn, path, NULL, 0);
}

4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116
static char *
qemuDomainSaveImageGetXMLDesc(virConnectPtr conn, const char *path,
                              unsigned int flags)
{
    struct qemud_driver *driver = conn->privateData;
    char *ret = NULL;
    virDomainDefPtr def = NULL;
    int fd = -1;
    struct qemud_save_header header;

    /* We only take subset of virDomainDefFormat flags.  */
    virCheckFlags(VIR_DOMAIN_XML_SECURE, NULL);

    qemuDriverLock(driver);

    fd = qemuDomainSaveImageOpen(driver, path, &def, &header, false, NULL,
E
Eric Blake 已提交
4117
                                 NULL, false, false);
4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147

    if (fd < 0)
        goto cleanup;

    ret = qemuDomainDefFormatXML(driver, def, flags);

cleanup:
    virDomainDefFree(def);
    VIR_FORCE_CLOSE(fd);
    qemuDriverUnlock(driver);
    return ret;
}

static int
qemuDomainSaveImageDefineXML(virConnectPtr conn, const char *path,
                             const char *dxml, unsigned int flags)
{
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;
    virDomainDefPtr def = NULL;
    int fd = -1;
    struct qemud_save_header header;
    char *xml = NULL;
    size_t len;

    virCheckFlags(0, -1);

    qemuDriverLock(driver);

    fd = qemuDomainSaveImageOpen(driver, path, &def, &header, false, NULL,
E
Eric Blake 已提交
4148
                                 dxml, true, false);
4149 4150 4151 4152 4153 4154 4155 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 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192

    if (fd < 0) {
        /* Check for special case of no change needed.  */
        if (fd == -2)
            ret = 0;
        goto cleanup;
    }

    xml = qemuDomainDefFormatXML(driver, def, (VIR_DOMAIN_XML_INACTIVE |
                                               VIR_DOMAIN_XML_SECURE));
    if (!xml)
        goto cleanup;
    len = strlen(xml) + 1;

    if (len > header.xml_len) {
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("new xml too large to fit in file"));
        goto cleanup;
    }
    if (VIR_EXPAND_N(xml, len, header.xml_len - len) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (lseek(fd, sizeof(header), SEEK_SET) != sizeof(header)) {
        virReportSystemError(errno, _("cannot seek in '%s'"), path);
        goto cleanup;
    }
    if (safewrite(fd, xml, len) != len ||
        VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("failed to write xml to '%s'"), path);
        goto cleanup;
    }

    ret = 0;

cleanup:
    virDomainDefFree(def);
    VIR_FORCE_CLOSE(fd);
    VIR_FREE(xml);
    qemuDriverUnlock(driver);
    return ret;
}

E
Eric Blake 已提交
4193 4194
/* Return 0 on success, 1 if incomplete saved image was silently unlinked,
 * and -1 on failure with error raised.  */
4195 4196 4197 4198
static int
qemuDomainObjRestore(virConnectPtr conn,
                     struct qemud_driver *driver,
                     virDomainObjPtr vm,
4199 4200
                     const char *path,
                     bool bypass_cache)
J
Jiri Denemark 已提交
4201 4202 4203 4204 4205
{
    virDomainDefPtr def = NULL;
    int fd = -1;
    int ret = -1;
    struct qemud_save_header header;
4206
    virFileDirectFdPtr directFd = NULL;
J
Jiri Denemark 已提交
4207

4208
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header,
E
Eric Blake 已提交
4209 4210 4211 4212
                                 bypass_cache, &directFd, NULL, false, true);
    if (fd < 0) {
        if (fd == -3)
            ret = 1;
J
Jiri Denemark 已提交
4213
        goto cleanup;
E
Eric Blake 已提交
4214
    }
J
Jiri Denemark 已提交
4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232

    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;

4233
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path);
4234 4235
    if (virFileDirectFdClose(directFd) < 0)
        VIR_WARN("Failed to close %s", path);
J
Jiri Denemark 已提交
4236 4237 4238

cleanup:
    virDomainDefFree(def);
4239
    VIR_FORCE_CLOSE(fd);
4240
    virFileDirectFdFree(directFd);
J
Jiri Denemark 已提交
4241 4242 4243
    return ret;
}

D
Daniel P. Berrange 已提交
4244

4245
static char *qemuDomainGetXMLDesc(virDomainPtr dom,
4246 4247
                                  unsigned int flags)
{
4248 4249 4250
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;
4251 4252
    unsigned long balloon;
    int err;
4253

4254
    /* Flags checked by virDomainDefFormat */
4255

4256
    qemuDriverLock(driver);
4257
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4258

D
Daniel P. Berrange 已提交
4259
    if (!vm) {
4260 4261
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4262 4263
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4264
        goto cleanup;
D
Daniel P. Berrange 已提交
4265 4266
    }

4267 4268 4269 4270
    /* 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))) {
4271
        qemuDomainObjPrivatePtr priv = vm->privateData;
4272 4273
        /* Don't delay if someone's using the monitor, just use
         * existing most recent data instead */
4274
        if (!priv->job.active) {
4275
            if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_QUERY) < 0)
4276 4277
                goto cleanup;

4278
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
4279
            err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
4280
            qemuDomainObjExitMonitorWithDriver(driver, vm);
4281
            if (qemuDomainObjEndJob(driver, vm) == 0) {
4282 4283 4284
                vm = NULL;
                goto cleanup;
            }
4285 4286 4287
            if (err < 0)
                goto cleanup;
            if (err > 0)
4288
                vm->def->mem.cur_balloon = balloon;
4289 4290
            /* err == 0 indicates no balloon support, so ignore it */
        }
4291
    }
4292

4293
    ret = qemuDomainFormatXML(driver, vm, flags);
4294 4295

cleanup:
4296 4297
    if (vm)
        virDomainObjUnlock(vm);
4298
    qemuDriverUnlock(driver);
4299
    return ret;
D
Daniel P. Berrange 已提交
4300 4301 4302
}


4303 4304 4305
static char *qemuDomainXMLFromNative(virConnectPtr conn,
                                     const char *format,
                                     const char *config,
E
Eric Blake 已提交
4306 4307
                                     unsigned int flags)
{
4308
    struct qemud_driver *driver = conn->privateData;
4309 4310 4311
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
4312 4313
    virCheckFlags(0, NULL);

4314
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
4315 4316
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
4317 4318 4319
        goto cleanup;
    }

4320
    qemuDriverLock(driver);
4321 4322
    def = qemuParseCommandLineString(driver->caps, config,
                                     NULL, NULL, NULL);
4323
    qemuDriverUnlock(driver);
4324 4325 4326
    if (!def)
        goto cleanup;

4327 4328 4329 4330 4331 4332
    if (!def->name &&
        !(def->name = strdup("unnamed"))) {
        virReportOOMError();
        goto cleanup;
    }

4333
    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
4334 4335 4336 4337 4338 4339

cleanup:
    virDomainDefFree(def);
    return xml;
}

4340 4341 4342
static char *qemuDomainXMLToNative(virConnectPtr conn,
                                   const char *format,
                                   const char *xmlData,
E
Eric Blake 已提交
4343 4344
                                   unsigned int flags)
{
4345 4346
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
4347
    virDomainChrSourceDef monConfig;
4348
    virBitmapPtr qemuCaps = NULL;
E
Eric Blake 已提交
4349
    virCommandPtr cmd = NULL;
4350 4351 4352
    char *ret = NULL;
    int i;

E
Eric Blake 已提交
4353 4354
    virCheckFlags(0, NULL);

4355 4356
    qemuDriverLock(driver);

4357
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
4358 4359
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
4360 4361 4362
        goto cleanup;
    }

M
Matthias Bolte 已提交
4363 4364
    def = virDomainDefParseString(driver->caps, xmlData,
                                  QEMU_EXPECTED_VIRT_TYPES, 0);
4365 4366 4367
    if (!def)
        goto cleanup;

4368 4369
    /* Since we're just exporting args, we can't do bridge/network/direct
     * setups, since libvirt will normally create TAP/macvtap devices
4370 4371 4372 4373 4374
     * 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];
4375
        int bootIndex = net->bootIndex;
4376 4377 4378 4379
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            int actualType = virDomainNetGetActualType(net);
            const char *brname;

4380
            VIR_FREE(net->data.network.name);
4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413
            VIR_FREE(net->data.network.portgroup);
            if ((actualType == VIR_DOMAIN_NET_TYPE_BRIDGE) &&
                (brname = virDomainNetGetActualBridgeName(net))) {

                char *brnamecopy = strdup(brname);
                if (!brnamecopy) {
                    virReportOOMError();
                    goto cleanup;
                }

                virDomainActualNetDefFree(net->data.network.actual);

                memset(net, 0, sizeof *net);

                net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
                net->data.ethernet.dev = brnamecopy;
                net->data.ethernet.script = NULL;
                net->data.ethernet.ipaddr = NULL;
            } else {
                /* actualType is either NETWORK or DIRECT. In either
                 * case, the best we can do is NULL everything out.
                 */
                virDomainActualNetDefFree(net->data.network.actual);
                memset(net, 0, sizeof *net);

                net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
                net->data.ethernet.dev = NULL;
                net->data.ethernet.script = NULL;
                net->data.ethernet.ipaddr = NULL;
            }
        } else if (net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
            VIR_FREE(net->data.direct.linkdev);
            VIR_FREE(net->data.direct.virtPortProfile);
4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432

            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;
        }
4433
        net->bootIndex = bootIndex;
4434 4435 4436 4437
    }
    for (i = 0 ; i < def->ngraphics ; i++) {
        if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
            def->graphics[i]->data.vnc.autoport)
4438
            def->graphics[i]->data.vnc.port = QEMU_VNC_PORT_MIN;
4439 4440
    }

4441
    if (qemuCapsExtractVersionInfo(def->emulator, def->os.arch,
4442
                                   NULL,
4443
                                   &qemuCaps) < 0)
4444 4445
        goto cleanup;

4446
    if (qemuProcessPrepareMonitorChr(driver, &monConfig, def->name) < 0)
4447
        goto cleanup;
4448

4449
    if (!(cmd = qemuBuildCommandLine(conn, driver, def,
4450
                                     &monConfig, false, qemuCaps,
4451
                                     NULL, -1, NULL, VIR_VM_OP_NO_OP)))
4452 4453
        goto cleanup;

E
Eric Blake 已提交
4454
    ret = virCommandToString(cmd);
4455 4456

cleanup:
4457
    qemuDriverUnlock(driver);
4458

4459
    qemuCapsFree(qemuCaps);
E
Eric Blake 已提交
4460
    virCommandFree(cmd);
4461 4462 4463 4464 4465
    virDomainDefFree(def);
    return ret;
}


4466
static int qemudListDefinedDomains(virConnectPtr conn,
4467
                            char **const names, int nnames) {
4468
    struct qemud_driver *driver = conn->privateData;
4469
    int n;
4470

4471
    qemuDriverLock(driver);
4472
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
4473
    qemuDriverUnlock(driver);
4474
    return n;
D
Daniel P. Berrange 已提交
4475 4476
}

4477
static int qemudNumDefinedDomains(virConnectPtr conn) {
4478
    struct qemud_driver *driver = conn->privateData;
4479
    int n;
4480

4481
    qemuDriverLock(driver);
4482
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
4483
    qemuDriverUnlock(driver);
4484

4485
    return n;
D
Daniel P. Berrange 已提交
4486 4487 4488
}


4489 4490 4491 4492
static int
qemuDomainObjStart(virConnectPtr conn,
                   struct qemud_driver *driver,
                   virDomainObjPtr vm,
4493
                   unsigned int flags)
J
Jiri Denemark 已提交
4494 4495 4496
{
    int ret = -1;
    char *managed_save;
4497 4498 4499 4500
    bool start_paused = (flags & VIR_DOMAIN_START_PAUSED) != 0;
    bool autodestroy = (flags & VIR_DOMAIN_START_AUTODESTROY) != 0;
    bool bypass_cache = (flags & VIR_DOMAIN_START_BYPASS_CACHE) != 0;
    bool force_boot = (flags & VIR_DOMAIN_START_FORCE_BOOT) != 0;
J
Jiri Denemark 已提交
4501 4502 4503

    /*
     * If there is a managed saved state restore it instead of starting
4504
     * from scratch. The old state is removed once the restoring succeeded.
J
Jiri Denemark 已提交
4505 4506
     */
    managed_save = qemuDomainManagedSavePath(driver, vm);
4507 4508 4509 4510

    if (!managed_save)
        goto cleanup;

E
Eric Blake 已提交
4511
    if (virFileExists(managed_save)) {
4512 4513 4514 4515 4516 4517 4518 4519 4520 4521
        if (force_boot) {
            if (unlink(managed_save) < 0) {
                virReportSystemError(errno,
                                     _("cannot remove managed save file %s"),
                                     managed_save);
                goto cleanup;
            }
        } else {
            ret = qemuDomainObjRestore(conn, driver, vm, managed_save,
                                       bypass_cache);
J
Jiri Denemark 已提交
4522

E
Eric Blake 已提交
4523
            if (ret == 0 && unlink(managed_save) < 0)
4524
                VIR_WARN("Failed to remove the managed state %s", managed_save);
E
Eric Blake 已提交
4525 4526 4527 4528
            if (ret > 0)
                VIR_WARN("Ignoring incomplete managed state %s", managed_save);
            else
                goto cleanup;
4529
        }
J
Jiri Denemark 已提交
4530 4531
    }

4532
    ret = qemuProcessStart(conn, driver, vm, NULL, start_paused,
4533
                           autodestroy, -1, NULL, NULL, VIR_VM_OP_CREATE);
4534
    virDomainAuditStart(vm, "booted", ret >= 0);
4535
    if (ret >= 0) {
J
Jiri Denemark 已提交
4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548
        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;
}

4549
static int
4550
qemuDomainStartWithFlags(virDomainPtr dom, unsigned int flags)
4551
{
4552 4553 4554
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
4555

4556
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
4557
                  VIR_DOMAIN_START_AUTODESTROY |
4558 4559
                  VIR_DOMAIN_START_BYPASS_CACHE |
                  VIR_DOMAIN_START_FORCE_BOOT, -1);
4560

4561
    qemuDriverLock(driver);
4562
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4563

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

4572
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
4573 4574 4575
        goto cleanup;

    if (virDomainObjIsActive(vm)) {
4576 4577
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is already running"));
4578 4579 4580
        goto endjob;
    }

4581
    if (qemuDomainObjStart(dom->conn, driver, vm, flags) < 0)
4582 4583 4584
        goto endjob;

    ret = 0;
4585

4586
endjob:
4587
    if (qemuDomainObjEndJob(driver, vm) == 0)
4588
        vm = NULL;
4589

4590
cleanup:
4591 4592
    if (vm)
        virDomainObjUnlock(vm);
4593
    qemuDriverUnlock(driver);
4594
    return ret;
D
Daniel P. Berrange 已提交
4595 4596
}

4597
static int
4598
qemuDomainStart(virDomainPtr dom)
4599
{
4600
    return qemuDomainStartWithFlags(dom, 0);
4601 4602
}

4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617
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;

4618
        if (def->os.machine && STRNEQ(def->os.machine, machine->name))
4619 4620 4621
            continue;

        if (!(*canonical = strdup(machine->canonical))) {
4622
            virReportOOMError();
4623 4624 4625 4626 4627 4628 4629 4630 4631
            return -1;
        }

        break;
    }

    return 0;
}

4632 4633 4634 4635 4636 4637
static int
qemudCanonicalizeMachineDirect(virDomainDefPtr def, char **canonical)
{
    virCapsGuestMachinePtr *machines = NULL;
    int i, nmachines = 0;

4638
    if (qemuCapsProbeMachineTypes(def->emulator, &machines, &nmachines) < 0)
4639 4640 4641 4642 4643 4644
        return -1;

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

4645
        if (def->os.machine && STRNEQ(def->os.machine, machines[i]->name))
4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657
            continue;

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

    virCapabilitiesFreeMachines(machines, nmachines);

    return 0;
}

4658 4659
int
qemudCanonicalizeMachine(struct qemud_driver *driver, virDomainDefPtr def)
4660 4661 4662 4663 4664 4665
{
    char *canonical = NULL;
    int i;

    for (i = 0; i < driver->caps->nguests; i++) {
        virCapsGuestPtr guest = driver->caps->guests[i];
4666
        virCapsGuestDomainInfoPtr info;
4667 4668 4669
        int j;

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

4672 4673 4674 4675 4676 4677 4678 4679 4680
            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;
4681 4682
        }

4683 4684 4685 4686
        info = &guest->arch.defaultInfo;

        if (info->emulator && STREQ(info->emulator, def->emulator)) {
            if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
4687 4688 4689 4690
                return -1;
            goto out;
        }
    }
4691 4692 4693 4694

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

4695 4696 4697 4698 4699 4700 4701
out:
    if (canonical) {
        VIR_FREE(def->os.machine);
        def->os.machine = canonical;
    }
    return 0;
}
D
Daniel P. Berrange 已提交
4702

4703
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
4704
    struct qemud_driver *driver = conn->privateData;
4705
    virDomainDefPtr def;
4706
    virDomainObjPtr vm = NULL;
4707
    virDomainPtr dom = NULL;
4708
    virDomainEventPtr event = NULL;
4709
    int dupVM;
4710

4711
    qemuDriverLock(driver);
4712
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
4713
                                        QEMU_EXPECTED_VIRT_TYPES,
4714
                                        VIR_DOMAIN_XML_INACTIVE)))
4715
        goto cleanup;
4716

4717
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
4718 4719
        goto cleanup;

4720 4721
    if ((dupVM = virDomainObjIsDuplicate(&driver->domains, def, 0)) < 0)
        goto cleanup;
4722

4723
    if (qemudCanonicalizeMachine(driver, def) < 0)
4724 4725
        goto cleanup;

4726
    if (qemuDomainAssignPCIAddresses(def) < 0)
4727 4728
        goto cleanup;

4729
    if (!(vm = virDomainAssignDef(driver->caps,
4730
                                  &driver->domains,
4731
                                  def, false))) {
4732
        goto cleanup;
4733
    }
4734
    def = NULL;
4735
    vm->persistent = 1;
4736

4737
    if (virDomainSaveConfig(driver->configDir,
4738
                            vm->newDef ? vm->newDef : vm->def) < 0) {
4739
        VIR_INFO("Defining domain '%s'", vm->def->name);
4740 4741
        virDomainRemoveInactive(&driver->domains,
                                vm);
4742
        vm = NULL;
4743
        goto cleanup;
4744 4745
    }

4746 4747
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
4748
                                     !dupVM ?
4749 4750
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
4751

4752
    VIR_INFO("Creating domain '%s'", vm->def->name);
4753
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
4754
    if (dom) dom->id = vm->def->id;
4755 4756

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

4766 4767 4768 4769
static int
qemuDomainUndefineFlags(virDomainPtr dom,
                         unsigned int flags)
{
4770 4771
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4772
    virDomainEventPtr event = NULL;
4773
    char *name = NULL;
4774
    int ret = -1;
D
Daniel P. Berrange 已提交
4775

4776 4777
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

4778
    qemuDriverLock(driver);
4779
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4780

D
Daniel P. Berrange 已提交
4781
    if (!vm) {
4782 4783
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4784 4785
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4786
        goto cleanup;
D
Daniel P. Berrange 已提交
4787 4788
    }

4789
    if (!vm->persistent) {
4790
        qemuReportError(VIR_ERR_OPERATION_INVALID,
4791
                        "%s", _("cannot undefine transient domain"));
4792
        goto cleanup;
4793 4794
    }

4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814
    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("Failed to remove domain managed "
                                  "save image"));
                goto cleanup;
            }
        } else {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("Refusing to undefine while domain managed "
                              "save image exists"));
            goto cleanup;
        }
    }

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

4818 4819 4820
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
4821

4822
    VIR_INFO("Undefining domain '%s'", vm->def->name);
4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835

    /* If the domain is active, keep it running but set it as transient.
     * domainDestroy and domainShutdown will take care of removing the
     * domain obj from the hash table.
     */
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
        virDomainRemoveInactive(&driver->domains,
                                vm);
        vm = NULL;
    }

4836
    ret = 0;
D
Daniel P. Berrange 已提交
4837

4838
cleanup:
4839
    VIR_FREE(name);
4840 4841
    if (vm)
        virDomainObjUnlock(vm);
4842 4843
    if (event)
        qemuDomainEventQueue(driver, event);
4844
    qemuDriverUnlock(driver);
4845
    return ret;
D
Daniel P. Berrange 已提交
4846 4847
}

4848 4849 4850 4851 4852 4853
static int
qemudDomainUndefine(virDomainPtr dom)
{
    return qemuDomainUndefineFlags(dom, 0);
}

4854 4855 4856
static int
qemuDomainAttachDeviceDiskLive(struct qemud_driver *driver,
                               virDomainObjPtr vm,
4857
                               virDomainDeviceDefPtr dev)
4858 4859 4860 4861
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
    int ret = -1;
4862

4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882
    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:
4883
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, false);
4884 4885 4886 4887
        break;
    case VIR_DOMAIN_DISK_DEVICE_DISK:
        if (disk->bus == VIR_DOMAIN_DISK_BUS_USB)
            ret = qemuDomainAttachUsbMassstorageDevice(driver, vm,
4888
                                                       disk);
4889
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
4890
            ret = qemuDomainAttachPciDiskDevice(driver, vm, disk);
4891
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
4892
            ret = qemuDomainAttachSCSIDisk(driver, vm, disk);
4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918
        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,
4919
                                     virDomainDeviceDefPtr dev)
4920 4921 4922 4923 4924 4925
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
4926
        ret = qemuDomainAttachPciControllerDevice(driver, vm, cont);
4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939
        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,
4940
                           virDomainPtr dom)
4941 4942 4943 4944 4945 4946
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
4947
        qemuDomainObjCheckDiskTaint(driver, vm, dev->data.disk, -1);
4948
        ret = qemuDomainAttachDeviceDiskLive(driver, vm, dev);
4949 4950 4951 4952 4953
        if (!ret)
            dev->data.disk = NULL;
        break;

    case VIR_DOMAIN_DEVICE_CONTROLLER:
4954
        ret = qemuDomainAttachDeviceControllerLive(driver, vm, dev);
4955 4956 4957 4958
        if (!ret)
            dev->data.controller = NULL;
        break;

4959 4960 4961 4962 4963 4964 4965
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainAttachLease(driver, vm,
                                    dev->data.lease);
        if (ret == 0)
            dev->data.lease = NULL;
        break;

4966
    case VIR_DOMAIN_DEVICE_NET:
4967
        qemuDomainObjCheckNetTaint(driver, vm, dev->data.net, -1);
4968
        ret = qemuDomainAttachNetDevice(dom->conn, driver, vm,
4969
                                        dev->data.net);
4970 4971 4972 4973 4974 4975
        if (!ret)
            dev->data.net = NULL;
        break;

    case VIR_DOMAIN_DEVICE_HOSTDEV:
        ret = qemuDomainAttachHostDevice(driver, vm,
4976
                                         dev->data.hostdev);
4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993
        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,
4994
                               virDomainDeviceDefPtr dev)
4995 4996 4997 4998 4999 5000 5001
{
    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)
5002
            ret = qemuDomainDetachPciDiskDevice(driver, vm, dev);
5003
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
5004
            ret =  qemuDomainDetachDiskDevice(driver, vm, dev);
5005
        else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB)
5006
            ret = qemuDomainDetachDiskDevice(driver, vm, dev);
5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022
        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,
5023
                                     virDomainDeviceDefPtr dev)
5024 5025 5026 5027 5028 5029
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
5030
        ret = qemuDomainDetachPciControllerDevice(driver, vm, dev);
5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042
        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,
5043
                           virDomainPtr dom)
5044 5045 5046 5047 5048 5049
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
5050
        ret = qemuDomainDetachDeviceDiskLive(driver, vm, dev);
5051 5052
        break;
    case VIR_DOMAIN_DEVICE_CONTROLLER:
5053
        ret = qemuDomainDetachDeviceControllerLive(driver, vm, dev);
5054
        break;
5055 5056 5057
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainDetachLease(driver, vm, dev->data.lease);
        break;
5058
    case VIR_DOMAIN_DEVICE_NET:
5059
        ret = qemuDomainDetachNetDevice(driver, vm, dev);
5060 5061
        break;
    case VIR_DOMAIN_DEVICE_HOSTDEV:
5062
        ret = qemuDomainDetachHostDevice(driver, vm, dev);
5063 5064 5065 5066 5067 5068 5069 5070 5071 5072
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        "%s", _("This type of device cannot be hot unplugged"));
        break;
    }

    return ret;
}

5073 5074 5075 5076 5077 5078 5079 5080
static int
qemuDomainChangeDiskMediaLive(virDomainObjPtr vm,
                              virDomainDeviceDefPtr dev,
                              struct qemud_driver *driver,
                              bool force)
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
5081
    int ret = -1;
5082 5083 5084

    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup,
5085
                               vm->def->name, &cgroup, 0) != 0) {
5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097
            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:
5098
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, force);
5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130
        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:
5131
        ret = qemuDomainChangeDiskMediaLive(vm, dev, driver, force);
5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145
        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;
}

5146
static int
5147
qemuDomainAttachDeviceConfig(virDomainDefPtr vmdef,
5148 5149
                             virDomainDeviceDefPtr dev)
{
5150
    virDomainDiskDefPtr disk;
5151
    virDomainNetDefPtr net;
5152
    virDomainLeaseDefPtr lease;
5153

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

5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191
    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;
5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207

    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;

5208 5209 5210 5211 5212 5213 5214 5215 5216 5217
    default:
         qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                         _("persistent attach of device is not supported"));
         return -1;
    }
    return 0;
}


static int
5218
qemuDomainDetachDeviceConfig(virDomainDefPtr vmdef,
5219 5220
                             virDomainDeviceDefPtr dev)
{
5221
    virDomainDiskDefPtr disk;
5222
    virDomainNetDefPtr net;
5223
    virDomainLeaseDefPtr lease;
5224

5225
    switch (dev->type) {
5226 5227 5228 5229 5230 5231 5232 5233
    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;
5234

5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245
    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;
5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256

    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;

5257 5258 5259 5260 5261 5262 5263 5264 5265
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("persistent detach of device is not supported"));
        return -1;
    }
    return 0;
}

static int
5266
qemuDomainUpdateDeviceConfig(virDomainDefPtr vmdef,
5267 5268
                             virDomainDeviceDefPtr dev)
{
5269 5270 5271
    virDomainDiskDefPtr orig, disk;
    int pos;

5272
    switch (dev->type) {
5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307
    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;
5308 5309 5310 5311 5312 5313 5314 5315
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                         _("persistent update of device is not supported"));
        return -1;
    }
    return 0;
}

5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326
/* 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)
5327
{
5328
    struct qemud_driver *driver = dom->conn->privateData;
5329
    virDomainObjPtr vm = NULL;
5330
    virDomainDefPtr vmdef = NULL;
5331
    virDomainDeviceDefPtr dev = NULL;
5332
    bool force = (flags & VIR_DOMAIN_DEVICE_MODIFY_FORCE) != 0;
5333
    int ret = -1;
5334
    unsigned int affect;
5335

5336 5337
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
5338 5339 5340
                  (action == QEMU_DEVICE_UPDATE ?
                   VIR_DOMAIN_DEVICE_MODIFY_FORCE : 0), -1);

5341 5342
    affect = flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG);

5343 5344 5345 5346 5347 5348 5349
    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);
5350 5351 5352
        goto cleanup;
    }

5353
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
5354
        goto cleanup;
5355

5356
    if (virDomainObjIsActive(vm)) {
5357
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
5358
            flags |= VIR_DOMAIN_AFFECT_LIVE;
5359
    } else {
5360
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
5361
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
5362
        /* check consistency between flags and the vm state */
5363
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5364 5365 5366 5367 5368 5369
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s",
                            _("cannot do live update a device on "
                              "inactive domain"));
            goto endjob;
        }
5370
    }
5371

5372
    if ((flags & VIR_DOMAIN_AFFECT_CONFIG) && !vm->persistent) {
5373 5374 5375 5376
         qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("cannot modify device on transient domain"));
         goto endjob;
    }
5377

5378
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5379 5380 5381 5382 5383
        dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                      VIR_DOMAIN_XML_INACTIVE);
        if (dev == NULL)
            goto endjob;

5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402
        /* 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;
        }
5403

5404 5405 5406 5407 5408
        if (ret == -1)
            goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5409 5410 5411 5412
        /* 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);
5413 5414
        if (dev == NULL) {
            ret = -1;
5415
            goto endjob;
5416
        }
5417

5418 5419
        switch (action) {
        case QEMU_DEVICE_ATTACH:
5420
            ret = qemuDomainAttachDeviceLive(vm, dev, dom);
5421 5422
            break;
        case QEMU_DEVICE_DETACH:
5423
            ret = qemuDomainDetachDeviceLive(vm, dev, dom);
5424 5425
            break;
        case QEMU_DEVICE_UPDATE:
5426
            ret = qemuDomainUpdateDeviceLive(vm, dev, dom, force);
5427 5428 5429 5430
            break;
        default:
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("unknown domain modify action %d"), action);
5431
            ret = -1;
5432 5433
            break;
        }
5434 5435 5436

        if (ret == -1)
            goto endjob;
5437 5438
        /*
         * update domain status forcibly because the domain status may be
5439 5440
         * changed even if we failed to attach the device. For example,
         * a new controller may be created.
5441
         */
5442
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
5443
            ret = -1;
5444 5445
            goto endjob;
        }
5446
    }
5447

5448
    /* Finally, if no error until here, we can save config. */
5449
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5450 5451 5452 5453 5454 5455
        ret = virDomainSaveConfig(driver->configDir, vmdef);
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false);
            vmdef = NULL;
        }
    }
5456 5457

endjob:
5458
    if (qemuDomainObjEndJob(driver, vm) == 0)
5459 5460 5461
        vm = NULL;

cleanup:
5462
    virDomainDefFree(vmdef);
5463 5464 5465 5466
    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
5467 5468 5469
    return ret;
}

5470 5471 5472 5473 5474 5475
static int qemuDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_ATTACH);
}

5476 5477 5478
static int qemuDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainAttachDeviceFlags(dom, xml,
5479
                                       VIR_DOMAIN_AFFECT_LIVE);
5480
}
5481

5482

5483 5484 5485 5486
static int qemuDomainUpdateDeviceFlags(virDomainPtr dom,
                                       const char *xml,
                                       unsigned int flags)
{
5487
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_UPDATE);
5488 5489
}

5490 5491 5492
static int qemuDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
5493
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_DETACH);
5494 5495
}

5496 5497 5498
static int qemuDomainDetachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainDetachDeviceFlags(dom, xml,
5499
                                       VIR_DOMAIN_AFFECT_LIVE);
5500 5501
}

5502
static int qemudDomainGetAutostart(virDomainPtr dom,
5503
                                   int *autostart) {
5504 5505 5506
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
5507

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

5512
    if (!vm) {
5513 5514
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5515 5516
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5517
        goto cleanup;
5518 5519 5520
    }

    *autostart = vm->autostart;
5521
    ret = 0;
5522

5523
cleanup:
5524 5525
    if (vm)
        virDomainObjUnlock(vm);
5526
    return ret;
5527 5528
}

5529
static int qemudDomainSetAutostart(virDomainPtr dom,
5530
                                   int autostart) {
5531 5532
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
5533 5534
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
5535

5536
    qemuDriverLock(driver);
5537
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5538

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

5547
    if (!vm->persistent) {
5548
        qemuReportError(VIR_ERR_OPERATION_INVALID,
5549
                        "%s", _("cannot set autostart for transient domain"));
5550
        goto cleanup;
5551 5552
    }

5553 5554
    autostart = (autostart != 0);

5555
    if (vm->autostart != autostart) {
5556
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
5557
            goto cleanup;
5558
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
5559
            goto cleanup;
5560

5561
        if (autostart) {
5562 5563
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
5564 5565
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
5566 5567
                goto cleanup;
            }
5568

5569
            if (symlink(configFile, autostartLink) < 0) {
5570
                virReportSystemError(errno,
5571 5572
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
5573 5574 5575 5576
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
5577
                virReportSystemError(errno,
5578 5579
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
5580 5581
                goto cleanup;
            }
5582 5583
        }

5584
        vm->autostart = autostart;
5585
    }
5586
    ret = 0;
5587

5588 5589 5590
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
5591 5592
    if (vm)
        virDomainObjUnlock(vm);
5593
    qemuDriverUnlock(driver);
5594
    return ret;
5595 5596
}

5597

5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630
/*
 * check whether the host supports CFS bandwidth
 *
 * Return 1 when CFS bandwidth is supported, 0 when CFS bandwidth is not
 * supported, -1 on error.
 */
static int qemuGetCpuBWStatus(virCgroupPtr cgroup)
{
    char *cfs_period_path = NULL;
    int ret = -1;

    if (!cgroup)
        return 0;

    if (virCgroupPathOfController(cgroup, VIR_CGROUP_CONTROLLER_CPU,
                                  "cpu.cfs_period_us", &cfs_period_path) < 0) {
        VIR_INFO("cannot get the path of cgroup CPU controller");
        ret = 0;
        goto cleanup;
    }

    if (access(cfs_period_path, F_OK) < 0) {
        ret = 0;
    } else {
        ret = 1;
    }

cleanup:
    VIR_FREE(cfs_period_path);
    return ret;
}


5631 5632 5633 5634
static char *qemuGetSchedulerType(virDomainPtr dom,
                                  int *nparams)
{
    struct qemud_driver *driver = dom->conn->privateData;
5635
    char *ret = NULL;
5636
    int rc;
5637

5638
    qemuDriverLock(driver);
5639
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
5640 5641
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup CPU controller is not mounted"));
5642
        goto cleanup;
5643 5644
    }

5645 5646 5647 5648 5649 5650 5651 5652 5653
    if (nparams) {
        rc = qemuGetCpuBWStatus(driver->cgroup);
        if (rc < 0)
            goto cleanup;
        else if (rc == 0)
            *nparams = 1;
        else
            *nparams = 3;
    }
5654 5655 5656

    ret = strdup("posix");
    if (!ret)
5657
        virReportOOMError();
5658 5659 5660

cleanup:
    qemuDriverUnlock(driver);
5661 5662 5663
    return ret;
}

5664
static int qemuDomainSetBlkioParameters(virDomainPtr dom,
5665
                                         virTypedParameterPtr params,
5666 5667 5668 5669 5670 5671 5672
                                         int nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5673
    virDomainDefPtr persistentDef = NULL;
5674
    int ret = -1;
5675
    bool isActive;
5676

5677 5678
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5679 5680 5681 5682 5683 5684 5685 5686 5687 5688
    qemuDriverLock(driver);

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

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

5689 5690 5691 5692 5693 5694 5695
    isActive = virDomainObjIsActive(vm);

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

5698 5699 5700 5701 5702 5703 5704 5705
    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)) {
5706
            qemuReportError(VIR_ERR_OPERATION_INVALID, _("blkio cgroup isn't mounted"));
5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724
            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;
5725 5726 5727
    }

    ret = 0;
5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746
    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;
                }
5747

5748 5749 5750 5751 5752 5753 5754 5755 5756
                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);
5757 5758
                ret = -1;
            }
5759 5760
        }
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
5761 5762 5763
        /* Clang can't see that if we get here, persistentDef was set.  */
        sa_assert(persistentDef);

5764 5765 5766 5767 5768 5769 5770 5771 5772 5773
        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;
                }
5774

5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785
                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);
5786 5787 5788
                ret = -1;
            }
        }
A
Alex Jia 已提交
5789 5790 5791

        if (virDomainSaveConfig(driver->configDir, persistentDef) < 0)
            ret = -1;
5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802
    }

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

static int qemuDomainGetBlkioParameters(virDomainPtr dom,
5803
                                         virTypedParameterPtr params,
5804 5805 5806 5807 5808 5809 5810
                                         int *nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5811
    virDomainDefPtr persistentDef = NULL;
5812 5813 5814
    unsigned int val;
    int ret = -1;
    int rc;
5815
    bool isActive;
5816

5817 5818
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841
    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;
    }

5842 5843 5844 5845 5846 5847 5848
    isActive = virDomainObjIsActive(vm);

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

5851 5852 5853 5854 5855 5856
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }
5857

5858
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
5859
            qemuReportError(VIR_ERR_OPERATION_INVALID, _("blkio cgroup isn't mounted"));
5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905
            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 */
5906
            }
5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923
        }
    } 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;
5924

5925 5926 5927 5928
            default:
                break;
                /* should not hit here */
            }
5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941
        }
    }

    ret = 0;

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

static int qemuDomainSetMemoryParameters(virDomainPtr dom,
5944
                                         virTypedParameterPtr params,
5945
                                         int nparams,
5946
                                         unsigned int flags)
5947 5948 5949
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
5950
    virDomainDefPtr persistentDef = NULL;
5951 5952 5953
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;
5954 5955
    bool isActive;

5956 5957
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968

    qemuDriverLock(driver);

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

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

5969 5970
    isActive = virDomainObjIsActive(vm);

5971
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
5972
        if (isActive)
5973
            flags = VIR_DOMAIN_AFFECT_LIVE;
5974
        else
5975
            flags = VIR_DOMAIN_AFFECT_CONFIG;
5976 5977
    }

5978
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997
        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;
        }
    }

5998
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5999 6000 6001 6002 6003 6004 6005
        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;
6006 6007 6008 6009
    }

    ret = 0;
    for (i = 0; i < nparams; i++) {
6010
        virTypedParameterPtr param = &params[i];
6011 6012 6013

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

6021
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6022 6023 6024 6025 6026 6027 6028 6029
                rc = virCgroupSetMemoryHardLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory hard_limit tunable"));
                    ret = -1;
                }
            }

6030
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6031
                persistentDef->mem.hard_limit = params[i].value.ul;
6032 6033 6034
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT)) {
            int rc;
6035
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
6036 6037 6038 6039 6040 6041
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for memory soft_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

6042
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6043 6044 6045 6046 6047 6048 6049 6050
                rc = virCgroupSetMemorySoftLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory soft_limit tunable"));
                    ret = -1;
                }
            }

6051
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6052
                persistentDef->mem.soft_limit = params[i].value.ul;
6053
            }
6054
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT)) {
6055
            int rc;
6056
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
6057 6058 6059 6060 6061 6062
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for swap_hard_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

6063
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6064 6065 6066 6067 6068 6069 6070
                rc = virCgroupSetMemSwapHardLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set swap_hard_limit tunable"));
                    ret = -1;
                }
            }
6071
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6072
                persistentDef->mem.swap_hard_limit = params[i].value.ul;
6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084
            }
        } 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;
        }
    }

6085
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6086 6087
        if (virDomainSaveConfig(driver->configDir, persistentDef) < 0)
            ret = -1;
6088 6089
    }

6090 6091 6092 6093 6094 6095 6096 6097
cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

6098
static int qemuDomainGetMemoryParameters(virDomainPtr dom,
6099
                                         virTypedParameterPtr params,
6100
                                         int *nparams,
6101
                                         unsigned int flags)
6102 6103 6104 6105 6106
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6107
    virDomainDefPtr persistentDef = NULL;
6108
    unsigned long long val;
6109 6110
    int ret = -1;
    int rc;
6111
    bool isActive;
6112

6113 6114
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6115

6116
    qemuDriverLock(driver);
6117 6118 6119 6120 6121 6122 6123 6124 6125

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

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

6126 6127
    isActive = virDomainObjIsActive(vm);

6128
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
6129
        if (isActive)
6130
            flags = VIR_DOMAIN_AFFECT_LIVE;
6131
        else
6132
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6133 6134
    }

6135
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154
        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;
        }
    }

6155
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6156 6157 6158 6159 6160 6161 6162
        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;
6163 6164
    }

6165 6166 6167 6168 6169 6170 6171
    if ((*nparams) == 0) {
        /* Current number of memory parameters supported by cgroups */
        *nparams = QEMU_NB_MEM_PARAM;
        ret = 0;
        goto cleanup;
    }

6172
    if ((*nparams) < QEMU_NB_MEM_PARAM) {
6173 6174 6175 6176 6177
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
        goto cleanup;
    }

6178
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6179 6180 6181 6182
        for (i = 0; i < *nparams; i++) {
            virMemoryParameterPtr param = &params[i];
            val = 0;
            param->value.ul = 0;
6183
            param->type = VIR_TYPED_PARAM_ULLONG;
6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218

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

6221
    for (i = 0; i < QEMU_NB_MEM_PARAM; i++) {
6222
        virTypedParameterPtr param = &params[i];
6223 6224
        val = 0;
        param->value.ul = 0;
6225
        param->type = VIR_TYPED_PARAM_ULLONG;
6226

6227 6228 6229
        /* Coverity does not realize that if we get here, group is set.  */
        sa_assert(group);

6230
        switch (i) {
6231 6232 6233 6234 6235
        case 0: /* fill memory hard limit here */
            rc = virCgroupGetMemoryHardLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory hard limit"));
6236
                goto cleanup;
6237 6238 6239 6240
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field memory hard limit too long for destination"));
6241
                goto cleanup;
6242 6243 6244 6245 6246 6247 6248 6249 6250
            }
            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"));
6251
                goto cleanup;
6252 6253 6254 6255
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field memory soft limit too long for destination"));
6256
                goto cleanup;
6257 6258 6259 6260 6261
            }
            param->value.ul = val;
            break;

        case 2: /* fill swap hard limit here */
6262
            rc = virCgroupGetMemSwapHardLimit(group, &val);
6263 6264 6265
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get swap hard limit"));
6266
                goto cleanup;
6267
            }
6268
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT) == NULL) {
6269 6270
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field swap hard limit too long for destination"));
6271
                goto cleanup;
6272 6273 6274 6275 6276 6277 6278 6279 6280 6281
            }
            param->value.ul = val;
            break;

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

6282
out:
6283
    *nparams = QEMU_NB_MEM_PARAM;
6284 6285
    ret = 0;

6286 6287 6288 6289 6290 6291 6292 6293 6294
cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

6295 6296 6297 6298 6299 6300 6301 6302
static int
qemuSetVcpusBWLive(virDomainObjPtr vm, virCgroupPtr cgroup,
                   unsigned long long period, long long quota)
{
    int i;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virCgroupPtr cgroup_vcpu = NULL;
    int rc;
W
Wen Congyang 已提交
6303 6304 6305
    long long vm_quota = 0;
    long long old_quota = 0;
    unsigned long long old_period = 0;
6306 6307 6308 6309

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

W
Wen Congyang 已提交
6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328
    /* Ensure that we can multiply by vcpus without overflowing. */
    if (quota > LLONG_MAX / vm->def->vcpus) {
        virReportSystemError(EINVAL,
                             _("%s"),
                             "Unable to set cpu bandwidth quota");
        goto cleanup;
    }

    if (quota > 0)
        vm_quota = quota * vm->def->vcpus;
    else
        vm_quota = quota;

    rc = virCgroupGetCpuCfsQuota(cgroup, &old_quota);
    if (rc < 0) {
        virReportSystemError(-rc, "%s",
                             _("unable to get cpu bandwidth tunable"));
        goto cleanup;
    }
6329

W
Wen Congyang 已提交
6330 6331 6332 6333 6334
    rc = virCgroupGetCpuCfsPeriod(cgroup, &old_period);
    if (rc < 0) {
        virReportSystemError(-rc, "%s",
                             _("unable to get cpu bandwidth period tunable"));
        goto cleanup;
6335 6336
    }

W
Wen Congyang 已提交
6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357
    /*
     * If quota will be changed to a small value, we should modify vcpu's quota
     * first. Otherwise, we should modify vm's quota first.
     *
     * If period will be changed to a small value, we should modify vm's period
     * first. Otherwise, we should modify vcpu's period first.
     *
     * If both quota and period will be changed to a big/small value, we cannot
     * modify period and quota together.
     */
    if ((quota != 0) && (period != 0)) {
        if (((quota > old_quota) && (period > old_period)) ||
            ((quota < old_quota) && (period < old_period))) {
            /* modify period */
            if (qemuSetVcpusBWLive(vm, cgroup, period, 0) < 0)
                goto cleanup;

            /* modify quota */
            if (qemuSetVcpusBWLive(vm, cgroup, 0, quota) < 0)
                goto cleanup;
            return 0;
6358
        }
W
Wen Congyang 已提交
6359
    }
6360

W
Wen Congyang 已提交
6361 6362 6363 6364
    if (((vm_quota != 0) && (vm_quota > old_quota)) ||
        ((period != 0) && (period < old_period)))
        /* Set cpu bandwidth for the vm */
        if (qemuSetupCgroupVcpuBW(cgroup, period, vm_quota) < 0)
6365 6366
            goto cleanup;

W
Wen Congyang 已提交
6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386
    /* If we does not know VCPU<->PID mapping or all vcpu runs in the same
     * thread, we cannot control each vcpu. So we only modify cpu bandwidth
     * when each vcpu has a separated thread.
     */
    if (priv->nvcpupids != 0 && priv->vcpupids[0] != vm->pid) {
        for (i = 0; i < priv->nvcpupids; i++) {
            rc = virCgroupForVcpu(cgroup, i, &cgroup_vcpu, 0);
            if (rc < 0) {
                virReportSystemError(-rc,
                                     _("Unable to find vcpu cgroup for %s(vcpu:"
                                       " %d)"),
                                     vm->def->name, i);
                goto cleanup;
            }

            if (qemuSetupCgroupVcpuBW(cgroup_vcpu, period, quota) < 0)
                goto cleanup;

            virCgroupFree(&cgroup_vcpu);
        }
6387 6388
    }

W
Wen Congyang 已提交
6389 6390 6391 6392 6393 6394
    if (((vm_quota != 0) && (vm_quota <= old_quota)) ||
        ((period != 0) && (period >= old_period)))
        /* Set cpu bandwidth for the vm */
        if (qemuSetupCgroupVcpuBW(cgroup, period, vm_quota) < 0)
            goto cleanup;

6395 6396 6397 6398 6399 6400 6401
    return 0;

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

6402
static int qemuSetSchedulerParametersFlags(virDomainPtr dom,
6403
                                           virTypedParameterPtr params,
6404 6405
                                           int nparams,
                                           unsigned int flags)
6406 6407 6408 6409 6410
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6411
    virDomainDefPtr vmdef = NULL;
6412
    int ret = -1;
6413
    bool isActive;
6414
    int rc;
6415

6416 6417
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6418

6419
    qemuDriverLock(driver);
6420 6421 6422 6423

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

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

6429 6430
    isActive = virDomainObjIsActive(vm);

6431
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
6432
        if (isActive)
6433
            flags = VIR_DOMAIN_AFFECT_LIVE;
6434
        else
6435
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6436 6437
    }

6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot change persistent config of a transient domain"));
            goto cleanup;
        }

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

6451
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470
        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;
        }
    }

6471
    for (i = 0; i < nparams; i++) {
6472
        virTypedParameterPtr param = &params[i];
6473 6474

        if (STREQ(param->field, "cpu_shares")) {
6475
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
6476 6477
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for cpu_shares tunable, expected a 'ullong'"));
6478 6479 6480
                goto cleanup;
            }

6481
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6482 6483 6484 6485 6486 6487 6488 6489
                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;
6490
            }
6491

6492
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6493 6494
                vmdef->cputune.shares = params[i].value.ul;
            }
W
Wen Congyang 已提交
6495
        } else if (STREQ(param->field, "vcpu_period")) {
6496 6497
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
W
Wen Congyang 已提交
6498
                                _("invalid type for vcpu_period tunable,"
6499 6500 6501 6502 6503 6504 6505
                                  " expected a 'ullong'"));
                goto cleanup;
            }

            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
                rc = qemuSetVcpusBWLive(vm, group, params[i].value.ul, 0);
                if (rc != 0)
6506
                    goto cleanup;
6507 6508 6509 6510 6511 6512 6513 6514

                if (params[i].value.ul)
                    vm->def->cputune.period = params[i].value.ul;
            }

            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
                vmdef->cputune.period = params[i].value.ul;
            }
W
Wen Congyang 已提交
6515
        } else if (STREQ(param->field, "vcpu_quota")) {
6516 6517
            if (param->type != VIR_TYPED_PARAM_LLONG) {
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
W
Wen Congyang 已提交
6518
                                _("invalid type for vcpu_quota tunable,"
6519 6520 6521 6522 6523 6524 6525
                                  " expected a 'llong'"));
                goto cleanup;
            }

            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
                rc = qemuSetVcpusBWLive(vm, group, 0, params[i].value.l);
                if (rc != 0)
6526
                    goto cleanup;
6527 6528 6529 6530 6531 6532 6533

                if (params[i].value.l)
                    vm->def->cputune.quota = params[i].value.l;
            }

            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
                vmdef->cputune.quota = params[i].value.l;
6534
            }
6535
        } else {
6536 6537
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Invalid parameter `%s'"), param->field);
6538 6539 6540
            goto cleanup;
        }
    }
6541

6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
        goto cleanup;


    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        rc = virDomainSaveConfig(driver->configDir, vmdef);
        if (rc < 0)
            goto cleanup;

        virDomainObjAssignDef(vm, vmdef, false);
        vmdef = NULL;
    }

6555 6556 6557
    ret = 0;

cleanup:
6558
    virDomainDefFree(vmdef);
6559 6560 6561
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
6562
    qemuDriverUnlock(driver);
6563 6564 6565
    return ret;
}

6566
static int qemuSetSchedulerParameters(virDomainPtr dom,
6567
                                      virTypedParameterPtr params,
6568 6569 6570 6571 6572
                                      int nparams)
{
    return qemuSetSchedulerParametersFlags(dom,
                                           params,
                                           nparams,
6573
                                           VIR_DOMAIN_AFFECT_LIVE);
6574 6575
}

6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640
static int
qemuGetVcpuBWLive(virCgroupPtr cgroup, unsigned long long *period,
                  long long *quota)
{
    int rc;

    rc = virCgroupGetCpuCfsPeriod(cgroup, period);
    if (rc < 0) {
        virReportSystemError(-rc, "%s",
                             _("unable to get cpu bandwidth period tunable"));
        return -1;
    }

    rc = virCgroupGetCpuCfsQuota(cgroup, quota);
    if (rc < 0) {
        virReportSystemError(-rc, "%s",
                             _("unable to get cpu bandwidth tunable"));
        return -1;
    }

    return 0;
}

static int
qemuGetVcpusBWLive(virDomainObjPtr vm, virCgroupPtr cgroup,
                   unsigned long long *period, long long *quota)
{
    virCgroupPtr cgroup_vcpu = NULL;
    qemuDomainObjPrivatePtr priv = NULL;
    int rc;
    int ret = -1;

    priv = vm->privateData;
    if (priv->nvcpupids == 0 || priv->vcpupids[0] == vm->pid) {
        /* We do not create sub dir for each vcpu */
        rc = qemuGetVcpuBWLive(cgroup, period, quota);
        if (rc < 0)
            goto cleanup;

        if (*quota > 0)
            *quota /= vm->def->vcpus;
        goto out;
    }

    /* get period and quota for vcpu0 */
    rc = virCgroupForVcpu(cgroup, 0, &cgroup_vcpu, 0);
    if (!cgroup_vcpu) {
        virReportSystemError(-rc,
                             _("Unable to find vcpu cgroup for %s(vcpu: 0)"),
                             vm->def->name);
        goto cleanup;
    }

    rc = qemuGetVcpuBWLive(cgroup_vcpu, period, quota);
    if (rc < 0)
        goto cleanup;

out:
    ret = 0;

cleanup:
    virCgroupFree(&cgroup_vcpu);
    return ret;
}

6641 6642 6643 6644 6645
static int
qemuGetSchedulerParametersFlags(virDomainPtr dom,
                                virTypedParameterPtr params,
                                int *nparams,
                                unsigned int flags)
6646 6647 6648 6649
{
    struct qemud_driver *driver = dom->conn->privateData;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
6650 6651 6652
    unsigned long long shares;
    unsigned long long period;
    long long quota;
6653 6654
    int ret = -1;
    int rc;
6655
    bool isActive;
6656
    bool cpu_bw_status = false;
6657
    int saved_nparams = 0;
6658

6659 6660
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6661

6662 6663
    qemuDriverLock(driver);

6664 6665
    if ((flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)) ==
        (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)) {
6666 6667
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("cannot query live and config together"));
6668
        goto cleanup;
6669 6670
    }

6671
    if (*nparams < 1) {
6672 6673
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
6674
        goto cleanup;
6675 6676
    }

6677 6678 6679 6680 6681 6682 6683
    if (*nparams > 1) {
        rc = qemuGetCpuBWStatus(driver->cgroup);
        if (rc < 0)
            goto cleanup;
        cpu_bw_status = !!rc;
    }

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

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

6692 6693
    isActive = virDomainObjIsActive(vm);

6694
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
6695
        if (isActive)
6696
            flags = VIR_DOMAIN_AFFECT_LIVE;
6697
        else
6698
            flags = VIR_DOMAIN_AFFECT_CONFIG;
6699 6700
    }

6701
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716
        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;
            }
6717 6718 6719 6720 6721
            shares = persistentDef->cputune.shares;
            if (*nparams > 1 && cpu_bw_status) {
                period = persistentDef->cputune.period;
                quota = persistentDef->cputune.quota;
            }
6722
        } else {
6723 6724 6725 6726 6727
            shares = vm->def->cputune.shares;
            if (*nparams > 1 && cpu_bw_status) {
                period = vm->def->cputune.period;
                quota = vm->def->cputune.quota;
            }
6728
        }
6729
        goto out;
6730 6731
    }

6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743
    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;
    }

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

6750
    rc = virCgroupGetCpuShares(group, &shares);
6751
    if (rc != 0) {
6752
        virReportSystemError(-rc, "%s",
6753 6754 6755
                             _("unable to get cpu shares tunable"));
        goto cleanup;
    }
6756 6757 6758 6759 6760 6761

    if (*nparams > 1 && cpu_bw_status) {
        rc = qemuGetVcpusBWLive(vm, group, &period, &quota);
        if (rc != 0)
            goto cleanup;
    }
6762
out:
6763
    params[0].value.ul = shares;
6764
    params[0].type = VIR_TYPED_PARAM_ULLONG;
C
Chris Lalancette 已提交
6765
    if (virStrcpyStatic(params[0].field, "cpu_shares") == NULL) {
6766 6767
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Field cpu_shares too long for destination"));
C
Chris Lalancette 已提交
6768 6769
        goto cleanup;
    }
6770

6771 6772 6773 6774 6775 6776
    saved_nparams++;

    if (cpu_bw_status) {
        if (*nparams > saved_nparams) {
            params[1].value.ul = period;
            params[1].type = VIR_TYPED_PARAM_ULLONG;
W
Wen Congyang 已提交
6777
            if (virStrcpyStatic(params[1].field, "vcpu_period") == NULL) {
6778 6779
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s",
W
Wen Congyang 已提交
6780
                                _("Field vcpu_period too long for destination"));
6781 6782 6783 6784 6785 6786 6787 6788
                goto cleanup;
            }
            saved_nparams++;
        }

        if (*nparams > saved_nparams) {
            params[2].value.ul = quota;
            params[2].type = VIR_TYPED_PARAM_LLONG;
W
Wen Congyang 已提交
6789
            if (virStrcpyStatic(params[2].field, "vcpu_quota") == NULL) {
6790 6791
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s",
W
Wen Congyang 已提交
6792
                                _("Field vcpu_quota too long for destination"));
6793 6794 6795 6796 6797 6798 6799 6800
                goto cleanup;
            }
            saved_nparams++;
        }
    }

    *nparams = saved_nparams;

6801 6802 6803 6804 6805 6806
    ret = 0;

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

6811 6812 6813 6814 6815 6816
static int
qemuGetSchedulerParameters(virDomainPtr dom,
                           virTypedParameterPtr params,
                           int *nparams)
{
    return qemuGetSchedulerParametersFlags(dom, params, nparams,
6817
                                           VIR_DOMAIN_AFFECT_CURRENT);
6818
}
6819

6820 6821 6822 6823 6824 6825 6826 6827 6828
/* 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)
{
6829
    struct qemud_driver *driver = dom->conn->privateData;
6830
    int i, ret = -1;
6831
    virDomainObjPtr vm;
6832
    virDomainDiskDefPtr disk = NULL;
6833
    qemuDomainObjPrivatePtr priv;
6834

6835
    qemuDriverLock(driver);
6836
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6837
    qemuDriverUnlock(driver);
6838
    if (!vm) {
6839 6840
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
6841 6842
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
6843
        goto cleanup;
6844
    }
6845

6846 6847 6848 6849 6850 6851
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

6852 6853 6854 6855 6856 6857 6858 6859
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

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

6865
    if (!disk->info.alias) {
6866 6867
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("missing disk device alias name for %s"), disk->dst);
6868
        goto cleanup;
6869
    }
6870

6871
    priv = vm->privateData;
6872 6873
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
        goto cleanup;
6874

6875 6876 6877 6878 6879
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }
6880

6881
    qemuDomainObjEnterMonitor(driver, vm);
6882 6883 6884 6885 6886 6887 6888 6889
    ret = qemuMonitorGetBlockStatsInfo(priv->mon,
                                       disk->info.alias,
                                       &stats->rd_req,
                                       &stats->rd_bytes,
                                       &stats->wr_req,
                                       &stats->wr_bytes,
                                       &stats->errs);
    qemuDomainObjExitMonitor(driver, vm);
6890

6891
endjob:
6892 6893
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
6894

6895
cleanup:
6896 6897
    if (vm)
        virDomainObjUnlock(vm);
6898
    return ret;
6899 6900
}

6901
#ifdef __linux__
6902 6903 6904 6905 6906
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
6907 6908
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
6909
    int i;
6910
    int ret = -1;
6911

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

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

D
Daniel P. Berrange 已提交
6924
    if (!virDomainObjIsActive(vm)) {
6925 6926
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
6927
        goto cleanup;
6928 6929 6930
    }

    /* Check the path is one of the domain's network interfaces. */
6931 6932
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
6933 6934 6935 6936
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
6937 6938
    }

6939
    if (ret == 0)
6940
        ret = linuxDomainInterfaceStats(path, stats);
6941
    else
6942 6943
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path, '%s' is not a known interface"), path);
6944

6945
cleanup:
6946 6947
    if (vm)
        virDomainObjUnlock(vm);
6948 6949
    return ret;
}
6950
#else
6951 6952 6953 6954
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
6955
{
6956 6957
    qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                    _("interface stats not implemented on this platform"));
6958 6959
    return -1;
}
6960
#endif
6961

6962 6963 6964
static int
qemudDomainMemoryStats (virDomainPtr dom,
                        struct _virDomainMemoryStat *stats,
6965 6966
                        unsigned int nr_stats,
                        unsigned int flags)
6967 6968 6969 6970 6971
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned int ret = -1;

6972 6973
    virCheckFlags(0, -1);

6974 6975 6976 6977 6978 6979 6980
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

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

6986
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
6987 6988
        goto cleanup;

6989 6990
    if (virDomainObjIsActive(vm)) {
        qemuDomainObjPrivatePtr priv = vm->privateData;
6991
        qemuDomainObjEnterMonitor(driver, vm);
6992
        ret = qemuMonitorGetMemoryStats(priv->mon, stats, nr_stats);
6993
        qemuDomainObjExitMonitor(driver, vm);
6994
    } else {
6995 6996
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
6997 6998
    }

6999
    if (qemuDomainObjEndJob(driver, vm) == 0)
7000 7001
        vm = NULL;

7002 7003 7004 7005 7006 7007
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

7008 7009 7010 7011 7012
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
E
Eric Blake 已提交
7013
                      unsigned int flags)
7014
{
7015 7016 7017
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
7018

E
Eric Blake 已提交
7019 7020
    virCheckFlags(0, -1);

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

7025
    if (!vm) {
7026 7027
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
7028 7029
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
7030
        goto cleanup;
7031 7032 7033
    }

    if (!path || path[0] == '\0') {
7034 7035
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("NULL or empty path"));
7036
        goto cleanup;
7037 7038 7039
    }

    /* Check the path belongs to this domain. */
7040 7041
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
7042 7043 7044 7045
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
7046 7047
    }

7048 7049 7050 7051 7052
    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) {
7053 7054
            virReportSystemError(errno,
                                 _("%s: failed to open"), path);
7055 7056
            goto cleanup;
        }
7057

7058 7059 7060 7061 7062 7063
        /* 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) {
7064 7065
            virReportSystemError(errno,
                                 _("%s: failed to seek or read"), path);
7066 7067 7068 7069 7070
            goto cleanup;
        }

        ret = 0;
    } else {
7071 7072
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("invalid path"));
7073 7074
    }

7075
cleanup:
7076
    VIR_FORCE_CLOSE(fd);
7077 7078
    if (vm)
        virDomainObjUnlock(vm);
7079 7080 7081
    return ret;
}

R
Richard W.M. Jones 已提交
7082 7083 7084 7085 7086 7087
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
7088 7089
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
7090
    char *tmp = NULL;
R
Richard W.M. Jones 已提交
7091
    int fd = -1, ret = -1;
7092
    qemuDomainObjPrivatePtr priv;
R
Richard W.M. Jones 已提交
7093

7094 7095
    virCheckFlags(VIR_MEMORY_VIRTUAL | VIR_MEMORY_PHYSICAL, -1);

7096
    qemuDriverLock(driver);
7097
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7098
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
7099 7100

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

7108
    if (flags != VIR_MEMORY_VIRTUAL && flags != VIR_MEMORY_PHYSICAL) {
7109 7110
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("flags parameter must be VIR_MEMORY_VIRTUAL or VIR_MEMORY_PHYSICAL"));
7111
        goto cleanup;
R
Richard W.M. Jones 已提交
7112 7113
    }

7114
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
7115 7116
        goto cleanup;

D
Daniel P. Berrange 已提交
7117
    if (!virDomainObjIsActive(vm)) {
7118 7119
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
7120
        goto endjob;
R
Richard W.M. Jones 已提交
7121 7122
    }

7123
    if (virAsprintf(&tmp, "%s/qemu.mem.XXXXXX", driver->cacheDir) < 0) {
7124
        virReportOOMError();
7125
        goto endjob;
7126 7127
    }

R
Richard W.M. Jones 已提交
7128 7129
    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
7130 7131
        virReportSystemError(errno,
                             _("mkstemp(\"%s\") failed"), tmp);
7132
        goto endjob;
R
Richard W.M. Jones 已提交
7133 7134
    }

7135 7136
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm, tmp);

7137
    priv = vm->privateData;
7138
    qemuDomainObjEnterMonitor(driver, vm);
7139
    if (flags == VIR_MEMORY_VIRTUAL) {
7140
        if (qemuMonitorSaveVirtualMemory(priv->mon, offset, size, tmp) < 0) {
7141
            qemuDomainObjExitMonitor(driver, vm);
7142
            goto endjob;
7143
        }
7144
    } else {
7145
        if (qemuMonitorSavePhysicalMemory(priv->mon, offset, size, tmp) < 0) {
7146
            qemuDomainObjExitMonitor(driver, vm);
7147
            goto endjob;
7148
        }
R
Richard W.M. Jones 已提交
7149
    }
7150
    qemuDomainObjExitMonitor(driver, vm);
R
Richard W.M. Jones 已提交
7151 7152 7153

    /* Read the memory file into buffer. */
    if (saferead (fd, buffer, size) == (ssize_t) -1) {
7154 7155 7156
        virReportSystemError(errno,
                             _("failed to read temporary file "
                               "created with template %s"), tmp);
7157
        goto endjob;
R
Richard W.M. Jones 已提交
7158 7159 7160
    }

    ret = 0;
7161

7162
endjob:
7163
    if (qemuDomainObjEndJob(driver, vm) == 0)
7164
        vm = NULL;
7165

7166
cleanup:
7167
    VIR_FORCE_CLOSE(fd);
7168 7169
    if (tmp)
        unlink(tmp);
W
Wen Congyang 已提交
7170
    VIR_FREE(tmp);
7171 7172
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
7173 7174 7175
    return ret;
}

7176

7177 7178 7179 7180 7181 7182 7183 7184 7185
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;
7186
    virStorageFileMetadata *meta = NULL;
7187
    virDomainDiskDefPtr disk = NULL;
7188 7189
    struct stat sb;
    int i;
7190
    int format;
7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214

    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)) {
7215
            disk = vm->def->disks[i];
7216 7217 7218 7219
            break;
        }
    }

7220
    if (!disk) {
7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234
        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 */
7235 7236 7237 7238 7239 7240 7241 7242
    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 {
7243 7244 7245 7246 7247 7248 7249
        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);
7250
            goto cleanup;
7251
        }
7252 7253
    }

7254 7255 7256 7257 7258
    if (VIR_ALLOC(meta) < 0) {
        virReportOOMError();
        goto cleanup;
    }

7259 7260
    if (virStorageFileGetMetadataFromFD(path, fd,
                                        format,
7261
                                        meta) < 0)
7262 7263 7264 7265 7266 7267 7268 7269 7270 7271
        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)) {
7272
#ifndef WIN32
7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297
        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 */
7298 7299
    if (meta->capacity)
        info->capacity = meta->capacity;
7300

7301
    /* Set default value .. */
7302 7303
    info->allocation = info->physical;

7304 7305 7306
    /* ..but if guest is running & not using raw
       disk format and on a block device, then query
       highest allocated extent from QEMU */
7307
    if (disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
7308
        format != VIR_STORAGE_FILE_RAW &&
7309 7310
        S_ISBLK(sb.st_mode) &&
        virDomainObjIsActive(vm)) {
7311
        qemuDomainObjPrivatePtr priv = vm->privateData;
7312

7313 7314
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
            goto cleanup;
7315

7316
        if (virDomainObjIsActive(vm)) {
7317
            qemuDomainObjEnterMonitor(driver, vm);
7318 7319 7320 7321
            ret = qemuMonitorGetBlockExtent(priv->mon,
                                            disk->info.alias,
                                            &info->allocation);
            qemuDomainObjExitMonitor(driver, vm);
7322
        } else {
7323
            ret = 0;
7324
        }
7325 7326 7327

        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
7328 7329 7330
    } else {
        ret = 0;
    }
7331 7332

cleanup:
7333
    virStorageFileFreeMetadata(meta);
7334
    VIR_FORCE_CLOSE(fd);
7335 7336 7337 7338 7339 7340
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


7341
static int
7342 7343 7344 7345
qemuDomainEventRegister(virConnectPtr conn,
                        virConnectDomainEventCallback callback,
                        void *opaque,
                        virFreeCallback freecb)
7346
{
7347 7348 7349
    struct qemud_driver *driver = conn->privateData;
    int ret;

7350
    qemuDriverLock(driver);
7351 7352
    ret = virDomainEventCallbackListAdd(conn,
                                        driver->domainEventState->callbacks,
7353
                                        callback, opaque, freecb);
7354
    qemuDriverUnlock(driver);
7355

7356
    return ret;
7357 7358
}

7359

7360
static int
7361 7362
qemuDomainEventDeregister(virConnectPtr conn,
                          virConnectDomainEventCallback callback)
7363
{
7364 7365 7366
    struct qemud_driver *driver = conn->privateData;
    int ret;

7367
    qemuDriverLock(driver);
7368 7369 7370
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
7371
    qemuDriverUnlock(driver);
7372

7373
    return ret;
7374 7375
}

7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389

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,
7390
                                          driver->domainEventState->callbacks,
7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406
                                          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);
7407 7408 7409
    ret = virDomainEventStateDeregisterAny(conn,
                                           driver->domainEventState,
                                           callbackID);
7410 7411 7412 7413 7414 7415
    qemuDriverUnlock(driver);

    return ret;
}


7416 7417 7418
/*******************************************************************
 * Migration Protocol Version 2
 *******************************************************************/
D
Daniel Veillard 已提交
7419

C
Chris Lalancette 已提交
7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434
/* 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;
7435

7436
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
7437

7438 7439
    qemuDriverLock(driver);

C
Chris Lalancette 已提交
7440
    if (!dom_xml) {
7441 7442
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
C
Chris Lalancette 已提交
7443 7444 7445
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
7446
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
7447 7448 7449 7450
                         "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
        goto cleanup;
    }
    if (st == NULL) {
7451 7452
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("tunnelled migration requested but NULL stream passed"));
C
Chris Lalancette 已提交
7453 7454 7455
        goto cleanup;
    }

7456 7457 7458 7459 7460 7461 7462
    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

7463 7464 7465
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     NULL, 0, NULL, NULL, /* No cookies in v2 */
                                     st, dname, dom_xml);
7466

C
Chris Lalancette 已提交
7467
cleanup:
7468
    qemuDriverUnlock(driver);
C
Chris Lalancette 已提交
7469 7470 7471
    return ret;
}

D
Daniel Veillard 已提交
7472 7473 7474 7475
/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
7476
static int ATTRIBUTE_NONNULL (5)
D
Daniel Veillard 已提交
7477
qemudDomainMigratePrepare2 (virConnectPtr dconn,
7478 7479
                            char **cookie ATTRIBUTE_UNUSED,
                            int *cookielen ATTRIBUTE_UNUSED,
D
Daniel Veillard 已提交
7480 7481
                            const char *uri_in,
                            char **uri_out,
C
Chris Lalancette 已提交
7482
                            unsigned long flags,
D
Daniel Veillard 已提交
7483 7484 7485 7486
                            const char *dname,
                            unsigned long resource ATTRIBUTE_UNUSED,
                            const char *dom_xml)
{
7487
    struct qemud_driver *driver = dconn->privateData;
7488
    int ret = -1;
7489

7490
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
7491

7492
    *uri_out = NULL;
D
Daniel Veillard 已提交
7493

7494
    qemuDriverLock(driver);
7495 7496 7497 7498 7499 7500 7501 7502

    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 已提交
7503 7504 7505 7506
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
7507 7508
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Tunnelled migration requested but invalid RPC method called"));
C
Chris Lalancette 已提交
7509 7510 7511
        goto cleanup;
    }

D
Daniel Veillard 已提交
7512
    if (!dom_xml) {
7513 7514
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
7515
        goto cleanup;
D
Daniel Veillard 已提交
7516 7517
    }

7518 7519 7520 7521
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
7522
    ret = qemuMigrationPrepareDirect(driver, dconn,
7523
                                     NULL, 0, NULL, NULL, /* No cookies */
7524 7525
                                     uri_in, uri_out,
                                     dname, dom_xml);
D
Daniel Veillard 已提交
7526

7527 7528 7529 7530
cleanup:
    qemuDriverUnlock(driver);
    return ret;
}
C
Chris Lalancette 已提交
7531

D
Daniel Veillard 已提交
7532

7533 7534 7535
/* Perform is the second step, and it runs on the source host. */
static int
qemudDomainMigratePerform (virDomainPtr dom,
7536 7537
                           const char *cookie,
                           int cookielen,
7538 7539 7540 7541 7542 7543 7544 7545
                           const char *uri,
                           unsigned long flags,
                           const char *dname,
                           unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
7546
    const char *dconnuri = NULL;
7547

7548
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
7549

7550
    qemuDriverLock(driver);
7551 7552 7553 7554 7555 7556 7557
    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

7558
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel Veillard 已提交
7559
    if (!vm) {
7560 7561
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
7562 7563
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
7564
        goto cleanup;
D
Daniel Veillard 已提交
7565 7566
    }

7567 7568 7569 7570 7571
    if (flags & VIR_MIGRATE_PEER2PEER) {
        dconnuri = uri;
        uri = NULL;
    }

7572 7573 7574 7575 7576 7577
    /* 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
     */
7578
    ret = qemuMigrationPerform(driver, dom->conn, vm,
7579
                               NULL, dconnuri, uri, cookie, cookielen,
7580
                               NULL, NULL, /* No output cookies in v2 */
7581
                               flags, dname, resource, false);
7582

7583
cleanup:
7584
    qemuDriverUnlock(driver);
7585
    return ret;
D
Daniel Veillard 已提交
7586 7587
}

7588

D
Daniel Veillard 已提交
7589 7590 7591 7592 7593 7594 7595
/* 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 已提交
7596
                           unsigned long flags,
D
Daniel Veillard 已提交
7597 7598
                           int retcode)
{
7599 7600 7601
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
D
Daniel Veillard 已提交
7602

7603
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
C
Chris Lalancette 已提交
7604

7605
    qemuDriverLock(driver);
7606
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
7607
    if (!vm) {
7608 7609
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
7610
        goto cleanup;
D
Daniel Veillard 已提交
7611 7612
    }

7613 7614 7615 7616
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
7617
    dom = qemuMigrationFinish(driver, dconn, vm,
7618
                              NULL, 0, NULL, NULL, /* No cookies */
7619
                              flags, retcode, false);
7620

7621
cleanup:
7622
    qemuDriverUnlock(driver);
7623
    return dom;
D
Daniel Veillard 已提交
7624 7625
}

7626

7627 7628 7629 7630 7631 7632
/*******************************************************************
 * Migration Protocol Version 3
 *******************************************************************/

static char *
qemuDomainMigrateBegin3(virDomainPtr domain,
7633
                        const char *xmlin,
7634 7635 7636 7637 7638 7639 7640 7641 7642 7643
                        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;

7644
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655

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

7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689
    if ((flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        if (qemuMigrationJobStart(driver, vm, QEMU_ASYNC_JOB_MIGRATION_OUT) < 0)
            goto cleanup;
    } else {
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
            goto cleanup;
    }

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

    if (!(xml = qemuMigrationBegin(driver, vm, xmlin,
                                   cookieout, cookieoutlen)))
        goto endjob;

    if ((flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        /* We keep the job active across API calls until the confirm() call.
         * This prevents any other APIs being invoked while migration is taking
         * place.
         */
        if (qemuMigrationJobContinue(vm) == 0) {
            vm = NULL;
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("domain disappeared"));
            VIR_FREE(xml);
            if (cookieout)
                VIR_FREE(*cookieout);
        }
    } else {
        goto endjob;
    }
7690 7691

cleanup:
7692 7693
    if (vm)
        virDomainObjUnlock(vm);
7694 7695
    qemuDriverUnlock(driver);
    return xml;
7696 7697 7698 7699 7700 7701 7702 7703 7704 7705

endjob:
    if ((flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        if (qemuMigrationJobFinish(driver, vm) == 0)
            vm = NULL;
    } else {
        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
    }
    goto cleanup;
7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723
}

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;

7724
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770

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

7771
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802

    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,
7803
                          const char *xmlin,
7804 7805 7806 7807
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
7808
                          const char *dconnuri,
7809 7810 7811 7812 7813 7814 7815 7816 7817
                          const char *uri,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

7818
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829

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

7830
    ret = qemuMigrationPerform(driver, dom->conn, vm, xmlin,
7831
                               dconnuri, uri, cookiein, cookieinlen,
7832
                               cookieout, cookieoutlen,
7833
                               flags, dname, resource, true);
7834 7835 7836 7837 7838 7839 7840

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}


7841
static virDomainPtr
7842 7843 7844 7845 7846 7847
qemuDomainMigrateFinish3(virConnectPtr dconn,
                         const char *dname,
                         const char *cookiein,
                         int cookieinlen,
                         char **cookieout,
                         int *cookieoutlen,
7848
                         const char *dconnuri ATTRIBUTE_UNUSED,
7849 7850
                         const char *uri ATTRIBUTE_UNUSED,
                         unsigned long flags,
7851
                         int cancelled)
7852 7853 7854
{
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
7855
    virDomainPtr dom = NULL;
7856

7857
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
7858 7859 7860 7861 7862 7863 7864 7865 7866

    qemuDriverLock(driver);
    vm = virDomainFindByName(&driver->domains, dname);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
        goto cleanup;
    }

7867 7868 7869 7870
    dom = qemuMigrationFinish(driver, dconn, vm,
                              cookiein, cookieinlen,
                              cookieout, cookieoutlen,
                              flags, cancelled, true);
7871 7872 7873

cleanup:
    qemuDriverUnlock(driver);
7874
    return dom;
7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886
}

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;
7887
    enum qemuMigrationJobPhase phase;
7888

7889
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900

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

7901
    if (!qemuMigrationJobIsActive(vm, QEMU_ASYNC_JOB_MIGRATION_OUT))
7902 7903
        goto cleanup;

7904 7905 7906 7907 7908 7909 7910
    if (cancelled)
        phase = QEMU_MIGRATION_PHASE_CONFIRM3_CANCELLED;
    else
        phase = QEMU_MIGRATION_PHASE_CONFIRM3;

    qemuMigrationJobStartPhase(driver, vm, phase);

7911 7912
    ret = qemuMigrationConfirm(driver, domain->conn, vm,
                               cookiein, cookieinlen,
7913 7914
                               flags, cancelled);

7915
    if (qemuMigrationJobFinish(driver, vm) == 0) {
7916 7917 7918 7919 7920 7921 7922 7923 7924
        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;
    }

7925
cleanup:
7926 7927
    if (vm)
        virDomainObjUnlock(vm);
7928 7929 7930 7931 7932
    qemuDriverUnlock(driver);
    return ret;
}


7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948
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;

7949
    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE);
7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966
    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) {
7967 7968
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("device %s is not a PCI device"), dev->name);
7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981
        goto out;
    }

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

static int
qemudNodeDeviceDettach (virNodeDevicePtr dev)
{
7982
    struct qemud_driver *driver = dev->conn->privateData;
7983 7984 7985 7986 7987 7988 7989
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

7990
    pci = pciGetDevice(domain, bus, slot, function);
7991 7992 7993
    if (!pci)
        return -1;

7994 7995
    qemuDriverLock(driver);
    if (pciDettachDevice(pci, driver->activePciHostdevs) < 0)
7996 7997 7998 7999
        goto out;

    ret = 0;
out:
8000
    qemuDriverUnlock(driver);
8001
    pciFreeDevice(pci);
8002 8003 8004 8005 8006 8007
    return ret;
}

static int
qemudNodeDeviceReAttach (virNodeDevicePtr dev)
{
8008
    struct qemud_driver *driver = dev->conn->privateData;
8009 8010 8011 8012 8013 8014 8015
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

8016
    pci = pciGetDevice(domain, bus, slot, function);
8017 8018 8019
    if (!pci)
        return -1;

8020 8021
    pciDeviceReAttachInit(pci);

8022 8023
    qemuDriverLock(driver);
    if (pciReAttachDevice(pci, driver->activePciHostdevs) < 0)
8024 8025 8026 8027
        goto out;

    ret = 0;
out:
8028
    qemuDriverUnlock(driver);
8029
    pciFreeDevice(pci);
8030 8031 8032 8033 8034 8035
    return ret;
}

static int
qemudNodeDeviceReset (virNodeDevicePtr dev)
{
8036
    struct qemud_driver *driver = dev->conn->privateData;
8037 8038 8039 8040 8041 8042 8043
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

8044
    pci = pciGetDevice(domain, bus, slot, function);
8045 8046 8047
    if (!pci)
        return -1;

8048 8049
    qemuDriverLock(driver);

8050
    if (pciResetDevice(pci, driver->activePciHostdevs, NULL) < 0)
8051 8052 8053 8054
        goto out;

    ret = 0;
out:
8055
    qemuDriverUnlock(driver);
8056
    pciFreeDevice(pci);
8057 8058 8059
    return ret;
}

8060 8061 8062
static int
qemuCPUCompare(virConnectPtr conn,
               const char *xmlDesc,
E
Eric Blake 已提交
8063
               unsigned int flags)
8064 8065 8066 8067
{
    struct qemud_driver *driver = conn->privateData;
    int ret = VIR_CPU_COMPARE_ERROR;

E
Eric Blake 已提交
8068 8069
    virCheckFlags(0, VIR_CPU_COMPARE_ERROR);

8070 8071 8072
    qemuDriverLock(driver);

    if (!driver->caps || !driver->caps->host.cpu) {
8073
        qemuReportError(VIR_ERR_OPERATION_INVALID,
8074
                        "%s", _("cannot get host CPU capabilities"));
E
Eric Blake 已提交
8075
    } else {
8076
        ret = cpuCompareXML(driver->caps->host.cpu, xmlDesc);
E
Eric Blake 已提交
8077
    }
8078 8079 8080 8081 8082 8083

    qemuDriverUnlock(driver);

    return ret;
}

8084

8085 8086 8087 8088
static char *
qemuCPUBaseline(virConnectPtr conn ATTRIBUTE_UNUSED,
                const char **xmlCPUs,
                unsigned int ncpus,
E
Eric Blake 已提交
8089
                unsigned int flags)
8090 8091 8092
{
    char *cpu;

E
Eric Blake 已提交
8093 8094
    virCheckFlags(0, NULL);

8095 8096 8097 8098 8099
    cpu = cpuBaselineXML(xmlCPUs, ncpus, NULL, 0);

    return cpu;
}

8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121

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)) {
8122
        if (priv->job.asyncJob) {
8123
            memcpy(info, &priv->job.info, sizeof(*info));
8124 8125 8126 8127 8128 8129

            /* 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 已提交
8130
            if (virTimeMs(&info->timeElapsed) < 0)
8131
                goto cleanup;
8132
            info->timeElapsed -= priv->job.start;
8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151
        } 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;
}


8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168
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;
    }

8169 8170
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_ABORT) < 0)
        goto cleanup;
8171

8172
    if (!virDomainObjIsActive(vm)) {
8173 8174
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
8175
        goto endjob;
8176 8177
    }

8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191
    priv = vm->privateData;

    if (!priv->job.asyncJob) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("no job is active on the domain"));
        goto endjob;
    } else if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_IN) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot abort incoming migration;"
                          " use virDomainDestroy instead"));
        goto endjob;
    }

    VIR_DEBUG("Cancelling job at client request");
8192
    qemuDomainObjEnterMonitor(driver, vm);
8193 8194 8195 8196 8197 8198
    ret = qemuMonitorMigrateCancel(priv->mon);
    qemuDomainObjExitMonitor(driver, vm);

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
8199 8200 8201 8202 8203 8204 8205 8206

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


8207 8208 8209 8210 8211 8212 8213 8214 8215 8216
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;

8217
    virCheckFlags(0, -1);
8218 8219 8220

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
8221
    qemuDriverUnlock(driver);
8222 8223 8224 8225 8226 8227

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

8231 8232 8233
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
        goto cleanup;

8234 8235 8236
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
8237
        goto endjob;
8238 8239 8240 8241
    }

    priv = vm->privateData;

8242
    if (priv->job.asyncJob != QEMU_ASYNC_JOB_MIGRATION_OUT) {
8243 8244
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not being migrated"));
8245
        goto endjob;
8246 8247
    }

8248
    VIR_DEBUG("Setting migration downtime to %llums", downtime);
8249
    qemuDomainObjEnterMonitor(driver, vm);
8250 8251 8252 8253 8254 8255
    ret = qemuMonitorSetMigrationDowntime(priv->mon, downtime);
    qemuDomainObjExitMonitor(driver, vm);

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
8256 8257 8258 8259 8260 8261 8262

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

8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276
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);
8277
    qemuDriverUnlock(driver);
8278 8279 8280 8281 8282 8283

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

8287 8288 8289
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
        goto cleanup;

8290 8291 8292
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
8293
        goto endjob;
8294 8295 8296 8297
    }

    priv = vm->privateData;

8298
    if (priv->job.asyncJob != QEMU_ASYNC_JOB_MIGRATION_OUT) {
8299 8300
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not being migrated"));
8301
        goto endjob;
8302 8303
    }

8304
    VIR_DEBUG("Setting migration bandwidth to %luMbs", bandwidth);
8305
    qemuDomainObjEnterMonitor(driver, vm);
8306 8307 8308 8309 8310 8311
    ret = qemuMonitorSetMigrationSpeed(priv->mon, bandwidth);
    qemuDomainObjExitMonitor(driver, vm);

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
8312 8313 8314 8315 8316 8317 8318

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

C
Chris Lalancette 已提交
8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332
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;
}

8333 8334 8335
static int qemuDomainSnapshotWriteMetadata(virDomainObjPtr vm,
                                           virDomainSnapshotObjPtr snapshot,
                                           char *snapshotDir)
C
Chris Lalancette 已提交
8336 8337 8338 8339 8340 8341 8342 8343 8344
{
    int fd = -1;
    char *newxml = NULL;
    int ret = -1;
    char *snapDir = NULL;
    char *snapFile = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    virUUIDFormat(vm->def->uuid, uuidstr);
8345
    newxml = virDomainSnapshotDefFormat(uuidstr, snapshot->def, 1);
C
Chris Lalancette 已提交
8346 8347 8348 8349 8350 8351 8352 8353 8354
    if (newxml == NULL) {
        virReportOOMError();
        return -1;
    }

    if (virAsprintf(&snapDir, "%s/%s", snapshotDir, vm->def->name) < 0) {
        virReportOOMError();
        goto cleanup;
    }
8355 8356
    if (virFileMakePath(snapDir) < 0) {
        virReportSystemError(errno, _("cannot create snapshot directory '%s'"),
C
Chris Lalancette 已提交
8357 8358 8359 8360
                             snapDir);
        goto cleanup;
    }

8361
    if (virAsprintf(&snapFile, "%s/%s.xml", snapDir, snapshot->def->name) < 0) {
C
Chris Lalancette 已提交
8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382
        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);
8383
    VIR_FORCE_CLOSE(fd);
C
Chris Lalancette 已提交
8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400
    return ret;
}


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,
8401 8402
                            _("Disk '%s' does not support snapshotting"),
                            vm->def->disks[i]->src);
C
Chris Lalancette 已提交
8403 8404 8405 8406 8407 8408 8409
            return 0;
        }
    }

    return 1;
}

8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457
/* 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
8458 8459
qemuDomainSnapshotCreateActive(virConnectPtr conn,
                               struct qemud_driver *driver,
8460 8461 8462 8463 8464
                               virDomainObjPtr *vmptr,
                               virDomainSnapshotObjPtr snap)
{
    virDomainObjPtr vm = *vmptr;
    qemuDomainObjPrivatePtr priv = vm->privateData;
8465 8466
    bool resume = false;
    int ret = -1;
8467

8468
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
8469 8470
        return -1;

J
Jiri Denemark 已提交
8471
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
8472 8473 8474 8475
        /* 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.
         */
8476 8477
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_NONE) < 0)
8478 8479 8480 8481 8482 8483 8484 8485 8486 8487
            goto cleanup;

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

8488
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
8489 8490 8491
    ret = qemuMonitorCreateSnapshot(priv->mon, snap->def->name);
    qemuDomainObjExitMonitorWithDriver(driver, vm);

8492 8493
cleanup:
    if (resume && virDomainObjIsActive(vm) &&
J
Jiri Denemark 已提交
8494
        qemuProcessStartCPUs(driver, vm, conn,
8495 8496
                             VIR_DOMAIN_RUNNING_UNPAUSED,
                             QEMU_ASYNC_JOB_NONE) < 0 &&
8497 8498 8499 8500 8501
        virGetLastError() == NULL) {
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("resuming after snapshot failed"));
    }

8502 8503 8504
    if (qemuDomainObjEndJob(driver, vm) == 0) {
        /* Only possible if a transient vm quit while our locks were down,
         * in which case we don't want to save snapshot metadata.  */
8505
        *vmptr = NULL;
8506 8507
        ret = -1;
    }
8508 8509 8510 8511

    return ret;
}

C
Chris Lalancette 已提交
8512 8513
static virDomainSnapshotPtr qemuDomainSnapshotCreateXML(virDomainPtr domain,
                                                        const char *xmlDesc,
8514
                                                        unsigned int flags)
C
Chris Lalancette 已提交
8515 8516 8517 8518 8519 8520
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
8521
    virDomainSnapshotDefPtr def = NULL;
C
Chris Lalancette 已提交
8522

8523 8524
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
8525 8526 8527 8528 8529 8530 8531 8532 8533
    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;
    }

8534 8535 8536 8537 8538 8539
    if (qemuProcessAutoDestroyActive(driver, vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is marked for auto destroy"));
        goto cleanup;
    }

C
Chris Lalancette 已提交
8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554
    /* 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;
8555
    def = NULL;
C
Chris Lalancette 已提交
8556

J
Jiri Denemark 已提交
8557
    snap->def->state = virDomainObjGetState(vm, NULL);
8558
    snap->def->current = true;
8559 8560 8561 8562 8563 8564
    if (vm->current_snapshot) {
        snap->def->parent = strdup(vm->current_snapshot->def->name);
        if (snap->def->parent == NULL) {
            virReportOOMError();
            goto cleanup;
        }
8565 8566 8567 8568
        vm->current_snapshot->def->current = false;
        if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                            driver->snapshotDir) < 0)
            goto cleanup;
8569 8570
        vm->current_snapshot = NULL;
    }
8571

C
Chris Lalancette 已提交
8572 8573
    /* actually do the snapshot */
    if (!virDomainObjIsActive(vm)) {
8574
        if (qemuDomainSnapshotCreateInactive(vm, snap) < 0)
C
Chris Lalancette 已提交
8575
            goto cleanup;
E
Eric Blake 已提交
8576
    } else {
8577 8578
        if (qemuDomainSnapshotCreateActive(domain->conn, driver,
                                           &vm, snap) < 0)
8579
            goto cleanup;
C
Chris Lalancette 已提交
8580 8581
    }

8582
    /* If we fail after this point, there's not a whole lot we can
C
Chris Lalancette 已提交
8583 8584 8585 8586 8587 8588
     * do; we've successfully taken the snapshot, and we are now running
     * on it, so we have to go forward the best we can
     */
    snapshot = virGetDomainSnapshot(domain, snap->def->name);

cleanup:
8589
    if (vm) {
8590 8591 8592 8593 8594 8595 8596 8597
        if (snapshot) {
            if (qemuDomainSnapshotWriteMetadata(vm, snap,
                                                driver->snapshotDir) < 0)
                VIR_WARN("unable to save metadata for snapshot %s",
                         snap->def->name);
            else
                vm->current_snapshot = snap;
        } else if (snap) {
8598
            virDomainSnapshotObjListRemove(&vm->snapshots, snap);
8599
        }
C
Chris Lalancette 已提交
8600
        virDomainObjUnlock(vm);
8601 8602
    }
    virDomainSnapshotDefFree(def);
C
Chris Lalancette 已提交
8603 8604 8605 8606 8607 8608
    qemuDriverUnlock(driver);
    return snapshot;
}

static int qemuDomainSnapshotListNames(virDomainPtr domain, char **names,
                                       int nameslen,
8609
                                       unsigned int flags)
C
Chris Lalancette 已提交
8610 8611 8612 8613 8614
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

8615 8616
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636
    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,
8637
                                 unsigned int flags)
C
Chris Lalancette 已提交
8638 8639 8640 8641 8642
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

8643 8644
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665
    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,
8666
                                                           unsigned int flags)
C
Chris Lalancette 已提交
8667 8668 8669 8670 8671 8672
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;

8673 8674
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701
    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,
8702
                                        unsigned int flags)
C
Chris Lalancette 已提交
8703 8704 8705 8706 8707
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

8708 8709
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729
    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,
8730
                                                      unsigned int flags)
C
Chris Lalancette 已提交
8731 8732 8733 8734 8735
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotPtr snapshot = NULL;

8736 8737
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762
    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;
}

8763 8764
static char *qemuDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                                          unsigned int flags)
C
Chris Lalancette 已提交
8765 8766 8767 8768 8769 8770 8771
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *xml = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

8772 8773
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800
    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,
8801
                                      unsigned int flags)
C
Chris Lalancette 已提交
8802 8803 8804 8805 8806 8807 8808 8809 8810 8811
{
    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;

8812 8813
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830
    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;
    }

8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841
    if (vm->current_snapshot) {
        vm->current_snapshot->def->current = false;
        if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                            driver->snapshotDir) < 0)
            goto cleanup;
        vm->current_snapshot = NULL;
        /* XXX Should we restore vm->current_snapshot after this point
         * in the failure cases where we know there was no change?  */
    }

    snap->def->current = true;
C
Chris Lalancette 已提交
8842

8843
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
C
Chris Lalancette 已提交
8844 8845 8846 8847 8848 8849 8850
        goto cleanup;

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

        if (virDomainObjIsActive(vm)) {
            priv = vm->privateData;
8851
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
C
Chris Lalancette 已提交
8852 8853 8854
            rc = qemuMonitorLoadSnapshot(priv->mon, snap->def->name);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            if (rc < 0)
8855
                goto endjob;
E
Eric Blake 已提交
8856
        } else {
8857
            rc = qemuProcessStart(snapshot->domain->conn, driver, vm, NULL,
8858
                                  false, false, -1, NULL, snap,
8859
                                  VIR_VM_OP_CREATE);
8860
            virDomainAuditStart(vm, "from-snapshot", rc >= 0);
C
Chris Lalancette 已提交
8861
            if (rc < 0)
8862
                goto endjob;
C
Chris Lalancette 已提交
8863 8864 8865 8866 8867
        }

        if (snap->def->state == VIR_DOMAIN_PAUSED) {
            /* qemu unconditionally starts the domain running again after
             * loadvm, so let's pause it to keep consistency
8868
             * XXX we should have used qemuProcessStart's start_paused instead
C
Chris Lalancette 已提交
8869
             */
J
Jiri Denemark 已提交
8870
            rc = qemuProcessStopCPUs(driver, vm,
8871 8872
                                     VIR_DOMAIN_PAUSED_FROM_SNAPSHOT,
                                     QEMU_ASYNC_JOB_NONE);
H
Hu Tao 已提交
8873
            if (rc < 0)
8874
                goto endjob;
J
Jiri Denemark 已提交
8875 8876 8877
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_FROM_SNAPSHOT);
C
Chris Lalancette 已提交
8878 8879 8880 8881 8882
        }

        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT);
E
Eric Blake 已提交
8883
    } else {
C
Chris Lalancette 已提交
8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894
        /* 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 已提交
8895
            qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT);
8896
            virDomainAuditStop(vm, "from-snapshot");
C
Chris Lalancette 已提交
8897 8898 8899
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STOPPED,
                                             VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT);
8900
            if (!vm->persistent) {
8901
                if (qemuDomainObjEndJob(driver, vm) > 0)
8902 8903
                    virDomainRemoveInactive(&driver->domains, vm);
                vm = NULL;
8904
                goto cleanup;
8905
            }
C
Chris Lalancette 已提交
8906 8907 8908 8909 8910
        }
    }

    ret = 0;

8911
endjob:
8912
    if (vm && qemuDomainObjEndJob(driver, vm) == 0)
C
Chris Lalancette 已提交
8913 8914
        vm = NULL;

8915
cleanup:
8916 8917 8918 8919 8920 8921 8922 8923 8924
    if (vm && ret == 0) {
        if (qemuDomainSnapshotWriteMetadata(vm, snap,
                                            driver->snapshotDir) < 0)
            ret = -1;
        else
            vm->current_snapshot = snap;
    } else if (snap) {
        snap->def->current = false;
    }
C
Chris Lalancette 已提交
8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942
    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;
8943
    virDomainSnapshotObjPtr parentsnap = NULL;
C
Chris Lalancette 已提交
8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973

    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;
                }
            }
        }
E
Eric Blake 已提交
8974
    } else {
C
Chris Lalancette 已提交
8975
        priv = vm->privateData;
8976
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
C
Chris Lalancette 已提交
8977 8978 8979 8980 8981
        /* we continue on even in the face of error */
        qemuMonitorDeleteSnapshot(priv->mon, snap->def->name);
        qemuDomainObjExitMonitorWithDriver(driver, vm);
    }

8982 8983 8984 8985 8986 8987
    if (virAsprintf(&snapFile, "%s/%s/%s.xml", driver->snapshotDir,
                    vm->def->name, snap->def->name) < 0) {
        virReportOOMError();
        goto cleanup;
    }

C
Chris Lalancette 已提交
8988 8989 8990 8991 8992
    if (snap == vm->current_snapshot) {
        if (snap->def->parent) {
            parentsnap = virDomainSnapshotFindByName(&vm->snapshots,
                                                     snap->def->parent);
            if (!parentsnap) {
8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003
                VIR_WARN("missing parent snapshot matching name '%s'",
                         snap->def->parent);
            } else {
                parentsnap->def->current = true;
                if (qemuDomainSnapshotWriteMetadata(vm, parentsnap,
                                                    driver->snapshotDir) < 0) {
                    VIR_WARN("failed to set parent snapshot '%s' as current",
                             snap->def->parent);
                    parentsnap->def->current = false;
                    parentsnap = NULL;
                }
C
Chris Lalancette 已提交
9004
            }
E
Eric Blake 已提交
9005
        }
9006
        vm->current_snapshot = parentsnap;
C
Chris Lalancette 已提交
9007 9008
    }

9009 9010
    if (unlink(snapFile) < 0)
        VIR_WARN("Failed to unlink %s", snapFile);
C
Chris Lalancette 已提交
9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029
    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,
9030
                                              const void *name ATTRIBUTE_UNUSED,
C
Chris Lalancette 已提交
9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051
                                              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);
    }
}

9052 9053 9054 9055 9056 9057 9058 9059 9060
struct snap_reparent {
    struct qemud_driver *driver;
    virDomainSnapshotObjPtr snap;
    virDomainObjPtr vm;
    int err;
};

static void
qemuDomainSnapshotReparentChildren(void *payload,
9061
                                   const void *name ATTRIBUTE_UNUSED,
9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088
                                   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 已提交
9089 9090 9091 9092 9093 9094 9095 9096 9097
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;
9098
    struct snap_reparent rep;
C
Chris Lalancette 已提交
9099

9100 9101
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

C
Chris Lalancette 已提交
9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118
    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;
    }

9119
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
9120 9121
        goto cleanup;

C
Chris Lalancette 已提交
9122 9123 9124 9125 9126 9127 9128 9129
    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)
9130
            goto endjob;
9131 9132 9133 9134 9135 9136 9137 9138 9139
    } 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 已提交
9140 9141 9142 9143
    }

    ret = qemuDomainSnapshotDiscard(driver, vm, snap);

9144
endjob:
9145
    if (qemuDomainObjEndJob(driver, vm) == 0)
9146 9147
        vm = NULL;

C
Chris Lalancette 已提交
9148 9149 9150 9151 9152 9153
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
9154

9155 9156 9157 9158 9159 9160 9161
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;
9162
    bool hmp;
9163

9164
    virCheckFlags(VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP, -1);
9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183

    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;

9184
    qemuDomainObjTaint(driver, vm, VIR_DOMAIN_TAINT_CUSTOM_MONITOR, -1);
9185

9186 9187
    hmp = !!(flags & VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP);

9188
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
9189
        goto cleanup;
9190
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
9191
    ret = qemuMonitorArbitraryCommand(priv->mon, cmd, result, hmp);
9192
    qemuDomainObjExitMonitorWithDriver(driver, vm);
9193
    if (qemuDomainObjEndJob(driver, vm) == 0) {
9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204
        vm = NULL;
        goto cleanup;
    }

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

9205

9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260
static virDomainPtr qemuDomainAttach(virConnectPtr conn,
                                     unsigned int pid,
                                     unsigned int flags)
{
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    virDomainPtr dom = NULL;
    virDomainChrSourceDefPtr monConfig = NULL;
    bool monJSON = false;
    char *pidfile;

    virCheckFlags(0, NULL);

    qemuDriverLock(driver);

    if (!(def = qemuParseCommandLinePid(driver->caps, pid,
                                        &pidfile, &monConfig, &monJSON)))
        goto cleanup;

    if (!monConfig) {
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("No monitor connection for pid %u"),
                        pid);
        goto cleanup;
    }
    if (monConfig->type != VIR_DOMAIN_CHR_TYPE_UNIX) {
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        _("Cannot connect to monitor connection of type '%s' for pid %u"),
                        virDomainChrTypeToString(monConfig->type), pid);
        goto cleanup;
    }

    if (!(def->name) &&
        virAsprintf(&def->name, "attach-pid-%u", pid) < 0) {
        virReportOOMError();
        goto cleanup;
    }

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

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

    if (qemuDomainAssignPCIAddresses(def) < 0)
        goto cleanup;

    if (!(vm = virDomainAssignDef(driver->caps,
                                  &driver->domains,
                                  def, false)))
        goto cleanup;

    def = NULL;

9261
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275
        goto cleanup;

    if (qemuProcessAttach(conn, driver, vm, pid,
                          pidfile, monConfig, monJSON) < 0) {
        monConfig = NULL;
        goto endjob;
    }

    monConfig = NULL;

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

endjob:
9276
    if (qemuDomainObjEndJob(driver, vm) == 0) {
9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291
        vm = NULL;
        goto cleanup;
    }

cleanup:
    virDomainDefFree(def);
    virDomainChrSourceDefFree(monConfig);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    VIR_FREE(pidfile);
    return dom;
}


9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347
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;
    }

9348
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
9349 9350 9351 9352 9353 9354
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"),
                        NULLSTR(devname));
        goto cleanup;
    }

9355
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
E
Eric Blake 已提交
9356
                            0, 0, O_RDWR) < 0)
9357 9358 9359 9360 9361 9362 9363 9364 9365 9366
        goto cleanup;

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

9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428
static const char *
qemuDiskPathToAlias(virDomainObjPtr vm, const char *path) {
    int i;
    char *ret = NULL;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        virDomainDiskDefPtr disk = vm->def->disks[i];

        if (disk->type != VIR_DOMAIN_DISK_TYPE_BLOCK &&
            disk->type != VIR_DOMAIN_DISK_TYPE_FILE)
            continue;

        if (disk->src != NULL && STREQ(disk->src, path)) {
            if (virAsprintf(&ret, "drive-%s", disk->info.alias) < 0) {
                virReportOOMError();
                return NULL;
            }
            break;
        }
    }

    if (!ret) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("No device found for specified path"));
    }
    return ret;
}

static int
qemuDomainBlockJobImpl(virDomainPtr dom, const char *path,
                       unsigned long bandwidth, virDomainBlockJobInfoPtr info,
                       int mode)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    qemuDomainObjPrivatePtr priv;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    const char *device = NULL;
    int ret = -1;

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

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

    device = qemuDiskPathToAlias(vm, path);
    if (!device) {
        goto cleanup;
    }

    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;
9429
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472
    priv = vm->privateData;
    ret = qemuMonitorBlockJob(priv->mon, device, bandwidth, info, mode);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
    if (qemuDomainObjEndJob(driver, vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

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

static int
qemuDomainBlockJobAbort(virDomainPtr dom, const char *path, unsigned int flags)
{
    virCheckFlags(0, -1);
    return qemuDomainBlockJobImpl(dom, path, 0, NULL, BLOCK_JOB_ABORT);
}

static int
qemuDomainGetBlockJobInfo(virDomainPtr dom, const char *path,
                           virDomainBlockJobInfoPtr info, unsigned int flags)
{
    virCheckFlags(0, -1);
    return qemuDomainBlockJobImpl(dom, path, 0, info, BLOCK_JOB_INFO);
}

static int
qemuDomainBlockJobSetSpeed(virDomainPtr dom, const char *path,
                           unsigned long bandwidth, unsigned int flags)
{
    virCheckFlags(0, -1);
    return qemuDomainBlockJobImpl(dom, path, bandwidth, NULL, BLOCK_JOB_SPEED);
}

static int
qemuDomainBlockPull(virDomainPtr dom, const char *path, unsigned long bandwidth,
                    unsigned int flags)
{
9473 9474
    int ret;

9475
    virCheckFlags(0, -1);
9476 9477 9478 9479 9480
    ret = qemuDomainBlockJobImpl(dom, path, bandwidth, NULL, BLOCK_JOB_PULL);
    if (ret == 0 && bandwidth != 0)
        ret = qemuDomainBlockJobImpl(dom, path, bandwidth, NULL,
                                     BLOCK_JOB_SPEED);
    return ret;
9481
}
9482

9483
static virDriver qemuDriver = {
9484 9485
    .no = VIR_DRV_QEMU,
    .name = "QEMU",
9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503
    .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 */
9504 9505
    .domainShutdown = qemuDomainShutdown, /* 0.2.0 */
    .domainReboot = qemuDomainReboot, /* 0.9.3 */
9506 9507
    .domainDestroy = qemuDomainDestroy, /* 0.2.0 */
    .domainDestroyFlags = qemuDomainDestroyFlags, /* 0.9.4 */
9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518
    .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 */
9519
    .domainGetControlInfo = qemuDomainGetControlInfo, /* 0.9.3 */
9520 9521
    .domainSave = qemuDomainSave, /* 0.2.0 */
    .domainSaveFlags = qemuDomainSaveFlags, /* 0.9.4 */
9522
    .domainRestore = qemuDomainRestore, /* 0.2.0 */
9523
    .domainRestoreFlags = qemuDomainRestoreFlags, /* 0.9.4 */
9524 9525
    .domainSaveImageGetXMLDesc = qemuDomainSaveImageGetXMLDesc, /* 0.9.4 */
    .domainSaveImageDefineXML = qemuDomainSaveImageDefineXML, /* 0.9.4 */
9526 9527
    .domainCoreDump = qemudDomainCoreDump, /* 0.7.0 */
    .domainScreenshot = qemuDomainScreenshot, /* 0.9.2 */
9528 9529
    .domainSetVcpus = qemuDomainSetVcpus, /* 0.4.4 */
    .domainSetVcpusFlags = qemuDomainSetVcpusFlags, /* 0.8.5 */
9530 9531
    .domainGetVcpusFlags = qemudDomainGetVcpusFlags, /* 0.8.5 */
    .domainPinVcpu = qemudDomainPinVcpu, /* 0.4.4 */
9532
    .domainPinVcpuFlags = qemudDomainPinVcpuFlags, /* 0.9.3 */
E
Eric Blake 已提交
9533
    .domainGetVcpuPinInfo = qemudDomainGetVcpuPinInfo, /* 0.9.3 */
9534 9535 9536 9537 9538 9539 9540 9541 9542
    .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 */
9543 9544
    .domainCreate = qemuDomainStart, /* 0.2.0 */
    .domainCreateWithFlags = qemuDomainStartWithFlags, /* 0.8.2 */
9545 9546
    .domainDefineXML = qemudDomainDefine, /* 0.2.0 */
    .domainUndefine = qemudDomainUndefine, /* 0.2.0 */
9547
    .domainUndefineFlags = qemuDomainUndefineFlags, /* 0.9.4 */
9548 9549 9550 9551 9552 9553 9554 9555 9556
    .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 */
9557
    .domainGetSchedulerParametersFlags = qemuGetSchedulerParametersFlags, /* 0.9.2 */
9558
    .domainSetSchedulerParameters = qemuSetSchedulerParameters, /* 0.7.0 */
9559
    .domainSetSchedulerParametersFlags = qemuSetSchedulerParametersFlags, /* 0.9.2 */
9560 9561 9562 9563 9564 9565 9566
    .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 */
9567
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
9568
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604
    .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 */
9605
    .qemuDomainAttach = qemuDomainAttach, /* 0.9.4 */
9606 9607
    .domainOpenConsole = qemuDomainOpenConsole, /* 0.8.6 */
    .domainInjectNMI = qemuDomainInjectNMI, /* 0.9.2 */
9608 9609 9610 9611 9612 9613
    .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 */
9614
    .domainSendKey = qemuDomainSendKey, /* 0.9.4 */
9615 9616 9617 9618
    .domainBlockJobAbort = qemuDomainBlockJobAbort, /* 0.9.4 */
    .domainGetBlockJobInfo = qemuDomainGetBlockJobInfo, /* 0.9.4 */
    .domainBlockJobSetSpeed = qemuDomainBlockJobSetSpeed, /* 0.9.4 */
    .domainBlockPull = qemuDomainBlockPull, /* 0.9.4 */
9619 9620 9621
};


9622
static virStateDriver qemuStateDriver = {
9623
    .name = "QEMU",
9624 9625 9626 9627
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
9628
};
9629

9630
static void
9631
qemuVMDriverLock(void) {
9632 9633 9634 9635 9636
    qemuDriverLock(qemu_driver);
};


static void
9637
qemuVMDriverUnlock(void) {
9638 9639 9640 9641
    qemuDriverUnlock(qemu_driver);
};


9642 9643 9644 9645 9646 9647 9648 9649 9650
static int
qemuVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                    virHashIterator iter, void *data)
{
    virHashForEach(qemu_driver->domains.objs, iter, data);

    return 0;
}

S
Stefan Berger 已提交
9651 9652
static virNWFilterCallbackDriver qemuCallbackDriver = {
    .name = "QEMU",
9653 9654 9655
    .vmFilterRebuild = qemuVMFilterRebuild,
    .vmDriverLock = qemuVMDriverLock,
    .vmDriverUnlock = qemuVMDriverUnlock,
S
Stefan Berger 已提交
9656 9657
};

9658
int qemuRegister(void) {
9659 9660
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
S
Stefan Berger 已提交
9661
    virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);
9662 9663
    return 0;
}