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

24
#include <config.h>
25

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

48

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

#include "virterror_internal.h"
#include "logging.h"
#include "datatypes.h"
65
#include "event.h"
66
#include "buf.h"
67
#include "util.h"
68
#include "nodeinfo.h"
69
#include "stats_linux.h"
70
#include "capabilities.h"
71
#include "memory.h"
72
#include "uuid.h"
73
#include "domain_conf.h"
74 75
#include "node_device_conf.h"
#include "pci.h"
76
#include "hostusb.h"
77
#include "processinfo.h"
C
Chris Lalancette 已提交
78
#include "libvirt_internal.h"
79
#include "xml.h"
80
#include "cpu/cpu.h"
81
#include "macvtap.h"
82
#include "sysinfo.h"
83
#include "domain_nwfilter.h"
84
#include "hooks.h"
85
#include "storage_file.h"
86
#include "files.h"
87
#include "fdstream.h"
88
#include "configmake.h"
H
Hu Tao 已提交
89
#include "threadpool.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 115

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

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

119 120
static int qemudShutdown(void);

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

126
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
127

128
struct qemud_driver *qemu_driver = NULL;
129 130


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

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

    virDomainObjLock(vm);
144 145 146 147 148 149 150 151 152
    virResetLastError();
    if (qemuDomainObjBeginJobWithDriver(data->driver, vm) < 0) {
        err = virGetLastError();
        VIR_ERROR(_("Failed to start job on VM '%s': %s"),
                  vm->def->name,
                  err ? err->message : _("unknown error"));
    } else {
        if (vm->autostart &&
            !virDomainObjIsActive(vm) &&
153
            qemudDomainObjStart(data->conn, data->driver, vm, 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 161

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

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

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

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

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

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

597
        qemu_driver->hugepage_path = mempath;
598
    }
599

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

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

612
    qemuProcessReconnectAll(conn, qemu_driver);
613

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

622

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

626 627 628
    qemu_driver->workerPool = virThreadPoolNew(0, 1, processWatchdogEvent, qemu_driver);
    if (!qemu_driver->workerPool)
        goto error;
629

630 631 632 633
    qemuDriverUnlock(qemu_driver);

    qemuAutostartDomains(qemu_driver);

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

637
    return 0;
638

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

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

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

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

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

685
    qemuAutostartDomains(qemu_driver);
686

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

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

702 703
    if (!qemu_driver)
        return 0;
704

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

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

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

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

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

731
    virSysinfoDefFree(qemu_driver->hostsysinfo);
732

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

754
    virSecurityManagerFree(qemu_driver->securityManager);
755

756
    ebtablesContextFree(qemu_driver->ebtables);
757

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

764
    /* Free domain callback list */
765
    virDomainEventStateFree(qemu_driver->domainEventState);
D
Daniel P. Berrange 已提交
766

767 768
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);
769

770
    virCgroupFree(&qemu_driver->cgroup);
771

772 773 774 775
    qemuDriverUnlock(qemu_driver);
    virMutexDestroy(&qemu_driver->lock);
    virThreadPoolFree(qemu_driver->workerPool);
    VIR_FREE(qemu_driver);
776

777
    return 0;
778 779
}

780 781 782 783 784 785 786

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


787
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
788
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
789
                                  int flags ATTRIBUTE_UNUSED) {
790
    if (conn->uri == NULL) {
791 792 793
        if (qemu_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

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

811
        if (qemu_driver == NULL) {
812 813
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("qemu state driver is not active"));
814 815 816
            return VIR_DRV_OPEN_ERROR;
        }

817
        if (conn->uri->path == NULL) {
818 819 820 821 822
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("no QEMU URI path given, try %s"),
                            qemu_driver->privileged
                            ? "qemu:///system"
                            : "qemu:///session");
823 824 825
                return VIR_DRV_OPEN_ERROR;
        }

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

    return VIR_DRV_OPEN_SUCCESS;
}

static int qemudClose(virConnectPtr conn) {
849
    struct qemud_driver *driver = conn->privateData;
850 851

    /* Get rid of callbacks registered for this conn */
852
    qemuDriverLock(driver);
853 854
    virDomainEventCallbackListRemoveConn(conn,
                                         driver->domainEventState->callbacks);
855
    qemuDriverUnlock(driver);
856 857 858 859 860 861

    conn->privateData = NULL;

    return 0;
}

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

876
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
877
    return "QEMU";
878 879
}

880

881 882 883 884 885 886 887 888 889 890 891 892 893
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;
}


894 895 896 897
static int kvmGetMaxVCPUs(void) {
    int maxvcpus = 1;

    int r, fd;
898

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

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

909
    VIR_FORCE_CLOSE(fd);
910 911 912 913
    return maxvcpus;
}


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

930
static int qemudGetMaxVCPUs(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
931 932 933
    if (!type)
        return 16;

934
    if (STRCASEEQ(type, "qemu"))
935 936
        return 16;

937
    if (STRCASEEQ(type, "kvm"))
938
        return kvmGetMaxVCPUs();
939

940
    if (STRCASEEQ(type, "kqemu"))
941
        return 1;
942

943 944
    qemuReportError(VIR_ERR_INVALID_ARG,
                    _("unknown type '%s'"), type);
945 946 947
    return -1;
}

948

949
static char *qemudGetCapabilities(virConnectPtr conn) {
950
    struct qemud_driver *driver = conn->privateData;
951
    virCapsPtr caps = NULL;
952
    char *xml = NULL;
953

954
    qemuDriverLock(driver);
955

956
    if ((caps = qemuCreateCapabilities(qemu_driver->caps,
957
                                       qemu_driver)) == NULL) {
958 959 960
        virCapabilitiesFree(caps);
        goto cleanup;
    }
961

962
    virCapabilitiesFree(qemu_driver->caps);
963 964 965
    qemu_driver->caps = caps;

    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
966
        virReportOOMError();
967 968

cleanup:
969
    qemuDriverUnlock(driver);
970

971
    return xml;
972 973 974
}


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

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

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

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

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

D
Daniel P. Berrange 已提交
1029

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

1033
    VIR_FORCE_FCLOSE(pidinfo);
D
Daniel P. Berrange 已提交
1034 1035 1036 1037 1038

    return 0;
}


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

1045
    qemuDriverLock(driver);
1046
    vm  = virDomainFindByID(&driver->domains, id);
1047
    qemuDriverUnlock(driver);
1048 1049

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

1055
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1056
    if (dom) dom->id = vm->def->id;
1057 1058

cleanup:
1059 1060
    if (vm)
        virDomainObjUnlock(vm);
1061 1062
    return dom;
}
1063

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

1070
    qemuDriverLock(driver);
1071
    vm = virDomainFindByUUID(&driver->domains, uuid);
1072 1073
    qemuDriverUnlock(driver);

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

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

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

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

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

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

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

cleanup:
1111 1112
    if (vm)
        virDomainObjUnlock(vm);
1113 1114 1115
    return dom;
}

1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126

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

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

1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
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 已提交
1175 1176 1177 1178
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1179 1180 1181 1182 1183 1184 1185 1186 1187
        goto cleanup;
    }
    ret = obj->updated;

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

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

1193
    qemuDriverLock(driver);
1194
    if (qemuCapsExtractVersion(driver->caps, &driver->qemuVersion) < 0)
1195
        goto cleanup;
1196

1197
    *version = driver->qemuVersion;
1198 1199 1200
    ret = 0;

cleanup:
1201
    qemuDriverUnlock(driver);
1202
    return ret;
D
Daniel P. Berrange 已提交
1203 1204
}

1205
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1206
    struct qemud_driver *driver = conn->privateData;
1207
    int n;
1208

1209
    qemuDriverLock(driver);
1210
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
1211
    qemuDriverUnlock(driver);
1212

1213
    return n;
D
Daniel P. Berrange 已提交
1214
}
1215

1216
static int qemudNumDomains(virConnectPtr conn) {
1217
    struct qemud_driver *driver = conn->privateData;
1218
    int n;
1219

1220
    qemuDriverLock(driver);
1221
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
1222
    qemuDriverUnlock(driver);
1223

1224
    return n;
D
Daniel P. Berrange 已提交
1225
}
1226

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

1235
    virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);
1236

1237
    qemuDriverLock(driver);
1238
    if (!(def = virDomainDefParseString(driver->caps, xml,
1239
                                        VIR_DOMAIN_XML_INACTIVE)))
1240
        goto cleanup;
1241

1242
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
1243 1244
        goto cleanup;

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

1248 1249 1250
    if (qemudCanonicalizeMachine(driver, def) < 0)
        goto cleanup;

1251
    if (qemuDomainAssignPCIAddresses(def) < 0)
1252 1253
        goto cleanup;

1254
    if (!(vm = virDomainAssignDef(driver->caps,
1255
                                  &driver->domains,
1256
                                  def, false)))
1257 1258 1259
        goto cleanup;

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

1261 1262 1263
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup; /* XXXX free the 'vm' we created ? */

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

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

1280
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1281
    if (dom) dom->id = vm->def->id;
1282

1283 1284 1285
    if (vm &&
        qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1286

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


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

1305
    qemuDriverLock(driver);
1306
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1307

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

    priv = vm->privateData;

1323
    if (priv->jobActive == QEMU_JOB_MIGRATION_OUT) {
J
Jiri Denemark 已提交
1324
        if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
            VIR_DEBUG("Requesting domain pause on %s",
                      vm->def->name);
            priv->jobSignals |= QEMU_JOB_SIGNAL_SUSPEND;
        }
        ret = 0;
        goto cleanup;
    } else {
        if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
            goto cleanup;

        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
1338
            goto endjob;
1339
        }
J
Jiri Denemark 已提交
1340 1341
        if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
            if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_USER) < 0) {
1342
                goto endjob;
1343
            }
1344 1345 1346 1347 1348 1349 1350
            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 已提交
1351
    }
1352

1353
endjob:
1354 1355
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1356

1357
cleanup:
1358 1359
    if (vm)
        virDomainObjUnlock(vm);
1360

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


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

1374
    qemuDriverLock(driver);
1375
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1376

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

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

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

1409
endjob:
1410 1411
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1412

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


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

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

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

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

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

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

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

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


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

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

1482 1483 1484 1485 1486 1487 1488
    /* 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);

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

D
Daniel P. Berrange 已提交
1492
    if (!virDomainObjIsActive(vm)) {
1493 1494
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
1495
        goto endjob;
1496
    }
1497

J
Jiri Denemark 已提交
1498
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_DESTROYED);
1499 1500 1501
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1502
    qemuAuditDomainStop(vm, "destroyed");
1503

1504
    if (!vm->persistent) {
1505 1506 1507
        if (qemuDomainObjEndJob(vm) > 0)
            virDomainRemoveInactive(&driver->domains,
                                    vm);
1508 1509
        vm = NULL;
    }
1510 1511
    ret = 0;

1512
endjob:
1513 1514 1515
    if (vm &&
        qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1516

1517
cleanup:
1518 1519
    if (vm)
        virDomainObjUnlock(vm);
1520 1521
    if (event)
        qemuDomainEventQueue(driver, event);
1522
    qemuDriverUnlock(driver);
1523
    return ret;
D
Daniel P. Berrange 已提交
1524 1525 1526
}


1527
static char *qemudDomainGetOSType(virDomainPtr dom) {
1528 1529 1530
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1531

1532
    qemuDriverLock(driver);
1533
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1534
    qemuDriverUnlock(driver);
1535
    if (!vm) {
1536 1537
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1538 1539
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1540
        goto cleanup;
1541 1542
    }

1543
    if (!(type = strdup(vm->def->os.type)))
1544
        virReportOOMError();
1545 1546

cleanup:
1547 1548
    if (vm)
        virDomainObjUnlock(vm);
1549 1550 1551
    return type;
}

1552 1553
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
1554 1555 1556
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
1557

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

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

1570
    ret = vm->def->mem.max_balloon;
1571 1572

cleanup:
1573 1574
    if (vm)
        virDomainObjUnlock(vm);
1575
    return ret;
1576 1577
}

1578 1579
static int qemudDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
                                     unsigned int flags) {
1580
    struct qemud_driver *driver = dom->conn->privateData;
1581
    qemuDomainObjPrivatePtr priv;
1582
    virDomainObjPtr vm;
1583
    virDomainDefPtr persistentDef = NULL;
1584
    int ret = -1, r;
1585
    bool isActive;
1586

1587
    virCheckFlags(VIR_DOMAIN_MEM_LIVE |
1588 1589
                  VIR_DOMAIN_MEM_CONFIG |
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1590

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

1602 1603 1604
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

1605 1606 1607 1608 1609 1610 1611 1612
    isActive = virDomainObjIsActive(vm);

    if (flags == VIR_DOMAIN_MEM_CURRENT) {
        if (isActive)
            flags = VIR_DOMAIN_MEM_LIVE;
        else
            flags = VIR_DOMAIN_MEM_CONFIG;
    }
1613 1614 1615 1616 1617 1618
    if (flags == VIR_DOMAIN_MEM_MAXIMUM) {
        if (isActive)
            flags = VIR_DOMAIN_MEM_LIVE | VIR_DOMAIN_MEM_MAXIMUM;
        else
            flags = VIR_DOMAIN_MEM_CONFIG | VIR_DOMAIN_MEM_MAXIMUM;
    }
1619 1620

    if (!isActive && (flags & VIR_DOMAIN_MEM_LIVE)) {
1621 1622 1623 1624 1625
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto endjob;
    }

1626 1627 1628 1629 1630 1631 1632 1633 1634
    if (flags & VIR_DOMAIN_MEM_CONFIG) {
        if (!vm->persistent) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot change persistent config of a transient domain"));
            goto endjob;
        }
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
            goto endjob;
    }
1635

1636 1637 1638 1639 1640 1641 1642
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */

        if (flags & VIR_DOMAIN_MEM_LIVE) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("cannot resize the maximum memory on an "
                              "active domain"));
1643
            goto endjob;
1644
        }
1645

1646
        if (flags & VIR_DOMAIN_MEM_CONFIG) {
E
Eric Blake 已提交
1647 1648
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
1649 1650 1651 1652
            persistentDef->mem.max_balloon = newmem;
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
1653 1654 1655
            goto endjob;
        }

1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
    } 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;
        }

        if (flags & VIR_DOMAIN_MEM_LIVE) {
            priv = vm->privateData;
            qemuDomainObjEnterMonitor(vm);
            r = qemuMonitorSetBalloon(priv->mon, newmem);
            qemuDomainObjExitMonitor(vm);
            qemuAuditMemory(vm, vm->def->mem.cur_balloon, newmem, "update",
                            r == 1);
            if (r < 0)
                goto endjob;

            /* Lack of balloon support is a fatal error */
            if (r == 0) {
                qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                _("cannot set memory of an active domain"));
                goto endjob;
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
E
Eric Blake 已提交
1684
            sa_assert(persistentDef);
1685 1686 1687 1688
            persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
            goto endjob;
        }
1689
    }
1690

1691
    ret = 0;
1692
endjob:
1693 1694
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
1695

1696
cleanup:
1697 1698
    if (vm)
        virDomainObjUnlock(vm);
1699
    return ret;
1700 1701
}

1702 1703
static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem)
{
1704 1705 1706
    return qemudDomainSetMemoryFlags(dom, newmem, VIR_DOMAIN_MEM_LIVE);
}

1707 1708 1709 1710 1711
static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return qemudDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

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

    virCheckFlags(0, -1);

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

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

    priv = vm->privateData;

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

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

1756
static int qemudDomainGetInfo(virDomainPtr dom,
1757 1758
                              virDomainInfoPtr info)
{
1759 1760 1761
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1762 1763
    int err;
    unsigned long balloon;
1764

1765
    qemuDriverLock(driver);
1766
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1767
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
1768
    if (!vm) {
1769 1770
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1771 1772
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
1773
        goto cleanup;
D
Daniel P. Berrange 已提交
1774 1775
    }

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

D
Daniel P. Berrange 已提交
1778
    if (!virDomainObjIsActive(vm)) {
1779
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
1780
    } else {
1781
        if (qemudGetProcessInfo(&(info->cpuTime), NULL, vm->pid, 0) < 0) {
E
Eric Blake 已提交
1782 1783
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("cannot read cputime for domain"));
1784
            goto cleanup;
D
Daniel P. Berrange 已提交
1785 1786 1787
        }
    }

1788
    info->maxMem = vm->def->mem.max_balloon;
1789

