qemu_driver.c 263.3 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"
85
#include "files.h"
86
#include "fdstream.h"
87
#include "configmake.h"
H
Hu Tao 已提交
88
#include "threadpool.h"
89
#include "locking/lock_manager.h"
90

91 92
#define VIR_FROM_THIS VIR_FROM_QEMU

93 94
#define QEMU_NB_MEM_PARAM  3

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

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

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

113
#define QEMU_NB_BLKIO_PARAM  1
114

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

117 118
static int qemudShutdown(void);

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

125
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
126

127
struct qemud_driver *qemu_driver = NULL;
128 129


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

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

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

160
        if (qemuDomainObjEndJob(data->driver, vm) == 0)
161
            vm = NULL;
162
    }
163 164 165

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

168

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

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

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

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

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

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

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

217
    return 0;
218

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

225

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

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

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

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

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

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

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

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

270
    return caps;
271

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

279
static void qemuDomainSnapshotLoad(void *payload,
280
                                   const void *name ATTRIBUTE_UNUSED,
281
                                   void *data)
282
{
283 284 285 286 287 288 289 290 291 292
    virDomainObjPtr vm = (virDomainObjPtr)payload;
    char *baseDir = (char *)data;
    char *snapDir = NULL;
    DIR *dir = NULL;
    struct dirent *entry;
    char *xmlStr;
    int ret;
    char *fullpath;
    virDomainSnapshotDefPtr def = NULL;
    char ebuf[1024];
293

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

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

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

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

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

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

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

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

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

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

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

358
    virResetLastError();
359

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

518
    VIR_FREE(base);
519

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

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

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

540 541
    if (qemuSecurityInit(qemu_driver) < 0)
        goto error;
542

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

547
    if ((qemu_driver->activePciHostdevs = pciDeviceListNew()) == NULL)
548
        goto error;
549

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

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

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

605
        qemu_driver->hugepage_path = mempath;
606
    }
607

608 609 610
    if (qemuProcessAutoDestroyInit(qemu_driver) < 0)
        goto error;

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

620 621 622
    conn = virConnectOpen(qemu_driver->privileged ?
                          "qemu:///system" :
                          "qemu:///session");
623

624
    qemuProcessReconnectAll(conn, qemu_driver);
625

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

635

636 637
    virHashForEach(qemu_driver->domains.objs, qemuDomainSnapshotLoad,
                   qemu_driver->snapshotDir);
638

639 640 641
    qemu_driver->workerPool = virThreadPoolNew(0, 1, processWatchdogEvent, qemu_driver);
    if (!qemu_driver->workerPool)
        goto error;
642

643 644 645 646
    qemuDriverUnlock(qemu_driver);

    qemuAutostartDomains(qemu_driver);

647 648
    if (conn)
        virConnectClose(conn);
649

650
    return 0;
651

652 653 654 655 656 657 658 659 660 661
out_of_memory:
    virReportOOMError();
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
    if (conn)
        virConnectClose(conn);
    VIR_FREE(base);
    VIR_FREE(driverConf);
    qemudShutdown();
662
    return -1;
663 664
}

665 666 667
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;
668

669 670 671 672 673 674 675
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
E
Eric Blake 已提交
676
    }
677
}
E
Eric Blake 已提交
678

679 680 681 682 683 684 685 686 687 688
/**
 * 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;
689

690 691 692 693 694
    qemuDriverLock(qemu_driver);
    virDomainLoadAllConfigs(qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
                            qemu_driver->autostartDir,
M
Matthias Bolte 已提交
695 696
                            0, QEMU_EXPECTED_VIRT_TYPES,
                            qemudNotifyLoadDomain, qemu_driver);
697
    qemuDriverUnlock(qemu_driver);
698

699
    qemuAutostartDomains(qemu_driver);
700

701 702
    return 0;
}
S
Stefan Berger 已提交
703

704 705 706 707 708 709 710 711 712 713 714
/**
 * 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;
715

716 717
    if (!qemu_driver)
        return 0;
718

719 720 721 722 723 724
    /* 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;
}
725

726 727 728 729 730 731 732 733
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
    int i;
734

735 736
    if (!qemu_driver)
        return -1;
737

738 739 740
    qemuDriverLock(qemu_driver);
    pciDeviceListFree(qemu_driver->activePciHostdevs);
    virCapabilitiesFree(qemu_driver->caps);
741

742 743
    virDomainObjListDeinit(&qemu_driver->domains);
    virBitmapFree(qemu_driver->reservedVNCPorts);
744

745
    virSysinfoDefFree(qemu_driver->hostsysinfo);
746

747 748
    qemuProcessAutoDestroyShutdown(qemu_driver);

749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
    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);
769

770
    virSecurityManagerFree(qemu_driver->securityManager);
771

772
    ebtablesContextFree(qemu_driver->ebtables);
773

774 775 776 777
    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 已提交
778 779
    }

780
    /* Free domain callback list */
781
    virDomainEventStateFree(qemu_driver->domainEventState);
D
Daniel P. Berrange 已提交
782

783 784
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);
785

786
    virCgroupFree(&qemu_driver->cgroup);
787

788 789
    virLockManagerPluginUnref(qemu_driver->lockManager);

790 791 792 793
    qemuDriverUnlock(qemu_driver);
    virMutexDestroy(&qemu_driver->lock);
    virThreadPoolFree(qemu_driver->workerPool);
    VIR_FREE(qemu_driver);
794

795
    return 0;
796 797
}

798 799 800 801 802 803 804

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


805
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
806
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
807
                                  unsigned int flags)
808
{
E
Eric Blake 已提交
809 810
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

811
    if (conn->uri == NULL) {
812 813 814
        if (qemu_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

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

832
        if (qemu_driver == NULL) {
833 834
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("qemu state driver is not active"));
835 836 837
            return VIR_DRV_OPEN_ERROR;
        }

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

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

    return VIR_DRV_OPEN_SUCCESS;
}

static int qemudClose(virConnectPtr conn) {
870
    struct qemud_driver *driver = conn->privateData;
871 872

    /* Get rid of callbacks registered for this conn */
873
    qemuDriverLock(driver);
874 875
    virDomainEventCallbackListRemoveConn(conn,
                                         driver->domainEventState->callbacks);
876
    qemuProcessAutoDestroyRun(driver, conn);
877
    qemuDriverUnlock(driver);
878 879 880 881 882 883

    conn->privateData = NULL;

    return 0;
}

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

898
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
899
    return "QEMU";
900 901
}

902

903 904 905 906 907 908 909 910 911 912 913 914 915
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;
}


916 917 918 919
static int kvmGetMaxVCPUs(void) {
    int maxvcpus = 1;

    int r, fd;
920

921 922
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
923
        virReportSystemError(errno, _("Unable to open %s"), KVM_DEVICE);
924
        return -1;
925 926 927 928 929 930
    }

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

931
    VIR_FORCE_CLOSE(fd);
932 933 934 935
    return maxvcpus;
}


E
Eric Blake 已提交
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
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, "");
}

952
static int qemudGetMaxVCPUs(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
953 954 955
    if (!type)
        return 16;

956
    if (STRCASEEQ(type, "qemu"))
957 958
        return 16;

959
    if (STRCASEEQ(type, "kvm"))
960
        return kvmGetMaxVCPUs();
961

962
    if (STRCASEEQ(type, "kqemu"))
963
        return 1;
964

965 966
    qemuReportError(VIR_ERR_INVALID_ARG,
                    _("unknown type '%s'"), type);
967 968 969
    return -1;
}

970

971
static char *qemudGetCapabilities(virConnectPtr conn) {
972
    struct qemud_driver *driver = conn->privateData;
973
    virCapsPtr caps = NULL;
974
    char *xml = NULL;
975

976
    qemuDriverLock(driver);
977

978
    if ((caps = qemuCreateCapabilities(qemu_driver->caps,
979
                                       qemu_driver)) == NULL) {
980 981 982
        virCapabilitiesFree(caps);
        goto cleanup;
    }
983

984
    virCapabilitiesFree(qemu_driver->caps);
985 986 987
    qemu_driver->caps = caps;

    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
988
        virReportOOMError();
989 990

cleanup:
991
    qemuDriverUnlock(driver);
992

993
    return xml;
994 995 996
}


997 998 999 1000 1001
static int
qemudGetProcessInfo(unsigned long long *cpuTime, int *lastCpu, int pid,
                    int tid)
{
    char *proc;
D
Daniel P. Berrange 已提交
1002
    FILE *pidinfo;
1003
    unsigned long long usertime, systime;
1004 1005
    int cpu;
    int ret;
D
Daniel P. Berrange 已提交
1006

1007
    if (tid)
1008
        ret = virAsprintf(&proc, "/proc/%d/task/%d/stat", pid, tid);
1009
    else
1010 1011
        ret = virAsprintf(&proc, "/proc/%d/stat", pid);
    if (ret < 0)
D
Daniel P. Berrange 已提交
1012 1013 1014 1015
        return -1;

    if (!(pidinfo = fopen(proc, "r"))) {
        /* VM probably shut down, so fake 0 */
1016 1017 1018 1019
        if (cpuTime)
            *cpuTime = 0;
        if (lastCpu)
            *lastCpu = 0;
1020
        VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1021 1022
        return 0;
    }
1023
    VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1024

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

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
1046 1047 1048 1049 1050
    if (cpuTime)
        *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
    if (lastCpu)
        *lastCpu = cpu;

D
Daniel P. Berrange 已提交
1051

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

1055
    VIR_FORCE_FCLOSE(pidinfo);
D
Daniel P. Berrange 已提交
1056 1057 1058 1059 1060

    return 0;
}


1061
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1062
                                          int id) {
1063 1064 1065 1066
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1067
    qemuDriverLock(driver);
1068
    vm  = virDomainFindByID(&driver->domains, id);
1069
    qemuDriverUnlock(driver);
1070 1071

    if (!vm) {
1072 1073
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching id %d"), id);
1074
        goto cleanup;
1075 1076
    }

1077
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1078
    if (dom) dom->id = vm->def->id;
1079 1080

cleanup:
1081 1082
    if (vm)
        virDomainObjUnlock(vm);
1083 1084
    return dom;
}
1085

1086
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1087
                                            const unsigned char *uuid) {
1088 1089 1090
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1091

1092
    qemuDriverLock(driver);
1093
    vm = virDomainFindByUUID(&driver->domains, uuid);
1094 1095
    qemuDriverUnlock(driver);

1096
    if (!vm) {
1097 1098
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
1099 1100
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1101
        goto cleanup;
1102 1103
    }

1104
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1105
    if (dom) dom->id = vm->def->id;
1106 1107

cleanup:
1108 1109
    if (vm)
        virDomainObjUnlock(vm);
1110 1111
    return dom;
}
1112

1113
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1114
                                            const char *name) {
1115 1116 1117
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1118

1119
    qemuDriverLock(driver);
1120
    vm = virDomainFindByName(&driver->domains, name);
1121 1122
    qemuDriverUnlock(driver);

1123
    if (!vm) {
1124 1125
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), name);
1126
        goto cleanup;
1127 1128
    }

1129
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1130
    if (dom) dom->id = vm->def->id;
1131 1132

cleanup:
1133 1134
    if (vm)
        virDomainObjUnlock(vm);
1135 1136 1137
    return dom;
}

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148

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

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

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

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

1211
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1212 1213 1214
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

1215
    qemuDriverLock(driver);
1216
    if (qemuCapsExtractVersion(driver->caps, &driver->qemuVersion) < 0)
1217
        goto cleanup;
1218

1219
    *version = driver->qemuVersion;
1220 1221 1222
    ret = 0;

cleanup:
1223
    qemuDriverUnlock(driver);
1224
    return ret;
D
Daniel P. Berrange 已提交
1225 1226
}

1227
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1228
    struct qemud_driver *driver = conn->privateData;
1229
    int n;
1230

1231
    qemuDriverLock(driver);
1232
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1233
    qemuDriverUnlock(driver);
1234

1235
    return n;
D
Daniel P. Berrange 已提交
1236
}
1237

1238
static int qemudNumDomains(virConnectPtr conn) {
1239
    struct qemud_driver *driver = conn->privateData;
1240
    int n;
1241

1242
    qemuDriverLock(driver);
1243
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1244
    qemuDriverUnlock(driver);
1245

1246
    return n;
D
Daniel P. Berrange 已提交
1247
}
1248

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

1257 1258
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
                  VIR_DOMAIN_START_AUTODESTROY, NULL);
1259

1260
    qemuDriverLock(driver);
1261
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1262
                                        QEMU_EXPECTED_VIRT_TYPES,
1263
                                        VIR_DOMAIN_XML_INACTIVE)))
1264
        goto cleanup;
1265

1266
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
1267 1268
        goto cleanup;

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

1272 1273 1274
    if (qemudCanonicalizeMachine(driver, def) < 0)
        goto cleanup;

1275
    if (qemuDomainAssignPCIAddresses(def) < 0)
1276 1277
        goto cleanup;

1278
    if (!(vm = virDomainAssignDef(driver->caps,
1279
                                  &driver->domains,
1280
                                  def, false)))
1281 1282 1283
        goto cleanup;

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

1285
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
1286 1287
        goto cleanup; /* XXXX free the 'vm' we created ? */

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

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

1305
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1306
    if (dom) dom->id = vm->def->id;
1307

1308
    if (vm &&
1309
        qemuDomainObjEndJob(driver, vm) == 0)
1310
        vm = NULL;
1311

1312 1313
cleanup:
    virDomainDefFree(def);
1314 1315
    if (vm)
        virDomainObjUnlock(vm);
1316 1317
    if (event)
        qemuDomainEventQueue(driver, event);
1318
    qemuDriverUnlock(driver);
1319
    return dom;
D
Daniel P. Berrange 已提交
1320 1321 1322
}


1323
static int qemudDomainSuspend(virDomainPtr dom) {
1324 1325 1326
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1327
    virDomainEventPtr event = NULL;
1328
    qemuDomainObjPrivatePtr priv;
1329

1330
    qemuDriverLock(driver);
1331
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1332

D
Daniel P. Berrange 已提交
1333
    if (!vm) {
1334 1335
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1336 1337
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1338
        goto cleanup;
D
Daniel P. Berrange 已提交
1339
    }
D
Daniel P. Berrange 已提交
1340
    if (!virDomainObjIsActive(vm)) {
1341 1342
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1343
        goto cleanup;
D
Daniel P. Berrange 已提交
1344
    }
1345

1346 1347 1348 1349 1350 1351
    if (qemuProcessAutoDestroyActive(driver, vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is marked for auto destroy"));
        goto cleanup;
    }

1352 1353
    priv = vm->privateData;

1354
    if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_OUT) {
J
Jiri Denemark 已提交
1355
        if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
1356 1357
            VIR_DEBUG("Requesting domain pause on %s",
                      vm->def->name);
1358
            priv->job.signals |= QEMU_JOB_SIGNAL_SUSPEND;
1359 1360 1361 1362
        }
        ret = 0;
        goto cleanup;
    } else {
1363
        if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_SUSPEND) < 0)
1364 1365 1366 1367 1368
            goto cleanup;

        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
1369
            goto endjob;
1370
        }
J
Jiri Denemark 已提交
1371 1372
        if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
            if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_USER) < 0) {
1373
                goto endjob;
1374
            }
1375 1376 1377 1378 1379 1380 1381
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_SUSPENDED,
                                             VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
        }
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
            goto endjob;
        ret = 0;
D
Daniel P. Berrange 已提交
1382
    }
1383

1384
endjob:
1385
    if (qemuDomainObjEndJob(driver, vm) == 0)
1386
        vm = NULL;
1387

1388
cleanup:
1389 1390
    if (vm)
        virDomainObjUnlock(vm);
1391

1392
    if (event)
1393
        qemuDomainEventQueue(driver, event);
1394
    qemuDriverUnlock(driver);
1395
    return ret;
D
Daniel P. Berrange 已提交
1396 1397 1398
}


1399
static int qemudDomainResume(virDomainPtr dom) {
1400 1401 1402
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1403
    virDomainEventPtr event = NULL;
1404

1405
    qemuDriverLock(driver);
1406
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1407

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

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

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

1440
endjob:
1441
    if (qemuDomainObjEndJob(driver, vm) == 0)
1442
        vm = NULL;
1443

1444
cleanup:
1445 1446
    if (vm)
        virDomainObjUnlock(vm);
1447
    if (event)
1448
        qemuDomainEventQueue(driver, event);
1449
    qemuDriverUnlock(driver);
1450
    return ret;
D
Daniel P. Berrange 已提交
1451 1452 1453
}


1454
static int qemuDomainShutdown(virDomainPtr dom) {
1455 1456 1457
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1458
    qemuDomainObjPrivatePtr priv;
1459

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

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

1472
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1473 1474
        goto cleanup;

D
Daniel P. Berrange 已提交
1475
    if (!virDomainObjIsActive(vm)) {
1476 1477
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1478
        goto endjob;
1479 1480
    }

1481
    priv = vm->privateData;
1482
    ignore_value(qemuDomainObjEnterMonitor(driver, vm));
1483
    ret = qemuMonitorSystemPowerdown(priv->mon);
1484
    qemuDomainObjExitMonitor(driver, vm);
1485

1486 1487
    priv->fakeReboot = false;

1488
endjob:
1489
    if (qemuDomainObjEndJob(driver, vm) == 0)
1490
        vm = NULL;
1491

1492
cleanup:
1493 1494
    if (vm)
        virDomainObjUnlock(vm);
1495
    return ret;
1496 1497 1498
}


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

    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
1522 1523
    priv = vm->privateData;

1524
    if (qemuCapsGet(priv->qemuCaps, QEMU_CAPS_MONITOR_JSON)) {
1525
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1526 1527 1528 1529 1530 1531 1532 1533
            goto cleanup;

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

1534
        ignore_value(qemuDomainObjEnterMonitor(driver, vm));
1535
        ret = qemuMonitorSystemPowerdown(priv->mon);
1536
        qemuDomainObjExitMonitor(driver, vm);
1537 1538 1539 1540

        priv->fakeReboot = true;

    endjob:
1541
        if (qemuDomainObjEndJob(driver, vm) == 0)
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
            vm = NULL;
    } else {
#endif
        qemuReportError(VIR_ERR_NO_SUPPORT, "%s",
                        _("Reboot is not supported without the JSON monitor"));
#if HAVE_YAJL
    }
#endif

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


1558
static int qemudDomainDestroy(virDomainPtr dom) {
1559 1560 1561
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1562
    virDomainEventPtr event = NULL;
1563
    qemuDomainObjPrivatePtr priv;
1564

1565
    qemuDriverLock(driver);
1566
    vm  = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel P. Berrange 已提交
1567
    if (!vm) {
1568 1569
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1570 1571
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1572
        goto cleanup;
D
Daniel P. Berrange 已提交
1573
    }
1574

1575 1576 1577
    priv = vm->privateData;
    priv->fakeReboot = false;

1578 1579 1580 1581 1582 1583 1584
    /* 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);

1585
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_DESTROY) < 0)
1586 1587
        goto cleanup;

D
Daniel P. Berrange 已提交
1588
    if (!virDomainObjIsActive(vm)) {
1589 1590
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1591
        goto endjob;
1592
    }
1593

J
Jiri Denemark 已提交
1594
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_DESTROYED);
1595 1596 1597
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1598
    virDomainAuditStop(vm, "destroyed");
1599

1600
    if (!vm->persistent) {
1601
        if (qemuDomainObjEndJob(driver, vm) > 0)
1602 1603
            virDomainRemoveInactive(&driver->domains,
                                    vm);
1604 1605
        vm = NULL;
    }
1606 1607
    ret = 0;

1608
endjob:
1609
    if (vm &&
1610
        qemuDomainObjEndJob(driver, vm) == 0)
1611
        vm = NULL;
1612

1613
cleanup:
1614 1615
    if (vm)
        virDomainObjUnlock(vm);
1616 1617
    if (event)
        qemuDomainEventQueue(driver, event);
1618
    qemuDriverUnlock(driver);
1619
    return ret;
D
Daniel P. Berrange 已提交
1620 1621 1622
}


1623
static char *qemudDomainGetOSType(virDomainPtr dom) {
1624 1625 1626
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1627

1628
    qemuDriverLock(driver);
1629
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1630
    qemuDriverUnlock(driver);
1631
    if (!vm) {
1632 1633
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1634 1635
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1636
        goto cleanup;
1637 1638
    }

1639
    if (!(type = strdup(vm->def->os.type)))
1640
        virReportOOMError();
1641 1642

cleanup:
1643 1644
    if (vm)
        virDomainObjUnlock(vm);
1645 1646 1647
    return type;
}

1648 1649
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
1650 1651 1652
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
1653

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

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

1666
    ret = vm->def->mem.max_balloon;
1667 1668

cleanup:
1669 1670
    if (vm)
        virDomainObjUnlock(vm);
1671
    return ret;
1672 1673
}

1674 1675
static int qemudDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
                                     unsigned int flags) {
1676
    struct qemud_driver *driver = dom->conn->privateData;
1677
    qemuDomainObjPrivatePtr priv;
1678
    virDomainObjPtr vm;
1679
    virDomainDefPtr persistentDef = NULL;
1680
    int ret = -1, r;
1681
    bool isActive;
1682

1683 1684
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
1685
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1686

1687
    qemuDriverLock(driver);
1688
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1689
    qemuDriverUnlock(driver);
1690
    if (!vm) {
1691 1692
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1693 1694
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1695
        goto cleanup;
1696 1697
    }

1698
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1699 1700
        goto cleanup;

1701 1702
    isActive = virDomainObjIsActive(vm);

1703
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
1704
        if (isActive)
1705
            flags = VIR_DOMAIN_AFFECT_LIVE;
1706
        else
1707
            flags = VIR_DOMAIN_AFFECT_CONFIG;
1708
    }
1709 1710
    if (flags == VIR_DOMAIN_MEM_MAXIMUM) {
        if (isActive)
1711
            flags = VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_MEM_MAXIMUM;
1712
        else
1713
            flags = VIR_DOMAIN_AFFECT_CONFIG | VIR_DOMAIN_MEM_MAXIMUM;
1714
    }
1715

1716
    if (!isActive && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
1717 1718 1719 1720 1721
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

1722
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
1723 1724 1725 1726 1727 1728 1729 1730
        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;
    }
1731

1732 1733 1734
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */

1735
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
1736 1737 1738
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot resize the maximum memory on an "
                              "active domain"));
1739
            goto endjob;
1740
        }
1741

1742
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
1743 1744
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
1745 1746 1747 1748
            persistentDef->mem.max_balloon = newmem;
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
1749 1750 1751
            goto endjob;
        }

1752 1753 1754 1755 1756 1757 1758 1759 1760
    } 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;
        }

1761
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
1762
            priv = vm->privateData;
1763
            ignore_value(qemuDomainObjEnterMonitor(driver, vm));
1764
            r = qemuMonitorSetBalloon(priv->mon, newmem);
1765
            qemuDomainObjExitMonitor(driver, vm);
1766 1767
            virDomainAuditMemory(vm, vm->def->mem.cur_balloon, newmem, "update",
                                 r == 1);
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
            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;
            }
        }

1779
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
1780
            sa_assert(persistentDef);
1781 1782 1783 1784
            persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
            goto endjob;
        }
1785
    }
1786

1787
    ret = 0;
1788
endjob:
1789
    if (qemuDomainObjEndJob(driver, vm) == 0)
1790
        vm = NULL;
1791

1792
cleanup:
1793 1794
    if (vm)
        virDomainObjUnlock(vm);
1795
    return ret;
1796 1797
}

1798 1799
static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem)
{
1800
    return qemudDomainSetMemoryFlags(dom, newmem, VIR_DOMAIN_AFFECT_LIVE);
1801 1802
}

1803 1804 1805 1806 1807
static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return qemudDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
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;

1835
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
1836
        goto cleanup;
1837
    ignore_value(qemuDomainObjEnterMonitorWithDriver(driver, vm));
1838 1839
    ret = qemuMonitorInjectNMI(priv->mon);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
1840
    if (qemuDomainObjEndJob(driver, vm) == 0) {
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
        vm = NULL;
        goto cleanup;
    }

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

1852
static int qemudDomainGetInfo(virDomainPtr dom,
1853 1854
                              virDomainInfoPtr info)
{
1855 1856 1857
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1858 1859
    int err;
    unsigned long balloon;
1860

1861
    qemuDriverLock(driver);
1862
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1863
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
1864
    if (!vm) {
1865 1866
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1867 1868
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1869
        goto cleanup;
D
Daniel P. Berrange 已提交
1870 1871
    }

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

D
Daniel P. Berrange 已提交
1874
    if (!virDomainObjIsActive(vm)) {
1875
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
1876
    } else {
1877
        if (qemudGetProcessInfo(&(info->cpuTime), NULL, vm->pid, 0) < 0) {
E
Eric Blake 已提交
1878 1879
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("cannot read cputime for domain"));
1880
            goto cleanup;
D
Daniel P. Berrange 已提交
1881 1882 1883
        }
    }

1884
    info->maxMem = vm->def->mem.max_balloon;
1885

D
Daniel P. Berrange 已提交
1886
    if (virDomainObjIsActive(vm)) {
1887
        qemuDomainObjPrivatePtr priv = vm->privateData;
1888 1889 1890

        if ((vm->def->memballoon != NULL) &&
            (vm->def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_NONE)) {
1891
            info->memory = vm->def->mem.max_balloon;
1892
        } else if (!priv->job.active) {
1893
            if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
1894
                goto cleanup;
1895 1896 1897
            if (!virDomainObjIsActive(vm))
                err = 0;
            else {
1898
                ignore_value(qemuDomainObjEnterMonitor(driver, vm));
1899
                err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
1900
                qemuDomainObjExitMonitor(driver, vm);
1901
            }
1902
            if (qemuDomainObjEndJob(driver, vm) == 0) {
1903
                vm = NULL;
1904 1905 1906
                goto cleanup;
            }

1907 1908
            if (err < 0)
                goto cleanup;
1909 1910
            if (err == 0)
                /* Balloon not supported, so maxmem is always the allocation */
1911
                info->memory = vm->def->mem.max_balloon;
1912 1913 1914
            else
                info->memory = balloon;
        } else {
1915
            info->memory = vm->def->mem.cur_balloon;
1916
        }
1917
    } else {
1918
        info->memory = vm->def->mem.cur_balloon;
1919 1920
    }

1921
    info->nrVirtCpu = vm->def->vcpus;
1922 1923 1924
    ret = 0;

cleanup:
1925 1926
    if (vm)
        virDomainObjUnlock(vm);
1927
    return ret;
D
Daniel P. Berrange 已提交
1928 1929
}

1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
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 已提交
1954
    *state = virDomainObjGetState(vm, reason);
1955 1956 1957 1958 1959 1960 1961 1962
    ret = 0;

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

1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
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;
1999
    } else if (priv->job.active) {
2000 2001 2002 2003
        if (!priv->monStart) {
            info->state = VIR_DOMAIN_CONTROL_JOB;
            if (virTimeMs(&info->stateTime) < 0)
                goto cleanup;
2004
            info->stateTime -= priv->job.start;
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
        } 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 已提交
2023

2024
#define QEMUD_SAVE_MAGIC "LibvirtQemudSave"
2025 2026 2027
#define QEMUD_SAVE_VERSION 2

enum qemud_save_formats {
2028 2029 2030
    QEMUD_SAVE_FORMAT_RAW = 0,
    QEMUD_SAVE_FORMAT_GZIP = 1,
    QEMUD_SAVE_FORMAT_BZIP2 = 2,
2031 2032
    /*
     * Deprecated by xz and never used as part of a release
2033
     * QEMUD_SAVE_FORMAT_LZMA
2034 2035
     */
    QEMUD_SAVE_FORMAT_XZ = 3,
2036
    QEMUD_SAVE_FORMAT_LZOP = 4,
2037 2038 2039
    /* Note: add new members only at the end.
       These values are used in the on-disk format.
       Do not change or re-use numbers. */
2040 2041

    QEMUD_SAVE_FORMAT_LAST
2042
};
2043

2044 2045 2046 2047 2048
VIR_ENUM_DECL(qemudSaveCompression)
VIR_ENUM_IMPL(qemudSaveCompression, QEMUD_SAVE_FORMAT_LAST,
              "raw",
              "gzip",
              "bzip2",
2049 2050
              "xz",
              "lzop")
2051

2052 2053
struct qemud_save_header {
    char magic[sizeof(QEMUD_SAVE_MAGIC)-1];
2054 2055 2056 2057 2058
    uint32_t version;
    uint32_t xml_len;
    uint32_t was_running;
    uint32_t compressed;
    uint32_t unused[15];
2059 2060
};

2061 2062 2063 2064 2065 2066 2067 2068 2069
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);
}


2070
/* return -errno on failure, or 0 on success */
E
Eric Blake 已提交
2071 2072 2073 2074
static int
qemuDomainSaveHeader(int fd, const char *path, char *xml,
                     struct qemud_save_header *header)
{
2075 2076
    int ret = 0;

E
Eric Blake 已提交
2077
    if (safewrite(fd, header, sizeof(*header)) != sizeof(*header)) {
2078
        ret = -errno;
2079
        qemuReportError(VIR_ERR_OPERATION_FAILED,
2080
                        _("failed to write header to domain save file '%s'"),
E
Eric Blake 已提交
2081
                        path);
2082 2083 2084
        goto endjob;
    }

E
Eric Blake 已提交
2085
    if (safewrite(fd, xml, header->xml_len) != header->xml_len) {
2086
        ret = -errno;
2087
        qemuReportError(VIR_ERR_OPERATION_FAILED,
E
Eric Blake 已提交
2088
                         _("failed to write xml to '%s'"), path);
2089 2090 2091 2092 2093 2094
        goto endjob;
    }
endjob:
    return ret;
}

2095 2096 2097 2098 2099 2100 2101 2102 2103
/* 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));
}

2104
/* This internal function expects the driver lock to already be held on
2105 2106 2107 2108
 * 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).
2109
 */
2110 2111
static int qemudDomainSaveFlag(struct qemud_driver *driver, virDomainPtr dom,
                               virDomainObjPtr vm, const char *path,
2112
                               int compressed)
2113
{
2114
    char *xml = NULL;
2115
    struct qemud_save_header header;
2116
    bool bypassSecurityDriver = false;
2117
    int ret = -1;
2118
    int rc;
2119
    virDomainEventPtr event = NULL;
2120
    qemuDomainObjPrivatePtr priv;
2121
    struct stat sb;
2122
    bool is_reg = false;
2123
    unsigned long long offset;
2124
    int fd = -1;
2125 2126
    uid_t uid = getuid();
    gid_t gid = getgid();
2127 2128 2129 2130 2131

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

2132
    header.compressed = compressed;
2133

2134
    priv = vm->privateData;
2135

2136 2137
    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             QEMU_ASYNC_JOB_SAVE) < 0)
2138 2139
        goto cleanup;

2140 2141
    memset(&priv->job.info, 0, sizeof(priv->job.info));
    priv->job.info.type = VIR_DOMAIN_JOB_UNBOUNDED;
2142

2143
    /* Pause */
J
Jiri Denemark 已提交
2144
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
2145
        header.was_running = 1;
J
Jiri Denemark 已提交
2146
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE) < 0)
2147
            goto endjob;
2148 2149 2150 2151 2152 2153

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

    /* Get XML for the domain */
2157
    xml = virDomainDefFormat(vm->def, VIR_DOMAIN_XML_SECURE);
2158
    if (!xml) {
2159 2160
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to get domain xml"));
2161
        goto endjob;
2162 2163 2164
    }
    header.xml_len = strlen(xml) + 1;

2165 2166 2167 2168 2169 2170 2171 2172
    /* path might be a pre-existing block dev, in which case
     * we need to skip the create step, and also avoid unlink
     * in the failure case */
    if (stat(path, &sb) < 0) {
        /* Avoid throwing an error here, since it is possible
         * that with NFS we can't actually stat() the file.
         * The subsequent codepaths will still raise an error
         * if a truely fatal problem is hit */
2173
        is_reg = true;
2174
    } else {
2175
        is_reg = !!S_ISREG(sb.st_mode);
2176
        /* If the path is regular file which exists
2177 2178
         * already and dynamic_ownership is off, we don't
         * want to change it's ownership, just open it as-is */
2179
        if (is_reg && !driver->dynamicOwnership) {
2180 2181 2182
            uid=sb.st_uid;
            gid=sb.st_gid;
        }
2183 2184
    }

2185 2186 2187 2188 2189
    offset = sizeof(header) + header.xml_len;

    /* Due to way we append QEMU state on our header with dd,
     * we need to ensure there's a 512 byte boundary. Unfortunately
     * we don't have an explicit offset in the header, so we fake
2190 2191
     * it by padding the XML string with NULLs.
     */
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
    if (offset % QEMU_MONITOR_MIGRATE_TO_FILE_BS) {
        unsigned long long pad =
            QEMU_MONITOR_MIGRATE_TO_FILE_BS -
            (offset % QEMU_MONITOR_MIGRATE_TO_FILE_BS);

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

2206
    /* Obtain the file handle.  */
2207

2208
    /* First try creating the file as root */
2209
    if (!is_reg) {
2210
        fd = open(path, O_WRONLY | O_TRUNC);
2211 2212
        if (fd < 0) {
            virReportSystemError(errno, _("unable to open %s"), path);
2213 2214
            goto endjob;
        }
2215
    } else {
2216 2217
        if ((fd = virFileOpenAs(path, O_CREAT|O_TRUNC|O_WRONLY,
                                S_IRUSR|S_IWUSR,
2218
                                uid, gid, 0)) < 0) {
2219
            /* If we failed as root, and the error was permission-denied
2220 2221
               (EACCES or EPERM), assume it's on a network-connected share
               where root access is restricted (eg, root-squashed NFS). If the
2222 2223 2224
               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 */
2225
            rc = fd;
2226
            if (((rc != -EACCES) && (rc != -EPERM)) ||
2227
                driver->user == getuid()) {
2228 2229
                virReportSystemError(-rc,
                                    _("Failed to create domain save file '%s'"),
2230 2231 2232
                                     path);
                goto endjob;
            }
2233

2234
            /* On Linux we can also verify the FS-type of the directory. */
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
            switch (virStorageFileIsSharedFS(path)) {
                case 1:
                   /* it was on a network share, so we'll continue
                    * as outlined above
                    */
                   break;

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

                case 0:
                default:
2252
                   /* local file - log the error returned by virFileOpenAs */
2253
                   virReportSystemError(-rc,
2254
                                    _("Failed to create domain save file '%s'"),
2255 2256 2257
                                        path);
                   goto endjob;
                   break;
2258 2259 2260

            }

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

2263 2264 2265 2266
            if ((fd = virFileOpenAs(path, O_CREAT|O_TRUNC|O_WRONLY,
                                    S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP,
                                    driver->user, driver->group,
                                    VIR_FILE_OPEN_AS_UID)) < 0) {
2267 2268 2269
                virReportSystemError(-fd,
                                   _("Error from child process creating '%s'"),
                                     path);
2270 2271
                goto endjob;
            }
2272

2273 2274 2275
            /* 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 */
2276

2277
            bypassSecurityDriver = true;
2278
        }
2279
    }
2280

2281
    /* Write header to file, followed by XML */
E
Eric Blake 已提交
2282
    if (qemuDomainSaveHeader(fd, path, xml, &header) < 0) {
2283 2284 2285 2286
        VIR_FORCE_CLOSE(fd);
        goto endjob;
    }

2287
    /* Perform the migration */
2288
    if (qemuMigrationToFile(driver, vm, fd, offset, path,
2289 2290
                            qemuCompressProgramName(compressed),
                            is_reg, bypassSecurityDriver) < 0)
2291
        goto endjob;
2292 2293
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("unable to close %s"), path);
2294
        goto endjob;
2295 2296
    }

2297 2298
    ret = 0;

2299
    /* Shut it down */
J
Jiri Denemark 已提交
2300
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_SAVED);
2301
    virDomainAuditStop(vm, "saved");
2302 2303 2304
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2305
    if (!vm->persistent) {
2306
        if (qemuDomainObjEndAsyncJob(driver, vm) > 0)
2307 2308
            virDomainRemoveInactive(&driver->domains,
                                    vm);
2309 2310
        vm = NULL;
    }
2311

2312
endjob:
2313
    if (vm) {
2314
        if (ret != 0) {
2315
            if (header.was_running && virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
2316 2317
                rc = qemuProcessStartCPUs(driver, vm, dom->conn,
                                          VIR_DOMAIN_RUNNING_SAVE_CANCELED);
2318
                if (rc < 0)
2319
                    VIR_WARN("Unable to resume guest CPUs after save failure");
2320
            }
2321
        }
2322
        if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
2323
            vm = NULL;
2324
    }
2325

2326
cleanup:
2327
    VIR_FORCE_CLOSE(fd);
2328
    VIR_FREE(xml);
2329
    if (ret != 0 && is_reg)
2330
        unlink(path);
2331 2332
    if (event)
        qemuDomainEventQueue(driver, event);
2333 2334
    if (vm)
        virDomainObjUnlock(vm);
2335
    return ret;
D
Daniel P. Berrange 已提交
2336 2337
}

2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
/* 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;
}

2354 2355 2356 2357
static int qemudDomainSave(virDomainPtr dom, const char *path)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int compressed;
2358 2359 2360 2361
    int ret = -1;
    virDomainObjPtr vm = NULL;

    qemuDriverLock(driver);
2362 2363 2364 2365 2366 2367 2368 2369 2370

    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"));
2371
            goto cleanup;
2372
        }
2373 2374 2375 2376
        if (!qemudCompressProgramAvailable(compressed)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Compression program for image format "
                                    "in configuration file isn't available"));
2377
            goto cleanup;
2378
        }
2379 2380
    }

2381 2382 2383 2384 2385 2386 2387 2388 2389
    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;
    }

2390 2391 2392 2393 2394 2395
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2396
    ret = qemudDomainSaveFlag(driver, dom, vm, path, compressed);
2397
    vm = NULL;
2398 2399 2400 2401 2402 2403 2404

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

    return ret;
2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427
}

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;

2428
    virCheckFlags(0, -1);
2429 2430 2431 2432 2433 2434 2435 2436

    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);
2437
        goto cleanup;
2438 2439
    }

2440 2441 2442 2443 2444 2445
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2446 2447
    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
2448
        goto cleanup;
2449

2450
    VIR_INFO("Saving state to %s", name);
2451 2452

    compressed = QEMUD_SAVE_FORMAT_RAW;
2453
    ret = qemudDomainSaveFlag(driver, dom, vm, name, compressed);
2454
    vm = NULL;
2455 2456 2457 2458 2459

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
2460 2461 2462
    VIR_FREE(name);

    return ret;
2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
}

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

2473
    virCheckFlags(0, -1);
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506

    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;

2507
    virCheckFlags(0, -1);
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531

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

2533 2534 2535 2536 2537
static int
doCoreDump(struct qemud_driver *driver,
           virDomainObjPtr vm,
           const char *path,
           enum qemud_save_formats compress)
H
Hu Tao 已提交
2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548
{
    int fd = -1;
    int ret = -1;

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

2549
    if (qemuMigrationToFile(driver, vm, fd, 0, path,
2550 2551 2552
                            qemuCompressProgramName(compress), true, false) < 0)
        goto cleanup;

H
Hu Tao 已提交
2553 2554 2555 2556 2557 2558 2559
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno,
                             _("unable to save file %s"),
                             path);
        goto cleanup;
    }

2560
    ret = 0;
H
Hu Tao 已提交
2561 2562

cleanup:
2563
    VIR_FORCE_CLOSE(fd);
H
Hu Tao 已提交
2564 2565 2566 2567 2568
    if (ret != 0)
        unlink(path);
    return ret;
}

2569 2570 2571 2572 2573
static enum qemud_save_formats
getCompressionType(struct qemud_driver *driver)
{
    int compress = QEMUD_SAVE_FORMAT_RAW;

2574 2575 2576 2577 2578 2579 2580
    /*
     * We reuse "save" flag for "dump" here. Then, we can support the same
     * format in "save" and "dump".
     */
    if (driver->dumpImageFormat) {
        compress = qemudSaveCompressionTypeFromString(driver->dumpImageFormat);
        if (compress < 0) {
2581 2582 2583 2584
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("Invalid dump image format specified in "
                              "configuration file, using raw"));
            return QEMUD_SAVE_FORMAT_RAW;
2585
        }
2586 2587 2588
        if (!qemudCompressProgramAvailable(compress)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Compression program for dump image format "
2589 2590 2591
                                    "in configuration file isn't available, "
                                    "using raw"));
            return QEMUD_SAVE_FORMAT_RAW;
2592
        }
2593
    }