D
Daniel P. Berrange 已提交
1790
    if (virDomainObjIsActive(vm)) {
1791
        qemuDomainObjPrivatePtr priv = vm->privateData;
1792 1793 1794

        if ((vm->def->memballoon != NULL) &&
            (vm->def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_NONE)) {
1795
            info->memory = vm->def->mem.max_balloon;
1796
        } else if (!priv->jobActive) {
1797 1798
            if (qemuDomainObjBeginJob(vm) < 0)
                goto cleanup;
1799 1800 1801 1802 1803 1804 1805 1806 1807
            if (!virDomainObjIsActive(vm))
                err = 0;
            else {
                qemuDomainObjEnterMonitor(vm);
                err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
                qemuDomainObjExitMonitor(vm);
            }
            if (qemuDomainObjEndJob(vm) == 0) {
                vm = NULL;
1808 1809 1810
                goto cleanup;
            }

1811 1812
            if (err < 0)
                goto cleanup;
1813 1814
            if (err == 0)
                /* Balloon not supported, so maxmem is always the allocation */
1815
                info->memory = vm->def->mem.max_balloon;
1816 1817 1818
            else
                info->memory = balloon;
        } else {
1819
            info->memory = vm->def->mem.cur_balloon;
1820
        }
1821
    } else {
1822
        info->memory = vm->def->mem.cur_balloon;
1823 1824
    }

1825
    info->nrVirtCpu = vm->def->vcpus;
1826 1827 1828
    ret = 0;

cleanup:
1829 1830
    if (vm)
        virDomainObjUnlock(vm);
1831
    return ret;
D
Daniel P. Berrange 已提交
1832 1833
}

1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
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 已提交
1858
    *state = virDomainObjGetState(vm, reason);
1859 1860 1861 1862 1863 1864 1865 1866
    ret = 0;

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

D
Daniel P. Berrange 已提交
1867

1868
#define QEMUD_SAVE_MAGIC "LibvirtQemudSave"
1869 1870 1871
#define QEMUD_SAVE_VERSION 2

enum qemud_save_formats {
1872 1873 1874
    QEMUD_SAVE_FORMAT_RAW = 0,
    QEMUD_SAVE_FORMAT_GZIP = 1,
    QEMUD_SAVE_FORMAT_BZIP2 = 2,
1875 1876
    /*
     * Deprecated by xz and never used as part of a release
1877
     * QEMUD_SAVE_FORMAT_LZMA
1878 1879
     */
    QEMUD_SAVE_FORMAT_XZ = 3,
1880
    QEMUD_SAVE_FORMAT_LZOP = 4,
1881 1882 1883
    /* Note: add new members only at the end.
       These values are used in the on-disk format.
       Do not change or re-use numbers. */
1884 1885

    QEMUD_SAVE_FORMAT_LAST
1886
};
1887

1888 1889 1890 1891 1892
VIR_ENUM_DECL(qemudSaveCompression)
VIR_ENUM_IMPL(qemudSaveCompression, QEMUD_SAVE_FORMAT_LAST,
              "raw",
              "gzip",
              "bzip2",
1893 1894
              "xz",
              "lzop")
1895

1896 1897
struct qemud_save_header {
    char magic[sizeof(QEMUD_SAVE_MAGIC)-1];
1898 1899 1900 1901 1902
    uint32_t version;
    uint32_t xml_len;
    uint32_t was_running;
    uint32_t compressed;
    uint32_t unused[15];
1903 1904
};

1905 1906 1907 1908 1909 1910 1911 1912 1913
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);
}


1914
/* return -errno on failure, or 0 on success */
E
Eric Blake 已提交
1915 1916 1917 1918
static int
qemuDomainSaveHeader(int fd, const char *path, char *xml,
                     struct qemud_save_header *header)
{
1919 1920
    int ret = 0;

E
Eric Blake 已提交
1921
    if (safewrite(fd, header, sizeof(*header)) != sizeof(*header)) {
1922
        ret = -errno;
1923
        qemuReportError(VIR_ERR_OPERATION_FAILED,
1924
                        _("failed to write header to domain save file '%s'"),
E
Eric Blake 已提交
1925
                        path);
1926 1927 1928
        goto endjob;
    }

E
Eric Blake 已提交
1929
    if (safewrite(fd, xml, header->xml_len) != header->xml_len) {
1930
        ret = -errno;
1931
        qemuReportError(VIR_ERR_OPERATION_FAILED,
E
Eric Blake 已提交
1932
                         _("failed to write xml to '%s'"), path);
1933 1934 1935 1936 1937 1938
        goto endjob;
    }
endjob:
    return ret;
}

1939 1940 1941 1942 1943 1944 1945 1946 1947
/* 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));
}

1948 1949 1950
/* This internal function expects the driver lock to already be held on
 * entry and the vm must be active.
 */
1951 1952
static int qemudDomainSaveFlag(struct qemud_driver *driver, virDomainPtr dom,
                               virDomainObjPtr vm, const char *path,
1953
                               int compressed)
1954
{
1955
    char *xml = NULL;
1956
    struct qemud_save_header header;
1957
    bool bypassSecurityDriver = false;
1958
    int ret = -1;
1959
    int rc;
1960
    virDomainEventPtr event = NULL;
1961
    qemuDomainObjPrivatePtr priv;
1962
    struct stat sb;
1963
    bool is_reg = false;
1964
    unsigned long long offset;
1965
    int fd = -1;
1966 1967 1968 1969 1970

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

1971
    header.compressed = compressed;
1972

1973
    priv = vm->privateData;
1974

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

O
Osier Yang 已提交
1978 1979
    priv->jobActive = QEMU_JOB_SAVE;

1980 1981 1982
    memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
    priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;

1983
    /* Pause */
J
Jiri Denemark 已提交
1984
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
1985
        header.was_running = 1;
J
Jiri Denemark 已提交
1986
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE) < 0)
1987
            goto endjob;
1988 1989 1990 1991 1992 1993

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

    /* Get XML for the domain */
1997
    xml = virDomainDefFormat(vm->def, VIR_DOMAIN_XML_SECURE);
1998
    if (!xml) {
1999 2000
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to get domain xml"));
2001
        goto endjob;
2002 2003 2004
    }
    header.xml_len = strlen(xml) + 1;

2005 2006 2007 2008 2009 2010 2011 2012
    /* 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 */
2013
        is_reg = true;
2014
    } else {
2015
        is_reg = !!S_ISREG(sb.st_mode);
2016 2017
    }

2018 2019 2020 2021 2022
    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
2023 2024
     * it by padding the XML string with NULLs.
     */
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
    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;
    }
2038

2039
    /* Obtain the file handle.  */
2040

2041
    /* First try creating the file as root */
2042
    if (!is_reg) {
2043
        fd = open(path, O_WRONLY | O_TRUNC);
2044 2045
        if (fd < 0) {
            virReportSystemError(errno, _("unable to open %s"), path);
2046 2047
            goto endjob;
        }
2048
    } else {
2049 2050 2051
        if ((fd = virFileOpenAs(path, O_CREAT|O_TRUNC|O_WRONLY,
                                S_IRUSR|S_IWUSR,
                                getuid(), getgid(), 0)) < 0) {
2052
            /* If we failed as root, and the error was permission-denied
2053 2054
               (EACCES or EPERM), assume it's on a network-connected share
               where root access is restricted (eg, root-squashed NFS). If the
2055 2056 2057
               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 */
2058
            rc = fd;
2059
            if (((rc != -EACCES) && (rc != -EPERM)) ||
2060
                driver->user == getuid()) {
2061 2062
                virReportSystemError(-rc,
                                    _("Failed to create domain save file '%s'"),
2063 2064 2065
                                     path);
                goto endjob;
            }
2066

2067
            /* On Linux we can also verify the FS-type of the directory. */
2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
            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:
2085
                   /* local file - log the error returned by virFileOpenAs */
2086
                   virReportSystemError(-rc,
2087
                                    _("Failed to create domain save file '%s'"),
2088 2089 2090
                                        path);
                   goto endjob;
                   break;
2091 2092 2093

            }

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

2096 2097 2098 2099
            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) {
2100 2101 2102
                virReportSystemError(-fd,
                                   _("Error from child process creating '%s'"),
                                     path);
2103 2104
                goto endjob;
            }
2105

2106 2107 2108
            /* 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 */
2109

2110
            bypassSecurityDriver = true;
2111
        }
2112
    }
2113

2114
    /* Write header to file, followed by XML */
E
Eric Blake 已提交
2115
    if (qemuDomainSaveHeader(fd, path, xml, &header) < 0) {
2116 2117 2118 2119
        VIR_FORCE_CLOSE(fd);
        goto endjob;
    }

2120
    /* Perform the migration */
2121
    if (qemuMigrationToFile(driver, vm, fd, offset, path,
2122 2123
                            qemuCompressProgramName(compressed),
                            is_reg, bypassSecurityDriver) < 0)
2124
        goto endjob;
2125 2126
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("unable to close %s"), path);
2127
        goto endjob;
2128 2129
    }

2130 2131
    ret = 0;

2132
    /* Shut it down */
J
Jiri Denemark 已提交
2133
    qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_SAVED);
2134
    qemuAuditDomainStop(vm, "saved");
2135 2136 2137
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2138
    if (!vm->persistent) {
2139 2140 2141
        if (qemuDomainObjEndJob(vm) > 0)
            virDomainRemoveInactive(&driver->domains,
                                    vm);
2142 2143
        vm = NULL;
    }
2144

2145
endjob:
2146
    if (vm) {
2147
        if (ret != 0) {
2148
            if (header.was_running && virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
2149 2150
                rc = qemuProcessStartCPUs(driver, vm, dom->conn,
                                          VIR_DOMAIN_RUNNING_SAVE_CANCELED);
2151
                if (rc < 0)
2152
                    VIR_WARN("Unable to resume guest CPUs after save failure");
2153
            }
2154
        }
2155
        if (qemuDomainObjEndJob(vm) == 0)
2156
            vm = NULL;
2157
    }
2158

2159
cleanup:
2160
    VIR_FORCE_CLOSE(fd);
2161
    VIR_FREE(xml);
2162
    if (ret != 0 && is_reg)
2163
        unlink(path);
2164 2165
    if (event)
        qemuDomainEventQueue(driver, event);
2166
    return ret;
D
Daniel P. Berrange 已提交
2167 2168
}

2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184
/* 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;
}

2185 2186 2187 2188
static int qemudDomainSave(virDomainPtr dom, const char *path)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int compressed;
2189 2190 2191 2192
    int ret = -1;
    virDomainObjPtr vm = NULL;

    qemuDriverLock(driver);
2193 2194 2195 2196 2197 2198 2199 2200 2201

    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"));
2202
            goto cleanup;
2203
        }
2204 2205 2206 2207
        if (!qemudCompressProgramAvailable(compressed)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Compression program for image format "
                                    "in configuration file isn't available"));
2208
            goto cleanup;
2209
        }
2210 2211
    }

2212 2213 2214 2215 2216 2217 2218 2219 2220
    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;
    }

2221 2222 2223 2224 2225 2226
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2227 2228 2229 2230 2231 2232 2233 2234
    ret = qemudDomainSaveFlag(driver, dom, vm, path, compressed);

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

    return ret;
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257
}

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;

2258
    virCheckFlags(0, -1);
2259 2260 2261 2262 2263 2264 2265 2266

    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);
2267
        goto cleanup;
2268 2269
    }

2270 2271 2272 2273 2274 2275
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

2276 2277
    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
2278
        goto cleanup;
2279

2280
    VIR_INFO("Saving state to %s", name);
2281 2282

    compressed = QEMUD_SAVE_FORMAT_RAW;
2283
    ret = qemudDomainSaveFlag(driver, dom, vm, name, compressed);
2284 2285 2286 2287 2288

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
2289 2290 2291
    VIR_FREE(name);

    return ret;
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
}

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

2302
    virCheckFlags(0, -1);
2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335

    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;

2336
    virCheckFlags(0, -1);
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360

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

H
Hu Tao 已提交
2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
static int doCoreDump(struct qemud_driver *driver,
                      virDomainObjPtr vm,
                      const char *path,
                      enum qemud_save_formats compress)
{
    int fd = -1;
    int ret = -1;

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

2377
    if (qemuMigrationToFile(driver, vm, fd, 0, path,
2378 2379 2380
                            qemuCompressProgramName(compress), true, false) < 0)
        goto cleanup;

H
Hu Tao 已提交
2381 2382 2383 2384 2385 2386 2387
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno,
                             _("unable to save file %s"),
                             path);
        goto cleanup;
    }

2388
    ret = 0;
H
Hu Tao 已提交
2389 2390 2391 2392 2393 2394 2395

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

2396 2397 2398 2399 2400
static enum qemud_save_formats
getCompressionType(struct qemud_driver *driver)
{
    int compress = QEMUD_SAVE_FORMAT_RAW;

2401 2402 2403 2404 2405 2406 2407
    /*
     * 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) {
2408 2409 2410 2411
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("Invalid dump image format specified in "
                              "configuration file, using raw"));
            return QEMUD_SAVE_FORMAT_RAW;
2412
        }
2413 2414 2415
        if (!qemudCompressProgramAvailable(compress)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Compression program for dump image format "
2416 2417 2418
                                    "in configuration file isn't available, "
                                    "using raw"));
            return QEMUD_SAVE_FORMAT_RAW;
2419
        }
2420
    }
2421 2422 2423 2424 2425
    return compress;
}

static int qemudDomainCoreDump(virDomainPtr dom,
                               const char *path,
2426 2427
                               int flags)
{
2428 2429 2430
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int resume = 0, paused = 0;
H
Hu Tao 已提交
2431
    int ret = -1;
2432 2433 2434
    virDomainEventPtr event = NULL;
    qemuDomainObjPrivatePtr priv;

2435 2436
    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

P
Paolo Bonzini 已提交
2437 2438 2439 2440 2441 2442
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2443 2444
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
P
Paolo Bonzini 已提交
2445 2446
        goto cleanup;
    }
2447
    priv = vm->privateData;
P
Paolo Bonzini 已提交
2448

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

D
Daniel P. Berrange 已提交
2452
    if (!virDomainObjIsActive(vm)) {
2453 2454
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
2455
        goto endjob;
P
Paolo Bonzini 已提交
2456 2457
    }

O
Osier Yang 已提交
2458 2459
    priv->jobActive = QEMU_JOB_DUMP;

P
Paolo Bonzini 已提交
2460 2461
    /* Migrate will always stop the VM, so the resume condition is
       independent of whether the stop command is issued.  */
J
Jiri Denemark 已提交
2462
    resume = virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING;
P
Paolo Bonzini 已提交
2463 2464

    /* Pause domain for non-live dump */
J
Jiri Denemark 已提交
2465 2466 2467
    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_DUMP) < 0)
2468
            goto endjob;
P
Paolo Bonzini 已提交
2469
        paused = 1;
2470 2471 2472 2473 2474 2475

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

H
Hu Tao 已提交
2478
    ret = doCoreDump(driver, vm, path, getCompressionType(driver));
2479 2480 2481 2482
    if (ret < 0)
        goto endjob;

    paused = 1;
2483 2484

endjob:
2485
    if ((ret == 0) && (flags & VIR_DUMP_CRASH)) {
J
Jiri Denemark 已提交
2486
        qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_CRASHED);
2487
        qemuAuditDomainStop(vm, "crashed");
2488 2489 2490 2491 2492
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
    }

P
Paolo Bonzini 已提交
2493 2494 2495
    /* 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.  */
2496
    else if (resume && paused && virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
2497 2498
        if (qemuProcessStartCPUs(driver, vm, dom->conn,
                                 VIR_DOMAIN_RUNNING_UNPAUSED) < 0) {
2499
            if (virGetLastError() == NULL)
2500 2501
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("resuming after dump failed"));
P
Paolo Bonzini 已提交
2502 2503
        }
    }
2504

2505 2506
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
2507
    else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
2508 2509 2510 2511
        virDomainRemoveInactive(&driver->domains,
                                vm);
        vm = NULL;
    }
2512 2513

cleanup:
P
Paolo Bonzini 已提交
2514 2515
    if (vm)
        virDomainObjUnlock(vm);
2516 2517
    if (event)
        qemuDomainEventQueue(driver, event);
2518
    qemuDriverUnlock(driver);
P
Paolo Bonzini 已提交
2519 2520 2521
    return ret;
}

2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
static char *
qemuDomainScreenshot(virDomainPtr dom,
                     virStreamPtr st,
                     unsigned int screen,
                     unsigned int flags ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    char *tmp = NULL;
    int tmp_fd = -1;
    char *ret = NULL;

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

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

    priv = vm->privateData;

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

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

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

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

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

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

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

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

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

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

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

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

H
Hu Tao 已提交
2610 2611 2612
static void processWatchdogEvent(void *data, void *opaque)
{
    int ret;
2613
    struct qemuDomainWatchdogEvent *wdEvent = data;
H
Hu Tao 已提交
2614 2615
    struct qemud_driver *driver = opaque;

W
Wen Congyang 已提交
2616 2617 2618
    qemuDriverLock(driver);
    virDomainObjLock(wdEvent->vm);

H
Hu Tao 已提交
2619 2620 2621 2622 2623
    switch (wdEvent->action) {
    case VIR_DOMAIN_WATCHDOG_ACTION_DUMP:
        {
            char *dumpfile;

E
Eric Blake 已提交
2624
            if (virAsprintf(&dumpfile, "%s/%s-%u",
H
Hu Tao 已提交
2625 2626
                            driver->autoDumpPath,
                            wdEvent->vm->def->name,
E
Eric Blake 已提交
2627 2628
                            (unsigned int)time(NULL)) < 0) {
                virReportOOMError();
W
Wen Congyang 已提交
2629
                goto unlock;
E
Eric Blake 已提交
2630
            }
H
Hu Tao 已提交
2631

W
Wen Congyang 已提交
2632 2633 2634 2635
            if (qemuDomainObjBeginJobWithDriver(driver, wdEvent->vm) < 0) {
                VIR_FREE(dumpfile);
                goto unlock;
            }
H
Hu Tao 已提交
2636 2637 2638 2639

            if (!virDomainObjIsActive(wdEvent->vm)) {
                qemuReportError(VIR_ERR_OPERATION_INVALID,
                                "%s", _("domain is not running"));
W
Wen Congyang 已提交
2640 2641
                VIR_FREE(dumpfile);
                goto endjob;
H
Hu Tao 已提交
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
            }

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

J
Jiri Denemark 已提交
2652 2653
            ret = qemuProcessStartCPUs(driver, wdEvent->vm, NULL,
                                       VIR_DOMAIN_RUNNING_UNPAUSED);
H
Hu Tao 已提交
2654 2655 2656 2657 2658 2659 2660 2661

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

            VIR_FREE(dumpfile);
        }
        break;
W
Wen Congyang 已提交
2662 2663
    default:
        goto unlock;
H
Hu Tao 已提交
2664 2665
    }

W
Wen Congyang 已提交
2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
endjob:
    /* Safe to ignore value since ref count was incremented in
     * qemuProcessHandleWatchdog().
     */
    ignore_value(qemuDomainObjEndJob(wdEvent->vm));

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

2679 2680 2681
static int qemudDomainHotplugVcpus(virDomainObjPtr vm, unsigned int nvcpus)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2682
    int i, rc = 1;
2683
    int ret = -1;
2684
    int oldvcpus = vm->def->vcpus;
E
Eric Blake 已提交
2685
    int vcpus = oldvcpus;
2686

2687 2688
    qemuDomainObjEnterMonitor(vm);

2689 2690 2691
    /* 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 已提交
2692 2693
    if (nvcpus > vcpus) {
        for (i = vcpus ; i < nvcpus ; i++) {
2694 2695 2696 2697 2698 2699 2700
            /* Online new CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 1);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
2701
            vcpus++;
2702 2703
        }
    } else {
E
Eric Blake 已提交
2704
        for (i = vcpus - 1 ; i >= nvcpus ; i--) {
2705 2706 2707 2708 2709 2710 2711
            /* Offline old CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 0);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
2712
            vcpus--;
2713 2714 2715 2716 2717 2718
        }
    }

    ret = 0;

cleanup:
2719
    qemuDomainObjExitMonitor(vm);
E
Eric Blake 已提交
2720
    vm->def->vcpus = vcpus;
2721
    qemuAuditVcpu(vm, oldvcpus, nvcpus, "update", rc == 1);
2722 2723 2724 2725 2726 2727 2728 2729 2730
    return ret;

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


2731 2732 2733 2734
static int
qemudDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
2735 2736
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2737
    virDomainDefPtr persistentDef;
2738 2739
    const char * type;
    int max;
2740
    int ret = -1;
2741

2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

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

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

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

2773 2774 2775
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

2776
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
2777 2778
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("domain is not running"));
2779
        goto endjob;
2780 2781
    }

2782 2783 2784 2785 2786 2787
    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot change persistent config of a transient domain"));
        goto endjob;
    }

2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800
    if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unknown virt type in domain definition '%d'"),
                        vm->def->virtType);
        goto endjob;
    }

    if ((max = qemudGetMaxVCPUs(NULL, type)) < 0) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("could not determine max vcpus for the domain"));
        goto endjob;
    }

C
Cole Robinson 已提交
2801
    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM) && vm->def->maxvcpus < max) {
2802 2803 2804
        max = vm->def->maxvcpus;
    }

2805 2806 2807 2808 2809 2810 2811
    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;
    }

2812 2813 2814
    if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
        goto endjob;

2815 2816
    switch (flags) {
    case VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_CONFIG:
2817 2818 2819
        persistentDef->maxvcpus = nvcpus;
        if (nvcpus < persistentDef->vcpus)
            persistentDef->vcpus = nvcpus;
2820 2821 2822 2823
        ret = 0;
        break;

    case VIR_DOMAIN_VCPU_CONFIG:
2824
        persistentDef->vcpus = nvcpus;
2825 2826 2827 2828 2829 2830 2831 2832 2833
        ret = 0;
        break;

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

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
        ret = qemudDomainHotplugVcpus(vm, nvcpus);
2834 2835 2836
        if (ret == 0) {
            persistentDef->vcpus = nvcpus;
        }
2837 2838
        break;
    }
2839

2840 2841 2842 2843
    /* Save the persistent config to disk */
    if (flags & VIR_DOMAIN_VCPU_CONFIG)
        ret = virDomainSaveConfig(driver->configDir, persistentDef);

2844 2845 2846
endjob:
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
2847

2848
cleanup:
2849 2850
    if (vm)
        virDomainObjUnlock(vm);
2851
    return ret;
2852 2853
}

2854 2855 2856 2857 2858 2859
static int
qemudDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
{
    return qemudDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_VCPU_LIVE);
}

2860 2861 2862 2863 2864 2865

static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
2866 2867
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2868
    int maxcpu, hostcpus;
2869
    virNodeInfo nodeinfo;
2870
    int ret = -1;
2871
    qemuDomainObjPrivatePtr priv;
2872

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

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

D
Daniel P. Berrange 已提交
2885
    if (!virDomainObjIsActive(vm)) {
2886 2887
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s",_("cannot pin vcpus on an inactive domain"));
2888
        goto cleanup;
2889 2890
    }

2891 2892 2893
    priv = vm->privateData;

    if (vcpu > (priv->nvcpupids-1)) {
2894 2895 2896
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("vcpu number out of range %d > %d"),
                        vcpu, priv->nvcpupids);
2897
        goto cleanup;
2898 2899
    }

2900
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
2901
        goto cleanup;
2902

2903
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
2904
    maxcpu = maplen * 8;
2905 2906
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
2907

2908 2909
    if (priv->vcpupids != NULL) {
        if (virProcessInfoSetAffinity(priv->vcpupids[vcpu],
2910
                                      cpumap, maplen, maxcpu) < 0)
2911
            goto cleanup;
2912
    } else {
2913 2914
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        "%s", _("cpu affinity is not supported"));
2915
        goto cleanup;
2916
    }
2917 2918 2919 2920 2921 2922 2923

    if (virDomainVcpupinAdd(vm->def, cpumap, maplen, vcpu) < 0) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("failed to update or add vcpupin xml"));
        goto cleanup;
    }

2924
    ret = 0;
2925

2926
cleanup:
2927 2928
    if (vm)
        virDomainObjUnlock(vm);
2929
    return ret;
2930 2931 2932 2933 2934 2935 2936 2937
}

static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
2938 2939
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2940
    virNodeInfo nodeinfo;
2941
    int i, v, maxcpu, hostcpus;
2942
    int ret = -1;
2943
    qemuDomainObjPrivatePtr priv;
2944

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

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

D
Daniel P. Berrange 已提交
2957
    if (!virDomainObjIsActive(vm)) {
2958 2959 2960
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s",
                        _("cannot list vcpu pinning for an inactive domain"));
2961
        goto cleanup;
2962 2963
    }

2964 2965
    priv = vm->privateData;

2966
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
2967
        goto cleanup;
2968

2969
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
2970
    maxcpu = maplen * 8;
2971 2972
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
2973 2974

    /* Clamp to actual number of vcpus */
2975 2976
    if (maxinfo > priv->nvcpupids)
        maxinfo = priv->nvcpupids;
2977

2978 2979 2980 2981 2982 2983
    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;
2984

2985
                if (priv->vcpupids != NULL &&
2986 2987 2988
                    qemudGetProcessInfo(&(info[i].cpuTime),
                                        &(info[i].cpu),
                                        vm->pid,
2989
                                        priv->vcpupids[i]) < 0) {
2990
                    virReportSystemError(errno, "%s",
2991 2992 2993
                                         _("cannot get vCPU placement & pCPU time"));
                    goto cleanup;
                }
2994
            }
2995 2996
        }

2997 2998
        if (cpumaps != NULL) {
            memset(cpumaps, 0, maplen * maxinfo);
2999
            if (priv->vcpupids != NULL) {
3000 3001 3002
                for (v = 0 ; v < maxinfo ; v++) {
                    unsigned char *cpumap = VIR_GET_CPUMAP(cpumaps, maplen, v);

3003
                    if (virProcessInfoGetAffinity(priv->vcpupids[v],
3004
                                                  cpumap, maplen, maxcpu) < 0)
3005
                        goto cleanup;
3006
                }
3007
            } else {
3008 3009
                qemuReportError(VIR_ERR_NO_SUPPORT,
                                "%s", _("cpu affinity is not available"));
3010
                goto cleanup;
3011 3012 3013
            }
        }
    }
3014
    ret = maxinfo;
3015

3016
cleanup:
3017 3018
    if (vm)
        virDomainObjUnlock(vm);
3019
    return ret;
3020 3021 3022
}


3023 3024 3025
static int
qemudDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
3026 3027
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3028
    virDomainDefPtr def;
3029
    int ret = -1;
3030

3031 3032 3033 3034 3035 3036 3037 3038
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

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

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

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

3054 3055 3056 3057 3058 3059 3060 3061 3062
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("domain not active"));
            goto cleanup;
        }
        def = vm->def;
    } else {
        def = vm->newDef ? vm->newDef : vm->def;
3063 3064
    }

3065
    ret = (flags & VIR_DOMAIN_VCPU_MAXIMUM) ? def->maxvcpus : def->vcpus;
3066

3067
cleanup:
3068 3069
    if (vm)
        virDomainObjUnlock(vm);
3070 3071 3072
    return ret;
}

3073 3074 3075 3076 3077 3078 3079
static int
qemudDomainGetMaxVcpus(virDomainPtr dom)
{
    return qemudDomainGetVcpusFlags(dom, (VIR_DOMAIN_VCPU_LIVE |
                                          VIR_DOMAIN_VCPU_MAXIMUM));
}

3080 3081 3082 3083 3084 3085 3086 3087 3088
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);

3089 3090
    memset(seclabel, 0, sizeof(*seclabel));

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

3099
    if (!virDomainVirtTypeToString(vm->def->virtType)) {
3100 3101 3102
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unknown virt type in domain definition '%d'"),
                        vm->def->virtType);
3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119
        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 已提交
3120
    if (virDomainObjIsActive(vm)) {
3121 3122
        if (virSecurityManagerGetProcessLabel(driver->securityManager,
                                              vm, seclabel) < 0) {
3123 3124 3125
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("Failed to get security label"));
            goto cleanup;
3126 3127 3128 3129 3130 3131 3132 3133
        }
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
3134
    qemuDriverUnlock(driver);
3135 3136 3137
    return ret;
}

3138 3139
static int qemudNodeGetSecurityModel(virConnectPtr conn,
                                     virSecurityModelPtr secmodel)
3140 3141 3142
{
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
    char *p;
3143
    int ret = 0;
3144

3145
    qemuDriverLock(driver);
3146 3147 3148 3149 3150
    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)
3151
        goto cleanup;
3152

3153 3154
    p = driver->caps->host.secModel.model;
    if (strlen(p) >= VIR_SECURITY_MODEL_BUFLEN-1) {
3155 3156 3157
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security model string exceeds max %d bytes"),
                        VIR_SECURITY_MODEL_BUFLEN-1);
3158 3159
        ret = -1;
        goto cleanup;
3160 3161 3162 3163 3164
    }
    strcpy(secmodel->model, p);

    p = driver->caps->host.secModel.doi;
    if (strlen(p) >= VIR_SECURITY_DOI_BUFLEN-1) {
3165 3166 3167
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security DOI string exceeds max %d bytes"),
                        VIR_SECURITY_DOI_BUFLEN-1);
3168 3169
        ret = -1;
        goto cleanup;
3170 3171
    }
    strcpy(secmodel->doi, p);
3172 3173 3174 3175

cleanup:
    qemuDriverUnlock(driver);
    return ret;
3176 3177
}

3178 3179 3180 3181 3182
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 已提交
3183 3184
{
    int fd;
3185
    struct qemud_save_header header;
J
Jiri Denemark 已提交
3186 3187
    char *xml = NULL;
    virDomainDefPtr def = NULL;
3188

3189 3190 3191
    if ((fd = virFileOpenAs(path, O_RDONLY, 0, getuid(), getgid(), 0)) < 0) {
        if ((fd != -EACCES && fd != -EPERM) ||
            driver->user == getuid()) {
3192 3193
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("cannot read domain image"));
J
Jiri Denemark 已提交
3194
            goto error;
3195 3196 3197
        }

        /* Opening as root failed, but qemu runs as a different user
3198 3199 3200 3201 3202 3203
         * 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 已提交
3204
            goto error;
3205
        }
3206 3207 3208
    }

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
3209 3210
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read qemu header"));
J
Jiri Denemark 已提交
3211
        goto error;
3212 3213 3214
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
3215 3216
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("image magic is incorrect"));
J
Jiri Denemark 已提交
3217
        goto error;
3218 3219 3220
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3221 3222 3223 3224 3225
        /* convert endianess and try again */
        bswap_header(&header);
    }

    if (header.version > QEMUD_SAVE_VERSION) {
3226 3227 3228
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("image version is not supported (%d > %d)"),
                        header.version, QEMUD_SAVE_VERSION);
J
Jiri Denemark 已提交
3229
        goto error;
3230 3231
    }

3232 3233 3234
    if (header.xml_len <= 0) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("invalid XML length: %d"), header.xml_len);
J
Jiri Denemark 已提交
3235
        goto error;
3236 3237
    }

3238 3239
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
        virReportOOMError();
J
Jiri Denemark 已提交
3240
        goto error;
3241 3242 3243
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
3244 3245
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read XML"));
J
Jiri Denemark 已提交
3246
        goto error;
3247 3248 3249
    }

    /* Create a domain from this XML */
3250
    if (!(def = virDomainDefParseString(driver->caps, xml,
3251
                                        VIR_DOMAIN_XML_INACTIVE)))
J
Jiri Denemark 已提交
3252
        goto error;
3253

J
Jiri Denemark 已提交
3254
    VIR_FREE(xml);
3255

J
Jiri Denemark 已提交
3256 3257
    *ret_def = def;
    *ret_header = header;
3258

J
Jiri Denemark 已提交
3259
    return fd;
3260

J
Jiri Denemark 已提交
3261 3262 3263
error:
    virDomainDefFree(def);
    VIR_FREE(xml);
3264
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
3265 3266 3267 3268

    return -1;
}

3269 3270 3271 3272 3273 3274 3275
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 已提交
3276 3277 3278 3279 3280 3281 3282 3283
{
    int ret = -1;
    virDomainEventPtr event;
    int intermediatefd = -1;
    pid_t intermediate_pid = -1;
    int childstat;

    if (header->version == 2) {
3284
        const char *intermediate_argv[3] = { NULL, "-dc", NULL };
J
Jiri Denemark 已提交
3285
        const char *prog = qemudSaveCompressionTypeToString(header->compressed);
3286
        if (prog == NULL) {
3287 3288
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("Invalid compressed save format %d"),
J
Jiri Denemark 已提交
3289 3290
                            header->compressed);
            goto out;
3291
        }
3292

J
Jiri Denemark 已提交
3293
        if (header->compressed != QEMUD_SAVE_FORMAT_RAW) {
3294
            intermediate_argv[0] = prog;
3295 3296
            intermediatefd = *fd;
            *fd = -1;
3297
            if (virExec(intermediate_argv, NULL, NULL,
3298
                        &intermediate_pid, intermediatefd, fd, NULL, 0) < 0) {
3299 3300 3301
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Failed to start decompression binary %s"),
                                intermediate_argv[0]);
3302
                *fd = intermediatefd;
J
Jiri Denemark 已提交
3303
                goto out;
3304 3305 3306
            }
        }
    }
J
Jiri Denemark 已提交
3307

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