2594 2595 2596 2597 2598
    return compress;
}

static int qemudDomainCoreDump(virDomainPtr dom,
                               const char *path,
2599
                               unsigned int flags)
2600
{
2601 2602 2603
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int resume = 0, paused = 0;
H
Hu Tao 已提交
2604
    int ret = -1;
2605 2606
    virDomainEventPtr event = NULL;

2607 2608
    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

P
Paolo Bonzini 已提交
2609 2610 2611 2612 2613 2614
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2615 2616
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
P
Paolo Bonzini 已提交
2617 2618 2619
        goto cleanup;
    }

2620 2621
    if (qemuDomainObjBeginAsyncJobWithDriver(driver, vm,
                                             QEMU_ASYNC_JOB_DUMP) < 0)
2622 2623
        goto cleanup;

D
Daniel P. Berrange 已提交
2624
    if (!virDomainObjIsActive(vm)) {
2625 2626
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
2627
        goto endjob;
P
Paolo Bonzini 已提交
2628 2629
    }

P
Paolo Bonzini 已提交
2630 2631
    /* Migrate will always stop the VM, so the resume condition is
       independent of whether the stop command is issued.  */
J
Jiri Denemark 已提交
2632
    resume = virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING;
P
Paolo Bonzini 已提交
2633 2634

    /* Pause domain for non-live dump */
J
Jiri Denemark 已提交
2635 2636 2637
    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_DUMP) < 0)
2638
            goto endjob;
P
Paolo Bonzini 已提交
2639
        paused = 1;
2640 2641 2642 2643 2644 2645

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

H
Hu Tao 已提交
2648
    ret = doCoreDump(driver, vm, path, getCompressionType(driver));
2649 2650 2651 2652
    if (ret < 0)
        goto endjob;

    paused = 1;
2653 2654

endjob:
2655
    if ((ret == 0) && (flags & VIR_DUMP_CRASH)) {
J
Jiri Denemark 已提交
2656
        qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_CRASHED);
2657
        virDomainAuditStop(vm, "crashed");
2658 2659 2660 2661 2662
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
    }

P
Paolo Bonzini 已提交
2663 2664 2665
    /* 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.  */
2666
    else if (resume && paused && virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
2667 2668
        if (qemuProcessStartCPUs(driver, vm, dom->conn,
                                 VIR_DOMAIN_RUNNING_UNPAUSED) < 0) {
2669
            if (virGetLastError() == NULL)
2670 2671
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("resuming after dump failed"));
P
Paolo Bonzini 已提交
2672 2673
        }
    }
2674

2675
    if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
2676
        vm = NULL;
2677
    else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
2678 2679 2680 2681
        virDomainRemoveInactive(&driver->domains,
                                vm);
        vm = NULL;
    }
2682 2683

cleanup:
P
Paolo Bonzini 已提交
2684 2685
    if (vm)
        virDomainObjUnlock(vm);
2686 2687
    if (event)
        qemuDomainEventQueue(driver, event);
2688
    qemuDriverUnlock(driver);
P
Paolo Bonzini 已提交
2689 2690 2691
    return ret;
}

2692 2693 2694 2695
static char *
qemuDomainScreenshot(virDomainPtr dom,
                     virStreamPtr st,
                     unsigned int screen,
E
Eric Blake 已提交
2696
                     unsigned int flags)
2697 2698 2699 2700 2701 2702 2703 2704
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    char *tmp = NULL;
    int tmp_fd = -1;
    char *ret = NULL;

E
Eric Blake 已提交
2705 2706
    virCheckFlags(0, NULL);

2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
    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;

2721
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748
        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;
    }

2749 2750
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm, tmp);

2751
    ignore_value(qemuDomainObjEnterMonitor(driver, vm));
2752
    if (qemuMonitorScreendump(priv->mon, tmp) < 0) {
2753
        qemuDomainObjExitMonitor(driver, vm);
2754 2755
        goto endjob;
    }
2756
    qemuDomainObjExitMonitor(driver, vm);
2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774

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

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

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

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

2775
    if (qemuDomainObjEndJob(driver, vm) == 0)
2776 2777 2778 2779 2780 2781 2782 2783
        vm = NULL;

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

H
Hu Tao 已提交
2784 2785 2786
static void processWatchdogEvent(void *data, void *opaque)
{
    int ret;
2787
    struct qemuDomainWatchdogEvent *wdEvent = data;
H
Hu Tao 已提交
2788 2789
    struct qemud_driver *driver = opaque;

W
Wen Congyang 已提交
2790 2791 2792
    qemuDriverLock(driver);
    virDomainObjLock(wdEvent->vm);

H
Hu Tao 已提交
2793 2794 2795 2796 2797
    switch (wdEvent->action) {
    case VIR_DOMAIN_WATCHDOG_ACTION_DUMP:
        {
            char *dumpfile;

E
Eric Blake 已提交
2798
            if (virAsprintf(&dumpfile, "%s/%s-%u",
H
Hu Tao 已提交
2799 2800
                            driver->autoDumpPath,
                            wdEvent->vm->def->name,
E
Eric Blake 已提交
2801 2802
                            (unsigned int)time(NULL)) < 0) {
                virReportOOMError();
W
Wen Congyang 已提交
2803
                goto unlock;
E
Eric Blake 已提交
2804
            }
H
Hu Tao 已提交
2805

2806 2807
            if (qemuDomainObjBeginAsyncJobWithDriver(driver, wdEvent->vm,
                                                     QEMU_ASYNC_JOB_DUMP) < 0) {
W
Wen Congyang 已提交
2808 2809 2810
                VIR_FREE(dumpfile);
                goto unlock;
            }
H
Hu Tao 已提交
2811 2812 2813 2814

            if (!virDomainObjIsActive(wdEvent->vm)) {
                qemuReportError(VIR_ERR_OPERATION_INVALID,
                                "%s", _("domain is not running"));
W
Wen Congyang 已提交
2815 2816
                VIR_FREE(dumpfile);
                goto endjob;
H
Hu Tao 已提交
2817 2818 2819 2820 2821 2822 2823 2824 2825 2826
            }

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

J
Jiri Denemark 已提交
2827 2828
            ret = qemuProcessStartCPUs(driver, wdEvent->vm, NULL,
                                       VIR_DOMAIN_RUNNING_UNPAUSED);
H
Hu Tao 已提交
2829 2830 2831 2832 2833 2834 2835 2836

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

            VIR_FREE(dumpfile);
        }
        break;
W
Wen Congyang 已提交
2837 2838
    default:
        goto unlock;
H
Hu Tao 已提交
2839 2840
    }

W
Wen Congyang 已提交
2841 2842 2843 2844
endjob:
    /* Safe to ignore value since ref count was incremented in
     * qemuProcessHandleWatchdog().
     */
2845
    ignore_value(qemuDomainObjEndAsyncJob(driver, wdEvent->vm));
W
Wen Congyang 已提交
2846 2847 2848 2849 2850

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

2854 2855 2856
static int qemudDomainHotplugVcpus(struct qemud_driver *driver,
                                   virDomainObjPtr vm,
                                   unsigned int nvcpus)
2857 2858
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2859
    int i, rc = 1;
2860
    int ret = -1;
2861
    int oldvcpus = vm->def->vcpus;
E
Eric Blake 已提交
2862
    int vcpus = oldvcpus;
2863

2864
    ignore_value(qemuDomainObjEnterMonitor(driver, vm));
2865

2866 2867 2868
    /* 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 已提交
2869 2870
    if (nvcpus > vcpus) {
        for (i = vcpus ; i < nvcpus ; i++) {
2871 2872 2873 2874 2875 2876 2877
            /* Online new CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 1);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
2878
            vcpus++;
2879 2880
        }
    } else {
E
Eric Blake 已提交
2881
        for (i = vcpus - 1 ; i >= nvcpus ; i--) {
2882 2883 2884 2885 2886 2887 2888
            /* Offline old CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 0);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
2889
            vcpus--;
2890 2891 2892 2893 2894 2895
        }
    }

    ret = 0;

cleanup:
2896
    qemuDomainObjExitMonitor(driver, vm);
E
Eric Blake 已提交
2897
    vm->def->vcpus = vcpus;
2898
    virDomainAuditVcpu(vm, oldvcpus, nvcpus, "update", rc == 1);
2899 2900 2901 2902 2903 2904 2905 2906 2907
    return ret;

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


2908
static int
2909 2910
qemuDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                        unsigned int flags)
2911
{
2912 2913
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2914
    virDomainDefPtr persistentDef;
2915 2916
    const char * type;
    int max;
2917
    int ret = -1;
2918 2919
    bool isActive;
    bool maximum;
2920

2921 2922
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
2923 2924 2925 2926 2927
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

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

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

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

2943
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
2944 2945
        goto cleanup;

2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964
    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)) {
2965 2966
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("domain is not running"));
2967
        goto endjob;
2968 2969
    }

2970
    if (!vm->persistent && (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
2971 2972 2973 2974 2975
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot change persistent config of a transient domain"));
        goto endjob;
    }

2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988
    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;
    }

2989
    if (!maximum && vm->def->maxvcpus < max) {
2990 2991 2992
        max = vm->def->maxvcpus;
    }

2993 2994 2995 2996 2997 2998 2999
    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;
    }

3000 3001 3002
    if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
        goto endjob;

3003
    switch (flags) {
3004
    case VIR_DOMAIN_AFFECT_CONFIG:
3005 3006 3007 3008 3009 3010 3011
        if (maximum) {
            persistentDef->maxvcpus = nvcpus;
            if (nvcpus < persistentDef->vcpus)
                persistentDef->vcpus = nvcpus;
        } else {
            persistentDef->vcpus = nvcpus;
        }
3012 3013 3014
        ret = 0;
        break;

3015
    case VIR_DOMAIN_AFFECT_LIVE:
3016
        ret = qemudDomainHotplugVcpus(driver, vm, nvcpus);
3017 3018
        break;

3019
    case VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG:
3020
        ret = qemudDomainHotplugVcpus(driver, vm, nvcpus);
3021 3022 3023
        if (ret == 0) {
            persistentDef->vcpus = nvcpus;
        }
3024 3025
        break;
    }
3026

3027
    /* Save the persistent config to disk */
3028
    if (flags & VIR_DOMAIN_AFFECT_CONFIG)
3029 3030
        ret = virDomainSaveConfig(driver->configDir, persistentDef);

3031
endjob:
3032
    if (qemuDomainObjEndJob(driver, vm) == 0)
3033
        vm = NULL;
3034

3035
cleanup:
3036 3037
    if (vm)
        virDomainObjUnlock(vm);
3038
    return ret;
3039 3040
}

3041
static int
3042
qemuDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
3043
{
3044
    return qemuDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
3045 3046
}

3047 3048

static int
3049 3050 3051 3052 3053 3054
qemudDomainPinVcpuFlags(virDomainPtr dom,
                        unsigned int vcpu,
                        unsigned char *cpumap,
                        int maplen,
                        unsigned int flags) {

3055 3056
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3057
    virDomainDefPtr persistentDef = NULL;
3058
    int maxcpu, hostcpus;
3059
    virNodeInfo nodeinfo;
3060
    int ret = -1;
3061
    bool isActive;
3062
    qemuDomainObjPrivatePtr priv;
3063
    bool canResetting = true;
E
Eric Blake 已提交
3064
    int pcpu;
3065

3066 3067 3068
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

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

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

3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092
    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"));
3093
        goto cleanup;
3094 3095
    }

3096 3097 3098
    priv = vm->privateData;

    if (vcpu > (priv->nvcpupids-1)) {
3099 3100 3101
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("vcpu number out of range %d > %d"),
                        vcpu, priv->nvcpupids);
3102
        goto cleanup;
3103 3104
    }

3105 3106 3107 3108 3109 3110 3111 3112 3113
    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;
    }
3114

3115 3116 3117 3118 3119 3120 3121 3122 3123
    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 已提交
3124
    for (pcpu = 0; pcpu < hostcpus; pcpu++) {
3125 3126 3127 3128 3129
        if ((cpumap[pcpu/8] & (1 << (pcpu % 8))) == 0) {
            canResetting = false;
            break;
        }
    }
3130

3131
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142

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

3143
        if (canResetting) {
E
Eric Blake 已提交
3144
            if (virDomainVcpuPinDel(vm->def, vcpu) < 0) {
3145 3146 3147 3148 3149 3150
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to delete vcpupin xml of "
                                  "a running domain"));
                goto cleanup;
            }
        } else {
E
Eric Blake 已提交
3151
            if (virDomainVcpuPinAdd(vm->def, cpumap, maplen, vcpu) < 0) {
3152 3153 3154 3155 3156
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to update or add vcpupin xml of "
                                  "a running domain"));
                goto cleanup;
            }
3157 3158
        }

3159 3160
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
            goto cleanup;
3161
    }
3162

3163 3164
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {

3165
        if (canResetting) {
E
Eric Blake 已提交
3166
            if (virDomainVcpuPinDel(persistentDef, vcpu) < 0) {
3167 3168 3169 3170 3171 3172
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to delete vcpupin xml of "
                                  "a persistent domain"));
                goto cleanup;
            }
        } else {
E
Eric Blake 已提交
3173
            if (virDomainVcpuPinAdd(persistentDef, cpumap, maplen, vcpu) < 0) {
3174 3175 3176 3177 3178
                qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("failed to update or add vcpupin xml of "
                                  "a persistent domain"));
                goto cleanup;
            }
3179
        }
3180

3181
        ret = virDomainSaveConfig(driver->configDir, persistentDef);
3182 3183 3184
        goto cleanup;
    }

3185
    ret = 0;
3186

3187
cleanup:
3188 3189
    if (vm)
        virDomainObjUnlock(vm);
3190
    return ret;
3191 3192
}

3193 3194 3195 3196 3197 3198 3199 3200 3201
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
    return qemudDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

3202
static int
E
Eric Blake 已提交
3203
qemudDomainGetVcpuPinInfo(virDomainPtr dom,
3204 3205 3206 3207 3208 3209
                          int ncpumaps,
                          unsigned char *cpumaps,
                          int maplen,
                          unsigned int flags) {

    struct qemud_driver *driver = dom->conn->privateData;
E
Eric Blake 已提交
3210
    virDomainObjPtr vm = NULL;
3211 3212 3213 3214 3215 3216
    virNodeInfo nodeinfo;
    virDomainDefPtr targetDef = NULL;
    int ret = -1;
    bool isActive;
    int maxcpu, hostcpus, vcpu, pcpu;
    int n;
E
Eric Blake 已提交
3217
    virDomainVcpuPinDefPtr *vcpupin_list;
3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312
    char *cpumask = NULL;
    unsigned char *cpumap;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

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

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

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

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

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

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

    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
        goto cleanup;
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
    maxcpu = maplen * 8;
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;

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

    if (ncpumaps < 1) {
        goto cleanup;
    }

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

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

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

3313 3314 3315 3316 3317 3318
static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
3319 3320
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3321
    virNodeInfo nodeinfo;
3322
    int i, v, maxcpu, hostcpus;
3323
    int ret = -1;
3324
    qemuDomainObjPrivatePtr priv;
3325

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

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

D
Daniel P. Berrange 已提交
3338
    if (!virDomainObjIsActive(vm)) {
3339 3340 3341
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s",
                        _("cannot list vcpu pinning for an inactive domain"));
3342
        goto cleanup;
3343 3344
    }

3345 3346
    priv = vm->privateData;

3347
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
3348
        goto cleanup;
3349

3350
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
3351
    maxcpu = maplen * 8;
3352 3353
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
3354 3355

    /* Clamp to actual number of vcpus */
3356 3357
    if (maxinfo > priv->nvcpupids)
        maxinfo = priv->nvcpupids;
3358

3359 3360 3361 3362 3363 3364
    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;
3365

3366
                if (priv->vcpupids != NULL &&
3367 3368 3369
                    qemudGetProcessInfo(&(info[i].cpuTime),
                                        &(info[i].cpu),
                                        vm->pid,
3370
                                        priv->vcpupids[i]) < 0) {
3371
                    virReportSystemError(errno, "%s",
3372 3373 3374
                                         _("cannot get vCPU placement & pCPU time"));
                    goto cleanup;
                }
3375
            }
3376 3377
        }

3378 3379
        if (cpumaps != NULL) {
            memset(cpumaps, 0, maplen * maxinfo);
3380
            if (priv->vcpupids != NULL) {
3381 3382 3383
                for (v = 0 ; v < maxinfo ; v++) {
                    unsigned char *cpumap = VIR_GET_CPUMAP(cpumaps, maplen, v);

3384
                    if (virProcessInfoGetAffinity(priv->vcpupids[v],
3385
                                                  cpumap, maplen, maxcpu) < 0)
3386
                        goto cleanup;
3387
                }
3388
            } else {
3389 3390
                qemuReportError(VIR_ERR_NO_SUPPORT,
                                "%s", _("cpu affinity is not available"));
3391
                goto cleanup;
3392 3393 3394
            }
        }
    }
3395
    ret = maxinfo;
3396

3397
cleanup:
3398 3399
    if (vm)
        virDomainObjUnlock(vm);
3400
    return ret;
3401 3402 3403
}


3404 3405 3406
static int
qemudDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
3407 3408
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3409
    virDomainDefPtr def;
3410
    int ret = -1;
3411

3412 3413
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
3414 3415 3416
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

    /* Exactly one of LIVE or CONFIG must be set.  */
3417
    if (!(flags & VIR_DOMAIN_AFFECT_LIVE) == !(flags & VIR_DOMAIN_AFFECT_CONFIG)) {
3418 3419
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid flag combination: (0x%x)"), flags);
3420 3421 3422
        return -1;
    }

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

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

3435
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
3436 3437 3438 3439 3440 3441 3442 3443
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("domain not active"));
            goto cleanup;
        }
        def = vm->def;
    } else {
        def = vm->newDef ? vm->newDef : vm->def;
3444 3445
    }

3446
    ret = (flags & VIR_DOMAIN_VCPU_MAXIMUM) ? def->maxvcpus : def->vcpus;
3447

3448
cleanup:
3449 3450
    if (vm)
        virDomainObjUnlock(vm);
3451 3452 3453
    return ret;
}

3454 3455 3456
static int
qemudDomainGetMaxVcpus(virDomainPtr dom)
{
3457
    return qemudDomainGetVcpusFlags(dom, (VIR_DOMAIN_AFFECT_LIVE |
3458 3459 3460
                                          VIR_DOMAIN_VCPU_MAXIMUM));
}

3461 3462 3463 3464 3465 3466 3467 3468 3469
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);

3470 3471
    memset(seclabel, 0, sizeof(*seclabel));

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

3480
    if (!virDomainVirtTypeToString(vm->def->virtType)) {
3481 3482 3483
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unknown virt type in domain definition '%d'"),
                        vm->def->virtType);
3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500
        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 已提交
3501
    if (virDomainObjIsActive(vm)) {
3502 3503
        if (virSecurityManagerGetProcessLabel(driver->securityManager,
                                              vm, seclabel) < 0) {
3504 3505 3506
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("Failed to get security label"));
            goto cleanup;
3507 3508 3509 3510 3511 3512 3513 3514
        }
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
3515
    qemuDriverUnlock(driver);
3516 3517 3518
    return ret;
}

3519 3520
static int qemudNodeGetSecurityModel(virConnectPtr conn,
                                     virSecurityModelPtr secmodel)
3521 3522 3523
{
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
    char *p;
3524
    int ret = 0;
3525

3526
    qemuDriverLock(driver);
3527 3528 3529 3530 3531
    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)
3532
        goto cleanup;
3533

3534 3535
    p = driver->caps->host.secModel.model;
    if (strlen(p) >= VIR_SECURITY_MODEL_BUFLEN-1) {
3536 3537 3538
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security model string exceeds max %d bytes"),
                        VIR_SECURITY_MODEL_BUFLEN-1);
3539 3540
        ret = -1;
        goto cleanup;
3541 3542 3543 3544 3545
    }
    strcpy(secmodel->model, p);

    p = driver->caps->host.secModel.doi;
    if (strlen(p) >= VIR_SECURITY_DOI_BUFLEN-1) {
3546 3547 3548
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security DOI string exceeds max %d bytes"),
                        VIR_SECURITY_DOI_BUFLEN-1);
3549 3550
        ret = -1;
        goto cleanup;
3551 3552
    }
    strcpy(secmodel->doi, p);
3553 3554 3555 3556

cleanup:
    qemuDriverUnlock(driver);
    return ret;
3557 3558
}