3312
    if (intermediate_pid != -1) {
3313
        if (ret < 0) {
3314 3315 3316
            /* if there was an error setting up qemu, the intermediate
             * process will wait forever to write to stdout, so we
             * must manually kill it.
3317 3318
             */
            VIR_FORCE_CLOSE(intermediatefd);
3319
            VIR_FORCE_CLOSE(*fd);
3320 3321 3322
            kill(intermediate_pid, SIGTERM);
        }

3323 3324
        /* Wait for intermediate process to exit */
        while (waitpid(intermediate_pid, &childstat, 0) == -1 &&
J
Jiri Denemark 已提交
3325 3326 3327
               errno == EINTR) {
            /* empty */
        }
3328
    }
3329
    VIR_FORCE_CLOSE(intermediatefd);
J
Jiri Denemark 已提交
3330

3331 3332 3333
    if (VIR_CLOSE(*fd) < 0) {
        virReportSystemError(errno, _("cannot close file: %s"), path);
        ret = -1;
3334
    }
J
Jiri Denemark 已提交
3335

3336
    if (ret < 0) {
3337
        qemuAuditDomainStart(vm, "restored", false);
J
Jiri Denemark 已提交
3338
        goto out;
3339
    }
3340

3341 3342 3343
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
3344
    qemuAuditDomainStart(vm, "restored", true);
J
Jiri Denemark 已提交
3345 3346 3347
    if (event)
        qemuDomainEventQueue(driver, event);

3348

3349
    /* If it was running before, resume it now. */
J
Jiri Denemark 已提交
3350
    if (header->was_running) {
J
Jiri Denemark 已提交
3351 3352
        if (qemuProcessStartCPUs(driver, vm, conn,
                                 VIR_DOMAIN_RUNNING_RESTORED) < 0) {
3353
            if (virGetLastError() == NULL)
3354 3355
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("failed to resume domain"));
J
Jiri Denemark 已提交
3356
            goto out;
3357
        }
3358 3359
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
J
Jiri Denemark 已提交
3360
            goto out;
3361
        }
3362
    }
J
Jiri Denemark 已提交
3363

3364
    ret = 0;
3365

J
Jiri Denemark 已提交
3366
out:
3367 3368
    if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
                                                 vm, path) < 0)
3369 3370
        VIR_WARN("failed to restore save state label on %s", path);

J
Jiri Denemark 已提交
3371 3372 3373
    return ret;
}

3374 3375 3376 3377
static int
qemuDomainRestore(virConnectPtr conn,
                  const char *path)
{
J
Jiri Denemark 已提交
3378 3379 3380 3381 3382 3383 3384 3385 3386
    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);

3387
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header);
J
Jiri Denemark 已提交
3388 3389 3390 3391 3392 3393 3394 3395 3396
    if (fd < 0)
        goto cleanup;

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

    if (!(vm = virDomainAssignDef(driver->caps,
                                  &driver->domains,
                                  def, true))) {
3397
        /* virDomainAssignDef already set the error */
J
Jiri Denemark 已提交
3398 3399 3400 3401 3402 3403 3404
        goto cleanup;
    }
    def = NULL;

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

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

    if (qemuDomainObjEndJob(vm) == 0)
3408
        vm = NULL;
J
Jiri Denemark 已提交
3409 3410 3411 3412
    else if (ret < 0 && !vm->persistent) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }
3413

3414 3415
cleanup:
    virDomainDefFree(def);
3416
    VIR_FORCE_CLOSE(fd);
3417 3418 3419
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
3420
    return ret;
D
Daniel P. Berrange 已提交
3421 3422
}

3423 3424 3425 3426 3427
static int
qemuDomainObjRestore(virConnectPtr conn,
                     struct qemud_driver *driver,
                     virDomainObjPtr vm,
                     const char *path)
J
Jiri Denemark 已提交
3428 3429 3430 3431 3432 3433
{
    virDomainDefPtr def = NULL;
    int fd = -1;
    int ret = -1;
    struct qemud_save_header header;

3434
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header);
J
Jiri Denemark 已提交
3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454
    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;

3455
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path);
J
Jiri Denemark 已提交
3456 3457 3458

cleanup:
    virDomainDefFree(def);
3459
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
3460 3461 3462
    return ret;
}

D
Daniel P. Berrange 已提交
3463

3464 3465
static char *qemuDomainGetXMLDesc(virDomainPtr dom,
                                  int flags) {
3466 3467 3468
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;
3469 3470
    unsigned long balloon;
    int err;
3471

3472
    qemuDriverLock(driver);
3473
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3474

D
Daniel P. Berrange 已提交
3475
    if (!vm) {
3476 3477
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3478 3479
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
3480
        goto cleanup;
D
Daniel P. Berrange 已提交
3481 3482
    }

3483 3484 3485 3486
    /* 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))) {
3487
        qemuDomainObjPrivatePtr priv = vm->privateData;
3488 3489 3490
        /* Don't delay if someone's using the monitor, just use
         * existing most recent data instead */
        if (!priv->jobActive) {
3491
            if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
3492 3493
                goto cleanup;

3494
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
3495
            err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
3496
            qemuDomainObjExitMonitorWithDriver(driver, vm);
3497 3498 3499 3500
            if (qemuDomainObjEndJob(vm) == 0) {
                vm = NULL;
                goto cleanup;
            }
3501 3502 3503
            if (err < 0)
                goto cleanup;
            if (err > 0)
3504
                vm->def->mem.cur_balloon = balloon;
3505 3506
            /* err == 0 indicates no balloon support, so ignore it */
        }
3507
    }
3508

3509
    ret = qemuDomainFormatXML(driver, vm, flags);
3510 3511

cleanup:
3512 3513
    if (vm)
        virDomainObjUnlock(vm);
3514
    qemuDriverUnlock(driver);
3515
    return ret;
D
Daniel P. Berrange 已提交
3516 3517 3518
}


3519 3520 3521 3522
static char *qemuDomainXMLFromNative(virConnectPtr conn,
                                     const char *format,
                                     const char *config,
                                     unsigned int flags ATTRIBUTE_UNUSED) {
3523
    struct qemud_driver *driver = conn->privateData;
3524 3525 3526 3527
    virDomainDefPtr def = NULL;
    char *xml = NULL;

    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
3528 3529
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
3530 3531 3532
        goto cleanup;
    }

3533
    qemuDriverLock(driver);
3534
    def = qemuParseCommandLineString(driver->caps, config);
3535
    qemuDriverUnlock(driver);
3536 3537 3538
    if (!def)
        goto cleanup;

3539
    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
3540 3541 3542 3543 3544 3545

cleanup:
    virDomainDefFree(def);
    return xml;
}

3546 3547 3548 3549 3550 3551
static char *qemuDomainXMLToNative(virConnectPtr conn,
                                   const char *format,
                                   const char *xmlData,
                                   unsigned int flags ATTRIBUTE_UNUSED) {
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
3552
    virDomainChrSourceDef monConfig;
3553
    virBitmapPtr qemuCaps = NULL;
E
Eric Blake 已提交
3554
    virCommandPtr cmd = NULL;
3555 3556 3557
    char *ret = NULL;
    int i;

3558 3559
    qemuDriverLock(driver);

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

3566
    def = virDomainDefParseString(driver->caps, xmlData, 0);
3567 3568 3569
    if (!def)
        goto cleanup;

3570 3571
    /* Since we're just exporting args, we can't do bridge/network/direct
     * setups, since libvirt will normally create TAP/macvtap devices
3572 3573 3574 3575 3576
     * 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];
3577
        int bootIndex = net->bootIndex;
3578 3579
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK ||
            net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599
            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;
        }
3600
        net->bootIndex = bootIndex;
3601 3602 3603 3604
    }
    for (i = 0 ; i < def->ngraphics ; i++) {
        if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
            def->graphics[i]->data.vnc.autoport)
3605
            def->graphics[i]->data.vnc.port = QEMU_VNC_PORT_MIN;
3606 3607
    }

3608
    if (qemuCapsExtractVersionInfo(def->emulator, def->os.arch,
3609
                                   NULL,
3610
                                   &qemuCaps) < 0)
3611 3612
        goto cleanup;

3613
    if (qemuProcessPrepareMonitorChr(driver, &monConfig, def->name) < 0)
3614
        goto cleanup;
3615

3616
    if (!(cmd = qemuBuildCommandLine(conn, driver, def,
3617
                                     &monConfig, false, qemuCaps,
3618
                                     NULL, -1, NULL, VIR_VM_OP_NO_OP)))
3619 3620
        goto cleanup;

E
Eric Blake 已提交
3621
    ret = virCommandToString(cmd);
3622 3623

cleanup:
3624
    qemuDriverUnlock(driver);
3625

3626
    qemuCapsFree(qemuCaps);
E
Eric Blake 已提交
3627
    virCommandFree(cmd);
3628 3629 3630 3631 3632
    virDomainDefFree(def);
    return ret;
}


3633
static int qemudListDefinedDomains(virConnectPtr conn,
3634
                            char **const names, int nnames) {
3635
    struct qemud_driver *driver = conn->privateData;
3636
    int n;
3637

3638
    qemuDriverLock(driver);
3639
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
3640
    qemuDriverUnlock(driver);
3641
    return n;
D
Daniel P. Berrange 已提交
3642 3643
}

3644
static int qemudNumDefinedDomains(virConnectPtr conn) {
3645
    struct qemud_driver *driver = conn->privateData;
3646
    int n;
3647

3648
    qemuDriverLock(driver);
3649
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
3650
    qemuDriverUnlock(driver);
3651

3652
    return n;
D
Daniel P. Berrange 已提交
3653 3654 3655
}


J
Jiri Denemark 已提交
3656 3657
static int qemudDomainObjStart(virConnectPtr conn,
                               struct qemud_driver *driver,
3658 3659
                               virDomainObjPtr vm,
                               bool start_paused)
J
Jiri Denemark 已提交
3660 3661 3662 3663 3664 3665
{
    int ret = -1;
    char *managed_save;

    /*
     * If there is a managed saved state restore it instead of starting
3666
     * from scratch. The old state is removed once the restoring succeeded.
J
Jiri Denemark 已提交
3667 3668
     */
    managed_save = qemuDomainManagedSavePath(driver, vm);
3669 3670 3671 3672

    if (!managed_save)
        goto cleanup;

E
Eric Blake 已提交
3673
    if (virFileExists(managed_save)) {
3674
        ret = qemuDomainObjRestore(conn, driver, vm, managed_save);
J
Jiri Denemark 已提交
3675

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

3679
        goto cleanup;
J
Jiri Denemark 已提交
3680 3681
    }

3682 3683
    ret = qemuProcessStart(conn, driver, vm, NULL, start_paused, -1, NULL,
                           VIR_VM_OP_CREATE);
3684
    qemuAuditDomainStart(vm, "booted", ret >= 0);
3685
    if (ret >= 0) {
J
Jiri Denemark 已提交
3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698
        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;
}

3699 3700 3701
static int
qemudDomainStartWithFlags(virDomainPtr dom, unsigned int flags)
{
3702 3703 3704
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
3705

3706
    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);
3707

3708
    qemuDriverLock(driver);
3709
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3710

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

3719 3720 3721 3722
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

    if (virDomainObjIsActive(vm)) {
3723 3724
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is already running"));
3725 3726 3727
        goto endjob;
    }

3728 3729
    ret = qemudDomainObjStart(dom->conn, driver, vm,
                              (flags & VIR_DOMAIN_START_PAUSED) != 0);
3730

3731
endjob:
3732 3733
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
3734

3735
cleanup:
3736 3737
    if (vm)
        virDomainObjUnlock(vm);
3738
    qemuDriverUnlock(driver);
3739
    return ret;
D
Daniel P. Berrange 已提交
3740 3741
}

3742 3743 3744 3745 3746 3747
static int
qemudDomainStart(virDomainPtr dom)
{
    return qemudDomainStartWithFlags(dom, 0);
}

3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762
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;

3763
        if (STRNEQ(def->os.machine, machine->name))
3764 3765 3766
            continue;

        if (!(*canonical = strdup(machine->canonical))) {
3767
            virReportOOMError();
3768 3769 3770 3771 3772 3773 3774 3775 3776
            return -1;
        }

        break;
    }

    return 0;
}

3777 3778 3779 3780 3781 3782
static int
qemudCanonicalizeMachineDirect(virDomainDefPtr def, char **canonical)
{
    virCapsGuestMachinePtr *machines = NULL;
    int i, nmachines = 0;

3783
    if (qemuCapsProbeMachineTypes(def->emulator, &machines, &nmachines) < 0)
3784 3785 3786 3787 3788 3789
        return -1;

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

3790
        if (STRNEQ(def->os.machine, machines[i]->name))
3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802
            continue;

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

    virCapabilitiesFreeMachines(machines, nmachines);

    return 0;
}

3803 3804
int
qemudCanonicalizeMachine(struct qemud_driver *driver, virDomainDefPtr def)
3805 3806 3807 3808 3809 3810
{
    char *canonical = NULL;
    int i;

    for (i = 0; i < driver->caps->nguests; i++) {
        virCapsGuestPtr guest = driver->caps->guests[i];
3811
        virCapsGuestDomainInfoPtr info;
3812 3813 3814
        int j;

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

3817 3818 3819 3820 3821 3822 3823 3824 3825
            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;
3826 3827
        }

3828 3829 3830 3831
        info = &guest->arch.defaultInfo;

        if (info->emulator && STREQ(info->emulator, def->emulator)) {
            if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
3832 3833 3834 3835
                return -1;
            goto out;
        }
    }
3836 3837 3838 3839

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

3840 3841 3842 3843 3844 3845 3846
out:
    if (canonical) {
        VIR_FREE(def->os.machine);
        def->os.machine = canonical;
    }
    return 0;
}
D
Daniel P. Berrange 已提交
3847

3848
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
3849
    struct qemud_driver *driver = conn->privateData;
3850
    virDomainDefPtr def;
3851
    virDomainObjPtr vm = NULL;
3852
    virDomainPtr dom = NULL;
3853
    virDomainEventPtr event = NULL;
3854
    int dupVM;
3855

3856
    qemuDriverLock(driver);
3857
    if (!(def = virDomainDefParseString(driver->caps, xml,
3858
                                        VIR_DOMAIN_XML_INACTIVE)))
3859
        goto cleanup;
3860

3861
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
3862 3863
        goto cleanup;

3864 3865
    if ((dupVM = virDomainObjIsDuplicate(&driver->domains, def, 0)) < 0)
        goto cleanup;
3866

3867
    if (qemudCanonicalizeMachine(driver, def) < 0)
3868 3869
        goto cleanup;

3870
    if (qemuDomainAssignPCIAddresses(def) < 0)
3871 3872
        goto cleanup;

3873
    if (!(vm = virDomainAssignDef(driver->caps,
3874
                                  &driver->domains,
3875
                                  def, false))) {
3876
        goto cleanup;
3877
    }
3878
    def = NULL;
3879
    vm->persistent = 1;
3880

3881
    if (virDomainSaveConfig(driver->configDir,
3882
                            vm->newDef ? vm->newDef : vm->def) < 0) {
3883
        VIR_INFO("Defining domain '%s'", vm->def->name);
3884 3885
        virDomainRemoveInactive(&driver->domains,
                                vm);
3886
        vm = NULL;
3887
        goto cleanup;
3888 3889
    }

3890 3891
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
3892
                                     !dupVM ?
3893 3894
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
3895

3896
    VIR_INFO("Creating domain '%s'", vm->def->name);
3897
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
3898
    if (dom) dom->id = vm->def->id;
3899 3900

cleanup:
3901
    virDomainDefFree(def);
3902 3903
    if (vm)
        virDomainObjUnlock(vm);
3904 3905
    if (event)
        qemuDomainEventQueue(driver, event);
3906
    qemuDriverUnlock(driver);
3907
    return dom;
D
Daniel P. Berrange 已提交
3908 3909
}

3910
static int qemudDomainUndefine(virDomainPtr dom) {
3911 3912
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3913
    virDomainEventPtr event = NULL;
3914
    int ret = -1;
D
Daniel P. Berrange 已提交
3915

3916
    qemuDriverLock(driver);
3917
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3918

D
Daniel P. Berrange 已提交
3919
    if (!vm) {
3920 3921
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3922 3923
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
3924
        goto cleanup;
D
Daniel P. Berrange 已提交
3925 3926
    }

D
Daniel P. Berrange 已提交
3927
    if (virDomainObjIsActive(vm)) {
3928 3929
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot delete active domain"));
3930
        goto cleanup;
D
Daniel P. Berrange 已提交
3931 3932
    }

3933
    if (!vm->persistent) {
3934
        qemuReportError(VIR_ERR_OPERATION_INVALID,
3935
                        "%s", _("cannot undefine transient domain"));
3936
        goto cleanup;
3937 3938
    }

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

3942 3943 3944
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
3945

3946
    VIR_INFO("Undefining domain '%s'", vm->def->name);
3947 3948
    virDomainRemoveInactive(&driver->domains,
                            vm);
3949
    vm = NULL;
3950
    ret = 0;
D
Daniel P. Berrange 已提交
3951

3952
cleanup:
3953 3954
    if (vm)
        virDomainObjUnlock(vm);
3955 3956
    if (event)
        qemuDomainEventQueue(driver, event);
3957
    qemuDriverUnlock(driver);
3958
    return ret;
D
Daniel P. Berrange 已提交
3959 3960
}