3559 3560 3561 3562 3563
static int ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4)
qemuDomainSaveImageOpen(struct qemud_driver *driver,
                        const char *path,
                        virDomainDefPtr *ret_def,
                        struct qemud_save_header *ret_header)
J
Jiri Denemark 已提交
3564 3565
{
    int fd;
3566
    struct qemud_save_header header;
J
Jiri Denemark 已提交
3567 3568
    char *xml = NULL;
    virDomainDefPtr def = NULL;
3569

3570 3571 3572
    if ((fd = virFileOpenAs(path, O_RDONLY, 0, getuid(), getgid(), 0)) < 0) {
        if ((fd != -EACCES && fd != -EPERM) ||
            driver->user == getuid()) {
3573 3574
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("cannot read domain image"));
J
Jiri Denemark 已提交
3575
            goto error;
3576 3577 3578
        }

        /* Opening as root failed, but qemu runs as a different user
3579 3580 3581 3582 3583 3584
         * that might have better luck. */
        if ((fd = virFileOpenAs(path, O_RDONLY, 0,
                                driver->user, driver->group,
                                VIR_FILE_OPEN_AS_UID)) < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("cannot read domain image"));
J
Jiri Denemark 已提交
3585
            goto error;
3586
        }
3587 3588 3589
    }

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
3590 3591
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read qemu header"));
J
Jiri Denemark 已提交
3592
        goto error;
3593 3594 3595
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
3596 3597
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("image magic is incorrect"));
J
Jiri Denemark 已提交
3598
        goto error;
3599 3600 3601
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3602 3603 3604 3605 3606
        /* convert endianess and try again */
        bswap_header(&header);
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3607 3608 3609
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("image version is not supported (%d > %d)"),
                        header.version, QEMUD_SAVE_VERSION);
J
Jiri Denemark 已提交
3610
        goto error;
3611 3612
    }

3613 3614 3615
    if (header.xml_len <= 0) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("invalid XML length: %d"), header.xml_len);
J
Jiri Denemark 已提交
3616
        goto error;
3617 3618
    }

3619 3620
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
        virReportOOMError();
J
Jiri Denemark 已提交
3621
        goto error;
3622 3623 3624
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
3625 3626
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read XML"));
J
Jiri Denemark 已提交
3627
        goto error;
3628 3629 3630
    }

    /* Create a domain from this XML */
3631
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
3632
                                        QEMU_EXPECTED_VIRT_TYPES,
3633
                                        VIR_DOMAIN_XML_INACTIVE)))
J
Jiri Denemark 已提交
3634
        goto error;
3635

J
Jiri Denemark 已提交
3636
    VIR_FREE(xml);
3637

J
Jiri Denemark 已提交
3638 3639
    *ret_def = def;
    *ret_header = header;
3640

J
Jiri Denemark 已提交
3641
    return fd;
3642

J
Jiri Denemark 已提交
3643 3644 3645
error:
    virDomainDefFree(def);
    VIR_FREE(xml);
3646
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
3647 3648 3649 3650

    return -1;
}

3651 3652 3653 3654 3655 3656 3657
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 已提交
3658 3659 3660 3661
{
    int ret = -1;
    virDomainEventPtr event;
    int intermediatefd = -1;
3662
    virCommandPtr cmd = NULL;
J
Jiri Denemark 已提交
3663 3664 3665

    if (header->version == 2) {
        const char *prog = qemudSaveCompressionTypeToString(header->compressed);
3666
        if (prog == NULL) {
3667 3668
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("Invalid compressed save format %d"),
J
Jiri Denemark 已提交
3669 3670
                            header->compressed);
            goto out;
3671
        }
3672

J
Jiri Denemark 已提交
3673
        if (header->compressed != QEMUD_SAVE_FORMAT_RAW) {
3674
            cmd = virCommandNewArgList(prog, "-dc", NULL);
3675 3676
            intermediatefd = *fd;
            *fd = -1;
3677 3678 3679 3680 3681

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

            if (virCommandRunAsync(cmd, NULL) < 0) {
3682 3683
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Failed to start decompression binary %s"),
3684
                                prog);
3685
                *fd = intermediatefd;
J
Jiri Denemark 已提交
3686
                goto out;
3687 3688 3689
            }
        }
    }
J
Jiri Denemark 已提交
3690

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

3695
    if (intermediatefd != -1) {
3696
        if (ret < 0) {
3697 3698 3699
            /* if there was an error setting up qemu, the intermediate
             * process will wait forever to write to stdout, so we
             * must manually kill it.
3700 3701
             */
            VIR_FORCE_CLOSE(intermediatefd);
3702
            VIR_FORCE_CLOSE(*fd);
3703 3704
        }

3705 3706
        if (virCommandWait(cmd, NULL) < 0)
            ret = -1;
3707
    }
3708
    VIR_FORCE_CLOSE(intermediatefd);
J
Jiri Denemark 已提交
3709

3710 3711 3712
    if (VIR_CLOSE(*fd) < 0) {
        virReportSystemError(errno, _("cannot close file: %s"), path);
        ret = -1;
3713
    }
J
Jiri Denemark 已提交
3714

3715
    if (ret < 0) {
3716
        virDomainAuditStart(vm, "restored", false);
J
Jiri Denemark 已提交
3717
        goto out;
3718
    }
3719

3720 3721 3722
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
3723
    virDomainAuditStart(vm, "restored", true);
J
Jiri Denemark 已提交
3724 3725 3726
    if (event)
        qemuDomainEventQueue(driver, event);

3727

3728
    /* If it was running before, resume it now. */
J
Jiri Denemark 已提交
3729
    if (header->was_running) {
J
Jiri Denemark 已提交
3730 3731
        if (qemuProcessStartCPUs(driver, vm, conn,
                                 VIR_DOMAIN_RUNNING_RESTORED) < 0) {
3732
            if (virGetLastError() == NULL)
3733 3734
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("failed to resume domain"));
J
Jiri Denemark 已提交
3735
            goto out;
3736
        }
3737 3738
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
J
Jiri Denemark 已提交
3739
            goto out;
3740
        }
3741
    }
J
Jiri Denemark 已提交
3742

3743
    ret = 0;
3744

J
Jiri Denemark 已提交
3745
out:
3746
    virCommandFree(cmd);
3747 3748
    if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
                                                 vm, path) < 0)
3749 3750
        VIR_WARN("failed to restore save state label on %s", path);

J
Jiri Denemark 已提交
3751 3752 3753
    return ret;
}

3754 3755 3756 3757
static int
qemuDomainRestore(virConnectPtr conn,
                  const char *path)
{
J
Jiri Denemark 已提交
3758 3759 3760 3761 3762 3763 3764 3765 3766
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    int fd = -1;
    int ret = -1;
    struct qemud_save_header header;

    qemuDriverLock(driver);

3767
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header);
J
Jiri Denemark 已提交
3768 3769 3770 3771 3772 3773 3774 3775 3776
    if (fd < 0)
        goto cleanup;

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

    if (!(vm = virDomainAssignDef(driver->caps,
                                  &driver->domains,
                                  def, true))) {
3777
        /* virDomainAssignDef already set the error */
J
Jiri Denemark 已提交
3778 3779 3780 3781
        goto cleanup;
    }
    def = NULL;

3782
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
J
Jiri Denemark 已提交
3783 3784
        goto cleanup;

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

3787
    if (qemuDomainObjEndJob(driver, vm) == 0)
3788
        vm = NULL;
J
Jiri Denemark 已提交
3789 3790 3791 3792
    else if (ret < 0 && !vm->persistent) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }
3793

3794 3795
cleanup:
    virDomainDefFree(def);
3796
    VIR_FORCE_CLOSE(fd);
3797 3798 3799
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
3800
    return ret;
D
Daniel P. Berrange 已提交
3801 3802
}

3803 3804 3805 3806 3807
static int
qemuDomainObjRestore(virConnectPtr conn,
                     struct qemud_driver *driver,
                     virDomainObjPtr vm,
                     const char *path)
J
Jiri Denemark 已提交
3808 3809 3810 3811 3812 3813
{
    virDomainDefPtr def = NULL;
    int fd = -1;
    int ret = -1;
    struct qemud_save_header header;

3814
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header);
J
Jiri Denemark 已提交
3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834
    if (fd < 0)
        goto cleanup;

    if (STRNEQ(vm->def->name, def->name) ||
        memcmp(vm->def->uuid, def->uuid, VIR_UUID_BUFLEN)) {
        char vm_uuidstr[VIR_UUID_STRING_BUFLEN];
        char def_uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(vm->def->uuid, vm_uuidstr);
        virUUIDFormat(def->uuid, def_uuidstr);
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("cannot restore domain '%s' uuid %s from a file"
                          " which belongs to domain '%s' uuid %s"),
                        vm->def->name, vm_uuidstr,
                        def->name, def_uuidstr);
        goto cleanup;
    }

    virDomainObjAssignDef(vm, def, true);
    def = NULL;

3835
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path);
J
Jiri Denemark 已提交
3836 3837 3838

cleanup:
    virDomainDefFree(def);
3839
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
3840 3841 3842
    return ret;
}

D
Daniel P. Berrange 已提交
3843

3844
static char *qemuDomainGetXMLDesc(virDomainPtr dom,
3845 3846
                                  unsigned int flags)
{
3847 3848 3849
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;
3850 3851
    unsigned long balloon;
    int err;
3852

3853
    /* Flags checked by virDomainDefFormat */
3854

3855
    qemuDriverLock(driver);
3856
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3857

D
Daniel P. Berrange 已提交
3858
    if (!vm) {
3859 3860
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3861 3862
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
3863
        goto cleanup;
D
Daniel P. Berrange 已提交
3864 3865
    }

3866 3867 3868 3869
    /* 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))) {
3870
        qemuDomainObjPrivatePtr priv = vm->privateData;
3871 3872
        /* Don't delay if someone's using the monitor, just use
         * existing most recent data instead */
3873
        if (!priv->job.active) {
3874
            if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_QUERY) < 0)
3875 3876
                goto cleanup;

3877
            ignore_value(qemuDomainObjEnterMonitorWithDriver(driver, vm));
3878
            err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
3879
            qemuDomainObjExitMonitorWithDriver(driver, vm);
3880
            if (qemuDomainObjEndJob(driver, vm) == 0) {
3881 3882 3883
                vm = NULL;
                goto cleanup;
            }
3884 3885 3886
            if (err < 0)
                goto cleanup;
            if (err > 0)
3887
                vm->def->mem.cur_balloon = balloon;
3888 3889
            /* err == 0 indicates no balloon support, so ignore it */
        }
3890
    }
3891

3892
    ret = qemuDomainFormatXML(driver, vm, flags);
3893 3894

cleanup:
3895 3896
    if (vm)
        virDomainObjUnlock(vm);
3897
    qemuDriverUnlock(driver);
3898
    return ret;
D
Daniel P. Berrange 已提交
3899 3900 3901
}


3902 3903 3904
static char *qemuDomainXMLFromNative(virConnectPtr conn,
                                     const char *format,
                                     const char *config,
E
Eric Blake 已提交
3905 3906
                                     unsigned int flags)
{
3907
    struct qemud_driver *driver = conn->privateData;
3908 3909 3910
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
3911 3912
    virCheckFlags(0, NULL);

3913
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
3914 3915
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
3916 3917 3918
        goto cleanup;
    }

3919
    qemuDriverLock(driver);
3920 3921
    def = qemuParseCommandLineString(driver->caps, config,
                                     NULL, NULL, NULL);
3922
    qemuDriverUnlock(driver);
3923 3924 3925
    if (!def)
        goto cleanup;

3926 3927 3928 3929 3930 3931
    if (!def->name &&
        !(def->name = strdup("unnamed"))) {
        virReportOOMError();
        goto cleanup;
    }

3932
    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
3933 3934 3935 3936 3937 3938

cleanup:
    virDomainDefFree(def);
    return xml;
}

3939 3940 3941
static char *qemuDomainXMLToNative(virConnectPtr conn,
                                   const char *format,
                                   const char *xmlData,
E
Eric Blake 已提交
3942 3943
                                   unsigned int flags)
{
3944 3945
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
3946
    virDomainChrSourceDef monConfig;
3947
    virBitmapPtr qemuCaps = NULL;
E
Eric Blake 已提交
3948
    virCommandPtr cmd = NULL;
3949 3950 3951
    char *ret = NULL;
    int i;

E
Eric Blake 已提交
3952 3953
    virCheckFlags(0, NULL);

3954 3955
    qemuDriverLock(driver);

3956
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
3957 3958
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
3959 3960 3961
        goto cleanup;
    }

M
Matthias Bolte 已提交
3962 3963
    def = virDomainDefParseString(driver->caps, xmlData,
                                  QEMU_EXPECTED_VIRT_TYPES, 0);
3964 3965 3966
    if (!def)
        goto cleanup;

3967 3968
    /* Since we're just exporting args, we can't do bridge/network/direct
     * setups, since libvirt will normally create TAP/macvtap devices
3969 3970 3971 3972 3973
     * 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];
3974
        int bootIndex = net->bootIndex;
3975 3976
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK ||
            net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996
            VIR_FREE(net->data.network.name);

            memset(net, 0, sizeof *net);

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
            net->data.ethernet.dev = NULL;
            net->data.ethernet.script = NULL;
            net->data.ethernet.ipaddr = NULL;
        } else if (net->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
            char *brname = net->data.bridge.brname;
            char *script = net->data.bridge.script;
            char *ipaddr = net->data.bridge.ipaddr;

            memset(net, 0, sizeof *net);

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
            net->data.ethernet.dev = brname;
            net->data.ethernet.script = script;
            net->data.ethernet.ipaddr = ipaddr;
        }
3997
        net->bootIndex = bootIndex;
3998 3999 4000 4001
    }
    for (i = 0 ; i < def->ngraphics ; i++) {
        if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
            def->graphics[i]->data.vnc.autoport)
4002
            def->graphics[i]->data.vnc.port = QEMU_VNC_PORT_MIN;
4003 4004
    }

4005
    if (qemuCapsExtractVersionInfo(def->emulator, def->os.arch,
4006
                                   NULL,
4007
                                   &qemuCaps) < 0)
4008 4009
        goto cleanup;

4010
    if (qemuProcessPrepareMonitorChr(driver, &monConfig, def->name) < 0)
4011
        goto cleanup;
4012

4013
    if (!(cmd = qemuBuildCommandLine(conn, driver, def,
4014
                                     &monConfig, false, qemuCaps,
4015
                                     NULL, -1, NULL, VIR_VM_OP_NO_OP)))
4016 4017
        goto cleanup;

E
Eric Blake 已提交
4018
    ret = virCommandToString(cmd);
4019 4020

cleanup:
4021
    qemuDriverUnlock(driver);
4022

4023
    qemuCapsFree(qemuCaps);
E
Eric Blake 已提交
4024
    virCommandFree(cmd);
4025 4026 4027 4028 4029
    virDomainDefFree(def);
    return ret;
}


4030
static int qemudListDefinedDomains(virConnectPtr conn,
4031
                            char **const names, int nnames) {
4032
    struct qemud_driver *driver = conn->privateData;
4033
    int n;
4034

4035
    qemuDriverLock(driver);
4036
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
4037
    qemuDriverUnlock(driver);
4038
    return n;
D
Daniel P. Berrange 已提交
4039 4040
}

4041
static int qemudNumDefinedDomains(virConnectPtr conn) {
4042
    struct qemud_driver *driver = conn->privateData;
4043
    int n;
4044

4045
    qemuDriverLock(driver);
4046
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
4047
    qemuDriverUnlock(driver);
4048

4049
    return n;
D
Daniel P. Berrange 已提交
4050 4051 4052
}


J
Jiri Denemark 已提交
4053 4054
static int qemudDomainObjStart(virConnectPtr conn,
                               struct qemud_driver *driver,
4055
                               virDomainObjPtr vm,
4056 4057
                               bool start_paused,
                               bool autodestroy)
J
Jiri Denemark 已提交
4058 4059 4060 4061 4062 4063
{
    int ret = -1;
    char *managed_save;

    /*
     * If there is a managed saved state restore it instead of starting
4064
     * from scratch. The old state is removed once the restoring succeeded.
J
Jiri Denemark 已提交
4065 4066
     */
    managed_save = qemuDomainManagedSavePath(driver, vm);
4067 4068 4069 4070

    if (!managed_save)
        goto cleanup;

E
Eric Blake 已提交
4071
    if (virFileExists(managed_save)) {
4072
        ret = qemuDomainObjRestore(conn, driver, vm, managed_save);
J
Jiri Denemark 已提交
4073

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

4077
        goto cleanup;
J
Jiri Denemark 已提交
4078 4079
    }

4080
    ret = qemuProcessStart(conn, driver, vm, NULL, start_paused,
4081
                           autodestroy, -1, NULL, VIR_VM_OP_CREATE);
4082
    virDomainAuditStart(vm, "booted", ret >= 0);
4083
    if (ret >= 0) {
J
Jiri Denemark 已提交
4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096
        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;
}

4097 4098 4099
static int
qemudDomainStartWithFlags(virDomainPtr dom, unsigned int flags)
{
4100 4101 4102
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
4103

4104 4105
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
                  VIR_DOMAIN_START_AUTODESTROY, -1);
4106

4107
    qemuDriverLock(driver);
4108
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4109

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

4118
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
4119 4120 4121
        goto cleanup;

    if (virDomainObjIsActive(vm)) {
4122 4123
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is already running"));
4124 4125 4126
        goto endjob;
    }

4127 4128 4129 4130 4131 4132
    if (qemudDomainObjStart(dom->conn, driver, vm,
                            (flags & VIR_DOMAIN_START_PAUSED) != 0,
                            (flags & VIR_DOMAIN_START_AUTODESTROY) != 0) < 0)
        goto endjob;

    ret = 0;
4133

4134
endjob:
4135
    if (qemuDomainObjEndJob(driver, vm) == 0)
4136
        vm = NULL;
4137

4138
cleanup:
4139 4140
    if (vm)
        virDomainObjUnlock(vm);
4141
    qemuDriverUnlock(driver);
4142
    return ret;
D
Daniel P. Berrange 已提交
4143 4144
}

4145 4146 4147 4148 4149 4150
static int
qemudDomainStart(virDomainPtr dom)
{
    return qemudDomainStartWithFlags(dom, 0);
}

4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165
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;

4166
        if (def->os.machine && STRNEQ(def->os.machine, machine->name))
4167 4168 4169
            continue;

        if (!(*canonical = strdup(machine->canonical))) {
4170
            virReportOOMError();
4171 4172 4173 4174 4175 4176 4177 4178 4179
            return -1;
        }

        break;
    }

    return 0;
}

4180 4181 4182 4183 4184 4185
static int
qemudCanonicalizeMachineDirect(virDomainDefPtr def, char **canonical)
{
    virCapsGuestMachinePtr *machines = NULL;
    int i, nmachines = 0;

4186
    if (qemuCapsProbeMachineTypes(def->emulator, &machines, &nmachines) < 0)
4187 4188 4189 4190 4191 4192
        return -1;

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

4193
        if (def->os.machine && STRNEQ(def->os.machine, machines[i]->name))
4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205
            continue;

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

    virCapabilitiesFreeMachines(machines, nmachines);

    return 0;
}

4206 4207
int
qemudCanonicalizeMachine(struct qemud_driver *driver, virDomainDefPtr def)
4208 4209 4210 4211 4212 4213
{
    char *canonical = NULL;
    int i;

    for (i = 0; i < driver->caps->nguests; i++) {
        virCapsGuestPtr guest = driver->caps->guests[i];
4214
        virCapsGuestDomainInfoPtr info;
4215 4216 4217
        int j;

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

4220 4221 4222 4223 4224 4225 4226 4227 4228
            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;
4229 4230
        }

4231 4232 4233 4234
        info = &guest->arch.defaultInfo;

        if (info->emulator && STREQ(info->emulator, def->emulator)) {
            if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
4235 4236 4237 4238
                return -1;
            goto out;
        }
    }
4239 4240 4241 4242

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

4243 4244 4245 4246 4247 4248 4249
out:
    if (canonical) {
        VIR_FREE(def->os.machine);
        def->os.machine = canonical;
    }
    return 0;
}
D
Daniel P. Berrange 已提交
4250

4251
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
4252
    struct qemud_driver *driver = conn->privateData;
4253
    virDomainDefPtr def;
4254
    virDomainObjPtr vm = NULL;
4255
    virDomainPtr dom = NULL;
4256
    virDomainEventPtr event = NULL;
4257
    int dupVM;
4258

4259
    qemuDriverLock(driver);
4260
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
4261
                                        QEMU_EXPECTED_VIRT_TYPES,
4262
                                        VIR_DOMAIN_XML_INACTIVE)))
4263
        goto cleanup;
4264

4265
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
4266 4267
        goto cleanup;

4268 4269
    if ((dupVM = virDomainObjIsDuplicate(&driver->domains, def, 0)) < 0)
        goto cleanup;
4270

4271
    if (qemudCanonicalizeMachine(driver, def) < 0)
4272 4273
        goto cleanup;

4274
    if (qemuDomainAssignPCIAddresses(def) < 0)
4275 4276
        goto cleanup;

4277
    if (!(vm = virDomainAssignDef(driver->caps,
4278
                                  &driver->domains,
4279
                                  def, false))) {
4280
        goto cleanup;
4281
    }
4282
    def = NULL;
4283
    vm->persistent = 1;
4284

4285
    if (virDomainSaveConfig(driver->configDir,
4286
                            vm->newDef ? vm->newDef : vm->def) < 0) {
4287
        VIR_INFO("Defining domain '%s'", vm->def->name);
4288 4289
        virDomainRemoveInactive(&driver->domains,
                                vm);
4290
        vm = NULL;
4291
        goto cleanup;
4292 4293
    }

4294 4295
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
4296
                                     !dupVM ?
4297 4298
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
4299

4300
    VIR_INFO("Creating domain '%s'", vm->def->name);
4301
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
4302
    if (dom) dom->id = vm->def->id;
4303 4304

cleanup:
4305
    virDomainDefFree(def);
4306 4307
    if (vm)
        virDomainObjUnlock(vm);
4308 4309
    if (event)
        qemuDomainEventQueue(driver, event);
4310
    qemuDriverUnlock(driver);
4311
    return dom;
D
Daniel P. Berrange 已提交
4312 4313
}

4314
static int qemudDomainUndefine(virDomainPtr dom) {
4315 4316
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4317
    virDomainEventPtr event = NULL;
4318
    int ret = -1;
D
Daniel P. Berrange 已提交
4319

4320
    qemuDriverLock(driver);
4321
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4322

D
Daniel P. Berrange 已提交
4323
    if (!vm) {
4324 4325
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4326 4327
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4328
        goto cleanup;
D
Daniel P. Berrange 已提交
4329 4330
    }

D
Daniel P. Berrange 已提交
4331
    if (virDomainObjIsActive(vm)) {
4332 4333
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot delete active domain"));
4334
        goto cleanup;
D
Daniel P. Berrange 已提交
4335 4336
    }

4337
    if (!vm->persistent) {
4338
        qemuReportError(VIR_ERR_OPERATION_INVALID,
4339
                        "%s", _("cannot undefine transient domain"));
4340
        goto cleanup;
4341 4342
    }

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

4346 4347 4348
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
4349

4350
    VIR_INFO("Undefining domain '%s'", vm->def->name);
4351 4352
    virDomainRemoveInactive(&driver->domains,
                            vm);
4353
    vm = NULL;
4354
    ret = 0;
D
Daniel P. Berrange 已提交
4355

4356
cleanup:
4357 4358
    if (vm)
        virDomainObjUnlock(vm);
4359 4360
    if (event)
        qemuDomainEventQueue(driver, event);
4361
    qemuDriverUnlock(driver);
4362
    return ret;
D
Daniel P. Berrange 已提交
4363 4364
}

4365 4366 4367
static int
qemuDomainAttachDeviceDiskLive(struct qemud_driver *driver,
                               virDomainObjPtr vm,
4368
                               virDomainDeviceDefPtr dev)
4369 4370 4371 4372
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
    int ret = -1;
4373

4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393
    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:
4394
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, false);
4395 4396 4397 4398
        break;
    case VIR_DOMAIN_DISK_DEVICE_DISK:
        if (disk->bus == VIR_DOMAIN_DISK_BUS_USB)
            ret = qemuDomainAttachUsbMassstorageDevice(driver, vm,
4399
                                                       disk);
4400
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
4401
            ret = qemuDomainAttachPciDiskDevice(driver, vm, disk);
4402
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
4403
            ret = qemuDomainAttachSCSIDisk(driver, vm, disk);
4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429
        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,
4430
                                     virDomainDeviceDefPtr dev)
4431 4432 4433 4434 4435 4436
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
4437
        ret = qemuDomainAttachPciControllerDevice(driver, vm, cont);
4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450
        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,
4451
                           virDomainPtr dom)
4452 4453 4454 4455 4456 4457
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
4458
        qemuDomainObjCheckDiskTaint(driver, vm, dev->data.disk, -1);
4459
        ret = qemuDomainAttachDeviceDiskLive(driver, vm, dev);
4460 4461 4462 4463 4464
        if (!ret)
            dev->data.disk = NULL;
        break;

    case VIR_DOMAIN_DEVICE_CONTROLLER:
4465
        ret = qemuDomainAttachDeviceControllerLive(driver, vm, dev);
4466 4467 4468 4469
        if (!ret)
            dev->data.controller = NULL;
        break;

4470 4471 4472 4473 4474 4475 4476
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainAttachLease(driver, vm,
                                    dev->data.lease);
        if (ret == 0)
            dev->data.lease = NULL;
        break;

4477
    case VIR_DOMAIN_DEVICE_NET:
4478
        qemuDomainObjCheckNetTaint(driver, vm, dev->data.net, -1);
4479
        ret = qemuDomainAttachNetDevice(dom->conn, driver, vm,
4480
                                        dev->data.net);
4481 4482 4483 4484 4485 4486
        if (!ret)
            dev->data.net = NULL;
        break;

    case VIR_DOMAIN_DEVICE_HOSTDEV:
        ret = qemuDomainAttachHostDevice(driver, vm,
4487
                                         dev->data.hostdev);
4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504
        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,
4505
                               virDomainDeviceDefPtr dev)
4506 4507 4508 4509 4510 4511 4512
{
    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)
4513
            ret = qemuDomainDetachPciDiskDevice(driver, vm, dev);
4514
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
4515
            ret =  qemuDomainDetachDiskDevice(driver, vm, dev);
4516
        else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB)
4517
            ret = qemuDomainDetachDiskDevice(driver, vm, dev);
4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533
        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,
4534
                                     virDomainDeviceDefPtr dev)
4535 4536 4537 4538 4539 4540
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
4541
        ret = qemuDomainDetachPciControllerDevice(driver, vm, dev);
4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553
        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,
4554
                           virDomainPtr dom)
4555 4556 4557 4558 4559 4560
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
4561
        ret = qemuDomainDetachDeviceDiskLive(driver, vm, dev);
4562 4563
        break;
    case VIR_DOMAIN_DEVICE_CONTROLLER:
4564
        ret = qemuDomainDetachDeviceControllerLive(driver, vm, dev);
4565
        break;
4566 4567 4568
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainDetachLease(driver, vm, dev->data.lease);
        break;
4569
    case VIR_DOMAIN_DEVICE_NET:
4570
        ret = qemuDomainDetachNetDevice(driver, vm, dev);
4571 4572
        break;
    case VIR_DOMAIN_DEVICE_HOSTDEV:
4573
        ret = qemuDomainDetachHostDevice(driver, vm, dev);
4574 4575 4576 4577 4578 4579 4580 4581 4582 4583
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        "%s", _("This type of device cannot be hot unplugged"));
        break;
    }

    return ret;
}

4584 4585 4586 4587 4588 4589 4590 4591
static int
qemuDomainChangeDiskMediaLive(virDomainObjPtr vm,
                              virDomainDeviceDefPtr dev,
                              struct qemud_driver *driver,
                              bool force)
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
4592
    int ret = -1;
4593 4594 4595

    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup,
4596
                               vm->def->name, &cgroup, 0) != 0) {
4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608
            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:
4609
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, force);
4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641
        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:
4642
        ret = qemuDomainChangeDiskMediaLive(vm, dev, driver, force);
4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656
        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;
}

4657
static int
4658
qemuDomainAttachDeviceConfig(virDomainDefPtr vmdef,
4659 4660
                             virDomainDeviceDefPtr dev)
{
4661
    virDomainDiskDefPtr disk;
4662
    virDomainNetDefPtr net;
4663
    virDomainLeaseDefPtr lease;
4664

4665
    switch (dev->type) {
4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685
    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;

4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702
    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;
4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718

    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;

4719 4720 4721 4722 4723 4724 4725 4726 4727 4728
    default:
         qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                         _("persistent attach of device is not supported"));
         return -1;
    }
    return 0;
}


static int
4729
qemuDomainDetachDeviceConfig(virDomainDefPtr vmdef,
4730 4731
                             virDomainDeviceDefPtr dev)
{
4732
    virDomainDiskDefPtr disk;
4733
    virDomainNetDefPtr net;
4734
    virDomainLeaseDefPtr lease;
4735

4736
    switch (dev->type) {
4737 4738 4739 4740 4741 4742 4743 4744
    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;
4745

4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756
    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;
4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767

    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;

4768 4769 4770 4771 4772 4773 4774 4775 4776
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("persistent detach of device is not supported"));
        return -1;
    }
    return 0;
}

static int
4777
qemuDomainUpdateDeviceConfig(virDomainDefPtr vmdef,
4778 4779
                             virDomainDeviceDefPtr dev)
{
4780 4781 4782
    virDomainDiskDefPtr orig, disk;
    int pos;

4783
    switch (dev->type) {
4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818
    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;
4819 4820 4821 4822 4823 4824 4825 4826
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                         _("persistent update of device is not supported"));
        return -1;
    }
    return 0;
}

4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837
/* 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)
4838
{
4839
    struct qemud_driver *driver = dom->conn->privateData;
4840
    virDomainObjPtr vm = NULL;
4841
    virDomainDefPtr vmdef = NULL;
4842
    virDomainDeviceDefPtr dev = NULL;
4843
    bool force = (flags & VIR_DOMAIN_DEVICE_MODIFY_FORCE) != 0;
4844
    int ret = -1;
4845
    unsigned int affect;
4846

4847 4848
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
4849 4850 4851
                  (action == QEMU_DEVICE_UPDATE ?
                   VIR_DOMAIN_DEVICE_MODIFY_FORCE : 0), -1);

4852 4853
    affect = flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG);

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

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

4867
    if (virDomainObjIsActive(vm)) {
4868
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
4869
            flags |= VIR_DOMAIN_AFFECT_LIVE;
4870
    } else {
4871
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
4872
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
4873
        /* check consistency between flags and the vm state */
4874
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
4875 4876 4877 4878 4879 4880
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s",
                            _("cannot do live update a device on "
                              "inactive domain"));
            goto endjob;
        }
4881
    }
4882

4883
    if ((flags & VIR_DOMAIN_AFFECT_CONFIG) && !vm->persistent) {
4884 4885 4886 4887
         qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("cannot modify device on transient domain"));
         goto endjob;
    }
4888

4889
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
4890 4891 4892 4893 4894
        dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                      VIR_DOMAIN_XML_INACTIVE);
        if (dev == NULL)
            goto endjob;

4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915
        /* Make a copy for updated domain. */
        vmdef = virDomainObjCopyPersistentDef(driver->caps, vm);
        if (!vmdef)
            goto endjob;
        switch (action) {
        case QEMU_DEVICE_ATTACH:
            ret = qemuDomainAttachDeviceConfig(vmdef, dev);
            break;
        case QEMU_DEVICE_DETACH:
            ret = qemuDomainDetachDeviceConfig(vmdef, dev);
            break;
        case QEMU_DEVICE_UPDATE:
            ret = qemuDomainUpdateDeviceConfig(vmdef, dev);
            break;
        default:
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("unknown domain modify action %d"), action);
            break;
        }
    } else
        ret = 0;
4916

4917
    if (!ret && (flags & VIR_DOMAIN_AFFECT_LIVE)) {
4918 4919 4920 4921 4922 4923 4924
        /* If dev exists it was created to modify the domain config. Free it. */
        virDomainDeviceDefFree(dev);
        dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                      VIR_DOMAIN_XML_INACTIVE);
        if (dev == NULL)
            goto endjob;

4925 4926
        switch (action) {
        case QEMU_DEVICE_ATTACH:
4927
            ret = qemuDomainAttachDeviceLive(vm, dev, dom);
4928 4929
            break;
        case QEMU_DEVICE_DETACH:
4930
            ret = qemuDomainDetachDeviceLive(vm, dev, dom);
4931 4932
            break;
        case QEMU_DEVICE_UPDATE:
4933
            ret = qemuDomainUpdateDeviceLive(vm, dev, dom, force);
4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948
            break;
        default:
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("unknown domain modify action %d"), action);
            break;
        }
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed. For example, a
         * For example, a new controller may be created.
         */
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
            ret = -1;
    }
    /* Finally, if no error until here, we can save config. */
4949
    if (!ret && (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
4950 4951 4952 4953 4954 4955
        ret = virDomainSaveConfig(driver->configDir, vmdef);
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false);
            vmdef = NULL;
        }
    }
4956 4957

endjob:
4958
    if (qemuDomainObjEndJob(driver, vm) == 0)
4959 4960 4961
        vm = NULL;

cleanup:
4962
    virDomainDefFree(vmdef);
4963 4964 4965 4966
    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
4967 4968 4969
    return ret;
}

4970 4971 4972 4973 4974 4975
static int qemuDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_ATTACH);
}

4976 4977 4978
static int qemuDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainAttachDeviceFlags(dom, xml,
4979
                                       VIR_DOMAIN_AFFECT_LIVE);
4980
}
4981

4982

4983 4984 4985 4986
static int qemuDomainUpdateDeviceFlags(virDomainPtr dom,
                                       const char *xml,
                                       unsigned int flags)
{
4987
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_UPDATE);
4988 4989
}

4990 4991 4992
static int qemuDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
4993
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_DETACH);
4994 4995
}

4996 4997 4998
static int qemuDomainDetachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainDetachDeviceFlags(dom, xml,
4999
                                       VIR_DOMAIN_AFFECT_LIVE);
5000 5001
}

5002
static int qemudDomainGetAutostart(virDomainPtr dom,
5003
                                   int *autostart) {
5004 5005 5006
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
5007

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

5012
    if (!vm) {
5013 5014
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5015 5016
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5017
        goto cleanup;
5018 5019 5020
    }

    *autostart = vm->autostart;
5021
    ret = 0;
5022

5023
cleanup:
5024 5025
    if (vm)
        virDomainObjUnlock(vm);
5026
    return ret;
5027 5028
}

5029
static int qemudDomainSetAutostart(virDomainPtr dom,
5030
                                   int autostart) {
5031 5032
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
5033 5034
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
5035

5036
    qemuDriverLock(driver);
5037
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5038

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

5047
    if (!vm->persistent) {
5048
        qemuReportError(VIR_ERR_OPERATION_INVALID,
5049
                        "%s", _("cannot set autostart for transient domain"));
5050
        goto cleanup;
5051 5052
    }

5053 5054
    autostart = (autostart != 0);

5055
    if (vm->autostart != autostart) {
5056
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
5057
            goto cleanup;
5058
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
5059
            goto cleanup;
5060

5061
        if (autostart) {
5062 5063
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
5064 5065
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
5066 5067
                goto cleanup;
            }
5068

5069
            if (symlink(configFile, autostartLink) < 0) {
5070
                virReportSystemError(errno,
5071 5072
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
5073 5074 5075 5076
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
5077
                virReportSystemError(errno,
5078 5079
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
5080 5081
                goto cleanup;
            }
5082 5083
        }

5084
        vm->autostart = autostart;
5085
    }
5086
    ret = 0;
5087

5088 5089 5090
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
5091 5092
    if (vm)
        virDomainObjUnlock(vm);
5093
    qemuDriverUnlock(driver);
5094
    return ret;
5095 5096
}

5097 5098 5099 5100 5101

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

5104
    qemuDriverLock(driver);
5105
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
5106 5107
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup CPU controller is not mounted"));
5108
        goto cleanup;
5109 5110 5111 5112 5113 5114 5115
    }

    if (nparams)
        *nparams = 1;

    ret = strdup("posix");
    if (!ret)
5116
        virReportOOMError();
5117 5118 5119

cleanup:
    qemuDriverUnlock(driver);
5120 5121 5122
    return ret;
}

5123
static int qemuDomainSetBlkioParameters(virDomainPtr dom,
5124
                                         virTypedParameterPtr params,
5125 5126 5127 5128 5129 5130 5131
                                         int nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5132
    virDomainDefPtr persistentDef = NULL;
5133
    int ret = -1;
5134
    bool isActive;
5135

5136 5137
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5138 5139 5140 5141 5142 5143 5144 5145 5146 5147
    qemuDriverLock(driver);

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

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

5148 5149 5150 5151 5152 5153 5154
    isActive = virDomainObjIsActive(vm);

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

5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }

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

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

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

    ret = 0;
5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205
    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;
                }
5206

5207 5208 5209 5210 5211 5212 5213 5214 5215
                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);
5216 5217
                ret = -1;
            }
5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229
        }
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        for (i = 0; i < nparams; i++) {
            virTypedParameterPtr param = &params[i];

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

5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241
                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);
5242 5243 5244
                ret = -1;
            }
        }
5245
        ret = virDomainSaveConfig(driver->configDir, persistentDef);
5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256
    }

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

static int qemuDomainGetBlkioParameters(virDomainPtr dom,
5257
                                         virTypedParameterPtr params,
5258 5259 5260 5261 5262 5263 5264
                                         int *nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5265
    virDomainDefPtr persistentDef = NULL;
5266 5267 5268
    unsigned int val;
    int ret = -1;
    int rc;
5269
    bool isActive;
5270

5271 5272
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295
    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;
    }

5296 5297 5298 5299 5300 5301 5302
    isActive = virDomainObjIsActive(vm);

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

5305 5306 5307 5308 5309 5310
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (!isActive) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
            goto cleanup;
        }
5311

5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359
        if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
            qemuReportError(VIR_ERR_NO_SUPPORT, _("blkio cgroup isn't mounted"));
            goto cleanup;
        }

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

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

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

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

            default:
                break;
                /* should not hit here */
5360
            }
5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377
        }
    } 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;
5378

5379 5380 5381 5382
            default:
                break;
                /* should not hit here */
            }
5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395
        }
    }

    ret = 0;

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

static int qemuDomainSetMemoryParameters(virDomainPtr dom,
5398
                                         virTypedParameterPtr params,
5399
                                         int nparams,
5400
                                         unsigned int flags)
5401 5402 5403
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
5404
    virDomainDefPtr persistentDef = NULL;
5405 5406 5407
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;
5408 5409
    bool isActive;

5410 5411
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422

    qemuDriverLock(driver);

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

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

5423 5424
    isActive = virDomainObjIsActive(vm);

5425
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
5426
        if (isActive)
5427
            flags = VIR_DOMAIN_AFFECT_LIVE;
5428
        else
5429
            flags = VIR_DOMAIN_AFFECT_CONFIG;
5430 5431
    }

5432
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451
        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;
        }
    }

5452
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5453 5454 5455 5456 5457 5458 5459
        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;
5460 5461 5462 5463
    }

    ret = 0;
    for (i = 0; i < nparams; i++) {
5464
        virTypedParameterPtr param = &params[i];
5465 5466 5467

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

5475
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5476 5477 5478 5479 5480 5481 5482 5483
                rc = virCgroupSetMemoryHardLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory hard_limit tunable"));
                    ret = -1;
                }
            }

5484
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5485
                persistentDef->mem.hard_limit = params[i].value.ul;
5486 5487 5488
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT)) {
            int rc;
5489
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
5490 5491 5492 5493 5494 5495
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for memory soft_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

5496
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5497 5498 5499 5500 5501 5502 5503 5504
                rc = virCgroupSetMemorySoftLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set memory soft_limit tunable"));
                    ret = -1;
                }
            }

5505
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5506
                persistentDef->mem.soft_limit = params[i].value.ul;
5507
            }
5508
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT)) {
5509
            int rc;
5510
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
5511 5512 5513 5514 5515 5516
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for swap_hard_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

5517
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5518 5519 5520 5521 5522 5523 5524
                rc = virCgroupSetMemSwapHardLimit(group, params[i].value.ul);
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set swap_hard_limit tunable"));
                    ret = -1;
                }
            }
5525
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5526
                persistentDef->mem.swap_hard_limit = params[i].value.ul;
5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538
            }
        } 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;
        }
    }