3961 3962 3963
static int
qemuDomainAttachDeviceDiskLive(struct qemud_driver *driver,
                               virDomainObjPtr vm,
3964
                               virDomainDeviceDefPtr dev)
3965 3966 3967 3968
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
    int ret = -1;
3969

3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989
    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:
3990
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, false);
3991 3992 3993 3994
        break;
    case VIR_DOMAIN_DISK_DEVICE_DISK:
        if (disk->bus == VIR_DOMAIN_DISK_BUS_USB)
            ret = qemuDomainAttachUsbMassstorageDevice(driver, vm,
3995
                                                       disk);
3996
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
3997
            ret = qemuDomainAttachPciDiskDevice(driver, vm, disk);
3998
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
3999
            ret = qemuDomainAttachSCSIDisk(driver, vm, disk);
4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025
        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,
4026
                                     virDomainDeviceDefPtr dev)
4027 4028 4029 4030 4031 4032
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
4033
        ret = qemuDomainAttachPciControllerDevice(driver, vm, cont);
4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046
        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,
4047
                           virDomainPtr dom)
4048 4049 4050 4051 4052 4053
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
4054
        qemuDomainObjCheckDiskTaint(driver, vm, dev->data.disk, -1);
4055
        ret = qemuDomainAttachDeviceDiskLive(driver, vm, dev);
4056 4057 4058 4059 4060
        if (!ret)
            dev->data.disk = NULL;
        break;

    case VIR_DOMAIN_DEVICE_CONTROLLER:
4061
        ret = qemuDomainAttachDeviceControllerLive(driver, vm, dev);
4062 4063 4064 4065 4066
        if (!ret)
            dev->data.controller = NULL;
        break;

    case VIR_DOMAIN_DEVICE_NET:
4067
        qemuDomainObjCheckNetTaint(driver, vm, dev->data.net, -1);
4068
        ret = qemuDomainAttachNetDevice(dom->conn, driver, vm,
4069
                                        dev->data.net);
4070 4071 4072 4073 4074 4075
        if (!ret)
            dev->data.net = NULL;
        break;

    case VIR_DOMAIN_DEVICE_HOSTDEV:
        ret = qemuDomainAttachHostDevice(driver, vm,
4076
                                         dev->data.hostdev);
4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093
        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,
4094
                               virDomainDeviceDefPtr dev)
4095 4096 4097 4098 4099 4100 4101
{
    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)
4102
            ret = qemuDomainDetachPciDiskDevice(driver, vm, dev);
4103
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI)
4104
            ret =  qemuDomainDetachDiskDevice(driver, vm, dev);
4105
        else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB)
4106
            ret = qemuDomainDetachDiskDevice(driver, vm, dev);
4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122
        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,
4123
                                     virDomainDeviceDefPtr dev)
4124 4125 4126 4127 4128 4129
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
4130
        ret = qemuDomainDetachPciControllerDevice(driver, vm, dev);
4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142
        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,
4143
                           virDomainPtr dom)
4144 4145 4146 4147 4148 4149
{
    struct qemud_driver *driver = dom->conn->privateData;
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
4150
        ret = qemuDomainDetachDeviceDiskLive(driver, vm, dev);
4151 4152
        break;
    case VIR_DOMAIN_DEVICE_CONTROLLER:
4153
        ret = qemuDomainDetachDeviceControllerLive(driver, vm, dev);
4154 4155
        break;
    case VIR_DOMAIN_DEVICE_NET:
4156
        ret = qemuDomainDetachNetDevice(driver, vm, dev);
4157 4158
        break;
    case VIR_DOMAIN_DEVICE_HOSTDEV:
4159
        ret = qemuDomainDetachHostDevice(driver, vm, dev);
4160 4161 4162 4163 4164 4165 4166 4167 4168 4169
        break;
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                        "%s", _("This type of device cannot be hot unplugged"));
        break;
    }

    return ret;
}

4170 4171 4172 4173 4174 4175 4176 4177
static int
qemuDomainChangeDiskMediaLive(virDomainObjPtr vm,
                              virDomainDeviceDefPtr dev,
                              struct qemud_driver *driver,
                              bool force)
{
    virDomainDiskDefPtr disk = dev->data.disk;
    virCgroupPtr cgroup = NULL;
4178
    int ret = -1;
4179 4180 4181

    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup,
4182
                               vm->def->name, &cgroup, 0) != 0) {
4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194
            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:
4195
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, force);
4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227
        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:
4228
        ret = qemuDomainChangeDiskMediaLive(vm, dev, driver, force);
4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242
        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;
}

4243
static int
4244
qemuDomainAttachDeviceConfig(virDomainDefPtr vmdef,
4245 4246
                             virDomainDeviceDefPtr dev)
{
4247 4248
    virDomainDiskDefPtr disk;

4249
    switch (dev->type) {
4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269
    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;

4270 4271 4272 4273 4274 4275 4276 4277 4278 4279
    default:
         qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                         _("persistent attach of device is not supported"));
         return -1;
    }
    return 0;
}


static int
4280
qemuDomainDetachDeviceConfig(virDomainDefPtr vmdef,
4281 4282
                             virDomainDeviceDefPtr dev)
{
4283 4284
    virDomainDiskDefPtr disk;

4285
    switch (dev->type) {
4286 4287 4288 4289 4290 4291 4292 4293
    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;
4294 4295 4296 4297 4298 4299 4300 4301 4302
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("persistent detach of device is not supported"));
        return -1;
    }
    return 0;
}

static int
4303
qemuDomainUpdateDeviceConfig(virDomainDefPtr vmdef,
4304 4305
                             virDomainDeviceDefPtr dev)
{
4306 4307 4308
    virDomainDiskDefPtr orig, disk;
    int pos;

4309
    switch (dev->type) {
4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344
    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;
4345 4346 4347 4348 4349 4350 4351 4352
    default:
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                         _("persistent update of device is not supported"));
        return -1;
    }
    return 0;
}

4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363
/* 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)
4364
{
4365
    struct qemud_driver *driver = dom->conn->privateData;
4366
    virDomainObjPtr vm = NULL;
4367
    virDomainDefPtr vmdef = NULL;
4368
    virDomainDeviceDefPtr dev = NULL;
4369
    bool force = (flags & VIR_DOMAIN_DEVICE_MODIFY_FORCE) != 0;
4370
    int ret = -1;
4371

4372
    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
4373 4374 4375 4376
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG |
                  (action == QEMU_DEVICE_UPDATE ?
                   VIR_DOMAIN_DEVICE_MODIFY_FORCE : 0), -1);

4377 4378 4379 4380 4381 4382 4383
    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);
4384 4385 4386
        goto cleanup;
    }

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

4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403
    if (virDomainObjIsActive(vm)) {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_LIVE;
    } else {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_CONFIG;
        /* check consistency between flags and the vm state */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s",
                            _("cannot do live update a device on "
                              "inactive domain"));
            goto endjob;
        }
4404
    }
4405

4406 4407 4408 4409 4410
    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
         qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("cannot modify device on transient domain"));
         goto endjob;
    }
4411 4412 4413 4414
    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL)
        goto endjob;
4415

4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        /* 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;
4438

4439 4440 4441
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE)) {
        switch (action) {
        case QEMU_DEVICE_ATTACH:
4442
            ret = qemuDomainAttachDeviceLive(vm, dev, dom);
4443 4444
            break;
        case QEMU_DEVICE_DETACH:
4445
            ret = qemuDomainDetachDeviceLive(vm, dev, dom);
4446 4447
            break;
        case QEMU_DEVICE_UPDATE:
4448
            ret = qemuDomainUpdateDeviceLive(vm, dev, dom, force);
4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470
            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. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
        ret = virDomainSaveConfig(driver->configDir, vmdef);
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false);
            vmdef = NULL;
        }
    }
4471 4472 4473 4474 4475 4476

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

cleanup:
4477
    virDomainDefFree(vmdef);
4478 4479 4480 4481
    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
4482 4483 4484
    return ret;
}

4485 4486 4487 4488 4489 4490
static int qemuDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_ATTACH);
}

4491 4492 4493 4494
static int qemuDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainAttachDeviceFlags(dom, xml,
                                       VIR_DOMAIN_DEVICE_MODIFY_LIVE);
4495
}
4496

4497

4498 4499 4500 4501
static int qemuDomainUpdateDeviceFlags(virDomainPtr dom,
                                       const char *xml,
                                       unsigned int flags)
{
4502
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_UPDATE);
4503 4504
}

4505 4506 4507
static int qemuDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
4508
    return qemuDomainModifyDeviceFlags(dom, xml, flags, QEMU_DEVICE_DETACH);
4509 4510
}

4511 4512 4513 4514
static int qemuDomainDetachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainDetachDeviceFlags(dom, xml,
                                       VIR_DOMAIN_DEVICE_MODIFY_LIVE);
4515 4516
}

4517
static int qemudDomainGetAutostart(virDomainPtr dom,
4518
                                   int *autostart) {
4519 4520 4521
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
4522

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

4527
    if (!vm) {
4528 4529
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4530 4531
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4532
        goto cleanup;
4533 4534 4535
    }

    *autostart = vm->autostart;
4536
    ret = 0;
4537

4538
cleanup:
4539 4540
    if (vm)
        virDomainObjUnlock(vm);
4541
    return ret;
4542 4543
}

4544
static int qemudDomainSetAutostart(virDomainPtr dom,
4545
                                   int autostart) {
4546 4547
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4548 4549
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
4550

4551
    qemuDriverLock(driver);
4552
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4553

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

4562
    if (!vm->persistent) {
4563
        qemuReportError(VIR_ERR_OPERATION_INVALID,
4564
                        "%s", _("cannot set autostart for transient domain"));
4565
        goto cleanup;
4566 4567
    }

4568 4569
    autostart = (autostart != 0);

4570
    if (vm->autostart != autostart) {
4571
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
4572
            goto cleanup;
4573
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
4574
            goto cleanup;
4575

4576 4577
        if (autostart) {
            int err;
4578

4579
            if ((err = virFileMakePath(driver->autostartDir))) {
4580
                virReportSystemError(err,
4581 4582
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
4583 4584
                goto cleanup;
            }
4585

4586
            if (symlink(configFile, autostartLink) < 0) {
4587
                virReportSystemError(errno,
4588 4589
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
4590 4591 4592 4593
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
4594
                virReportSystemError(errno,
4595 4596
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
4597 4598
                goto cleanup;
            }
4599 4600
        }

4601
        vm->autostart = autostart;
4602
    }
4603
    ret = 0;
4604

4605 4606 4607
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
4608 4609
    if (vm)
        virDomainObjUnlock(vm);
4610
    qemuDriverUnlock(driver);
4611
    return ret;
4612 4613
}

4614 4615 4616 4617 4618

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

4621
    qemuDriverLock(driver);
4622
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
4623 4624
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup CPU controller is not mounted"));
4625
        goto cleanup;
4626 4627 4628 4629 4630 4631 4632
    }

    if (nparams)
        *nparams = 1;

    ret = strdup("posix");
    if (!ret)
4633
        virReportOOMError();
4634 4635 4636

cleanup:
    qemuDriverUnlock(driver);
4637 4638 4639
    return ret;
}

4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665
static int qemuDomainSetBlkioParameters(virDomainPtr dom,
                                         virBlkioParameterPtr params,
                                         int nparams,
                                         unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;

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

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

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

4666 4667 4668 4669 4670 4671
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747
    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find cgroup for domain %s"), vm->def->name);
        goto cleanup;
    }

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

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

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

            rc = virCgroupSetBlkioWeight(group, params[i].value.ui);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to set blkio weight tunable"));
                ret = -1;
            }
        } else {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Parameter `%s' not supported"), param->field);
            ret = -1;
        }
    }

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

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

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

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

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

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

4748 4749 4750 4751 4752 4753
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778
    if ((*nparams) == 0) {
        /* Current number of blkio parameters supported by cgroups */
        *nparams = QEMU_NB_BLKIO_PARAM;
        ret = 0;
        goto cleanup;
    }

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

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

    for (i = 0; i < *nparams; i++) {
        virBlkioParameterPtr param = &params[i];
        val = 0;
        param->value.ui = 0;
        param->type = VIR_DOMAIN_BLKIO_PARAM_UINT;

4779
        switch (i) {
4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810
        case 0: /* fill blkio weight here */
            rc = virCgroupGetBlkioWeight(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get blkio weight"));
                goto cleanup;
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_BLKIO_WEIGHT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field blkio weight too long for destination"));
                goto cleanup;
            }
            param->value.ui = val;
            break;

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

    ret = 0;

cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824

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

    qemuDriverLock(driver);
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
4825 4826
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup memory controller is not mounted"));
4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837
        goto cleanup;
    }

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

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

4838 4839 4840 4841 4842 4843
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883
    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find cgroup for domain %s"), vm->def->name);
        goto cleanup;
    }

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

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

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

            rc = virCgroupSetMemorySoftLimit(group, params[i].value.ul);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to set memory soft_limit tunable"));
                ret = -1;
            }
4884
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT)) {
4885 4886 4887 4888 4889 4890 4891 4892
            int rc;
            if (param->type != VIR_DOMAIN_MEMORY_PARAM_ULLONG) {
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for swap_hard_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

4893
            rc = virCgroupSetMemSwapHardLimit(group, params[i].value.ul);
4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to set swap_hard_limit tunable"));
                ret = -1;
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Memory tunable `%s' not implemented"), param->field);
            ret = -1;
        } else {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Parameter `%s' not supported"), param->field);
            ret = -1;
        }
    }

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

4918 4919 4920 4921 4922 4923 4924 4925 4926
static int qemuDomainGetMemoryParameters(virDomainPtr dom,
                                         virMemoryParameterPtr params,
                                         int *nparams,
                                         unsigned int flags ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
4927
    unsigned long long val;
4928 4929 4930 4931 4932 4933
    int ret = -1;
    int rc;

    qemuDriverLock(driver);

    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
4934 4935
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup memory controller is not mounted"));
4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946
        goto cleanup;
    }

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

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

4947 4948 4949 4950 4951 4952
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

4953 4954 4955 4956 4957 4958 4959
    if ((*nparams) == 0) {
        /* Current number of memory parameters supported by cgroups */
        *nparams = QEMU_NB_MEM_PARAM;
        ret = 0;
        goto cleanup;
    }

4960
    if ((*nparams) < QEMU_NB_MEM_PARAM) {
4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
        goto cleanup;
    }

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

4972
    for (i = 0; i < QEMU_NB_MEM_PARAM; i++) {
4973 4974 4975 4976 4977
        virMemoryParameterPtr param = &params[i];
        val = 0;
        param->value.ul = 0;
        param->type = VIR_DOMAIN_MEMORY_PARAM_ULLONG;

4978
        switch (i) {
4979 4980 4981 4982 4983
        case 0: /* fill memory hard limit here */
            rc = virCgroupGetMemoryHardLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory hard limit"));
4984
                goto cleanup;
4985 4986 4987 4988
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field memory hard limit too long for destination"));
4989
                goto cleanup;
4990 4991 4992 4993 4994 4995 4996 4997 4998
            }
            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"));
4999
                goto cleanup;
5000 5001 5002 5003
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field memory soft limit too long for destination"));
5004
                goto cleanup;
5005 5006 5007 5008 5009
            }
            param->value.ul = val;
            break;

        case 2: /* fill swap hard limit here */
5010
            rc = virCgroupGetMemSwapHardLimit(group, &val);
5011 5012 5013
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get swap hard limit"));
5014
                goto cleanup;
5015
            }
5016
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT) == NULL) {
5017 5018
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field swap hard limit too long for destination"));
5019
                goto cleanup;
5020 5021 5022 5023 5024 5025 5026 5027 5028 5029
            }
            param->value.ul = val;
            break;

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

5030
    *nparams = QEMU_NB_MEM_PARAM;
5031 5032
    ret = 0;

5033 5034 5035 5036 5037 5038 5039 5040 5041
cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

5042 5043 5044 5045
static int qemuSetSchedulerParametersFlags(virDomainPtr dom,
                                           virSchedParameterPtr params,
                                           int nparams,
                                           unsigned int flags)