5539
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5540 5541 5542
        ret = virDomainSaveConfig(driver->configDir, persistentDef);
    }

5543 5544 5545 5546 5547 5548 5549 5550
cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

5551
static int qemuDomainGetMemoryParameters(virDomainPtr dom,
5552
                                         virTypedParameterPtr params,
5553
                                         int *nparams,
5554
                                         unsigned int flags)
5555 5556 5557 5558 5559
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5560
    virDomainDefPtr persistentDef = NULL;
5561
    unsigned long long val;
5562 5563
    int ret = -1;
    int rc;
5564
    bool isActive;
5565

5566 5567
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5568

5569
    qemuDriverLock(driver);
5570 5571 5572 5573 5574 5575 5576 5577 5578

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

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

5579 5580
    isActive = virDomainObjIsActive(vm);

5581
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
5582
        if (isActive)
5583
            flags = VIR_DOMAIN_AFFECT_LIVE;
5584
        else
5585
            flags = VIR_DOMAIN_AFFECT_CONFIG;
5586 5587
    }

5588
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607
        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;
        }
    }

5608
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5609 5610 5611 5612 5613 5614 5615
        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;
5616 5617
    }

5618 5619 5620 5621 5622 5623 5624
    if ((*nparams) == 0) {
        /* Current number of memory parameters supported by cgroups */
        *nparams = QEMU_NB_MEM_PARAM;
        ret = 0;
        goto cleanup;
    }

5625
    if ((*nparams) < QEMU_NB_MEM_PARAM) {
5626 5627 5628 5629 5630
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
        goto cleanup;
    }

5631
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5632 5633 5634 5635
        for (i = 0; i < *nparams; i++) {
            virMemoryParameterPtr param = &params[i];
            val = 0;
            param->value.ul = 0;
5636
            param->type = VIR_TYPED_PARAM_ULLONG;
5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671

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

5674
    for (i = 0; i < QEMU_NB_MEM_PARAM; i++) {
5675
        virTypedParameterPtr param = &params[i];
5676 5677
        val = 0;
        param->value.ul = 0;
5678
        param->type = VIR_TYPED_PARAM_ULLONG;
5679

5680
        switch (i) {
5681 5682 5683 5684 5685
        case 0: /* fill memory hard limit here */
            rc = virCgroupGetMemoryHardLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory hard limit"));
5686
                goto cleanup;
5687 5688 5689 5690
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field memory hard limit too long for destination"));
5691
                goto cleanup;
5692 5693 5694 5695 5696 5697 5698 5699 5700
            }
            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"));
5701
                goto cleanup;
5702 5703 5704 5705
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field memory soft limit too long for destination"));
5706
                goto cleanup;
5707 5708 5709 5710 5711
            }
            param->value.ul = val;
            break;

        case 2: /* fill swap hard limit here */
5712
            rc = virCgroupGetMemSwapHardLimit(group, &val);
5713 5714 5715
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get swap hard limit"));
5716
                goto cleanup;
5717
            }
5718
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT) == NULL) {
5719 5720
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field swap hard limit too long for destination"));
5721
                goto cleanup;
5722 5723 5724 5725 5726 5727 5728 5729 5730 5731
            }
            param->value.ul = val;
            break;

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

5732
out:
5733
    *nparams = QEMU_NB_MEM_PARAM;
5734 5735
    ret = 0;

5736 5737 5738 5739 5740 5741 5742 5743 5744
cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

5745
static int qemuSetSchedulerParametersFlags(virDomainPtr dom,
5746
                                           virTypedParameterPtr params,
5747 5748
                                           int nparams,
                                           unsigned int flags)
5749 5750 5751 5752 5753
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5754
    virDomainDefPtr persistentDef = NULL;
5755
    int ret = -1;
5756 5757
    bool isActive;

5758 5759
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5760

5761
    qemuDriverLock(driver);
5762 5763 5764 5765

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

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

5771 5772
    isActive = virDomainObjIsActive(vm);

5773
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
5774
        if (isActive)
5775
            flags = VIR_DOMAIN_AFFECT_LIVE;
5776
        else
5777
            flags = VIR_DOMAIN_AFFECT_CONFIG;
5778 5779
    }

5780
    if ((flags & VIR_DOMAIN_AFFECT_CONFIG) && !vm->persistent) {
5781 5782
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot change persistent config of a transient domain"));
5783 5784 5785
        goto cleanup;
    }

5786
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805
        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;
        }
    }

5806
    for (i = 0; i < nparams; i++) {
5807
        virTypedParameterPtr param = &params[i];
5808 5809 5810

        if (STREQ(param->field, "cpu_shares")) {
            int rc;
5811
            if (param->type != VIR_TYPED_PARAM_ULLONG) {
5812 5813
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for cpu_shares tunable, expected a 'ullong'"));
5814 5815 5816
                goto cleanup;
            }

5817
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
5818 5819 5820 5821 5822 5823 5824 5825
                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;
5826
            }
5827

5828
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842
                persistentDef = virDomainObjGetPersistentDef(driver->caps, vm);
                if (!persistentDef) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                    _("can't get persistentDef"));
                    goto cleanup;
                }
                persistentDef->cputune.shares = params[i].value.ul;
                rc = virDomainSaveConfig(driver->configDir, persistentDef);
                if (rc) {
                    qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                    _("can't save config"));
                    goto cleanup;
                }
            }