5046 5047 5048 5049 5050
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
5051
    virDomainDefPtr persistentDef = NULL;
5052
    int ret = -1;
5053 5054 5055 5056
    bool isActive;

    virCheckFlags(VIR_DOMAIN_SCHEDPARAM_LIVE |
                  VIR_DOMAIN_SCHEDPARAM_CONFIG, -1);
5057

5058
    qemuDriverLock(driver);
5059 5060 5061 5062

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

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

5068 5069 5070 5071 5072 5073 5074
    isActive = virDomainObjIsActive(vm);

    if (flags == VIR_DOMAIN_SCHEDPARAM_CURRENT) {
        if (isActive)
            flags = VIR_DOMAIN_SCHEDPARAM_LIVE;
        else
            flags = VIR_DOMAIN_SCHEDPARAM_CONFIG;
5075 5076
    }

5077 5078 5079
    if ((flags & VIR_DOMAIN_MEM_CONFIG) && !vm->persistent) {
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot change persistent config of a transient domain"));
5080 5081 5082
        goto cleanup;
    }

5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102
    if (flags & VIR_DOMAIN_SCHEDPARAM_LIVE) {
        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;
        }
    }

5103 5104 5105 5106 5107 5108
    for (i = 0; i < nparams; i++) {
        virSchedParameterPtr param = &params[i];

        if (STREQ(param->field, "cpu_shares")) {
            int rc;
            if (param->type != VIR_DOMAIN_SCHED_FIELD_ULLONG) {
5109 5110
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for cpu_shares tunable, expected a 'ullong'"));
5111 5112 5113
                goto cleanup;
            }

5114 5115 5116 5117 5118 5119 5120 5121 5122
            if (flags & VIR_DOMAIN_SCHEDPARAM_LIVE) {
                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;
5123
            }
5124

5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139
            if (flags & VIR_DOMAIN_SCHEDPARAM_CONFIG) {
                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;
                }
            }
5140
        } else {
5141 5142
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Invalid parameter `%s'"), param->field);
5143 5144 5145
            goto cleanup;
        }
    }
5146

5147 5148 5149 5150 5151 5152
    ret = 0;

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

5157 5158 5159 5160 5161 5162 5163 5164 5165 5166
static int qemuSetSchedulerParameters(virDomainPtr dom,
                                      virSchedParameterPtr params,
                                      int nparams)
{
    return qemuSetSchedulerParametersFlags(dom,
                                           params,
                                           nparams,
                                           VIR_DOMAIN_SCHEDPARAM_LIVE);
}

5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177
static int qemuGetSchedulerParameters(virDomainPtr dom,
                                      virSchedParameterPtr params,
                                      int *nparams)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    unsigned long long val;
    int ret = -1;
    int rc;

5178
    qemuDriverLock(driver);
5179
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
5180 5181
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cgroup CPU controller is not mounted"));
5182
        goto cleanup;
5183 5184
    }

5185
    if (*nparams < 1) {
5186 5187
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
5188
        goto cleanup;
5189 5190 5191 5192 5193
    }

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

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

5199
    if (!virDomainObjIsActive(vm)) {
5200 5201
        val = vm->def->cputune.shares;
        goto out;
5202 5203
    }

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

    rc = virCgroupGetCpuShares(group, &val);
    if (rc != 0) {
5212
        virReportSystemError(-rc, "%s",
5213 5214 5215
                             _("unable to get cpu shares tunable"));
        goto cleanup;
    }
5216
out:
5217 5218
    params[0].value.ul = val;
    params[0].type = VIR_DOMAIN_SCHED_FIELD_ULLONG;
C
Chris Lalancette 已提交
5219
    if (virStrcpyStatic(params[0].field, "cpu_shares") == NULL) {
5220 5221
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Field cpu_shares too long for destination"));
C
Chris Lalancette 已提交
5222 5223
        goto cleanup;
    }
5224

5225
    *nparams = 1;
5226 5227 5228 5229 5230 5231
    ret = 0;

cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
5232
    qemuDriverUnlock(driver);
5233 5234 5235 5236
    return ret;
}


5237 5238 5239 5240 5241 5242 5243 5244 5245
/* 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)
{
5246
    struct qemud_driver *driver = dom->conn->privateData;
5247
    int i, ret = -1;
5248
    virDomainObjPtr vm;
5249
    virDomainDiskDefPtr disk = NULL;
5250
    qemuDomainObjPrivatePtr priv;
5251

5252
    qemuDriverLock(driver);
5253
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5254
    qemuDriverUnlock(driver);
5255
    if (!vm) {
5256 5257
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5258 5259
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5260
        goto cleanup;
5261
    }
5262 5263 5264 5265

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

5266
    if (!virDomainObjIsActive(vm)) {
5267 5268
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
5269
        goto endjob;
5270 5271
    }

5272 5273 5274 5275 5276 5277 5278 5279
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

    if (!disk) {
5280 5281
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path: %s"), path);
5282
        goto endjob;
5283 5284
    }

5285
    if (!disk->info.alias) {
5286 5287
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("missing disk device alias name for %s"), disk->dst);
5288
        goto endjob;
5289
    }
5290

5291
    priv = vm->privateData;
5292 5293
    qemuDomainObjEnterMonitor(vm);
    ret = qemuMonitorGetBlockStatsInfo(priv->mon,
5294
                                       disk->info.alias,
5295 5296 5297 5298 5299 5300
                                       &stats->rd_req,
                                       &stats->rd_bytes,
                                       &stats->wr_req,
                                       &stats->wr_bytes,
                                       &stats->errs);
    qemuDomainObjExitMonitor(vm);
5301

5302
endjob:
5303 5304
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
5305

5306
cleanup:
5307 5308
    if (vm)
        virDomainObjUnlock(vm);
5309
    return ret;
5310 5311
}

5312
#ifdef __linux__
5313 5314 5315 5316 5317
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
5318 5319
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
5320
    int i;
5321
    int ret = -1;
5322

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

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

D
Daniel P. Berrange 已提交
5335
    if (!virDomainObjIsActive(vm)) {
5336 5337
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
5338
        goto cleanup;
5339 5340 5341
    }

    /* Check the path is one of the domain's network interfaces. */
5342 5343
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
5344 5345 5346 5347
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
5348 5349
    }

5350
    if (ret == 0)
5351
        ret = linuxDomainInterfaceStats(path, stats);
5352
    else
5353 5354
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path, '%s' is not a known interface"), path);
5355

5356
cleanup:
5357 5358
    if (vm)
        virDomainObjUnlock(vm);
5359 5360
    return ret;
}
5361
#else
5362 5363 5364 5365
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
5366
{
5367 5368
    qemuReportError(VIR_ERR_NO_SUPPORT,
                    "%s", __FUNCTION__);
5369 5370
    return -1;
}
5371
#endif
5372

5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388
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);
5389 5390
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5391 5392 5393
        goto cleanup;
    }

5394 5395 5396
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

5397 5398 5399
    if (virDomainObjIsActive(vm)) {
        qemuDomainObjPrivatePtr priv = vm->privateData;
        qemuDomainObjEnterMonitor(vm);
5400
        ret = qemuMonitorGetMemoryStats(priv->mon, stats, nr_stats);
5401 5402
        qemuDomainObjExitMonitor(vm);
    } else {
5403 5404
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
5405 5406
    }

5407 5408 5409
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;

5410 5411 5412 5413 5414 5415
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

5416 5417 5418 5419 5420 5421 5422
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
                      unsigned int flags ATTRIBUTE_UNUSED)
{
5423 5424 5425
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
5426

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

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

    if (!path || path[0] == '\0') {
5440 5441
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("NULL or empty path"));
5442
        goto cleanup;
5443 5444 5445
    }

    /* Check the path belongs to this domain. */
5446 5447
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
5448 5449 5450 5451
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
5452 5453
    }

5454 5455 5456 5457 5458
    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) {
5459 5460
            virReportSystemError(errno,
                                 _("%s: failed to open"), path);
5461 5462
            goto cleanup;
        }
5463

5464 5465 5466 5467 5468 5469
        /* 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) {
5470 5471
            virReportSystemError(errno,
                                 _("%s: failed to seek or read"), path);
5472 5473 5474 5475 5476
            goto cleanup;
        }

        ret = 0;
    } else {
5477 5478
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("invalid path"));
5479 5480
    }

5481
cleanup:
5482
    VIR_FORCE_CLOSE(fd);
5483 5484
    if (vm)
        virDomainObjUnlock(vm);
5485 5486 5487
    return ret;
}

R
Richard W.M. Jones 已提交
5488 5489 5490 5491 5492 5493
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
5494 5495
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
5496
    char *tmp = NULL;
R
Richard W.M. Jones 已提交
5497
    int fd = -1, ret = -1;
5498
    qemuDomainObjPrivatePtr priv;
R
Richard W.M. Jones 已提交
5499

5500
    qemuDriverLock(driver);
5501
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5502
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
5503 5504

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

5512
    if (flags != VIR_MEMORY_VIRTUAL && flags != VIR_MEMORY_PHYSICAL) {
5513 5514
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("flags parameter must be VIR_MEMORY_VIRTUAL or VIR_MEMORY_PHYSICAL"));
5515
        goto cleanup;
R
Richard W.M. Jones 已提交
5516 5517
    }

5518 5519 5520
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
5521
    if (!virDomainObjIsActive(vm)) {
5522 5523
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
5524
        goto endjob;
R
Richard W.M. Jones 已提交
5525 5526
    }

5527
    if (virAsprintf(&tmp, "%s/qemu.mem.XXXXXX", driver->cacheDir) < 0) {
5528
        virReportOOMError();
5529
        goto endjob;
5530 5531
    }

R
Richard W.M. Jones 已提交
5532 5533
    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
5534 5535
        virReportSystemError(errno,
                             _("mkstemp(\"%s\") failed"), tmp);
5536
        goto endjob;
R
Richard W.M. Jones 已提交
5537 5538
    }

5539 5540
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm, tmp);

5541
    priv = vm->privateData;
5542
    qemuDomainObjEnterMonitor(vm);
5543
    if (flags == VIR_MEMORY_VIRTUAL) {
5544 5545
        if (qemuMonitorSaveVirtualMemory(priv->mon, offset, size, tmp) < 0) {
            qemuDomainObjExitMonitor(vm);
5546
            goto endjob;
5547
        }
5548
    } else {
5549 5550
        if (qemuMonitorSavePhysicalMemory(priv->mon, offset, size, tmp) < 0) {
            qemuDomainObjExitMonitor(vm);
5551
            goto endjob;
5552
        }
R
Richard W.M. Jones 已提交
5553
    }
5554
    qemuDomainObjExitMonitor(vm);
R
Richard W.M. Jones 已提交
5555 5556 5557

    /* Read the memory file into buffer. */
    if (saferead (fd, buffer, size) == (ssize_t) -1) {
5558 5559 5560
        virReportSystemError(errno,
                             _("failed to read temporary file "
                               "created with template %s"), tmp);
5561
        goto endjob;
R
Richard W.M. Jones 已提交
5562 5563 5564
    }

    ret = 0;
5565

5566
endjob:
5567 5568
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
5569

5570
cleanup:
5571
    VIR_FORCE_CLOSE(fd);
5572 5573
    if (tmp)
        unlink(tmp);
W
Wen Congyang 已提交
5574
    VIR_FREE(tmp);
5575 5576
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
5577 5578 5579
    return ret;
}

5580

5581 5582 5583 5584 5585 5586 5587 5588 5589 5590
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;
5591
    virDomainDiskDefPtr disk = NULL;
5592 5593
    struct stat sb;
    int i;
5594
    int format;
5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618

    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)) {
5619
            disk = vm->def->disks[i];
5620 5621 5622 5623
            break;
        }
    }

5624
    if (!disk) {
5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638
        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 */
5639 5640 5641 5642 5643 5644 5645 5646
    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 {
5647 5648 5649 5650 5651 5652 5653
        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);
5654
            goto cleanup;
5655
        }
5656 5657 5658 5659 5660
    }

    if (virStorageFileGetMetadataFromFD(path, fd,
                                        format,
                                        &meta) < 0)
5661 5662 5663 5664 5665 5666 5667 5668 5669 5670
        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)) {
5671
#ifndef WIN32
5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699
        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;

5700
    /* Set default value .. */
5701 5702
    info->allocation = info->physical;

5703 5704 5705
    /* ..but if guest is running & not using raw
       disk format and on a block device, then query
       highest allocated extent from QEMU */
5706
    if (disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
5707
        format != VIR_STORAGE_FILE_RAW &&
5708 5709 5710 5711
        S_ISBLK(sb.st_mode)) {
        qemuDomainObjPrivatePtr priv = vm->privateData;
        if (qemuDomainObjBeginJob(vm) < 0)
            goto cleanup;
5712 5713 5714 5715 5716 5717 5718 5719 5720
        if (!virDomainObjIsActive(vm))
            ret = 0;
        else {
            qemuDomainObjEnterMonitor(vm);
            ret = qemuMonitorGetBlockExtent(priv->mon,
                                            disk->info.alias,
                                            &info->allocation);
            qemuDomainObjExitMonitor(vm);
        }
5721 5722 5723 5724 5725 5726

        if (qemuDomainObjEndJob(vm) == 0)
            vm = NULL;
    } else {
        ret = 0;
    }
5727 5728

cleanup:
5729
    VIR_FORCE_CLOSE(fd);
5730 5731 5732 5733 5734 5735
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


5736
static int
5737 5738 5739 5740
qemuDomainEventRegister(virConnectPtr conn,
                        virConnectDomainEventCallback callback,
                        void *opaque,
                        virFreeCallback freecb)
5741
{
5742 5743 5744
    struct qemud_driver *driver = conn->privateData;
    int ret;

5745
    qemuDriverLock(driver);
5746 5747
    ret = virDomainEventCallbackListAdd(conn,
                                        driver->domainEventState->callbacks,
5748
                                        callback, opaque, freecb);
5749
    qemuDriverUnlock(driver);
5750

5751
    return ret;
5752 5753
}

5754

5755
static int
5756 5757
qemuDomainEventDeregister(virConnectPtr conn,
                          virConnectDomainEventCallback callback)
5758
{
5759 5760 5761
    struct qemud_driver *driver = conn->privateData;
    int ret;

5762
    qemuDriverLock(driver);
5763 5764 5765
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
5766
    qemuDriverUnlock(driver);
5767

5768
    return ret;
5769 5770
}

5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784

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,
5785
                                          driver->domainEventState->callbacks,
5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801
                                          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);
5802 5803 5804
    ret = virDomainEventStateDeregisterAny(conn,
                                           driver->domainEventState,
                                           callbackID);
5805 5806 5807 5808 5809 5810
    qemuDriverUnlock(driver);

    return ret;
}


5811 5812 5813
/*******************************************************************
 * Migration Protocol Version 2
 *******************************************************************/
D
Daniel Veillard 已提交
5814

C
Chris Lalancette 已提交
5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829
/* 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;
5830

5831 5832 5833 5834 5835 5836 5837 5838 5839
    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, -1);

C
Chris Lalancette 已提交
5840
    if (!dom_xml) {
5841 5842
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
C
Chris Lalancette 已提交
5843 5844 5845
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
5846
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
5847 5848 5849 5850
                         "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
        goto cleanup;
    }
    if (st == NULL) {
5851 5852
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("tunnelled migration requested but NULL stream passed"));
C
Chris Lalancette 已提交
5853 5854 5855
        goto cleanup;
    }

5856
    qemuDriverLock(driver);
5857 5858 5859
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     NULL, 0, NULL, NULL, /* No cookies in v2 */
                                     st, dname, dom_xml);
5860
    qemuDriverUnlock(driver);
5861

C
Chris Lalancette 已提交
5862 5863 5864 5865
cleanup:
    return ret;
}

D
Daniel Veillard 已提交
5866 5867 5868 5869
/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
5870
static int ATTRIBUTE_NONNULL (5)
D
Daniel Veillard 已提交
5871
qemudDomainMigratePrepare2 (virConnectPtr dconn,
5872 5873
                            char **cookie ATTRIBUTE_UNUSED,
                            int *cookielen ATTRIBUTE_UNUSED,
D
Daniel Veillard 已提交
5874 5875
                            const char *uri_in,
                            char **uri_out,
C
Chris Lalancette 已提交
5876
                            unsigned long flags,
D
Daniel Veillard 已提交
5877 5878 5879 5880
                            const char *dname,
                            unsigned long resource ATTRIBUTE_UNUSED,
                            const char *dom_xml)
{
5881
    struct qemud_driver *driver = dconn->privateData;
5882
    int ret = -1;
5883

C
Chris Lalancette 已提交
5884 5885 5886 5887 5888 5889 5890 5891 5892
    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, -1);

5893
    *uri_out = NULL;
D
Daniel Veillard 已提交
5894

5895
    qemuDriverLock(driver);
C
Chris Lalancette 已提交
5896 5897 5898 5899
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
5900 5901
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Tunnelled migration requested but invalid RPC method called"));
C
Chris Lalancette 已提交
5902 5903 5904
        goto cleanup;
    }

D
Daniel Veillard 已提交
5905
    if (!dom_xml) {
5906 5907
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
5908
        goto cleanup;
D
Daniel Veillard 已提交
5909 5910
    }

5911 5912 5913 5914
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
5915
    ret = qemuMigrationPrepareDirect(driver, dconn,
5916
                                     NULL, 0, NULL, NULL, /* No cookies */
5917 5918
                                     uri_in, uri_out,
                                     dname, dom_xml);
D
Daniel Veillard 已提交
5919

5920 5921 5922 5923
cleanup:
    qemuDriverUnlock(driver);
    return ret;
}
C
Chris Lalancette 已提交
5924

D
Daniel Veillard 已提交
5925

5926 5927 5928
/* Perform is the second step, and it runs on the source host. */
static int
qemudDomainMigratePerform (virDomainPtr dom,
5929 5930
                           const char *cookie,
                           int cookielen,
5931 5932 5933 5934 5935 5936 5937 5938
                           const char *uri,
                           unsigned long flags,
                           const char *dname,
                           unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
5939

5940 5941 5942 5943 5944 5945 5946 5947
    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, -1);
C
Chris Lalancette 已提交
5948

5949
    qemuDriverLock(driver);
5950
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel Veillard 已提交
5951
    if (!vm) {
5952 5953
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5954 5955
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5956
        goto cleanup;
D
Daniel Veillard 已提交
5957 5958
    }

5959 5960 5961 5962 5963 5964
    /* 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
     */
5965
    ret = qemuMigrationPerform(driver, dom->conn, vm,
5966 5967
                               uri, cookie, cookielen,
                               NULL, NULL, /* No output cookies in v2 */
5968
                               flags, dname, resource, true);
5969

5970
cleanup:
5971
    qemuDriverUnlock(driver);
5972
    return ret;
D
Daniel Veillard 已提交
5973 5974
}

5975

D
Daniel Veillard 已提交
5976 5977 5978 5979 5980 5981 5982
/* 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 已提交
5983
                           unsigned long flags,
D
Daniel Veillard 已提交
5984 5985
                           int retcode)
{
5986 5987 5988
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
5989
    virErrorPtr orig_err;
D
Daniel Veillard 已提交
5990

C
Chris Lalancette 已提交
5991 5992 5993 5994 5995 5996 5997 5998 5999
    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, NULL);

6000 6001 6002
    /* Migration failed. Save the current error so nothing squashes it */
    orig_err = virSaveLastError();

6003
    qemuDriverLock(driver);
6004
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
6005
    if (!vm) {
6006 6007
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
6008
        goto cleanup;
D
Daniel Veillard 已提交
6009 6010
    }

6011 6012 6013 6014
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
6015
    dom = qemuMigrationFinish(driver, dconn, vm,
6016
                              NULL, 0, NULL, NULL, /* No cookies */
6017
                              flags, retcode);
6018

6019
cleanup:
6020 6021 6022 6023
    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }
6024
    qemuDriverUnlock(driver);
6025
    return dom;
D
Daniel Veillard 已提交
6026 6027
}

6028

6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316
/*******************************************************************
 * Migration Protocol Version 3
 *******************************************************************/

static char *
qemuDomainMigrateBegin3(virDomainPtr domain,
                        char **cookieout,
                        int *cookieoutlen,
                        unsigned long flags,
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    char *xml = NULL;

    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, NULL);

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

    xml = qemuMigrationBegin(driver, vm,
                             cookieout, cookieoutlen);

cleanup:
    qemuDriverUnlock(driver);
    return xml;
}

static int
qemuDomainMigratePrepare3(virConnectPtr dconn,
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
                          const char *uri_in,
                          char **uri_out,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource ATTRIBUTE_UNUSED,
                          const char *dom_xml)
{
    struct qemud_driver *driver = dconn->privateData;
    int ret = -1;

    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, -1);

    *uri_out = NULL;

    qemuDriverLock(driver);
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Tunnelled migration requested but invalid RPC method called"));
        goto cleanup;
    }

    if (!dom_xml) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
        goto cleanup;
    }

    ret = qemuMigrationPrepareDirect(driver, dconn,
                                     cookiein, cookieinlen,
                                     cookieout, cookieoutlen,
                                     uri_in, uri_out,
                                     dname, dom_xml);

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}


static int
qemuDomainMigratePrepareTunnel3(virConnectPtr dconn,
                                virStreamPtr st,
                                const char *cookiein,
                                int cookieinlen,
                                char **cookieout,
                                int *cookieoutlen,
                                unsigned long flags,
                                const char *dname,
                                unsigned long resource ATTRIBUTE_UNUSED,
                                const char *dom_xml)
{
    struct qemud_driver *driver = dconn->privateData;
    int ret = -1;

    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, -1);

    if (!dom_xml) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                         "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
        goto cleanup;
    }
    if (st == NULL) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("tunnelled migration requested but NULL stream passed"));
        goto cleanup;
    }

    qemuDriverLock(driver);
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     cookiein, cookieinlen,
                                     cookieout, cookieoutlen,
                                     st, dname, dom_xml);
    qemuDriverUnlock(driver);

cleanup:
    return ret;
}


static int
qemuDomainMigratePerform3(virDomainPtr dom,
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
                          const char *uri,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, -1);

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

    ret = qemuMigrationPerform(driver, dom->conn, vm,
                               uri, cookiein, cookieinlen,
                               cookieout, cookieoutlen,
                               flags, dname, resource, false);

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}


static int
qemuDomainMigrateFinish3(virConnectPtr dconn,
                         const char *dname,
                         const char *cookiein,
                         int cookieinlen,
                         char **cookieout,
                         int *cookieoutlen,
                         const char *uri ATTRIBUTE_UNUSED,
                         unsigned long flags,
                         int cancelled,
                         virDomainPtr *newdom)
{
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virErrorPtr orig_err;
    int ret = -1;

    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, -1);

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

    qemuDriverLock(driver);
    vm = virDomainFindByName(&driver->domains, dname);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
        goto cleanup;
    }

    *newdom = qemuMigrationFinish(driver, dconn, vm,
                                  cookiein, cookieinlen,
                                  cookieout, cookieoutlen,
                                  flags, cancelled);

    ret = 0;

cleanup:
    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }
    qemuDriverUnlock(driver);
    return ret;
}

static int
qemuDomainMigrateConfirm3(virDomainPtr domain,
                          const char *cookiein,
                          int cookieinlen,
                          unsigned long flags,
                          int cancelled)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, -1);

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

    ret = qemuMigrationConfirm(driver, domain->conn, vm,
                               cookiein, cookieinlen,
                               flags, cancelled, false);

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}


6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332
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;

6333
    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE);
6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350
    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) {
6351 6352
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("device %s is not a PCI device"), dev->name);
6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365
        goto out;
    }

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

static int
qemudNodeDeviceDettach (virNodeDevicePtr dev)
{
6366
    struct qemud_driver *driver = dev->conn->privateData;
6367 6368 6369 6370 6371 6372 6373
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

6374
    pci = pciGetDevice(domain, bus, slot, function);
6375 6376 6377
    if (!pci)
        return -1;

6378 6379
    qemuDriverLock(driver);
    if (pciDettachDevice(pci, driver->activePciHostdevs) < 0)
6380 6381 6382 6383
        goto out;

    ret = 0;
out:
6384
    qemuDriverUnlock(driver);
6385
    pciFreeDevice(pci);
6386 6387 6388 6389 6390 6391
    return ret;
}

static int
qemudNodeDeviceReAttach (virNodeDevicePtr dev)
{
6392
    struct qemud_driver *driver = dev->conn->privateData;
6393 6394 6395 6396 6397 6398 6399
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

6400
    pci = pciGetDevice(domain, bus, slot, function);
6401 6402 6403
    if (!pci)
        return -1;

6404 6405
    qemuDriverLock(driver);
    if (pciReAttachDevice(pci, driver->activePciHostdevs) < 0)
6406 6407 6408 6409
        goto out;

    ret = 0;
out:
6410
    qemuDriverUnlock(driver);
6411
    pciFreeDevice(pci);
6412 6413 6414 6415 6416 6417
    return ret;
}

static int
qemudNodeDeviceReset (virNodeDevicePtr dev)
{
6418
    struct qemud_driver *driver = dev->conn->privateData;
6419 6420 6421 6422 6423 6424 6425
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

6426
    pci = pciGetDevice(domain, bus, slot, function);
6427 6428 6429
    if (!pci)
        return -1;

6430 6431
    qemuDriverLock(driver);

6432
    if (pciResetDevice(pci, driver->activePciHostdevs, NULL) < 0)
6433 6434 6435 6436
        goto out;

    ret = 0;
out:
6437
    qemuDriverUnlock(driver);
6438
    pciFreeDevice(pci);
6439 6440 6441
    return ret;
}

6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452
static int
qemuCPUCompare(virConnectPtr conn,
               const char *xmlDesc,
               unsigned int flags ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = conn->privateData;
    int ret = VIR_CPU_COMPARE_ERROR;

    qemuDriverLock(driver);

    if (!driver->caps || !driver->caps->host.cpu) {
6453 6454
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        "%s", _("cannot get host CPU capabilities"));
6455 6456
    }
    else
6457
        ret = cpuCompareXML(driver->caps->host.cpu, xmlDesc);
6458 6459 6460 6461 6462 6463

    qemuDriverUnlock(driver);

    return ret;
}

6464

6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477
static char *
qemuCPUBaseline(virConnectPtr conn ATTRIBUTE_UNUSED,
                const char **xmlCPUs,
                unsigned int ncpus,
                unsigned int flags ATTRIBUTE_UNUSED)
{
    char *cpu;

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

    return cpu;
}

6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500

static int qemuDomainGetJobInfo(virDomainPtr dom,
                                virDomainJobInfoPtr info) {
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

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

    priv = vm->privateData;

    if (virDomainObjIsActive(vm)) {
        if (priv->jobActive) {
6501 6502
            struct timeval now;

6503
            memcpy(info, &priv->jobInfo, sizeof(*info));
6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514

            /* Refresh elapsed time again just to ensure it
             * is fully updated. This is primarily for benefit
             * of incoming migration which we don't currently
             * monitor actively in the background thread
             */
            if (gettimeofday(&now, NULL) < 0) {
                virReportSystemError(errno, "%s",
                                     _("cannot get time of day"));
                goto cleanup;
            }
6515
            info->timeElapsed = timeval_to_ms(now) - priv->jobStart;
6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534
        } 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;
}


6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556
static int qemuDomainAbortJob(virDomainPtr dom) {
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

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

    priv = vm->privateData;

    if (virDomainObjIsActive(vm)) {
        if (priv->jobActive) {
            VIR_DEBUG("Requesting cancellation of job on vm %s", vm->def->name);
6557
            priv->jobSignals |= QEMU_JOB_SIGNAL_CANCEL;
6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577
        } 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;
}


6578 6579 6580 6581 6582 6583 6584 6585 6586 6587
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;

6588
    virCheckFlags(0, -1);
6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608

    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;

6609
    if (priv->jobActive != QEMU_JOB_MIGRATION_OUT) {
6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not being migrated"));
        goto cleanup;
    }

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

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

6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675
static int
qemuDomainMigrateSetMaxSpeed(virDomainPtr dom,
                             unsigned long bandwidth,
                             unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(0, -1);

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

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

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

    priv = vm->privateData;

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

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

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

C
Chris Lalancette 已提交
6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689
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;
}

6690 6691 6692
static int qemuDomainSnapshotWriteMetadata(virDomainObjPtr vm,
                                           virDomainSnapshotObjPtr snapshot,
                                           char *snapshotDir)
C
Chris Lalancette 已提交
6693 6694 6695 6696 6697 6698 6699 6700 6701 6702
{
    int fd = -1;
    char *newxml = NULL;
    int ret = -1;
    char *snapDir = NULL;
    char *snapFile = NULL;
    int err;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    virUUIDFormat(vm->def->uuid, uuidstr);
6703
    newxml = virDomainSnapshotDefFormat(uuidstr, snapshot->def, 1);
C
Chris Lalancette 已提交
6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719
    if (newxml == NULL) {
        virReportOOMError();
        return -1;
    }

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

6720
    if (virAsprintf(&snapFile, "%s/%s.xml", snapDir, snapshot->def->name) < 0) {
C
Chris Lalancette 已提交
6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741
        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);
6742
    VIR_FORCE_CLOSE(fd);
C
Chris Lalancette 已提交
6743 6744 6745
    return ret;
}

6746 6747
static int qemuDomainSnapshotSetCurrentActive(virDomainObjPtr vm,
                                              char *snapshotDir)
C
Chris Lalancette 已提交
6748 6749 6750 6751
{
    if (vm->current_snapshot) {
        vm->current_snapshot->def->active = 1;

6752 6753
        return qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                               snapshotDir);
C
Chris Lalancette 已提交
6754 6755 6756 6757 6758
    }

    return 0;
}

6759 6760
static int qemuDomainSnapshotSetCurrentInactive(virDomainObjPtr vm,
                                                char *snapshotDir)
C
Chris Lalancette 已提交
6761 6762 6763 6764
{
    if (vm->current_snapshot) {
        vm->current_snapshot->def->active = 0;

6765 6766
        return qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                               snapshotDir);
C
Chris Lalancette 已提交
6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785
    }

    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,
6786 6787
                            _("Disk '%s' does not support snapshotting"),
                            vm->def->disks[i]->src);
C
Chris Lalancette 已提交
6788 6789 6790 6791 6792 6793 6794
            return 0;
        }
    }

    return 1;
}

6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842
/* 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
6843 6844
qemuDomainSnapshotCreateActive(virConnectPtr conn,
                               struct qemud_driver *driver,
6845 6846 6847 6848 6849
                               virDomainObjPtr *vmptr,
                               virDomainSnapshotObjPtr snap)
{
    virDomainObjPtr vm = *vmptr;
    qemuDomainObjPrivatePtr priv = vm->privateData;
6850 6851
    bool resume = false;
    int ret = -1;
6852 6853 6854 6855

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

J
Jiri Denemark 已提交
6856
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
6857 6858 6859 6860
        /* 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 已提交
6861
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE) < 0)
6862 6863 6864 6865 6866 6867 6868 6869 6870 6871
            goto cleanup;

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

6872 6873 6874 6875
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    ret = qemuMonitorCreateSnapshot(priv->mon, snap->def->name);
    qemuDomainObjExitMonitorWithDriver(driver, vm);

6876 6877
cleanup:
    if (resume && virDomainObjIsActive(vm) &&
J
Jiri Denemark 已提交
6878 6879
        qemuProcessStartCPUs(driver, vm, conn,
                             VIR_DOMAIN_RUNNING_UNPAUSED) < 0 &&
6880 6881 6882 6883 6884
        virGetLastError() == NULL) {
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("resuming after snapshot failed"));
    }

6885 6886 6887 6888 6889 6890
    if (qemuDomainObjEndJob(vm) == 0)
        *vmptr = NULL;

    return ret;
}

C
Chris Lalancette 已提交
6891 6892
static virDomainSnapshotPtr qemuDomainSnapshotCreateXML(virDomainPtr domain,
                                                        const char *xmlDesc,
6893
                                                        unsigned int flags)
C
Chris Lalancette 已提交
6894 6895 6896 6897 6898 6899 6900 6901
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virDomainSnapshotDefPtr def;

6902 6903
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
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
    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 已提交
6929
    snap->def->state = virDomainObjGetState(vm, NULL);
6930

C
Chris Lalancette 已提交
6931 6932
    /* actually do the snapshot */
    if (!virDomainObjIsActive(vm)) {
6933
        if (qemuDomainSnapshotCreateInactive(vm, snap) < 0)
C
Chris Lalancette 已提交
6934 6935 6936
            goto cleanup;
    }
    else {
6937 6938
        if (qemuDomainSnapshotCreateActive(domain->conn, driver,
                                           &vm, snap) < 0)
6939
            goto cleanup;
C
Chris Lalancette 已提交
6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957
    }

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

6958 6959 6960
    if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
                                        driver->snapshotDir) < 0)
        /* qemuDomainSnapshotWriteMetadata set the error */
C
Chris Lalancette 已提交
6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973
        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,
6974
                                       unsigned int flags)
C
Chris Lalancette 已提交
6975 6976 6977 6978 6979
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

6980 6981
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001
    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,
7002
                                 unsigned int flags)
C
Chris Lalancette 已提交
7003 7004 7005 7006 7007
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

7008 7009
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030
    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,
7031
                                                           unsigned int flags)
C
Chris Lalancette 已提交
7032 7033 7034 7035 7036 7037
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;

7038 7039
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066
    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,
7067
                                        unsigned int flags)
C
Chris Lalancette 已提交
7068 7069 7070 7071 7072
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

7073 7074
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094
    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,
7095
                                                      unsigned int flags)
C
Chris Lalancette 已提交
7096 7097 7098 7099 7100
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotPtr snapshot = NULL;

7101 7102
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127
    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;
}

7128 7129
static char *qemuDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                                          unsigned int flags)
C
Chris Lalancette 已提交
7130 7131 7132 7133 7134 7135 7136
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *xml = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

7137 7138
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165
    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,
7166
                                      unsigned int flags)
C
Chris Lalancette 已提交
7167 7168 7169 7170 7171 7172 7173 7174 7175 7176
{
    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;

7177 7178
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209
    qemuDriverLock(driver);
    virUUIDFormat(snapshot->domain->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
    if (!snap) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                        _("no domain snapshot with matching name '%s'"),
                        snapshot->name);
        goto cleanup;
    }

    vm->current_snapshot = snap;

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

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

        if (virDomainObjIsActive(vm)) {
            priv = vm->privateData;
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
            rc = qemuMonitorLoadSnapshot(priv->mon, snap->def->name);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            if (rc < 0)
7210
                goto endjob;
C
Chris Lalancette 已提交
7211 7212
        }
        else {
7213
            if (qemuDomainSnapshotSetCurrentActive(vm, driver->snapshotDir) < 0)
7214
                goto endjob;
C
Chris Lalancette 已提交
7215

7216 7217
            rc = qemuProcessStart(snapshot->domain->conn, driver, vm, NULL,
                                  false, -1, NULL, VIR_VM_OP_CREATE);
7218
            qemuAuditDomainStart(vm, "from-snapshot", rc >= 0);
7219
            if (qemuDomainSnapshotSetCurrentInactive(vm, driver->snapshotDir) < 0)
7220
                goto endjob;
C
Chris Lalancette 已提交
7221
            if (rc < 0)
7222
                goto endjob;
C
Chris Lalancette 已提交
7223 7224 7225 7226 7227 7228
        }

        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 已提交
7229 7230
            rc = qemuProcessStopCPUs(driver, vm,
                                     VIR_DOMAIN_PAUSED_FROM_SNAPSHOT);
H
Hu Tao 已提交
7231
            if (rc < 0)
7232
                goto endjob;
J
Jiri Denemark 已提交
7233 7234 7235
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_FROM_SNAPSHOT);
C
Chris Lalancette 已提交
7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253
        }

        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 已提交
7254
            qemuProcessStop(driver, vm, 0, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT);
7255
            qemuAuditDomainStop(vm, "from-snapshot");
C
Chris Lalancette 已提交
7256 7257 7258
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STOPPED,
                                             VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT);
7259 7260 7261 7262
            if (!vm->persistent) {
                if (qemuDomainObjEndJob(vm) > 0)
                    virDomainRemoveInactive(&driver->domains, vm);
                vm = NULL;
7263
                goto cleanup;
7264
            }
C
Chris Lalancette 已提交
7265 7266
        }

7267
        if (qemuDomainSnapshotSetCurrentActive(vm, driver->snapshotDir) < 0)
7268
            goto endjob;
C
Chris Lalancette 已提交
7269 7270 7271 7272
    }

    ret = 0;

7273
endjob:
C
Chris Lalancette 已提交
7274 7275 7276
    if (vm && qemuDomainObjEndJob(vm) == 0)
        vm = NULL;

7277
cleanup:
C
Chris Lalancette 已提交
7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379
    if (event)
        qemuDomainEventQueue(driver, event);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);

    return ret;
}

static int qemuDomainSnapshotDiscard(struct qemud_driver *driver,
                                     virDomainObjPtr vm,
                                     virDomainSnapshotObjPtr snap)
{
    const char *qemuimgarg[] = { NULL, "snapshot", "-d", NULL, NULL, NULL };
    char *snapFile = NULL;
    int ret = -1;
    int i;
    qemuDomainObjPrivatePtr priv;
    virDomainSnapshotObjPtr parentsnap;

    if (!virDomainObjIsActive(vm)) {
        qemuimgarg[0] = qemuFindQemuImgBinary();
        if (qemuimgarg[0] == NULL)
            /* qemuFindQemuImgBinary set the error */
            goto cleanup;

        qemuimgarg[3] = snap->def->name;

        for (i = 0; i < vm->def->ndisks; i++) {
            /* FIXME: we also need to handle LVM here */
            if (vm->def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
                if (!vm->def->disks[i]->driverType ||
                    STRNEQ(vm->def->disks[i]->driverType, "qcow2")) {
                    /* we continue on even in the face of error, since other
                     * disks in this VM may have this snapshot in place
                     */
                    continue;
                }

                qemuimgarg[4] = vm->def->disks[i]->src;

                if (virRun(qemuimgarg, NULL) < 0) {
                    /* we continue on even in the face of error, since other
                     * disks in this VM may have this snapshot in place
                     */
                    continue;
                }
            }
        }
    }
    else {
        priv = vm->privateData;
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
        /* we continue on even in the face of error */
        qemuMonitorDeleteSnapshot(priv->mon, snap->def->name);
        qemuDomainObjExitMonitorWithDriver(driver, vm);
    }

    if (snap == vm->current_snapshot) {
        if (snap->def->parent) {
            parentsnap = virDomainSnapshotFindByName(&vm->snapshots,
                                                     snap->def->parent);
            if (!parentsnap) {
                qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                                _("no domain snapshot parent with matching name '%s'"),
                                snap->def->parent);
                goto cleanup;
            }

            /* Now we set the new current_snapshot for the domain */
            vm->current_snapshot = parentsnap;
        }
        else
            vm->current_snapshot = NULL;
    }

    if (virAsprintf(&snapFile, "%s/%s/%s.xml", driver->snapshotDir,
                    vm->def->name, snap->def->name) < 0) {
        virReportOOMError();
        goto cleanup;
    }
    unlink(snapFile);

    virDomainSnapshotObjListRemove(&vm->snapshots, snap);

    ret = 0;

cleanup:
    VIR_FREE(snapFile);
    VIR_FREE(qemuimgarg[0]);

    return ret;
}

struct snap_remove {
    struct qemud_driver *driver;
    virDomainObjPtr vm;
    char *parent;
    int err;
};

static void qemuDomainSnapshotDiscardChildren(void *payload,
7380
                                              const void *name ATTRIBUTE_UNUSED,
C
Chris Lalancette 已提交
7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401
                                              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);
    }
}

7402 7403 7404 7405 7406 7407 7408 7409 7410
struct snap_reparent {
    struct qemud_driver *driver;
    virDomainSnapshotObjPtr snap;
    virDomainObjPtr vm;
    int err;
};

static void
qemuDomainSnapshotReparentChildren(void *payload,
7411
                                   const void *name ATTRIBUTE_UNUSED,
7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438
                                   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 已提交
7439 7440 7441 7442 7443 7444 7445 7446 7447
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;
7448
    struct snap_reparent rep;
C
Chris Lalancette 已提交
7449

7450 7451
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

C
Chris Lalancette 已提交
7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468
    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;
    }

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

C
Chris Lalancette 已提交
7472 7473 7474 7475 7476 7477 7478 7479
    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)
7480
            goto endjob;
7481 7482 7483 7484 7485 7486 7487 7488 7489
    } 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 已提交
7490 7491 7492 7493
    }

    ret = qemuDomainSnapshotDiscard(driver, vm, snap);

7494 7495 7496 7497
endjob:
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;

C
Chris Lalancette 已提交
7498 7499 7500 7501 7502 7503
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
7504

7505 7506 7507 7508 7509 7510 7511
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;
7512
    bool hmp;
7513

7514
    virCheckFlags(VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP, -1);
7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533

    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;

7534
    qemuDomainObjTaint(driver, vm, VIR_DOMAIN_TAINT_CUSTOM_MONITOR, -1);
7535

7536 7537
    hmp = !!(flags & VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP);

7538 7539 7540
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
7541
    ret = qemuMonitorArbitraryCommand(priv->mon, cmd, result, hmp);
7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554
    qemuDomainObjExitMonitorWithDriver(driver, vm);
    if (qemuDomainObjEndJob(vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

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

7555 7556 7557 7558 7559 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 7608 7609 7610 7611

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

7612
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
7613 7614 7615 7616 7617 7618
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("character device %s is not using a PTY"),
                        NULLSTR(devname));
        goto cleanup;
    }

7619 7620
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
                            0, 0, O_RDWR, false) < 0)
7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631
        goto cleanup;

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


7632
static virDriver qemuDriver = {
7633 7634
    .no = VIR_DRV_QEMU,
    .name = "QEMU",
7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741
    .open = qemudOpen, /* 0.2.0 */
    .close = qemudClose, /* 0.2.0 */
    .supports_feature = qemudSupportsFeature, /* 0.5.0 */
    .type = qemudGetType, /* 0.2.0 */
    .version = qemudGetVersion, /* 0.2.0 */
    .getHostname = virGetHostname, /* 0.3.3 */
    .getSysinfo = qemuGetSysinfo, /* 0.8.8 */
    .getMaxVcpus = qemudGetMaxVCPUs, /* 0.2.1 */
    .nodeGetInfo = nodeGetInfo, /* 0.2.0 */
    .getCapabilities = qemudGetCapabilities, /* 0.2.1 */
    .listDomains = qemudListDomains, /* 0.2.0 */
    .numOfDomains = qemudNumDomains, /* 0.2.0 */
    .domainCreateXML = qemudDomainCreate, /* 0.2.0 */
    .domainLookupByID = qemudDomainLookupByID, /* 0.2.0 */
    .domainLookupByUUID = qemudDomainLookupByUUID, /* 0.2.0 */
    .domainLookupByName = qemudDomainLookupByName, /* 0.2.0 */
    .domainSuspend = qemudDomainSuspend, /* 0.2.0 */
    .domainResume = qemudDomainResume, /* 0.2.0 */
    .domainShutdown = qemudDomainShutdown, /* 0.2.0 */
    .domainDestroy = qemudDomainDestroy, /* 0.2.0 */
    .domainGetOSType = qemudDomainGetOSType, /* 0.2.2 */
    .domainGetMaxMemory = qemudDomainGetMaxMemory, /* 0.4.2 */
    .domainSetMaxMemory = qemudDomainSetMaxMemory, /* 0.4.2 */
    .domainSetMemory = qemudDomainSetMemory, /* 0.4.2 */
    .domainSetMemoryFlags = qemudDomainSetMemoryFlags, /* 0.9.0 */
    .domainSetMemoryParameters = qemuDomainSetMemoryParameters, /* 0.8.5 */
    .domainGetMemoryParameters = qemuDomainGetMemoryParameters, /* 0.8.5 */
    .domainSetBlkioParameters = qemuDomainSetBlkioParameters, /* 0.9.0 */
    .domainGetBlkioParameters = qemuDomainGetBlkioParameters, /* 0.9.0 */
    .domainGetInfo = qemudDomainGetInfo, /* 0.2.0 */
    .domainGetState = qemuDomainGetState, /* 0.9.2 */
    .domainSave = qemudDomainSave, /* 0.2.0 */
    .domainRestore = qemuDomainRestore, /* 0.2.0 */
    .domainCoreDump = qemudDomainCoreDump, /* 0.7.0 */
    .domainScreenshot = qemuDomainScreenshot, /* 0.9.2 */
    .domainSetVcpus = qemudDomainSetVcpus, /* 0.4.4 */
    .domainSetVcpusFlags = qemudDomainSetVcpusFlags, /* 0.8.5 */
    .domainGetVcpusFlags = qemudDomainGetVcpusFlags, /* 0.8.5 */
    .domainPinVcpu = qemudDomainPinVcpu, /* 0.4.4 */
    .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 */
    .domainSetSchedulerParameters = qemuSetSchedulerParameters, /* 0.7.0 */
    .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 */
    .nodeGetCellsFreeMemory = nodeGetCellsFreeMemory, /* 0.4.4 */
    .nodeGetFreeMemory = nodeGetFreeMemory, /* 0.4.4 */
    .domainEventRegister = qemuDomainEventRegister, /* 0.5.0 */
    .domainEventDeregister = qemuDomainEventDeregister, /* 0.5.0 */
    .domainMigratePrepare2 = qemudDomainMigratePrepare2, /* 0.5.0 */
    .domainMigrateFinish2 = qemudDomainMigrateFinish2, /* 0.5.0 */
    .nodeDeviceDettach = qemudNodeDeviceDettach, /* 0.6.1 */
    .nodeDeviceReAttach = qemudNodeDeviceReAttach, /* 0.6.1 */
    .nodeDeviceReset = qemudNodeDeviceReset, /* 0.6.1 */
    .domainMigratePrepareTunnel = qemudDomainMigratePrepareTunnel, /* 0.7.2 */
    .isEncrypted = qemuIsEncrypted, /* 0.7.3 */
    .isSecure = qemuIsSecure, /* 0.7.3 */
    .domainIsActive = qemuDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = qemuDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = qemuDomainIsUpdated, /* 0.8.6 */
    .cpuCompare = qemuCPUCompare, /* 0.7.5 */
    .cpuBaseline = qemuCPUBaseline, /* 0.7.7 */
    .domainGetJobInfo = qemuDomainGetJobInfo, /* 0.7.7 */
    .domainAbortJob = qemuDomainAbortJob, /* 0.7.7 */
    .domainMigrateSetMaxDowntime = qemuDomainMigrateSetMaxDowntime, /* 0.8.0 */
    .domainMigrateSetMaxSpeed = qemuDomainMigrateSetMaxSpeed, /* 0.9.0 */
    .domainEventRegisterAny = qemuDomainEventRegisterAny, /* 0.8.0 */
    .domainEventDeregisterAny = qemuDomainEventDeregisterAny, /* 0.8.0 */
    .domainManagedSave = qemuDomainManagedSave, /* 0.8.0 */
    .domainHasManagedSaveImage = qemuDomainHasManagedSaveImage, /* 0.8.0 */
    .domainManagedSaveRemove = qemuDomainManagedSaveRemove, /* 0.8.0 */
    .domainSnapshotCreateXML = qemuDomainSnapshotCreateXML, /* 0.8.0 */
    .domainSnapshotGetXMLDesc = qemuDomainSnapshotGetXMLDesc, /* 0.8.0 */
    .domainSnapshotNum = qemuDomainSnapshotNum, /* 0.8.0 */
    .domainSnapshotListNames = qemuDomainSnapshotListNames, /* 0.8.0 */
    .domainSnapshotLookupByName = qemuDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = qemuDomainHasCurrentSnapshot, /* 0.8.0 */
    .domainSnapshotCurrent = qemuDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = qemuDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = qemuDomainSnapshotDelete, /* 0.8.0 */
    .qemuDomainMonitorCommand = qemuDomainMonitorCommand, /* 0.8.3 */
    .domainOpenConsole = qemuDomainOpenConsole, /* 0.8.6 */
    .domainInjectNMI = qemuDomainInjectNMI, /* 0.9.2 */
7742 7743 7744 7745 7746 7747
    .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 */
7748
    .domainSetSchedulerParametersFlags = qemuSetSchedulerParametersFlags, /* 0.9.2 */
7749 7750 7751
};


7752
static virStateDriver qemuStateDriver = {
7753
    .name = "QEMU",
7754 7755 7756 7757
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
7758
};
7759

7760
static void
7761
qemuVMDriverLock(void) {
7762 7763 7764 7765 7766
    qemuDriverLock(qemu_driver);
};


static void
7767
qemuVMDriverUnlock(void) {
7768 7769 7770 7771
    qemuDriverUnlock(qemu_driver);
};


7772 7773 7774 7775 7776 7777 7778 7779 7780
static int
qemuVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
                    virHashIterator iter, void *data)
{
    virHashForEach(qemu_driver->domains.objs, iter, data);

    return 0;
}

S
Stefan Berger 已提交
7781 7782
static virNWFilterCallbackDriver qemuCallbackDriver = {
    .name = "QEMU",
7783 7784 7785
    .vmFilterRebuild = qemuVMFilterRebuild,
    .vmDriverLock = qemuVMDriverLock,
    .vmDriverUnlock = qemuVMDriverUnlock,
S
Stefan Berger 已提交
7786 7787
};

7788
int qemuRegister(void) {
7789 7790
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
S
Stefan Berger 已提交
7791
    virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);
7792 7793
    return 0;
}