5843
        } else {
5844 5845
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Invalid parameter `%s'"), param->field);
5846 5847 5848
            goto cleanup;
        }
    }
5849

5850 5851 5852 5853 5854 5855
    ret = 0;

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

5860
static int qemuSetSchedulerParameters(virDomainPtr dom,
5861
                                      virTypedParameterPtr params,
5862 5863 5864 5865 5866
                                      int nparams)
{
    return qemuSetSchedulerParametersFlags(dom,
                                           params,
                                           nparams,
5867
                                           VIR_DOMAIN_AFFECT_LIVE);
5868 5869
}

5870 5871 5872 5873 5874
static int
qemuGetSchedulerParametersFlags(virDomainPtr dom,
                                virTypedParameterPtr params,
                                int *nparams,
                                unsigned int flags)
5875 5876 5877 5878 5879 5880 5881
{
    struct qemud_driver *driver = dom->conn->privateData;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    unsigned long long val;
    int ret = -1;
    int rc;
5882
    bool isActive;
5883

5884 5885
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5886

5887 5888
    qemuDriverLock(driver);

5889 5890
    if ((flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)) ==
        (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)) {
5891 5892
        qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                        _("cannot query live and config together"));
5893
        goto cleanup;
5894 5895
    }

5896
    if (*nparams < 1) {
5897 5898
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
5899
        goto cleanup;
5900 5901 5902 5903 5904
    }

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

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

5910 5911
    isActive = virDomainObjIsActive(vm);

5912
    if (flags == VIR_DOMAIN_AFFECT_CURRENT) {
5913
        if (isActive)
5914
            flags = VIR_DOMAIN_AFFECT_LIVE;
5915
        else
5916
            flags = VIR_DOMAIN_AFFECT_CONFIG;
5917 5918
    }

5919
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot query persistent config of a transient domain"));
            goto cleanup;
        }

        if (isActive) {
            virDomainDefPtr persistentDef;

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

5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953
    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;
    }

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

    rc = virCgroupGetCpuShares(group, &val);
    if (rc != 0) {
5962
        virReportSystemError(-rc, "%s",
5963 5964 5965
                             _("unable to get cpu shares tunable"));
        goto cleanup;
    }
5966
out:
5967
    params[0].value.ul = val;
5968
    params[0].type = VIR_TYPED_PARAM_ULLONG;
C
Chris Lalancette 已提交
5969
    if (virStrcpyStatic(params[0].field, "cpu_shares") == NULL) {
5970 5971
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Field cpu_shares too long for destination"));
C
Chris Lalancette 已提交
5972 5973
        goto cleanup;
    }
5974

5975
    *nparams = 1;
5976 5977 5978 5979 5980 5981
    ret = 0;

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

5986 5987 5988 5989 5990 5991
static int
qemuGetSchedulerParameters(virDomainPtr dom,
                           virTypedParameterPtr params,
                           int *nparams)
{
    return qemuGetSchedulerParametersFlags(dom, params, nparams,
5992
                                           VIR_DOMAIN_AFFECT_CURRENT);
5993
}
5994

5995 5996 5997 5998 5999 6000 6001 6002 6003
/* 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)
{
6004
    struct qemud_driver *driver = dom->conn->privateData;
6005
    int i, ret = -1;
6006
    virDomainObjPtr vm;
6007
    virDomainDiskDefPtr disk = NULL;
6008
    qemuDomainObjPrivatePtr priv;
6009

6010
    qemuDriverLock(driver);
6011
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6012
    qemuDriverUnlock(driver);
6013
    if (!vm) {
6014 6015
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
6016 6017
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
6018
        goto cleanup;
6019
    }
6020

6021 6022 6023 6024 6025 6026
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

6027 6028 6029 6030 6031 6032 6033 6034
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

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

6040
    if (!disk->info.alias) {
6041 6042
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("missing disk device alias name for %s"), disk->dst);
6043
        goto cleanup;
6044
    }
6045

6046
    priv = vm->privateData;
6047 6048
    if ((priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_OUT)
        || (priv->job.asyncJob == QEMU_ASYNC_JOB_SAVE)) {
6049
        virDomainObjRef(vm);
6050 6051
        while (priv->job.signals & QEMU_JOB_SIGNAL_BLKSTAT)
            ignore_value(virCondWait(&priv->job.signalCond, &vm->lock));
6052

6053 6054 6055 6056
        priv->job.signalsData.statDevName = disk->info.alias;
        priv->job.signalsData.blockStat = stats;
        priv->job.signalsData.statRetCode = &ret;
        priv->job.signals |= QEMU_JOB_SIGNAL_BLKSTAT;
6057

6058 6059
        while (priv->job.signals & QEMU_JOB_SIGNAL_BLKSTAT)
            ignore_value(virCondWait(&priv->job.signalCond, &vm->lock));
6060 6061 6062 6063

        if (virDomainObjUnref(vm) == 0)
            vm = NULL;
    } else {
6064
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
6065 6066 6067 6068 6069 6070 6071 6072
            goto cleanup;

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

6073
        ignore_value(qemuDomainObjEnterMonitor(driver, vm));
6074 6075 6076 6077 6078 6079 6080
        ret = qemuMonitorGetBlockStatsInfo(priv->mon,
                                           disk->info.alias,
                                           &stats->rd_req,
                                           &stats->rd_bytes,
                                           &stats->wr_req,
                                           &stats->wr_bytes,
                                           &stats->errs);
6081
        qemuDomainObjExitMonitor(driver, vm);
6082

6083
endjob:
6084
        if (qemuDomainObjEndJob(driver, vm) == 0)
6085 6086
            vm = NULL;
    }
6087

6088
cleanup:
6089 6090
    if (vm)
        virDomainObjUnlock(vm);
6091
    return ret;
6092 6093
}

6094
#ifdef __linux__
6095 6096 6097 6098 6099
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
6100 6101
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
6102
    int i;
6103
    int ret = -1;
6104

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

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

D
Daniel P. Berrange 已提交
6117
    if (!virDomainObjIsActive(vm)) {
6118 6119
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
6120
        goto cleanup;
6121 6122 6123
    }

    /* Check the path is one of the domain's network interfaces. */
6124 6125
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
6126 6127 6128 6129
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
6130 6131
    }

6132
    if (ret == 0)
6133
        ret = linuxDomainInterfaceStats(path, stats);
6134
    else
6135 6136
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path, '%s' is not a known interface"), path);
6137

6138
cleanup:
6139 6140
    if (vm)
        virDomainObjUnlock(vm);
6141 6142
    return ret;
}
6143
#else
6144 6145 6146 6147
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
6148
{
6149 6150
    qemuReportError(VIR_ERR_NO_SUPPORT,
                    "%s", __FUNCTION__);
6151 6152
    return -1;
}
6153
#endif
6154

6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170
static int
qemudDomainMemoryStats (virDomainPtr dom,
                        struct _virDomainMemoryStat *stats,
                        unsigned int nr_stats)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned int ret = -1;

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

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

6176
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
6177 6178
        goto cleanup;

6179 6180
    if (virDomainObjIsActive(vm)) {
        qemuDomainObjPrivatePtr priv = vm->privateData;
6181
        ignore_value(qemuDomainObjEnterMonitor(driver, vm));
6182
        ret = qemuMonitorGetMemoryStats(priv->mon, stats, nr_stats);
6183
        qemuDomainObjExitMonitor(driver, vm);
6184
    } else {
6185 6186
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
6187 6188
    }

6189
    if (qemuDomainObjEndJob(driver, vm) == 0)
6190 6191
        vm = NULL;

6192 6193 6194 6195 6196 6197
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

6198 6199 6200 6201 6202
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
E
Eric Blake 已提交
6203
                      unsigned int flags)
6204
{
6205 6206 6207
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
6208

E
Eric Blake 已提交
6209 6210
    virCheckFlags(0, -1);

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

6215
    if (!vm) {
6216 6217
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
6218 6219
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
6220
        goto cleanup;
6221 6222 6223
    }

    if (!path || path[0] == '\0') {
6224 6225
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("NULL or empty path"));
6226
        goto cleanup;
6227 6228 6229
    }

    /* Check the path belongs to this domain. */
6230 6231
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
6232 6233 6234 6235
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
6236 6237
    }

6238 6239 6240 6241 6242
    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) {
6243 6244
            virReportSystemError(errno,
                                 _("%s: failed to open"), path);
6245 6246
            goto cleanup;
        }
6247

6248 6249 6250 6251 6252 6253
        /* 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) {
6254 6255
            virReportSystemError(errno,
                                 _("%s: failed to seek or read"), path);
6256 6257 6258 6259 6260
            goto cleanup;
        }

        ret = 0;
    } else {
6261 6262
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("invalid path"));
6263 6264
    }

6265
cleanup:
6266
    VIR_FORCE_CLOSE(fd);
6267 6268
    if (vm)
        virDomainObjUnlock(vm);
6269 6270 6271
    return ret;
}

R
Richard W.M. Jones 已提交
6272 6273 6274 6275 6276 6277
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
6278 6279
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
6280
    char *tmp = NULL;
R
Richard W.M. Jones 已提交
6281
    int fd = -1, ret = -1;
6282
    qemuDomainObjPrivatePtr priv;
R
Richard W.M. Jones 已提交
6283

6284 6285
    virCheckFlags(VIR_MEMORY_VIRTUAL | VIR_MEMORY_PHYSICAL, -1);

6286
    qemuDriverLock(driver);
6287
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6288
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
6289 6290

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

6298
    if (flags != VIR_MEMORY_VIRTUAL && flags != VIR_MEMORY_PHYSICAL) {
6299 6300
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("flags parameter must be VIR_MEMORY_VIRTUAL or VIR_MEMORY_PHYSICAL"));
6301
        goto cleanup;
R
Richard W.M. Jones 已提交
6302 6303
    }

6304
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
6305 6306
        goto cleanup;

D
Daniel P. Berrange 已提交
6307
    if (!virDomainObjIsActive(vm)) {
6308 6309
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
6310
        goto endjob;
R
Richard W.M. Jones 已提交
6311 6312
    }

6313
    if (virAsprintf(&tmp, "%s/qemu.mem.XXXXXX", driver->cacheDir) < 0) {
6314
        virReportOOMError();
6315
        goto endjob;
6316 6317
    }

R
Richard W.M. Jones 已提交
6318 6319
    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
6320 6321
        virReportSystemError(errno,
                             _("mkstemp(\"%s\") failed"), tmp);
6322
        goto endjob;
R
Richard W.M. Jones 已提交
6323 6324
    }

6325 6326
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm, tmp);

6327
    priv = vm->privateData;
6328
    ignore_value(qemuDomainObjEnterMonitor(driver, vm));
6329
    if (flags == VIR_MEMORY_VIRTUAL) {
6330
        if (qemuMonitorSaveVirtualMemory(priv->mon, offset, size, tmp) < 0) {
6331
            qemuDomainObjExitMonitor(driver, vm);
6332
            goto endjob;
6333
        }
6334
    } else {
6335
        if (qemuMonitorSavePhysicalMemory(priv->mon, offset, size, tmp) < 0) {
6336
            qemuDomainObjExitMonitor(driver, vm);
6337
            goto endjob;
6338
        }
R
Richard W.M. Jones 已提交
6339
    }
6340
    qemuDomainObjExitMonitor(driver, vm);
R
Richard W.M. Jones 已提交
6341 6342 6343

    /* Read the memory file into buffer. */
    if (saferead (fd, buffer, size) == (ssize_t) -1) {
6344 6345 6346
        virReportSystemError(errno,
                             _("failed to read temporary file "
                               "created with template %s"), tmp);
6347
        goto endjob;
R
Richard W.M. Jones 已提交
6348 6349 6350
    }

    ret = 0;
6351

6352
endjob:
6353
    if (qemuDomainObjEndJob(driver, vm) == 0)
6354
        vm = NULL;
6355

6356
cleanup:
6357
    VIR_FORCE_CLOSE(fd);
6358 6359
    if (tmp)
        unlink(tmp);
W
Wen Congyang 已提交
6360
    VIR_FREE(tmp);
6361 6362
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
6363 6364 6365
    return ret;
}

6366

6367 6368 6369 6370 6371 6372 6373 6374 6375 6376
static int qemuDomainGetBlockInfo(virDomainPtr dom,
                                  const char *path,
                                  virDomainBlockInfoPtr info,
                                  unsigned int flags) {
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    int fd = -1;
    off_t end;
    virStorageFileMetadata meta;
6377
    virDomainDiskDefPtr disk = NULL;
6378 6379
    struct stat sb;
    int i;
6380
    int format;
6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404

    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)) {
6405
            disk = vm->def->disks[i];
6406 6407 6408 6409
            break;
        }
    }

6410
    if (!disk) {
6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424
        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 */
6425 6426 6427 6428 6429 6430 6431 6432
    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 {
6433 6434 6435 6436 6437 6438 6439
        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);
6440
            goto cleanup;
6441
        }
6442 6443 6444 6445 6446
    }

    if (virStorageFileGetMetadataFromFD(path, fd,
                                        format,
                                        &meta) < 0)
6447 6448 6449 6450 6451 6452 6453 6454 6455 6456
        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)) {
6457
#ifndef WIN32
6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485
        info->physical = (unsigned long long)sb.st_blocks *
            (unsigned long long)DEV_BSIZE;
#else
        info->physical = sb.st_size;
#endif
        /* Regular files may be sparse, so logical size (capacity) is not same
         * as actual physical above
         */
        info->capacity = sb.st_size;
    } else {
        /* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
         * be 64 bits on all platforms.
         */
        end = lseek (fd, 0, SEEK_END);
        if (end == (off_t)-1) {
            virReportSystemError(errno,
                                 _("failed to seek to end of %s"), path);
            goto cleanup;
        }
        info->physical = end;
        info->capacity = end;
    }

    /* If the file we probed has a capacity set, then override
     * what we calculated from file/block extents */
    if (meta.capacity)
        info->capacity = meta.capacity;

6486
    /* Set default value .. */
6487 6488
    info->allocation = info->physical;

6489 6490 6491
    /* ..but if guest is running & not using raw
       disk format and on a block device, then query
       highest allocated extent from QEMU */
6492
    if (disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
6493
        format != VIR_STORAGE_FILE_RAW &&
6494 6495
        S_ISBLK(sb.st_mode) &&
        virDomainObjIsActive(vm)) {
6496
        qemuDomainObjPrivatePtr priv = vm->privateData;
6497

6498 6499
        if ((priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_OUT)
            || (priv->job.asyncJob == QEMU_ASYNC_JOB_SAVE)) {
6500
            virDomainObjRef(vm);
6501 6502
            while (priv->job.signals & QEMU_JOB_SIGNAL_BLKINFO)
                ignore_value(virCondWait(&priv->job.signalCond, &vm->lock));
6503

6504 6505 6506 6507
            priv->job.signalsData.infoDevName = disk->info.alias;
            priv->job.signalsData.blockInfo = info;
            priv->job.signalsData.infoRetCode = &ret;
            priv->job.signals |= QEMU_JOB_SIGNAL_BLKINFO;
6508

6509 6510
            while (priv->job.signals & QEMU_JOB_SIGNAL_BLKINFO)
                ignore_value(virCondWait(&priv->job.signalCond, &vm->lock));
6511 6512 6513 6514

            if (virDomainObjUnref(vm) == 0)
                vm = NULL;
        } else {
6515
            if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
6516 6517
                goto cleanup;

6518
            if (virDomainObjIsActive(vm)) {
6519
                ignore_value(qemuDomainObjEnterMonitor(driver, vm));
6520 6521 6522
                ret = qemuMonitorGetBlockExtent(priv->mon,
                                                disk->info.alias,
                                                &info->allocation);
6523
                qemuDomainObjExitMonitor(driver, vm);
6524 6525
            } else {
                ret = 0;
6526 6527
            }

6528
            if (qemuDomainObjEndJob(driver, vm) == 0)
6529 6530
                vm = NULL;
        }
6531 6532 6533
    } else {
        ret = 0;
    }
6534 6535

cleanup:
6536
    VIR_FORCE_CLOSE(fd);
6537 6538 6539 6540 6541 6542
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


6543
static int
6544 6545 6546 6547
qemuDomainEventRegister(virConnectPtr conn,
                        virConnectDomainEventCallback callback,
                        void *opaque,
                        virFreeCallback freecb)
6548
{
6549 6550 6551
    struct qemud_driver *driver = conn->privateData;
    int ret;

6552
    qemuDriverLock(driver);
6553 6554
    ret = virDomainEventCallbackListAdd(conn,
                                        driver->domainEventState->callbacks,
6555
                                        callback, opaque, freecb);
6556
    qemuDriverUnlock(driver);
6557

6558
    return ret;
6559 6560
}

6561

6562
static int
6563 6564
qemuDomainEventDeregister(virConnectPtr conn,
                          virConnectDomainEventCallback callback)
6565
{
6566 6567 6568
    struct qemud_driver *driver = conn->privateData;
    int ret;

6569
    qemuDriverLock(driver);
6570 6571 6572
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
6573
    qemuDriverUnlock(driver);
6574

6575
    return ret;
6576 6577
}

6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591

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,
6592
                                          driver->domainEventState->callbacks,
6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608
                                          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);
6609 6610 6611
    ret = virDomainEventStateDeregisterAny(conn,
                                           driver->domainEventState,
                                           callbackID);
6612 6613 6614 6615 6616 6617
    qemuDriverUnlock(driver);

    return ret;
}


6618 6619 6620
/*******************************************************************
 * Migration Protocol Version 2
 *******************************************************************/
D
Daniel Veillard 已提交
6621

C
Chris Lalancette 已提交
6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636
/* 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;
6637

6638
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
6639

6640 6641
    qemuDriverLock(driver);

C
Chris Lalancette 已提交
6642
    if (!dom_xml) {
6643 6644
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
C
Chris Lalancette 已提交
6645 6646 6647
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
6648
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
6649 6650 6651 6652
                         "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
        goto cleanup;
    }
    if (st == NULL) {
6653 6654
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("tunnelled migration requested but NULL stream passed"));
C
Chris Lalancette 已提交
6655 6656 6657
        goto cleanup;
    }

6658 6659 6660 6661 6662 6663 6664
    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

6665 6666 6667
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     NULL, 0, NULL, NULL, /* No cookies in v2 */
                                     st, dname, dom_xml);
6668

C
Chris Lalancette 已提交
6669
cleanup:
6670
    qemuDriverUnlock(driver);
C
Chris Lalancette 已提交
6671 6672 6673
    return ret;
}

D
Daniel Veillard 已提交
6674 6675 6676 6677
/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
6678
static int ATTRIBUTE_NONNULL (5)
D
Daniel Veillard 已提交
6679
qemudDomainMigratePrepare2 (virConnectPtr dconn,
6680 6681
                            char **cookie ATTRIBUTE_UNUSED,
                            int *cookielen ATTRIBUTE_UNUSED,
D
Daniel Veillard 已提交
6682 6683
                            const char *uri_in,
                            char **uri_out,
C
Chris Lalancette 已提交
6684
                            unsigned long flags,
D
Daniel Veillard 已提交
6685 6686 6687 6688
                            const char *dname,
                            unsigned long resource ATTRIBUTE_UNUSED,
                            const char *dom_xml)
{
6689
    struct qemud_driver *driver = dconn->privateData;
6690
    int ret = -1;
6691

6692
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
6693

6694
    *uri_out = NULL;
D
Daniel Veillard 已提交
6695

6696
    qemuDriverLock(driver);
6697 6698 6699 6700 6701 6702 6703 6704

    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 已提交
6705 6706 6707 6708
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
6709 6710
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Tunnelled migration requested but invalid RPC method called"));
C
Chris Lalancette 已提交
6711 6712 6713
        goto cleanup;
    }

D
Daniel Veillard 已提交
6714
    if (!dom_xml) {
6715 6716
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
6717
        goto cleanup;
D
Daniel Veillard 已提交
6718 6719
    }

6720 6721 6722 6723
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
6724
    ret = qemuMigrationPrepareDirect(driver, dconn,
6725
                                     NULL, 0, NULL, NULL, /* No cookies */
6726 6727
                                     uri_in, uri_out,
                                     dname, dom_xml);
D
Daniel Veillard 已提交
6728

6729 6730 6731 6732
cleanup:
    qemuDriverUnlock(driver);
    return ret;
}
C
Chris Lalancette 已提交
6733

D
Daniel Veillard 已提交
6734

6735 6736 6737
/* Perform is the second step, and it runs on the source host. */
static int
qemudDomainMigratePerform (virDomainPtr dom,
6738 6739
                           const char *cookie,
                           int cookielen,
6740 6741 6742 6743 6744 6745 6746 6747
                           const char *uri,
                           unsigned long flags,
                           const char *dname,
                           unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
6748
    const char *dconnuri = NULL;
6749

6750
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
6751

6752
    qemuDriverLock(driver);
6753 6754 6755 6756 6757 6758 6759
    if (virLockManagerPluginUsesState(driver->lockManager)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot use migrate v2 protocol with lock manager %s"),
                        virLockManagerPluginGetName(driver->lockManager));
        goto cleanup;
    }

6760
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel Veillard 已提交
6761
    if (!vm) {
6762 6763
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
6764 6765
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
6766
        goto cleanup;
D
Daniel Veillard 已提交
6767 6768
    }

6769 6770 6771 6772 6773
    if (flags & VIR_MIGRATE_PEER2PEER) {
        dconnuri = uri;
        uri = NULL;
    }

6774 6775 6776 6777 6778 6779
    /* 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
     */
6780
    ret = qemuMigrationPerform(driver, dom->conn, vm,
6781
                               NULL, dconnuri, uri, cookie, cookielen,
6782
                               NULL, NULL, /* No output cookies in v2 */
6783
                               flags, dname, resource, false);
6784

6785
cleanup:
6786
    qemuDriverUnlock(driver);
6787
    return ret;
D
Daniel Veillard 已提交
6788 6789
}

6790

D
Daniel Veillard 已提交
6791 6792 6793 6794 6795 6796 6797
/* 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 已提交
6798
                           unsigned long flags,
D
Daniel Veillard 已提交
6799 6800
                           int retcode)
{
6801 6802 6803
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
D
Daniel Veillard 已提交
6804

6805
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
C
Chris Lalancette 已提交
6806

6807
    qemuDriverLock(driver);
6808
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
6809
    if (!vm) {
6810 6811
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
6812
        goto cleanup;
D
Daniel Veillard 已提交
6813 6814
    }

6815 6816 6817 6818
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
6819
    dom = qemuMigrationFinish(driver, dconn, vm,
6820
                              NULL, 0, NULL, NULL, /* No cookies */
6821
                              flags, retcode, false);
6822

6823
cleanup:
6824
    qemuDriverUnlock(driver);
6825
    return dom;
D
Daniel Veillard 已提交
6826 6827
}

6828

6829 6830 6831 6832 6833 6834
/*******************************************************************
 * Migration Protocol Version 3
 *******************************************************************/

static char *
qemuDomainMigrateBegin3(virDomainPtr domain,
6835
                        const char *xmlin,
6836 6837 6838 6839 6840 6841 6842 6843 6844 6845
                        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;

6846
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857

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

6858
    xml = qemuMigrationBegin(driver, vm, xmlin,
6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881
                             cookieout, cookieoutlen);

cleanup:
    qemuDriverUnlock(driver);
    return xml;
}

static int
qemuDomainMigratePrepare3(virConnectPtr dconn,
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
                          const char *uri_in,
                          char **uri_out,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource ATTRIBUTE_UNUSED,
                          const char *dom_xml)
{
    struct qemud_driver *driver = dconn->privateData;
    int ret = -1;

6882
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928

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

6929
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960

    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,
6961
                          const char *xmlin,
6962 6963 6964 6965
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
6966
                          const char *dconnuri,
6967 6968 6969 6970 6971 6972 6973 6974 6975
                          const char *uri,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

6976
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987

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

6988
    ret = qemuMigrationPerform(driver, dom->conn, vm, xmlin,
6989
                               dconnuri, uri, cookiein, cookieinlen,
6990
                               cookieout, cookieoutlen,
6991
                               flags, dname, resource, true);
6992 6993 6994 6995 6996 6997 6998

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}


6999
static virDomainPtr
7000 7001 7002 7003 7004 7005
qemuDomainMigrateFinish3(virConnectPtr dconn,
                         const char *dname,
                         const char *cookiein,
                         int cookieinlen,
                         char **cookieout,
                         int *cookieoutlen,
7006
                         const char *dconnuri ATTRIBUTE_UNUSED,
7007 7008
                         const char *uri ATTRIBUTE_UNUSED,
                         unsigned long flags,
7009
                         int cancelled)
7010 7011 7012
{
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
7013
    virDomainPtr dom = NULL;
7014

7015
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
7016 7017 7018 7019 7020 7021 7022 7023 7024

    qemuDriverLock(driver);
    vm = virDomainFindByName(&driver->domains, dname);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
        goto cleanup;
    }

7025 7026 7027 7028
    dom = qemuMigrationFinish(driver, dconn, vm,
                              cookiein, cookieinlen,
                              cookieout, cookieoutlen,
                              flags, cancelled, true);
7029 7030 7031

cleanup:
    qemuDriverUnlock(driver);
7032
    return dom;
7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045
}

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;

7046
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057

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

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

7061 7062
    ret = qemuMigrationConfirm(driver, domain->conn, vm,
                               cookiein, cookieinlen,
7063 7064
                               flags, cancelled);

7065
    if (qemuDomainObjEndJob(driver, vm) == 0) {
7066 7067 7068 7069 7070 7071 7072 7073 7074
        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;
    }

7075
cleanup:
7076 7077
    if (vm)
        virDomainObjUnlock(vm);
7078 7079 7080 7081 7082
    qemuDriverUnlock(driver);
    return ret;
}


7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098
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;

7099
    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE);
7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116
    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) {
7117 7118
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("device %s is not a PCI device"), dev->name);
7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131
        goto out;
    }

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

static int
qemudNodeDeviceDettach (virNodeDevicePtr dev)
{
7132
    struct qemud_driver *driver = dev->conn->privateData;
7133 7134 7135 7136 7137 7138 7139
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

7140
    pci = pciGetDevice(domain, bus, slot, function);
7141 7142 7143
    if (!pci)
        return -1;

7144 7145
    qemuDriverLock(driver);
    if (pciDettachDevice(pci, driver->activePciHostdevs) < 0)
7146 7147 7148 7149
        goto out;

    ret = 0;
out:
7150
    qemuDriverUnlock(driver);
7151
    pciFreeDevice(pci);
7152 7153 7154 7155 7156 7157
    return ret;
}

static int
qemudNodeDeviceReAttach (virNodeDevicePtr dev)
{
7158
    struct qemud_driver *driver = dev->conn->privateData;
7159 7160 7161 7162 7163 7164 7165
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

7166
    pci = pciGetDevice(domain, bus, slot, function);
7167 7168 7169
    if (!pci)
        return -1;

7170 7171
    pciDeviceReAttachInit(pci);

7172 7173
    qemuDriverLock(driver);
    if (pciReAttachDevice(pci, driver->activePciHostdevs) < 0)
7174 7175 7176 7177
        goto out;

    ret = 0;
out:
7178
    qemuDriverUnlock(driver);
7179
    pciFreeDevice(pci);
7180 7181 7182 7183 7184 7185
    return ret;
}

static int
qemudNodeDeviceReset (virNodeDevicePtr dev)
{
7186
    struct qemud_driver *driver = dev->conn->privateData;
7187 7188 7189 7190 7191 7192 7193
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

7194
    pci = pciGetDevice(domain, bus, slot, function);
7195 7196 7197
    if (!pci)
        return -1;

7198 7199
    qemuDriverLock(driver);

7200
    if (pciResetDevice(pci, driver->activePciHostdevs, NULL) < 0)
7201 7202 7203 7204
        goto out;

    ret = 0;
out:
7205
    qemuDriverUnlock(driver);
7206
    pciFreeDevice(pci);
7207 7208 7209
    return ret;
}

7210 7211 7212
static int
qemuCPUCompare(virConnectPtr conn,
               const char *xmlDesc,
E
Eric Blake 已提交
7213
               unsigned int flags)
7214 7215 7216 7217
{
    struct qemud_driver *driver = conn->privateData;
    int ret = VIR_CPU_COMPARE_ERROR;

E
Eric Blake 已提交
7218 7219
    virCheckFlags(0, VIR_CPU_COMPARE_ERROR);

7220 7221 7222
    qemuDriverLock(driver);

    if (!driver->caps || !driver->caps->host.cpu) {
7223 7224
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        "%s", _("cannot get host CPU capabilities"));
7225 7226
    }
    else
7227
        ret = cpuCompareXML(driver->caps->host.cpu, xmlDesc);
7228 7229 7230 7231 7232 7233

    qemuDriverUnlock(driver);

    return ret;
}

7234

7235 7236 7237 7238
static char *
qemuCPUBaseline(virConnectPtr conn ATTRIBUTE_UNUSED,
                const char **xmlCPUs,
                unsigned int ncpus,
E
Eric Blake 已提交
7239
                unsigned int flags)
7240 7241 7242
{
    char *cpu;

E
Eric Blake 已提交
7243 7244
    virCheckFlags(0, NULL);

7245 7246 7247 7248 7249
    cpu = cpuBaselineXML(xmlCPUs, ncpus, NULL, 0);

    return cpu;
}

7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271

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)) {
7272
        if (priv->job.asyncJob) {
7273
            memcpy(info, &priv->job.info, sizeof(*info));
7274 7275 7276 7277 7278 7279

            /* 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 已提交
7280
            if (virTimeMs(&info->timeElapsed) < 0)
7281
                goto cleanup;
7282
            info->timeElapsed -= priv->job.start;
7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301
        } 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;
}


7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321
static int qemuDomainAbortJob(virDomainPtr dom) {
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

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

    priv = vm->privateData;

    if (virDomainObjIsActive(vm)) {
7322
        if (priv->job.asyncJob) {
7323
            VIR_DEBUG("Requesting cancellation of job on vm %s", vm->def->name);
7324
            priv->job.signals |= QEMU_JOB_SIGNAL_CANCEL;
7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344
        } else {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("no job is active on the domain"));
            goto cleanup;
        }
    } else {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

    ret = 0;

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


7345 7346 7347 7348 7349 7350 7351 7352 7353 7354
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;

7355
    virCheckFlags(0, -1);
7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375

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

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

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

    priv = vm->privateData;

7376
    if (priv->job.asyncJob != QEMU_ASYNC_JOB_MIGRATION_OUT) {
7377 7378 7379 7380 7381 7382
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not being migrated"));
        goto cleanup;
    }

    VIR_DEBUG("Requesting migration downtime change to %llums", downtime);
7383 7384
    priv->job.signalsData.migrateDowntime = downtime;
    priv->job.signals |= QEMU_JOB_SIGNAL_MIGRATE_DOWNTIME;
7385 7386 7387 7388 7389 7390 7391 7392 7393
    ret = 0;

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

7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424
static int
qemuDomainMigrateSetMaxSpeed(virDomainPtr dom,
                             unsigned long bandwidth,
                             unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(0, -1);

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

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

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

    priv = vm->privateData;

7425
    if (priv->job.asyncJob != QEMU_ASYNC_JOB_MIGRATION_OUT) {
7426 7427 7428 7429 7430 7431
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not being migrated"));
        goto cleanup;
    }

    VIR_DEBUG("Requesting migration speed change to %luMbs", bandwidth);
7432 7433
    priv->job.signalsData.migrateBandwidth = bandwidth;
    priv->job.signals |= QEMU_JOB_SIGNAL_MIGRATE_SPEED;
7434 7435 7436 7437 7438 7439 7440 7441 7442
    ret = 0;

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

C
Chris Lalancette 已提交
7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456
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;
}

7457 7458 7459
static int qemuDomainSnapshotWriteMetadata(virDomainObjPtr vm,
                                           virDomainSnapshotObjPtr snapshot,
                                           char *snapshotDir)
C
Chris Lalancette 已提交
7460 7461 7462 7463 7464 7465 7466 7467 7468
{
    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);
7469
    newxml = virDomainSnapshotDefFormat(uuidstr, snapshot->def, 1);
C
Chris Lalancette 已提交
7470 7471 7472 7473 7474 7475 7476 7477 7478
    if (newxml == NULL) {
        virReportOOMError();
        return -1;
    }

    if (virAsprintf(&snapDir, "%s/%s", snapshotDir, vm->def->name) < 0) {
        virReportOOMError();
        goto cleanup;
    }
7479 7480
    if (virFileMakePath(snapDir) < 0) {
        virReportSystemError(errno, _("cannot create snapshot directory '%s'"),
C
Chris Lalancette 已提交
7481 7482 7483 7484
                             snapDir);
        goto cleanup;
    }

7485
    if (virAsprintf(&snapFile, "%s/%s.xml", snapDir, snapshot->def->name) < 0) {
C
Chris Lalancette 已提交
7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506
        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);
7507
    VIR_FORCE_CLOSE(fd);
C
Chris Lalancette 已提交
7508 7509 7510
    return ret;
}

7511 7512
static int qemuDomainSnapshotSetCurrentActive(virDomainObjPtr vm,
                                              char *snapshotDir)
C
Chris Lalancette 已提交
7513 7514 7515 7516
{
    if (vm->current_snapshot) {
        vm->current_snapshot->def->active = 1;

7517 7518
        return qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                               snapshotDir);
C
Chris Lalancette 已提交
7519 7520 7521 7522 7523
    }

    return 0;
}

7524 7525
static int qemuDomainSnapshotSetCurrentInactive(virDomainObjPtr vm,
                                                char *snapshotDir)
C
Chris Lalancette 已提交
7526 7527 7528 7529
{
    if (vm->current_snapshot) {
        vm->current_snapshot->def->active = 0;

7530 7531
        return qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                               snapshotDir);
C
Chris Lalancette 已提交
7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550
    }

    return 0;
}


static int qemuDomainSnapshotIsAllowed(virDomainObjPtr vm)
{
    int i;

    /* FIXME: we need to figure out what else here might succeed; in
     * particular, if it's a raw device but on LVM, we could probably make
     * that succeed as well
     */
    for (i = 0; i < vm->def->ndisks; i++) {
        if (vm->def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
            (!vm->def->disks[i]->driverType ||
             STRNEQ(vm->def->disks[i]->driverType, "qcow2"))) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
7551 7552
                            _("Disk '%s' does not support snapshotting"),
                            vm->def->disks[i]->src);
C
Chris Lalancette 已提交
7553 7554 7555 7556 7557 7558 7559
            return 0;
        }
    }

    return 1;
}

7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607
/* 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
7608 7609
qemuDomainSnapshotCreateActive(virConnectPtr conn,
                               struct qemud_driver *driver,
7610 7611 7612 7613 7614
                               virDomainObjPtr *vmptr,
                               virDomainSnapshotObjPtr snap)
{
    virDomainObjPtr vm = *vmptr;
    qemuDomainObjPrivatePtr priv = vm->privateData;
7615 7616
    bool resume = false;
    int ret = -1;
7617

7618
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
7619 7620
        return -1;

J
Jiri Denemark 已提交
7621
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
7622 7623 7624 7625
        /* savevm monitor command pauses the domain emitting an event which
         * confuses libvirt since it's not notified when qemu resumes the
         * domain. Thus we stop and start CPUs ourselves.
         */
J
Jiri Denemark 已提交
7626
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE) < 0)
7627 7628 7629 7630 7631 7632 7633 7634 7635 7636
            goto cleanup;

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

7637
    ignore_value(qemuDomainObjEnterMonitorWithDriver(driver, vm));
7638 7639 7640
    ret = qemuMonitorCreateSnapshot(priv->mon, snap->def->name);
    qemuDomainObjExitMonitorWithDriver(driver, vm);

7641 7642
cleanup:
    if (resume && virDomainObjIsActive(vm) &&
J
Jiri Denemark 已提交
7643 7644
        qemuProcessStartCPUs(driver, vm, conn,
                             VIR_DOMAIN_RUNNING_UNPAUSED) < 0 &&
7645 7646 7647 7648 7649
        virGetLastError() == NULL) {
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("resuming after snapshot failed"));
    }

7650
    if (qemuDomainObjEndJob(driver, vm) == 0)
7651 7652 7653 7654 7655
        *vmptr = NULL;

    return ret;
}

C
Chris Lalancette 已提交
7656 7657
static virDomainSnapshotPtr qemuDomainSnapshotCreateXML(virDomainPtr domain,
                                                        const char *xmlDesc,
7658
                                                        unsigned int flags)
C
Chris Lalancette 已提交
7659 7660 7661 7662 7663 7664 7665 7666
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virDomainSnapshotDefPtr def;

7667 7668
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693
    qemuDriverLock(driver);
    virUUIDFormat(domain->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    /* in a perfect world, we would allow qemu to tell us this.  The problem
     * is that qemu only does this check device-by-device; so if you had a
     * domain that booted from a large qcow2 device, but had a secondary raw
     * device attached, you wouldn't find out that you can't snapshot your
     * guest until *after* it had spent the time to snapshot the boot device.
     * This is probably a bug in qemu, but we'll work around it here for now.
     */
    if (!qemuDomainSnapshotIsAllowed(vm))
        goto cleanup;

    if (!(def = virDomainSnapshotDefParseString(xmlDesc, 1)))
        goto cleanup;

    if (!(snap = virDomainSnapshotAssignDef(&vm->snapshots, def)))
        goto cleanup;

J
Jiri Denemark 已提交
7694
    snap->def->state = virDomainObjGetState(vm, NULL);
7695

C
Chris Lalancette 已提交
7696 7697
    /* actually do the snapshot */
    if (!virDomainObjIsActive(vm)) {
7698
        if (qemuDomainSnapshotCreateInactive(vm, snap) < 0)
C
Chris Lalancette 已提交
7699 7700 7701
            goto cleanup;
    }
    else {
7702 7703
        if (qemuDomainSnapshotCreateActive(domain->conn, driver,
                                           &vm, snap) < 0)
7704
            goto cleanup;
C
Chris Lalancette 已提交
7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722
    }

    /* FIXME: if we fail after this point, there's not a whole lot we can
     * do; we've successfully taken the snapshot, and we are now running
     * on it, so we have to go forward the best we can
     */

    if (vm->current_snapshot) {
        def->parent = strdup(vm->current_snapshot->def->name);
        if (def->parent == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    }

    /* Now we set the new current_snapshot for the domain */
    vm->current_snapshot = snap;

7723 7724 7725
    if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                        driver->snapshotDir) < 0)
        /* qemuDomainSnapshotWriteMetadata set the error */
C
Chris Lalancette 已提交
7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738
        goto cleanup;

    snapshot = virGetDomainSnapshot(domain, snap->def->name);

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

static int qemuDomainSnapshotListNames(virDomainPtr domain, char **names,
                                       int nameslen,
7739
                                       unsigned int flags)
C
Chris Lalancette 已提交
7740 7741 7742 7743 7744
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

7745 7746
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766
    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,
7767
                                 unsigned int flags)
C
Chris Lalancette 已提交
7768 7769 7770 7771 7772
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

7773 7774
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795
    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,
7796
                                                           unsigned int flags)
C
Chris Lalancette 已提交
7797 7798 7799 7800 7801 7802
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;

7803 7804
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831
    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,
7832
                                        unsigned int flags)
C
Chris Lalancette 已提交
7833 7834 7835 7836 7837
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

7838 7839
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859
    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,
7860
                                                      unsigned int flags)
C
Chris Lalancette 已提交
7861 7862 7863 7864 7865
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotPtr snapshot = NULL;

7866 7867
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892
    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;
}

7893 7894
static char *qemuDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                                          unsigned int flags)
C
Chris Lalancette 已提交
7895 7896 7897 7898 7899 7900 7901
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *xml = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

7902 7903
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930
    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,
7931
                                      unsigned int flags)
C
Chris Lalancette 已提交
7932 7933 7934 7935 7936 7937 7938 7939 7940 7941
{
    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;

7942 7943
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962
    qemuDriverLock(driver);
    virUUIDFormat(snapshot->domain->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
    if (!snap) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                        _("no domain snapshot with matching name '%s'"),
                        snapshot->name);
        goto cleanup;
    }

    vm->current_snapshot = snap;

7963
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
C
Chris Lalancette 已提交
7964 7965 7966 7967 7968 7969 7970
        goto cleanup;

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

        if (virDomainObjIsActive(vm)) {
            priv = vm->privateData;
7971
            ignore_value(qemuDomainObjEnterMonitorWithDriver(driver, vm));
C
Chris Lalancette 已提交
7972 7973 7974
            rc = qemuMonitorLoadSnapshot(priv->mon, snap->def->name);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            if (rc < 0)
7975
                goto endjob;
C
Chris Lalancette 已提交
7976 7977
        }
        else {
7978
            if (qemuDomainSnapshotSetCurrentActive(vm, driver->snapshotDir) < 0)
7979
                goto endjob;
C
Chris Lalancette 已提交
7980

7981
            rc = qemuProcessStart(snapshot->domain->conn, driver, vm, NULL,
7982
                                  false, false, -1, NULL, VIR_VM_OP_CREATE);
7983
            virDomainAuditStart(vm, "from-snapshot", rc >= 0);
7984
            if (qemuDomainSnapshotSetCurrentInactive(vm, driver->snapshotDir) < 0)
7985
                goto endjob;
C
Chris Lalancette 已提交
7986
            if (rc < 0)
7987
                goto endjob;
C
Chris Lalancette 已提交
7988 7989 7990 7991 7992 7993
        }

        if (snap->def->state == VIR_DOMAIN_PAUSED) {
            /* qemu unconditionally starts the domain running again after
             * loadvm, so let's pause it to keep consistency
             */
J
Jiri Denemark 已提交
7994 7995
            rc = qemuProcessStopCPUs(driver, vm,
                                     VIR_DOMAIN_PAUSED_FROM_SNAPSHOT);
H
Hu Tao 已提交
7996
            if (rc < 0)
7997
                goto endjob;
J
Jiri Denemark 已提交
7998 7999 8000
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_FROM_SNAPSHOT);
C
Chris Lalancette 已提交
8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018
        }

        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT);
    }
    else {
        /* qemu is a little funny with running guests and the restoration
         * of snapshots.  If the snapshot was taken online,
         * then after a "loadvm" monitor command, the VM is set running
         * again.  If the snapshot was taken offline, then after a "loadvm"
         * monitor command the VM is left paused.  Unpausing it leads to
         * the memory state *before* the loadvm with the disk *after* the
         * loadvm, which obviously is bound to corrupt something.
         * Therefore we destroy the domain and set it to "off" in this case.
         */

        if (virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
8019
            qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT);
8020
            virDomainAuditStop(vm, "from-snapshot");
C
Chris Lalancette 已提交
8021 8022 8023
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STOPPED,
                                             VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT);
8024
            if (!vm->persistent) {
8025
                if (qemuDomainObjEndJob(driver, vm) > 0)
8026 8027
                    virDomainRemoveInactive(&driver->domains, vm);
                vm = NULL;
8028
                goto cleanup;
8029
            }
C
Chris Lalancette 已提交
8030 8031
        }

8032
        if (qemuDomainSnapshotSetCurrentActive(vm, driver->snapshotDir) < 0)
8033
            goto endjob;
C
Chris Lalancette 已提交
8034 8035 8036 8037
    }

    ret = 0;

8038
endjob:
8039
    if (vm && qemuDomainObjEndJob(driver, vm) == 0)
C
Chris Lalancette 已提交
8040 8041
        vm = NULL;

8042
cleanup:
C
Chris Lalancette 已提交
8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094
    if (event)
        qemuDomainEventQueue(driver, event);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);

    return ret;
}

static int qemuDomainSnapshotDiscard(struct qemud_driver *driver,
                                     virDomainObjPtr vm,
                                     virDomainSnapshotObjPtr snap)
{
    const char *qemuimgarg[] = { NULL, "snapshot", "-d", NULL, NULL, NULL };
    char *snapFile = NULL;
    int ret = -1;
    int i;
    qemuDomainObjPrivatePtr priv;
    virDomainSnapshotObjPtr parentsnap;

    if (!virDomainObjIsActive(vm)) {
        qemuimgarg[0] = qemuFindQemuImgBinary();
        if (qemuimgarg[0] == NULL)
            /* qemuFindQemuImgBinary set the error */
            goto cleanup;

        qemuimgarg[3] = snap->def->name;

        for (i = 0; i < vm->def->ndisks; i++) {
            /* FIXME: we also need to handle LVM here */
            if (vm->def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
                if (!vm->def->disks[i]->driverType ||
                    STRNEQ(vm->def->disks[i]->driverType, "qcow2")) {
                    /* we continue on even in the face of error, since other
                     * disks in this VM may have this snapshot in place
                     */
                    continue;
                }

                qemuimgarg[4] = vm->def->disks[i]->src;

                if (virRun(qemuimgarg, NULL) < 0) {
                    /* we continue on even in the face of error, since other
                     * disks in this VM may have this snapshot in place
                     */
                    continue;
                }
            }
        }
    }
    else {
        priv = vm->privateData;
8095
        ignore_value(qemuDomainObjEnterMonitorWithDriver(driver, vm));
C
Chris Lalancette 已提交
8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144
        /* we continue on even in the face of error */
        qemuMonitorDeleteSnapshot(priv->mon, snap->def->name);
        qemuDomainObjExitMonitorWithDriver(driver, vm);
    }

    if (snap == vm->current_snapshot) {
        if (snap->def->parent) {
            parentsnap = virDomainSnapshotFindByName(&vm->snapshots,
                                                     snap->def->parent);
            if (!parentsnap) {
                qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                                _("no domain snapshot parent with matching name '%s'"),
                                snap->def->parent);
                goto cleanup;
            }

            /* Now we set the new current_snapshot for the domain */
            vm->current_snapshot = parentsnap;
        }
        else
            vm->current_snapshot = NULL;
    }

    if (virAsprintf(&snapFile, "%s/%s/%s.xml", driver->snapshotDir,
                    vm->def->name, snap->def->name) < 0) {
        virReportOOMError();
        goto cleanup;
    }
    unlink(snapFile);

    virDomainSnapshotObjListRemove(&vm->snapshots, snap);

    ret = 0;

cleanup:
    VIR_FREE(snapFile);
    VIR_FREE(qemuimgarg[0]);

    return ret;
}

struct snap_remove {
    struct qemud_driver *driver;
    virDomainObjPtr vm;
    char *parent;
    int err;
};

static void qemuDomainSnapshotDiscardChildren(void *payload,
8145
                                              const void *name ATTRIBUTE_UNUSED,
C
Chris Lalancette 已提交
8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166
                                              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);
    }
}

8167 8168 8169 8170 8171 8172 8173 8174 8175
struct snap_reparent {
    struct qemud_driver *driver;
    virDomainSnapshotObjPtr snap;
    virDomainObjPtr vm;
    int err;
};

static void
qemuDomainSnapshotReparentChildren(void *payload,
8176
                                   const void *name ATTRIBUTE_UNUSED,
8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203
                                   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 已提交
8204 8205 8206 8207 8208 8209 8210 8211 8212
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;
8213
    struct snap_reparent rep;
C
Chris Lalancette 已提交
8214

8215 8216
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

C
Chris Lalancette 已提交
8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233
    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;
    }

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

C
Chris Lalancette 已提交
8237 8238 8239 8240 8241 8242 8243 8244
    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)
8245
            goto endjob;
8246 8247 8248 8249 8250 8251 8252 8253 8254
    } 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 已提交
8255 8256 8257 8258
    }

    ret = qemuDomainSnapshotDiscard(driver, vm, snap);

8259
endjob:
8260
    if (qemuDomainObjEndJob(driver, vm) == 0)
8261 8262
        vm = NULL;

C
Chris Lalancette 已提交
8263 8264 8265 8266 8267 8268
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
8269

8270 8271 8272 8273 8274 8275 8276
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;
8277
    bool hmp;
8278

8279
    virCheckFlags(VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP, -1);
8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298

    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;

8299
    qemuDomainObjTaint(driver, vm, VIR_DOMAIN_TAINT_CUSTOM_MONITOR, -1);
8300

8301 8302
    hmp = !!(flags & VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP);

8303
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
8304
        goto cleanup;
8305
    ignore_value(qemuDomainObjEnterMonitorWithDriver(driver, vm));
8306
    ret = qemuMonitorArbitraryCommand(priv->mon, cmd, result, hmp);
8307
    qemuDomainObjExitMonitorWithDriver(driver, vm);
8308
    if (qemuDomainObjEndJob(driver, vm) == 0) {
8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319
        vm = NULL;
        goto cleanup;
    }

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

8320

8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375
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;

8376
    if (qemuDomainObjBeginJobWithDriver(driver, vm, QEMU_JOB_MODIFY) < 0)
8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390
        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:
8391
    if (qemuDomainObjEndJob(driver, vm) == 0) {
8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406
        vm = NULL;
        goto cleanup;
    }

cleanup:
    virDomainDefFree(def);
    virDomainChrSourceDefFree(monConfig);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    VIR_FREE(pidfile);
    return dom;
}


8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 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 8458 8459 8460 8461 8462
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;
    }

8463
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
8464 8465 8466 8467 8468 8469
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"),
                        NULLSTR(devname));
        goto cleanup;
    }

8470 8471
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
                            0, 0, O_RDWR, false) < 0)
8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482
        goto cleanup;

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


8483
static virDriver qemuDriver = {
8484 8485
    .no = VIR_DRV_QEMU,
    .name = "QEMU",
8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503
    .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 */
8504 8505
    .domainShutdown = qemuDomainShutdown, /* 0.2.0 */
    .domainReboot = qemuDomainReboot, /* 0.9.3 */
8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517
    .domainDestroy = qemudDomainDestroy, /* 0.2.0 */
    .domainGetOSType = qemudDomainGetOSType, /* 0.2.2 */
    .domainGetMaxMemory = qemudDomainGetMaxMemory, /* 0.4.2 */
    .domainSetMaxMemory = qemudDomainSetMaxMemory, /* 0.4.2 */
    .domainSetMemory = qemudDomainSetMemory, /* 0.4.2 */
    .domainSetMemoryFlags = qemudDomainSetMemoryFlags, /* 0.9.0 */
    .domainSetMemoryParameters = qemuDomainSetMemoryParameters, /* 0.8.5 */
    .domainGetMemoryParameters = qemuDomainGetMemoryParameters, /* 0.8.5 */
    .domainSetBlkioParameters = qemuDomainSetBlkioParameters, /* 0.9.0 */
    .domainGetBlkioParameters = qemuDomainGetBlkioParameters, /* 0.9.0 */
    .domainGetInfo = qemudDomainGetInfo, /* 0.2.0 */
    .domainGetState = qemuDomainGetState, /* 0.9.2 */
8518
    .domainGetControlInfo = qemuDomainGetControlInfo, /* 0.9.3 */
8519 8520 8521 8522
    .domainSave = qemudDomainSave, /* 0.2.0 */
    .domainRestore = qemuDomainRestore, /* 0.2.0 */
    .domainCoreDump = qemudDomainCoreDump, /* 0.7.0 */
    .domainScreenshot = qemuDomainScreenshot, /* 0.9.2 */
8523 8524
    .domainSetVcpus = qemuDomainSetVcpus, /* 0.4.4 */
    .domainSetVcpusFlags = qemuDomainSetVcpusFlags, /* 0.8.5 */
8525 8526
    .domainGetVcpusFlags = qemudDomainGetVcpusFlags, /* 0.8.5 */
    .domainPinVcpu = qemudDomainPinVcpu, /* 0.4.4 */
8527
    .domainPinVcpuFlags = qemudDomainPinVcpuFlags, /* 0.9.3 */
E
Eric Blake 已提交
8528
    .domainGetVcpuPinInfo = qemudDomainGetVcpuPinInfo, /* 0.9.3 */
8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550
    .domainGetVcpus = qemudDomainGetVcpus, /* 0.4.4 */
    .domainGetMaxVcpus = qemudDomainGetMaxVcpus, /* 0.4.4 */
    .domainGetSecurityLabel = qemudDomainGetSecurityLabel, /* 0.6.1 */
    .nodeGetSecurityModel = qemudNodeGetSecurityModel, /* 0.6.1 */
    .domainGetXMLDesc = qemuDomainGetXMLDesc, /* 0.2.0 */
    .domainXMLFromNative = qemuDomainXMLFromNative, /* 0.6.4 */
    .domainXMLToNative = qemuDomainXMLToNative, /* 0.6.4 */
    .listDefinedDomains = qemudListDefinedDomains, /* 0.2.0 */
    .numOfDefinedDomains = qemudNumDefinedDomains, /* 0.2.0 */
    .domainCreate = qemudDomainStart, /* 0.2.0 */
    .domainCreateWithFlags = qemudDomainStartWithFlags, /* 0.8.2 */
    .domainDefineXML = qemudDomainDefine, /* 0.2.0 */
    .domainUndefine = qemudDomainUndefine, /* 0.2.0 */
    .domainAttachDevice = qemuDomainAttachDevice, /* 0.4.1 */
    .domainAttachDeviceFlags = qemuDomainAttachDeviceFlags, /* 0.7.7 */
    .domainDetachDevice = qemuDomainDetachDevice, /* 0.5.0 */
    .domainDetachDeviceFlags = qemuDomainDetachDeviceFlags, /* 0.7.7 */
    .domainUpdateDeviceFlags = qemuDomainUpdateDeviceFlags, /* 0.8.0 */
    .domainGetAutostart = qemudDomainGetAutostart, /* 0.2.1 */
    .domainSetAutostart = qemudDomainSetAutostart, /* 0.2.1 */
    .domainGetSchedulerType = qemuGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = qemuGetSchedulerParameters, /* 0.7.0 */
8551
    .domainGetSchedulerParametersFlags = qemuGetSchedulerParametersFlags, /* 0.9.2 */
8552
    .domainSetSchedulerParameters = qemuSetSchedulerParameters, /* 0.7.0 */
8553
    .domainSetSchedulerParametersFlags = qemuSetSchedulerParametersFlags, /* 0.9.2 */
8554 8555 8556 8557 8558 8559 8560
    .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 */
8561
    .nodeGetCPUStats = nodeGetCPUStats, /* 0.9.3 */
8562
    .nodeGetMemoryStats = nodeGetMemoryStats, /* 0.9.3 */
8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598
    .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 */
8599
    .qemuDomainAttach = qemuDomainAttach, /* 0.9.4 */
8600 8601
    .domainOpenConsole = qemuDomainOpenConsole, /* 0.8.6 */
    .domainInjectNMI = qemuDomainInjectNMI, /* 0.9.2 */
8602 8603 8604 8605 8606 8607
    .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 */
8608 8609 8610
};


8611
static virStateDriver qemuStateDriver = {
8612
    .name = "QEMU",
8613 8614 8615 8616
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
8617
};
8618

8619
static void
8620
qemuVMDriverLock(void) {
8621 8622 8623 8624 8625
    qemuDriverLock(qemu_driver);
};


static void
8626
qemuVMDriverUnlock(void) {
8627 8628 8629 8630
    qemuDriverUnlock(qemu_driver);
};


8631 8632 8633 8634 8635 8636 8637 8638 8639
static int
qemuVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                    virHashIterator iter, void *data)
{
    virHashForEach(qemu_driver->domains.objs, iter, data);

    return 0;
}

S
Stefan Berger 已提交
8640 8641
static virNWFilterCallbackDriver qemuCallbackDriver = {
    .name = "QEMU",
8642 8643 8644
    .vmFilterRebuild = qemuVMFilterRebuild,
    .vmDriverLock = qemuVMDriverLock,
    .vmDriverUnlock = qemuVMDriverUnlock,
S
Stefan Berger 已提交
8645 8646
};

8647
int qemuRegister(void) {
8648 8649
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
S
Stefan Berger 已提交
8650
    virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);
8651 8652
    return 0;
}