qemu_driver.c 508.0 KB
Newer Older
D
Daniel P. Berrange 已提交
1
/*
2
 * qemu_driver.c: core driver methods for managing qemu guests
D
Daniel P. Berrange 已提交
3
 *
4
 * Copyright (C) 2006-2013 Red Hat, Inc.
D
Daniel P. Berrange 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
D
Daniel P. Berrange 已提交
20 21 22 23
 *
 * 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 38 39 40 41
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <paths.h>
#include <sys/wait.h>
42
#include <sys/ioctl.h>
43
#include <sys/un.h>
44
#include <byteswap.h>
D
Daniel P. Berrange 已提交
45

46

47
#include "qemu_driver.h"
48
#include "qemu_agent.h"
49
#include "qemu_conf.h"
50
#include "qemu_capabilities.h"
51
#include "qemu_command.h"
52
#include "qemu_cgroup.h"
53
#include "qemu_hostdev.h"
54
#include "qemu_hotplug.h"
55
#include "qemu_monitor.h"
56
#include "qemu_bridge_filter.h"
57
#include "qemu_process.h"
58
#include "qemu_migration.h"
59

60
#include "virerror.h"
61
#include "virlog.h"
62
#include "datatypes.h"
63
#include "virbuffer.h"
64
#include "nodeinfo.h"
65
#include "virstatslinux.h"
66
#include "capabilities.h"
67
#include "viralloc.h"
68
#include "viruuid.h"
69
#include "domain_conf.h"
70
#include "domain_audit.h"
71
#include "node_device_conf.h"
72
#include "virpci.h"
73
#include "virusb.h"
74
#include "virprocess.h"
C
Chris Lalancette 已提交
75
#include "libvirt_internal.h"
76
#include "virxml.h"
77
#include "cpu/cpu.h"
78
#include "virsysinfo.h"
79
#include "domain_nwfilter.h"
80
#include "nwfilter_conf.h"
81
#include "virhook.h"
82
#include "virstoragefile.h"
E
Eric Blake 已提交
83
#include "virfile.h"
84
#include "fdstream.h"
85
#include "configmake.h"
86
#include "virthreadpool.h"
87
#include "locking/lock_manager.h"
88
#include "locking/domain_lock.h"
89
#include "virkeycode.h"
90
#include "virnodesuspend.h"
91
#include "virtime.h"
92
#include "virtypedparam.h"
93
#include "virbitmap.h"
94
#include "virstring.h"
95 96
#include "viraccessapicheck.h"
#include "viraccessapicheckqemu.h"
97

98 99
#define VIR_FROM_THIS VIR_FROM_QEMU

100 101
#define QEMU_DRIVER_NAME "QEMU"

102 103
#define QEMU_NB_MEM_PARAM  3

104 105
#define QEMU_NB_BLOCK_IO_TUNE_PARAM  6

106 107
#define QEMU_NB_NUMA_PARAM 2

E
Eric Blake 已提交
108
#define QEMU_NB_TOTAL_CPU_STAT_PARAM 3
109
#define QEMU_NB_PER_CPU_STAT_PARAM 2
E
Eric Blake 已提交
110

111 112 113 114 115
#define QEMU_SCHED_MIN_PERIOD              1000LL
#define QEMU_SCHED_MAX_PERIOD           1000000LL
#define QEMU_SCHED_MIN_QUOTA               1000LL
#define QEMU_SCHED_MAX_QUOTA  18446744073709551LL

116 117 118
#if HAVE_LINUX_KVM_H
# include <linux/kvm.h>
#endif
119

120 121
/* device for kvm ioctls */
#define KVM_DEVICE "/dev/kvm"
122

123 124 125 126 127 128 129 130 131 132 133
/* 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

134
#define QEMU_NB_BLKIO_PARAM  2
135

136 137
#define QEMU_NB_BANDWIDTH_PARAM 6

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

140
static int qemuStateCleanup(void);
141

142
static int qemuDomainObjStart(virConnectPtr conn,
143
                              virQEMUDriverPtr driver,
144
                              virDomainObjPtr vm,
145
                              unsigned int flags);
J
Jiri Denemark 已提交
146

147
static int qemuDomainGetMaxVcpus(virDomainPtr dom);
148

149 150
static int qemuDomainManagedSaveLoad(virDomainObjPtr vm,
                                     void *opaque);
151 152


153
virQEMUDriverPtr qemu_driver = NULL;
154 155


156
static void
157
qemuVMDriverLock(void) {}
158
static void
159
qemuVMDriverUnlock(void) {}
160 161 162

static int
qemuVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
163
                    virDomainObjListIterator iter, void *data)
164
{
165
    return virDomainObjListForEach(qemu_driver->domains, iter, data);
166 167 168 169 170 171 172 173 174 175
}

static virNWFilterCallbackDriver qemuCallbackDriver = {
    .name = QEMU_DRIVER_NAME,
    .vmFilterRebuild = qemuVMFilterRebuild,
    .vmDriverLock = qemuVMDriverLock,
    .vmDriverUnlock = qemuVMDriverUnlock,
};


176
struct qemuAutostartData {
177
    virQEMUDriverPtr driver;
178 179
    virConnectPtr conn;
};
180

181

182
/**
183
 * qemuDomObjFromDomain:
184 185
 * @domain: Domain pointer that has to be looked up
 *
186 187
 * This function looks up @domain and returns the appropriate
 * virDomainObjPtr.
188
 *
189 190
 * Returns the domain object which is locked on success, NULL
 * otherwise.
191
 */
192
static virDomainObjPtr
193
qemuDomObjFromDomain(virDomainPtr domain)
194 195
{
    virDomainObjPtr vm;
196
    virQEMUDriverPtr driver = domain->conn->privateData;
197 198
    char uuidstr[VIR_UUID_STRING_BUFLEN];

199
    vm = virDomainObjListFindByUUID(driver->domains, domain->uuid);
200 201 202
    if (!vm) {
        virUUIDFormat(domain->uuid, uuidstr);
        virReportError(VIR_ERR_NO_DOMAIN,
203 204
                       _("no domain with matching uuid '%s' (%s)"),
                       uuidstr, domain->name);
205
        return NULL;
206 207
    }

208 209
    return vm;
}
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

/* Looks up the domain object from snapshot and unlocks the driver. The
 * returned domain object is locked and the caller is responsible for
 * unlocking it */
static virDomainObjPtr
qemuDomObjFromSnapshot(virDomainSnapshotPtr snapshot)
{
    return qemuDomObjFromDomain(snapshot->domain);
}


/* Looks up snapshot object from VM and name */
static virDomainSnapshotObjPtr
qemuSnapObjFromName(virDomainObjPtr vm,
                    const char *name)
{
    virDomainSnapshotObjPtr snap = NULL;
    snap = virDomainSnapshotFindByName(vm->snapshots, name);
    if (!snap)
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("no domain snapshot with matching name '%s'"),
                       name);

    return snap;
}


/* Looks up snapshot object from VM and snapshotPtr */
static virDomainSnapshotObjPtr
qemuSnapObjFromSnapshot(virDomainObjPtr vm,
                        virDomainSnapshotPtr snapshot)
{
    return qemuSnapObjFromName(vm, snapshot->name);
}

245 246
static int
qemuAutostartDomain(virDomainObjPtr vm,
247
                    void *opaque)
248 249
{
    struct qemuAutostartData *data = opaque;
250
    virErrorPtr err;
251
    int flags = 0;
252
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(data->driver);
253
    int ret = -1;
254

255
    if (cfg->autoStartBypassCache)
256
        flags |= VIR_DOMAIN_START_BYPASS_CACHE;
257

258
    virObjectLock(vm);
259
    virResetLastError();
260 261
    if (vm->autostart &&
        !virDomainObjIsActive(vm)) {
262 263
        if (qemuDomainObjBeginJob(data->driver, vm,
                                  QEMU_JOB_MODIFY) < 0) {
264 265 266 267 268 269 270 271
            err = virGetLastError();
            VIR_ERROR(_("Failed to start job on VM '%s': %s"),
                      vm->def->name,
                      err ? err->message : _("unknown error"));
            goto cleanup;
        }

        if (qemuDomainObjStart(data->conn, data->driver, vm, flags) < 0) {
272
            err = virGetLastError();
273
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
274
                      vm->def->name,
275
                      err ? err->message : _("unknown error"));
276
        }
277

278
        if (qemuDomainObjEndJob(data->driver, vm) == 0)
279
            vm = NULL;
280
    }
281

282
    ret = 0;
283
cleanup:
284
    if (vm)
285
        virObjectUnlock(vm);
286
    virObjectUnref(cfg);
287
    return ret;
288 289
}

290

291
static void
292
qemuAutostartDomains(virQEMUDriverPtr driver)
293
{
294
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
295 296 297 298 299
    /* 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
     */
300
    virConnectPtr conn = virConnectOpen(cfg->uri);
301
    /* Ignoring NULL conn which is mostly harmless here */
302
    struct qemuAutostartData data = { driver, conn };
303

304
    virDomainObjListForEach(driver->domains, qemuAutostartDomain, &data);
305

306 307
    if (conn)
        virConnectClose(conn);
308
    virObjectUnref(cfg);
309 310
}

311
static int
312
qemuSecurityInit(virQEMUDriverPtr driver)
313
{
314
    char **names;
315 316
    virSecurityManagerPtr mgr = NULL;
    virSecurityManagerPtr stack = NULL;
317
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
318

319 320 321
    if (cfg->securityDriverNames &&
        cfg->securityDriverNames[0]) {
        names = cfg->securityDriverNames;
322
        while (names && *names) {
323 324
            if (!(mgr = virSecurityManagerNew(*names,
                                              QEMU_DRIVER_NAME,
325 326 327
                                              cfg->allowDiskFormatProbing,
                                              cfg->securityDefaultConfined,
                                              cfg->securityRequireConfined)))
328
                goto error;
329 330 331 332 333 334 335 336
            if (!stack) {
                if (!(stack = virSecurityManagerNewStack(mgr)))
                    goto error;
            } else {
                if (virSecurityManagerStackAddNested(stack, mgr) < 0)
                    goto error;
            }
            mgr = NULL;
337 338
            names++;
        }
339 340 341
    } else {
        if (!(mgr = virSecurityManagerNew(NULL,
                                          QEMU_DRIVER_NAME,
342 343 344
                                          cfg->allowDiskFormatProbing,
                                          cfg->securityDefaultConfined,
                                          cfg->securityRequireConfined)))
345
            goto error;
346
        if (!(stack = virSecurityManagerNewStack(mgr)))
347
            goto error;
348 349
        mgr = NULL;
    }
350

351
    if (cfg->privileged) {
352
        if (!(mgr = virSecurityManagerNewDAC(QEMU_DRIVER_NAME,
353 354 355 356 357 358
                                             cfg->user,
                                             cfg->group,
                                             cfg->allowDiskFormatProbing,
                                             cfg->securityDefaultConfined,
                                             cfg->securityRequireConfined,
                                             cfg->dynamicOwnership)))
359 360 361 362 363 364 365 366 367
            goto error;
        if (!stack) {
            if (!(stack = virSecurityManagerNewStack(mgr)))
                goto error;
        } else {
            if (virSecurityManagerStackAddNested(stack, mgr) < 0)
                goto error;
        }
        mgr = NULL;
368
    }
D
Daniel Veillard 已提交
369

370
    driver->securityManager = stack;
371
    virObjectUnref(cfg);
372
    return 0;
373

374
error:
375
    VIR_ERROR(_("Failed to initialize security drivers"));
376 377
    virObjectUnref(stack);
    virObjectUnref(mgr);
378
    virObjectUnref(cfg);
379 380
    return -1;
}
381

382

383 384
static int
qemuDomainSnapshotLoad(virDomainObjPtr vm,
385
                       void *data)
386
{
387 388 389 390 391 392 393
    char *baseDir = (char *)data;
    char *snapDir = NULL;
    DIR *dir = NULL;
    struct dirent *entry;
    char *xmlStr;
    char *fullpath;
    virDomainSnapshotDefPtr def = NULL;
394
    virDomainSnapshotObjPtr snap = NULL;
395
    virDomainSnapshotObjPtr current = NULL;
396
    char ebuf[1024];
397
    unsigned int flags = (VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE |
398
                          VIR_DOMAIN_SNAPSHOT_PARSE_DISKS |
399
                          VIR_DOMAIN_SNAPSHOT_PARSE_INTERNAL);
400
    int ret = -1;
401
    virCapsPtr caps = NULL;
402

403
    virObjectLock(vm);
404 405 406
    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);
407
        goto cleanup;
408 409
    }

410 411 412
    if (!(caps = virQEMUDriverGetCapabilities(qemu_driver, false)))
        goto cleanup;

413 414
    VIR_INFO("Scanning for snapshots for domain %s in %s", vm->def->name,
             snapDir);
415

416 417 418 419 420
    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)));
421
        goto cleanup;
422 423
    }

424 425 426
    while ((entry = readdir(dir))) {
        if (entry->d_name[0] == '.')
            continue;
427

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

432
        if (virAsprintf(&fullpath, "%s/%s", snapDir, entry->d_name) < 0) {
433
            VIR_ERROR(_("Failed to allocate memory for path"));
434 435
            continue;
        }
436

437
        if (virFileReadAll(fullpath, 1024*1024*1, &xmlStr) < 0) {
438 439 440 441 442 443
            /* 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;
        }
444

445
        def = virDomainSnapshotDefParseString(xmlStr, caps,
446
                                              qemu_driver->xmlopt,
447 448
                                              QEMU_EXPECTED_VIRT_TYPES,
                                              flags);
449 450
        if (def == NULL) {
            /* Nothing we can do here, skip this one */
451 452
            VIR_ERROR(_("Failed to parse snapshot XML from file '%s'"),
                      fullpath);
453 454 455 456
            VIR_FREE(fullpath);
            VIR_FREE(xmlStr);
            continue;
        }
457

458
        snap = virDomainSnapshotAssignDef(vm->snapshots, def);
459 460
        if (snap == NULL) {
            virDomainSnapshotDefFree(def);
461 462 463 464
        } else if (snap->def->current) {
            current = snap;
            if (!vm->current_snapshot)
                vm->current_snapshot = snap;
465
        }
466

467 468
        VIR_FREE(fullpath);
        VIR_FREE(xmlStr);
469 470
    }

471 472 473 474 475 476
    if (vm->current_snapshot != current) {
        VIR_ERROR(_("Too many snapshots claiming to be current for domain %s"),
                  vm->def->name);
        vm->current_snapshot = NULL;
    }

477
    if (virDomainSnapshotUpdateRelations(vm->snapshots) < 0)
478 479 480
        VIR_ERROR(_("Snapshots have inconsistent relations for domain %s"),
                  vm->def->name);

481 482 483 484 485 486 487 488
    /* 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.
     */
489

490
    virResetLastError();
491

492
    ret = 0;
493 494 495 496
cleanup:
    if (dir)
        closedir(dir);
    VIR_FREE(snapDir);
497
    virObjectUnref(caps);
498
    virObjectUnlock(vm);
499
    return ret;
500 501
}

502

503 504
static int
qemuDomainNetsRestart(virDomainObjPtr vm,
505
                      void *data ATTRIBUTE_UNUSED)
506
{
507 508 509
    int i;
    virDomainDefPtr def = vm->def;

510
    virObjectLock(vm);
511 512 513 514 515 516 517 518

    for (i = 0; i < def->nnets; i++) {
        virDomainNetDefPtr net = def->nets[i];
        if (virDomainNetGetActualType(net) == VIR_DOMAIN_NET_TYPE_DIRECT &&
            virDomainNetGetActualDirectMode(net) == VIR_NETDEV_MACVLAN_MODE_VEPA) {
            VIR_DEBUG("VEPA mode device %s active in domain %s. Reassociating.",
                      net->ifname, def->name);
            ignore_value(virNetDevMacVLanRestartWithVPortProfile(net->ifname,
519
                                                                 &net->mac,
520 521 522 523 524 525 526
                                                                 virDomainNetGetActualDirectDev(net),
                                                                 def->uuid,
                                                                 virDomainNetGetActualVirtPortProfile(net),
                                                                 VIR_NETDEV_VPORT_PROFILE_OP_CREATE));
        }
    }

527
    virObjectUnlock(vm);
528
    return 0;
529 530
}

531

532 533
static int
qemuDomainFindMaxID(virDomainObjPtr vm,
534 535 536 537 538 539
                    void *data)
{
    int *driver_maxid = data;

    if (vm->def->id >= *driver_maxid)
        *driver_maxid = vm->def->id + 1;
540 541

    return 0;
542 543 544
}


545
/**
546
 * qemuStateInitialize:
547 548 549
 *
 * Initialization function for the QEmu daemon
 */
550
static int
551 552 553
qemuStateInitialize(bool privileged,
                    virStateInhibitCallback callback,
                    void *opaque)
554
{
555 556
    char *driverConf = NULL;
    virConnectPtr conn = NULL;
557
    char ebuf[1024];
558 559
    char *membase = NULL;
    char *mempath = NULL;
560
    virQEMUDriverConfigPtr cfg;
561 562
    uid_t run_uid = -1;
    gid_t run_gid = -1;
563

564 565
    if (VIR_ALLOC(qemu_driver) < 0)
        return -1;
566

567
    if (virMutexInit(&qemu_driver->lock) < 0) {
568
        VIR_ERROR(_("cannot initialize mutex"));
569 570
        VIR_FREE(qemu_driver);
        return -1;
571
    }
572

573 574
    qemu_driver->inhibitCallback = callback;
    qemu_driver->inhibitOpaque = opaque;
575

576 577
    /* Don't have a dom0 so start from 1 */
    qemu_driver->nextvmid = 1;
578

579 580
    if (!(qemu_driver->domains = virDomainObjListNew()))
        goto error;
581

582
    /* Init domain events */
583
    qemu_driver->domainEventState = virDomainEventStateNew();
584
    if (!qemu_driver->domainEventState)
585
        goto error;
586

587 588 589
    /* read the host sysinfo */
    if (privileged)
        qemu_driver->hostsysinfo = virSysinfoRead();
590

591 592
    if (!(qemu_driver->config = cfg = virQEMUDriverConfigNew(privileged)))
        goto error;
593

594 595
    if (virAsprintf(&driverConf, "%s/qemu.conf", cfg->configBaseDir) < 0)
        goto out_of_memory;
596

597 598 599
    if (virQEMUDriverConfigLoadFile(cfg, driverConf) < 0)
        goto error;
    VIR_FREE(driverConf);
H
Hu Tao 已提交
600

601
    if (virFileMakePath(cfg->stateDir) < 0) {
602
        VIR_ERROR(_("Failed to create state dir '%s': %s"),
603
                  cfg->stateDir, virStrerror(errno, ebuf, sizeof(ebuf)));
604
        goto error;
H
Hu Tao 已提交
605
    }
606
    if (virFileMakePath(cfg->libDir) < 0) {
607
        VIR_ERROR(_("Failed to create lib dir '%s': %s"),
608
                  cfg->libDir, virStrerror(errno, ebuf, sizeof(ebuf)));
609 610
        goto error;
    }
611
    if (virFileMakePath(cfg->cacheDir) < 0) {
612
        VIR_ERROR(_("Failed to create cache dir '%s': %s"),
613
                  cfg->cacheDir, virStrerror(errno, ebuf, sizeof(ebuf)));
614 615
        goto error;
    }
616
    if (virFileMakePath(cfg->saveDir) < 0) {
617
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
618
                  cfg->saveDir, virStrerror(errno, ebuf, sizeof(ebuf)));
619 620
        goto error;
    }
621
    if (virFileMakePath(cfg->snapshotDir) < 0) {
622
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
623
                  cfg->snapshotDir, virStrerror(errno, ebuf, sizeof(ebuf)));
624 625
        goto error;
    }
626
    if (virFileMakePath(cfg->autoDumpPath) < 0) {
627
        VIR_ERROR(_("Failed to create dump dir '%s': %s"),
628
                  cfg->autoDumpPath, virStrerror(errno, ebuf, sizeof(ebuf)));
629
        goto error;
630 631
    }

632 633 634
    qemu_driver->qemuImgBinary = virFindFileInPath("kvm-img");
    if (!qemu_driver->qemuImgBinary)
        qemu_driver->qemuImgBinary = virFindFileInPath("qemu-img");
635 636 637 638 639 640 641

    if (!(qemu_driver->lockManager =
          virLockManagerPluginNew(cfg->lockManagerName ?
                                  cfg->lockManagerName : "nop",
                                  "qemu",
                                  cfg->configBaseDir,
                                  0)))
642
        goto error;
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658

   if (cfg->macFilter) {
        if (!(qemu_driver->ebtables = ebtablesContextNew("qemu"))) {
            virReportSystemError(errno,
                                 _("failed to enable mac filter in '%s'"),
                                 __FILE__);
            goto error;
        }

        if ((errno = networkDisableAllFrames(qemu_driver))) {
            virReportSystemError(errno,
                                 _("failed to add rule to drop all frames in '%s'"),
                                 __FILE__);
            goto error;
        }
   }
659

660 661 662
    /* Allocate bitmap for remote display port reservations. We cannot
     * do this before the config is loaded properly, since the port
     * numbers are configurable now */
663
    if ((qemu_driver->remotePorts =
664 665
         virPortAllocatorNew(cfg->remotePortMin,
                             cfg->remotePortMax)) == NULL)
666 667
        goto error;

668 669 670 671 672
    if ((qemu_driver->webSocketPorts =
         virPortAllocatorNew(cfg->webSocketPortMin,
                             cfg->webSocketPortMax)) == NULL)
        goto error;

673 674
    if (qemuSecurityInit(qemu_driver) < 0)
        goto error;
675

676
    if ((qemu_driver->activePciHostdevs = virPCIDeviceListNew()) == NULL)
677
        goto error;
678

679
    if ((qemu_driver->activeUsbHostdevs = virUSBDeviceListNew()) == NULL)
680 681
        goto error;

682
    if ((qemu_driver->inactivePciHostdevs = virPCIDeviceListNew()) == NULL)
683 684
        goto error;

685 686 687
    if ((qemu_driver->activeScsiHostdevs = virSCSIDeviceListNew()) == NULL)
        goto error;

688
    if (!(qemu_driver->sharedDevices = virHashCreate(30, qemuSharedDeviceEntryFree)))
689 690
        goto error;

691
    if (privileged) {
692
        if (chown(cfg->libDir, cfg->user, cfg->group) < 0) {
693 694
            virReportSystemError(errno,
                                 _("unable to set ownership of '%s' to user %d:%d"),
E
Eric Blake 已提交
695 696
                                 cfg->libDir, (int) cfg->user,
                                 (int) cfg->group);
697
            goto error;
698
        }
699
        if (chown(cfg->cacheDir, cfg->user, cfg->group) < 0) {
700
            virReportSystemError(errno,
701
                                 _("unable to set ownership of '%s' to %d:%d"),
E
Eric Blake 已提交
702 703
                                 cfg->cacheDir, (int) cfg->user,
                                 (int) cfg->group);
704
            goto error;
705
        }
706
        if (chown(cfg->saveDir, cfg->user, cfg->group) < 0) {
707 708
            virReportSystemError(errno,
                                 _("unable to set ownership of '%s' to %d:%d"),
E
Eric Blake 已提交
709 710
                                 cfg->saveDir, (int) cfg->user,
                                 (int) cfg->group);
711 712
            goto error;
        }
713
        if (chown(cfg->snapshotDir, cfg->user, cfg->group) < 0) {
714 715
            virReportSystemError(errno,
                                 _("unable to set ownership of '%s' to %d:%d"),
E
Eric Blake 已提交
716 717
                                 cfg->snapshotDir, (int) cfg->user,
                                 (int) cfg->group);
718
            goto error;
719
        }
720 721
        run_uid = cfg->user;
        run_gid = cfg->group;
722
    }
723

724
    qemu_driver->qemuCapsCache = virQEMUCapsCacheNew(cfg->libDir,
725 726
                                                     run_uid,
                                                     run_gid);
727
    if (!qemu_driver->qemuCapsCache)
728 729
        goto error;

730
    if ((qemu_driver->caps = virQEMUDriverCreateCapabilities(qemu_driver)) == NULL)
731 732
        goto error;

733
    if (!(qemu_driver->xmlopt = virQEMUDriverCreateXMLConf(qemu_driver)))
734 735
        goto error;

736 737 738 739 740 741
    /* 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
742
     */
743 744
    if (cfg->hugetlbfsMount &&
        cfg->hugetlbfsMount[0] == '/') {
745
        if (virAsprintf(&membase, "%s/libvirt",
746
                        cfg->hugetlbfsMount) < 0 ||
747
            virAsprintf(&mempath, "%s/qemu", membase) < 0)
748
            goto out_of_memory;
749

750 751
        if (virFileMakePath(mempath) < 0) {
            virReportSystemError(errno,
752 753
                                 _("unable to create hugepage path %s"), mempath);
            goto error;
754
        }
755
        if (cfg->privileged) {
756 757
            if (virFileUpdatePerm(membase, 0, S_IXGRP | S_IXOTH) < 0)
                goto error;
758
            if (chown(mempath, cfg->user, cfg->group) < 0) {
759 760
                virReportSystemError(errno,
                                     _("unable to set ownership on %s to %d:%d"),
E
Eric Blake 已提交
761 762
                                     mempath, (int) cfg->user,
                                     (int) cfg->group);
763 764
                goto error;
            }
G
Guido Günther 已提交
765
        }
S
Stefan Berger 已提交
766
        VIR_FREE(membase);
E
Eric Blake 已提交
767

768
        cfg->hugepagePath = mempath;
769
    }
770

771
    if (!(qemu_driver->closeCallbacks = virQEMUCloseCallbacksNew()))
772 773
        goto error;

774
    /* Get all the running persistent or transient configs first */
775
    if (virDomainObjListLoadAllConfigs(qemu_driver->domains,
776 777
                                       cfg->stateDir,
                                       NULL, 1,
778
                                       qemu_driver->caps,
779
                                       qemu_driver->xmlopt,
780
                                       QEMU_EXPECTED_VIRT_TYPES,
781
                                       NULL, NULL) < 0)
782
        goto error;
783

784 785 786
    /* find the maximum ID from active and transient configs to initialize
     * the driver with. This is to avoid race between autostart and reconnect
     * threads */
787 788 789
    virDomainObjListForEach(qemu_driver->domains,
                            qemuDomainFindMaxID,
                            &qemu_driver->nextvmid);
790

791 792 793
    virDomainObjListForEach(qemu_driver->domains,
                            qemuDomainNetsRestart,
                            NULL);
794

795
    conn = virConnectOpen(cfg->uri);
796

797
    qemuProcessReconnectAll(conn, qemu_driver);
798

799
    /* Then inactive persistent configs */
800
    if (virDomainObjListLoadAllConfigs(qemu_driver->domains,
801 802
                                       cfg->configDir,
                                       cfg->autostartDir, 0,
803
                                       qemu_driver->caps,
804
                                       qemu_driver->xmlopt,
805
                                       QEMU_EXPECTED_VIRT_TYPES,
806
                                       NULL, NULL) < 0)
807
        goto error;
808

809

810 811 812
    virDomainObjListForEach(qemu_driver->domains,
                            qemuDomainSnapshotLoad,
                            cfg->snapshotDir);
813

814 815 816
    virDomainObjListForEach(qemu_driver->domains,
                            qemuDomainManagedSaveLoad,
                            qemu_driver);
817

818
    qemu_driver->workerPool = virThreadPoolNew(0, 1, 0, processWatchdogEvent, qemu_driver);
819 820
    if (!qemu_driver->workerPool)
        goto error;
821

822 823
    qemuAutostartDomains(qemu_driver);

824 825
    if (conn)
        virConnectClose(conn);
826

827
    virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);
828
    return 0;
829

830 831 832 833 834 835
out_of_memory:
    virReportOOMError();
error:
    if (conn)
        virConnectClose(conn);
    VIR_FREE(driverConf);
836 837
    VIR_FREE(membase);
    VIR_FREE(mempath);
838
    qemuStateCleanup();
839
    return -1;
840 841
}

842
static void qemuNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
843
{
844
    virQEMUDriverPtr driver = opaque;
845

846 847 848 849 850 851 852
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
E
Eric Blake 已提交
853
    }
854
}
E
Eric Blake 已提交
855

856
/**
857
 * qemuStateReload:
858 859 860 861 862
 *
 * Function to restart the QEmu daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
863
qemuStateReload(void) {
864 865
    virQEMUDriverConfigPtr cfg = NULL;
    virCapsPtr caps = NULL;
866

867 868
    if (!qemu_driver)
        return 0;
869

870 871 872
    if (!(caps = virQEMUDriverGetCapabilities(qemu_driver, false)))
        goto cleanup;

873
    cfg = virQEMUDriverGetConfig(qemu_driver);
874 875
    virDomainObjListLoadAllConfigs(qemu_driver->domains,
                                   cfg->configDir,
876 877 878
                                   cfg->autostartDir, 0,
                                   caps, qemu_driver->xmlopt,
                                   QEMU_EXPECTED_VIRT_TYPES,
879
                                   qemuNotifyLoadDomain, qemu_driver);
880
cleanup:
881
    virObjectUnref(cfg);
882
    virObjectUnref(caps);
883 884
    return 0;
}
S
Stefan Berger 已提交
885

886 887

/*
888
 * qemuStateStop:
889 890 891 892 893
 *
 * Save any VMs in preparation for shutdown
 *
 */
static int
894
qemuStateStop(void) {
895 896
    int ret = -1;
    virConnectPtr conn;
897
    int numDomains = 0;
898 899 900 901
    size_t i;
    int state;
    virDomainPtr *domains = NULL;
    unsigned int *flags = NULL;
902
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(qemu_driver);
903

904 905
    if (!(conn = virConnectOpen(cfg->uri)))
        goto cleanup;
906 907 908 909 910 911 912 913 914 915 916 917 918 919

    if ((numDomains = virConnectListAllDomains(conn,
                                               &domains,
                                               VIR_CONNECT_LIST_DOMAINS_ACTIVE)) < 0)
        goto cleanup;

    if (VIR_ALLOC_N(flags, numDomains) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    /* First we pause all VMs to make them stop dirtying
       pages, etc. We remember if any VMs were paused so
       we can restore that on resume. */
920
    for (i = 0; i < numDomains; i++) {
921 922 923 924 925 926 927 928 929 930 931
        flags[i] = VIR_DOMAIN_SAVE_RUNNING;
        if (virDomainGetState(domains[i], &state, NULL, 0) == 0) {
            if (state == VIR_DOMAIN_PAUSED) {
                flags[i] = VIR_DOMAIN_SAVE_PAUSED;
            }
        }
        virDomainSuspend(domains[i]);
    }

    ret = 0;
    /* Then we save the VMs to disk */
932
    for (i = 0; i < numDomains; i++)
933 934 935 936
        if (virDomainManagedSave(domains[i], flags[i]) < 0)
            ret = -1;

 cleanup:
937
    for (i = 0; i < numDomains; i++)
938 939 940
        virDomainFree(domains[i]);
    VIR_FREE(domains);
    VIR_FREE(flags);
941 942 943
    if (conn)
        virConnectClose(conn);
    virObjectUnref(cfg);
944 945 946 947

    return ret;
}

948
/**
949
 * qemuStateCleanup:
950 951 952 953
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
954
qemuStateCleanup(void) {
955 956
    if (!qemu_driver)
        return -1;
957

958
    virNWFilterUnRegisterCallbackDriver(&qemuCallbackDriver);
959
    virObjectUnref(qemu_driver->config);
960 961 962
    virObjectUnref(qemu_driver->activePciHostdevs);
    virObjectUnref(qemu_driver->inactivePciHostdevs);
    virObjectUnref(qemu_driver->activeUsbHostdevs);
963
    virHashFree(qemu_driver->sharedDevices);
964
    virObjectUnref(qemu_driver->caps);
965
    virQEMUCapsCacheFree(qemu_driver->qemuCapsCache);
966

967
    virObjectUnref(qemu_driver->domains);
968
    virObjectUnref(qemu_driver->remotePorts);
969

970
    virObjectUnref(qemu_driver->xmlopt);
971

972
    virSysinfoDefFree(qemu_driver->hostsysinfo);
973

974
    virObjectUnref(qemu_driver->closeCallbacks);
975

E
Eric Blake 已提交
976
    VIR_FREE(qemu_driver->qemuImgBinary);
977

978
    virObjectUnref(qemu_driver->securityManager);
979

980
    ebtablesContextFree(qemu_driver->ebtables);
981

982
    /* Free domain callback list */
983
    virDomainEventStateFree(qemu_driver->domainEventState);
D
Daniel P. Berrange 已提交
984

985 986
    virLockManagerPluginUnref(qemu_driver->lockManager);

987 988 989
    virMutexDestroy(&qemu_driver->lock);
    virThreadPoolFree(qemu_driver->workerPool);
    VIR_FREE(qemu_driver);
990

991
    return 0;
992 993
}

994

995 996 997
static virDrvOpenStatus qemuConnectOpen(virConnectPtr conn,
                                        virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                        unsigned int flags)
998
{
999 1000
    virQEMUDriverConfigPtr cfg = NULL;
    virDrvOpenStatus ret = VIR_DRV_OPEN_ERROR;
E
Eric Blake 已提交
1001 1002
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

1003
    if (conn->uri == NULL) {
1004 1005 1006 1007 1008 1009
        if (qemu_driver == NULL) {
            ret = VIR_DRV_OPEN_DECLINED;
            goto cleanup;
        }

        cfg = virQEMUDriverGetConfig(qemu_driver);
1010

1011 1012
        if (!(conn->uri = virURIParse(cfg->uri)))
            goto cleanup;
1013 1014 1015
    } else {
        /* If URI isn't 'qemu' its definitely not for us */
        if (conn->uri->scheme == NULL ||
1016 1017 1018 1019
            STRNEQ(conn->uri->scheme, "qemu")) {
            ret = VIR_DRV_OPEN_DECLINED;
            goto cleanup;
        }
1020 1021

        /* Allow remote driver to deal with URIs with hostname server */
1022 1023 1024 1025
        if (conn->uri->server != NULL) {
            ret = VIR_DRV_OPEN_DECLINED;
            goto cleanup;
        }
1026

1027
        if (qemu_driver == NULL) {
1028 1029
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("qemu state driver is not active"));
1030
            goto cleanup;
1031 1032
        }

J
Ján Tomko 已提交
1033
        cfg = virQEMUDriverGetConfig(qemu_driver);
1034
        if (conn->uri->path == NULL) {
1035 1036
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("no QEMU URI path given, try %s"),
1037 1038
                           cfg->uri);
            goto cleanup;
1039 1040
        }

1041
        if (cfg->privileged) {
1042 1043
            if (STRNEQ(conn->uri->path, "/system") &&
                STRNEQ(conn->uri->path, "/session")) {
1044 1045 1046
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected QEMU URI path '%s', try qemu:///system"),
                               conn->uri->path);
1047
                goto cleanup;
1048 1049
            }
        } else {
1050
            if (STRNEQ(conn->uri->path, "/session")) {
1051 1052 1053
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected QEMU URI path '%s', try qemu:///session"),
                               conn->uri->path);
1054
                goto cleanup;
1055 1056
            }
        }
1057
    }
1058 1059 1060 1061

    if (virConnectOpenEnsureACL(conn) < 0)
        goto cleanup;

1062 1063
    conn->privateData = qemu_driver;

1064 1065 1066 1067
    ret = VIR_DRV_OPEN_SUCCESS;
cleanup:
    virObjectUnref(cfg);
    return ret;
1068 1069
}

1070
static int qemuConnectClose(virConnectPtr conn)
1071
{
1072
    virQEMUDriverPtr driver = conn->privateData;
1073 1074

    /* Get rid of callbacks registered for this conn */
1075
    virQEMUCloseCallbacksRun(driver->closeCallbacks, conn, driver);
1076 1077 1078 1079 1080 1081

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
1082 1083
/* Which features are supported by this driver? */
static int
1084
qemuConnectSupportsFeature(virConnectPtr conn, int feature)
D
Daniel Veillard 已提交
1085
{
1086 1087 1088
    if (virConnectSupportsFeatureEnsureACL(conn) < 0)
        return -1;

D
Daniel Veillard 已提交
1089
    switch (feature) {
1090
    case VIR_DRV_FEATURE_MIGRATION_V2:
1091
    case VIR_DRV_FEATURE_MIGRATION_V3:
1092
    case VIR_DRV_FEATURE_MIGRATION_P2P:
1093
    case VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION:
1094
    case VIR_DRV_FEATURE_FD_PASSING:
1095
    case VIR_DRV_FEATURE_TYPED_PARAM_STRING:
1096
    case VIR_DRV_FEATURE_XML_MIGRATABLE:
L
liguang 已提交
1097
    case VIR_DRV_FEATURE_MIGRATION_OFFLINE:
1098
    case VIR_DRV_FEATURE_MIGRATION_PARAMS:
1099 1100 1101
        return 1;
    default:
        return 0;
D
Daniel Veillard 已提交
1102 1103 1104
    }
}

1105
static const char *qemuConnectGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
1106 1107 1108
    if (virConnectGetTypeEnsureACL(conn) < 0)
        return NULL;

1109
    return "QEMU";
1110 1111
}

1112

1113
static int qemuConnectIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
1114 1115 1116 1117 1118
{
    /* Trivially secure, since always inside the daemon */
    return 1;
}

1119
static int qemuConnectIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
1120 1121 1122 1123 1124
{
    /* Not encrypted, but remote driver takes care of that */
    return 0;
}

1125
static int qemuConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
1126 1127 1128 1129
{
    return 1;
}

1130

1131 1132 1133 1134
static int
kvmGetMaxVCPUs(void) {
    int fd;
    int ret;
1135

1136
    if ((fd = open(KVM_DEVICE, O_RDONLY)) < 0) {
1137
        virReportSystemError(errno, _("Unable to open %s"), KVM_DEVICE);
1138
        return -1;
1139 1140
    }

1141
#ifdef KVM_CAP_MAX_VCPUS
1142 1143 1144
    /* at first try KVM_CAP_MAX_VCPUS to determine the maximum count */
    if ((ret = ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_MAX_VCPUS)) > 0)
        goto cleanup;
1145
#endif /* KVM_CAP_MAX_VCPUS */
1146 1147 1148 1149 1150 1151 1152 1153 1154

    /* as a fallback get KVM_CAP_NR_VCPUS (the recommended maximum number of
     * vcpus). Note that on most machines this is set to 160. */
    if ((ret = ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_NR_VCPUS)) > 0)
        goto cleanup;

    /* if KVM_CAP_NR_VCPUS doesn't exist either, kernel documentation states
     * that 4 should be used as the maximum number of cpus */
    ret = 4;
1155

1156
cleanup:
1157
    VIR_FORCE_CLOSE(fd);
1158
    return ret;
1159 1160 1161
}


E
Eric Blake 已提交
1162
static char *
1163
qemuConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
E
Eric Blake 已提交
1164
{
1165
    virQEMUDriverPtr driver = conn->privateData;
1166
    virBuffer buf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
1167 1168 1169

    virCheckFlags(0, NULL);

1170 1171 1172
    if (virConnectGetSysinfoEnsureACL(conn) < 0)
        return NULL;

E
Eric Blake 已提交
1173
    if (!driver->hostsysinfo) {
1174 1175
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Host SMBIOS information is not available"));
E
Eric Blake 已提交
1176 1177 1178
        return NULL;
    }

1179 1180 1181 1182 1183 1184 1185
    if (virSysinfoFormat(&buf, driver->hostsysinfo) < 0)
        return NULL;
    if (virBufferError(&buf)) {
        virReportOOMError();
        return NULL;
    }
    return virBufferContentAndReset(&buf);
E
Eric Blake 已提交
1186 1187
}

1188
static int qemuConnectGetMaxVcpus(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
1189 1190 1191
    if (virConnectGetMaxVcpusEnsureACL(conn) < 0)
        return -1;

1192 1193 1194
    if (!type)
        return 16;

1195
    if (STRCASEEQ(type, "qemu"))
1196 1197
        return 16;

1198
    if (STRCASEEQ(type, "kvm"))
1199
        return kvmGetMaxVCPUs();
1200

1201
    if (STRCASEEQ(type, "kqemu"))
1202
        return 1;
1203

1204 1205
    virReportError(VIR_ERR_INVALID_ARG,
                   _("unknown type '%s'"), type);
1206 1207 1208
    return -1;
}

1209

1210
static char *qemuConnectGetCapabilities(virConnectPtr conn) {
1211
    virQEMUDriverPtr driver = conn->privateData;
1212
    virCapsPtr caps = NULL;
1213
    char *xml = NULL;
1214

1215 1216 1217
    if (virConnectGetCapabilitiesEnsureACL(conn) < 0)
        return NULL;

1218
    if (!(caps = virQEMUDriverGetCapabilities(driver, true)))
1219
        goto cleanup;
1220

1221
    if ((xml = virCapabilitiesFormatXML(caps)) == NULL)
1222
        virReportOOMError();
1223
    virObjectUnref(caps);
1224 1225

cleanup:
1226

1227
    return xml;
1228 1229 1230
}


1231
static int
1232 1233
qemuGetProcessInfo(unsigned long long *cpuTime, int *lastCpu, long *vm_rss,
                   pid_t pid, int tid)
1234 1235
{
    char *proc;
D
Daniel P. Berrange 已提交
1236
    FILE *pidinfo;
1237
    unsigned long long usertime, systime;
1238
    long rss;
1239 1240
    int cpu;
    int ret;
D
Daniel P. Berrange 已提交
1241

1242 1243
    /* In general, we cannot assume pid_t fits in int; but /proc parsing
     * is specific to Linux where int works fine.  */
1244
    if (tid)
1245
        ret = virAsprintf(&proc, "/proc/%d/task/%d/stat", (int) pid, tid);
1246
    else
1247
        ret = virAsprintf(&proc, "/proc/%d/stat", (int) pid);
1248
    if (ret < 0)
D
Daniel P. Berrange 已提交
1249 1250 1251 1252
        return -1;

    if (!(pidinfo = fopen(proc, "r"))) {
        /* VM probably shut down, so fake 0 */
1253 1254 1255 1256
        if (cpuTime)
            *cpuTime = 0;
        if (lastCpu)
            *lastCpu = 0;
1257 1258
        if (vm_rss)
            *vm_rss = 0;
1259
        VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1260 1261
        return 0;
    }
1262
    VIR_FREE(proc);
D
Daniel P. Berrange 已提交
1263

1264 1265 1266 1267 1268 1269
    /* 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 */
1270
               "%*d %*d %*d %*d %*d %*d %*u %*u %ld %*u %*u %*u"
1271 1272
               /* startstack -> processor */
               "%*u %*u %*u %*u %*u %*u %*u %*u %*u %*u %*d %d",
1273
               &usertime, &systime, &rss, &cpu) != 4) {
1274
        VIR_FORCE_FCLOSE(pidinfo);
1275
        VIR_WARN("cannot parse process status data");
1276
        errno = -EINVAL;
D
Daniel P. Berrange 已提交
1277 1278 1279 1280 1281 1282 1283 1284
        return -1;
    }

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
1285 1286 1287 1288 1289
    if (cpuTime)
        *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
    if (lastCpu)
        *lastCpu = cpu;

1290 1291 1292 1293 1294 1295
    /* We got pages
     * We want kiloBytes
     * _SC_PAGESIZE is page size in Bytes
     * So calculate, but first lower the pagesize so we don't get overflow */
    if (vm_rss)
        *vm_rss = rss * (sysconf(_SC_PAGESIZE) >> 10);
D
Daniel P. Berrange 已提交
1296

1297 1298

    VIR_DEBUG("Got status for %d/%d user=%llu sys=%llu cpu=%d rss=%ld",
1299
              (int) pid, tid, usertime, systime, cpu, rss);
D
Daniel P. Berrange 已提交
1300

1301
    VIR_FORCE_FCLOSE(pidinfo);
D
Daniel P. Berrange 已提交
1302 1303 1304 1305 1306

    return 0;
}


1307 1308
static virDomainPtr qemuDomainLookupByID(virConnectPtr conn,
                                         int id) {
1309
    virQEMUDriverPtr driver = conn->privateData;
1310 1311 1312
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1313
    vm  = virDomainObjListFindByID(driver->domains, id);
1314 1315

    if (!vm) {
1316 1317
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), id);
1318
        goto cleanup;
1319 1320
    }

1321 1322 1323
    if (virDomainLookupByIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

1324
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1325
    if (dom) dom->id = vm->def->id;
1326 1327

cleanup:
1328
    if (vm)
1329
        virObjectUnlock(vm);
1330 1331
    return dom;
}
1332

1333 1334
static virDomainPtr qemuDomainLookupByUUID(virConnectPtr conn,
                                           const unsigned char *uuid) {
1335
    virQEMUDriverPtr driver = conn->privateData;
1336 1337
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1338

1339
    vm = virDomainObjListFindByUUID(driver->domains, uuid);
1340

1341
    if (!vm) {
1342 1343
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
1344 1345
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
1346
        goto cleanup;
1347 1348
    }

1349 1350 1351
    if (virDomainLookupByUUIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

1352
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1353
    if (dom) dom->id = vm->def->id;
1354 1355

cleanup:
1356
    if (vm)
1357
        virObjectUnlock(vm);
1358 1359
    return dom;
}
1360

1361 1362
static virDomainPtr qemuDomainLookupByName(virConnectPtr conn,
                                           const char *name) {
1363
    virQEMUDriverPtr driver = conn->privateData;
1364 1365
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1366

1367
    vm = virDomainObjListFindByName(driver->domains, name);
1368

1369
    if (!vm) {
1370 1371
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching name '%s'"), name);
1372
        goto cleanup;
1373 1374
    }

1375 1376 1377
    if (virDomainLookupByNameEnsureACL(conn, vm->def) < 0)
        goto cleanup;

1378
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1379
    if (dom) dom->id = vm->def->id;
1380 1381

cleanup:
1382
    if (vm)
1383
        virObjectUnlock(vm);
1384 1385 1386
    return dom;
}

1387 1388 1389 1390 1391 1392

static int qemuDomainIsActive(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

1393
    if (!(obj = qemuDomObjFromDomain(dom)))
1394
        goto cleanup;
1395

1396 1397 1398
    if (virDomainIsActiveEnsureACL(dom->conn, obj->def) < 0)
        goto cleanup;

1399 1400 1401 1402
    ret = virDomainObjIsActive(obj);

cleanup:
    if (obj)
1403
        virObjectUnlock(obj);
1404 1405 1406 1407 1408 1409 1410 1411
    return ret;
}

static int qemuDomainIsPersistent(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

1412
    if (!(obj = qemuDomObjFromDomain(dom)))
1413
        goto cleanup;
1414

1415 1416 1417
    if (virDomainIsPersistentEnsureACL(dom->conn, obj->def) < 0)
        goto cleanup;

1418 1419 1420 1421
    ret = obj->persistent;

cleanup:
    if (obj)
1422
        virObjectUnlock(obj);
1423 1424 1425
    return ret;
}

1426 1427 1428 1429 1430
static int qemuDomainIsUpdated(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

1431
    if (!(obj = qemuDomObjFromDomain(dom)))
1432
        goto cleanup;
1433

1434 1435 1436
    if (virDomainIsUpdatedEnsureACL(dom->conn, obj->def) < 0)
        goto cleanup;

1437 1438 1439 1440
    ret = obj->updated;

cleanup:
    if (obj)
1441
        virObjectUnlock(obj);
1442 1443
    return ret;
}
1444

1445
static int qemuConnectGetVersion(virConnectPtr conn, unsigned long *version) {
1446
    virQEMUDriverPtr driver = conn->privateData;
1447
    int ret = -1;
1448
    unsigned int qemuVersion = 0;
1449
    virCapsPtr caps = NULL;
1450

1451 1452 1453
    if (virConnectGetVersionEnsureACL(conn) < 0)
        return -1;

1454 1455 1456 1457
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

    if (virQEMUCapsGetDefaultVersion(caps,
1458 1459
                                     driver->qemuCapsCache,
                                     &qemuVersion) < 0)
1460
        goto cleanup;
1461

1462
    *version = qemuVersion;
1463 1464 1465
    ret = 0;

cleanup:
1466
    virObjectUnref(caps);
1467
    return ret;
D
Daniel P. Berrange 已提交
1468 1469
}

1470

1471
static char *qemuConnectGetHostname(virConnectPtr conn)
1472
{
1473 1474 1475
    if (virConnectGetHostnameEnsureACL(conn) < 0)
        return NULL;

1476 1477 1478 1479
    return virGetHostname();
}


1480
static int qemuConnectListDomains(virConnectPtr conn, int *ids, int nids) {
1481
    virQEMUDriverPtr driver = conn->privateData;
1482
    int n;
1483

1484 1485 1486
    if (virConnectListDomainsEnsureACL(conn) < 0)
        return -1;

1487
    n = virDomainObjListGetActiveIDs(driver->domains, ids, nids);
1488

1489
    return n;
D
Daniel P. Berrange 已提交
1490
}
1491

1492
static int qemuConnectNumOfDomains(virConnectPtr conn) {
1493
    virQEMUDriverPtr driver = conn->privateData;
1494
    int n;
1495

1496 1497 1498
    if (virConnectNumOfDomainsEnsureACL(conn) < 0)
        return -1;

1499
    n = virDomainObjListNumOfDomains(driver->domains, 1);
1500

1501
    return n;
D
Daniel P. Berrange 已提交
1502
}
1503

1504 1505

static int
1506
qemuCanonicalizeMachine(virDomainDefPtr def, virQEMUCapsPtr qemuCaps)
1507
{
1508
    const char *canon;
1509

1510
    if (!(canon = virQEMUCapsGetCanonicalMachine(qemuCaps, def->os.machine)))
1511 1512 1513
        return 0;

    if (STRNEQ(canon, def->os.machine)) {
1514
        char *tmp;
1515
        if (VIR_STRDUP(tmp, canon) < 0)
1516 1517 1518 1519 1520 1521 1522 1523 1524
            return -1;
        VIR_FREE(def->os.machine);
        def->os.machine = tmp;
    }

    return 0;
}


1525 1526 1527
static virDomainPtr qemuDomainCreateXML(virConnectPtr conn,
                                        const char *xml,
                                        unsigned int flags) {
1528
    virQEMUDriverPtr driver = conn->privateData;
1529
    virDomainDefPtr def = NULL;
1530
    virDomainObjPtr vm = NULL;
1531
    virDomainPtr dom = NULL;
1532
    virDomainEventPtr event = NULL;
1533
    virDomainEventPtr event2 = NULL;
1534
    unsigned int start_flags = VIR_QEMU_PROCESS_START_COLD;
1535
    virQEMUCapsPtr qemuCaps = NULL;
1536
    virCapsPtr caps = NULL;
D
Daniel P. Berrange 已提交
1537

1538 1539
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
                  VIR_DOMAIN_START_AUTODESTROY, NULL);
1540

1541 1542 1543
    if (flags & VIR_DOMAIN_START_PAUSED)
        start_flags |= VIR_QEMU_PROCESS_START_PAUSED;
    if (flags & VIR_DOMAIN_START_AUTODESTROY)
1544
        start_flags |= VIR_QEMU_PROCESS_START_AUTODESTROY;
1545

1546 1547 1548
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

1549
    if (!(def = virDomainDefParseString(xml, caps, driver->xmlopt,
M
Matthias Bolte 已提交
1550
                                        QEMU_EXPECTED_VIRT_TYPES,
1551
                                        VIR_DOMAIN_XML_INACTIVE)))
1552
        goto cleanup;
1553

1554 1555 1556
    if (virDomainCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

1557
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
1558 1559
        goto cleanup;

1560
    if (!(qemuCaps = virQEMUCapsCacheLookup(driver->qemuCapsCache, def->emulator)))
1561 1562
        goto cleanup;

1563
    if (qemuCanonicalizeMachine(def, qemuCaps) < 0)
1564 1565
        goto cleanup;

1566
    if (qemuDomainAssignAddresses(def, qemuCaps, NULL) < 0)
1567 1568
        goto cleanup;

1569
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1570
                                   driver->xmlopt,
1571 1572
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
1573 1574 1575
        goto cleanup;

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

1577
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1578 1579
        goto cleanup; /* XXXX free the 'vm' we created ? */

1580 1581 1582
    if (qemuProcessStart(conn, driver, vm, NULL, -1, NULL, NULL,
                         VIR_NETDEV_VPORT_PROFILE_OP_CREATE,
                         start_flags) < 0) {
1583
        virDomainAuditStart(vm, "booted", false);
1584
        if (qemuDomainObjEndJob(driver, vm) > 0)
1585
            qemuDomainRemoveInactive(driver, vm);
1586
        vm = NULL;
1587
        goto cleanup;
D
Daniel P. Berrange 已提交
1588
    }
1589 1590 1591 1592

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
    if (event && (flags & VIR_DOMAIN_START_PAUSED)) {
        /* There are two classes of event-watching clients - those
         * that only care about on/off (and must see a started event
         * no matter what, but don't care about suspend events), and
         * those that also care about running/paused.  To satisfy both
         * client types, we have to send two events.  */
        event2 = virDomainEventNewFromObj(vm,
                                          VIR_DOMAIN_EVENT_SUSPENDED,
                                          VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
    }
1603
    virDomainAuditStart(vm, "booted", true);
D
Daniel P. Berrange 已提交
1604

1605
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1606
    if (dom) dom->id = vm->def->id;
1607

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

1612 1613
cleanup:
    virDomainDefFree(def);
1614
    if (vm)
1615
        virObjectUnlock(vm);
1616
    if (event) {
1617
        qemuDomainEventQueue(driver, event);
1618 1619 1620
        if (event2)
            qemuDomainEventQueue(driver, event2);
    }
1621
    virObjectUnref(caps);
1622
    virObjectUnref(qemuCaps);
1623
    return dom;
D
Daniel P. Berrange 已提交
1624 1625 1626
}


1627
static int qemuDomainSuspend(virDomainPtr dom) {
1628
    virQEMUDriverPtr driver = dom->conn->privateData;
1629 1630
    virDomainObjPtr vm;
    int ret = -1;
1631
    virDomainEventPtr event = NULL;
1632
    qemuDomainObjPrivatePtr priv;
1633 1634
    virDomainPausedReason reason;
    int eventDetail;
1635
    int state;
1636
    virQEMUDriverConfigPtr cfg = NULL;
1637

1638 1639
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
1640

1641 1642 1643
    if (virDomainSuspendEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
1644
    if (!virDomainObjIsActive(vm)) {
1645 1646
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
1647
        goto cleanup;
D
Daniel P. Berrange 已提交
1648
    }
1649

1650
    cfg = virQEMUDriverGetConfig(driver);
1651 1652
    priv = vm->privateData;

1653
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_SUSPEND) < 0)
1654 1655 1656
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
1657 1658
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
1659 1660
        goto endjob;
    }
1661

1662 1663 1664
    if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_OUT) {
        reason = VIR_DOMAIN_PAUSED_MIGRATION;
        eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED;
1665 1666 1667
    } else if (priv->job.asyncJob == QEMU_ASYNC_JOB_SNAPSHOT) {
        reason = VIR_DOMAIN_PAUSED_SNAPSHOT;
        eventDetail = -1; /* don't create lifecycle events when doing snapshot */
1668 1669 1670 1671 1672
    } else {
        reason = VIR_DOMAIN_PAUSED_USER;
        eventDetail = VIR_DOMAIN_EVENT_SUSPENDED_PAUSED;
    }

1673 1674 1675 1676 1677 1678
    state = virDomainObjGetState(vm, NULL);
    if (state == VIR_DOMAIN_PMSUSPENDED) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is pmsuspended"));
        goto endjob;
    } else if (state != VIR_DOMAIN_PAUSED) {
1679
        if (qemuProcessStopCPUs(driver, vm, reason, QEMU_ASYNC_JOB_NONE) < 0) {
1680
            goto endjob;
1681
        }
1682 1683 1684 1685 1686 1687

        if (eventDetail >= 0) {
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_SUSPENDED,
                                             eventDetail);
        }
D
Daniel P. Berrange 已提交
1688
    }
1689
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
1690 1691
        goto endjob;
    ret = 0;
1692

1693
endjob:
1694
    if (qemuDomainObjEndJob(driver, vm) == 0)
1695
        vm = NULL;
1696

1697
cleanup:
1698
    if (vm)
1699
        virObjectUnlock(vm);
1700

1701
    if (event)
1702
        qemuDomainEventQueue(driver, event);
1703
    virObjectUnref(cfg);
1704
    return ret;
D
Daniel P. Berrange 已提交
1705 1706 1707
}


1708
static int qemuDomainResume(virDomainPtr dom) {
1709
    virQEMUDriverPtr driver = dom->conn->privateData;
1710 1711
    virDomainObjPtr vm;
    int ret = -1;
1712
    virDomainEventPtr event = NULL;
1713
    int state;
1714
    virQEMUDriverConfigPtr cfg = NULL;
1715
    virCapsPtr caps = NULL;
1716

1717 1718
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
1719

1720 1721
    cfg = virQEMUDriverGetConfig(driver);

1722 1723 1724
    if (virDomainResumeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1725
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1726 1727
        goto cleanup;

D
Daniel P. Berrange 已提交
1728
    if (!virDomainObjIsActive(vm)) {
1729 1730
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
1731
        goto endjob;
D
Daniel P. Berrange 已提交
1732
    }
1733 1734 1735 1736 1737 1738 1739

    state = virDomainObjGetState(vm, NULL);
    if (state == VIR_DOMAIN_PMSUSPENDED) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is pmsuspended"));
        goto endjob;
    } else if (state == VIR_DOMAIN_PAUSED) {
J
Jiri Denemark 已提交
1740
        if (qemuProcessStartCPUs(driver, vm, dom->conn,
1741 1742
                                 VIR_DOMAIN_RUNNING_UNPAUSED,
                                 QEMU_ASYNC_JOB_NONE) < 0) {
1743
            if (virGetLastError() == NULL)
1744 1745
                virReportError(VIR_ERR_OPERATION_FAILED,
                               "%s", _("resume operation failed"));
1746
            goto endjob;
1747
        }
1748 1749 1750
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
D
Daniel P. Berrange 已提交
1751
    }
1752 1753
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto endjob;
1754
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
1755
        goto endjob;
1756 1757
    ret = 0;

1758
endjob:
1759
    if (qemuDomainObjEndJob(driver, vm) == 0)
1760
        vm = NULL;
1761

1762
cleanup:
1763
    if (vm)
1764
        virObjectUnlock(vm);
1765
    if (event)
1766
        qemuDomainEventQueue(driver, event);
1767
    virObjectUnref(caps);
1768
    virObjectUnref(cfg);
1769
    return ret;
D
Daniel P. Berrange 已提交
1770 1771
}

1772
static int qemuDomainShutdownFlags(virDomainPtr dom, unsigned int flags) {
1773
    virQEMUDriverPtr driver = dom->conn->privateData;
1774 1775
    virDomainObjPtr vm;
    int ret = -1;
1776
    qemuDomainObjPrivatePtr priv;
1777
    bool useAgent = false, agentRequested, acpiRequested;
1778 1779
    bool isReboot = false;
    int agentFlag = QEMU_AGENT_SHUTDOWN_POWERDOWN;
1780 1781 1782

    virCheckFlags(VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN |
                  VIR_DOMAIN_SHUTDOWN_GUEST_AGENT, -1);
1783

1784
    if (!(vm = qemuDomObjFromDomain(dom)))
1785
        goto cleanup;
1786

1787 1788 1789 1790 1791 1792 1793
    if (vm->def->onPoweroff == VIR_DOMAIN_LIFECYCLE_RESTART ||
        vm->def->onPoweroff == VIR_DOMAIN_LIFECYCLE_RESTART_RENAME) {
        isReboot = true;
        agentFlag = QEMU_AGENT_SHUTDOWN_REBOOT;
        VIR_INFO("Domain on_poweroff setting overridden, attempting reboot");
    }

1794
    priv = vm->privateData;
1795 1796
    agentRequested = flags & VIR_DOMAIN_SHUTDOWN_GUEST_AGENT;
    acpiRequested  = flags & VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN;
1797

1798 1799
    /* Prefer agent unless we were requested to not to. */
    if (agentRequested || (!flags && priv->agent))
1800 1801
        useAgent = true;

1802 1803 1804
    if (virDomainShutdownFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1805 1806
    if (priv->agentError) {
        if (agentRequested && !acpiRequested) {
1807 1808 1809
            virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                           _("QEMU guest agent is not "
                             "available due to an error"));
1810
            goto cleanup;
1811 1812
        } else {
            useAgent = false;
1813
        }
1814 1815 1816 1817
    }

    if (!priv->agent) {
        if (agentRequested && !acpiRequested) {
1818 1819
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                           _("QEMU guest agent is not configured"));
1820
            goto cleanup;
1821 1822
        } else {
            useAgent = false;
1823 1824 1825
        }
    }

1826
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
1827 1828
        goto cleanup;

D
Daniel P. Berrange 已提交
1829
    if (!virDomainObjIsActive(vm)) {
1830 1831
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
1832
        goto endjob;
1833 1834
    }

1835
    if (useAgent) {
1836
        qemuDomainObjEnterAgent(vm);
1837
        ret = qemuAgentShutdown(priv->agent, agentFlag);
1838
        qemuDomainObjExitAgent(vm);
1839 1840 1841 1842 1843 1844 1845
    }

    /* If we are not enforced to use just an agent, try ACPI
     * shutdown as well in case agent did not succeed.
     */
    if (!useAgent ||
        (ret < 0 && (acpiRequested || !flags))) {
1846
        qemuDomainSetFakeReboot(driver, vm, isReboot);
1847

1848 1849 1850 1851
        qemuDomainObjEnterMonitor(driver, vm);
        ret = qemuMonitorSystemPowerdown(priv->mon);
        qemuDomainObjExitMonitor(driver, vm);
    }
1852

1853
endjob:
1854
    if (qemuDomainObjEndJob(driver, vm) == 0)
1855
        vm = NULL;
1856

1857
cleanup:
1858
    if (vm)
1859
        virObjectUnlock(vm);
1860
    return ret;
1861 1862
}

1863 1864
static int qemuDomainShutdown(virDomainPtr dom)
{
1865 1866 1867
    return qemuDomainShutdownFlags(dom, 0);
}

1868

1869 1870 1871
static int
qemuDomainReboot(virDomainPtr dom, unsigned int flags)
{
1872
    virQEMUDriverPtr driver = dom->conn->privateData;
1873 1874 1875
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;
1876
    bool useAgent = false;
1877 1878
    bool isReboot = true;
    int agentFlag = QEMU_AGENT_SHUTDOWN_REBOOT;
1879

1880 1881
    virCheckFlags(VIR_DOMAIN_REBOOT_ACPI_POWER_BTN |
                  VIR_DOMAIN_REBOOT_GUEST_AGENT , -1);
1882

1883 1884 1885 1886 1887 1888 1889 1890
    /* At most one of these two flags should be set.  */
    if ((flags & VIR_DOMAIN_REBOOT_ACPI_POWER_BTN) &&
        (flags & VIR_DOMAIN_REBOOT_GUEST_AGENT)) {
        virReportInvalidArg(flags, "%s",
                            _("flags for acpi power button and guest agent are mutually exclusive"));
        return -1;
    }

1891
    if (!(vm = qemuDomObjFromDomain(dom)))
1892 1893
        goto cleanup;

1894 1895 1896 1897 1898 1899 1900
    if (vm->def->onReboot == VIR_DOMAIN_LIFECYCLE_DESTROY ||
        vm->def->onReboot == VIR_DOMAIN_LIFECYCLE_PRESERVE) {
        agentFlag = QEMU_AGENT_SHUTDOWN_POWERDOWN;
        isReboot = false;
        VIR_INFO("Domain on_reboot setting overridden, shutting down");
    }

1901 1902
    priv = vm->privateData;

1903 1904 1905
    if (virDomainRebootEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1906 1907
    if ((flags & VIR_DOMAIN_REBOOT_GUEST_AGENT) ||
        (!(flags & VIR_DOMAIN_REBOOT_ACPI_POWER_BTN) &&
1908 1909 1910 1911 1912
         priv->agent))
        useAgent = true;

    if (useAgent) {
        if (priv->agentError) {
1913 1914 1915
            virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                           _("QEMU guest agent is not "
                             "available due to an error"));
1916 1917 1918
            goto cleanup;
        }
        if (!priv->agent) {
1919 1920
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                           _("QEMU guest agent is not configured"));
1921 1922 1923
            goto cleanup;
        }
    } else {
1924
#if WITH_YAJL
1925 1926
        if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_MONITOR_JSON)) {
            if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NO_SHUTDOWN)) {
1927 1928
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("Reboot is not supported with this QEMU binary"));
1929 1930 1931 1932
                goto cleanup;
            }
        } else {
#endif
1933 1934
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Reboot is not supported without the JSON monitor"));
1935
            goto cleanup;
1936
#if WITH_YAJL
1937
        }
1938 1939
#endif
    }
1940

1941 1942
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;
1943

1944
    if (!virDomainObjIsActive(vm)) {
1945 1946
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
1947 1948
        goto endjob;
    }
1949

1950
    if (useAgent) {
1951
        qemuDomainObjEnterAgent(vm);
1952
        ret = qemuAgentShutdown(priv->agent, agentFlag);
1953
        qemuDomainObjExitAgent(vm);
1954
    } else {
1955
        qemuDomainObjEnterMonitor(driver, vm);
1956
        ret = qemuMonitorSystemPowerdown(priv->mon);
1957
        qemuDomainObjExitMonitor(driver, vm);
1958

1959
        if (ret == 0)
1960
            qemuDomainSetFakeReboot(driver, vm, isReboot);
1961 1962
    }

1963 1964 1965 1966
endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;

1967 1968
cleanup:
    if (vm)
1969
        virObjectUnlock(vm);
1970 1971 1972 1973
    return ret;
}


1974 1975 1976
static int
qemuDomainReset(virDomainPtr dom, unsigned int flags)
{
1977
    virQEMUDriverPtr driver = dom->conn->privateData;
1978 1979 1980 1981 1982 1983
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, -1);

1984
    if (!(vm = qemuDomObjFromDomain(dom)))
1985 1986
        goto cleanup;

1987 1988 1989
    if (virDomainResetEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1990 1991 1992 1993
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
1994 1995
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
        goto endjob;
    }

    priv = vm->privateData;
    qemuDomainObjEnterMonitor(driver, vm);
    ret = qemuMonitorSystemReset(priv->mon);
    qemuDomainObjExitMonitor(driver, vm);

    priv->fakeReboot = false;

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

cleanup:
    if (vm)
2012
        virObjectUnlock(vm);
2013 2014 2015 2016
    return ret;
}


2017
/* Count how many snapshots in a set are external snapshots or checkpoints.  */
2018 2019 2020 2021 2022 2023 2024 2025
static void
qemuDomainSnapshotCountExternal(void *payload,
                                const void *name ATTRIBUTE_UNUSED,
                                void *data)
{
    virDomainSnapshotObjPtr snap = payload;
    int *count = data;

2026
    if (virDomainSnapshotIsExternal(snap))
2027 2028 2029
        (*count)++;
}

2030 2031 2032 2033
static int
qemuDomainDestroyFlags(virDomainPtr dom,
                       unsigned int flags)
{
2034
    virQEMUDriverPtr driver = dom->conn->privateData;
2035 2036
    virDomainObjPtr vm;
    int ret = -1;
2037
    virDomainEventPtr event = NULL;
2038
    qemuDomainObjPrivatePtr priv;
2039

2040
    virCheckFlags(VIR_DOMAIN_DESTROY_GRACEFUL, -1);
2041

2042 2043
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
2044

2045 2046
    priv = vm->privateData;

2047 2048 2049
    if (virDomainDestroyFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2050
    qemuDomainSetFakeReboot(driver, vm, false);
2051

2052 2053 2054 2055 2056 2057

    /* We need to prevent monitor EOF callback from doing our work (and sending
     * misleading events) while the vm is unlocked inside BeginJob/ProcessKill API
     */
    priv->beingDestroyed = true;

2058 2059 2060 2061 2062
    /* 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
     */
2063
    if (flags & VIR_DOMAIN_DESTROY_GRACEFUL) {
2064
        if (qemuProcessKill(vm, 0) < 0) {
2065
            priv->beingDestroyed = false;
2066
            goto cleanup;
2067
        }
2068
    } else {
2069
        if (qemuProcessKill(vm, VIR_QEMU_PROCESS_KILL_FORCE) < 0) {
2070
            priv->beingDestroyed = false;
2071
            goto cleanup;
2072
        }
2073
    }
2074

2075
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_DESTROY) < 0)
2076 2077
        goto cleanup;

2078 2079
    priv->beingDestroyed = false;

D
Daniel P. Berrange 已提交
2080
    if (!virDomainObjIsActive(vm)) {
2081 2082
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
2083
        goto endjob;
2084
    }
2085

2086
    qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED, 0);
2087 2088 2089
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
2090
    virDomainAuditStop(vm, "destroyed");
2091

2092
    if (!vm->persistent) {
2093
        if (qemuDomainObjEndJob(driver, vm) > 0)
2094
            qemuDomainRemoveInactive(driver, vm);
2095 2096
        vm = NULL;
    }
2097 2098
    ret = 0;

2099
endjob:
2100
    if (vm &&
2101
        qemuDomainObjEndJob(driver, vm) == 0)
2102
        vm = NULL;
2103

2104
cleanup:
2105
    if (vm)
2106
        virObjectUnlock(vm);
2107 2108
    if (event)
        qemuDomainEventQueue(driver, event);
2109
    return ret;
D
Daniel P. Berrange 已提交
2110 2111
}

2112 2113 2114 2115 2116
static int
qemuDomainDestroy(virDomainPtr dom)
{
    return qemuDomainDestroyFlags(dom, 0);
}
D
Daniel P. Berrange 已提交
2117

2118
static char *qemuDomainGetOSType(virDomainPtr dom) {
2119 2120
    virDomainObjPtr vm;
    char *type = NULL;
2121

2122
    if (!(vm = qemuDomObjFromDomain(dom)))
2123
        goto cleanup;
2124

2125 2126 2127
    if (virDomainGetOSTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2128
    ignore_value(VIR_STRDUP(type, vm->def->os.type));
2129 2130

cleanup:
2131
    if (vm)
2132
        virObjectUnlock(vm);
2133 2134 2135
    return type;
}

2136
/* Returns max memory in kb, 0 if error */
2137 2138 2139
static unsigned long long
qemuDomainGetMaxMemory(virDomainPtr dom)
{
2140
    virDomainObjPtr vm;
2141
    unsigned long long ret = 0;
2142

2143
    if (!(vm = qemuDomObjFromDomain(dom)))
2144
        goto cleanup;
2145

2146 2147 2148
    if (virDomainGetMaxMemoryEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2149
    ret = vm->def->mem.max_balloon;
2150 2151

cleanup:
2152
    if (vm)
2153
        virObjectUnlock(vm);
2154
    return ret;
2155 2156
}

2157 2158
static int qemuDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
                                    unsigned int flags) {
2159
    virQEMUDriverPtr driver = dom->conn->privateData;
2160
    qemuDomainObjPrivatePtr priv;
2161
    virDomainObjPtr vm;
2162
    virDomainDefPtr persistentDef = NULL;
2163
    int ret = -1, r;
2164
    virQEMUDriverConfigPtr cfg = NULL;
2165
    virCapsPtr caps = NULL;
2166

2167 2168
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
2169
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
2170

2171
    if (!(vm = qemuDomObjFromDomain(dom)))
2172
        goto cleanup;
2173

2174 2175
    cfg = virQEMUDriverGetConfig(driver);

2176 2177 2178
    if (virDomainSetMemoryFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

2179
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
2180 2181
        goto cleanup;

2182 2183
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto endjob;
2184
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
2185
                                        &persistentDef) < 0)
2186
        goto endjob;
2187

2188 2189 2190
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */

2191
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
2192 2193 2194
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot resize the maximum memory on an "
                             "active domain"));
2195
            goto endjob;
2196
        }
2197

2198
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
2199 2200
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
2201 2202 2203
            persistentDef->mem.max_balloon = newmem;
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
2204
            ret = virDomainSaveConfig(cfg->configDir, persistentDef);
2205 2206 2207
            goto endjob;
        }

2208 2209 2210 2211
    } else {
        /* resize the current memory */

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

2217
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
2218
            priv = vm->privateData;
2219
            qemuDomainObjEnterMonitor(driver, vm);
2220
            r = qemuMonitorSetBalloon(priv->mon, newmem);
2221
            qemuDomainObjExitMonitor(driver, vm);
2222 2223
            virDomainAuditMemory(vm, vm->def->mem.cur_balloon, newmem, "update",
                                 r == 1);
2224 2225 2226 2227 2228
            if (r < 0)
                goto endjob;

            /* Lack of balloon support is a fatal error */
            if (r == 0) {
2229 2230 2231
                virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                               _("Unable to change memory of active domain without "
                                 "the balloon device and guest OS balloon driver"));
2232 2233 2234 2235
                goto endjob;
            }
        }

2236
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
2237
            sa_assert(persistentDef);
2238
            persistentDef->mem.cur_balloon = newmem;
2239
            ret = virDomainSaveConfig(cfg->configDir, persistentDef);
2240 2241
            goto endjob;
        }
2242
    }
2243

2244
    ret = 0;
2245
endjob:
2246
    if (qemuDomainObjEndJob(driver, vm) == 0)
2247
        vm = NULL;
2248

2249
cleanup:
2250
    if (vm)
2251
        virObjectUnlock(vm);
2252
    virObjectUnref(caps);
2253
    virObjectUnref(cfg);
2254
    return ret;
2255 2256
}

2257
static int qemuDomainSetMemory(virDomainPtr dom, unsigned long newmem)
2258
{
2259
    return qemuDomainSetMemoryFlags(dom, newmem, VIR_DOMAIN_AFFECT_LIVE);
2260 2261
}

2262
static int qemuDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
2263
{
2264
    return qemuDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
2265 2266
}

2267 2268
static int qemuDomainInjectNMI(virDomainPtr domain, unsigned int flags)
{
2269
    virQEMUDriverPtr driver = domain->conn->privateData;
2270 2271 2272 2273 2274 2275
    virDomainObjPtr vm = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, -1);

2276 2277
    if (!(vm = qemuDomObjFromDomain(domain)))
        return -1;
2278

2279 2280 2281
    if (virDomainInjectNMIEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

2282
    if (!virDomainObjIsActive(vm)) {
2283 2284
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
2285 2286 2287 2288 2289
        goto cleanup;
    }

    priv = vm->privateData;

2290
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
2291
        goto cleanup;
2292 2293

    if (!virDomainObjIsActive(vm)) {
2294 2295
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
2296 2297 2298
        goto endjob;
    }

2299
    qemuDomainObjEnterMonitor(driver, vm);
2300
    ret = qemuMonitorInjectNMI(priv->mon);
2301
    qemuDomainObjExitMonitor(driver, vm);
2302 2303

endjob:
2304
    if (qemuDomainObjEndJob(driver, vm) == 0) {
2305 2306 2307 2308 2309 2310
        vm = NULL;
        goto cleanup;
    }

cleanup:
    if (vm)
2311
        virObjectUnlock(vm);
2312 2313 2314
    return ret;
}

2315 2316 2317 2318 2319 2320 2321
static int qemuDomainSendKey(virDomainPtr domain,
                             unsigned int codeset,
                             unsigned int holdtime,
                             unsigned int *keycodes,
                             int nkeycodes,
                             unsigned int flags)
{
2322
    virQEMUDriverPtr driver = domain->conn->privateData;
2323 2324 2325 2326 2327 2328
    virDomainObjPtr vm = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, -1);

2329 2330
    /* translate the keycode to RFB for qemu driver */
    if (codeset != VIR_KEYCODE_SET_RFB) {
2331 2332 2333 2334
        int i;
        int keycode;

        for (i = 0; i < nkeycodes; i++) {
2335
            keycode = virKeycodeValueTranslate(codeset, VIR_KEYCODE_SET_RFB,
2336 2337
                                               keycodes[i]);
            if (keycode < 0) {
2338 2339 2340 2341
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("cannot translate keycode %u of %s codeset to rfb keycode"),
                               keycodes[i],
                               virKeycodeSetTypeToString(codeset));
2342 2343 2344 2345 2346 2347
                return -1;
            }
            keycodes[i] = keycode;
        }
    }

2348
    if (!(vm = qemuDomObjFromDomain(domain)))
2349 2350 2351 2352
        goto cleanup;

    priv = vm->privateData;

2353 2354 2355
    if (virDomainSendKeyEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

2356
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
2357 2358 2359
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
2360 2361
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
2362
        goto endjob;
2363 2364
    }

2365
    qemuDomainObjEnterMonitor(driver, vm);
2366
    ret = qemuMonitorSendKey(priv->mon, holdtime, keycodes, nkeycodes);
2367
    qemuDomainObjExitMonitor(driver, vm);
2368 2369 2370

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
2371 2372 2373 2374
        vm = NULL;

cleanup:
    if (vm)
2375
        virObjectUnlock(vm);
2376 2377 2378
    return ret;
}

2379 2380
static int qemuDomainGetInfo(virDomainPtr dom,
                             virDomainInfoPtr info)
2381
{
2382
    virQEMUDriverPtr driver = dom->conn->privateData;
2383 2384
    virDomainObjPtr vm;
    int ret = -1;
2385
    int err;
2386
    unsigned long long balloon;
2387

2388
    if (!(vm = qemuDomObjFromDomain(dom)))
2389
        goto cleanup;
D
Daniel P. Berrange 已提交
2390

2391 2392 2393
    if (virDomainGetInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

D
Daniel P. Berrange 已提交
2396
    if (!virDomainObjIsActive(vm)) {
2397
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
2398
    } else {
2399
        if (qemuGetProcessInfo(&(info->cpuTime), NULL, NULL, vm->pid, 0) < 0) {
2400 2401
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("cannot read cputime for domain"));
2402
            goto cleanup;
D
Daniel P. Berrange 已提交
2403 2404 2405
        }
    }

2406
    info->maxMem = vm->def->mem.max_balloon;
2407

D
Daniel P. Berrange 已提交
2408
    if (virDomainObjIsActive(vm)) {
2409
        qemuDomainObjPrivatePtr priv = vm->privateData;
2410 2411 2412

        if ((vm->def->memballoon != NULL) &&
            (vm->def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_NONE)) {
2413
            info->memory = vm->def->mem.max_balloon;
2414
        } else if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BALLOON_EVENT)) {
2415
            info->memory = vm->def->mem.cur_balloon;
2416
        } else if (qemuDomainJobAllowed(priv, QEMU_JOB_QUERY)) {
2417
            if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
2418
                goto cleanup;
2419 2420 2421
            if (!virDomainObjIsActive(vm))
                err = 0;
            else {
2422
                qemuDomainObjEnterMonitor(driver, vm);
2423
                err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
2424
                qemuDomainObjExitMonitor(driver, vm);
2425
            }
2426
            if (qemuDomainObjEndJob(driver, vm) == 0) {
2427
                vm = NULL;
2428 2429 2430
                goto cleanup;
            }

2431 2432 2433 2434 2435 2436 2437
            if (err < 0) {
                /* We couldn't get current memory allocation but that's not
                 * a show stopper; we wouldn't get it if there was a job
                 * active either
                 */
                info->memory = vm->def->mem.cur_balloon;
            } else if (err == 0) {
2438
                /* Balloon not supported, so maxmem is always the allocation */
2439
                info->memory = vm->def->mem.max_balloon;
2440
            } else {
2441
                info->memory = balloon;
2442
            }
2443
        } else {
2444
            info->memory = vm->def->mem.cur_balloon;
2445
        }
2446
    } else {
2447
        info->memory = vm->def->mem.cur_balloon;
2448 2449
    }

2450
    info->nrVirtCpu = vm->def->vcpus;
2451 2452 2453
    ret = 0;

cleanup:
2454
    if (vm)
2455
        virObjectUnlock(vm);
2456
    return ret;
D
Daniel P. Berrange 已提交
2457 2458
}

2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
static int
qemuDomainGetState(virDomainPtr dom,
                   int *state,
                   int *reason,
                   unsigned int flags)
{
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

2470
    if (!(vm = qemuDomObjFromDomain(dom)))
2471 2472
        goto cleanup;

2473 2474 2475
    if (virDomainGetStateEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jiri Denemark 已提交
2476
    *state = virDomainObjGetState(vm, reason);
2477 2478 2479 2480
    ret = 0;

cleanup:
    if (vm)
2481
        virObjectUnlock(vm);
2482 2483 2484
    return ret;
}

2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495
static int
qemuDomainGetControlInfo(virDomainPtr dom,
                          virDomainControlInfoPtr info,
                          unsigned int flags)
{
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(0, -1);

2496
    if (!(vm = qemuDomObjFromDomain(dom)))
2497 2498
        goto cleanup;

2499 2500 2501
    if (virDomainGetControlInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2502
    if (!virDomainObjIsActive(vm)) {
2503 2504
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
2505 2506 2507 2508 2509 2510 2511 2512 2513
        goto cleanup;
    }

    priv = vm->privateData;

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

    if (priv->monError) {
        info->state = VIR_DOMAIN_CONTROL_ERROR;
2514
    } else if (priv->job.active) {
2515 2516
        if (!priv->monStart) {
            info->state = VIR_DOMAIN_CONTROL_JOB;
2517
            if (virTimeMillisNow(&info->stateTime) < 0)
2518
                goto cleanup;
2519
            info->stateTime -= priv->job.start;
2520 2521
        } else {
            info->state = VIR_DOMAIN_CONTROL_OCCUPIED;
2522
            if (virTimeMillisNow(&info->stateTime) < 0)
2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533
                goto cleanup;
            info->stateTime -= priv->monStart;
        }
    } else {
        info->state = VIR_DOMAIN_CONTROL_OK;
    }

    ret = 0;

cleanup:
    if (vm)
2534
        virObjectUnlock(vm);
2535 2536 2537
    return ret;
}

D
Daniel P. Berrange 已提交
2538

2539 2540 2541 2542 2543 2544
/* It would be nice to replace 'Qemud' with 'Qemu' but
 * this magic string is ABI, so it can't be changed
 */
#define QEMU_SAVE_MAGIC   "LibvirtQemudSave"
#define QEMU_SAVE_PARTIAL "LibvirtQemudPart"
#define QEMU_SAVE_VERSION 2
2545

2546
verify(sizeof(QEMU_SAVE_MAGIC) == sizeof(QEMU_SAVE_PARTIAL));
E
Eric Blake 已提交
2547

2548
typedef enum {
2549 2550 2551
    QEMU_SAVE_FORMAT_RAW = 0,
    QEMU_SAVE_FORMAT_GZIP = 1,
    QEMU_SAVE_FORMAT_BZIP2 = 2,
2552 2553
    /*
     * Deprecated by xz and never used as part of a release
2554
     * QEMU_SAVE_FORMAT_LZMA
2555
     */
2556 2557
    QEMU_SAVE_FORMAT_XZ = 3,
    QEMU_SAVE_FORMAT_LZOP = 4,
2558 2559 2560
    /* Note: add new members only at the end.
       These values are used in the on-disk format.
       Do not change or re-use numbers. */
2561

2562
    QEMU_SAVE_FORMAT_LAST
2563
} virQEMUSaveFormat;
2564

2565 2566
VIR_ENUM_DECL(qemuSaveCompression)
VIR_ENUM_IMPL(qemuSaveCompression, QEMU_SAVE_FORMAT_LAST,
2567 2568 2569
              "raw",
              "gzip",
              "bzip2",
2570 2571
              "xz",
              "lzop")
2572

2573 2574 2575
typedef struct _virQEMUSaveHeader virQEMUSaveHeader;
typedef virQEMUSaveHeader *virQEMUSaveHeaderPtr;
struct _virQEMUSaveHeader {
2576
    char magic[sizeof(QEMU_SAVE_MAGIC)-1];
2577 2578 2579 2580 2581
    uint32_t version;
    uint32_t xml_len;
    uint32_t was_running;
    uint32_t compressed;
    uint32_t unused[15];
2582 2583
};

2584
static inline void
2585
bswap_header(virQEMUSaveHeaderPtr hdr) {
2586 2587 2588 2589 2590 2591 2592
    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);
}


2593
/* return -errno on failure, or 0 on success */
E
Eric Blake 已提交
2594
static int
2595
qemuDomainSaveHeader(int fd, const char *path, const char *xml,
2596
                     virQEMUSaveHeaderPtr header)
E
Eric Blake 已提交
2597
{
2598 2599
    int ret = 0;

E
Eric Blake 已提交
2600
    if (safewrite(fd, header, sizeof(*header)) != sizeof(*header)) {
2601
        ret = -errno;
2602 2603 2604
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("failed to write header to domain save file '%s'"),
                       path);
2605 2606 2607
        goto endjob;
    }

E
Eric Blake 已提交
2608
    if (safewrite(fd, xml, header->xml_len) != header->xml_len) {
2609
        ret = -errno;
2610 2611
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("failed to write xml to '%s'"), path);
2612 2613 2614 2615 2616 2617
        goto endjob;
    }
endjob:
    return ret;
}

2618
/* Given a virQEMUSaveFormat compression level, return the name
2619 2620 2621 2622
 * of the program to run, or NULL if no program is needed.  */
static const char *
qemuCompressProgramName(int compress)
{
2623 2624
    return (compress == QEMU_SAVE_FORMAT_RAW ? NULL :
            qemuSaveCompressionTypeToString(compress));
2625 2626
}

2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653
static virCommandPtr
qemuCompressGetCommand(virQEMUSaveFormat compression)
{
    virCommandPtr ret = NULL;
    const char *prog = qemuSaveCompressionTypeToString(compression);

    if (!prog) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Invalid compressed save format %d"),
                       compression);
        return NULL;
    }

    ret = virCommandNew(prog);
    virCommandAddArg(ret, "-dc");

    switch (compression) {
    case QEMU_SAVE_FORMAT_LZOP:
        virCommandAddArg(ret, "--ignore-warn");
        break;
    default:
        break;
    }

    return ret;
}

E
Eric Blake 已提交
2654 2655 2656
/* Internal function to properly create or open existing files, with
 * ownership affected by qemu driver setup.  */
static int
2657
qemuOpenFile(virQEMUDriverPtr driver, const char *path, int oflags,
E
Eric Blake 已提交
2658 2659 2660 2661 2662 2663
             bool *needUnlink, bool *bypassSecurityDriver)
{
    struct stat sb;
    bool is_reg = true;
    bool need_unlink = false;
    bool bypass_security = false;
L
Laine Stump 已提交
2664
    unsigned int vfoflags = 0;
E
Eric Blake 已提交
2665
    int fd = -1;
2666
    int path_shared = virStorageFileIsSharedFS(path);
E
Eric Blake 已提交
2667 2668
    uid_t uid = getuid();
    gid_t gid = getgid();
2669
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
E
Eric Blake 已提交
2670 2671 2672 2673 2674 2675

    /* path might be a pre-existing block dev, in which case
     * we need to skip the create step, and also avoid unlink
     * in the failure case */
    if (oflags & O_CREAT) {
        need_unlink = true;
2676 2677 2678

        /* Don't force chown on network-shared FS
         * as it is likely to fail. */
2679
        if (path_shared <= 0 || cfg->dynamicOwnership)
2680 2681
            vfoflags |= VIR_FILE_OPEN_FORCE_OWNER;

E
Eric Blake 已提交
2682 2683 2684 2685 2686
        if (stat(path, &sb) == 0) {
            is_reg = !!S_ISREG(sb.st_mode);
            /* If the path is regular file which exists
             * already and dynamic_ownership is off, we don't
             * want to change it's ownership, just open it as-is */
2687
            if (is_reg && !cfg->dynamicOwnership) {
E
Eric Blake 已提交
2688 2689 2690 2691 2692 2693 2694 2695
                uid = sb.st_uid;
                gid = sb.st_gid;
            }
        }
    }

    /* First try creating the file as root */
    if (!is_reg) {
2696 2697 2698
        if ((fd = open(path, oflags & ~O_CREAT)) < 0) {
            fd = -errno;
            goto error;
E
Eric Blake 已提交
2699 2700
        }
    } else {
L
Laine Stump 已提交
2701 2702
        if ((fd = virFileOpenAs(path, oflags, S_IRUSR | S_IWUSR, uid, gid,
                                vfoflags | VIR_FILE_OPEN_NOFORK)) < 0) {
E
Eric Blake 已提交
2703 2704 2705
            /* If we failed as root, and the error was permission-denied
               (EACCES or EPERM), assume it's on a network-connected share
               where root access is restricted (eg, root-squashed NFS). If the
2706
               qemu user (cfg->user) is non-root, just set a flag to
E
Eric Blake 已提交
2707 2708
               bypass security driver shenanigans, and retry the operation
               after doing setuid to qemu user */
2709 2710
            if ((fd != -EACCES && fd != -EPERM) || cfg->user == getuid())
                goto error;
E
Eric Blake 已提交
2711 2712

            /* On Linux we can also verify the FS-type of the directory. */
2713
            switch (path_shared) {
E
Eric Blake 已提交
2714
                case 1:
2715 2716 2717 2718
                    /* it was on a network share, so we'll continue
                     * as outlined above
                     */
                    break;
E
Eric Blake 已提交
2719 2720

                case -1:
2721 2722 2723 2724 2725 2726 2727
                    virReportSystemError(-fd, oflags & O_CREAT
                                         ? _("Failed to create file "
                                             "'%s': couldn't determine fs type")
                                         : _("Failed to open file "
                                             "'%s': couldn't determine fs type"),
                                         path);
                    goto cleanup;
E
Eric Blake 已提交
2728 2729 2730

                case 0:
                default:
2731 2732
                    /* local file - log the error returned by virFileOpenAs */
                    goto error;
E
Eric Blake 已提交
2733 2734
            }

2735
            /* Retry creating the file as cfg->user */
E
Eric Blake 已提交
2736 2737 2738

            if ((fd = virFileOpenAs(path, oflags,
                                    S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP,
2739
                                    cfg->user, cfg->group,
L
Laine Stump 已提交
2740
                                    vfoflags | VIR_FILE_OPEN_FORK)) < 0) {
2741 2742 2743
                virReportSystemError(-fd, oflags & O_CREAT
                                     ? _("Error from child process creating '%s'")
                                     : _("Error from child process opening '%s'"),
E
Eric Blake 已提交
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
                                     path);
                goto cleanup;
            }

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

            bypass_security = true;
        }
    }
cleanup:
    if (needUnlink)
        *needUnlink = need_unlink;
    if (bypassSecurityDriver)
        *bypassSecurityDriver = bypass_security;
2760
    virObjectUnref(cfg);
E
Eric Blake 已提交
2761
    return fd;
2762 2763 2764 2765 2766 2767 2768

error:
    virReportSystemError(-fd, oflags & O_CREAT
                         ? _("Failed to create file '%s'")
                         : _("Failed to open file '%s'"),
                         path);
    goto cleanup;
E
Eric Blake 已提交
2769 2770
}

2771 2772 2773
/* Helper function to execute a migration to file with a correct save header
 * the caller needs to make sure that the processors are stopped and do all other
 * actions besides saving memory */
2774
static int
2775
qemuDomainSaveMemory(virQEMUDriverPtr driver,
2776 2777
                     virDomainObjPtr vm,
                     const char *path,
2778
                     const char *domXML,
2779 2780 2781 2782
                     int compressed,
                     bool was_running,
                     unsigned int flags,
                     enum qemuDomainAsyncJob asyncJob)
2783
{
2784
    virQEMUSaveHeader header;
2785
    bool bypassSecurityDriver = false;
E
Eric Blake 已提交
2786
    bool needUnlink = false;
2787
    int ret = -1;
2788
    int fd = -1;
2789
    int directFlag = 0;
J
Jiri Denemark 已提交
2790
    virFileWrapperFdPtr wrapperFd = NULL;
2791
    unsigned int wrapperFlags = VIR_FILE_WRAPPER_NON_BLOCKING;
2792 2793 2794
    unsigned long long pad;
    unsigned long long offset;
    size_t len;
2795
    char *xml = NULL;
2796

2797
    memset(&header, 0, sizeof(header));
2798 2799
    memcpy(header.magic, QEMU_SAVE_PARTIAL, sizeof(header.magic));
    header.version = QEMU_SAVE_VERSION;
2800
    header.was_running = was_running ? 1 : 0;
2801

2802
    header.compressed = compressed;
2803

2804
    len = strlen(domXML) + 1;
2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817
    offset = sizeof(header) + len;

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

2824 2825
    offset += pad;
    header.xml_len = len;
2826

2827
    /* Obtain the file handle.  */
2828 2829
    if ((flags & VIR_DOMAIN_SAVE_BYPASS_CACHE)) {
        wrapperFlags |= VIR_FILE_WRAPPER_BYPASS_CACHE;
2830 2831
        directFlag = virFileDirectFdFlag();
        if (directFlag < 0) {
2832 2833
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("bypass cache unsupported by this system"));
E
Eric Blake 已提交
2834
            goto cleanup;
2835
        }
2836
    }
E
Eric Blake 已提交
2837 2838 2839
    fd = qemuOpenFile(driver, path, O_WRONLY | O_TRUNC | O_CREAT | directFlag,
                      &needUnlink, &bypassSecurityDriver);
    if (fd < 0)
2840 2841
        goto cleanup;

2842
    if (!(wrapperFd = virFileWrapperFdNew(&fd, path, wrapperFlags)))
2843
        goto cleanup;
2844

2845
    /* Write header to file, followed by XML */
2846 2847
    if (qemuDomainSaveHeader(fd, path, xml, &header) < 0)
        goto cleanup;
2848

2849
    /* Perform the migration */
2850
    if (qemuMigrationToFile(driver, vm, fd, offset, path,
2851
                            qemuCompressProgramName(compressed),
E
Eric Blake 已提交
2852
                            bypassSecurityDriver,
2853 2854
                            asyncJob) < 0)
        goto cleanup;
E
Eric Blake 已提交
2855

2856 2857 2858 2859 2860 2861 2862 2863
    /* Touch up file header to mark image complete. */

    /* Reopen the file to touch up the header, since we aren't set
     * up to seek backwards on wrapperFd.  The reopened fd will
     * trigger a single page of file system cache pollution, but
     * that's acceptable.  */
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("unable to close %s"), path);
2864
        goto cleanup;
E
Eric Blake 已提交
2865
    }
2866

2867
    if (virFileWrapperFdClose(wrapperFd) < 0)
2868 2869 2870 2871
        goto cleanup;

    if ((fd = qemuOpenFile(driver, path, O_WRONLY, NULL, NULL)) < 0)
        goto cleanup;
2872

2873
    memcpy(header.magic, QEMU_SAVE_MAGIC, sizeof(header.magic));
2874

E
Eric Blake 已提交
2875 2876
    if (safewrite(fd, &header, sizeof(header)) != sizeof(header)) {
        virReportSystemError(errno, _("unable to write %s"), path);
2877
        goto cleanup;
E
Eric Blake 已提交
2878
    }
2879

2880 2881
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("unable to close %s"), path);
2882
        goto cleanup;
2883 2884
    }

2885 2886
    ret = 0;

2887 2888 2889
cleanup:
    VIR_FORCE_CLOSE(fd);
    virFileWrapperFdFree(wrapperFd);
2890
    VIR_FREE(xml);
2891 2892 2893 2894 2895 2896 2897

    if (ret != 0 && needUnlink)
        unlink(path);

    return ret;
}

2898
/* The vm must be active + locked. Vm will be unlocked and
2899 2900 2901 2902 2903
 * potentially free'd after this returns (eg transient VMs are freed
 * shutdown). So 'vm' must not be referenced by the caller after
 * this returns (whether returning success or failure).
 */
static int
2904
qemuDomainSaveInternal(virQEMUDriverPtr driver, virDomainPtr dom,
2905 2906 2907 2908 2909 2910 2911 2912 2913
                       virDomainObjPtr vm, const char *path,
                       int compressed, const char *xmlin, unsigned int flags)
{
    char *xml = NULL;
    bool was_running = false;
    int ret = -1;
    int rc;
    virDomainEventPtr event = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
2914 2915 2916 2917
    virCapsPtr caps;

    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;
2918

2919
    if (!qemuMigrationIsAllowed(driver, vm, vm->def, false, false))
2920 2921
        goto cleanup;

2922
    if (qemuDomainObjBeginAsyncJob(driver, vm,
2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954
                                             QEMU_ASYNC_JOB_SAVE) < 0)

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

    /* Pause */
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
        was_running = true;
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_SAVE) < 0)
            goto endjob;

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

   /* libvirt.c already guaranteed these two flags are exclusive.  */
    if (flags & VIR_DOMAIN_SAVE_RUNNING)
        was_running = true;
    else if (flags & VIR_DOMAIN_SAVE_PAUSED)
        was_running = false;

    /* Get XML for the domain.  Restore needs only the inactive xml,
     * including secure.  We should get the same result whether xmlin
     * is NULL or whether it was the live xml of the domain moments
     * before.  */
    if (xmlin) {
        virDomainDefPtr def = NULL;

2955
        if (!(def = virDomainDefParseString(xmlin, caps, driver->xmlopt,
2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978
                                            QEMU_EXPECTED_VIRT_TYPES,
                                            VIR_DOMAIN_XML_INACTIVE))) {
            goto endjob;
        }
        if (!virDomainDefCheckABIStability(vm->def, def)) {
            virDomainDefFree(def);
            goto endjob;
        }
        xml = qemuDomainDefFormatLive(driver, def, true, true);
    } else {
        xml = qemuDomainDefFormatLive(driver, vm->def, true, true);
    }
    if (!xml) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("failed to get domain xml"));
        goto endjob;
    }

    ret = qemuDomainSaveMemory(driver, vm, path, xml, compressed,
                               was_running, flags, QEMU_ASYNC_JOB_SAVE);
    if (ret < 0)
        goto endjob;

2979
    /* Shut it down */
2980
    qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_SAVED, 0);
2981
    virDomainAuditStop(vm, "saved");
2982 2983 2984
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2985
    if (!vm->persistent) {
2986
        if (qemuDomainObjEndAsyncJob(driver, vm) > 0)
2987
            qemuDomainRemoveInactive(driver, vm);
2988 2989
        vm = NULL;
    }
2990

2991
endjob:
2992
    if (vm) {
2993
        if (ret != 0) {
2994
            if (was_running && virDomainObjIsActive(vm)) {
J
Jiri Denemark 已提交
2995
                rc = qemuProcessStartCPUs(driver, vm, dom->conn,
2996 2997
                                          VIR_DOMAIN_RUNNING_SAVE_CANCELED,
                                          QEMU_ASYNC_JOB_SAVE);
2998
                if (rc < 0) {
2999
                    VIR_WARN("Unable to resume guest CPUs after save failure");
3000 3001 3002 3003
                    event = virDomainEventNewFromObj(vm,
                                                     VIR_DOMAIN_EVENT_SUSPENDED,
                                                     VIR_DOMAIN_EVENT_SUSPENDED_API_ERROR);
                }
3004
            }
3005
        }
3006
        if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
3007
            vm = NULL;
3008
    }
3009

3010 3011
cleanup:
    VIR_FREE(xml);
3012 3013
    if (event)
        qemuDomainEventQueue(driver, event);
3014
    if (vm)
3015
        virObjectUnlock(vm);
3016
    virObjectUnref(caps);
3017
    return ret;
D
Daniel P. Berrange 已提交
3018 3019
}

3020
/* Returns true if a compression program is available in PATH */
3021
static bool qemuCompressProgramAvailable(virQEMUSaveFormat compress)
3022 3023 3024 3025
{
    const char *prog;
    char *c;

3026
    if (compress == QEMU_SAVE_FORMAT_RAW)
3027
        return true;
3028
    prog = qemuSaveCompressionTypeToString(compress);
3029 3030 3031 3032 3033 3034 3035
    c = virFindFileInPath(prog);
    if (!c)
        return false;
    VIR_FREE(c);
    return true;
}

3036 3037 3038
static int
qemuDomainSaveFlags(virDomainPtr dom, const char *path, const char *dxml,
                    unsigned int flags)
3039
{
3040
    virQEMUDriverPtr driver = dom->conn->privateData;
3041
    int compressed;
3042 3043
    int ret = -1;
    virDomainObjPtr vm = NULL;
3044
    virQEMUDriverConfigPtr cfg = NULL;
3045

3046 3047 3048
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
                  VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
3049

3050 3051
    cfg = virQEMUDriverGetConfig(driver);
    if (cfg->saveImageFormat == NULL)
3052
        compressed = QEMU_SAVE_FORMAT_RAW;
3053
    else {
3054
        compressed = qemuSaveCompressionTypeFromString(cfg->saveImageFormat);
3055
        if (compressed < 0) {
3056 3057 3058
            virReportError(VIR_ERR_OPERATION_FAILED,
                           "%s", _("Invalid save image format specified "
                                   "in configuration file"));
3059
            goto cleanup;
3060
        }
3061
        if (!qemuCompressProgramAvailable(compressed)) {
3062 3063 3064
            virReportError(VIR_ERR_OPERATION_FAILED,
                           "%s", _("Compression program for image format "
                                   "in configuration file isn't available"));
3065
            goto cleanup;
3066
        }
3067 3068
    }

3069
    if (!(vm = qemuDomObjFromDomain(dom)))
3070 3071
        goto cleanup;

3072 3073 3074
    if (virDomainSaveFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3075
    if (!virDomainObjIsActive(vm)) {
3076 3077
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
3078 3079 3080
        goto cleanup;
    }

3081
    ret = qemuDomainSaveInternal(driver, dom, vm, path, compressed,
3082
                                 dxml, flags);
3083
    vm = NULL;
3084 3085 3086

cleanup:
    if (vm)
3087
        virObjectUnlock(vm);
3088
    virObjectUnref(cfg);
3089
    return ret;
3090 3091
}

3092 3093 3094 3095 3096 3097
static int
qemuDomainSave(virDomainPtr dom, const char *path)
{
    return qemuDomainSaveFlags(dom, path, NULL, 0);
}

3098
static char *
3099 3100
qemuDomainManagedSavePath(virQEMUDriverPtr driver, virDomainObjPtr vm)
{
3101
    char *ret;
3102
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
3103

3104
    if (virAsprintf(&ret, "%s/%s.save", cfg->saveDir, vm->def->name) < 0) {
3105
        virReportOOMError();
3106
        virObjectUnref(cfg);
3107
        return NULL;
3108 3109
    }

3110
    virObjectUnref(cfg);
3111
    return ret;
3112 3113 3114 3115 3116
}

static int
qemuDomainManagedSave(virDomainPtr dom, unsigned int flags)
{
3117
    virQEMUDriverPtr driver = dom->conn->privateData;
3118
    virDomainObjPtr vm;
3119 3120 3121 3122
    char *name = NULL;
    int ret = -1;
    int compressed;

3123 3124 3125
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
                  VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
3126

3127
    if (!(vm = qemuDomObjFromDomain(dom)))
3128
        return -1;
3129

3130 3131 3132
    if (virDomainManagedSaveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3133
    if (!virDomainObjIsActive(vm)) {
3134 3135
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
3136 3137
        goto cleanup;
    }
3138
    if (!vm->persistent) {
3139 3140
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
3141 3142
        goto cleanup;
    }
3143

3144
    if (!(name = qemuDomainManagedSavePath(driver, vm)))
3145
        goto cleanup;
3146

3147
    VIR_INFO("Saving state to %s", name);
3148

3149
    compressed = QEMU_SAVE_FORMAT_RAW;
3150 3151 3152 3153
    if ((ret = qemuDomainSaveInternal(driver, dom, vm, name, compressed,
                                      NULL, flags)) == 0)
        vm->hasManagedSave = true;

3154
    vm = NULL;
3155 3156 3157

cleanup:
    if (vm)
3158
        virObjectUnlock(vm);
3159 3160 3161
    VIR_FREE(name);

    return ret;
3162 3163
}

3164 3165
static int
qemuDomainManagedSaveLoad(virDomainObjPtr vm,
3166 3167
                          void *opaque)
{
3168
    virQEMUDriverPtr driver = opaque;
3169
    char *name;
3170
    int ret = -1;
3171

3172
    virObjectLock(vm);
3173 3174 3175 3176 3177 3178

    if (!(name = qemuDomainManagedSavePath(driver, vm)))
        goto cleanup;

    vm->hasManagedSave = virFileExists(name);

3179
    ret = 0;
3180
cleanup:
3181
    virObjectUnlock(vm);
3182
    VIR_FREE(name);
3183
    return ret;
3184 3185
}

3186

3187 3188 3189 3190
static int
qemuDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm = NULL;
3191
    int ret = -1;
3192

3193
    virCheckFlags(0, -1);
3194

3195 3196
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
3197

3198 3199 3200
    if (virDomainHasManagedSaveImageEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3201
    ret = vm->hasManagedSave;
3202 3203

cleanup:
3204
    virObjectUnlock(vm);
3205 3206 3207 3208 3209 3210
    return ret;
}

static int
qemuDomainManagedSaveRemove(virDomainPtr dom, unsigned int flags)
{
3211
    virQEMUDriverPtr driver = dom->conn->privateData;
3212
    virDomainObjPtr vm;
3213 3214 3215
    int ret = -1;
    char *name = NULL;

3216
    virCheckFlags(0, -1);
3217

3218
    if (!(vm = qemuDomObjFromDomain(dom)))
3219
        return -1;
3220

3221 3222 3223
    if (virDomainManagedSaveRemoveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3224
    if (!(name = qemuDomainManagedSavePath(driver, vm)))
3225 3226
        goto cleanup;

3227 3228 3229 3230 3231 3232 3233
    if (unlink(name) < 0) {
        virReportSystemError(errno,
                             _("Failed to remove managed save file '%s'"),
                             name);
        goto cleanup;
    }

3234
    vm->hasManagedSave = false;
3235
    ret = 0;
3236 3237 3238

cleanup:
    VIR_FREE(name);
3239
    virObjectUnlock(vm);
3240 3241
    return ret;
}
D
Daniel P. Berrange 已提交
3242

3243
static int qemuDumpToFd(virQEMUDriverPtr driver, virDomainObjPtr vm,
3244 3245 3246 3247 3248
                        int fd, enum qemuDomainAsyncJob asyncJob)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret = -1;

3249
    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DUMP_GUEST_MEMORY)) {
3250
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
3251
                       _("dump-guest-memory is not supported"));
3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263
        return -1;
    }

    if (virSecurityManagerSetImageFDLabel(driver->securityManager, vm->def,
                                          fd) < 0)
        return -1;

    priv->job.dump_memory_only = true;

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

3264
    ret = qemuMonitorDumpToFd(priv->mon, fd);
3265
    qemuDomainObjExitMonitor(driver, vm);
3266 3267 3268 3269

    return ret;
}

3270
static int
3271
doCoreDump(virQEMUDriverPtr driver,
3272 3273
           virDomainObjPtr vm,
           const char *path,
3274
           virQEMUSaveFormat compress,
3275
           unsigned int dump_flags)
H
Hu Tao 已提交
3276 3277 3278
{
    int fd = -1;
    int ret = -1;
J
Jiri Denemark 已提交
3279
    virFileWrapperFdPtr wrapperFd = NULL;
3280
    int directFlag = 0;
3281
    unsigned int flags = VIR_FILE_WRAPPER_NON_BLOCKING;
H
Hu Tao 已提交
3282 3283

    /* Create an empty file with appropriate ownership.  */
3284
    if (dump_flags & VIR_DUMP_BYPASS_CACHE) {
3285
        flags |= VIR_FILE_WRAPPER_BYPASS_CACHE;
3286 3287
        directFlag = virFileDirectFdFlag();
        if (directFlag < 0) {
3288 3289
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("bypass cache unsupported by this system"));
3290 3291 3292
            goto cleanup;
        }
    }
E
Eric Blake 已提交
3293 3294 3295 3296 3297 3298
    /* Core dumps usually imply last-ditch analysis efforts are
     * desired, so we intentionally do not unlink even if a file was
     * created.  */
    if ((fd = qemuOpenFile(driver, path,
                           O_CREAT | O_TRUNC | O_WRONLY | directFlag,
                           NULL, NULL)) < 0)
H
Hu Tao 已提交
3299 3300
        goto cleanup;

3301
    if (!(wrapperFd = virFileWrapperFdNew(&fd, path, flags)))
3302 3303
        goto cleanup;

3304 3305 3306 3307 3308 3309 3310 3311 3312
    if (dump_flags & VIR_DUMP_MEMORY_ONLY) {
        ret = qemuDumpToFd(driver, vm, fd, QEMU_ASYNC_JOB_DUMP);
    } else {
        ret = qemuMigrationToFile(driver, vm, fd, 0, path,
                                  qemuCompressProgramName(compress), false,
                                  QEMU_ASYNC_JOB_DUMP);
    }

    if (ret < 0)
3313 3314
        goto cleanup;

H
Hu Tao 已提交
3315 3316
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno,
3317
                             _("unable to close file %s"),
H
Hu Tao 已提交
3318 3319 3320
                             path);
        goto cleanup;
    }
J
Jiri Denemark 已提交
3321
    if (virFileWrapperFdClose(wrapperFd) < 0)
3322
        goto cleanup;
H
Hu Tao 已提交
3323

3324
    ret = 0;
H
Hu Tao 已提交
3325 3326

cleanup:
3327
    VIR_FORCE_CLOSE(fd);
3328
    if (ret != 0)
H
Hu Tao 已提交
3329
        unlink(path);
3330
    virFileWrapperFdFree(wrapperFd);
H
Hu Tao 已提交
3331 3332 3333
    return ret;
}

3334
static virQEMUSaveFormat
3335
getCompressionType(virQEMUDriverPtr driver)
3336
{
3337 3338
    int ret = QEMU_SAVE_FORMAT_RAW;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
3339

3340 3341 3342 3343
    /*
     * We reuse "save" flag for "dump" here. Then, we can support the same
     * format in "save" and "dump".
     */
3344 3345
    if (cfg->dumpImageFormat) {
        ret = qemuSaveCompressionTypeFromString(cfg->dumpImageFormat);
3346 3347 3348
        /* Use "raw" as the format if the specified format is not valid,
         * or the compress program is not available.
         */
3349
        if (ret < 0) {
3350 3351
            VIR_WARN("%s", _("Invalid dump image format specified in "
                             "configuration file, using raw"));
3352 3353
            ret = QEMU_SAVE_FORMAT_RAW;
            goto cleanup;
3354
        }
3355
        if (!qemuCompressProgramAvailable(ret)) {
3356 3357 3358
            VIR_WARN("%s", _("Compression program for dump image format "
                             "in configuration file isn't available, "
                             "using raw"));
3359 3360
            ret = QEMU_SAVE_FORMAT_RAW;
            goto cleanup;
3361
        }
3362
    }
3363 3364 3365
cleanup:
    virObjectUnref(cfg);
    return ret;
3366 3367
}

3368 3369 3370
static int qemuDomainCoreDump(virDomainPtr dom,
                              const char *path,
                              unsigned int flags)
3371
{
3372
    virQEMUDriverPtr driver = dom->conn->privateData;
3373
    virDomainObjPtr vm;
M
Michal Privoznik 已提交
3374
    qemuDomainObjPrivatePtr priv;
3375
    bool resume = false, paused = false;
H
Hu Tao 已提交
3376
    int ret = -1;
3377 3378
    virDomainEventPtr event = NULL;

M
Michal Privoznik 已提交
3379
    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH |
3380 3381
                  VIR_DUMP_BYPASS_CACHE | VIR_DUMP_RESET |
                  VIR_DUMP_MEMORY_ONLY, -1);
3382

3383 3384
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
P
Paolo Bonzini 已提交
3385

3386 3387 3388
    if (virDomainCoreDumpEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3389 3390
    if (qemuDomainObjBeginAsyncJob(driver, vm,
                                   QEMU_ASYNC_JOB_DUMP) < 0)
3391 3392
        goto cleanup;

D
Daniel P. Berrange 已提交
3393
    if (!virDomainObjIsActive(vm)) {
3394 3395
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
3396
        goto endjob;
P
Paolo Bonzini 已提交
3397 3398
    }

P
Paolo Bonzini 已提交
3399 3400
    /* Migrate will always stop the VM, so the resume condition is
       independent of whether the stop command is issued.  */
J
Jiri Denemark 已提交
3401
    resume = virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING;
P
Paolo Bonzini 已提交
3402 3403

    /* Pause domain for non-live dump */
J
Jiri Denemark 已提交
3404 3405
    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
3406 3407
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_DUMP,
                                QEMU_ASYNC_JOB_DUMP) < 0)
3408
            goto endjob;
3409
        paused = true;
3410 3411

        if (!virDomainObjIsActive(vm)) {
3412 3413
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("guest unexpectedly quit"));
3414 3415
            goto endjob;
        }
P
Paolo Bonzini 已提交
3416 3417
    }

3418
    ret = doCoreDump(driver, vm, path, getCompressionType(driver), flags);
3419 3420 3421
    if (ret < 0)
        goto endjob;

3422
    paused = true;
3423 3424

endjob:
3425
    if ((ret == 0) && (flags & VIR_DUMP_CRASH)) {
3426
        qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_CRASHED, 0);
3427
        virDomainAuditStop(vm, "crashed");
3428 3429 3430 3431 3432
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
    }

P
Paolo Bonzini 已提交
3433 3434 3435
    /* 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.  */
M
Michal Privoznik 已提交
3436 3437 3438 3439
    else if (((resume && paused) || (flags & VIR_DUMP_RESET)) &&
             virDomainObjIsActive(vm)) {
        if ((ret == 0) && (flags & VIR_DUMP_RESET)) {
            priv =  vm->privateData;
3440
            qemuDomainObjEnterMonitor(driver, vm);
M
Michal Privoznik 已提交
3441
            ret = qemuMonitorSystemReset(priv->mon);
3442
            qemuDomainObjExitMonitor(driver, vm);
M
Michal Privoznik 已提交
3443 3444 3445 3446 3447
        }

        if (resume && qemuProcessStartCPUs(driver, vm, dom->conn,
                                           VIR_DOMAIN_RUNNING_UNPAUSED,
                                           QEMU_ASYNC_JOB_DUMP) < 0) {
3448 3449 3450
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_SUSPENDED,
                                             VIR_DOMAIN_EVENT_SUSPENDED_API_ERROR);
3451
            if (virGetLastError() == NULL)
3452 3453
                virReportError(VIR_ERR_OPERATION_FAILED,
                               "%s", _("resuming after dump failed"));
P
Paolo Bonzini 已提交
3454 3455
        }
    }
3456

3457
    if (qemuDomainObjEndAsyncJob(driver, vm) == 0)
3458
        vm = NULL;
3459
    else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
3460
        qemuDomainRemoveInactive(driver, vm);
3461 3462
        vm = NULL;
    }
3463 3464

cleanup:
P
Paolo Bonzini 已提交
3465
    if (vm)
3466
        virObjectUnlock(vm);
3467 3468
    if (event)
        qemuDomainEventQueue(driver, event);
P
Paolo Bonzini 已提交
3469 3470 3471
    return ret;
}

3472 3473 3474 3475
static char *
qemuDomainScreenshot(virDomainPtr dom,
                     virStreamPtr st,
                     unsigned int screen,
E
Eric Blake 已提交
3476
                     unsigned int flags)
3477
{
3478
    virQEMUDriverPtr driver = dom->conn->privateData;
3479 3480 3481 3482 3483
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    char *tmp = NULL;
    int tmp_fd = -1;
    char *ret = NULL;
E
Eric Blake 已提交
3484
    bool unlink_tmp = false;
3485
    virQEMUDriverConfigPtr cfg = NULL;
3486

E
Eric Blake 已提交
3487 3488
    virCheckFlags(0, NULL);

3489
    if (!(vm = qemuDomObjFromDomain(dom)))
3490 3491 3492
        goto cleanup;

    priv = vm->privateData;
3493
    cfg = virQEMUDriverGetConfig(driver);
3494

3495 3496 3497
    if (virDomainScreenshotEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3498
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
3499 3500 3501
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
3502 3503
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
3504 3505 3506 3507 3508 3509
        goto endjob;
    }

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

3516
    if (virAsprintf(&tmp, "%s/qemu.screendump.XXXXXX", cfg->cacheDir) < 0) {
3517 3518 3519 3520
        virReportOOMError();
        goto endjob;
    }

3521 3522
    if ((tmp_fd = mkostemp(tmp, O_CLOEXEC)) == -1) {
        virReportSystemError(errno, _("mkostemp(\"%s\") failed"), tmp);
3523 3524
        goto endjob;
    }
E
Eric Blake 已提交
3525
    unlink_tmp = true;
3526

3527
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm->def, tmp);
3528

3529
    qemuDomainObjEnterMonitor(driver, vm);
3530
    if (qemuMonitorScreendump(priv->mon, tmp) < 0) {
3531
        qemuDomainObjExitMonitor(driver, vm);
3532 3533
        goto endjob;
    }
3534
    qemuDomainObjExitMonitor(driver, vm);
3535 3536 3537 3538 3539 3540

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

E
Eric Blake 已提交
3541
    if (virFDStreamOpenFile(st, tmp, 0, 0, O_RDONLY) < 0) {
3542 3543
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("unable to open stream"));
3544 3545 3546
        goto endjob;
    }

3547
    ignore_value(VIR_STRDUP(ret, "image/x-portable-pixmap"));
3548 3549 3550

endjob:
    VIR_FORCE_CLOSE(tmp_fd);
E
Eric Blake 已提交
3551 3552
    if (unlink_tmp)
        unlink(tmp);
E
Eric Blake 已提交
3553
    VIR_FREE(tmp);
3554

3555
    if (qemuDomainObjEndJob(driver, vm) == 0)
3556 3557 3558 3559
        vm = NULL;

cleanup:
    if (vm)
3560
        virObjectUnlock(vm);
3561
    virObjectUnref(cfg);
3562 3563 3564
    return ret;
}

H
Hu Tao 已提交
3565 3566 3567
static void processWatchdogEvent(void *data, void *opaque)
{
    int ret;
3568
    struct qemuDomainWatchdogEvent *wdEvent = data;
3569
    virQEMUDriverPtr driver = opaque;
3570
    virQEMUDriverConfigPtr cfg;
H
Hu Tao 已提交
3571

3572
    virObjectLock(wdEvent->vm);
3573
    cfg = virQEMUDriverGetConfig(driver);
W
Wen Congyang 已提交
3574

H
Hu Tao 已提交
3575 3576 3577 3578
    switch (wdEvent->action) {
    case VIR_DOMAIN_WATCHDOG_ACTION_DUMP:
        {
            char *dumpfile;
3579
            unsigned int flags = 0;
H
Hu Tao 已提交
3580

E
Eric Blake 已提交
3581
            if (virAsprintf(&dumpfile, "%s/%s-%u",
3582
                            cfg->autoDumpPath,
H
Hu Tao 已提交
3583
                            wdEvent->vm->def->name,
E
Eric Blake 已提交
3584 3585
                            (unsigned int)time(NULL)) < 0) {
                virReportOOMError();
W
Wen Congyang 已提交
3586
                goto unlock;
E
Eric Blake 已提交
3587
            }
H
Hu Tao 已提交
3588

3589
            if (qemuDomainObjBeginAsyncJob(driver, wdEvent->vm,
3590
                                                     QEMU_ASYNC_JOB_DUMP) < 0) {
W
Wen Congyang 已提交
3591 3592 3593
                VIR_FREE(dumpfile);
                goto unlock;
            }
H
Hu Tao 已提交
3594 3595

            if (!virDomainObjIsActive(wdEvent->vm)) {
3596 3597
                virReportError(VIR_ERR_OPERATION_INVALID,
                               "%s", _("domain is not running"));
W
Wen Congyang 已提交
3598 3599
                VIR_FREE(dumpfile);
                goto endjob;
H
Hu Tao 已提交
3600 3601
            }

3602
            flags |= cfg->autoDumpBypassCache ? VIR_DUMP_BYPASS_CACHE: 0;
3603
            ret = doCoreDump(driver, wdEvent->vm, dumpfile,
3604
                             getCompressionType(driver), flags);
H
Hu Tao 已提交
3605
            if (ret < 0)
3606 3607
                virReportError(VIR_ERR_OPERATION_FAILED,
                               "%s", _("Dump failed"));
H
Hu Tao 已提交
3608

J
Jiri Denemark 已提交
3609
            ret = qemuProcessStartCPUs(driver, wdEvent->vm, NULL,
3610 3611
                                       VIR_DOMAIN_RUNNING_UNPAUSED,
                                       QEMU_ASYNC_JOB_DUMP);
H
Hu Tao 已提交
3612 3613

            if (ret < 0)
3614 3615
                virReportError(VIR_ERR_OPERATION_FAILED,
                               "%s", _("Resuming after dump failed"));
H
Hu Tao 已提交
3616 3617 3618 3619

            VIR_FREE(dumpfile);
        }
        break;
W
Wen Congyang 已提交
3620 3621
    default:
        goto unlock;
H
Hu Tao 已提交
3622 3623
    }

W
Wen Congyang 已提交
3624 3625 3626 3627
endjob:
    /* Safe to ignore value since ref count was incremented in
     * qemuProcessHandleWatchdog().
     */
3628
    ignore_value(qemuDomainObjEndAsyncJob(driver, wdEvent->vm));
W
Wen Congyang 已提交
3629 3630

unlock:
3631
    virObjectUnlock(wdEvent->vm);
3632
    virObjectUnref(wdEvent->vm);
H
Hu Tao 已提交
3633
    VIR_FREE(wdEvent);
3634
    virObjectUnref(cfg);
H
Hu Tao 已提交
3635
}
P
Paolo Bonzini 已提交
3636

3637
static int qemuDomainHotplugVcpus(virQEMUDriverPtr driver,
3638 3639
                                  virDomainObjPtr vm,
                                  unsigned int nvcpus)
3640 3641
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
3642
    int i, rc = 1;
3643
    int ret = -1;
3644
    int oldvcpus = vm->def->vcpus;
E
Eric Blake 已提交
3645
    int vcpus = oldvcpus;
3646 3647
    pid_t *cpupids = NULL;
    int ncpupids;
3648
    virCgroupPtr cgroup_vcpu = NULL;
3649

3650
    qemuDomainObjEnterMonitor(driver, vm);
3651

3652 3653 3654
    /* 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 已提交
3655
    if (nvcpus > vcpus) {
3656
        for (i = vcpus; i < nvcpus; i++) {
3657
            /* Online new CPU */
3658
            rc = qemuMonitorSetCPU(priv->mon, i, true);
3659 3660 3661 3662 3663
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
3664
            vcpus++;
3665 3666
        }
    } else {
3667
        for (i = vcpus - 1; i >= nvcpus; i--) {
3668
            /* Offline old CPU */
3669
            rc = qemuMonitorSetCPU(priv->mon, i, false);
3670 3671 3672 3673 3674
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

E
Eric Blake 已提交
3675
            vcpus--;
3676 3677 3678
        }
    }

3679 3680
    /* hotplug succeeded */

3681 3682
    ret = 0;

3683 3684 3685 3686 3687 3688 3689 3690 3691 3692
    /* After hotplugging the CPUs we need to re-detect threads corresponding
     * to the virtual CPUs. Some older versions don't provide the thread ID
     * or don't have the "info cpus" command (and they don't support multiple
     * CPUs anyways), so errors in the re-detection will not be treated
     * fatal */
    if ((ncpupids = qemuMonitorGetCPUInfo(priv->mon, &cpupids)) <= 0) {
        virResetLastError();
        goto cleanup;
    }

3693 3694 3695 3696 3697 3698 3699 3700 3701
    /* check if hotplug has failed */
    if (vcpus < oldvcpus && ncpupids == oldvcpus) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("qemu didn't unplug the vCPUs properly"));
        vcpus = oldvcpus;
        ret = -1;
        goto cleanup;
    }

3702
    if (ncpupids != vcpus) {
3703 3704 3705 3706
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("got wrong number of vCPU pids from QEMU monitor. "
                         "got %d, wanted %d"),
                       ncpupids, vcpus);
3707 3708 3709 3710
        ret = -1;
        goto cleanup;
    }

3711 3712
    if (nvcpus > oldvcpus) {
        for (i = oldvcpus; i < nvcpus; i++) {
3713
            if (priv->cgroup) {
3714
                int rv = -1;
3715
                /* Create cgroup for the onlined vcpu */
3716
                rv = virCgroupNewVcpu(priv->cgroup, i, true, &cgroup_vcpu);
3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733
                if (rv < 0) {
                    virReportSystemError(-rv,
                                         _("Unable to create vcpu cgroup for %s(vcpu:"
                                           " %d)"),
                                         vm->def->name, i);
                    goto cleanup;
                }

                /* Add vcpu thread to the cgroup */
                rv = virCgroupAddTask(cgroup_vcpu, cpupids[i]);
                if (rv < 0) {
                    virReportSystemError(-rv,
                                         _("unable to add vcpu %d task %d to cgroup"),
                                         i, cpupids[i]);
                    virCgroupRemove(cgroup_vcpu);
                    goto cleanup;
                }
3734
            }
3735

3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758
            /* Inherit def->cpuset */
            if (vm->def->cpumask) {
                /* vm->def->cputune.vcpupin can't be NULL if
                 * vm->def->cpumask is not NULL.
                 */
                virDomainVcpuPinDefPtr vcpupin = NULL;

                if (VIR_REALLOC_N(vm->def->cputune.vcpupin,
                                  vm->def->cputune.nvcpupin + 1) < 0) {
                    virReportOOMError();
                    goto cleanup;
                }

                if (VIR_ALLOC(vcpupin) < 0) {
                    virReportOOMError();
                    goto cleanup;
                }

                vcpupin->cpumask = virBitmapNew(VIR_DOMAIN_CPUMASK_LEN);
                virBitmapCopy(vcpupin->cpumask, vm->def->cpumask);
                vcpupin->vcpuid = i;
                vm->def->cputune.vcpupin[vm->def->cputune.nvcpupin++] = vcpupin;

3759
                if (cgroup_vcpu) {
3760 3761 3762 3763 3764 3765 3766 3767 3768 3769
                    if (qemuSetupCgroupVcpuPin(cgroup_vcpu,
                                               vm->def->cputune.vcpupin,
                                               vm->def->cputune.nvcpupin, i) < 0) {
                        virReportError(VIR_ERR_OPERATION_INVALID,
                                       _("failed to set cpuset.cpus in cgroup"
                                         " for vcpu %d"), i);
                        ret = -1;
                        goto cleanup;
                    }
                } else {
3770 3771
                    if (virProcessSetAffinity(cpupids[i],
                                              vcpupin->cpumask) < 0) {
3772 3773 3774 3775 3776 3777 3778
                        virReportError(VIR_ERR_SYSTEM_ERROR,
                                       _("failed to set cpu affinity for vcpu %d"),
                                       i);
                        ret = -1;
                        goto cleanup;
                    }
                }
3779
            }
3780 3781

            virCgroupFree(&cgroup_vcpu);
G
Guido Günther 已提交
3782
        }
3783 3784 3785 3786
    } else {
        for (i = oldvcpus - 1; i >= nvcpus; i--) {
            virDomainVcpuPinDefPtr vcpupin = NULL;

3787
            if (priv->cgroup) {
3788 3789
                int rv = -1;

3790
                rv = virCgroupNewVcpu(priv->cgroup, i, false, &cgroup_vcpu);
3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803
                if (rv < 0) {
                    virReportSystemError(-rv,
                                         _("Unable to access vcpu cgroup for %s(vcpu:"
                                           " %d)"),
                                         vm->def->name, i);
                    goto cleanup;
                }

                /* Remove cgroup for the offlined vcpu */
                virCgroupRemove(cgroup_vcpu);
                virCgroupFree(&cgroup_vcpu);
            }

3804 3805 3806 3807 3808
            /* Free vcpupin setting */
            if ((vcpupin = virDomainLookupVcpuPin(vm->def, i))) {
                VIR_FREE(vcpupin);
            }
        }
3809 3810
    }

3811 3812 3813 3814 3815
    priv->nvcpupids = ncpupids;
    VIR_FREE(priv->vcpupids);
    priv->vcpupids = cpupids;
    cpupids = NULL;

3816
cleanup:
3817
    qemuDomainObjExitMonitor(driver, vm);
E
Eric Blake 已提交
3818
    vm->def->vcpus = vcpus;
3819
    VIR_FREE(cpupids);
3820
    virDomainAuditVcpu(vm, oldvcpus, nvcpus, "update", rc == 1);
3821 3822
    if (cgroup_vcpu)
        virCgroupFree(&cgroup_vcpu);
3823 3824 3825
    return ret;

unsupported:
3826 3827
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("cannot change vcpu count of this domain"));
3828 3829 3830 3831
    goto cleanup;
}


3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893
static int
qemuDomainPrepareAgentVCPUs(unsigned int nvcpus,
                            qemuAgentCPUInfoPtr cpuinfo,
                            int ncpuinfo)
{
    int i;
    int nonline = 0;
    int nofflinable = 0;

    /* count the active and offlinable cpus */
    for (i = 0; i < ncpuinfo; i++) {
        if (cpuinfo[i].online)
            nonline++;

        if (cpuinfo[i].offlinable && cpuinfo[i].online)
            nofflinable++;

        /* This shouldn't happen, but we can't trust the guest agent */
        if (!cpuinfo[i].online && !cpuinfo[i].offlinable) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Invalid data provided by guest agent"));
            return -1;
        }
    }

    /* the guest agent reported less cpus than requested */
    if (nvcpus > ncpuinfo) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest agent reports less cpu than requested"));
        return -1;
    }

    /* not enough offlinable CPUs to support the request */
    if (nvcpus < nonline - nofflinable) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Cannot offline enough CPUs"));
        return -1;
    }

    for (i = 0; i < ncpuinfo; i++) {
        if (nvcpus < nonline) {
            /* unplug */
            if (cpuinfo[i].offlinable && cpuinfo[i].online) {
                cpuinfo[i].online = false;
                nonline--;
            }
        } else if (nvcpus > nonline) {
            /* plug */
            if (!cpuinfo[i].online) {
                cpuinfo[i].online = true;
                nonline++;
            }
        } else {
            /* done */
            break;
        }
    }

    return 0;
}


3894
static int
3895 3896
qemuDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                        unsigned int flags)
3897
{
3898
    virQEMUDriverPtr driver = dom->conn->privateData;
3899
    virDomainObjPtr vm = NULL;
3900
    virDomainDefPtr persistentDef;
3901
    int ret = -1;
3902
    bool maximum;
3903
    virQEMUDriverConfigPtr cfg = NULL;
3904
    virCapsPtr caps = NULL;
3905 3906 3907
    qemuAgentCPUInfoPtr cpuinfo = NULL;
    int ncpuinfo;
    qemuDomainObjPrivatePtr priv;
3908

3909 3910
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
3911
                  VIR_DOMAIN_VCPU_MAXIMUM |
3912
                  VIR_DOMAIN_VCPU_GUEST, -1);
3913 3914

    if (!nvcpus || (unsigned short) nvcpus != nvcpus) {
3915 3916
        virReportError(VIR_ERR_INVALID_ARG,
                       _("argument out of range: %d"), nvcpus);
3917 3918 3919
        return -1;
    }

3920 3921 3922
    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;

3923
    cfg = virQEMUDriverGetConfig(driver);
3924 3925

    if (virDomainSetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
3926
        goto cleanup;
3927

3928
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
3929
        goto cleanup;
3930

3931 3932
    priv = vm->privateData;

3933
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
3934 3935
        goto cleanup;

3936 3937 3938
    maximum = (flags & VIR_DOMAIN_VCPU_MAXIMUM) != 0;
    flags &= ~VIR_DOMAIN_VCPU_MAXIMUM;

3939
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
3940 3941
                                        &persistentDef) < 0)
        goto endjob;
3942 3943 3944

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

3950
    if (!maximum && nvcpus > vm->def->maxvcpus) {
3951 3952
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
3953 3954
                         " vcpus for the domain: %d > %d"),
                       nvcpus, vm->def->maxvcpus);
3955 3956 3957
        goto endjob;
    }

3958
    if (flags & VIR_DOMAIN_VCPU_GUEST) {
3959 3960 3961 3962
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
            virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                           _("chainging of maximum vCPU count isn't supported "
                             "via guest agent"));
3963
            goto endjob;
3964
        }
3965

3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980
        qemuDomainObjEnterAgent(vm);
        ncpuinfo = qemuAgentGetVCPUs(priv->agent, &cpuinfo);
        qemuDomainObjExitAgent(vm);

        if (ncpuinfo < 0)
            goto endjob;

        if (qemuDomainPrepareAgentVCPUs(nvcpus, cpuinfo, ncpuinfo) < 0)
            goto endjob;

        qemuDomainObjEnterAgent(vm);
        ret = qemuAgentSetVCPUs(priv->agent, cpuinfo, ncpuinfo);
        qemuDomainObjExitAgent(vm);

        if (ret < 0)
3981
            goto endjob;
3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007

        if (ret < ncpuinfo) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("failed to set state of cpu %d via guest agent"),
                           cpuinfo[ret-1].id);
            ret = -1;
            goto endjob;
        }
    } else {
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
            if (qemuDomainHotplugVcpus(driver, vm, nvcpus) < 0)
                goto endjob;
        }

        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
            if (maximum) {
                persistentDef->maxvcpus = nvcpus;
                if (nvcpus < persistentDef->vcpus)
                    persistentDef->vcpus = nvcpus;
            } else {
                persistentDef->vcpus = nvcpus;
            }

            if (virDomainSaveConfig(cfg->configDir, persistentDef) < 0)
                goto endjob;
        }
4008
    }
4009

4010
    ret = 0;
4011

4012
endjob:
4013
    if (qemuDomainObjEndJob(driver, vm) == 0)
4014
        vm = NULL;
4015

4016
cleanup:
4017
    if (vm)
4018
        virObjectUnlock(vm);
4019
    virObjectUnref(caps);
4020
    VIR_FREE(cpuinfo);
4021
    virObjectUnref(cfg);
4022
    return ret;
4023 4024
}

4025
static int
4026
qemuDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
4027
{
4028
    return qemuDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
4029 4030
}

4031 4032

static int
4033 4034 4035 4036 4037
qemuDomainPinVcpuFlags(virDomainPtr dom,
                       unsigned int vcpu,
                       unsigned char *cpumap,
                       int maplen,
                       unsigned int flags) {
4038

4039
    virQEMUDriverPtr driver = dom->conn->privateData;
4040
    virDomainObjPtr vm;
4041
    virDomainDefPtr persistentDef = NULL;
4042
    virCgroupPtr cgroup_vcpu = NULL;
4043
    int ret = -1;
4044
    qemuDomainObjPrivatePtr priv;
4045
    bool doReset = false;
4046 4047
    int newVcpuPinNum = 0;
    virDomainVcpuPinDefPtr *newVcpuPin = NULL;
4048
    virBitmapPtr pcpumap = NULL;
4049
    virQEMUDriverConfigPtr cfg = NULL;
4050
    virCapsPtr caps = NULL;
4051

4052 4053 4054
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

4055 4056
    cfg = virQEMUDriverGetConfig(driver);

4057
    if (!(vm = qemuDomObjFromDomain(dom)))
4058 4059
        goto cleanup;

4060 4061 4062
    if (virDomainPinVcpuFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

4063 4064 4065
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

4066
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
4067
                                        &persistentDef) < 0)
4068
        goto cleanup;
4069

4070 4071 4072
    priv = vm->privateData;

    if (vcpu > (priv->nvcpupids-1)) {
4073 4074 4075
        virReportError(VIR_ERR_INVALID_ARG,
                       _("vcpu number out of range %d > %d"),
                       vcpu, priv->nvcpupids);
4076
        goto cleanup;
4077 4078
    }

4079 4080 4081 4082
    pcpumap = virBitmapNewData(cpumap, maplen);
    if (!pcpumap)
        goto cleanup;

4083 4084 4085 4086 4087 4088
    if (virBitmapIsAllClear(pcpumap)) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Empty cpu list for pinning"));
        goto cleanup;
    }

4089 4090 4091
    /* pinning to all physical cpus means resetting,
     * so check if we can reset setting.
     */
4092 4093
    if (virBitmapIsAllSet(pcpumap))
        doReset = true;
4094

4095
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
4096

4097
        if (priv->vcpupids == NULL) {
4098 4099
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("cpu affinity is not supported"));
4100 4101 4102
            goto cleanup;
        }

4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117
        if (vm->def->cputune.vcpupin) {
            newVcpuPin = virDomainVcpuPinDefCopy(vm->def->cputune.vcpupin,
                                                 vm->def->cputune.nvcpupin);
            if (!newVcpuPin)
                goto cleanup;

            newVcpuPinNum = vm->def->cputune.nvcpupin;
        } else {
            if (VIR_ALLOC(newVcpuPin) < 0) {
                virReportOOMError();
                goto cleanup;
            }
            newVcpuPinNum = 0;
        }

4118
        if (virDomainVcpuPinAdd(&newVcpuPin, &newVcpuPinNum, cpumap, maplen, vcpu) < 0) {
4119 4120
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("failed to update vcpupin"));
H
Hu Tao 已提交
4121
            virDomainVcpuPinDefArrayFree(newVcpuPin, newVcpuPinNum);
4122 4123 4124 4125
            goto cleanup;
        }

        /* Configure the corresponding cpuset cgroup before set affinity. */
4126
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET)) {
4127
            if (virCgroupNewVcpu(priv->cgroup, vcpu, false, &cgroup_vcpu) == 0 &&
4128 4129 4130 4131
                qemuSetupCgroupVcpuPin(cgroup_vcpu, newVcpuPin, newVcpuPinNum, vcpu) < 0) {
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("failed to set cpuset.cpus in cgroup"
                                 " for vcpu %d"), vcpu);
4132 4133 4134
                goto cleanup;
            }
        } else {
4135
            if (virProcessSetAffinity(priv->vcpupids[vcpu], pcpumap) < 0) {
4136 4137 4138 4139
                virReportError(VIR_ERR_SYSTEM_ERROR,
                               _("failed to set cpu affinity for vcpu %d"),
                               vcpu);
                goto cleanup;
H
Hu Tao 已提交
4140
            }
4141 4142
        }

4143
        if (doReset) {
4144
            if (virDomainVcpuPinDel(vm->def, vcpu) < 0) {
4145
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
4146
                               _("failed to delete vcpupin xml of "
4147
                                 "a running domain"));
4148 4149
                goto cleanup;
            }
4150 4151
        } else {
            if (vm->def->cputune.vcpupin)
H
Hu Tao 已提交
4152
                virDomainVcpuPinDefArrayFree(vm->def->cputune.vcpupin, vm->def->cputune.nvcpupin);
4153 4154 4155 4156

            vm->def->cputune.vcpupin = newVcpuPin;
            vm->def->cputune.nvcpupin = newVcpuPinNum;
            newVcpuPin = NULL;
4157 4158
        }

4159
        if (newVcpuPin)
H
Hu Tao 已提交
4160
            virDomainVcpuPinDefArrayFree(newVcpuPin, newVcpuPinNum);
4161

4162
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
4163
            goto cleanup;
4164
    }
4165

4166 4167
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {

4168
        if (doReset) {
E
Eric Blake 已提交
4169
            if (virDomainVcpuPinDel(persistentDef, vcpu) < 0) {
4170 4171 4172
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to delete vcpupin xml of "
                                 "a persistent domain"));
4173 4174 4175
                goto cleanup;
            }
        } else {
H
Hu Tao 已提交
4176 4177 4178 4179 4180 4181 4182
            if (!persistentDef->cputune.vcpupin) {
                if (VIR_ALLOC(persistentDef->cputune.vcpupin) < 0) {
                    virReportOOMError();
                    goto cleanup;
                }
                persistentDef->cputune.nvcpupin = 0;
            }
4183
            if (virDomainVcpuPinAdd(&persistentDef->cputune.vcpupin,
H
Hu Tao 已提交
4184 4185 4186 4187
                                    &persistentDef->cputune.nvcpupin,
                                    cpumap,
                                    maplen,
                                    vcpu) < 0) {
4188 4189 4190
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to update or add vcpupin xml of "
                                 "a persistent domain"));
4191 4192
                goto cleanup;
            }
4193
        }
4194

4195
        ret = virDomainSaveConfig(cfg->configDir, persistentDef);
4196 4197 4198
        goto cleanup;
    }

4199
    ret = 0;
4200

4201
cleanup:
4202 4203
    if (cgroup_vcpu)
        virCgroupFree(&cgroup_vcpu);
4204
    if (vm)
4205
        virObjectUnlock(vm);
4206
    virBitmapFree(pcpumap);
4207
    virObjectUnref(caps);
4208
    virObjectUnref(cfg);
4209
    return ret;
4210 4211
}

4212
static int
4213
qemuDomainPinVcpu(virDomainPtr dom,
4214 4215 4216
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
4217 4218
    return qemuDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                  VIR_DOMAIN_AFFECT_LIVE);
4219 4220
}

4221
static int
4222 4223 4224 4225 4226
qemuDomainGetVcpuPinInfo(virDomainPtr dom,
                         int ncpumaps,
                         unsigned char *cpumaps,
                         int maplen,
                         unsigned int flags) {
4227

4228
    virQEMUDriverPtr driver = dom->conn->privateData;
E
Eric Blake 已提交
4229
    virDomainObjPtr vm = NULL;
4230 4231 4232 4233
    virDomainDefPtr targetDef = NULL;
    int ret = -1;
    int maxcpu, hostcpus, vcpu, pcpu;
    int n;
E
Eric Blake 已提交
4234
    virDomainVcpuPinDefPtr *vcpupin_list;
H
Hu Tao 已提交
4235
    virBitmapPtr cpumask = NULL;
4236
    unsigned char *cpumap;
H
Hu Tao 已提交
4237
    bool pinned;
4238
    virCapsPtr caps = NULL;
4239 4240 4241 4242

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

4243
    if (!(vm = qemuDomObjFromDomain(dom)))
4244 4245
        goto cleanup;

4246 4247 4248
    if (virDomainGetVcpuPinInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4249 4250 4251
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

4252
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
4253 4254
                                        &targetDef) < 0)
        goto cleanup;
4255 4256 4257 4258 4259

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        targetDef = vm->def;
    }

4260 4261 4262
    /* Coverity didn't realize that targetDef must be set if we got here.  */
    sa_assert(targetDef);

4263
    if ((hostcpus = nodeGetCPUCount()) < 0)
4264
        goto cleanup;
4265

4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293
    maxcpu = maplen * 8;
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;

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

    if (ncpumaps < 1) {
        goto cleanup;
    }

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

    /* if vcpupin setting exists, there are unused physical cpus */
    for (n = 0; n < targetDef->cputune.nvcpupin; n++) {
        vcpupin_list = targetDef->cputune.vcpupin;
        vcpu = vcpupin_list[n]->vcpuid;
        cpumask = vcpupin_list[n]->cpumask;
        cpumap = VIR_GET_CPUMAP(cpumaps, maplen, vcpu);
        for (pcpu = 0; pcpu < maxcpu; pcpu++) {
H
Hu Tao 已提交
4294 4295 4296
            if (virBitmapGetBit(cpumask, pcpu, &pinned) < 0)
                goto cleanup;
            if (!pinned)
4297 4298 4299 4300 4301 4302 4303
                VIR_UNUSE_CPU(cpumap, pcpu);
        }
    }
    ret = ncpumaps;

cleanup:
    if (vm)
4304
        virObjectUnlock(vm);
4305
    virObjectUnref(caps);
4306 4307 4308
    return ret;
}

H
Hu Tao 已提交
4309
static int
4310 4311 4312 4313
qemuDomainPinEmulator(virDomainPtr dom,
                      unsigned char *cpumap,
                      int maplen,
                      unsigned int flags)
H
Hu Tao 已提交
4314
{
4315
    virQEMUDriverPtr driver = dom->conn->privateData;
H
Hu Tao 已提交
4316 4317 4318 4319 4320 4321
    virDomainObjPtr vm;
    virCgroupPtr cgroup_emulator = NULL;
    pid_t pid;
    virDomainDefPtr persistentDef = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;
4322
    bool doReset = false;
H
Hu Tao 已提交
4323 4324
    int newVcpuPinNum = 0;
    virDomainVcpuPinDefPtr *newVcpuPin = NULL;
4325
    virBitmapPtr pcpumap = NULL;
4326
    virQEMUDriverConfigPtr cfg = NULL;
4327
    virCapsPtr caps = NULL;
H
Hu Tao 已提交
4328 4329 4330 4331

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

4332 4333
    cfg = virQEMUDriverGetConfig(driver);

4334
    if (!(vm = qemuDomObjFromDomain(dom)))
H
Hu Tao 已提交
4335 4336
        goto cleanup;

4337 4338 4339
    if (virDomainPinEmulatorEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

4340 4341 4342
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

4343 4344 4345 4346 4347 4348 4349
    if (vm->def->placement_mode == VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Changing affinity for emulator thread dynamically "
                         "is not allowed when CPU placement is 'auto'"));
        goto cleanup;
    }

4350
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
H
Hu Tao 已提交
4351 4352 4353 4354 4355
                                        &persistentDef) < 0)
        goto cleanup;

    priv = vm->privateData;

4356 4357 4358 4359
    pcpumap = virBitmapNewData(cpumap, maplen);
    if (!pcpumap)
        goto cleanup;

4360 4361 4362 4363 4364 4365
    if (virBitmapIsAllClear(pcpumap)) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Empty cpu list for pinning"));
        goto cleanup;
    }

H
Hu Tao 已提交
4366 4367 4368
    /* pinning to all physical cpus means resetting,
     * so check if we can reset setting.
     */
4369 4370
    if (virBitmapIsAllSet(pcpumap))
        doReset = true;
H
Hu Tao 已提交
4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381

    pid = vm->pid;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {

        if (priv->vcpupids != NULL) {
            if (VIR_ALLOC(newVcpuPin) < 0) {
                virReportOOMError();
                goto cleanup;
            }

4382
            if (virDomainVcpuPinAdd(&newVcpuPin, &newVcpuPinNum, cpumap, maplen, -1) < 0) {
H
Hu Tao 已提交
4383 4384
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to update vcpupin"));
H
Hu Tao 已提交
4385
                virDomainVcpuPinDefArrayFree(newVcpuPin, newVcpuPinNum);
H
Hu Tao 已提交
4386 4387 4388
                goto cleanup;
            }

4389 4390
            if (virCgroupHasController(priv->cgroup,
                                       VIR_CGROUP_CONTROLLER_CPUSET)) {
H
Hu Tao 已提交
4391 4392 4393 4394
                /*
                 * Configure the corresponding cpuset cgroup.
                 * If no cgroup for domain or hypervisor exists, do nothing.
                 */
4395
                if (virCgroupNewEmulator(priv->cgroup, false, &cgroup_emulator) == 0) {
4396 4397 4398 4399 4400 4401
                    if (qemuSetupCgroupEmulatorPin(cgroup_emulator,
                                                   newVcpuPin[0]->cpumask) < 0) {
                        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                       _("failed to set cpuset.cpus in cgroup"
                                         " for emulator threads"));
                        goto cleanup;
H
Hu Tao 已提交
4402 4403 4404
                    }
                }
            } else {
4405
                if (virProcessSetAffinity(pid, pcpumap) < 0) {
H
Hu Tao 已提交
4406 4407 4408 4409 4410 4411 4412
                    virReportError(VIR_ERR_SYSTEM_ERROR, "%s",
                                   _("failed to set cpu affinity for "
                                     "emulator threads"));
                    goto cleanup;
                }
            }

4413
            if (doReset) {
H
Hu Tao 已提交
4414 4415 4416 4417 4418 4419 4420
                if (virDomainEmulatorPinDel(vm->def) < 0) {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("failed to delete emulatorpin xml of "
                                     "a running domain"));
                    goto cleanup;
                }
            } else {
H
Hu Tao 已提交
4421
                virDomainVcpuPinDefFree(vm->def->cputune.emulatorpin);
H
Hu Tao 已提交
4422 4423 4424 4425 4426
                vm->def->cputune.emulatorpin = newVcpuPin[0];
                VIR_FREE(newVcpuPin);
            }

            if (newVcpuPin)
H
Hu Tao 已提交
4427
                virDomainVcpuPinDefArrayFree(newVcpuPin, newVcpuPinNum);
H
Hu Tao 已提交
4428 4429 4430 4431 4432 4433
        } else {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("cpu affinity is not supported"));
            goto cleanup;
        }

4434
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
H
Hu Tao 已提交
4435 4436 4437 4438 4439
            goto cleanup;
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {

4440
        if (doReset) {
H
Hu Tao 已提交
4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455
            if (virDomainEmulatorPinDel(persistentDef) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to delete emulatorpin xml of "
                                 "a persistent domain"));
                goto cleanup;
            }
        } else {
            if (virDomainEmulatorPinAdd(persistentDef, cpumap, maplen) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to update or add emulatorpin xml "
                                 "of a persistent domain"));
                goto cleanup;
            }
        }

4456
        ret = virDomainSaveConfig(cfg->configDir, persistentDef);
H
Hu Tao 已提交
4457 4458 4459 4460 4461 4462 4463 4464
        goto cleanup;
    }

    ret = 0;

cleanup:
    if (cgroup_emulator)
        virCgroupFree(&cgroup_emulator);
4465
    virBitmapFree(pcpumap);
4466
    virObjectUnref(caps);
H
Hu Tao 已提交
4467
    if (vm)
4468
        virObjectUnlock(vm);
4469
    virObjectUnref(cfg);
H
Hu Tao 已提交
4470 4471 4472 4473
    return ret;
}

static int
4474 4475 4476 4477
qemuDomainGetEmulatorPinInfo(virDomainPtr dom,
                             unsigned char *cpumaps,
                             int maplen,
                             unsigned int flags)
H
Hu Tao 已提交
4478
{
4479
    virQEMUDriverPtr driver = dom->conn->privateData;
H
Hu Tao 已提交
4480 4481 4482 4483
    virDomainObjPtr vm = NULL;
    virDomainDefPtr targetDef = NULL;
    int ret = -1;
    int maxcpu, hostcpus, pcpu;
H
Hu Tao 已提交
4484 4485
    virBitmapPtr cpumask = NULL;
    bool pinned;
4486
    virCapsPtr caps = NULL;
H
Hu Tao 已提交
4487 4488 4489 4490

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

4491
    if (!(vm = qemuDomObjFromDomain(dom)))
H
Hu Tao 已提交
4492 4493
        goto cleanup;

4494 4495 4496
    if (virDomainGetEmulatorPinInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4497 4498 4499
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

4500
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt,
4501
                                        vm, &flags, &targetDef) < 0)
H
Hu Tao 已提交
4502 4503 4504 4505 4506 4507 4508 4509
        goto cleanup;

    if (flags & VIR_DOMAIN_AFFECT_LIVE)
        targetDef = vm->def;

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

4510
    if ((hostcpus = nodeGetCPUCount()) < 0)
H
Hu Tao 已提交
4511
        goto cleanup;
4512

H
Hu Tao 已提交
4513 4514 4515 4516 4517 4518 4519 4520 4521 4522
    maxcpu = maplen * 8;
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;

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

4523 4524 4525 4526 4527
    if (targetDef->cputune.emulatorpin) {
        cpumask = targetDef->cputune.emulatorpin->cpumask;
    } else if (targetDef->cpumask) {
        cpumask = targetDef->cpumask;
    } else {
H
Hu Tao 已提交
4528 4529 4530 4531 4532
        ret = 0;
        goto cleanup;
    }

    for (pcpu = 0; pcpu < maxcpu; pcpu++) {
H
Hu Tao 已提交
4533 4534 4535
        if (virBitmapGetBit(cpumask, pcpu, &pinned) < 0)
            goto cleanup;
        if (!pinned)
H
Hu Tao 已提交
4536 4537 4538 4539 4540 4541 4542
            VIR_UNUSE_CPU(cpumaps, pcpu);
    }

    ret = 1;

cleanup:
    if (vm)
4543
        virObjectUnlock(vm);
4544
    virObjectUnref(caps);
H
Hu Tao 已提交
4545 4546 4547
    return ret;
}

4548
static int
4549 4550 4551 4552 4553
qemuDomainGetVcpus(virDomainPtr dom,
                   virVcpuInfoPtr info,
                   int maxinfo,
                   unsigned char *cpumaps,
                   int maplen) {
4554
    virDomainObjPtr vm;
4555
    int i, v, maxcpu, hostcpus;
4556
    int ret = -1;
4557
    qemuDomainObjPrivatePtr priv;
4558

4559
    if (!(vm = qemuDomObjFromDomain(dom)))
4560 4561
        goto cleanup;

4562 4563 4564
    if (virDomainGetVcpusEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
4565
    if (!virDomainObjIsActive(vm)) {
4566 4567 4568
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s",
                       _("cannot list vcpu pinning for an inactive domain"));
4569
        goto cleanup;
4570 4571
    }

4572 4573
    priv = vm->privateData;

4574
    if ((hostcpus = nodeGetCPUCount()) < 0)
4575
        goto cleanup;
4576 4577

    maxcpu = maplen * 8;
4578 4579
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
4580 4581

    /* Clamp to actual number of vcpus */
4582 4583
    if (maxinfo > priv->nvcpupids)
        maxinfo = priv->nvcpupids;
4584

4585 4586 4587
    if (maxinfo >= 1) {
        if (info != NULL) {
            memset(info, 0, sizeof(*info) * maxinfo);
4588
            for (i = 0; i < maxinfo; i++) {
4589 4590
                info[i].number = i;
                info[i].state = VIR_VCPU_RUNNING;
4591

4592
                if (priv->vcpupids != NULL &&
4593 4594 4595 4596 4597
                    qemuGetProcessInfo(&(info[i].cpuTime),
                                       &(info[i].cpu),
                                       NULL,
                                       vm->pid,
                                       priv->vcpupids[i]) < 0) {
4598
                    virReportSystemError(errno, "%s",
4599 4600 4601
                                         _("cannot get vCPU placement & pCPU time"));
                    goto cleanup;
                }
4602
            }
4603 4604
        }

4605 4606
        if (cpumaps != NULL) {
            memset(cpumaps, 0, maplen * maxinfo);
4607
            if (priv->vcpupids != NULL) {
4608
                for (v = 0; v < maxinfo; v++) {
4609
                    unsigned char *cpumap = VIR_GET_CPUMAP(cpumaps, maplen, v);
4610 4611 4612
                    virBitmapPtr map = NULL;
                    unsigned char *tmpmap = NULL;
                    int tmpmapLen = 0;
4613

4614 4615
                    if (virProcessGetAffinity(priv->vcpupids[v],
                                              &map, maxcpu) < 0)
4616
                        goto cleanup;
4617 4618 4619 4620 4621 4622 4623
                    virBitmapToData(map, &tmpmap, &tmpmapLen);
                    if (tmpmapLen > maplen)
                        tmpmapLen = maplen;
                    memcpy(cpumap, tmpmap, tmpmapLen);

                    VIR_FREE(tmpmap);
                    virBitmapFree(map);
4624
                }
4625
            } else {
4626 4627
                virReportError(VIR_ERR_OPERATION_INVALID,
                               "%s", _("cpu affinity is not available"));
4628
                goto cleanup;
4629 4630 4631
            }
        }
    }
4632
    ret = maxinfo;
4633

4634
cleanup:
4635
    if (vm)
4636
        virObjectUnlock(vm);
4637
    return ret;
4638 4639 4640
}


4641
static int
4642
qemuDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
4643
{
4644
    virQEMUDriverPtr driver = dom->conn->privateData;
4645
    qemuDomainObjPrivatePtr priv;
4646
    virDomainObjPtr vm;
4647
    virDomainDefPtr def;
4648
    int ret = -1;
4649
    virCapsPtr caps = NULL;
4650
    qemuAgentCPUInfoPtr cpuinfo = NULL;
4651
    int ncpuinfo = -1;
4652
    int i;
4653

4654 4655
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
4656
                  VIR_DOMAIN_VCPU_MAXIMUM |
4657
                  VIR_DOMAIN_VCPU_GUEST, -1);
4658

4659
    if (!(vm = qemuDomObjFromDomain(dom)))
4660 4661 4662
        return -1;

    priv = vm->privateData;
4663

4664 4665 4666
    if (virDomainGetVcpusFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4667 4668 4669
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

4670
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt,
4671
                                        vm, &flags, &def) < 0)
4672
        goto cleanup;
4673

4674
    if (flags & VIR_DOMAIN_AFFECT_LIVE)
4675
        def = vm->def;
4676

4677
    if (flags & VIR_DOMAIN_VCPU_GUEST) {
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
        if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("vCPU count provided by the guest agent can only be "
                             " requested for live domains"));
            goto cleanup;
        }

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

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

        qemuDomainObjEnterAgent(vm);
        ncpuinfo = qemuAgentGetVCPUs(priv->agent, &cpuinfo);
        qemuDomainObjExitAgent(vm);

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

        if (ncpuinfo < 0)
            goto cleanup;

        if (flags & VIR_DOMAIN_VCPU_MAXIMUM) {
            ret = ncpuinfo;
            goto cleanup;
        }

        /* count the online vcpus */
        ret = 0;
        for (i = 0; i < ncpuinfo; i++) {
            if (cpuinfo[i].online)
                ret++;
        }
    } else {
        if (flags & VIR_DOMAIN_VCPU_MAXIMUM)
            ret = def->maxvcpus;
        else
            ret = def->vcpus;
4721 4722 4723
    }


4724
cleanup:
4725
    if (vm)
4726
        virObjectUnlock(vm);
4727
    virObjectUnref(caps);
4728
    VIR_FREE(cpuinfo);
4729 4730 4731
    return ret;
}

4732
static int
4733
qemuDomainGetMaxVcpus(virDomainPtr dom)
4734
{
4735 4736
    return qemuDomainGetVcpusFlags(dom, (VIR_DOMAIN_AFFECT_LIVE |
                                         VIR_DOMAIN_VCPU_MAXIMUM));
4737 4738
}

4739
static int qemuDomainGetSecurityLabel(virDomainPtr dom, virSecurityLabelPtr seclabel)
4740
{
4741
    virQEMUDriverPtr driver = dom->conn->privateData;
4742 4743 4744
    virDomainObjPtr vm;
    int ret = -1;

4745 4746
    memset(seclabel, 0, sizeof(*seclabel));

4747 4748
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
4749

4750 4751 4752
    if (virDomainGetSecurityLabelEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4753
    if (!virDomainVirtTypeToString(vm->def->virtType)) {
4754 4755 4756
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown virt type in domain definition '%d'"),
                       vm->def->virtType);
4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773
        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 已提交
4774
    if (virDomainObjIsActive(vm)) {
4775
        if (virSecurityManagerGetProcessLabel(driver->securityManager,
4776
                                              vm->def, vm->pid, seclabel) < 0) {
4777 4778
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Failed to get security label"));
4779
            goto cleanup;
4780 4781 4782 4783 4784 4785 4786
        }
    }

    ret = 0;

cleanup:
    if (vm)
4787
        virObjectUnlock(vm);
4788 4789 4790
    return ret;
}

M
Marcelo Cerri 已提交
4791 4792 4793
static int qemuDomainGetSecurityLabelList(virDomainPtr dom,
                                          virSecurityLabelPtr* seclabels)
{
4794
    virQEMUDriverPtr driver = dom->conn->privateData;
M
Marcelo Cerri 已提交
4795 4796 4797
    virDomainObjPtr vm;
    int i, ret = -1;

4798 4799
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
M
Marcelo Cerri 已提交
4800

4801 4802 4803
    if (virDomainGetSecurityLabelListEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

M
Marcelo Cerri 已提交
4804 4805 4806 4807 4808 4809 4810 4811
    if (!virDomainVirtTypeToString(vm->def->virtType)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown virt type in domain definition '%d'"),
                       vm->def->virtType);
        goto cleanup;
    }

    /*
4812
     * Check the comment in qemuDomainGetSecurityLabel function.
M
Marcelo Cerri 已提交
4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852
     */
    if (!virDomainObjIsActive(vm)) {
        /* No seclabels */
        *seclabels = NULL;
        ret = 0;
    } else {
        int len = 0;
        virSecurityManagerPtr* mgrs = virSecurityManagerGetNested(
                                            driver->securityManager);
        if (!mgrs)
            goto cleanup;

        /* Allocate seclabels array */
        for (i = 0; mgrs[i]; i++)
            len++;

        if (VIR_ALLOC_N((*seclabels), len) < 0) {
            virReportOOMError();
            VIR_FREE(mgrs);
            goto cleanup;
        }
        memset(*seclabels, 0, sizeof(**seclabels) * len);

        /* Fill the array */
        for (i = 0; i < len; i++) {
            if (virSecurityManagerGetProcessLabel(mgrs[i], vm->def, vm->pid,
                                                  &(*seclabels)[i]) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("Failed to get security label"));
                VIR_FREE(mgrs);
                VIR_FREE(*seclabels);
                goto cleanup;
            }
        }
        ret = len;
        VIR_FREE(mgrs);
    }

cleanup:
    if (vm)
4853
        virObjectUnlock(vm);
M
Marcelo Cerri 已提交
4854 4855
    return ret;
}
4856 4857


4858 4859
static int qemuNodeGetSecurityModel(virConnectPtr conn,
                                    virSecurityModelPtr secmodel)
4860
{
4861
    virQEMUDriverPtr driver = conn->privateData;
4862
    char *p;
4863
    int ret = 0;
4864
    virCapsPtr caps = NULL;
4865

4866 4867
    memset(secmodel, 0, sizeof(*secmodel));

4868 4869 4870
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

4871 4872 4873
    if (virNodeGetSecurityModelEnsureACL(conn) < 0)
        goto cleanup;

4874
    /* We treat no driver as success, but simply return no data in *secmodel */
4875 4876
    if (caps->host.nsecModels == 0 ||
        caps->host.secModels[0].model == NULL)
4877
        goto cleanup;
4878

4879
    p = caps->host.secModels[0].model;
4880
    if (strlen(p) >= VIR_SECURITY_MODEL_BUFLEN-1) {
4881 4882 4883
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security model string exceeds max %d bytes"),
                       VIR_SECURITY_MODEL_BUFLEN-1);
4884 4885
        ret = -1;
        goto cleanup;
4886 4887 4888
    }
    strcpy(secmodel->model, p);

4889
    p = caps->host.secModels[0].doi;
4890
    if (strlen(p) >= VIR_SECURITY_DOI_BUFLEN-1) {
4891 4892 4893
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("security DOI string exceeds max %d bytes"),
                       VIR_SECURITY_DOI_BUFLEN-1);
4894 4895
        ret = -1;
        goto cleanup;
4896 4897
    }
    strcpy(secmodel->doi, p);
4898 4899

cleanup:
4900
    virObjectUnref(caps);
4901
    return ret;
4902 4903
}

E
Eric Blake 已提交
4904
/* Return -1 on most failures after raising error, -2 if edit was specified
4905 4906 4907
 * but xmlin and state (-1 for no change, 0 for paused, 1 for running) do
 * not represent any changes (no error raised), -3 if corrupt image was
 * unlinked (no error raised), and opened fd on success.  */
4908
static int ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4)
4909
qemuDomainSaveImageOpen(virQEMUDriverPtr driver,
4910 4911
                        const char *path,
                        virDomainDefPtr *ret_def,
4912
                        virQEMUSaveHeaderPtr ret_header,
J
Jiri Denemark 已提交
4913 4914
                        bool bypass_cache,
                        virFileWrapperFdPtr *wrapperFd,
4915 4916
                        const char *xmlin, int state, bool edit,
                        bool unlink_corrupt)
J
Jiri Denemark 已提交
4917
{
W
Wen Congyang 已提交
4918
    int fd = -1;
4919
    virQEMUSaveHeader header;
J
Jiri Denemark 已提交
4920 4921
    char *xml = NULL;
    virDomainDefPtr def = NULL;
4922
    int oflags = edit ? O_RDWR : O_RDONLY;
4923
    virCapsPtr caps = NULL;
4924

4925
    if (bypass_cache) {
4926
        int directFlag = virFileDirectFdFlag();
4927
        if (directFlag < 0) {
4928 4929
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("bypass cache unsupported by this system"));
4930 4931
            goto error;
        }
4932
        oflags |= directFlag;
4933
    }
4934

4935 4936 4937
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto error;

E
Eric Blake 已提交
4938 4939
    if ((fd = qemuOpenFile(driver, path, oflags, NULL, NULL)) < 0)
        goto error;
J
Jiri Denemark 已提交
4940 4941 4942
    if (bypass_cache &&
        !(*wrapperFd = virFileWrapperFdNew(&fd, path,
                                           VIR_FILE_WRAPPER_BYPASS_CACHE)))
4943
        goto error;
4944 4945

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
4946 4947 4948 4949 4950 4951 4952 4953 4954
        if (unlink_corrupt) {
            if (VIR_CLOSE(fd) < 0 || unlink(path) < 0) {
                virReportSystemError(errno,
                                     _("cannot remove corrupt file: %s"),
                                     path);
                goto error;
            }
            return -3;
        }
4955 4956
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("failed to read qemu header"));
J
Jiri Denemark 已提交
4957
        goto error;
4958 4959
    }

4960
    if (memcmp(header.magic, QEMU_SAVE_MAGIC, sizeof(header.magic)) != 0) {
E
Eric Blake 已提交
4961 4962
        const char *msg = _("image magic is incorrect");

4963
        if (memcmp(header.magic, QEMU_SAVE_PARTIAL,
E
Eric Blake 已提交
4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975
                   sizeof(header.magic)) == 0) {
            msg = _("save image is incomplete");
            if (unlink_corrupt) {
                if (VIR_CLOSE(fd) < 0 || unlink(path) < 0) {
                    virReportSystemError(errno,
                                         _("cannot remove corrupt file: %s"),
                                         path);
                    goto error;
                }
                return -3;
            }
        }
4976
        virReportError(VIR_ERR_OPERATION_FAILED, "%s", msg);
J
Jiri Denemark 已提交
4977
        goto error;
4978 4979
    }

4980
    if (header.version > QEMU_SAVE_VERSION) {
4981 4982 4983 4984
        /* convert endianess and try again */
        bswap_header(&header);
    }

4985
    if (header.version > QEMU_SAVE_VERSION) {
4986 4987
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("image version is not supported (%d > %d)"),
4988
                       header.version, QEMU_SAVE_VERSION);
J
Jiri Denemark 已提交
4989
        goto error;
4990 4991
    }

4992
    if (header.xml_len <= 0) {
4993 4994
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("invalid XML length: %d"), header.xml_len);
J
Jiri Denemark 已提交
4995
        goto error;
4996 4997
    }

4998 4999
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
        virReportOOMError();
J
Jiri Denemark 已提交
5000
        goto error;
5001 5002 5003
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
5004 5005
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("failed to read XML"));
J
Jiri Denemark 已提交
5006
        goto error;
5007 5008
    }

5009 5010
    if (edit && STREQ(xml, xmlin) &&
        (state < 0 || state == header.was_running)) {
5011 5012 5013 5014 5015 5016 5017
        VIR_FREE(xml);
        if (VIR_CLOSE(fd) < 0) {
            virReportSystemError(errno, _("cannot close file: %s"), path);
            goto error;
        }
        return -2;
    }
5018 5019
    if (state >= 0)
        header.was_running = state;
5020

5021
    /* Create a domain from this XML */
5022
    if (!(def = virDomainDefParseString(xml, caps, driver->xmlopt,
M
Matthias Bolte 已提交
5023
                                        QEMU_EXPECTED_VIRT_TYPES,
5024
                                        VIR_DOMAIN_XML_INACTIVE)))
J
Jiri Denemark 已提交
5025
        goto error;
5026 5027
    if (xmlin) {
        virDomainDefPtr def2 = NULL;
5028
        virDomainDefPtr newdef = NULL;
5029

5030
        if (!(def2 = virDomainDefParseString(xmlin, caps, driver->xmlopt,
5031 5032 5033
                                             QEMU_EXPECTED_VIRT_TYPES,
                                             VIR_DOMAIN_XML_INACTIVE)))
            goto error;
5034 5035 5036 5037 5038 5039 5040 5041

        newdef = qemuDomainDefCopy(driver, def2, VIR_DOMAIN_XML_MIGRATABLE);
        virDomainDefFree(def2);
        if (!newdef)
            goto error;

        if (!virDomainDefCheckABIStability(def, newdef)) {
            virDomainDefFree(newdef);
5042 5043 5044
            goto error;
        }
        virDomainDefFree(def);
5045
        def = newdef;
5046
    }
5047

J
Jiri Denemark 已提交
5048
    VIR_FREE(xml);
5049

J
Jiri Denemark 已提交
5050 5051
    *ret_def = def;
    *ret_header = header;
5052

5053 5054
    virObjectUnref(caps);

J
Jiri Denemark 已提交
5055
    return fd;
5056

J
Jiri Denemark 已提交
5057 5058 5059
error:
    virDomainDefFree(def);
    VIR_FREE(xml);
5060
    VIR_FORCE_CLOSE(fd);
5061
    virObjectUnref(caps);
J
Jiri Denemark 已提交
5062 5063 5064 5065

    return -1;
}

5066 5067
static int ATTRIBUTE_NONNULL(4) ATTRIBUTE_NONNULL(5) ATTRIBUTE_NONNULL(6)
qemuDomainSaveImageStartVM(virConnectPtr conn,
5068
                           virQEMUDriverPtr driver,
5069 5070
                           virDomainObjPtr vm,
                           int *fd,
5071
                           const virQEMUSaveHeaderPtr header,
5072 5073
                           const char *path,
                           bool start_paused)
J
Jiri Denemark 已提交
5074 5075 5076 5077
{
    int ret = -1;
    virDomainEventPtr event;
    int intermediatefd = -1;
5078
    virCommandPtr cmd = NULL;
5079
    char *errbuf = NULL;
5080
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
J
Jiri Denemark 已提交
5081

5082 5083 5084
    if ((header->version == 2) &&
        (header->compressed != QEMU_SAVE_FORMAT_RAW)) {
        if (!(cmd = qemuCompressGetCommand(header->compressed)))
5085
            goto cleanup;
5086

5087 5088
        intermediatefd = *fd;
        *fd = -1;
5089

5090 5091 5092 5093
        virCommandSetInputFD(cmd, intermediatefd);
        virCommandSetOutputFD(cmd, fd);
        virCommandSetErrorBuffer(cmd, &errbuf);
        virCommandDoAsyncIO(cmd);
5094

5095 5096 5097
        if (virCommandRunAsync(cmd, NULL) < 0) {
            *fd = intermediatefd;
            goto cleanup;
5098 5099
        }
    }
J
Jiri Denemark 已提交
5100

5101
    /* Set the migration source and start it up. */
5102 5103 5104
    ret = qemuProcessStart(conn, driver, vm, "stdio", *fd, path, NULL,
                           VIR_NETDEV_VPORT_PROFILE_OP_RESTORE,
                           VIR_QEMU_PROCESS_START_PAUSED);
J
Jiri Denemark 已提交
5105

5106
    if (intermediatefd != -1) {
5107
        if (ret < 0) {
5108 5109 5110
            /* if there was an error setting up qemu, the intermediate
             * process will wait forever to write to stdout, so we
             * must manually kill it.
5111 5112
             */
            VIR_FORCE_CLOSE(intermediatefd);
5113
            VIR_FORCE_CLOSE(*fd);
5114 5115
        }

5116 5117
        if (virCommandWait(cmd, NULL) < 0) {
            qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FAILED, 0);
5118
            ret = -1;
5119
        }
5120
        VIR_DEBUG("Decompression binary stderr: %s", NULLSTR(errbuf));
5121
    }
5122
    VIR_FORCE_CLOSE(intermediatefd);
J
Jiri Denemark 已提交
5123

5124 5125 5126
    if (VIR_CLOSE(*fd) < 0) {
        virReportSystemError(errno, _("cannot close file: %s"), path);
        ret = -1;
5127
    }
J
Jiri Denemark 已提交
5128

5129
    if (ret < 0) {
5130
        virDomainAuditStart(vm, "restored", false);
5131
        goto cleanup;
5132
    }
5133

5134 5135 5136
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
5137
    virDomainAuditStart(vm, "restored", true);
J
Jiri Denemark 已提交
5138 5139 5140
    if (event)
        qemuDomainEventQueue(driver, event);

5141

5142 5143
    /* If it was running before, resume it now unless caller requested pause. */
    if (header->was_running && !start_paused) {
J
Jiri Denemark 已提交
5144
        if (qemuProcessStartCPUs(driver, vm, conn,
5145 5146
                                 VIR_DOMAIN_RUNNING_RESTORED,
                                 QEMU_ASYNC_JOB_NONE) < 0) {
5147
            if (virGetLastError() == NULL)
5148 5149
                virReportError(VIR_ERR_OPERATION_FAILED,
                               "%s", _("failed to resume domain"));
5150
            goto cleanup;
5151
        }
5152
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0) {
5153
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
5154
            goto cleanup;
5155
        }
5156 5157 5158 5159 5160 5161 5162 5163
    } else {
        int detail = (start_paused ? VIR_DOMAIN_EVENT_SUSPENDED_PAUSED :
                      VIR_DOMAIN_EVENT_SUSPENDED_RESTORED);
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         detail);
        if (event)
            qemuDomainEventQueue(driver, event);
5164
    }
J
Jiri Denemark 已提交
5165

5166
    ret = 0;
5167

5168
cleanup:
5169
    virCommandFree(cmd);
5170
    VIR_FREE(errbuf);
5171
    if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
5172
                                                 vm->def, path) < 0)
5173
        VIR_WARN("failed to restore save state label on %s", path);
5174
    virObjectUnref(cfg);
J
Jiri Denemark 已提交
5175 5176 5177
    return ret;
}

5178
static int
5179 5180 5181 5182
qemuDomainRestoreFlags(virConnectPtr conn,
                       const char *path,
                       const char *dxml,
                       unsigned int flags)
5183
{
5184
    virQEMUDriverPtr driver = conn->privateData;
J
Jiri Denemark 已提交
5185 5186 5187 5188
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    int fd = -1;
    int ret = -1;
5189
    virQEMUSaveHeader header;
J
Jiri Denemark 已提交
5190
    virFileWrapperFdPtr wrapperFd = NULL;
5191
    int state = -1;
J
Jiri Denemark 已提交
5192

5193 5194 5195
    virCheckFlags(VIR_DOMAIN_SAVE_BYPASS_CACHE |
                  VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
5196

J
Jiri Denemark 已提交
5197

5198 5199 5200 5201 5202
    if (flags & VIR_DOMAIN_SAVE_RUNNING)
        state = 1;
    else if (flags & VIR_DOMAIN_SAVE_PAUSED)
        state = 0;

5203 5204
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header,
                                 (flags & VIR_DOMAIN_SAVE_BYPASS_CACHE) != 0,
J
Jiri Denemark 已提交
5205
                                 &wrapperFd, dxml, state, false, false);
J
Jiri Denemark 已提交
5206 5207 5208
    if (fd < 0)
        goto cleanup;

5209 5210 5211
    if (virDomainRestoreFlagsEnsureACL(conn, def) < 0)
        goto cleanup;

5212
    if (!(vm = virDomainObjListAdd(driver->domains, def,
5213
                                   driver->xmlopt,
5214 5215 5216
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
J
Jiri Denemark 已提交
5217 5218 5219
        goto cleanup;
    def = NULL;

5220
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
J
Jiri Denemark 已提交
5221 5222
        goto cleanup;

5223 5224
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path,
                                     false);
J
Jiri Denemark 已提交
5225
    if (virFileWrapperFdClose(wrapperFd) < 0)
5226
        VIR_WARN("Failed to close %s", path);
J
Jiri Denemark 已提交
5227

5228
    if (qemuDomainObjEndJob(driver, vm) == 0)
5229
        vm = NULL;
J
Jiri Denemark 已提交
5230
    else if (ret < 0 && !vm->persistent) {
5231
        qemuDomainRemoveInactive(driver, vm);
J
Jiri Denemark 已提交
5232 5233
        vm = NULL;
    }
5234

5235 5236
cleanup:
    virDomainDefFree(def);
5237
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
5238
    virFileWrapperFdFree(wrapperFd);
5239
    if (vm)
5240
        virObjectUnlock(vm);
5241
    return ret;
D
Daniel P. Berrange 已提交
5242 5243
}

5244 5245 5246 5247 5248 5249 5250
static int
qemuDomainRestore(virConnectPtr conn,
                  const char *path)
{
    return qemuDomainRestoreFlags(conn, path, NULL, 0);
}

5251 5252 5253 5254
static char *
qemuDomainSaveImageGetXMLDesc(virConnectPtr conn, const char *path,
                              unsigned int flags)
{
5255
    virQEMUDriverPtr driver = conn->privateData;
5256 5257 5258
    char *ret = NULL;
    virDomainDefPtr def = NULL;
    int fd = -1;
5259
    virQEMUSaveHeader header;
5260 5261 5262 5263 5264

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

    fd = qemuDomainSaveImageOpen(driver, path, &def, &header, false, NULL,
5265
                                 NULL, -1, false, false);
5266 5267 5268 5269

    if (fd < 0)
        goto cleanup;

5270 5271 5272
    if (virDomainSaveImageGetXMLDescEnsureACL(conn, def) < 0)
        goto cleanup;

5273
    ret = qemuDomainDefFormatXML(driver, def, flags);
5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284

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

static int
qemuDomainSaveImageDefineXML(virConnectPtr conn, const char *path,
                             const char *dxml, unsigned int flags)
{
5285
    virQEMUDriverPtr driver = conn->privateData;
5286 5287 5288
    int ret = -1;
    virDomainDefPtr def = NULL;
    int fd = -1;
5289
    virQEMUSaveHeader header;
5290 5291
    char *xml = NULL;
    size_t len;
5292
    int state = -1;
5293

5294 5295
    virCheckFlags(VIR_DOMAIN_SAVE_RUNNING |
                  VIR_DOMAIN_SAVE_PAUSED, -1);
5296

5297 5298 5299 5300 5301
    if (flags & VIR_DOMAIN_SAVE_RUNNING)
        state = 1;
    else if (flags & VIR_DOMAIN_SAVE_PAUSED)
        state = 0;

5302
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header, false, NULL,
5303
                                 dxml, state, true, false);
5304 5305 5306 5307 5308 5309 5310 5311

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

5312 5313 5314
    if (virDomainSaveImageDefineXMLEnsureACL(conn, def) < 0)
        goto cleanup;

5315 5316
    xml = qemuDomainDefFormatXML(driver, def,
                                 VIR_DOMAIN_XML_INACTIVE |
5317 5318
                                 VIR_DOMAIN_XML_SECURE |
                                 VIR_DOMAIN_XML_MIGRATABLE);
5319 5320 5321 5322 5323
    if (!xml)
        goto cleanup;
    len = strlen(xml) + 1;

    if (len > header.xml_len) {
5324 5325
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("new xml too large to fit in file"));
5326 5327 5328 5329 5330 5331 5332
        goto cleanup;
    }
    if (VIR_EXPAND_N(xml, len, header.xml_len - len) < 0) {
        virReportOOMError();
        goto cleanup;
    }

5333
    if (lseek(fd, 0, SEEK_SET) != 0) {
5334 5335 5336
        virReportSystemError(errno, _("cannot seek in '%s'"), path);
        goto cleanup;
    }
5337 5338
    if (safewrite(fd, &header, sizeof(header)) != sizeof(header) ||
        safewrite(fd, xml, len) != len ||
5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352
        VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("failed to write xml to '%s'"), path);
        goto cleanup;
    }

    ret = 0;

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

E
Eric Blake 已提交
5353 5354
/* Return 0 on success, 1 if incomplete saved image was silently unlinked,
 * and -1 on failure with error raised.  */
5355 5356
static int
qemuDomainObjRestore(virConnectPtr conn,
5357
                     virQEMUDriverPtr driver,
5358
                     virDomainObjPtr vm,
5359
                     const char *path,
5360
                     bool start_paused,
5361
                     bool bypass_cache)
J
Jiri Denemark 已提交
5362 5363 5364 5365
{
    virDomainDefPtr def = NULL;
    int fd = -1;
    int ret = -1;
5366
    virQEMUSaveHeader header;
J
Jiri Denemark 已提交
5367
    virFileWrapperFdPtr wrapperFd = NULL;
J
Jiri Denemark 已提交
5368

5369
    fd = qemuDomainSaveImageOpen(driver, path, &def, &header,
J
Jiri Denemark 已提交
5370
                                 bypass_cache, &wrapperFd, NULL, -1, false,
5371
                                 true);
E
Eric Blake 已提交
5372 5373 5374
    if (fd < 0) {
        if (fd == -3)
            ret = 1;
J
Jiri Denemark 已提交
5375
        goto cleanup;
E
Eric Blake 已提交
5376
    }
J
Jiri Denemark 已提交
5377 5378 5379 5380 5381 5382 5383

    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);
5384 5385 5386 5387 5388
        virReportError(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);
J
Jiri Denemark 已提交
5389 5390 5391
        goto cleanup;
    }

5392
    virDomainObjAssignDef(vm, def, true, NULL);
J
Jiri Denemark 已提交
5393 5394
    def = NULL;

5395 5396
    ret = qemuDomainSaveImageStartVM(conn, driver, vm, &fd, &header, path,
                                     start_paused);
J
Jiri Denemark 已提交
5397
    if (virFileWrapperFdClose(wrapperFd) < 0)
5398
        VIR_WARN("Failed to close %s", path);
J
Jiri Denemark 已提交
5399 5400 5401

cleanup:
    virDomainDefFree(def);
5402
    VIR_FORCE_CLOSE(fd);
J
Jiri Denemark 已提交
5403
    virFileWrapperFdFree(wrapperFd);
J
Jiri Denemark 已提交
5404 5405 5406
    return ret;
}

D
Daniel P. Berrange 已提交
5407

5408
static char *qemuDomainGetXMLDesc(virDomainPtr dom,
5409 5410
                                  unsigned int flags)
{
5411
    virQEMUDriverPtr driver = dom->conn->privateData;
5412 5413
    virDomainObjPtr vm;
    char *ret = NULL;
5414
    unsigned long long balloon;
5415
    int err = 0;
5416
    qemuDomainObjPrivatePtr priv;
5417

5418
    /* Flags checked by virDomainDefFormat */
5419

5420
    if (!(vm = qemuDomObjFromDomain(dom)))
5421
        goto cleanup;
D
Daniel P. Berrange 已提交
5422

5423 5424
    priv = vm->privateData;

5425 5426 5427
    if (virDomainGetXMLDescEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

5428 5429 5430
    /* Refresh current memory based on balloon info if supported */
    if ((vm->def->memballoon != NULL) &&
        (vm->def->memballoon->model != VIR_DOMAIN_MEMBALLOON_MODEL_NONE) &&
5431
        !virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BALLOON_EVENT) &&
5432
        (virDomainObjIsActive(vm))) {
5433 5434
        /* Don't delay if someone's using the monitor, just use
         * existing most recent data instead */
5435
        if (qemuDomainJobAllowed(priv, QEMU_JOB_QUERY)) {
5436
            if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
5437 5438
                goto cleanup;

5439
            if (!virDomainObjIsActive(vm)) {
5440 5441
                virReportError(VIR_ERR_OPERATION_INVALID,
                               "%s", _("domain is not running"));
5442 5443 5444
                goto endjob;
            }

5445
            qemuDomainObjEnterMonitor(driver, vm);
5446
            err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
5447
            qemuDomainObjExitMonitor(driver, vm);
5448 5449

endjob:
5450
            if (qemuDomainObjEndJob(driver, vm) == 0) {
5451 5452 5453
                vm = NULL;
                goto cleanup;
            }
5454 5455 5456
            if (err < 0)
                goto cleanup;
            if (err > 0)
5457
                vm->def->mem.cur_balloon = balloon;
5458 5459
            /* err == 0 indicates no balloon support, so ignore it */
        }
5460
    }
5461

5462 5463 5464 5465
    if ((flags & VIR_DOMAIN_XML_MIGRATABLE))
        flags |= QEMU_DOMAIN_FORMAT_LIVE_FLAGS;

    ret = qemuDomainFormatXML(driver, vm, flags);
5466 5467

cleanup:
5468
    if (vm)
5469
        virObjectUnlock(vm);
5470
    return ret;
D
Daniel P. Berrange 已提交
5471 5472 5473
}


5474 5475 5476 5477
static char *qemuConnectDomainXMLFromNative(virConnectPtr conn,
                                            const char *format,
                                            const char *config,
                                            unsigned int flags)
E
Eric Blake 已提交
5478
{
5479
    virQEMUDriverPtr driver = conn->privateData;
5480 5481
    virDomainDefPtr def = NULL;
    char *xml = NULL;
5482
    virCapsPtr caps = NULL;
5483

E
Eric Blake 已提交
5484 5485
    virCheckFlags(0, NULL);

5486 5487 5488
    if (virConnectDomainXMLFromNativeEnsureACL(conn) < 0)
        goto cleanup;

5489
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
5490 5491
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), format);
5492 5493 5494
        goto cleanup;
    }

5495 5496 5497
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

5498
    def = qemuParseCommandLineString(caps, driver->xmlopt, config,
5499
                                     NULL, NULL, NULL);
5500 5501 5502
    if (!def)
        goto cleanup;

5503
    if (!def->name && VIR_STRDUP(def->name, "unnamed") < 0)
5504 5505
        goto cleanup;

5506
    xml = qemuDomainDefFormatXML(driver, def, VIR_DOMAIN_XML_INACTIVE);
5507 5508 5509

cleanup:
    virDomainDefFree(def);
5510
    virObjectUnref(caps);
5511 5512 5513
    return xml;
}

5514 5515 5516 5517
static char *qemuConnectDomainXMLToNative(virConnectPtr conn,
                                          const char *format,
                                          const char *xmlData,
                                          unsigned int flags)
E
Eric Blake 已提交
5518
{
5519
    virQEMUDriverPtr driver = conn->privateData;
5520
    virDomainDefPtr def = NULL;
5521
    virDomainChrSourceDef monConfig;
5522
    virQEMUCapsPtr qemuCaps = NULL;
T
tangchen 已提交
5523
    bool monitor_json = false;
E
Eric Blake 已提交
5524
    virCommandPtr cmd = NULL;
5525 5526
    char *ret = NULL;
    int i;
5527
    virQEMUDriverConfigPtr cfg;
5528
    virCapsPtr caps = NULL;
5529

E
Eric Blake 已提交
5530 5531
    virCheckFlags(0, NULL);

5532
    cfg = virQEMUDriverGetConfig(driver);
5533

5534 5535 5536
    if (virConnectDomainXMLToNativeEnsureACL(conn) < 0)
        goto cleanup;

5537
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
5538 5539
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), format);
5540 5541 5542
        goto cleanup;
    }

5543 5544 5545
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

5546
    def = virDomainDefParseString(xmlData, caps, driver->xmlopt,
M
Matthias Bolte 已提交
5547
                                  QEMU_EXPECTED_VIRT_TYPES, 0);
5548 5549 5550
    if (!def)
        goto cleanup;

5551
    if (!(qemuCaps = virQEMUCapsCacheLookup(driver->qemuCapsCache, def->emulator)))
5552 5553
        goto cleanup;

5554 5555
    /* Since we're just exporting args, we can't do bridge/network/direct
     * setups, since libvirt will normally create TAP/macvtap devices
5556 5557 5558
     * directly. We convert those configs into generic 'ethernet'
     * config and assume the user has suitable 'ifup-qemu' scripts
     */
5559
    for (i = 0; i < def->nnets; i++) {
5560
        virDomainNetDefPtr net = def->nets[i];
5561
        int bootIndex = net->info.bootIndex;
5562 5563
        char *model = net->model;

5564 5565 5566 5567
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            int actualType = virDomainNetGetActualType(net);
            const char *brname;

5568
            VIR_FREE(net->data.network.name);
5569 5570 5571 5572
            VIR_FREE(net->data.network.portgroup);
            if ((actualType == VIR_DOMAIN_NET_TYPE_BRIDGE) &&
                (brname = virDomainNetGetActualBridgeName(net))) {

5573 5574
                char *brnamecopy;
                if (VIR_STRDUP(brnamecopy, brname) < 0)
5575 5576 5577 5578
                    goto cleanup;

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

5579
                memset(net, 0, sizeof(*net));
5580 5581

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

                net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
5593
                net->script = NULL;
5594 5595 5596 5597 5598
                net->data.ethernet.dev = NULL;
                net->data.ethernet.ipaddr = NULL;
            }
        } else if (net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
            VIR_FREE(net->data.direct.linkdev);
5599

5600
            memset(net, 0, sizeof(*net));
5601 5602

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
5603
            net->script = NULL;
5604 5605 5606
            net->data.ethernet.dev = NULL;
            net->data.ethernet.ipaddr = NULL;
        } else if (net->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
5607
            char *script = net->script;
5608 5609 5610
            char *brname = net->data.bridge.brname;
            char *ipaddr = net->data.bridge.ipaddr;

5611
            memset(net, 0, sizeof(*net));
5612 5613

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
5614
            net->script = script;
5615 5616 5617
            net->data.ethernet.dev = brname;
            net->data.ethernet.ipaddr = ipaddr;
        }
5618

5619
        VIR_FREE(net->virtPortProfile);
5620
        net->info.bootIndex = bootIndex;
5621
        net->model = model;
5622 5623
    }

5624
    monitor_json = virQEMUCapsGet(qemuCaps, QEMU_CAPS_MONITOR_JSON);
T
tangchen 已提交
5625

5626
    if (qemuProcessPrepareMonitorChr(cfg, &monConfig, def->name) < 0)
5627
        goto cleanup;
5628

5629
    if (qemuAssignDeviceAliases(def, qemuCaps) < 0)
5630 5631
        goto cleanup;

5632 5633 5634
    if (qemuDomainAssignAddresses(def, qemuCaps, NULL) < 0)
        goto cleanup;

5635
    /* do fake auto-alloc of graphics ports, if such config is used */
5636
    for (i = 0; i < def->ngraphics; ++i) {
5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648
        virDomainGraphicsDefPtr graphics = def->graphics[i];
        if (graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
            !graphics->data.vnc.socket && graphics->data.vnc.autoport) {
            graphics->data.vnc.port = 5900;
        } else if (graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE) {
            int j;
            bool needTLSPort = false;
            bool needPort = false;
            int defaultMode = graphics->data.spice.defaultMode;

            if (graphics->data.spice.autoport) {
                /* check if tlsPort or port need allocation */
5649
                for (j = 0; j < VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_LAST; j++) {
5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686
                    switch (graphics->data.spice.channels[j]) {
                    case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_SECURE:
                        needTLSPort = true;
                        break;

                    case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_INSECURE:
                        needPort = true;
                        break;

                    case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_ANY:
                        switch (defaultMode) {
                        case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_SECURE:
                            needTLSPort = true;
                            break;

                        case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_INSECURE:
                            needPort = true;
                            break;

                        case VIR_DOMAIN_GRAPHICS_SPICE_CHANNEL_MODE_ANY:
                            needTLSPort = true;
                            needPort = true;
                            break;
                        }
                        break;
                    }
                }
            }

            if (needPort || graphics->data.spice.port == -1)
                graphics->data.spice.port = 5901;

            if (needTLSPort || graphics->data.spice.tlsPort == -1)
                graphics->data.spice.tlsPort = 5902;
        }
    }

5687
    if (!(cmd = qemuBuildCommandLine(conn, driver, def,
5688
                                     &monConfig, monitor_json, qemuCaps,
5689 5690
                                     NULL, -1, NULL, VIR_NETDEV_VPORT_PROFILE_OP_NO_OP,
                                     &buildCommandLineCallbacks)))
5691 5692
        goto cleanup;

E
Eric Blake 已提交
5693
    ret = virCommandToString(cmd);
5694 5695 5696

cleanup:

5697
    virObjectUnref(qemuCaps);
E
Eric Blake 已提交
5698
    virCommandFree(cmd);
5699
    virDomainDefFree(def);
5700
    virObjectUnref(caps);
5701
    virObjectUnref(cfg);
5702 5703 5704 5705
    return ret;
}


5706 5707
static int qemuConnectListDefinedDomains(virConnectPtr conn,
                                         char **const names, int nnames) {
5708
    virQEMUDriverPtr driver = conn->privateData;
5709
    int ret = -1;
5710

5711 5712 5713 5714 5715 5716 5717
    if (virConnectListDefinedDomainsEnsureACL(conn) < 0)
        goto cleanup;

    ret = virDomainObjListGetInactiveNames(driver->domains, names, nnames);

cleanup:
    return ret;
D
Daniel P. Berrange 已提交
5718 5719
}

5720
static int qemuConnectNumOfDefinedDomains(virConnectPtr conn) {
5721
    virQEMUDriverPtr driver = conn->privateData;
5722 5723 5724 5725
    int ret = -1;

    if (virConnectNumOfDefinedDomainsEnsureACL(conn) < 0)
        goto cleanup;
5726

5727
    ret = virDomainObjListNumOfDomains(driver->domains, 0);
5728

5729 5730
cleanup:
    return ret;
D
Daniel P. Berrange 已提交
5731 5732 5733
}


5734 5735
static int
qemuDomainObjStart(virConnectPtr conn,
5736
                   virQEMUDriverPtr driver,
5737
                   virDomainObjPtr vm,
5738
                   unsigned int flags)
J
Jiri Denemark 已提交
5739 5740 5741
{
    int ret = -1;
    char *managed_save;
5742 5743 5744 5745
    bool start_paused = (flags & VIR_DOMAIN_START_PAUSED) != 0;
    bool autodestroy = (flags & VIR_DOMAIN_START_AUTODESTROY) != 0;
    bool bypass_cache = (flags & VIR_DOMAIN_START_BYPASS_CACHE) != 0;
    bool force_boot = (flags & VIR_DOMAIN_START_FORCE_BOOT) != 0;
5746 5747 5748
    unsigned int start_flags = VIR_QEMU_PROCESS_START_COLD;

    start_flags |= start_paused ? VIR_QEMU_PROCESS_START_PAUSED : 0;
5749
    start_flags |= autodestroy ? VIR_QEMU_PROCESS_START_AUTODESTROY : 0;
J
Jiri Denemark 已提交
5750 5751 5752

    /*
     * If there is a managed saved state restore it instead of starting
5753
     * from scratch. The old state is removed once the restoring succeeded.
J
Jiri Denemark 已提交
5754 5755
     */
    managed_save = qemuDomainManagedSavePath(driver, vm);
5756 5757 5758 5759

    if (!managed_save)
        goto cleanup;

E
Eric Blake 已提交
5760
    if (virFileExists(managed_save)) {
5761 5762 5763 5764 5765 5766 5767
        if (force_boot) {
            if (unlink(managed_save) < 0) {
                virReportSystemError(errno,
                                     _("cannot remove managed save file %s"),
                                     managed_save);
                goto cleanup;
            }
5768
            vm->hasManagedSave = false;
5769 5770
        } else {
            ret = qemuDomainObjRestore(conn, driver, vm, managed_save,
5771
                                       start_paused, bypass_cache);
J
Jiri Denemark 已提交
5772

5773 5774 5775 5776 5777 5778 5779
            if (ret == 0) {
                if (unlink(managed_save) < 0)
                    VIR_WARN("Failed to remove the managed state %s", managed_save);
                else
                    vm->hasManagedSave = false;
            }

E
Eric Blake 已提交
5780 5781 5782 5783
            if (ret > 0)
                VIR_WARN("Ignoring incomplete managed state %s", managed_save);
            else
                goto cleanup;
5784
        }
J
Jiri Denemark 已提交
5785 5786
    }

5787 5788
    ret = qemuProcessStart(conn, driver, vm, NULL, -1, NULL, NULL,
                           VIR_NETDEV_VPORT_PROFILE_OP_CREATE, start_flags);
5789
    virDomainAuditStart(vm, "booted", ret >= 0);
5790
    if (ret >= 0) {
J
Jiri Denemark 已提交
5791 5792 5793 5794
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
5795
        if (event) {
J
Jiri Denemark 已提交
5796
            qemuDomainEventQueue(driver, event);
5797 5798 5799 5800 5801 5802 5803 5804
            if (start_paused) {
                event = virDomainEventNewFromObj(vm,
                                                 VIR_DOMAIN_EVENT_SUSPENDED,
                                                 VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
                if (event)
                    qemuDomainEventQueue(driver, event);
            }
        }
J
Jiri Denemark 已提交
5805 5806 5807 5808 5809 5810 5811
    }

cleanup:
    VIR_FREE(managed_save);
    return ret;
}

5812
static int
5813
qemuDomainCreateWithFlags(virDomainPtr dom, unsigned int flags)
5814
{
5815
    virQEMUDriverPtr driver = dom->conn->privateData;
5816 5817
    virDomainObjPtr vm;
    int ret = -1;
5818

5819
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
5820
                  VIR_DOMAIN_START_AUTODESTROY |
5821 5822
                  VIR_DOMAIN_START_BYPASS_CACHE |
                  VIR_DOMAIN_START_FORCE_BOOT, -1);
5823

5824 5825
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
5826

5827 5828 5829
    if (virDomainCreateWithFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

5830
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
5831 5832 5833
        goto cleanup;

    if (virDomainObjIsActive(vm)) {
5834 5835
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is already running"));
5836 5837 5838
        goto endjob;
    }

5839
    if (qemuDomainObjStart(dom->conn, driver, vm, flags) < 0)
5840 5841 5842
        goto endjob;

    ret = 0;
5843

5844
endjob:
5845
    if (qemuDomainObjEndJob(driver, vm) == 0)
5846
        vm = NULL;
5847

5848
cleanup:
5849
    if (vm)
5850
        virObjectUnlock(vm);
5851
    return ret;
D
Daniel P. Berrange 已提交
5852 5853
}

5854
static int
5855
qemuDomainCreate(virDomainPtr dom)
5856
{
5857
    return qemuDomainCreateWithFlags(dom, 0);
5858 5859
}

5860
static virDomainPtr qemuDomainDefineXML(virConnectPtr conn, const char *xml) {
5861
    virQEMUDriverPtr driver = conn->privateData;
5862
    virDomainDefPtr def = NULL;
5863
    virDomainDefPtr oldDef = NULL;
5864
    virDomainObjPtr vm = NULL;
5865
    virDomainPtr dom = NULL;
5866
    virDomainEventPtr event = NULL;
5867
    virQEMUCapsPtr qemuCaps = NULL;
5868
    virQEMUDriverConfigPtr cfg;
5869
    virCapsPtr caps = NULL;
5870

5871
    cfg = virQEMUDriverGetConfig(driver);
5872 5873 5874 5875

    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

5876
    if (!(def = virDomainDefParseString(xml, caps, driver->xmlopt,
M
Matthias Bolte 已提交
5877
                                        QEMU_EXPECTED_VIRT_TYPES,
5878
                                        VIR_DOMAIN_XML_INACTIVE)))
5879
        goto cleanup;
5880

5881 5882 5883
    if (virDomainDefineXMLEnsureACL(conn, def) < 0)
        goto cleanup;

5884
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
5885 5886
        goto cleanup;

5887
    if (!(qemuCaps = virQEMUCapsCacheLookup(driver->qemuCapsCache, def->emulator)))
5888 5889
        goto cleanup;

5890
    if (qemuCanonicalizeMachine(def, qemuCaps) < 0)
5891 5892
        goto cleanup;

5893
    if (qemuDomainAssignAddresses(def, qemuCaps, NULL) < 0)
5894 5895
        goto cleanup;

5896
    if (!(vm = virDomainObjListAdd(driver->domains, def,
5897
                                   driver->xmlopt,
5898
                                   0, &oldDef)))
5899 5900
        goto cleanup;

5901
    def = NULL;
E
Eric Blake 已提交
5902 5903 5904
    if (virDomainHasDiskMirror(vm)) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE, "%s",
                       _("domain has active block copy job"));
5905
        virDomainObjAssignDef(vm, NULL, false, NULL);
E
Eric Blake 已提交
5906 5907
        goto cleanup;
    }
5908
    vm->persistent = 1;
5909

5910
    if (virDomainSaveConfig(cfg->configDir,
5911
                            vm->newDef ? vm->newDef : vm->def) < 0) {
5912
        if (oldDef) {
M
Michal Privoznik 已提交
5913 5914 5915 5916
            /* There is backup so this VM was defined before.
             * Just restore the backup. */
            VIR_INFO("Restoring domain '%s' definition", vm->def->name);
            if (virDomainObjIsActive(vm))
5917
                vm->newDef = oldDef;
M
Michal Privoznik 已提交
5918
            else
5919 5920
                vm->def = oldDef;
            oldDef = NULL;
M
Michal Privoznik 已提交
5921 5922 5923 5924 5925 5926
        } else {
            /* Brand new domain. Remove it */
            VIR_INFO("Deleting domain '%s'", vm->def->name);
            qemuDomainRemoveInactive(driver, vm);
            vm = NULL;
        }
5927
        goto cleanup;
5928 5929
    }

5930 5931
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
5932
                                     !oldDef ?
5933 5934
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
5935

5936
    VIR_INFO("Creating domain '%s'", vm->def->name);
5937
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
5938
    if (dom) dom->id = vm->def->id;
5939 5940

cleanup:
5941
    virDomainDefFree(oldDef);
5942
    virDomainDefFree(def);
5943
    if (vm)
5944
        virObjectUnlock(vm);
5945 5946
    if (event)
        qemuDomainEventQueue(driver, event);
5947
    virObjectUnref(qemuCaps);
5948
    virObjectUnref(caps);
5949
    virObjectUnref(cfg);
5950
    return dom;
D
Daniel P. Berrange 已提交
5951 5952
}

5953 5954
static int
qemuDomainUndefineFlags(virDomainPtr dom,
5955
                        unsigned int flags)
5956
{
5957
    virQEMUDriverPtr driver = dom->conn->privateData;
5958
    virDomainObjPtr vm;
5959
    virDomainEventPtr event = NULL;
5960
    char *name = NULL;
5961
    int ret = -1;
5962
    int nsnapshots;
5963
    virQEMUDriverConfigPtr cfg = NULL;
D
Daniel P. Berrange 已提交
5964

5965 5966
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE |
                  VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA, -1);
5967

5968 5969
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
5970

5971
    cfg = virQEMUDriverGetConfig(driver);
D
Daniel P. Berrange 已提交
5972

5973 5974 5975
    if (virDomainUndefineFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

5976
    if (!vm->persistent) {
5977 5978
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot undefine transient domain"));
5979 5980 5981
        goto cleanup;
    }

5982
    if (!virDomainObjIsActive(vm) &&
5983
        (nsnapshots = virDomainSnapshotObjListNum(vm->snapshots, NULL, 0))) {
5984
        if (!(flags & VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA)) {
5985 5986 5987 5988
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("cannot delete inactive domain with %d "
                             "snapshots"),
                           nsnapshots);
5989 5990
            goto cleanup;
        }
5991
        if (qemuDomainSnapshotDiscardAllMetadata(driver, vm) < 0)
5992
            goto cleanup;
5993 5994
    }

5995 5996 5997 5998 5999 6000 6001
    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
6002 6003 6004
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to remove domain managed "
                                 "save image"));
6005 6006 6007
                goto cleanup;
            }
        } else {
6008 6009 6010
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while domain managed "
                             "save image exists"));
6011 6012 6013 6014
            goto cleanup;
        }
    }

6015
    if (virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm) < 0)
6016
        goto cleanup;
D
Daniel P. Berrange 已提交
6017

6018 6019 6020
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
6021

6022
    VIR_INFO("Undefining domain '%s'", vm->def->name);
6023 6024 6025 6026 6027 6028 6029 6030

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

6035
    ret = 0;
D
Daniel P. Berrange 已提交
6036

6037
cleanup:
6038
    VIR_FREE(name);
6039
    if (vm)
6040
        virObjectUnlock(vm);
6041 6042
    if (event)
        qemuDomainEventQueue(driver, event);
6043
    virObjectUnref(cfg);
6044
    return ret;
D
Daniel P. Berrange 已提交
6045 6046
}

6047
static int
6048
qemuDomainUndefine(virDomainPtr dom)
6049 6050 6051 6052
{
    return qemuDomainUndefineFlags(dom, 0);
}

6053
static int
6054
qemuDomainAttachDeviceDiskLive(virConnectPtr conn,
6055
                               virQEMUDriverPtr driver,
6056
                               virDomainObjPtr vm,
6057
                               virDomainDeviceDefPtr dev)
6058 6059
{
    virDomainDiskDefPtr disk = dev->data.disk;
6060 6061 6062
    virDomainDiskDefPtr orig_disk = NULL;
    virDomainDeviceDefPtr dev_copy = NULL;
    virDomainDiskDefPtr tmp = NULL;
6063
    virCgroupPtr cgroup = NULL;
6064
    virCapsPtr caps = NULL;
6065
    int ret = -1;
6066

6067
    if (disk->driverName != NULL && !STREQ(disk->driverName, "qemu")) {
6068 6069 6070
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("unsupported driver name '%s' for disk '%s'"),
                       disk->driverName, disk->src);
6071 6072 6073
        goto end;
    }

6074 6075 6076
    if (qemuTranslateDiskSourcePool(conn, disk) < 0)
        goto end;

6077
    if (qemuAddSharedDevice(driver, dev, vm->def->name) < 0)
6078 6079
        goto end;

6080
    if (qemuSetUnprivSGIO(dev) < 0)
6081 6082
        goto end;

6083 6084 6085
    if (qemuDomainDetermineDiskChain(driver, disk, false) < 0)
        goto end;

6086 6087
    if (qemuSetupDiskCgroup(vm, disk) < 0)
        goto end;
6088

6089 6090 6091
    switch (disk->device)  {
    case VIR_DOMAIN_DISK_DEVICE_CDROM:
    case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106
        if (!(orig_disk = virDomainDiskFindByBusAndDst(vm->def,
                                                       disk->bus, disk->dst))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("No device with bus '%s' and target '%s'"),
                           virDomainDiskBusTypeToString(disk->bus),
                           disk->dst);
            goto end;
        }

        if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
            goto end;

        tmp = dev->data.disk;
        dev->data.disk = orig_disk;

6107 6108
        if (!(dev_copy = virDomainDeviceDefCopy(dev, vm->def,
                                                caps, driver->xmlopt))) {
6109 6110 6111 6112 6113 6114
            dev->data.disk = tmp;
            goto end;
        }
        dev->data.disk = tmp;

        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, orig_disk, false);
6115 6116 6117
        /* 'disk' must not be accessed now - it has been free'd.
         * 'orig_disk' now points to the new disk, while 'dev_copy'
         * now points to the old disk */
6118 6119 6120 6121

        /* Need to remove the shared disk entry for the original disk src
         * if the operation is either ejecting or updating.
         */
6122
        if (ret == 0)
6123 6124
            ignore_value(qemuRemoveSharedDevice(driver, dev_copy,
                                                vm->def->name));
6125 6126
        break;
    case VIR_DOMAIN_DISK_DEVICE_DISK:
6127
    case VIR_DOMAIN_DISK_DEVICE_LUN:
6128 6129
        if (disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
            if (disk->device == VIR_DOMAIN_DISK_DEVICE_LUN) {
6130 6131
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("disk device='lun' is not supported for usb bus"));
6132 6133
                break;
            }
6134
            ret = qemuDomainAttachUsbMassstorageDevice(conn, driver, vm,
6135
                                                       disk);
6136
        } else if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
6137
            ret = qemuDomainAttachVirtioDiskDevice(conn, driver, vm, disk);
6138
        } else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI) {
6139
            ret = qemuDomainAttachSCSIDisk(conn, driver, vm, disk);
6140
        } else {
6141 6142 6143
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk bus '%s' cannot be hotplugged."),
                           virDomainDiskBusTypeToString(disk->bus));
6144
        }
6145 6146
        break;
    default:
6147 6148 6149
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("disk device type '%s' cannot be hotplugged"),
                       virDomainDiskDeviceTypeToString(disk->device));
6150 6151 6152 6153
        break;
    }

    if (ret != 0 && cgroup) {
6154
        if (qemuTeardownDiskCgroup(vm, disk) < 0)
6155 6156 6157
            VIR_WARN("Failed to teardown cgroup for disk path %s",
                     NULLSTR(disk->src));
    }
6158

6159
end:
6160
    if (ret != 0)
6161
        ignore_value(qemuRemoveSharedDevice(driver, dev, vm->def->name));
6162 6163
    virObjectUnref(caps);
    virDomainDeviceDefFree(dev_copy);
6164 6165 6166 6167
    return ret;
}

static int
6168
qemuDomainAttachDeviceControllerLive(virQEMUDriverPtr driver,
6169
                                     virDomainObjPtr vm,
6170
                                     virDomainDeviceDefPtr dev)
6171 6172 6173 6174 6175 6176
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
6177
        ret = qemuDomainAttachPciControllerDevice(driver, vm, cont);
6178 6179
        break;
    default:
6180
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6181
                       _("'%s' controller cannot be hotplugged."),
6182
                       virDomainControllerTypeToString(cont->type));
6183 6184 6185 6186 6187 6188 6189 6190
        break;
    }
    return ret;
}

static int
qemuDomainAttachDeviceLive(virDomainObjPtr vm,
                           virDomainDeviceDefPtr dev,
6191
                           virDomainPtr dom)
6192
{
6193
    virQEMUDriverPtr driver = dom->conn->privateData;
6194 6195 6196 6197
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
6198
        qemuDomainObjCheckDiskTaint(driver, vm, dev->data.disk, -1);
6199
        ret = qemuDomainAttachDeviceDiskLive(dom->conn, driver, vm, dev);
6200 6201 6202 6203 6204
        if (!ret)
            dev->data.disk = NULL;
        break;

    case VIR_DOMAIN_DEVICE_CONTROLLER:
6205
        ret = qemuDomainAttachDeviceControllerLive(driver, vm, dev);
6206 6207 6208 6209
        if (!ret)
            dev->data.controller = NULL;
        break;

6210 6211 6212 6213 6214 6215 6216
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainAttachLease(driver, vm,
                                    dev->data.lease);
        if (ret == 0)
            dev->data.lease = NULL;
        break;

6217
    case VIR_DOMAIN_DEVICE_NET:
6218
        qemuDomainObjCheckNetTaint(driver, vm, dev->data.net, -1);
6219
        ret = qemuDomainAttachNetDevice(dom->conn, driver, vm,
6220
                                        dev->data.net);
6221 6222 6223 6224 6225 6226
        if (!ret)
            dev->data.net = NULL;
        break;

    case VIR_DOMAIN_DEVICE_HOSTDEV:
        ret = qemuDomainAttachHostDevice(driver, vm,
6227
                                         dev->data.hostdev);
6228 6229 6230 6231
        if (!ret)
            dev->data.hostdev = NULL;
        break;

6232 6233 6234 6235 6236 6237 6238
    case VIR_DOMAIN_DEVICE_REDIRDEV:
        ret = qemuDomainAttachRedirdevDevice(driver, vm,
                                             dev->data.redirdev);
        if (!ret)
            dev->data.redirdev = NULL;
        break;

6239
    default:
6240 6241 6242
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("device type '%s' cannot be attached"),
                       virDomainDeviceTypeToString(dev->type));
6243 6244 6245 6246 6247 6248 6249
        break;
    }

    return ret;
}

static int
6250
qemuDomainDetachDeviceDiskLive(virQEMUDriverPtr driver,
6251
                               virDomainObjPtr vm,
6252
                               virDomainDeviceDefPtr dev)
6253 6254 6255 6256 6257 6258
{
    virDomainDiskDefPtr disk = dev->data.disk;
    int ret = -1;

    switch (disk->device) {
    case VIR_DOMAIN_DISK_DEVICE_DISK:
6259
    case VIR_DOMAIN_DISK_DEVICE_LUN:
6260
        if (disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)
6261
            ret = qemuDomainDetachVirtioDiskDevice(driver, vm, dev);
O
Osier Yang 已提交
6262 6263
        else if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
                 disk->bus == VIR_DOMAIN_DISK_BUS_USB)
6264
            ret = qemuDomainDetachDiskDevice(driver, vm, dev);
6265
        else
6266 6267
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("This type of disk cannot be hot unplugged"));
6268 6269
        break;
    default:
6270 6271
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("disk device type '%s' cannot be detached"),
6272
                       virDomainDiskDeviceTypeToString(disk->device));
6273 6274
        break;
    }
6275

6276
    if (ret == 0)
6277
        ignore_value(qemuRemoveSharedDevice(driver, dev, vm->def->name));
6278

6279 6280 6281 6282
    return ret;
}

static int
6283
qemuDomainDetachDeviceControllerLive(virQEMUDriverPtr driver,
6284
                                     virDomainObjPtr vm,
6285
                                     virDomainDeviceDefPtr dev)
6286 6287 6288 6289 6290 6291
{
    virDomainControllerDefPtr cont = dev->data.controller;
    int ret = -1;

    switch (cont->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
6292
        ret = qemuDomainDetachPciControllerDevice(driver, vm, dev);
6293 6294
        break;
    default :
6295
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6296
                       _("'%s' controller cannot be hotunplugged."),
6297
                       virDomainControllerTypeToString(cont->type));
6298 6299 6300 6301 6302 6303 6304
    }
    return ret;
}

static int
qemuDomainDetachDeviceLive(virDomainObjPtr vm,
                           virDomainDeviceDefPtr dev,
6305
                           virDomainPtr dom)
6306
{
6307
    virQEMUDriverPtr driver = dom->conn->privateData;
6308 6309 6310 6311
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
6312
        ret = qemuDomainDetachDeviceDiskLive(driver, vm, dev);
6313 6314
        break;
    case VIR_DOMAIN_DEVICE_CONTROLLER:
6315
        ret = qemuDomainDetachDeviceControllerLive(driver, vm, dev);
6316
        break;
6317 6318 6319
    case VIR_DOMAIN_DEVICE_LEASE:
        ret = qemuDomainDetachLease(driver, vm, dev->data.lease);
        break;
6320
    case VIR_DOMAIN_DEVICE_NET:
6321
        ret = qemuDomainDetachNetDevice(driver, vm, dev);
6322 6323
        break;
    case VIR_DOMAIN_DEVICE_HOSTDEV:
6324
        ret = qemuDomainDetachHostDevice(driver, vm, dev);
6325 6326
        break;
    default:
6327 6328
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       "%s", _("This type of device cannot be hot unplugged"));
6329 6330 6331 6332 6333 6334
        break;
    }

    return ret;
}

6335
static int
6336 6337
qemuDomainChangeDiskMediaLive(virConnectPtr conn,
                              virDomainObjPtr vm,
6338
                              virDomainDeviceDefPtr dev,
6339
                              virQEMUDriverPtr driver,
6340 6341 6342
                              bool force)
{
    virDomainDiskDefPtr disk = dev->data.disk;
6343 6344 6345 6346
    virDomainDiskDefPtr orig_disk = NULL;
    virDomainDiskDefPtr tmp = NULL;
    virDomainDeviceDefPtr dev_copy = NULL;
    virCapsPtr caps = NULL;
6347
    int ret = -1;
6348

6349 6350 6351
    if (qemuTranslateDiskSourcePool(conn, disk) < 0)
        goto end;

6352 6353 6354
    if (qemuDomainDetermineDiskChain(driver, disk, false) < 0)
        goto end;

6355 6356
    if (qemuSetupDiskCgroup(vm, disk) < 0)
        goto end;
6357 6358 6359 6360

    switch (disk->device) {
    case VIR_DOMAIN_DISK_DEVICE_CDROM:
    case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375
        if (!(orig_disk = virDomainDiskFindByBusAndDst(vm->def,
                                                       disk->bus, disk->dst))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("No device with bus '%s' and target '%s'"),
                           virDomainDiskBusTypeToString(disk->bus),
                           disk->dst);
            goto end;
        }

        if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
            goto end;

        tmp = dev->data.disk;
        dev->data.disk = orig_disk;

6376 6377
        if (!(dev_copy = virDomainDeviceDefCopy(dev, vm->def,
                                                caps, driver->xmlopt))) {
6378 6379 6380 6381 6382
            dev->data.disk = tmp;
            goto end;
        }
        dev->data.disk = tmp;

6383
        /* Add the new disk src into shared disk hash table */
6384
        if (qemuAddSharedDevice(driver, dev, vm->def->name) < 0)
6385 6386
            goto end;

6387
        ret = qemuDomainChangeEjectableMedia(driver, vm, disk, orig_disk, force);
6388 6389 6390 6391 6392 6393 6394
        /* 'disk' must not be accessed now - it has been freed.
         * 'orig_disk' now points to the new disk, while 'dev_copy'
         * now points to the old disk */

        /* Need to remove the shared disk entry for the original
         * disk src if the operation is either ejecting or updating.
         */
6395
        if (ret == 0) {
6396
            dev->data.disk = NULL;
6397 6398
            ignore_value(qemuRemoveSharedDevice(driver, dev_copy,
                                                vm->def->name));
6399
        }
6400 6401
        break;
    default:
6402 6403 6404
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("disk bus '%s' cannot be updated."),
                       virDomainDiskBusTypeToString(disk->bus));
6405 6406 6407
        break;
    }

6408 6409 6410 6411 6412
    if (ret != 0 &&
        qemuTeardownDiskCgroup(vm, disk) < 0)
        VIR_WARN("Failed to teardown cgroup for disk path %s",
                 NULLSTR(disk->src));

6413
end:
6414 6415
    virObjectUnref(caps);
    virDomainDeviceDefFree(dev_copy);
6416 6417 6418 6419
    return ret;
}

static int
6420 6421
qemuDomainUpdateDeviceLive(virConnectPtr conn,
                           virDomainObjPtr vm,
6422 6423 6424 6425
                           virDomainDeviceDefPtr dev,
                           virDomainPtr dom,
                           bool force)
{
6426
    virQEMUDriverPtr driver = dom->conn->privateData;
6427 6428 6429 6430
    int ret = -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
6431
        ret = qemuDomainChangeDiskMediaLive(conn, vm, dev, driver, force);
6432 6433 6434 6435
        break;
    case VIR_DOMAIN_DEVICE_GRAPHICS:
        ret = qemuDomainChangeGraphics(driver, vm, dev->data.graphics);
        break;
6436
    case VIR_DOMAIN_DEVICE_NET:
6437
        ret = qemuDomainChangeNet(driver, vm, dom, dev);
6438
        break;
6439
    default:
6440 6441 6442
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("device type '%s' cannot be updated"),
                       virDomainDeviceTypeToString(dev->type));
6443 6444 6445 6446 6447 6448
        break;
    }

    return ret;
}

6449
static int
6450
qemuDomainAttachDeviceConfig(virQEMUCapsPtr qemuCaps,
6451
                             virDomainDefPtr vmdef,
6452 6453
                             virDomainDeviceDefPtr dev)
{
6454
    virDomainDiskDefPtr disk;
6455
    virDomainNetDefPtr net;
6456
    virDomainHostdevDefPtr hostdev;
6457
    virDomainLeaseDefPtr lease;
6458
    virDomainControllerDefPtr controller;
6459

6460
    switch (dev->type) {
6461 6462
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
6463
        if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
6464 6465
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("target %s already exists"), disk->dst);
6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476
            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;
6477
        if (qemuDomainAssignAddresses(vmdef, qemuCaps, NULL) < 0)
6478 6479 6480
            return -1;
        break;

6481 6482 6483 6484 6485 6486 6487
    case VIR_DOMAIN_DEVICE_NET:
        net = dev->data.net;
        if (virDomainNetInsert(vmdef, net)) {
            virReportOOMError();
            return -1;
        }
        dev->data.net = NULL;
6488
        if (qemuDomainAssignAddresses(vmdef, qemuCaps, NULL) < 0)
6489 6490
            return -1;
        break;
6491

6492 6493 6494
    case VIR_DOMAIN_DEVICE_HOSTDEV:
        hostdev = dev->data.hostdev;
        if (virDomainHostdevFind(vmdef, hostdev, NULL) >= 0) {
6495
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
6496
                           _("device is already in the domain configuration"));
6497 6498 6499 6500 6501 6502 6503
            return -1;
        }
        if (virDomainHostdevInsert(vmdef, hostdev)) {
            virReportOOMError();
            return -1;
        }
        dev->data.hostdev = NULL;
6504
        if (qemuDomainAssignAddresses(vmdef, qemuCaps, NULL) < 0)
6505 6506 6507
            return -1;
        break;

6508 6509 6510
    case VIR_DOMAIN_DEVICE_LEASE:
        lease = dev->data.lease;
        if (virDomainLeaseIndex(vmdef, lease) >= 0) {
6511
            virReportError(VIR_ERR_OPERATION_INVALID,
6512 6513
                           _("Lease %s in lockspace %s already exists"),
                           lease->key, NULLSTR(lease->lockspace));
6514 6515 6516 6517 6518 6519 6520 6521 6522
            return -1;
        }
        if (virDomainLeaseInsert(vmdef, lease) < 0)
            return -1;

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

6523 6524 6525 6526
    case VIR_DOMAIN_DEVICE_CONTROLLER:
        controller = dev->data.controller;
        if (virDomainControllerFind(vmdef, controller->type,
                                    controller->idx) > 0) {
6527
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
6528 6529 6530 6531 6532 6533 6534 6535
                           _("Target already exists"));
            return -1;
        }

        if (virDomainControllerInsert(vmdef, controller) < 0)
            return -1;
        dev->data.controller = NULL;

6536
        if (qemuDomainAssignAddresses(vmdef, qemuCaps, NULL) < 0)
6537 6538 6539
            return -1;
        break;

6540
    default:
6541 6542
         virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                        _("persistent attach of device is not supported"));
6543 6544 6545 6546 6547 6548 6549
         return -1;
    }
    return 0;
}


static int
6550
qemuDomainDetachDeviceConfig(virDomainDefPtr vmdef,
6551 6552
                             virDomainDeviceDefPtr dev)
{
6553
    virDomainDiskDefPtr disk, det_disk;
6554
    virDomainNetDefPtr net;
6555
    virDomainHostdevDefPtr hostdev, det_hostdev;
6556
    virDomainLeaseDefPtr lease, det_lease;
6557 6558
    virDomainControllerDefPtr cont, det_cont;
    int idx;
6559
    char mac[VIR_MAC_STRING_BUFLEN];
6560

6561
    switch (dev->type) {
6562 6563
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
6564
        if (!(det_disk = virDomainDiskRemoveByName(vmdef, disk->dst))) {
6565 6566
            virReportError(VIR_ERR_INVALID_ARG,
                           _("no target device %s"), disk->dst);
6567 6568
            return -1;
        }
6569
        virDomainDiskDefFree(det_disk);
6570
        break;
6571

6572 6573
    case VIR_DOMAIN_DEVICE_NET:
        net = dev->data.net;
6574 6575 6576 6577 6578 6579 6580 6581 6582
        idx = virDomainNetFindIdx(vmdef, net);
        if (idx == -2) {
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("multiple devices matching mac address %s found"),
                           virMacAddrFormat(&net->mac, mac));
            return -1;
        } else if (idx < 0) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("no matching network device was found"));
6583 6584
            return -1;
        }
6585 6586
        /* this is guaranteed to succeed */
        virDomainNetDefFree(virDomainNetRemove(vmdef, idx));
6587
        break;
6588

6589 6590 6591
    case VIR_DOMAIN_DEVICE_HOSTDEV: {
        hostdev = dev->data.hostdev;
        if ((idx = virDomainHostdevFind(vmdef, hostdev, &det_hostdev)) < 0) {
6592 6593
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("device not present in domain configuration"));
6594 6595 6596 6597 6598 6599 6600
            return -1;
        }
        virDomainHostdevRemove(vmdef, idx);
        virDomainHostdevDefFree(det_hostdev);
        break;
    }

6601 6602
    case VIR_DOMAIN_DEVICE_LEASE:
        lease = dev->data.lease;
6603
        if (!(det_lease = virDomainLeaseRemove(vmdef, lease))) {
6604 6605 6606
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Lease %s in lockspace %s does not exist"),
                           lease->key, NULLSTR(lease->lockspace));
6607 6608
            return -1;
        }
6609
        virDomainLeaseDefFree(det_lease);
6610 6611
        break;

6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624
    case VIR_DOMAIN_DEVICE_CONTROLLER:
        cont = dev->data.controller;
        if ((idx = virDomainControllerFind(vmdef, cont->type,
                                           cont->idx)) < 0) {
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("device not present in domain configuration"));
            return -1;
        }
        det_cont = virDomainControllerRemove(vmdef, idx);
        virDomainControllerDefFree(det_cont);

        break;

6625
    default:
6626 6627
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("persistent detach of device is not supported"));
6628 6629 6630 6631 6632 6633
        return -1;
    }
    return 0;
}

static int
6634
qemuDomainUpdateDeviceConfig(virQEMUCapsPtr qemuCaps,
6635
                             virDomainDefPtr vmdef,
6636 6637
                             virDomainDeviceDefPtr dev)
{
6638
    virDomainDiskDefPtr orig, disk;
6639
    virDomainNetDefPtr net;
6640
    int pos;
6641 6642
    char mac[VIR_MAC_STRING_BUFLEN];

6643

6644
    switch (dev->type) {
6645 6646
    case VIR_DOMAIN_DEVICE_DISK:
        disk = dev->data.disk;
6647
        pos = virDomainDiskIndexByName(vmdef, disk->dst, false);
6648
        if (pos < 0) {
6649 6650
            virReportError(VIR_ERR_INVALID_ARG,
                           _("target %s doesn't exist."), disk->dst);
6651 6652 6653 6654 6655
            return -1;
        }
        orig = vmdef->disks[pos];
        if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM) &&
            !(orig->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY)) {
6656 6657
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("this disk doesn't support update"));
6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672
            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;
        }
6673 6674
        if (disk->format)
            orig->format = disk->format;
6675 6676
        disk->src = NULL;
        break;
6677 6678 6679

    case VIR_DOMAIN_DEVICE_NET:
        net = dev->data.net;
6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691
        pos = virDomainNetFindIdx(vmdef, net);
        if (pos == -2) {
            virMacAddrFormat(&net->mac, mac);
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("couldn't find matching device "
                             "with mac address %s"), mac);
            return -1;
        } else if (pos < 0) {
            virMacAddrFormat(&net->mac, mac);
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("couldn't find matching device "
                             "with mac address %s"), mac);
6692 6693 6694
            return -1;
        }

6695
        virDomainNetDefFree(vmdef->nets[pos]);
6696 6697 6698 6699

        vmdef->nets[pos] = net;
        dev->data.net = NULL;

6700
        if (qemuDomainAssignAddresses(vmdef, qemuCaps, NULL) < 0)
6701 6702 6703
            return -1;
        break;

6704
    default:
6705 6706
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("persistent update of device is not supported"));
6707 6708 6709 6710 6711
        return -1;
    }
    return 0;
}

6712

6713 6714
static int qemuDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
6715
{
6716
    virQEMUDriverPtr driver = dom->conn->privateData;
6717
    virDomainObjPtr vm = NULL;
6718
    virDomainDefPtr vmdef = NULL;
6719
    virDomainDeviceDefPtr dev = NULL, dev_copy = NULL;
6720
    int ret = -1;
6721
    unsigned int affect;
6722
    virQEMUCapsPtr qemuCaps = NULL;
6723
    qemuDomainObjPrivatePtr priv;
6724
    virQEMUDriverConfigPtr cfg = NULL;
6725
    virCapsPtr caps = NULL;
6726

6727
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
6728
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
6729

6730 6731
    cfg = virQEMUDriverGetConfig(driver);

6732 6733
    affect = flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG);

6734 6735 6736
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

6737
    if (!(vm = qemuDomObjFromDomain(dom)))
6738
        goto cleanup;
6739

6740
    priv = vm->privateData;
6741

6742 6743 6744
    if (virDomainAttachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

6745
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
6746
        goto cleanup;
6747

6748
    if (virDomainObjIsActive(vm)) {
6749
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
6750
            flags |= VIR_DOMAIN_AFFECT_LIVE;
6751
    } else {
6752
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
6753
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
6754
        /* check consistency between flags and the vm state */
6755
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6756
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
6757 6758
                           _("cannot do live update a device on "
                             "inactive domain"));
6759 6760
            goto endjob;
        }
6761
    }
6762

6763
    if ((flags & VIR_DOMAIN_AFFECT_CONFIG) && !vm->persistent) {
6764 6765
         virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot modify device on transient domain"));
6766 6767
         goto endjob;
    }
6768

6769 6770
    dev = dev_copy = virDomainDeviceDefParse(xml, vm->def,
                                             caps, driver->xmlopt,
6771 6772 6773 6774 6775 6776 6777 6778 6779 6780
                                             VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL)
        goto endjob;

    if (flags & VIR_DOMAIN_AFFECT_CONFIG &&
        flags & VIR_DOMAIN_AFFECT_LIVE) {
        /* If we are affecting both CONFIG and LIVE
         * create a deep copy of device as adding
         * to CONFIG takes one instance.
         */
6781
        dev_copy = virDomainDeviceDefCopy(dev, vm->def, caps, driver->xmlopt);
6782
        if (!dev_copy)
6783
            goto endjob;
6784
    }
6785

6786 6787 6788
    if (priv->qemuCaps)
        qemuCaps = virObjectRef(priv->qemuCaps);
    else if (!(qemuCaps = virQEMUCapsCacheLookup(driver->qemuCapsCache, vm->def->emulator)))
6789 6790
        goto cleanup;

6791
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6792
        if (virDomainDefCompatibleDevice(vm->def, dev) < 0)
6793 6794
            goto endjob;

6795
        /* Make a copy for updated domain. */
6796
        vmdef = virDomainObjCopyPersistentDef(vm, caps, driver->xmlopt);
6797 6798
        if (!vmdef)
            goto endjob;
6799
        if ((ret = qemuDomainAttachDeviceConfig(qemuCaps, vmdef, dev)) < 0)
6800 6801 6802 6803
            goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
6804 6805 6806
        if (virDomainDefCompatibleDevice(vm->def, dev_copy) < 0)
            goto endjob;

6807
        if ((ret = qemuDomainAttachDeviceLive(vm, dev_copy, dom)) < 0)
6808
            goto endjob;
6809 6810
        /*
         * update domain status forcibly because the domain status may be
6811 6812
         * changed even if we failed to attach the device. For example,
         * a new controller may be created.
6813
         */
6814
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0) {
6815
            ret = -1;
6816 6817
            goto endjob;
        }
6818
    }
6819

6820
    /* Finally, if no error until here, we can save config. */
6821
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
6822
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
6823
        if (!ret) {
6824
            virDomainObjAssignDef(vm, vmdef, false, NULL);
6825 6826 6827
            vmdef = NULL;
        }
    }
6828 6829

endjob:
6830
    if (qemuDomainObjEndJob(driver, vm) == 0)
6831 6832 6833
        vm = NULL;

cleanup:
6834
    virObjectUnref(qemuCaps);
6835
    virDomainDefFree(vmdef);
6836 6837
    if (dev != dev_copy)
        virDomainDeviceDefFree(dev_copy);
6838 6839
    virDomainDeviceDefFree(dev);
    if (vm)
6840
        virObjectUnlock(vm);
6841
    virObjectUnref(caps);
6842
    virObjectUnref(cfg);
6843 6844 6845
    return ret;
}

6846 6847 6848
static int qemuDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainAttachDeviceFlags(dom, xml,
6849
                                       VIR_DOMAIN_AFFECT_LIVE);
6850
}
6851

6852

6853 6854 6855 6856
static int qemuDomainUpdateDeviceFlags(virDomainPtr dom,
                                       const char *xml,
                                       unsigned int flags)
{
6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884
    virQEMUDriverPtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL, dev_copy = NULL;
    bool force = (flags & VIR_DOMAIN_DEVICE_MODIFY_FORCE) != 0;
    int ret = -1;
    unsigned int affect;
    virQEMUCapsPtr qemuCaps = NULL;
    qemuDomainObjPrivatePtr priv;
    virQEMUDriverConfigPtr cfg = NULL;
    virCapsPtr caps = NULL;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_DOMAIN_DEVICE_MODIFY_FORCE, -1);

    cfg = virQEMUDriverGetConfig(driver);

    affect = flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG);

    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;

    priv = vm->privateData;

6885 6886 6887
    if (virDomainUpdateDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;

    if (virDomainObjIsActive(vm)) {
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
            flags |= VIR_DOMAIN_AFFECT_LIVE;
    } else {
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
        /* check consistency between flags and the vm state */
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot do live update a device on "
                             "inactive domain"));
            goto endjob;
        }
    }

    if ((flags & VIR_DOMAIN_AFFECT_CONFIG) && !vm->persistent) {
         virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot modify device on transient domain"));
         goto endjob;
    }

    dev = dev_copy = virDomainDeviceDefParse(xml, vm->def,
                                             caps, driver->xmlopt,
                                             VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL)
        goto endjob;

    if (flags & VIR_DOMAIN_AFFECT_CONFIG &&
        flags & VIR_DOMAIN_AFFECT_LIVE) {
        /* If we are affecting both CONFIG and LIVE
         * create a deep copy of device as adding
         * to CONFIG takes one instance.
         */
        dev_copy = virDomainDeviceDefCopy(dev, vm->def, caps, driver->xmlopt);
        if (!dev_copy)
            goto endjob;
    }

    if (priv->qemuCaps)
        qemuCaps = virObjectRef(priv->qemuCaps);
    else if (!(qemuCaps = virQEMUCapsCacheLookup(driver->qemuCapsCache, vm->def->emulator)))
        goto cleanup;

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        if (virDomainDefCompatibleDevice(vm->def, dev) < 0)
            goto endjob;

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

        if ((ret = qemuDomainUpdateDeviceConfig(qemuCaps, vmdef, dev)) < 0)
            goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (virDomainDefCompatibleDevice(vm->def, dev_copy) < 0)
            goto endjob;

        if ((ret = qemuDomainUpdateDeviceLive(dom->conn, vm, dev_copy, dom, force)) < 0)
            goto endjob;
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we failed to attach the device. For example,
         * a new controller may be created.
         */
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0) {
            ret = -1;
            goto endjob;
        }
    }

    /* Finally, if no error until here, we can save config. */
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

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

cleanup:
    virObjectUnref(qemuCaps);
    virDomainDefFree(vmdef);
    if (dev != dev_copy)
        virDomainDeviceDefFree(dev_copy);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
    virObjectUnref(caps);
    virObjectUnref(cfg);
    return ret;
6988 6989
}

6990

6991 6992 6993
static int qemuDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags)
{
6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019
    virQEMUDriverPtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL, dev_copy = NULL;
    int ret = -1;
    unsigned int affect;
    virQEMUCapsPtr qemuCaps = NULL;
    qemuDomainObjPrivatePtr priv;
    virQEMUDriverConfigPtr cfg = NULL;
    virCapsPtr caps = NULL;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

    cfg = virQEMUDriverGetConfig(driver);

    affect = flags & (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG);

    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;

    priv = vm->privateData;

7020 7021 7022
    if (virDomainDetachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;

    if (virDomainObjIsActive(vm)) {
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
            flags |= VIR_DOMAIN_AFFECT_LIVE;
    } else {
        if (affect == VIR_DOMAIN_AFFECT_CURRENT)
            flags |= VIR_DOMAIN_AFFECT_CONFIG;
        /* check consistency between flags and the vm state */
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot do live update a device on "
                             "inactive domain"));
            goto endjob;
        }
    }

    if ((flags & VIR_DOMAIN_AFFECT_CONFIG) && !vm->persistent) {
         virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("cannot modify device on transient domain"));
         goto endjob;
    }

    dev = dev_copy = virDomainDeviceDefParse(xml, vm->def,
                                             caps, driver->xmlopt,
                                             VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL)
        goto endjob;

    if (flags & VIR_DOMAIN_AFFECT_CONFIG &&
        flags & VIR_DOMAIN_AFFECT_LIVE) {
        /* If we are affecting both CONFIG and LIVE
         * create a deep copy of device as adding
         * to CONFIG takes one instance.
         */
        dev_copy = virDomainDeviceDefCopy(dev, vm->def, caps, driver->xmlopt);
        if (!dev_copy)
            goto endjob;
    }

    if (priv->qemuCaps)
        qemuCaps = virObjectRef(priv->qemuCaps);
    else if (!(qemuCaps = virQEMUCapsCacheLookup(driver->qemuCapsCache, vm->def->emulator)))
        goto cleanup;

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        if (virDomainDefCompatibleDevice(vm->def, dev) < 0)
            goto endjob;

        /* Make a copy for updated domain. */
        vmdef = virDomainObjCopyPersistentDef(vm, caps, driver->xmlopt);
        if (!vmdef)
            goto endjob;
        if ((ret = qemuDomainDetachDeviceConfig(vmdef, dev)) < 0)
            goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (virDomainDefCompatibleDevice(vm->def, dev_copy) < 0)
            goto endjob;

        if ((ret = qemuDomainDetachDeviceLive(vm, dev_copy, dom)) < 0)
            goto endjob;
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we failed to attach the device. For example,
         * a new controller may be created.
         */
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0) {
            ret = -1;
            goto endjob;
        }
    }

    /* Finally, if no error until here, we can save config. */
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

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

cleanup:
    virObjectUnref(qemuCaps);
    virDomainDefFree(vmdef);
    if (dev != dev_copy)
        virDomainDeviceDefFree(dev_copy);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
    virObjectUnref(caps);
    virObjectUnref(cfg);
    return ret;
7122 7123
}

7124 7125 7126
static int qemuDomainDetachDevice(virDomainPtr dom, const char *xml)
{
    return qemuDomainDetachDeviceFlags(dom, xml,
7127
                                       VIR_DOMAIN_AFFECT_LIVE);
7128 7129
}

7130 7131
static int qemuDomainGetAutostart(virDomainPtr dom,
                                  int *autostart) {
7132 7133
    virDomainObjPtr vm;
    int ret = -1;
7134

7135
    if (!(vm = qemuDomObjFromDomain(dom)))
7136
        goto cleanup;
7137

7138 7139 7140
    if (virDomainGetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

7141
    *autostart = vm->autostart;
7142
    ret = 0;
7143

7144
cleanup:
7145
    if (vm)
7146
        virObjectUnlock(vm);
7147
    return ret;
7148 7149
}

7150 7151
static int qemuDomainSetAutostart(virDomainPtr dom,
                                  int autostart) {
7152
    virQEMUDriverPtr driver = dom->conn->privateData;
7153
    virDomainObjPtr vm;
7154 7155
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
7156
    virQEMUDriverConfigPtr cfg = NULL;
7157

7158 7159 7160
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;

7161
    cfg = virQEMUDriverGetConfig(driver);
7162

7163 7164 7165
    if (virDomainSetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

7166
    if (!vm->persistent) {
7167 7168
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
7169
        goto cleanup;
7170 7171
    }

7172 7173
    autostart = (autostart != 0);

7174
    if (vm->autostart != autostart) {
7175
        if ((configFile = virDomainConfigFile(cfg->configDir, vm->def->name)) == NULL)
7176
            goto cleanup;
7177
        if ((autostartLink = virDomainConfigFile(cfg->autostartDir, vm->def->name)) == NULL)
7178
            goto cleanup;
7179

7180
        if (autostart) {
7181
            if (virFileMakePath(cfg->autostartDir) < 0) {
7182
                virReportSystemError(errno,
7183
                                     _("cannot create autostart directory %s"),
7184
                                     cfg->autostartDir);
7185 7186
                goto cleanup;
            }
7187

7188
            if (symlink(configFile, autostartLink) < 0) {
7189
                virReportSystemError(errno,
7190 7191
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
7192 7193 7194 7195
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
7196
                virReportSystemError(errno,
7197 7198
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
7199 7200
                goto cleanup;
            }
7201 7202
        }

7203
        vm->autostart = autostart;
7204
    }
7205
    ret = 0;
7206

7207 7208 7209
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
7210
    if (vm)
7211
        virObjectUnlock(vm);
7212
    virObjectUnref(cfg);
7213
    return ret;
7214 7215
}

7216

7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249
/*
 * check whether the host supports CFS bandwidth
 *
 * Return 1 when CFS bandwidth is supported, 0 when CFS bandwidth is not
 * supported, -1 on error.
 */
static int qemuGetCpuBWStatus(virCgroupPtr cgroup)
{
    char *cfs_period_path = NULL;
    int ret = -1;

    if (!cgroup)
        return 0;

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

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

cleanup:
    VIR_FREE(cfs_period_path);
    return ret;
}


7250 7251
static char *qemuDomainGetSchedulerType(virDomainPtr dom,
                                        int *nparams)
7252
{
7253
    virQEMUDriverPtr driver = dom->conn->privateData;
7254
    char *ret = NULL;
7255
    int rc;
7256 7257 7258 7259 7260 7261 7262 7263 7264 7265
    virDomainObjPtr vm = NULL;
    qemuDomainObjPrivatePtr priv;

    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
    if (vm == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No such domain %s"), dom->uuid);
        goto cleanup;
    }
    priv = vm->privateData;
7266

7267 7268 7269
    if (virDomainGetSchedulerTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

7270 7271 7272 7273 7274 7275 7276 7277
    /* Domain not running, thus no cgroups - return defaults */
    if (!virDomainObjIsActive(vm)) {
        if (nparams)
            *nparams = 5;
        ignore_value(VIR_STRDUP(ret, "posix"));
        goto cleanup;
    }

7278
    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
7279 7280
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cgroup CPU controller is not mounted"));
7281
        goto cleanup;
7282 7283
    }

7284
    if (nparams) {
7285
        rc = qemuGetCpuBWStatus(priv->cgroup);
7286 7287 7288 7289 7290
        if (rc < 0)
            goto cleanup;
        else if (rc == 0)
            *nparams = 1;
        else
7291
            *nparams = 5;
7292
    }
7293

7294
    ignore_value(VIR_STRDUP(ret, "posix"));
7295 7296

cleanup:
7297 7298
    if (vm)
        virObjectUnlock(vm);
7299 7300 7301
    return ret;
}

7302 7303 7304 7305
/* deviceWeightStr in the form of /device/path,weight,/device/path,weight
 * for example, /dev/disk/by-path/pci-0000:00:1f.2-scsi-0:0:0:0,800
 */
static int
7306 7307
qemuDomainParseDeviceWeightStr(char *deviceWeightStr,
                               virBlkioDeviceWeightPtr *dw, size_t *size)
7308 7309 7310 7311 7312 7313 7314
{
    char *temp;
    int ndevices = 0;
    int nsep = 0;
    int i;
    virBlkioDeviceWeightPtr result = NULL;

7315 7316 7317 7318 7319 7320
    *dw = NULL;
    *size = 0;

    if (STREQ(deviceWeightStr, ""))
        return 0;

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
    temp = deviceWeightStr;
    while (temp) {
        temp = strchr(temp, ',');
        if (temp) {
            temp++;
            nsep++;
        }
    }

    /* A valid string must have even number of fields, hence an odd
     * number of commas.  */
    if (!(nsep & 1))
        goto error;

    ndevices = (nsep + 1) / 2;

    if (VIR_ALLOC_N(result, ndevices) < 0) {
        virReportOOMError();
        return -1;
    }

    i = 0;
    temp = deviceWeightStr;
    while (temp) {
        char *p = temp;

        /* device path */
        p = strchr(p, ',');
        if (!p)
            goto error;

7352
        if (VIR_STRNDUP(result[i].path, temp, p - temp) < 0)
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
            goto cleanup;

        /* weight */
        temp = p + 1;

        if (virStrToLong_ui(temp, &p, 10, &result[i].weight) < 0)
            goto error;

        i++;

        if (*p == '\0')
            break;
        else if (*p != ',')
            goto error;
        temp = p + 1;
    }

    if (!i)
        VIR_FREE(result);

    *dw = result;
    *size = i;

    return 0;

error:
7379 7380
    virReportError(VIR_ERR_INVALID_ARG,
                   _("unable to parse device weight '%s'"), deviceWeightStr);
7381 7382 7383 7384 7385 7386
cleanup:
    virBlkioDeviceWeightArrayClear(result, ndevices);
    VIR_FREE(result);
    return -1;
}

7387 7388
/* Modify dest_array to reflect all device weight changes described in
 * src_array.  */
7389
static int
7390 7391 7392 7393
qemuDomainMergeDeviceWeights(virBlkioDeviceWeightPtr *dest_array,
                             size_t *dest_size,
                             virBlkioDeviceWeightPtr src_array,
                             size_t src_size)
7394 7395
{
    int i, j;
7396
    virBlkioDeviceWeightPtr dest, src;
7397

7398
    for (i = 0; i < src_size; i++) {
7399 7400
        bool found = false;

7401 7402 7403 7404
        src = &src_array[i];
        for (j = 0; j < *dest_size; j++) {
            dest = &(*dest_array)[j];
            if (STREQ(src->path, dest->path)) {
7405
                found = true;
7406
                dest->weight = src->weight;
7407 7408 7409 7410
                break;
            }
        }
        if (!found) {
7411
            if (!src->weight)
7412
                continue;
7413
            if (VIR_EXPAND_N(*dest_array, *dest_size, 1) < 0) {
7414 7415 7416
                virReportOOMError();
                return -1;
            }
7417 7418 7419 7420
            dest = &(*dest_array)[*dest_size - 1];
            dest->path = src->path;
            dest->weight = src->weight;
            src->path = NULL;
7421 7422 7423 7424 7425 7426
        }
    }

    return 0;
}

7427 7428 7429 7430 7431
static int
qemuDomainSetBlkioParameters(virDomainPtr dom,
                             virTypedParameterPtr params,
                             int nparams,
                             unsigned int flags)
7432
{
7433
    virQEMUDriverPtr driver = dom->conn->privateData;
7434 7435
    int i;
    virDomainObjPtr vm = NULL;
7436
    virDomainDefPtr persistentDef = NULL;
7437
    int ret = -1;
7438
    virQEMUDriverConfigPtr cfg = NULL;
7439
    virCapsPtr caps = NULL;
7440
    qemuDomainObjPrivatePtr priv;
7441

7442 7443
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
7444 7445 7446 7447 7448 7449
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_BLKIO_WEIGHT,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_BLKIO_DEVICE_WEIGHT,
                               VIR_TYPED_PARAM_STRING,
                               NULL) < 0)
7450
        return -1;
7451

7452 7453 7454
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;

7455
    priv = vm->privateData;
7456
    cfg = virQEMUDriverGetConfig(driver);
7457 7458 7459 7460

    if (virDomainSetBlkioParametersEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

7461 7462
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;
7463

7464
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
7465 7466
                                        &persistentDef) < 0)
        goto cleanup;
7467

7468
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7469
        if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_BLKIO)) {
7470 7471
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("blkio cgroup isn't mounted"));
7472 7473 7474 7475
            goto cleanup;
        }
    }

7476
    ret = 0;
7477 7478
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        for (i = 0; i < nparams; i++) {
7479
            int rc;
7480 7481 7482 7483
            virTypedParameterPtr param = &params[i];

            if (STREQ(param->field, VIR_DOMAIN_BLKIO_WEIGHT)) {
                if (params[i].value.ui > 1000 || params[i].value.ui < 100) {
7484 7485
                    virReportError(VIR_ERR_INVALID_ARG, "%s",
                                   _("out of blkio weight range."));
7486 7487 7488
                    ret = -1;
                    continue;
                }
7489

7490
                rc = virCgroupSetBlkioWeight(priv->cgroup, params[i].value.ui);
7491 7492 7493 7494 7495
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to set blkio weight tunable"));
                    ret = -1;
                }
7496
            } else if (STREQ(param->field, VIR_DOMAIN_BLKIO_DEVICE_WEIGHT)) {
7497
                size_t ndevices;
7498
                virBlkioDeviceWeightPtr devices = NULL;
7499 7500
                int j;

7501 7502 7503
                if (qemuDomainParseDeviceWeightStr(params[i].value.s,
                                                   &devices,
                                                   &ndevices) < 0) {
7504 7505 7506
                    ret = -1;
                    continue;
                }
7507
                for (j = 0; j < ndevices; j++) {
7508
                    rc = virCgroupSetBlkioDeviceWeight(priv->cgroup,
7509 7510
                                                       devices[j].path,
                                                       devices[j].weight);
7511 7512 7513 7514
                    if (rc < 0) {
                        virReportSystemError(-rc,
                                             _("Unable to set io device weight "
                                               "for path %s"),
7515
                                             devices[j].path);
7516 7517 7518
                        break;
                    }
                }
7519 7520
                if (j != ndevices ||
                    qemuDomainMergeDeviceWeights(&vm->def->blkio.devices,
7521 7522 7523 7524 7525
                                                 &vm->def->blkio.ndevices,
                                                 devices, ndevices) < 0)
                    ret = -1;
                virBlkioDeviceWeightArrayClear(devices, ndevices);
                VIR_FREE(devices);
7526
            }
7527
        }
E
Eric Blake 已提交
7528 7529 7530 7531
    }
    if (ret < 0)
        goto cleanup;
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
E
Eric Blake 已提交
7532 7533 7534
        /* Clang can't see that if we get here, persistentDef was set.  */
        sa_assert(persistentDef);

7535 7536 7537 7538 7539
        for (i = 0; i < nparams; i++) {
            virTypedParameterPtr param = &params[i];

            if (STREQ(param->field, VIR_DOMAIN_BLKIO_WEIGHT)) {
                if (params[i].value.ui > 1000 || params[i].value.ui < 100) {
7540 7541
                    virReportError(VIR_ERR_INVALID_ARG, "%s",
                                   _("out of blkio weight range."));
7542 7543 7544 7545 7546
                    ret = -1;
                    continue;
                }

                persistentDef->blkio.weight = params[i].value.ui;
7547 7548
            } else if (STREQ(param->field, VIR_DOMAIN_BLKIO_DEVICE_WEIGHT)) {
                virBlkioDeviceWeightPtr devices = NULL;
7549
                size_t ndevices;
7550

7551 7552 7553
                if (qemuDomainParseDeviceWeightStr(params[i].value.s,
                                                   &devices,
                                                   &ndevices) < 0) {
7554 7555 7556
                    ret = -1;
                    continue;
                }
7557 7558
                if (qemuDomainMergeDeviceWeights(&persistentDef->blkio.devices,
                                                 &persistentDef->blkio.ndevices,
7559 7560 7561 7562
                                                 devices, ndevices) < 0)
                    ret = -1;
                virBlkioDeviceWeightArrayClear(devices, ndevices);
                VIR_FREE(devices);
7563 7564
            }
        }
A
Alex Jia 已提交
7565

7566
        if (virDomainSaveConfig(cfg->configDir, persistentDef) < 0)
A
Alex Jia 已提交
7567
            ret = -1;
7568 7569 7570 7571
    }

cleanup:
    if (vm)
7572
        virObjectUnlock(vm);
7573
    virObjectUnref(caps);
7574
    virObjectUnref(cfg);
7575 7576 7577
    return ret;
}

7578 7579 7580 7581 7582
static int
qemuDomainGetBlkioParameters(virDomainPtr dom,
                             virTypedParameterPtr params,
                             int *nparams,
                             unsigned int flags)
7583
{
7584
    virQEMUDriverPtr driver = dom->conn->privateData;
7585
    int i, j;
7586
    virDomainObjPtr vm = NULL;
7587
    virDomainDefPtr persistentDef = NULL;
7588 7589 7590
    unsigned int val;
    int ret = -1;
    int rc;
7591
    virCapsPtr caps = NULL;
7592
    qemuDomainObjPrivatePtr priv;
7593

7594
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
7595 7596
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);
7597

7598 7599 7600
    /* We blindly return a string, and let libvirt.c and
     * remote_driver.c do the filtering on behalf of older clients
     * that can't parse it.  */
7601 7602
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

7603 7604
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
7605

7606 7607
    priv = vm->privateData;

7608 7609 7610
    if (virDomainGetBlkioParametersEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

7611 7612 7613
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

7614 7615 7616 7617 7618 7619 7620
    if ((*nparams) == 0) {
        /* Current number of blkio parameters supported by cgroups */
        *nparams = QEMU_NB_BLKIO_PARAM;
        ret = 0;
        goto cleanup;
    }

7621
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
7622 7623
                                        &persistentDef) < 0)
        goto cleanup;
7624

7625
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7626
        if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_BLKIO)) {
7627 7628
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("blkio cgroup isn't mounted"));
7629 7630 7631 7632 7633
            goto cleanup;
        }
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7634
        for (i = 0; i < *nparams && i < QEMU_NB_BLKIO_PARAM; i++) {
7635 7636 7637 7638 7639
            virTypedParameterPtr param = &params[i];
            val = 0;

            switch (i) {
            case 0: /* fill blkio weight here */
7640
                rc = virCgroupGetBlkioWeight(priv->cgroup, &val);
7641 7642 7643 7644 7645
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to get blkio weight"));
                    goto cleanup;
                }
7646 7647
                if (virTypedParameterAssign(param, VIR_DOMAIN_BLKIO_WEIGHT,
                                            VIR_TYPED_PARAM_UINT, val) < 0)
7648 7649
                    goto cleanup;
                break;
7650 7651 7652 7653
            case 1: /* blkiotune.device_weight */
                if (vm->def->blkio.ndevices > 0) {
                    virBuffer buf = VIR_BUFFER_INITIALIZER;
                    bool comma = false;
7654

7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671
                    for (j = 0; j < vm->def->blkio.ndevices; j++) {
                        if (!vm->def->blkio.devices[j].weight)
                            continue;
                        if (comma)
                            virBufferAddChar(&buf, ',');
                        else
                            comma = true;
                        virBufferAsprintf(&buf, "%s,%u",
                                          vm->def->blkio.devices[j].path,
                                          vm->def->blkio.devices[j].weight);
                    }
                    if (virBufferError(&buf)) {
                        virReportOOMError();
                        goto cleanup;
                    }
                    param->value.s = virBufferContentAndReset(&buf);
                }
7672 7673 7674 7675
                if (virTypedParameterAssign(param,
                                            VIR_DOMAIN_BLKIO_DEVICE_WEIGHT,
                                            VIR_TYPED_PARAM_STRING,
                                            param->value.s) < 0)
7676 7677
                    goto cleanup;
                break;
7678 7679 7680 7681

            default:
                break;
                /* should not hit here */
7682
            }
7683 7684
        }
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
7685
        for (i = 0; i < *nparams && i < QEMU_NB_BLKIO_PARAM; i++) {
7686 7687 7688 7689 7690 7691 7692 7693
            virTypedParameterPtr param = &params[i];
            val = 0;
            param->value.ui = 0;
            param->type = VIR_TYPED_PARAM_UINT;

            switch (i) {
            case 0: /* fill blkio weight here */
                if (virStrcpyStatic(param->field, VIR_DOMAIN_BLKIO_WEIGHT) == NULL) {
7694 7695 7696
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Field name '%s' too long"),
                                   VIR_DOMAIN_BLKIO_WEIGHT);
7697 7698 7699 7700
                    goto cleanup;
                }
                param->value.ui = persistentDef->blkio.weight;
                break;
7701

7702 7703 7704
            case 1: /* blkiotune.device_weight */
                if (persistentDef->blkio.ndevices > 0) {
                    virBuffer buf = VIR_BUFFER_INITIALIZER;
7705 7706
                    bool comma = false;

7707
                    for (j = 0; j < persistentDef->blkio.ndevices; j++) {
7708 7709 7710
                        if (!persistentDef->blkio.devices[j].weight)
                            continue;
                        if (comma)
7711
                            virBufferAddChar(&buf, ',');
7712 7713
                        else
                            comma = true;
7714 7715 7716 7717 7718 7719 7720 7721 7722
                        virBufferAsprintf(&buf, "%s,%u",
                                          persistentDef->blkio.devices[j].path,
                                          persistentDef->blkio.devices[j].weight);
                    }
                    if (virBufferError(&buf)) {
                        virReportOOMError();
                        goto cleanup;
                    }
                    param->value.s = virBufferContentAndReset(&buf);
7723
                }
7724 7725
                if (!param->value.s && VIR_STRDUP(param->value.s, "") < 0)
                    goto cleanup;
7726 7727 7728
                param->type = VIR_TYPED_PARAM_STRING;
                if (virStrcpyStatic(param->field,
                                    VIR_DOMAIN_BLKIO_DEVICE_WEIGHT) == NULL) {
7729 7730 7731
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Field name '%s' too long"),
                                   VIR_DOMAIN_BLKIO_DEVICE_WEIGHT);
7732 7733 7734 7735
                    goto cleanup;
                }
                break;

7736 7737 7738 7739
            default:
                break;
                /* should not hit here */
            }
7740 7741 7742
        }
    }

7743 7744
    if (QEMU_NB_BLKIO_PARAM < *nparams)
        *nparams = QEMU_NB_BLKIO_PARAM;
7745 7746 7747 7748
    ret = 0;

cleanup:
    if (vm)
7749
        virObjectUnlock(vm);
7750
    virObjectUnref(caps);
7751 7752
    return ret;
}
7753

7754 7755 7756 7757 7758
static int
qemuDomainSetMemoryParameters(virDomainPtr dom,
                              virTypedParameterPtr params,
                              int nparams,
                              unsigned int flags)
7759
{
7760
    virQEMUDriverPtr driver = dom->conn->privateData;
7761
    virDomainDefPtr persistentDef = NULL;
7762
    virDomainObjPtr vm = NULL;
7763
    unsigned long long swap_hard_limit;
7764 7765
    unsigned long long hard_limit = 0;
    unsigned long long soft_limit = 0;
7766
    bool set_swap_hard_limit = false;
7767 7768
    bool set_hard_limit = false;
    bool set_soft_limit = false;
7769
    virQEMUDriverConfigPtr cfg = NULL;
7770
    int ret = -1;
7771
    int rc;
7772
    virCapsPtr caps = NULL;
7773
    qemuDomainObjPrivatePtr priv;
7774

7775 7776
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
7777

7778 7779 7780 7781 7782 7783 7784 7785
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_MEMORY_HARD_LIMIT,
                               VIR_TYPED_PARAM_ULLONG,
                               VIR_DOMAIN_MEMORY_SOFT_LIMIT,
                               VIR_TYPED_PARAM_ULLONG,
                               VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT,
                               VIR_TYPED_PARAM_ULLONG,
                               NULL) < 0)
7786
        return -1;
7787 7788


7789 7790
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
7791

7792
    priv = vm->privateData;
7793 7794
    cfg = virQEMUDriverGetConfig(driver);

7795 7796 7797
    if (virDomainSetMemoryParametersEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

7798 7799 7800
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

7801
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
7802 7803
                                        &persistentDef) < 0)
        goto cleanup;
7804

7805
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7806
        if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_MEMORY)) {
7807 7808
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("cgroup memory controller is not mounted"));
7809 7810 7811 7812
            goto cleanup;
        }
    }

7813
#define VIR_GET_LIMIT_PARAMETER(PARAM, VALUE)                                \
7814
    if ((rc = virTypedParamsGetULLong(params, nparams, PARAM, &VALUE)) < 0)  \
7815 7816 7817 7818 7819 7820
        goto cleanup;                                                        \
                                                                             \
    if (rc == 1)                                                             \
        set_ ## VALUE = true;

    VIR_GET_LIMIT_PARAMETER(VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT, swap_hard_limit)
7821 7822
    VIR_GET_LIMIT_PARAMETER(VIR_DOMAIN_MEMORY_HARD_LIMIT, hard_limit)
    VIR_GET_LIMIT_PARAMETER(VIR_DOMAIN_MEMORY_SOFT_LIMIT, soft_limit)
7823 7824 7825

#undef VIR_GET_LIMIT_PARAMETER

7826 7827 7828 7829 7830
    /* Swap hard limit must be greater than hard limit.
     * Note that limit of 0 denotes unlimited */
    if (set_swap_hard_limit || set_hard_limit) {
        unsigned long long mem_limit = vm->def->mem.hard_limit;
        unsigned long long swap_limit = vm->def->mem.swap_hard_limit;
7831

7832 7833
        if (set_swap_hard_limit)
            swap_limit = swap_hard_limit;
7834

7835 7836 7837 7838 7839 7840 7841 7842
        if (set_hard_limit)
            mem_limit = hard_limit;

        if (virCompareLimitUlong(mem_limit, swap_limit) > 0) {
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("memory hard_limit tunable value must be lower "
                             "than swap_hard_limit"));
            goto cleanup;
7843
        }
7844
    }
7845

7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859
#define QEMU_SET_MEM_PARAMETER(FUNC, VALUE)                                     \
    if (set_ ## VALUE) {                                                        \
        if (flags & VIR_DOMAIN_AFFECT_LIVE) {                                   \
            if ((rc = FUNC(priv->cgroup, VALUE)) < 0) {                         \
                virReportSystemError(-rc, _("unable to set memory %s tunable"), \
                                     #VALUE);                                   \
                                                                                \
                goto cleanup;                                                   \
            }                                                                   \
            vm->def->mem.VALUE = VALUE;                                         \
        }                                                                       \
                                                                                \
        if (flags & VIR_DOMAIN_AFFECT_CONFIG)                                   \
            persistentDef->mem.VALUE = VALUE;                                   \
7860 7861
    }

7862 7863
    /* Soft limit doesn't clash with the others */
    QEMU_SET_MEM_PARAMETER(virCgroupSetMemorySoftLimit, soft_limit);
7864

7865 7866 7867 7868 7869
    /* set hard limit before swap hard limit if decreasing it */
    if (virCompareLimitUlong(vm->def->mem.hard_limit, hard_limit) > 0) {
        QEMU_SET_MEM_PARAMETER(virCgroupSetMemoryHardLimit, hard_limit);
        /* inhibit changing the limit a second time */
        set_hard_limit = false;
7870
    }
7871

7872
    QEMU_SET_MEM_PARAMETER(virCgroupSetMemSwapHardLimit, swap_hard_limit);
7873

7874 7875 7876 7877
    /* otherwise increase it after swap hard limit */
    QEMU_SET_MEM_PARAMETER(virCgroupSetMemoryHardLimit, hard_limit);

#undef QEMU_SET_MEM_PARAMETER
7878

7879 7880 7881 7882 7883 7884
    if (flags & VIR_DOMAIN_AFFECT_CONFIG &&
        virDomainSaveConfig(cfg->configDir, persistentDef) < 0)
        goto cleanup;

    ret = 0;

7885
cleanup:
7886
    virObjectUnlock(vm);
7887
    virObjectUnref(caps);
7888
    virObjectUnref(cfg);
7889 7890 7891
    return ret;
}

7892 7893 7894 7895 7896
static int
qemuDomainGetMemoryParameters(virDomainPtr dom,
                              virTypedParameterPtr params,
                              int *nparams,
                              unsigned int flags)
7897
{
7898
    virQEMUDriverPtr driver = dom->conn->privateData;
7899 7900
    int i;
    virDomainObjPtr vm = NULL;
7901
    virDomainDefPtr persistentDef = NULL;
7902 7903
    int ret = -1;
    int rc;
7904
    virCapsPtr caps = NULL;
7905
    qemuDomainObjPrivatePtr priv;
7906

7907
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
7908 7909
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);
7910

7911 7912 7913
    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

7914 7915
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
7916

7917
    priv = vm->privateData;
7918 7919 7920 7921

    if (virDomainGetMemoryParametersEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

7922 7923 7924
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

7925
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
7926 7927
                                        &persistentDef) < 0)
        goto cleanup;
7928

7929
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
7930
        if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_MEMORY)) {
7931 7932
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("cgroup memory controller is not mounted"));
7933 7934 7935 7936
            goto cleanup;
        }
    }

7937 7938 7939 7940 7941 7942 7943
    if ((*nparams) == 0) {
        /* Current number of memory parameters supported by cgroups */
        *nparams = QEMU_NB_MEM_PARAM;
        ret = 0;
        goto cleanup;
    }

7944
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
7945
        for (i = 0; i < *nparams && i < QEMU_NB_MEM_PARAM; i++) {
7946 7947 7948 7949
            virMemoryParameterPtr param = &params[i];

            switch (i) {
            case 0: /* fill memory hard limit here */
7950 7951 7952 7953
                if (virTypedParameterAssign(param,
                                            VIR_DOMAIN_MEMORY_HARD_LIMIT,
                                            VIR_TYPED_PARAM_ULLONG,
                                            persistentDef->mem.hard_limit) < 0)
7954 7955 7956 7957
                    goto cleanup;
                break;

            case 1: /* fill memory soft limit here */
7958 7959 7960 7961
                if (virTypedParameterAssign(param,
                                            VIR_DOMAIN_MEMORY_SOFT_LIMIT,
                                            VIR_TYPED_PARAM_ULLONG,
                                            persistentDef->mem.soft_limit) < 0)
7962 7963 7964 7965
                    goto cleanup;
                break;

            case 2: /* fill swap hard limit here */
7966 7967 7968 7969
                if (virTypedParameterAssign(param,
                                            VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT,
                                            VIR_TYPED_PARAM_ULLONG,
                                            persistentDef->mem.swap_hard_limit) < 0)
7970 7971 7972 7973 7974 7975 7976 7977 7978
                    goto cleanup;
                break;

            default:
                break;
                /* should not hit here */
            }
        }
        goto out;
7979 7980
    }

7981
    for (i = 0; i < *nparams && i < QEMU_NB_MEM_PARAM; i++) {
7982
        virTypedParameterPtr param = &params[i];
7983
        unsigned long long val = 0;
7984

7985
        switch (i) {
7986
        case 0: /* fill memory hard limit here */
7987
            rc = virCgroupGetMemoryHardLimit(priv->cgroup, &val);
7988 7989 7990
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory hard limit"));
7991
                goto cleanup;
7992
            }
7993 7994 7995
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_MEMORY_HARD_LIMIT,
                                        VIR_TYPED_PARAM_ULLONG, val) < 0)
7996
                goto cleanup;
7997 7998 7999
            break;

        case 1: /* fill memory soft limit here */
8000
            rc = virCgroupGetMemorySoftLimit(priv->cgroup, &val);
8001 8002 8003
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory soft limit"));
8004
                goto cleanup;
8005
            }
8006 8007 8008
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_MEMORY_SOFT_LIMIT,
                                        VIR_TYPED_PARAM_ULLONG, val) < 0)
8009
                goto cleanup;
8010 8011 8012
            break;

        case 2: /* fill swap hard limit here */
8013
            rc = virCgroupGetMemSwapHardLimit(priv->cgroup, &val);
8014
            if (rc != 0) {
8015 8016 8017 8018 8019 8020
                if (rc != -ENOENT) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to get swap hard limit"));
                    goto cleanup;
                }
                val = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
8021
            }
8022 8023 8024
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT,
                                        VIR_TYPED_PARAM_ULLONG, val) < 0)
8025
                goto cleanup;
8026 8027 8028 8029 8030 8031 8032 8033
            break;

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

8034
out:
8035 8036
    if (QEMU_NB_MEM_PARAM < *nparams)
        *nparams = QEMU_NB_MEM_PARAM;
8037 8038
    ret = 0;

8039 8040
cleanup:
    if (vm)
8041
        virObjectUnlock(vm);
8042
    virObjectUnref(caps);
8043 8044 8045
    return ret;
}

8046 8047 8048 8049 8050 8051
static int
qemuDomainSetNumaParameters(virDomainPtr dom,
                            virTypedParameterPtr params,
                            int nparams,
                            unsigned int flags)
{
8052
    virQEMUDriverPtr driver = dom->conn->privateData;
8053 8054 8055 8056
    int i;
    virDomainDefPtr persistentDef = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;
8057
    virQEMUDriverConfigPtr cfg = NULL;
8058
    virCapsPtr caps = NULL;
8059
    qemuDomainObjPrivatePtr priv;
8060 8061 8062

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
8063 8064 8065 8066 8067 8068
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_NUMA_MODE,
                               VIR_TYPED_PARAM_INT,
                               VIR_DOMAIN_NUMA_NODESET,
                               VIR_TYPED_PARAM_STRING,
                               NULL) < 0)
8069
        return -1;
8070

8071 8072
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
8073

8074
    priv = vm->privateData;
8075
    cfg = virQEMUDriverGetConfig(driver);
8076

8077 8078 8079
    if (virDomainSetNumaParametersEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

8080 8081 8082
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

8083
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
8084 8085 8086 8087
                                        &persistentDef) < 0)
        goto cleanup;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
8088
        if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET)) {
8089 8090
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("cgroup cpuset controller is not mounted"));
8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101
            goto cleanup;
        }
    }

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

        if (STREQ(param->field, VIR_DOMAIN_NUMA_MODE)) {
            if ((flags & VIR_DOMAIN_AFFECT_LIVE) &&
                vm->def->numatune.memory.mode != params[i].value.i) {
8102 8103
                virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                               _("can't change numa mode for running domain"));
8104 8105 8106 8107 8108 8109 8110 8111 8112
                ret = -1;
                goto cleanup;
            }

            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
                persistentDef->numatune.memory.mode = params[i].value.i;
            }
        } else if (STREQ(param->field, VIR_DOMAIN_NUMA_NODESET)) {
            int rc;
8113
            virBitmapPtr nodeset = NULL;
8114 8115
            char *nodeset_str = NULL;

8116 8117 8118
            if (virBitmapParse(params[i].value.s,
                               0, &nodeset,
                               VIR_DOMAIN_CPUMASK_LEN) < 0) {
8119 8120 8121 8122 8123
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to parse nodeset"));
                ret = -1;
                continue;
            }
8124 8125 8126 8127

            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
                if (vm->def->numatune.memory.mode !=
                    VIR_DOMAIN_NUMATUNE_MEM_STRICT) {
8128 8129 8130
                    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                   _("change of nodeset for running domain "
                                     "requires strict numa mode"));
8131
                    virBitmapFree(nodeset);
8132 8133 8134
                    ret = -1;
                    continue;
                }
8135 8136

                /* Ensure the cpuset string is formated before passing to cgroup */
8137
                if (!(nodeset_str = virBitmapFormat(nodeset))) {
8138 8139
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("Failed to format nodeset"));
8140
                    virBitmapFree(nodeset);
8141 8142 8143 8144
                    ret = -1;
                    continue;
                }

O
Osier Yang 已提交
8145
                if ((rc = virCgroupSetCpusetMems(priv->cgroup, nodeset_str)) != 0) {
8146 8147
                    virReportSystemError(-rc, "%s",
                                         _("unable to set numa tunable"));
8148
                    virBitmapFree(nodeset);
8149
                    VIR_FREE(nodeset_str);
8150 8151 8152
                    ret = -1;
                    continue;
                }
8153
                VIR_FREE(nodeset_str);
8154 8155 8156

                /* update vm->def here so that dumpxml can read the new
                 * values from vm->def. */
8157
                virBitmapFree(vm->def->numatune.memory.nodemask);
8158

8159
                vm->def->numatune.memory.placement_mode =
G
Gao feng 已提交
8160
                    VIR_NUMA_TUNE_MEM_PLACEMENT_MODE_STATIC;
8161
                vm->def->numatune.memory.nodemask = virBitmapNewCopy(nodeset);
8162 8163 8164
            }

            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
8165
                virBitmapFree(persistentDef->numatune.memory.nodemask);
8166 8167

                persistentDef->numatune.memory.nodemask = nodeset;
8168
                persistentDef->numatune.memory.placement_mode =
G
Gao feng 已提交
8169
                    VIR_NUMA_TUNE_MEM_PLACEMENT_MODE_STATIC;
8170
                nodeset = NULL;
8171
            }
8172
            virBitmapFree(nodeset);
8173 8174 8175 8176
        }
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
8177 8178
        if (!persistentDef->numatune.memory.placement_mode)
            persistentDef->numatune.memory.placement_mode =
G
Gao feng 已提交
8179
                VIR_NUMA_TUNE_MEM_PLACEMENT_MODE_AUTO;
8180
        if (virDomainSaveConfig(cfg->configDir, persistentDef) < 0)
8181 8182 8183 8184 8185
            ret = -1;
    }

cleanup:
    if (vm)
8186
        virObjectUnlock(vm);
8187
    virObjectUnref(caps);
8188
    virObjectUnref(cfg);
8189 8190 8191 8192 8193 8194 8195 8196 8197
    return ret;
}

static int
qemuDomainGetNumaParameters(virDomainPtr dom,
                            virTypedParameterPtr params,
                            int *nparams,
                            unsigned int flags)
{
8198
    virQEMUDriverPtr driver = dom->conn->privateData;
8199 8200 8201 8202 8203 8204
    int i;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr persistentDef = NULL;
    char *nodeset = NULL;
    int ret = -1;
    int rc;
8205
    virCapsPtr caps = NULL;
8206
    qemuDomainObjPrivatePtr priv;
8207 8208 8209 8210 8211 8212 8213 8214 8215 8216

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);

    /* We blindly return a string, and let libvirt.c and
     * remote_driver.c do the filtering on behalf of older clients
     * that can't parse it.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

8217 8218
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
8219

8220 8221
    priv = vm->privateData;

8222 8223 8224
    if (virDomainGetNumaParametersEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

8225 8226 8227
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

8228
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
8229 8230 8231 8232 8233 8234 8235 8236 8237 8238
                                        &persistentDef) < 0)
        goto cleanup;

    if ((*nparams) == 0) {
        *nparams = QEMU_NB_NUMA_PARAM;
        ret = 0;
        goto cleanup;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
8239
        if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_MEMORY)) {
8240 8241
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("cgroup memory controller is not mounted"));
8242 8243 8244 8245 8246 8247 8248 8249 8250
            goto cleanup;
        }
    }

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

        switch (i) {
        case 0: /* fill numa mode here */
8251 8252
            if (virTypedParameterAssign(param, VIR_DOMAIN_NUMA_MODE,
                                        VIR_TYPED_PARAM_INT, 0) < 0)
8253 8254 8255 8256 8257 8258 8259 8260 8261
                goto cleanup;
            if (flags & VIR_DOMAIN_AFFECT_CONFIG)
                param->value.i = persistentDef->numatune.memory.mode;
            else
                param->value.i = vm->def->numatune.memory.mode;
            break;

        case 1: /* fill numa nodeset here */
            if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
8262
                nodeset = virBitmapFormat(persistentDef->numatune.memory.nodemask);
8263 8264
                if (!nodeset && VIR_STRDUP(nodeset, "") < 0)
                    goto cleanup;
8265
            } else {
8266
                rc = virCgroupGetCpusetMems(priv->cgroup, &nodeset);
8267 8268 8269 8270 8271 8272
                if (rc != 0) {
                    virReportSystemError(-rc, "%s",
                                         _("unable to get numa nodeset"));
                    goto cleanup;
                }
            }
8273 8274
            if (virTypedParameterAssign(param, VIR_DOMAIN_NUMA_NODESET,
                                        VIR_TYPED_PARAM_STRING, nodeset) < 0)
8275
                goto cleanup;
S
Stefan Berger 已提交
8276 8277 8278

            nodeset = NULL;

8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291
            break;

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

    if (*nparams > QEMU_NB_NUMA_PARAM)
        *nparams = QEMU_NB_NUMA_PARAM;
    ret = 0;

cleanup:
S
Stefan Berger 已提交
8292
    VIR_FREE(nodeset);
8293
    if (vm)
8294
        virObjectUnlock(vm);
8295
    virObjectUnref(caps);
8296 8297 8298
    return ret;
}

8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310
static int
qemuSetVcpusBWLive(virDomainObjPtr vm, virCgroupPtr cgroup,
                   unsigned long long period, long long quota)
{
    int i;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virCgroupPtr cgroup_vcpu = NULL;
    int rc;

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

W
Wen Congyang 已提交
8311 8312 8313 8314 8315 8316
    /* If we does not know VCPU<->PID mapping or all vcpu runs in the same
     * thread, we cannot control each vcpu. So we only modify cpu bandwidth
     * when each vcpu has a separated thread.
     */
    if (priv->nvcpupids != 0 && priv->vcpupids[0] != vm->pid) {
        for (i = 0; i < priv->nvcpupids; i++) {
8317
            rc = virCgroupNewVcpu(cgroup, i, false, &cgroup_vcpu);
W
Wen Congyang 已提交
8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330
            if (rc < 0) {
                virReportSystemError(-rc,
                                     _("Unable to find vcpu cgroup for %s(vcpu:"
                                       " %d)"),
                                     vm->def->name, i);
                goto cleanup;
            }

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

            virCgroupFree(&cgroup_vcpu);
        }
8331 8332 8333 8334 8335 8336 8337 8338 8339
    }

    return 0;

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

8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354
static int
qemuSetEmulatorBandwidthLive(virDomainObjPtr vm, virCgroupPtr cgroup,
                             unsigned long long period, long long quota)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virCgroupPtr cgroup_emulator = NULL;
    int rc;

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

    if (priv->nvcpupids == 0 || priv->vcpupids[0] == vm->pid) {
        return 0;
    }

8355
    rc = virCgroupNewEmulator(cgroup, false, &cgroup_emulator);
8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373
    if (rc < 0) {
        virReportSystemError(-rc,
                             _("Unable to find emulator cgroup for %s"),
                             vm->def->name);
        goto cleanup;
    }

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

    virCgroupFree(&cgroup_emulator);
    return 0;

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

8374 8375 8376 8377 8378 8379 8380 8381 8382
#define SCHED_RANGE_CHECK(VAR, NAME, MIN, MAX)                              \
    if (((VAR) > 0 && (VAR) < (MIN)) || (VAR) > (MAX)) {                    \
        virReportError(VIR_ERR_INVALID_ARG,                                 \
                       _("value of '%s' is out of range [%lld, %lld]"),     \
                       NAME, MIN, MAX);                                     \
        rc = -1;                                                            \
        goto cleanup;                                                       \
    }

8383
static int
8384 8385 8386 8387
qemuDomainSetSchedulerParametersFlags(virDomainPtr dom,
                                      virTypedParameterPtr params,
                                      int nparams,
                                      unsigned int flags)
8388
{
8389
    virQEMUDriverPtr driver = dom->conn->privateData;
8390 8391
    int i;
    virDomainObjPtr vm = NULL;
8392
    virDomainDefPtr vmdef = NULL;
8393 8394
    unsigned long long value_ul;
    long long value_l;
8395
    int ret = -1;
8396
    int rc;
8397
    virQEMUDriverConfigPtr cfg = NULL;
8398
    virCapsPtr caps = NULL;
8399
    qemuDomainObjPrivatePtr priv;
8400

8401 8402
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_SCHEDULER_CPU_SHARES,
                               VIR_TYPED_PARAM_ULLONG,
                               VIR_DOMAIN_SCHEDULER_VCPU_PERIOD,
                               VIR_TYPED_PARAM_ULLONG,
                               VIR_DOMAIN_SCHEDULER_VCPU_QUOTA,
                               VIR_TYPED_PARAM_LLONG,
                               VIR_DOMAIN_SCHEDULER_EMULATOR_PERIOD,
                               VIR_TYPED_PARAM_ULLONG,
                               VIR_DOMAIN_SCHEDULER_EMULATOR_QUOTA,
                               VIR_TYPED_PARAM_LLONG,
                               NULL) < 0)
8415
        return -1;
8416

8417 8418
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
8419

8420
    priv = vm->privateData;
8421 8422
    cfg = virQEMUDriverGetConfig(driver);

8423 8424 8425
    if (virDomainSetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

8426 8427 8428
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

8429
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
8430 8431
                                        &vmdef) < 0)
        goto cleanup;
8432

8433 8434
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        /* Make a copy for updated domain. */
8435
        vmdef = virDomainObjCopyPersistentDef(vm, caps, driver->xmlopt);
8436 8437
        if (!vmdef)
            goto cleanup;
8438 8439
    }

8440
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
8441
        if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
8442 8443
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("cgroup CPU controller is not mounted"));
8444 8445 8446 8447
            goto cleanup;
        }
    }

8448
    for (i = 0; i < nparams; i++) {
8449
        virTypedParameterPtr param = &params[i];
8450 8451
        value_ul = param->value.ul;
        value_l = param->value.l;
8452

8453
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CPU_SHARES)) {
8454
            if (flags & VIR_DOMAIN_AFFECT_LIVE) {
8455
                if ((rc = virCgroupSetCpuShares(priv->cgroup, value_ul))) {
8456 8457 8458 8459
                    virReportSystemError(-rc, "%s",
                                         _("unable to set cpu shares tunable"));
                    goto cleanup;
                }
8460
                vm->def->cputune.shares = value_ul;
8461
            }
8462

8463 8464 8465
            if (flags & VIR_DOMAIN_AFFECT_CONFIG)
                vmdef->cputune.shares = value_ul;

8466
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_VCPU_PERIOD)) {
8467 8468 8469
            SCHED_RANGE_CHECK(value_ul, VIR_DOMAIN_SCHEDULER_VCPU_PERIOD,
                              QEMU_SCHED_MIN_PERIOD, QEMU_SCHED_MAX_PERIOD);

8470
            if (flags & VIR_DOMAIN_AFFECT_LIVE && value_ul) {
8471
                if ((rc = qemuSetVcpusBWLive(vm, priv->cgroup, value_ul, 0)))
8472
                    goto cleanup;
8473

8474
                vm->def->cputune.period = value_ul;
8475 8476
            }

8477
            if (flags & VIR_DOMAIN_AFFECT_CONFIG)
8478
                vmdef->cputune.period = params[i].value.ul;
8479

8480
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_VCPU_QUOTA)) {
8481 8482 8483
            SCHED_RANGE_CHECK(value_l, VIR_DOMAIN_SCHEDULER_VCPU_QUOTA,
                              QEMU_SCHED_MIN_QUOTA, QEMU_SCHED_MAX_QUOTA);

8484
            if (flags & VIR_DOMAIN_AFFECT_LIVE && value_l) {
8485
                if ((rc = qemuSetVcpusBWLive(vm, priv->cgroup, 0, value_l)))
8486
                    goto cleanup;
8487

8488
                vm->def->cputune.quota = value_l;
8489 8490
            }

8491 8492 8493
            if (flags & VIR_DOMAIN_AFFECT_CONFIG)
                vmdef->cputune.quota = value_l;

8494
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_EMULATOR_PERIOD)) {
8495 8496 8497
            SCHED_RANGE_CHECK(value_ul, VIR_DOMAIN_SCHEDULER_EMULATOR_PERIOD,
                              QEMU_SCHED_MIN_PERIOD, QEMU_SCHED_MAX_PERIOD);

8498
            if (flags & VIR_DOMAIN_AFFECT_LIVE && value_ul) {
8499 8500
                if ((rc = qemuSetEmulatorBandwidthLive(vm, priv->cgroup,
                                                       value_ul, 0)))
8501 8502
                    goto cleanup;

8503
                vm->def->cputune.emulator_period = value_ul;
8504 8505
            }

8506 8507 8508
            if (flags & VIR_DOMAIN_AFFECT_CONFIG)
                vmdef->cputune.emulator_period = value_ul;

8509
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_EMULATOR_QUOTA)) {
8510 8511 8512
            SCHED_RANGE_CHECK(value_l, VIR_DOMAIN_SCHEDULER_EMULATOR_QUOTA,
                              QEMU_SCHED_MIN_QUOTA, QEMU_SCHED_MAX_QUOTA);

8513
            if (flags & VIR_DOMAIN_AFFECT_LIVE && value_l) {
8514 8515
                if ((rc = qemuSetEmulatorBandwidthLive(vm, priv->cgroup,
                                                       0, value_l)))
8516 8517
                    goto cleanup;

8518
                vm->def->cputune.emulator_quota = value_l;
8519 8520
            }

8521 8522
            if (flags & VIR_DOMAIN_AFFECT_CONFIG)
                vmdef->cputune.emulator_quota = value_l;
8523 8524
        }
    }
8525

8526
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
8527 8528 8529 8530
        goto cleanup;


    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
8531
        rc = virDomainSaveConfig(cfg->configDir, vmdef);
8532 8533 8534
        if (rc < 0)
            goto cleanup;

8535
        virDomainObjAssignDef(vm, vmdef, false, NULL);
8536 8537 8538
        vmdef = NULL;
    }

8539 8540 8541
    ret = 0;

cleanup:
8542
    virDomainDefFree(vmdef);
8543
    if (vm)
8544
        virObjectUnlock(vm);
8545
    virObjectUnref(caps);
8546
    virObjectUnref(cfg);
8547 8548
    return ret;
}
8549
#undef SCHED_RANGE_CHECK
8550

8551
static int
8552 8553 8554
qemuDomainSetSchedulerParameters(virDomainPtr dom,
                                 virTypedParameterPtr params,
                                 int nparams)
8555
{
8556 8557 8558 8559
    return qemuDomainSetSchedulerParametersFlags(dom,
                                                 params,
                                                 nparams,
                                                 VIR_DOMAIN_AFFECT_CURRENT);
8560 8561
}

8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585
static int
qemuGetVcpuBWLive(virCgroupPtr cgroup, unsigned long long *period,
                  long long *quota)
{
    int rc;

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

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

    return 0;
}

static int
8586
qemuGetVcpusBWLive(virDomainObjPtr vm,
8587 8588 8589 8590 8591 8592 8593 8594 8595 8596
                   unsigned long long *period, long long *quota)
{
    virCgroupPtr cgroup_vcpu = NULL;
    qemuDomainObjPrivatePtr priv = NULL;
    int rc;
    int ret = -1;

    priv = vm->privateData;
    if (priv->nvcpupids == 0 || priv->vcpupids[0] == vm->pid) {
        /* We do not create sub dir for each vcpu */
8597
        rc = qemuGetVcpuBWLive(priv->cgroup, period, quota);
8598 8599 8600 8601 8602 8603 8604 8605 8606
        if (rc < 0)
            goto cleanup;

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

    /* get period and quota for vcpu0 */
8607
    rc = virCgroupNewVcpu(priv->cgroup, 0, false, &cgroup_vcpu);
8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626
    if (!cgroup_vcpu) {
        virReportSystemError(-rc,
                             _("Unable to find vcpu cgroup for %s(vcpu: 0)"),
                             vm->def->name);
        goto cleanup;
    }

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

out:
    ret = 0;

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

8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644
static int
qemuGetEmulatorBandwidthLive(virDomainObjPtr vm, virCgroupPtr cgroup,
                             unsigned long long *period, long long *quota)
{
    virCgroupPtr cgroup_emulator = NULL;
    qemuDomainObjPrivatePtr priv = NULL;
    int rc;
    int ret = -1;

    priv = vm->privateData;
    if (priv->nvcpupids == 0 || priv->vcpupids[0] == vm->pid) {
        /* We don't create sub dir for each vcpu */
        *period = 0;
        *quota = 0;
        return 0;
    }

    /* get period and quota for emulator */
8645
    rc = virCgroupNewEmulator(cgroup, false, &cgroup_emulator);
8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663
    if (!cgroup_emulator) {
        virReportSystemError(-rc,
                             _("Unable to find emulator cgroup for %s"),
                             vm->def->name);
        goto cleanup;
    }

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

    ret = 0;

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

8664
static int
8665 8666 8667 8668
qemuDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                      virTypedParameterPtr params,
                                      int *nparams,
                                      unsigned int flags)
8669
{
8670
    virQEMUDriverPtr driver = dom->conn->privateData;
8671
    virDomainObjPtr vm = NULL;
8672 8673 8674
    unsigned long long shares;
    unsigned long long period;
    long long quota;
8675 8676
    unsigned long long emulator_period;
    long long emulator_quota;
8677 8678
    int ret = -1;
    int rc;
8679
    bool cpu_bw_status = false;
8680
    int saved_nparams = 0;
8681
    virDomainDefPtr persistentDef;
8682
    virCapsPtr caps = NULL;
8683
    qemuDomainObjPrivatePtr priv;
8684

8685
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
8686 8687
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);
8688

8689 8690 8691
    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

8692 8693 8694 8695 8696
    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;

    priv = vm->privateData;

8697 8698 8699
    if (virDomainGetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

8700
    if (*nparams > 1) {
8701
        rc = qemuGetCpuBWStatus(priv->cgroup);
8702 8703 8704 8705 8706
        if (rc < 0)
            goto cleanup;
        cpu_bw_status = !!rc;
    }

8707 8708 8709
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

8710
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
8711 8712
                                        &persistentDef) < 0)
        goto cleanup;
8713

8714
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
8715
        shares = persistentDef->cputune.shares;
8716
        if (*nparams > 1) {
8717 8718
            period = persistentDef->cputune.period;
            quota = persistentDef->cputune.quota;
8719 8720
            emulator_period = persistentDef->cputune.emulator_period;
            emulator_quota = persistentDef->cputune.emulator_quota;
8721
            cpu_bw_status = true; /* Allow copy of data to params[] */
8722
        }
8723
        goto out;
8724 8725
    }

8726
    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
8727 8728
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cgroup CPU controller is not mounted"));
8729 8730 8731
        goto cleanup;
    }

8732
    rc = virCgroupGetCpuShares(priv->cgroup, &shares);
8733
    if (rc != 0) {
8734
        virReportSystemError(-rc, "%s",
8735 8736 8737
                             _("unable to get cpu shares tunable"));
        goto cleanup;
    }
8738 8739

    if (*nparams > 1 && cpu_bw_status) {
8740
        rc = qemuGetVcpusBWLive(vm, &period, &quota);
8741 8742 8743
        if (rc != 0)
            goto cleanup;
    }
8744 8745

    if (*nparams > 3 && cpu_bw_status) {
8746
        rc = qemuGetEmulatorBandwidthLive(vm, priv->cgroup, &emulator_period,
8747 8748 8749 8750 8751
                                          &emulator_quota);
        if (rc != 0)
            goto cleanup;
    }

8752
out:
8753 8754
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CPU_SHARES,
                                VIR_TYPED_PARAM_ULLONG, shares) < 0)
C
Chris Lalancette 已提交
8755
        goto cleanup;
8756 8757 8758 8759
    saved_nparams++;

    if (cpu_bw_status) {
        if (*nparams > saved_nparams) {
8760 8761 8762
            if (virTypedParameterAssign(&params[1],
                                        VIR_DOMAIN_SCHEDULER_VCPU_PERIOD,
                                        VIR_TYPED_PARAM_ULLONG, period) < 0)
8763 8764 8765 8766 8767
                goto cleanup;
            saved_nparams++;
        }

        if (*nparams > saved_nparams) {
8768 8769 8770
            if (virTypedParameterAssign(&params[2],
                                        VIR_DOMAIN_SCHEDULER_VCPU_QUOTA,
                                        VIR_TYPED_PARAM_LLONG, quota) < 0)
8771 8772 8773
                goto cleanup;
            saved_nparams++;
        }
8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791

        if (*nparams > saved_nparams) {
            if (virTypedParameterAssign(&params[3],
                                        VIR_DOMAIN_SCHEDULER_EMULATOR_PERIOD,
                                        VIR_TYPED_PARAM_ULLONG,
                                        emulator_period) < 0)
                goto cleanup;
            saved_nparams++;
        }

        if (*nparams > saved_nparams) {
            if (virTypedParameterAssign(&params[4],
                                        VIR_DOMAIN_SCHEDULER_EMULATOR_QUOTA,
                                        VIR_TYPED_PARAM_LLONG,
                                        emulator_quota) < 0)
                goto cleanup;
            saved_nparams++;
        }
8792 8793 8794 8795
    }

    *nparams = saved_nparams;

8796 8797 8798 8799
    ret = 0;

cleanup:
    if (vm)
8800
        virObjectUnlock(vm);
8801
    virObjectUnref(caps);
8802 8803 8804
    return ret;
}

8805
static int
8806 8807 8808
qemuDomainGetSchedulerParameters(virDomainPtr dom,
                                 virTypedParameterPtr params,
                                 int *nparams)
8809
{
8810 8811
    return qemuDomainGetSchedulerParametersFlags(dom, params, nparams,
                                                 VIR_DOMAIN_AFFECT_CURRENT);
8812
}
8813

8814 8815 8816 8817 8818 8819 8820
/**
 * Resize a block device while a guest is running. Resize to a lower size
 * is supported, but should be used with extreme caution.  Note that it
 * only supports to resize image files, it can't resize block devices
 * like LVM volumes.
 */
static int
E
Eric Blake 已提交
8821 8822 8823 8824
qemuDomainBlockResize(virDomainPtr dom,
                      const char *path,
                      unsigned long long size,
                      unsigned int flags)
8825
{
8826
    virQEMUDriverPtr driver = dom->conn->privateData;
8827 8828 8829 8830 8831 8832
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1, i;
    char *device = NULL;
    virDomainDiskDefPtr disk = NULL;

E
Eric Blake 已提交
8833
    virCheckFlags(VIR_DOMAIN_BLOCK_RESIZE_BYTES, -1);
8834 8835

    if (path[0] == '\0') {
8836 8837
        virReportError(VIR_ERR_INVALID_ARG,
                       "%s", _("empty path"));
8838 8839 8840
        return -1;
    }

E
Eric Blake 已提交
8841 8842 8843
    /* We prefer operating on bytes.  */
    if ((flags & VIR_DOMAIN_BLOCK_RESIZE_BYTES) == 0) {
        if (size > ULLONG_MAX / 1024) {
8844 8845 8846
            virReportError(VIR_ERR_OVERFLOW,
                           _("size must be less than %llu"),
                           ULLONG_MAX / 1024);
E
Eric Blake 已提交
8847 8848 8849
            return -1;
        }
        size *= 1024;
8850 8851
    }

8852
    if (!(vm = qemuDomObjFromDomain(dom)))
8853 8854 8855 8856
        goto cleanup;

    priv = vm->privateData;

8857 8858 8859
    if (virDomainBlockResizeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

8860 8861 8862 8863
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
8864 8865
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
8866 8867 8868 8869
        goto endjob;
    }

    if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
8870 8871
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid path: %s"), path);
8872
        goto endjob;
8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897
    }
    disk = vm->def->disks[i];

    if (virAsprintf(&device, "%s%s", QEMU_DRIVE_HOST_PREFIX,
                    disk->info.alias) < 0) {
        virReportOOMError();
        goto endjob;
    }

    qemuDomainObjEnterMonitor(driver, vm);
    if (qemuMonitorBlockResize(priv->mon, device, size) < 0) {
        qemuDomainObjExitMonitor(driver, vm);
        goto endjob;
    }
    qemuDomainObjExitMonitor(driver, vm);

    ret = 0;

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

cleanup:
    VIR_FREE(device);
    if (vm)
8898
        virObjectUnlock(vm);
8899 8900 8901
    return ret;
}

8902 8903 8904 8905 8906
/* 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
8907 8908 8909
qemuDomainBlockStats(virDomainPtr dom,
                     const char *path,
                     struct _virDomainBlockStats *stats)
8910
{
8911
    virQEMUDriverPtr driver = dom->conn->privateData;
8912
    int i, ret = -1;
8913
    virDomainObjPtr vm;
8914
    virDomainDiskDefPtr disk = NULL;
8915
    qemuDomainObjPrivatePtr priv;
8916

8917
    if (!(vm = qemuDomObjFromDomain(dom)))
8918
        goto cleanup;
8919

8920 8921 8922
    if (virDomainBlockStatsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

8923
    if (!virDomainObjIsActive(vm)) {
8924 8925
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
8926 8927 8928
        goto cleanup;
    }

8929
    if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
8930 8931
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid path: %s"), path);
8932
        goto cleanup;
8933
    }
8934
    disk = vm->def->disks[i];
8935

8936
    if (!disk->info.alias) {
8937 8938
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("missing disk device alias name for %s"), disk->dst);
8939
        goto cleanup;
8940
    }
8941

8942
    priv = vm->privateData;
8943 8944
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
        goto cleanup;
8945

8946
    if (!virDomainObjIsActive(vm)) {
8947 8948
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
8949 8950
        goto endjob;
    }
8951

8952
    qemuDomainObjEnterMonitor(driver, vm);
8953 8954 8955 8956
    ret = qemuMonitorGetBlockStatsInfo(priv->mon,
                                       disk->info.alias,
                                       &stats->rd_req,
                                       &stats->rd_bytes,
8957
                                       NULL,
8958 8959
                                       &stats->wr_req,
                                       &stats->wr_bytes,
8960 8961 8962
                                       NULL,
                                       NULL,
                                       NULL,
8963 8964
                                       &stats->errs);
    qemuDomainObjExitMonitor(driver, vm);
8965

8966
endjob:
8967 8968
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
8969

8970
cleanup:
8971
    if (vm)
8972
        virObjectUnlock(vm);
8973
    return ret;
8974 8975
}

8976
static int
8977 8978 8979 8980 8981
qemuDomainBlockStatsFlags(virDomainPtr dom,
                          const char *path,
                          virTypedParameterPtr params,
                          int *nparams,
                          unsigned int flags)
8982
{
8983
    virQEMUDriverPtr driver = dom->conn->privateData;
8984 8985 8986 8987 8988 8989
    int i, tmp, ret = -1;
    virDomainObjPtr vm;
    virDomainDiskDefPtr disk = NULL;
    qemuDomainObjPrivatePtr priv;
    long long rd_req, rd_bytes, wr_req, wr_bytes, rd_total_times;
    long long wr_total_times, flush_req, flush_total_times, errs;
8990
    virTypedParameterPtr param;
8991

8992 8993 8994 8995
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;
8996

8997
    if (!(vm = qemuDomObjFromDomain(dom)))
8998 8999
        goto cleanup;

9000 9001 9002
    if (virDomainBlockStatsFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

9003 9004 9005
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
        goto cleanup;

9006
    if (!virDomainObjIsActive(vm)) {
9007 9008
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
9009
        goto endjob;
9010 9011 9012
    }

    if (*nparams != 0) {
9013
        if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
9014 9015
            virReportError(VIR_ERR_INVALID_ARG,
                           _("invalid path: %s"), path);
9016
            goto endjob;
9017
        }
9018
        disk = vm->def->disks[i];
9019 9020

        if (!disk->info.alias) {
9021 9022 9023
             virReportError(VIR_ERR_INTERNAL_ERROR,
                            _("missing disk device alias name for %s"),
                            disk->dst);
9024
             goto endjob;
9025 9026 9027 9028 9029 9030 9031 9032 9033 9034
        }
    }

    priv = vm->privateData;
    VIR_DEBUG("priv=%p, params=%p, flags=%x", priv, params, flags);

    qemuDomainObjEnterMonitor(driver, vm);
    tmp = *nparams;
    ret = qemuMonitorGetBlockStatsParamsNumber(priv->mon, nparams);

9035
    if (tmp == 0 || ret < 0) {
9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056
        qemuDomainObjExitMonitor(driver, vm);
        goto endjob;
    }

    ret = qemuMonitorGetBlockStatsInfo(priv->mon,
                                       disk->info.alias,
                                       &rd_req,
                                       &rd_bytes,
                                       &rd_total_times,
                                       &wr_req,
                                       &wr_bytes,
                                       &wr_total_times,
                                       &flush_req,
                                       &flush_total_times,
                                       &errs);

    qemuDomainObjExitMonitor(driver, vm);

    if (ret < 0)
        goto endjob;

9057 9058
    tmp = 0;
    ret = -1;
9059

9060 9061
    if (tmp < *nparams && wr_bytes != -1) {
        param = &params[tmp];
9062 9063
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_WRITE_BYTES,
                                    VIR_TYPED_PARAM_LLONG, wr_bytes) < 0)
9064 9065 9066
            goto endjob;
        tmp++;
    }
9067

9068
    if (tmp < *nparams && wr_req != -1) {
9069
        param = &params[tmp];
9070 9071
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_WRITE_REQ,
                                    VIR_TYPED_PARAM_LLONG, wr_req) < 0)
9072 9073 9074
            goto endjob;
        tmp++;
    }
9075

9076
    if (tmp < *nparams && rd_bytes != -1) {
9077
        param = &params[tmp];
9078 9079
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_READ_BYTES,
                                    VIR_TYPED_PARAM_LLONG, rd_bytes) < 0)
9080 9081 9082
            goto endjob;
        tmp++;
    }
9083

9084
    if (tmp < *nparams && rd_req != -1) {
9085
        param = &params[tmp];
9086 9087
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_READ_REQ,
                                    VIR_TYPED_PARAM_LLONG, rd_req) < 0)
9088 9089 9090
            goto endjob;
        tmp++;
    }
9091

9092
    if (tmp < *nparams && flush_req != -1) {
9093
        param = &params[tmp];
9094 9095
        if (virTypedParameterAssign(param, VIR_DOMAIN_BLOCK_STATS_FLUSH_REQ,
                                    VIR_TYPED_PARAM_LLONG, flush_req) < 0)
9096 9097 9098
            goto endjob;
        tmp++;
    }
9099

9100
    if (tmp < *nparams && wr_total_times != -1) {
9101
        param = &params[tmp];
9102 9103 9104
        if (virTypedParameterAssign(param,
                                    VIR_DOMAIN_BLOCK_STATS_WRITE_TOTAL_TIMES,
                                    VIR_TYPED_PARAM_LLONG, wr_total_times) < 0)
9105 9106 9107
            goto endjob;
        tmp++;
    }
9108

9109
    if (tmp < *nparams && rd_total_times != -1) {
9110
        param = &params[tmp];
9111 9112 9113
        if (virTypedParameterAssign(param,
                                    VIR_DOMAIN_BLOCK_STATS_READ_TOTAL_TIMES,
                                    VIR_TYPED_PARAM_LLONG, rd_total_times) < 0)
9114 9115 9116
            goto endjob;
        tmp++;
    }
9117

9118
    if (tmp < *nparams && flush_total_times != -1) {
9119
        param = &params[tmp];
9120 9121 9122 9123
        if (virTypedParameterAssign(param,
                                    VIR_DOMAIN_BLOCK_STATS_FLUSH_TOTAL_TIMES,
                                    VIR_TYPED_PARAM_LLONG,
                                    flush_total_times) < 0)
9124 9125
            goto endjob;
        tmp++;
9126 9127
    }

9128 9129 9130 9131 9132
    /* Field 'errs' is meaningless for QEMU, won't set it. */

    ret = 0;
    *nparams = tmp;

9133 9134 9135 9136 9137 9138
endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;

cleanup:
    if (vm)
9139
        virObjectUnlock(vm);
9140 9141 9142
    return ret;
}

9143
#ifdef __linux__
9144
static int
9145 9146 9147
qemuDomainInterfaceStats(virDomainPtr dom,
                         const char *path,
                         struct _virDomainInterfaceStats *stats)
9148
{
9149
    virDomainObjPtr vm;
9150
    int i;
9151
    int ret = -1;
9152

9153
    if (!(vm = qemuDomObjFromDomain(dom)))
9154
        goto cleanup;
9155

9156 9157 9158
    if (virDomainInterfaceStatsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
9159
    if (!virDomainObjIsActive(vm)) {
9160 9161
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
9162
        goto cleanup;
9163 9164 9165
    }

    /* Check the path is one of the domain's network interfaces. */
9166
    for (i = 0; i < vm->def->nnets; i++) {
9167
        if (vm->def->nets[i]->ifname &&
9168
            STREQ(vm->def->nets[i]->ifname, path)) {
9169 9170 9171
            ret = 0;
            break;
        }
9172 9173
    }

9174
    if (ret == 0)
9175
        ret = linuxDomainInterfaceStats(path, stats);
9176
    else
9177 9178
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid path, '%s' is not a known interface"), path);
9179

9180
cleanup:
9181
    if (vm)
9182
        virObjectUnlock(vm);
9183 9184
    return ret;
}
9185
#else
9186
static int
E
Eric Blake 已提交
9187
qemuDomainInterfaceStats(virDomainPtr dom ATTRIBUTE_UNUSED,
9188 9189
                         const char *path ATTRIBUTE_UNUSED,
                         struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
9190
{
9191 9192
    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                   _("interface stats not implemented on this platform"));
9193 9194
    return -1;
}
9195
#endif
9196

9197 9198 9199 9200 9201 9202 9203
static int
qemuDomainSetInterfaceParameters(virDomainPtr dom,
                                 const char *device,
                                 virTypedParameterPtr params,
                                 int nparams,
                                 unsigned int flags)
{
9204
    virQEMUDriverPtr driver = dom->conn->privateData;
9205 9206 9207 9208 9209
    int i;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr persistentDef = NULL;
    int ret = -1;
    virDomainNetDefPtr net = NULL, persistentNet = NULL;
9210
    virNetDevBandwidthPtr bandwidth = NULL, newBandwidth = NULL;
9211
    virQEMUDriverConfigPtr cfg = NULL;
9212
    virCapsPtr caps = NULL;
9213 9214 9215

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_BANDWIDTH_IN_AVERAGE,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_BANDWIDTH_IN_PEAK,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_BANDWIDTH_IN_BURST,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_BANDWIDTH_OUT_AVERAGE,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_BANDWIDTH_OUT_PEAK,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_BANDWIDTH_OUT_BURST,
                               VIR_TYPED_PARAM_UINT,
                               NULL) < 0)
9230
        return -1;
9231

9232 9233
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
9234

9235 9236
    cfg = virQEMUDriverGetConfig(driver);

9237 9238 9239
    if (virDomainSetInterfaceParametersEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

9240 9241 9242
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

9243
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
9244 9245 9246 9247 9248 9249
                                        &persistentDef) < 0)
        goto cleanup;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        net = virDomainNetFind(vm->def, device);
        if (!net) {
9250 9251
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Can't find device %s"), device);
9252 9253 9254 9255 9256 9257
            goto cleanup;
        }
    }
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        persistentNet = virDomainNetFind(persistentDef, device);
        if (!persistentNet) {
9258 9259
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Can't find device %s"), device);
9260 9261 9262 9263
            goto cleanup;
        }
    }

9264 9265 9266
    if ((VIR_ALLOC(bandwidth) < 0) ||
        (VIR_ALLOC(bandwidth->in) < 0) ||
        (VIR_ALLOC(bandwidth->out) < 0)) {
9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288
        virReportOOMError();
        goto cleanup;
    }

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

        if (STREQ(param->field, VIR_DOMAIN_BANDWIDTH_IN_AVERAGE)) {
            bandwidth->in->average = params[i].value.ui;
        } else if (STREQ(param->field, VIR_DOMAIN_BANDWIDTH_IN_PEAK)) {
            bandwidth->in->peak = params[i].value.ui;
        } else if (STREQ(param->field, VIR_DOMAIN_BANDWIDTH_IN_BURST)) {
            bandwidth->in->burst = params[i].value.ui;
        } else if (STREQ(param->field, VIR_DOMAIN_BANDWIDTH_OUT_AVERAGE)) {
            bandwidth->out->average = params[i].value.ui;
        } else if (STREQ(param->field, VIR_DOMAIN_BANDWIDTH_OUT_PEAK)) {
            bandwidth->out->peak = params[i].value.ui;
        } else if (STREQ(param->field, VIR_DOMAIN_BANDWIDTH_OUT_BURST)) {
            bandwidth->out->burst = params[i].value.ui;
        }
    }

9289
    /* average is mandatory, peak and burst are optional. So if no
9290
     * average is given, we free inbound/outbound here which causes
9291
     * inbound/outbound to not be set. */
9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306
    if (!bandwidth->in->average) {
        VIR_FREE(bandwidth->in);
    }
    if (!bandwidth->out->average) {
        VIR_FREE(bandwidth->out);
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        if (VIR_ALLOC(newBandwidth) < 0) {
            virReportOOMError();
            goto cleanup;
        }

        /* virNetDevBandwidthSet() will clear any previous value of
         * bandwidth parameters, so merge with old bandwidth parameters
9307
         * here to prevent them from being lost. */
9308 9309
        if (bandwidth->in ||
            (net->bandwidth && net->bandwidth->in)) {
9310 9311 9312 9313
            if (VIR_ALLOC(newBandwidth->in) < 0) {
                virReportOOMError();
                goto cleanup;
            }
9314 9315 9316 9317 9318 9319 9320

            memcpy(newBandwidth->in,
                   bandwidth->in ? bandwidth->in : net->bandwidth->in,
                   sizeof(*newBandwidth->in));
        }
        if (bandwidth->out ||
            (net->bandwidth && net->bandwidth->out)) {
9321 9322 9323 9324
            if (VIR_ALLOC(newBandwidth->out) < 0) {
                virReportOOMError();
                goto cleanup;
            }
9325 9326 9327 9328

            memcpy(newBandwidth->out,
                   bandwidth->out ? bandwidth->out : net->bandwidth->out,
                   sizeof(*newBandwidth->out));
9329 9330
        }

9331
        if (virNetDevBandwidthSet(net->ifname, newBandwidth, false) < 0) {
9332 9333 9334
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot set bandwidth limits on %s"),
                           device);
9335 9336 9337 9338 9339
            goto cleanup;
        }

        virNetDevBandwidthFree(net->bandwidth);
        net->bandwidth = newBandwidth;
E
Eric Blake 已提交
9340
        newBandwidth = NULL;
9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358
    }
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        if (!persistentNet->bandwidth) {
            persistentNet->bandwidth = bandwidth;
            bandwidth = NULL;
        } else {
            if (bandwidth->in) {
                VIR_FREE(persistentNet->bandwidth->in);
                persistentNet->bandwidth->in = bandwidth->in;
                bandwidth->in = NULL;
            }
            if (bandwidth->out) {
                VIR_FREE(persistentNet->bandwidth->out);
                persistentNet->bandwidth->out = bandwidth->out;
                bandwidth->out = NULL;
            }
        }

9359
        if (virDomainSaveConfig(cfg->configDir, persistentDef) < 0)
9360 9361 9362 9363 9364 9365
            goto cleanup;
    }

    ret = 0;
cleanup:
    virNetDevBandwidthFree(bandwidth);
9366
    virNetDevBandwidthFree(newBandwidth);
9367
    if (vm)
9368
        virObjectUnlock(vm);
9369
    virObjectUnref(caps);
9370
    virObjectUnref(cfg);
9371 9372 9373 9374 9375 9376 9377 9378 9379 9380
    return ret;
}

static int
qemuDomainGetInterfaceParameters(virDomainPtr dom,
                                 const char *device,
                                 virTypedParameterPtr params,
                                 int *nparams,
                                 unsigned int flags)
{
9381
    virQEMUDriverPtr driver = dom->conn->privateData;
9382 9383 9384 9385 9386 9387
    int i;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    virDomainDefPtr persistentDef = NULL;
    virDomainNetDefPtr net = NULL;
    int ret = -1;
9388
    virCapsPtr caps = NULL;
9389 9390 9391 9392 9393 9394 9395

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);

    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

9396 9397
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
9398

9399 9400 9401
    if (virDomainGetInterfaceParametersEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

9402 9403 9404
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

9405
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420
                                        &persistentDef) < 0)
        goto cleanup;

    if ((*nparams) == 0) {
        *nparams = QEMU_NB_BANDWIDTH_PARAM;
        ret = 0;
        goto cleanup;
    }

    def = persistentDef;
    if (!def)
        def = vm->def;

    net = virDomainNetFind(def, device);
    if (!net) {
9421 9422
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Can't find device %s"), device);
9423 9424 9425 9426
        goto cleanup;
    }

    for (i = 0; i < *nparams && i < QEMU_NB_BANDWIDTH_PARAM; i++) {
9427
        switch (i) {
9428
        case 0: /* inbound.average */
9429 9430 9431
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_IN_AVERAGE,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
9432 9433 9434 9435 9436
                goto cleanup;
            if (net->bandwidth && net->bandwidth->in)
                params[i].value.ui = net->bandwidth->in->average;
            break;
        case 1: /* inbound.peak */
9437 9438 9439
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_IN_PEAK,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
9440 9441 9442 9443 9444
                goto cleanup;
            if (net->bandwidth && net->bandwidth->in)
                params[i].value.ui = net->bandwidth->in->peak;
            break;
        case 2: /* inbound.burst */
9445 9446 9447
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_IN_BURST,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
9448 9449 9450 9451 9452
                goto cleanup;
            if (net->bandwidth && net->bandwidth->in)
                params[i].value.ui = net->bandwidth->in->burst;
            break;
        case 3: /* outbound.average */
9453 9454 9455
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_OUT_AVERAGE,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
9456 9457 9458 9459 9460
                goto cleanup;
            if (net->bandwidth && net->bandwidth->out)
                params[i].value.ui = net->bandwidth->out->average;
            break;
        case 4: /* outbound.peak */
9461 9462 9463
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_OUT_PEAK,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
9464 9465 9466 9467 9468
                goto cleanup;
            if (net->bandwidth && net->bandwidth->out)
                params[i].value.ui = net->bandwidth->out->peak;
            break;
        case 5: /* outbound.burst */
9469 9470 9471
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_BANDWIDTH_OUT_BURST,
                                        VIR_TYPED_PARAM_UINT, 0) < 0)
9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487
                goto cleanup;
            if (net->bandwidth && net->bandwidth->out)
                params[i].value.ui = net->bandwidth->out->burst;
            break;
        default:
            break;
            /* should not hit here */
        }
    }

    if (*nparams > QEMU_NB_BANDWIDTH_PARAM)
        *nparams = QEMU_NB_BANDWIDTH_PARAM;
    ret = 0;

cleanup:
    if (vm)
9488
        virObjectUnlock(vm);
9489
    virObjectUnref(caps);
9490 9491 9492
    return ret;
}

9493
static int
9494 9495 9496 9497
qemuDomainMemoryStats(virDomainPtr dom,
                      struct _virDomainMemoryStat *stats,
                      unsigned int nr_stats,
                      unsigned int flags)
9498
{
9499
    virQEMUDriverPtr driver = dom->conn->privateData;
9500
    virDomainObjPtr vm;
M
Martin Kletzander 已提交
9501
    int ret = -1;
9502

9503 9504
    virCheckFlags(0, -1);

9505
    if (!(vm = qemuDomObjFromDomain(dom)))
9506 9507
        goto cleanup;

9508 9509 9510
    if (virDomainMemoryStatsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

9511
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
9512 9513
        goto cleanup;

M
Martin Kletzander 已提交
9514
    if (!virDomainObjIsActive(vm)) {
9515 9516
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
M
Martin Kletzander 已提交
9517
    } else {
9518
        qemuDomainObjPrivatePtr priv = vm->privateData;
9519
        qemuDomainObjEnterMonitor(driver, vm);
9520
        ret = qemuMonitorGetMemoryStats(priv->mon, stats, nr_stats);
9521
        qemuDomainObjExitMonitor(driver, vm);
M
Martin Kletzander 已提交
9522 9523 9524

        if (ret >= 0 && ret < nr_stats) {
            long rss;
9525
            if (qemuGetProcessInfo(NULL, NULL, &rss, vm->pid, 0) < 0) {
9526 9527
                virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                               _("cannot get RSS for domain"));
M
Martin Kletzander 已提交
9528 9529 9530 9531 9532 9533 9534
            } else {
                stats[ret].tag = VIR_DOMAIN_MEMORY_STAT_RSS;
                stats[ret].val = rss;
                ret++;
            }

        }
9535 9536
    }

9537
    if (qemuDomainObjEndJob(driver, vm) == 0)
9538 9539
        vm = NULL;

9540 9541
cleanup:
    if (vm)
9542
        virObjectUnlock(vm);
9543 9544 9545
    return ret;
}

9546
static int
9547 9548 9549 9550 9551
qemuDomainBlockPeek(virDomainPtr dom,
                    const char *path,
                    unsigned long long offset, size_t size,
                    void *buffer,
                    unsigned int flags)
9552
{
9553
    virDomainObjPtr vm;
9554 9555
    int fd = -1, ret = -1;
    const char *actual;
9556

E
Eric Blake 已提交
9557 9558
    virCheckFlags(0, -1);

9559
    if (!(vm = qemuDomObjFromDomain(dom)))
9560
        goto cleanup;
9561

9562 9563 9564
    if (virDomainBlockPeekEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

9565
    if (!path || path[0] == '\0') {
9566 9567
        virReportError(VIR_ERR_INVALID_ARG,
                       "%s", _("NULL or empty path"));
9568
        goto cleanup;
9569 9570
    }

9571 9572
    /* Check the path belongs to this domain.  */
    if (!(actual = virDomainDiskPathByName(vm->def, path))) {
9573 9574
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid path '%s'"), path);
9575
        goto cleanup;
9576
    }
9577
    path = actual;
9578

9579 9580 9581 9582 9583 9584 9585
    /* The path is correct, now try to open it and get its size. */
    fd = open(path, O_RDONLY);
    if (fd == -1) {
        virReportSystemError(errno,
                             _("%s: failed to open"), path);
        goto cleanup;
    }
9586

9587 9588 9589 9590 9591 9592 9593 9594 9595
    /* 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) {
        virReportSystemError(errno,
                             _("%s: failed to seek or read"), path);
        goto cleanup;
9596 9597
    }

9598 9599
    ret = 0;

9600
cleanup:
9601
    VIR_FORCE_CLOSE(fd);
9602
    if (vm)
9603
        virObjectUnlock(vm);
9604 9605 9606
    return ret;
}

R
Richard W.M. Jones 已提交
9607
static int
9608 9609 9610 9611
qemuDomainMemoryPeek(virDomainPtr dom,
                     unsigned long long offset, size_t size,
                     void *buffer,
                     unsigned int flags)
R
Richard W.M. Jones 已提交
9612
{
9613
    virQEMUDriverPtr driver = dom->conn->privateData;
9614
    virDomainObjPtr vm;
9615
    char *tmp = NULL;
R
Richard W.M. Jones 已提交
9616
    int fd = -1, ret = -1;
9617
    qemuDomainObjPrivatePtr priv;
9618
    virQEMUDriverConfigPtr cfg = NULL;
R
Richard W.M. Jones 已提交
9619

9620 9621
    virCheckFlags(VIR_MEMORY_VIRTUAL | VIR_MEMORY_PHYSICAL, -1);

9622
    if (!(vm = qemuDomObjFromDomain(dom)))
9623 9624
        goto cleanup;

9625 9626
    cfg = virQEMUDriverGetConfig(driver);

9627 9628 9629
    if (virDomainMemoryPeekEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

9630
    if (flags != VIR_MEMORY_VIRTUAL && flags != VIR_MEMORY_PHYSICAL) {
9631 9632
        virReportError(VIR_ERR_INVALID_ARG,
                       "%s", _("flags parameter must be VIR_MEMORY_VIRTUAL or VIR_MEMORY_PHYSICAL"));
9633
        goto cleanup;
R
Richard W.M. Jones 已提交
9634 9635
    }

9636
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
9637 9638
        goto cleanup;

D
Daniel P. Berrange 已提交
9639
    if (!virDomainObjIsActive(vm)) {
9640 9641
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
9642
        goto endjob;
R
Richard W.M. Jones 已提交
9643 9644
    }

9645
    if (virAsprintf(&tmp, "%s/qemu.mem.XXXXXX", cfg->cacheDir) < 0) {
9646
        virReportOOMError();
9647
        goto endjob;
9648 9649
    }

R
Richard W.M. Jones 已提交
9650
    /* Create a temporary filename. */
9651
    if ((fd = mkostemp(tmp, O_CLOEXEC)) == -1) {
9652
        virReportSystemError(errno,
9653
                             _("mkostemp(\"%s\") failed"), tmp);
9654
        goto endjob;
R
Richard W.M. Jones 已提交
9655 9656
    }

9657
    virSecurityManagerSetSavedStateLabel(qemu_driver->securityManager, vm->def, tmp);
9658

9659
    priv = vm->privateData;
9660
    qemuDomainObjEnterMonitor(driver, vm);
9661
    if (flags == VIR_MEMORY_VIRTUAL) {
9662
        if (qemuMonitorSaveVirtualMemory(priv->mon, offset, size, tmp) < 0) {
9663
            qemuDomainObjExitMonitor(driver, vm);
9664
            goto endjob;
9665
        }
9666
    } else {
9667
        if (qemuMonitorSavePhysicalMemory(priv->mon, offset, size, tmp) < 0) {
9668
            qemuDomainObjExitMonitor(driver, vm);
9669
            goto endjob;
9670
        }
R
Richard W.M. Jones 已提交
9671
    }
9672
    qemuDomainObjExitMonitor(driver, vm);
R
Richard W.M. Jones 已提交
9673 9674

    /* Read the memory file into buffer. */
9675
    if (saferead(fd, buffer, size) == (ssize_t) -1) {
9676 9677 9678
        virReportSystemError(errno,
                             _("failed to read temporary file "
                               "created with template %s"), tmp);
9679
        goto endjob;
R
Richard W.M. Jones 已提交
9680 9681 9682
    }

    ret = 0;
9683

9684
endjob:
9685
    if (qemuDomainObjEndJob(driver, vm) == 0)
9686
        vm = NULL;
9687

9688
cleanup:
9689
    VIR_FORCE_CLOSE(fd);
9690 9691
    if (tmp)
        unlink(tmp);
W
Wen Congyang 已提交
9692
    VIR_FREE(tmp);
9693
    if (vm)
9694
        virObjectUnlock(vm);
9695
    virObjectUnref(cfg);
R
Richard W.M. Jones 已提交
9696 9697 9698
    return ret;
}

9699

9700 9701 9702 9703
static int qemuDomainGetBlockInfo(virDomainPtr dom,
                                  const char *path,
                                  virDomainBlockInfoPtr info,
                                  unsigned int flags) {
9704
    virQEMUDriverPtr driver = dom->conn->privateData;
9705 9706 9707 9708
    virDomainObjPtr vm;
    int ret = -1;
    int fd = -1;
    off_t end;
9709
    virStorageFileMetadata *meta = NULL;
9710
    virDomainDiskDefPtr disk = NULL;
9711
    struct stat sb;
9712
    int i;
9713
    int format;
9714
    virQEMUDriverConfigPtr cfg = NULL;
9715 9716 9717

    virCheckFlags(0, -1);

9718
    if (!(vm = qemuDomObjFromDomain(dom)))
9719 9720
        goto cleanup;

9721 9722
    cfg = virQEMUDriverGetConfig(driver);

9723 9724 9725
    if (virDomainGetBlockInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

9726
    if (!path || path[0] == '\0') {
9727 9728
        virReportError(VIR_ERR_INVALID_ARG,
                       "%s", _("NULL or empty path"));
9729 9730 9731 9732
        goto cleanup;
    }

    /* Check the path belongs to this domain. */
9733
    if ((i = virDomainDiskIndexByName(vm->def, path, false)) < 0) {
9734 9735
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid path %s not assigned to domain"), path);
9736 9737
        goto cleanup;
    }
9738 9739
    disk = vm->def->disks[i];
    if (!disk->src) {
9740 9741 9742
        virReportError(VIR_ERR_INVALID_ARG,
                       _("disk %s does not currently have a source assigned"),
                       path);
9743 9744 9745
        goto cleanup;
    }
    path = disk->src;
9746 9747

    /* The path is correct, now try to open it and get its size. */
9748
    fd = open(path, O_RDONLY);
9749 9750 9751 9752 9753 9754 9755
    if (fd == -1) {
        virReportSystemError(errno,
                             _("failed to open path '%s'"), path);
        goto cleanup;
    }

    /* Probe for magic formats */
9756 9757
    if (disk->format) {
        format = disk->format;
9758
    } else {
9759 9760 9761 9762
        if (cfg->allowDiskFormatProbing) {
            if ((format = virStorageFileProbeFormat(disk->src,
                                                    cfg->user,
                                                    cfg->group)) < 0)
9763 9764
                goto cleanup;
        } else {
9765 9766 9767
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("no disk format for %s and probing is disabled"),
                           disk->src);
9768
            goto cleanup;
9769
        }
9770 9771
    }

9772
    if (!(meta = virStorageFileGetMetadataFromFD(path, fd, format)))
9773 9774 9775 9776 9777 9778 9779 9780 9781 9782
        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)) {
9783
#ifndef WIN32
9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796
        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.
         */
9797
        end = lseek(fd, 0, SEEK_END);
9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808
        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 */
9809 9810
    if (meta->capacity)
        info->capacity = meta->capacity;
9811

9812
    /* Set default value .. */
9813 9814
    info->allocation = info->physical;

9815 9816 9817
    /* ..but if guest is running & not using raw
       disk format and on a block device, then query
       highest allocated extent from QEMU */
9818
    if (disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
9819
        format != VIR_STORAGE_FILE_RAW &&
9820 9821
        S_ISBLK(sb.st_mode) &&
        virDomainObjIsActive(vm)) {
9822
        qemuDomainObjPrivatePtr priv = vm->privateData;
9823

9824 9825
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
            goto cleanup;
9826

9827
        if (virDomainObjIsActive(vm)) {
9828
            qemuDomainObjEnterMonitor(driver, vm);
9829 9830 9831 9832
            ret = qemuMonitorGetBlockExtent(priv->mon,
                                            disk->info.alias,
                                            &info->allocation);
            qemuDomainObjExitMonitor(driver, vm);
9833
        } else {
9834
            ret = 0;
9835
        }
9836 9837 9838

        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
9839 9840 9841
    } else {
        ret = 0;
    }
9842 9843

cleanup:
9844
    virStorageFileFreeMetadata(meta);
9845
    VIR_FORCE_CLOSE(fd);
9846
    if (vm)
9847
        virObjectUnlock(vm);
9848
    virObjectUnref(cfg);
9849 9850 9851 9852
    return ret;
}


9853
static int
9854 9855 9856 9857
qemuConnectDomainEventRegister(virConnectPtr conn,
                               virConnectDomainEventCallback callback,
                               void *opaque,
                               virFreeCallback freecb)
9858
{
9859
    virQEMUDriverPtr driver = conn->privateData;
9860
    int ret = -1;
9861

9862 9863 9864 9865 9866 9867 9868
    if (virConnectDomainEventRegisterEnsureACL(conn) < 0)
        goto cleanup;

    if (virDomainEventStateRegister(conn,
                                    driver->domainEventState,
                                    callback, opaque, freecb) < 0)
        goto cleanup;
9869

9870 9871 9872
    ret = 0;

cleanup:
9873
    return ret;
9874 9875
}

9876

9877
static int
9878 9879
qemuConnectDomainEventDeregister(virConnectPtr conn,
                                 virConnectDomainEventCallback callback)
9880
{
9881
    virQEMUDriverPtr driver = conn->privateData;
9882
    int ret = -1;
9883

9884 9885 9886 9887 9888 9889 9890 9891 9892
    if (virConnectDomainEventDeregisterEnsureACL(conn) < 0)
        goto cleanup;

    if (virDomainEventStateDeregister(conn,
                                      driver->domainEventState,
                                      callback) < 0)
        goto cleanup;

    ret = 0;
9893

9894
cleanup:
9895
    return ret;
9896 9897
}

9898 9899

static int
9900 9901 9902 9903 9904 9905
qemuConnectDomainEventRegisterAny(virConnectPtr conn,
                                  virDomainPtr dom,
                                  int eventID,
                                  virConnectDomainEventGenericCallback callback,
                                  void *opaque,
                                  virFreeCallback freecb)
9906
{
9907
    virQEMUDriverPtr driver = conn->privateData;
9908 9909 9910 9911
    int ret = -1;

    if (virConnectDomainEventRegisterAnyEnsureACL(conn) < 0)
        goto cleanup;
9912

9913 9914 9915 9916
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID,
                                      callback, opaque, freecb, &ret) < 0)
9917
        goto cleanup;
9918

9919 9920 9921
    ret = 0;

cleanup:
9922 9923 9924 9925 9926
    return ret;
}


static int
9927 9928
qemuConnectDomainEventDeregisterAny(virConnectPtr conn,
                                    int callbackID)
9929
{
9930
    virQEMUDriverPtr driver = conn->privateData;
9931
    int ret = -1;
9932

9933 9934
    if (virConnectDomainEventDeregisterAnyEnsureACL(conn) < 0)
        goto cleanup;
9935

9936 9937 9938 9939 9940 9941 9942 9943
    if (virDomainEventStateDeregisterID(conn,
                                        driver->domainEventState,
                                        callbackID) < 0)
        goto cleanup;

    ret = 0;

cleanup:
9944 9945 9946 9947
    return ret;
}


9948 9949 9950
/*******************************************************************
 * Migration Protocol Version 2
 *******************************************************************/
D
Daniel Veillard 已提交
9951

C
Chris Lalancette 已提交
9952 9953 9954 9955 9956 9957
/* 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
9958 9959 9960 9961 9962 9963
qemuDomainMigratePrepareTunnel(virConnectPtr dconn,
                               virStreamPtr st,
                               unsigned long flags,
                               const char *dname,
                               unsigned long resource ATTRIBUTE_UNUSED,
                               const char *dom_xml)
C
Chris Lalancette 已提交
9964
{
9965
    virQEMUDriverPtr driver = dconn->privateData;
9966
    virDomainDefPtr def = NULL;
C
Chris Lalancette 已提交
9967
    int ret = -1;
9968

9969
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
9970

C
Chris Lalancette 已提交
9971
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
9972 9973
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("PrepareTunnel called but no TUNNELLED flag set"));
C
Chris Lalancette 已提交
9974 9975 9976
        goto cleanup;
    }

9977
    if (virLockManagerPluginUsesState(driver->lockManager)) {
9978 9979 9980
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot use migrate v2 protocol with lock manager %s"),
                       virLockManagerPluginGetName(driver->lockManager));
9981 9982 9983
        goto cleanup;
    }

9984
    if (!(def = qemuMigrationPrepareDef(driver, dom_xml, dname)))
9985 9986
        goto cleanup;

9987 9988 9989
    if (virDomainMigratePrepareTunnelEnsureACL(dconn, def) < 0)
        goto cleanup;

9990 9991
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     NULL, 0, NULL, NULL, /* No cookies in v2 */
9992
                                     st, &def, flags);
9993

C
Chris Lalancette 已提交
9994
cleanup:
9995
    virDomainDefFree(def);
C
Chris Lalancette 已提交
9996 9997 9998
    return ret;
}

D
Daniel Veillard 已提交
9999 10000 10001 10002
/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
10003
static int ATTRIBUTE_NONNULL(5)
10004 10005 10006 10007 10008 10009 10010 10011 10012
qemuDomainMigratePrepare2(virConnectPtr dconn,
                          char **cookie ATTRIBUTE_UNUSED,
                          int *cookielen ATTRIBUTE_UNUSED,
                          const char *uri_in,
                          char **uri_out,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource ATTRIBUTE_UNUSED,
                          const char *dom_xml)
D
Daniel Veillard 已提交
10013
{
10014
    virQEMUDriverPtr driver = dconn->privateData;
10015
    virDomainDefPtr def = NULL;
10016
    int ret = -1;
10017

10018
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
10019

C
Chris Lalancette 已提交
10020 10021 10022 10023
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
10024 10025 10026
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Tunnelled migration requested but invalid "
                         "RPC method called"));
C
Chris Lalancette 已提交
10027 10028 10029
        goto cleanup;
    }

10030
    if (virLockManagerPluginUsesState(driver->lockManager)) {
10031
        virReportError(VIR_ERR_INTERNAL_ERROR,
10032 10033
                       _("Cannot use migrate v2 protocol with lock manager %s"),
                       virLockManagerPluginGetName(driver->lockManager));
10034
        goto cleanup;
D
Daniel Veillard 已提交
10035 10036
    }

10037
    if (!(def = qemuMigrationPrepareDef(driver, dom_xml, dname)))
10038 10039
        goto cleanup;

10040 10041 10042
    if (virDomainMigratePrepare2EnsureACL(dconn, def) < 0)
        goto cleanup;

10043 10044 10045 10046
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
10047
    ret = qemuMigrationPrepareDirect(driver, dconn,
10048
                                     NULL, 0, NULL, NULL, /* No cookies */
10049
                                     uri_in, uri_out,
10050
                                     &def, flags);
D
Daniel Veillard 已提交
10051

10052
cleanup:
10053
    virDomainDefFree(def);
10054 10055
    return ret;
}
C
Chris Lalancette 已提交
10056

D
Daniel Veillard 已提交
10057

10058 10059
/* Perform is the second step, and it runs on the source host. */
static int
10060 10061 10062 10063 10064 10065 10066
qemuDomainMigratePerform(virDomainPtr dom,
                         const char *cookie,
                         int cookielen,
                         const char *uri,
                         unsigned long flags,
                         const char *dname,
                         unsigned long resource)
10067
{
10068
    virQEMUDriverPtr driver = dom->conn->privateData;
10069 10070
    virDomainObjPtr vm;
    int ret = -1;
10071
    const char *dconnuri = NULL;
10072

10073
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
C
Chris Lalancette 已提交
10074

10075
    if (virLockManagerPluginUsesState(driver->lockManager)) {
10076 10077 10078
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot use migrate v2 protocol with lock manager %s"),
                       virLockManagerPluginGetName(driver->lockManager));
10079 10080 10081
        goto cleanup;
    }

10082
    if (!(vm = qemuDomObjFromDomain(dom)))
10083
        goto cleanup;
D
Daniel Veillard 已提交
10084

10085 10086 10087
    if (virDomainMigratePerformEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

10088 10089 10090 10091 10092
    if (flags & VIR_MIGRATE_PEER2PEER) {
        dconnuri = uri;
        uri = NULL;
    }

10093 10094 10095 10096 10097 10098
    /* 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
     */
10099
    ret = qemuMigrationPerform(driver, dom->conn, vm,
10100
                               NULL, dconnuri, uri, NULL, cookie, cookielen,
10101
                               NULL, NULL, /* No output cookies in v2 */
10102
                               flags, dname, resource, false);
10103

10104
cleanup:
10105
    return ret;
D
Daniel Veillard 已提交
10106 10107
}

10108

D
Daniel Veillard 已提交
10109 10110
/* Finish is the third and final step, and it runs on the destination host. */
static virDomainPtr
10111 10112 10113 10114 10115 10116 10117
qemuDomainMigrateFinish2(virConnectPtr dconn,
                         const char *dname,
                         const char *cookie ATTRIBUTE_UNUSED,
                         int cookielen ATTRIBUTE_UNUSED,
                         const char *uri ATTRIBUTE_UNUSED,
                         unsigned long flags,
                         int retcode)
D
Daniel Veillard 已提交
10118
{
10119
    virQEMUDriverPtr driver = dconn->privateData;
10120 10121
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
D
Daniel Veillard 已提交
10122

10123
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
C
Chris Lalancette 已提交
10124

10125
    vm = virDomainObjListFindByName(driver->domains, dname);
D
Daniel Veillard 已提交
10126
    if (!vm) {
10127 10128
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching name '%s'"), dname);
10129
        goto cleanup;
D
Daniel Veillard 已提交
10130 10131
    }

10132 10133 10134
    if (virDomainMigrateFinish2EnsureACL(dconn, vm->def) < 0)
        goto cleanup;

10135 10136 10137 10138
    /* Do not use cookies in v2 protocol, since the cookie
     * length was not sufficiently large, causing failures
     * migrating between old & new libvirtd
     */
10139
    dom = qemuMigrationFinish(driver, dconn, vm,
10140
                              NULL, 0, NULL, NULL, /* No cookies */
10141
                              flags, retcode, false);
10142

10143 10144
cleanup:
    return dom;
D
Daniel Veillard 已提交
10145 10146
}

10147

10148 10149 10150 10151 10152 10153
/*******************************************************************
 * Migration Protocol Version 3
 *******************************************************************/

static char *
qemuDomainMigrateBegin3(virDomainPtr domain,
10154
                        const char *xmlin,
10155 10156 10157
                        char **cookieout,
                        int *cookieoutlen,
                        unsigned long flags,
10158
                        const char *dname,
10159 10160 10161 10162
                        unsigned long resource ATTRIBUTE_UNUSED)
{
    virDomainObjPtr vm;

10163
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
10164

10165 10166
    if (!(vm = qemuDomObjFromDomain(domain)))
        return NULL;
10167

10168
    if (virDomainMigrateBegin3EnsureACL(domain->conn, vm->def) < 0) {
10169
        virObjectUnlock(vm);
10170
        return NULL;
10171
    }
10172 10173 10174

    return qemuMigrationBegin(domain->conn, vm, xmlin, dname,
                              cookieout, cookieoutlen, flags);
10175 10176
}

10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213
static char *
qemuDomainMigrateBegin3Params(virDomainPtr domain,
                              virTypedParameterPtr params,
                              int nparams,
                              char **cookieout,
                              int *cookieoutlen,
                              unsigned int flags)
{
    const char *xmlin = NULL;
    const char *dname = NULL;
    virDomainObjPtr vm;

    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
    if (virTypedParamsValidate(params, nparams, QEMU_MIGRATION_PARAMETERS) < 0)
        return NULL;

    if (virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_XML,
                                &xmlin) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_NAME,
                                &dname) < 0)
        return NULL;

    if (!(vm = qemuDomObjFromDomain(domain)))
        return NULL;

    if (virDomainMigrateBegin3ParamsEnsureACL(domain->conn, vm->def) < 0) {
        virObjectUnlock(vm);
        return NULL;
    }

    return qemuMigrationBegin(domain->conn, vm, xmlin, dname,
                              cookieout, cookieoutlen, flags);
}


10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226
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)
{
10227
    virQEMUDriverPtr driver = dconn->privateData;
10228
    virDomainDefPtr def = NULL;
10229 10230
    int ret = -1;

10231
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
10232 10233 10234 10235 10236

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

10243
    if (!(def = qemuMigrationPrepareDef(driver, dom_xml, dname)))
10244 10245
        goto cleanup;

10246 10247 10248
    if (virDomainMigratePrepare3EnsureACL(dconn, def) < 0)
        goto cleanup;

10249 10250 10251 10252
    ret = qemuMigrationPrepareDirect(driver, dconn,
                                     cookiein, cookieinlen,
                                     cookieout, cookieoutlen,
                                     uri_in, uri_out,
10253
                                     &def, flags);
10254 10255

cleanup:
10256
    virDomainDefFree(def);
10257 10258 10259
    return ret;
}

10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319
static int
qemuDomainMigratePrepare3Params(virConnectPtr dconn,
                                virTypedParameterPtr params,
                                int nparams,
                                const char *cookiein,
                                int cookieinlen,
                                char **cookieout,
                                int *cookieoutlen,
                                char **uri_out,
                                unsigned int flags)
{
    virQEMUDriverPtr driver = dconn->privateData;
    virDomainDefPtr def = NULL;
    const char *dom_xml = NULL;
    const char *dname = NULL;
    const char *uri_in = NULL;
    int ret = -1;

    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
    if (virTypedParamsValidate(params, nparams, QEMU_MIGRATION_PARAMETERS) < 0)
        return -1;

    if (virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_XML,
                                &dom_xml) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_NAME,
                                &dname) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_URI,
                                &uri_in) < 0)
        return -1;

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

    if (!(def = qemuMigrationPrepareDef(driver, dom_xml, dname)))
        goto cleanup;

    if (virDomainMigratePrepare3ParamsEnsureACL(dconn, def) < 0)
        goto cleanup;

    ret = qemuMigrationPrepareDirect(driver, dconn,
                                     cookiein, cookieinlen,
                                     cookieout, cookieoutlen,
                                     uri_in, uri_out,
                                     &def, flags);

cleanup:
    virDomainDefFree(def);
    return ret;
}

10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332

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)
{
10333
    virQEMUDriverPtr driver = dconn->privateData;
10334
    virDomainDefPtr def = NULL;
10335 10336
    int ret = -1;

10337
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
10338 10339

    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
10340 10341
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("PrepareTunnel called but no TUNNELLED flag set"));
10342 10343 10344
        goto cleanup;
    }

10345
    if (!(def = qemuMigrationPrepareDef(driver, dom_xml, dname)))
10346 10347
        goto cleanup;

10348 10349 10350
    if (virDomainMigratePrepareTunnel3EnsureACL(dconn, def) < 0)
        goto cleanup;

10351 10352 10353
    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     cookiein, cookieinlen,
                                     cookieout, cookieoutlen,
10354
                                     st, &def, flags);
10355 10356

cleanup:
10357
    virDomainDefFree(def);
10358 10359 10360
    return ret;
}

10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411
static int
qemuDomainMigratePrepareTunnel3Params(virConnectPtr dconn,
                                      virStreamPtr st,
                                      virTypedParameterPtr params,
                                      int nparams,
                                      const char *cookiein,
                                      int cookieinlen,
                                      char **cookieout,
                                      int *cookieoutlen,
                                      unsigned int flags)
{
    virQEMUDriverPtr driver = dconn->privateData;
    virDomainDefPtr def = NULL;
    const char *dom_xml = NULL;
    const char *dname = NULL;
    int ret = -1;

    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
    if (virTypedParamsValidate(params, nparams, QEMU_MIGRATION_PARAMETERS) < 0)
        return -1;

    if (virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_XML,
                                &dom_xml) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_NAME,
                                &dname) < 0)
        return -1;

    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("PrepareTunnel called but no TUNNELLED flag set"));
        goto cleanup;
    }

    if (!(def = qemuMigrationPrepareDef(driver, dom_xml, dname)))
        goto cleanup;

    if (virDomainMigratePrepareTunnel3ParamsEnsureACL(dconn, def) < 0)
        goto cleanup;

    ret = qemuMigrationPrepareTunnel(driver, dconn,
                                     cookiein, cookieinlen,
                                     cookieout, cookieoutlen,
                                     st, &def, flags);

cleanup:
    virDomainDefFree(def);
    return ret;
}

10412 10413 10414

static int
qemuDomainMigratePerform3(virDomainPtr dom,
10415
                          const char *xmlin,
10416 10417 10418 10419
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
10420
                          const char *dconnuri,
10421 10422 10423 10424 10425
                          const char *uri,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource)
{
10426
    virQEMUDriverPtr driver = dom->conn->privateData;
10427 10428
    virDomainObjPtr vm;

10429
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
10430

10431 10432
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
10433

10434 10435 10436 10437 10438
    if (virDomainMigratePerform3EnsureACL(dom->conn, vm->def) < 0) {
        virObjectUnlock(vm);
        return -1;
    }

10439
    return qemuMigrationPerform(driver, dom->conn, vm, xmlin,
10440
                                dconnuri, uri, NULL, cookiein, cookieinlen,
10441 10442
                                cookieout, cookieoutlen,
                                flags, dname, resource, true);
10443 10444
}

10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460
static int
qemuDomainMigratePerform3Params(virDomainPtr dom,
                                const char *dconnuri,
                                virTypedParameterPtr params,
                                int nparams,
                                const char *cookiein,
                                int cookieinlen,
                                char **cookieout,
                                int *cookieoutlen,
                                unsigned int flags)
{
    virQEMUDriverPtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    const char *dom_xml = NULL;
    const char *dname = NULL;
    const char *uri = NULL;
10461
    const char *graphicsuri = NULL;
10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478
    unsigned long long bandwidth = 0;

    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
    if (virTypedParamsValidate(params, nparams, QEMU_MIGRATION_PARAMETERS) < 0)
        return -1;

    if (virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_XML,
                                &dom_xml) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_NAME,
                                &dname) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_URI,
                                &uri) < 0 ||
        virTypedParamsGetULLong(params, nparams,
                                VIR_MIGRATE_PARAM_BANDWIDTH,
10479 10480 10481 10482
                                &bandwidth) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_GRAPHICS_URI,
                                &graphicsuri) < 0)
10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493
        return -1;

    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;

    if (virDomainMigratePerform3ParamsEnsureACL(dom->conn, vm->def) < 0) {
        virObjectUnlock(vm);
        return -1;
    }

    return qemuMigrationPerform(driver, dom->conn, vm, dom_xml,
10494 10495
                                dconnuri, uri, graphicsuri,
                                cookiein, cookieinlen, cookieout, cookieoutlen,
10496 10497 10498
                                flags, dname, bandwidth, true);
}

10499

10500
static virDomainPtr
10501 10502 10503 10504 10505 10506
qemuDomainMigrateFinish3(virConnectPtr dconn,
                         const char *dname,
                         const char *cookiein,
                         int cookieinlen,
                         char **cookieout,
                         int *cookieoutlen,
10507
                         const char *dconnuri ATTRIBUTE_UNUSED,
10508 10509
                         const char *uri ATTRIBUTE_UNUSED,
                         unsigned long flags,
10510
                         int cancelled)
10511
{
10512
    virQEMUDriverPtr driver = dconn->privateData;
10513 10514
    virDomainObjPtr vm;

10515
    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
10516

10517 10518
    if (!dname ||
        !(vm = virDomainObjListFindByName(driver->domains, dname))) {
10519
        virReportError(VIR_ERR_NO_DOMAIN,
10520 10521 10522
                       _("no domain with matching name '%s'"),
                       NULLSTR(dname));
        return NULL;
10523 10524
    }

10525 10526 10527 10528
    if (virDomainMigrateFinish3EnsureACL(dconn, vm->def) < 0) {
        virObjectUnlock(vm);
        return NULL;
    }
10529

10530 10531 10532 10533 10534
    return qemuMigrationFinish(driver, dconn, vm,
                               cookiein, cookieinlen,
                               cookieout, cookieoutlen,
                               flags, cancelled, true);
}
10535

10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576
static virDomainPtr
qemuDomainMigrateFinish3Params(virConnectPtr dconn,
                               virTypedParameterPtr params,
                               int nparams,
                               const char *cookiein,
                               int cookieinlen,
                               char **cookieout,
                               int *cookieoutlen,
                               unsigned int flags,
                               int cancelled)
{
    virQEMUDriverPtr driver = dconn->privateData;
    virDomainObjPtr vm;
    const char *dname = NULL;

    virCheckFlags(QEMU_MIGRATION_FLAGS, NULL);
    if (virTypedParamsValidate(params, nparams, QEMU_MIGRATION_PARAMETERS) < 0)
        return NULL;

    if (virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_NAME,
                                &dname) < 0)
        return NULL;

    if (!dname ||
        !(vm = virDomainObjListFindByName(driver->domains, dname))) {
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching name '%s'"),
                       NULLSTR(dname));
        return NULL;
    }

    if (virDomainMigrateFinish3ParamsEnsureACL(dconn, vm->def) < 0) {
        virObjectUnlock(vm);
        return NULL;
    }

    return qemuMigrationFinish(driver, dconn, vm,
                               cookiein, cookieinlen,
                               cookieout, cookieoutlen,
                               flags, cancelled, true);
10577 10578
}

10579

10580 10581 10582 10583 10584 10585 10586 10587 10588
static int
qemuDomainMigrateConfirm3(virDomainPtr domain,
                          const char *cookiein,
                          int cookieinlen,
                          unsigned long flags,
                          int cancelled)
{
    virDomainObjPtr vm;

10589
    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);
10590

10591 10592
    if (!(vm = qemuDomObjFromDomain(domain)))
        return -1;
10593

10594 10595 10596
    if (virDomainMigrateConfirm3EnsureACL(domain->conn, vm->def) < 0) {
        virObjectUnlock(vm);
        return -1;
10597 10598
    }

10599 10600
    return qemuMigrationConfirm(domain->conn, vm, cookiein, cookieinlen,
                                flags, cancelled);
10601 10602
}

10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630
static int
qemuDomainMigrateConfirm3Params(virDomainPtr domain,
                                virTypedParameterPtr params,
                                int nparams,
                                const char *cookiein,
                                int cookieinlen,
                                unsigned int flags,
                                int cancelled)
{
    virDomainObjPtr vm;

    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);

    if (virTypedParamsValidate(params, nparams, QEMU_MIGRATION_PARAMETERS) < 0)
        return -1;

    if (!(vm = qemuDomObjFromDomain(domain)))
        return -1;

    if (virDomainMigrateConfirm3ParamsEnsureACL(domain->conn, vm->def) < 0) {
        virObjectUnlock(vm);
        return -1;
    }

    return qemuMigrationConfirm(domain->conn, vm, cookiein, cookieinlen,
                                flags, cancelled);
}

10631

10632
static int
10633
qemuNodeDeviceGetPciInfo(virNodeDeviceDefPtr def,
10634 10635 10636 10637
                         unsigned *domain,
                         unsigned *bus,
                         unsigned *slot,
                         unsigned *function)
10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655
{
    virNodeDevCapsDefPtr cap;
    int ret = -1;

    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) {
10656
        virReportError(VIR_ERR_INVALID_ARG,
10657
                       _("device %s is not a PCI device"), def->name);
10658 10659 10660 10661 10662 10663 10664 10665 10666
        goto out;
    }

    ret = 0;
out:
    return ret;
}

static int
10667 10668 10669
qemuNodeDeviceDetachFlags(virNodeDevicePtr dev,
                          const char *driverName,
                          unsigned int flags)
10670
{
10671
    virQEMUDriverPtr driver = dev->conn->privateData;
10672
    virPCIDevicePtr pci = NULL;
10673 10674
    unsigned domain, bus, slot, function;
    int ret = -1;
10675 10676
    virNodeDeviceDefPtr def = NULL;
    char *xml = NULL;
10677

10678 10679
    virCheckFlags(0, -1);

10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692
    xml = virNodeDeviceGetXMLDesc(dev, 0);
    if (!xml)
        goto cleanup;

    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE, NULL);
    if (!def)
        goto cleanup;

    if (virNodeDeviceDetachFlagsEnsureACL(dev->conn, def) < 0)
        goto cleanup;

    if (qemuNodeDeviceGetPciInfo(def, &domain, &bus, &slot, &function) < 0)
        goto cleanup;
10693

10694
    pci = virPCIDeviceNew(domain, bus, slot, function);
10695
    if (!pci)
10696
        goto cleanup;
10697

10698
    if (!driverName || STREQ(driverName, "kvm")) {
10699 10700
        if (virPCIDeviceSetStubDriver(pci, "pci-stub") < 0)
            goto cleanup;
10701
    } else if (STREQ(driverName, "vfio")) {
10702 10703
        if (virPCIDeviceSetStubDriver(pci, "vfio-pci") < 0)
            goto cleanup;
10704 10705 10706
    } else {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unknown driver name '%s'"), driverName);
10707
        goto cleanup;
10708 10709
    }

10710 10711
    virObjectLock(driver->activePciHostdevs);
    virObjectLock(driver->inactivePciHostdevs);
10712

10713
    if (virPCIDeviceDetach(pci, driver->activePciHostdevs,
10714
                           driver->inactivePciHostdevs, NULL) < 0) {
10715
        goto out;
10716
    }
10717 10718 10719

    ret = 0;
out:
10720 10721
    virObjectUnlock(driver->inactivePciHostdevs);
    virObjectUnlock(driver->activePciHostdevs);
10722
cleanup:
10723
    virPCIDeviceFree(pci);
10724 10725
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
10726 10727 10728
    return ret;
}

10729 10730 10731 10732 10733 10734
static int
qemuNodeDeviceDettach(virNodeDevicePtr dev)
{
    return qemuNodeDeviceDetachFlags(dev, NULL, 0);
}

10735
static int
10736
qemuNodeDeviceReAttach(virNodeDevicePtr dev)
10737
{
10738
    virQEMUDriverPtr driver = dev->conn->privateData;
10739
    virPCIDevicePtr pci = NULL;
10740
    virPCIDevicePtr other;
10741 10742
    unsigned domain, bus, slot, function;
    int ret = -1;
10743 10744
    virNodeDeviceDefPtr def = NULL;
    char *xml = NULL;
10745

10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758
    xml = virNodeDeviceGetXMLDesc(dev, 0);
    if (!xml)
        goto cleanup;

    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE, NULL);
    if (!def)
        goto cleanup;

    if (virNodeDeviceReAttachEnsureACL(dev->conn, def) < 0)
        goto cleanup;

    if (qemuNodeDeviceGetPciInfo(def, &domain, &bus, &slot, &function) < 0)
        goto cleanup;
10759

10760
    pci = virPCIDeviceNew(domain, bus, slot, function);
10761
    if (!pci)
10762
        goto cleanup;
10763

10764 10765
    virObjectLock(driver->activePciHostdevs);
    virObjectLock(driver->inactivePciHostdevs);
10766
    other = virPCIDeviceListFind(driver->activePciHostdevs, pci);
10767
    if (other) {
10768
        const char *other_name = virPCIDeviceGetUsedBy(other);
10769 10770

        if (other_name)
10771 10772
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is still in use by domain %s"),
10773
                           virPCIDeviceGetName(pci), other_name);
10774
        else
10775 10776
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("PCI device %s is still in use"),
10777
                           virPCIDeviceGetName(pci));
10778
        goto out;
10779 10780
    }

10781
    virPCIDeviceReattachInit(pci);
10782

10783
    if (virPCIDeviceReattach(pci, driver->activePciHostdevs,
10784
                             driver->inactivePciHostdevs) < 0)
10785 10786 10787 10788
        goto out;

    ret = 0;
out:
10789 10790
    virObjectUnlock(driver->inactivePciHostdevs);
    virObjectUnlock(driver->activePciHostdevs);
10791
    virPCIDeviceFree(pci);
10792 10793 10794
cleanup:
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
10795 10796 10797 10798
    return ret;
}

static int
10799
qemuNodeDeviceReset(virNodeDevicePtr dev)
10800
{
10801
    virQEMUDriverPtr driver = dev->conn->privateData;
10802
    virPCIDevicePtr pci;
10803 10804
    unsigned domain, bus, slot, function;
    int ret = -1;
10805 10806
    virNodeDeviceDefPtr def = NULL;
    char *xml = NULL;
10807

10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820
    xml = virNodeDeviceGetXMLDesc(dev, 0);
    if (!xml)
        goto cleanup;

    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE, NULL);
    if (!def)
        goto cleanup;

    if (virNodeDeviceResetEnsureACL(dev->conn, def) < 0)
        goto cleanup;

    if (qemuNodeDeviceGetPciInfo(def, &domain, &bus, &slot, &function) < 0)
        goto cleanup;
10821

10822
    pci = virPCIDeviceNew(domain, bus, slot, function);
10823
    if (!pci)
10824
        goto cleanup;
10825

10826 10827
    virObjectLock(driver->activePciHostdevs);
    virObjectLock(driver->inactivePciHostdevs);
10828

10829 10830
    if (virPCIDeviceReset(pci, driver->activePciHostdevs,
                          driver->inactivePciHostdevs) < 0)
10831 10832 10833 10834
        goto out;

    ret = 0;
out:
10835 10836
    virObjectUnlock(driver->inactivePciHostdevs);
    virObjectUnlock(driver->activePciHostdevs);
10837
    virPCIDeviceFree(pci);
10838 10839 10840
cleanup:
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
10841 10842 10843
    return ret;
}

10844
static int
10845 10846 10847
qemuConnectCompareCPU(virConnectPtr conn,
                      const char *xmlDesc,
                      unsigned int flags)
10848
{
10849
    virQEMUDriverPtr driver = conn->privateData;
10850
    int ret = VIR_CPU_COMPARE_ERROR;
10851
    virCapsPtr caps = NULL;
10852

E
Eric Blake 已提交
10853 10854
    virCheckFlags(0, VIR_CPU_COMPARE_ERROR);

10855 10856 10857
    if (virConnectCompareCPUEnsureACL(conn) < 0)
        goto cleanup;

10858 10859 10860 10861 10862
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

    if (!caps->host.cpu ||
        !caps->host.cpu->model) {
10863 10864
        VIR_WARN("cannot get host CPU capabilities");
        ret = VIR_CPU_COMPARE_INCOMPATIBLE;
E
Eric Blake 已提交
10865
    } else {
10866
        ret = cpuCompareXML(caps->host.cpu, xmlDesc);
E
Eric Blake 已提交
10867
    }
10868

10869 10870
cleanup:
    virObjectUnref(caps);
10871 10872 10873
    return ret;
}

10874

10875
static char *
10876 10877 10878 10879
qemuConnectBaselineCPU(virConnectPtr conn ATTRIBUTE_UNUSED,
                       const char **xmlCPUs,
                       unsigned int ncpus,
                       unsigned int flags)
10880
{
10881
    char *cpu = NULL;
10882

E
Eric Blake 已提交
10883 10884
    virCheckFlags(0, NULL);

10885 10886 10887
    if (virConnectBaselineCPUEnsureACL(conn) < 0)
        goto cleanup;

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

10890
cleanup:
10891 10892 10893
    return cpu;
}

10894 10895 10896 10897 10898 10899 10900

static int qemuDomainGetJobInfo(virDomainPtr dom,
                                virDomainJobInfoPtr info) {
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

10901
    if (!(vm = qemuDomObjFromDomain(dom)))
10902 10903 10904 10905
        goto cleanup;

    priv = vm->privateData;

10906 10907 10908
    if (virDomainGetJobInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

10909
    if (virDomainObjIsActive(vm)) {
10910
        if (priv->job.asyncJob && !priv->job.dump_memory_only) {
10911
            memcpy(info, &priv->job.info, sizeof(*info));
10912 10913 10914 10915 10916 10917

            /* 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
             */
10918
            if (virTimeMillisNow(&info->timeElapsed) < 0)
10919
                goto cleanup;
10920
            info->timeElapsed -= priv->job.start;
10921 10922 10923 10924 10925
        } else {
            memset(info, 0, sizeof(*info));
            info->type = VIR_DOMAIN_JOB_NONE;
        }
    } else {
10926 10927
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
10928 10929 10930 10931 10932 10933 10934
        goto cleanup;
    }

    ret = 0;

cleanup:
    if (vm)
10935
        virObjectUnlock(vm);
10936 10937 10938 10939
    return ret;
}


10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960
static int
qemuDomainGetJobStats(virDomainPtr dom,
                      int *type,
                      virTypedParameterPtr *params,
                      int *nparams,
                      unsigned int flags)
{
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    virTypedParameterPtr par = NULL;
    int maxpar = 0;
    int npar = 0;
    int ret = -1;

    virCheckFlags(0, -1);

    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;

    priv = vm->privateData;

10961 10962 10963
    if (virDomainGetJobStatsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082
    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
        goto cleanup;
    }

    if (!priv->job.asyncJob || priv->job.dump_memory_only) {
        *type = VIR_DOMAIN_JOB_NONE;
        *params = NULL;
        *nparams = 0;
        ret = 0;
        goto cleanup;
    }

    /* 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 (virTimeMillisNow(&priv->job.info.timeElapsed) < 0)
        goto cleanup;
    priv->job.info.timeElapsed -= priv->job.start;

    if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_TIME_ELAPSED,
                                priv->job.info.timeElapsed) < 0)
        goto cleanup;

    if (priv->job.info.type == VIR_DOMAIN_JOB_BOUNDED &&
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_TIME_REMAINING,
                                priv->job.info.timeRemaining) < 0)
        goto cleanup;

    if (priv->job.status.downtime_set &&
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DOWNTIME,
                                priv->job.status.downtime) < 0)
        goto cleanup;

    if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DATA_TOTAL,
                                priv->job.info.dataTotal) < 0 ||
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DATA_PROCESSED,
                                priv->job.info.dataProcessed) < 0 ||
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DATA_REMAINING,
                                priv->job.info.dataRemaining) < 0)
        goto cleanup;

    if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_MEMORY_TOTAL,
                                priv->job.info.memTotal) < 0 ||
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_MEMORY_PROCESSED,
                                priv->job.info.memProcessed) < 0 ||
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_MEMORY_REMAINING,
                                priv->job.info.memRemaining) < 0)
        goto cleanup;

    if (priv->job.status.ram_duplicate_set) {
        if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_MEMORY_CONSTANT,
                                    priv->job.status.ram_duplicate) < 0 ||
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_MEMORY_NORMAL,
                                    priv->job.status.ram_normal) < 0 ||
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_MEMORY_NORMAL_BYTES,
                                    priv->job.status.ram_normal_bytes) < 0)
            goto cleanup;
    }

    if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DISK_TOTAL,
                                priv->job.info.fileTotal) < 0 ||
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DISK_PROCESSED,
                                priv->job.info.fileProcessed) < 0 ||
        virTypedParamsAddULLong(&par, &npar, &maxpar,
                                VIR_DOMAIN_JOB_DISK_REMAINING,
                                priv->job.info.fileRemaining) < 0)
        goto cleanup;

    if (priv->job.status.xbzrle_set) {
        if (virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_CACHE,
                                    priv->job.status.xbzrle_cache_size) < 0 ||
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_BYTES,
                                    priv->job.status.xbzrle_bytes) < 0 ||
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_PAGES,
                                    priv->job.status.xbzrle_pages) < 0 ||
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_CACHE_MISSES,
                                    priv->job.status.xbzrle_cache_miss) < 0 ||
            virTypedParamsAddULLong(&par, &npar, &maxpar,
                                    VIR_DOMAIN_JOB_COMPRESSION_OVERFLOW,
                                    priv->job.status.xbzrle_overflow) < 0)
            goto cleanup;
    }

    *type = priv->job.info.type;
    *params = par;
    *nparams = npar;
    ret = 0;

cleanup:
    if (vm)
        virObjectUnlock(vm);
    if (ret < 0)
        virTypedParamsFree(par, npar);
    return ret;
}


11083
static int qemuDomainAbortJob(virDomainPtr dom) {
11084
    virQEMUDriverPtr driver = dom->conn->privateData;
11085 11086 11087 11088
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

11089
    if (!(vm = qemuDomObjFromDomain(dom)))
11090 11091
        goto cleanup;

11092 11093 11094
    if (virDomainAbortJobEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

11095 11096
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_ABORT) < 0)
        goto cleanup;
11097

11098
    if (!virDomainObjIsActive(vm)) {
11099 11100
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
11101
        goto endjob;
11102 11103
    }

11104 11105
    priv = vm->privateData;

11106
    if (!priv->job.asyncJob || priv->job.dump_memory_only) {
11107 11108
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("no job is active on the domain"));
11109 11110
        goto endjob;
    } else if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_IN) {
11111 11112 11113
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot abort incoming migration;"
                         " use virDomainDestroy instead"));
11114 11115 11116 11117
        goto endjob;
    }

    VIR_DEBUG("Cancelling job at client request");
11118
    qemuDomainObjAbortAsyncJob(vm);
11119
    qemuDomainObjEnterMonitor(driver, vm);
11120 11121 11122 11123 11124 11125
    ret = qemuMonitorMigrateCancel(priv->mon);
    qemuDomainObjExitMonitor(driver, vm);

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
11126 11127 11128

cleanup:
    if (vm)
11129
        virObjectUnlock(vm);
11130 11131 11132 11133
    return ret;
}


11134 11135 11136 11137 11138
static int
qemuDomainMigrateSetMaxDowntime(virDomainPtr dom,
                                unsigned long long downtime,
                                unsigned int flags)
{
11139
    virQEMUDriverPtr driver = dom->conn->privateData;
11140 11141 11142 11143
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1;

11144
    virCheckFlags(0, -1);
11145

11146 11147
    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;
11148

11149 11150 11151
    if (virDomainMigrateSetMaxDowntimeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

11152 11153 11154
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
        goto cleanup;

11155
    if (!virDomainObjIsActive(vm)) {
11156 11157
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
11158
        goto endjob;
11159 11160 11161 11162
    }

    priv = vm->privateData;

11163
    if (priv->job.asyncJob != QEMU_ASYNC_JOB_MIGRATION_OUT) {
11164 11165
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not being migrated"));
11166
        goto endjob;
11167 11168
    }

11169
    VIR_DEBUG("Setting migration downtime to %llums", downtime);
11170
    qemuDomainObjEnterMonitor(driver, vm);
11171 11172 11173 11174 11175 11176
    ret = qemuMonitorSetMigrationDowntime(priv->mon, downtime);
    qemuDomainObjExitMonitor(driver, vm);

endjob:
    if (qemuDomainObjEndJob(driver, vm) == 0)
        vm = NULL;
11177 11178 11179

cleanup:
    if (vm)
11180
        virObjectUnlock(vm);
11181 11182 11183
    return ret;
}

11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198
static int
qemuDomainMigrateGetCompressionCache(virDomainPtr dom,
                                     unsigned long long *cacheSize,
                                     unsigned int flags)
{
    virQEMUDriverPtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(0, -1);

    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;

11199 11200 11201
    if (virDomainMigrateGetCompressionCacheEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
        goto cleanup;

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

    priv = vm->privateData;

    qemuDomainObjEnterMonitor(driver, vm);

    ret = qemuMonitorGetMigrationCapability(
                priv->mon,
                QEMU_MONITOR_MIGRATION_CAPS_XBZRLE);
    if (ret == 0) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("Compressed migration is not supported by "
                         "QEMU binary"));
        ret = -1;
    } else if (ret > 0) {
        ret = qemuMonitorGetMigrationCacheSize(priv->mon, cacheSize);
    }

    qemuDomainObjExitMonitor(driver, vm);

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

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

static int
qemuDomainMigrateSetCompressionCache(virDomainPtr dom,
                                     unsigned long long cacheSize,
                                     unsigned int flags)
{
    virQEMUDriverPtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(0, -1);

    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;

11254 11255 11256
    if (virDomainMigrateSetCompressionCacheEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
        goto cleanup;

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

    priv = vm->privateData;

    qemuDomainObjEnterMonitor(driver, vm);

    ret = qemuMonitorGetMigrationCapability(
                priv->mon,
                QEMU_MONITOR_MIGRATION_CAPS_XBZRLE);
    if (ret == 0) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("Compressed migration is not supported by "
                         "QEMU binary"));
        ret = -1;
    } else if (ret > 0) {
        VIR_DEBUG("Setting compression cache to %llu B", cacheSize);
        ret = qemuMonitorSetMigrationCacheSize(priv->mon, cacheSize);
    }

    qemuDomainObjExitMonitor(driver, vm);

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

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

11295 11296 11297 11298 11299
static int
qemuDomainMigrateSetMaxSpeed(virDomainPtr dom,
                             unsigned long bandwidth,
                             unsigned int flags)
{
11300
    virQEMUDriverPtr driver = dom->conn->privateData;
11301 11302 11303 11304 11305 11306
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(0, -1);

11307 11308
    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;
11309 11310

    priv = vm->privateData;
11311 11312 11313 11314

    if (virDomainMigrateSetMaxSpeedEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

11315 11316 11317
    if (virDomainObjIsActive(vm)) {
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MIGRATION_OP) < 0)
            goto cleanup;
11318

11319
        if (!virDomainObjIsActive(vm)) {
11320 11321
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is not running"));
11322 11323 11324
            goto endjob;
        }

11325 11326 11327 11328
        VIR_DEBUG("Setting migration bandwidth to %luMbs", bandwidth);
        qemuDomainObjEnterMonitor(driver, vm);
        ret = qemuMonitorSetMigrationSpeed(priv->mon, bandwidth);
        qemuDomainObjExitMonitor(driver, vm);
11329

11330 11331
        if (ret == 0)
            priv->migMaxBandwidth = bandwidth;
11332

11333
endjob:
11334 11335 11336 11337 11338 11339
        if (qemuDomainObjEndJob(driver, vm) == 0)
            vm = NULL;
    } else {
        priv->migMaxBandwidth = bandwidth;
        ret = 0;
    }
11340 11341 11342

cleanup:
    if (vm)
11343
        virObjectUnlock(vm);
11344 11345 11346
    return ret;
}

11347 11348 11349 11350 11351 11352
static int
qemuDomainMigrateGetMaxSpeed(virDomainPtr dom,
                             unsigned long *bandwidth,
                             unsigned int flags)
{
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
11353
    qemuDomainObjPrivatePtr priv;
11354 11355 11356 11357
    int ret = -1;

    virCheckFlags(0, -1);

11358
    if (!(vm = qemuDomObjFromDomain(dom)))
11359 11360
        goto cleanup;

J
Jim Fehlig 已提交
11361
    priv = vm->privateData;
11362 11363 11364 11365

    if (virDomainMigrateGetMaxSpeedEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
11366
    *bandwidth = priv->migMaxBandwidth;
11367 11368 11369 11370
    ret = 0;

cleanup:
    if (vm)
11371
        virObjectUnlock(vm);
11372 11373 11374
    return ret;
}

11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386
typedef enum {
    VIR_DISK_CHAIN_NO_ACCESS,
    VIR_DISK_CHAIN_READ_ONLY,
    VIR_DISK_CHAIN_READ_WRITE,
} qemuDomainDiskChainMode;

/* Several operations end up adding or removing a single element of a
 * disk backing file chain; this helper function ensures that the lock
 * manager, cgroup device controller, and security manager labelling
 * are all aware of each new file before it is added to a chain, and
 * can revoke access to a file no longer needed in a chain.  */
static int
11387
qemuDomainPrepareDiskChainElement(virQEMUDriverPtr driver,
11388 11389
                                  virDomainObjPtr vm,
                                  virDomainDiskDefPtr disk,
11390
                                  const char *file,
11391 11392 11393 11394 11395 11396 11397 11398 11399 11400
                                  qemuDomainDiskChainMode mode)
{
    /* The easiest way to label a single file with the same
     * permissions it would have as if part of the disk chain is to
     * temporarily modify the disk in place.  */
    char *origsrc = disk->src;
    int origformat = disk->format;
    virStorageFileMetadataPtr origchain = disk->backingChain;
    bool origreadonly = disk->readonly;
    int ret = -1;
11401
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
11402

11403
    disk->src = (char *) file; /* casting away const is safe here */
11404 11405 11406 11407 11408 11409 11410 11411
    disk->format = VIR_STORAGE_FILE_RAW;
    disk->backingChain = NULL;
    disk->readonly = mode == VIR_DISK_CHAIN_READ_ONLY;

    if (mode == VIR_DISK_CHAIN_NO_ACCESS) {
        if (virSecurityManagerRestoreImageLabel(driver->securityManager,
                                                vm->def, disk) < 0)
            VIR_WARN("Unable to restore security label on %s", disk->src);
11412
        if (qemuTeardownDiskCgroup(vm, disk) < 0)
11413 11414 11415
            VIR_WARN("Failed to teardown cgroup for disk path %s", disk->src);
        if (virDomainLockDiskDetach(driver->lockManager, vm, disk) < 0)
            VIR_WARN("Unable to release lock on %s", disk->src);
11416
    } else if (virDomainLockDiskAttach(driver->lockManager, cfg->uri,
11417
                                       vm, disk) < 0 ||
11418
               qemuSetupDiskCgroup(vm, disk) < 0 ||
11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430
               virSecurityManagerSetImageLabel(driver->securityManager,
                                               vm->def, disk) < 0) {
        goto cleanup;
    }

    ret = 0;

cleanup:
    disk->src = origsrc;
    disk->format = origformat;
    disk->backingChain = origchain;
    disk->readonly = origreadonly;
11431
    virObjectUnref(cfg);
11432 11433 11434 11435
    return ret;
}


11436
static int
11437
qemuDomainSnapshotFSFreeze(virDomainObjPtr vm) {
11438 11439 11440 11441
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int freezed;

    if (priv->agentError) {
11442
        virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
11443 11444
                       _("QEMU guest agent is not "
                         "available due to an error"));
11445 11446 11447
        return -1;
    }
    if (!priv->agent) {
11448 11449
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("QEMU guest agent is not configured"));
11450 11451 11452
        return -1;
    }

11453
    qemuDomainObjEnterAgent(vm);
11454
    freezed = qemuAgentFSFreeze(priv->agent);
11455
    qemuDomainObjExitAgent(vm);
11456 11457 11458 11459 11460

    return freezed;
}

static int
11461
qemuDomainSnapshotFSThaw(virDomainObjPtr vm, bool report)
E
Eric Blake 已提交
11462
{
11463 11464
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int thawed;
E
Eric Blake 已提交
11465
    virErrorPtr err = NULL;
11466 11467

    if (priv->agentError) {
E
Eric Blake 已提交
11468
        if (report)
11469
            virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
11470 11471
                           _("QEMU guest agent is not "
                             "available due to an error"));
11472 11473 11474
        return -1;
    }
    if (!priv->agent) {
E
Eric Blake 已提交
11475
        if (report)
11476 11477
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                           _("QEMU guest agent is not configured"));
11478 11479 11480
        return -1;
    }

11481
    qemuDomainObjEnterAgent(vm);
E
Eric Blake 已提交
11482
    if (!report)
11483
        err = virSaveLastError();
11484
    thawed = qemuAgentFSThaw(priv->agent);
11485 11486
    if (!report)
        virSetError(err);
11487
    qemuDomainObjExitAgent(vm);
11488

11489
    virFreeError(err);
11490 11491 11492
    return thawed;
}

11493 11494
/* The domain is expected to be locked and inactive. */
static int
11495
qemuDomainSnapshotCreateInactiveInternal(virQEMUDriverPtr driver,
11496 11497
                                         virDomainObjPtr vm,
                                         virDomainSnapshotObjPtr snap)
11498
{
E
Eric Blake 已提交
11499
    return qemuDomainSnapshotForEachQcow2(driver, vm, snap, "-c", false);
11500 11501
}

11502 11503
/* The domain is expected to be locked and inactive. */
static int
11504
qemuDomainSnapshotCreateInactiveExternal(virQEMUDriverPtr driver,
11505 11506 11507 11508 11509 11510 11511 11512 11513
                                         virDomainObjPtr vm,
                                         virDomainSnapshotObjPtr snap,
                                         bool reuse)
{
    int i;
    virDomainSnapshotDiskDefPtr snapdisk;
    virDomainDiskDefPtr defdisk;
    virCommandPtr cmd = NULL;
    const char *qemuImgPath;
11514 11515
    virBitmapPtr created = NULL;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
11516 11517 11518
    int ret = -1;

    if (!(qemuImgPath = qemuFindQemuImgBinary(driver)))
11519
        goto cleanup;
11520 11521 11522

    if (!(created = virBitmapNew(snap->def->ndisks))) {
        virReportOOMError();
11523
        goto cleanup;
11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552
    }

    /* If reuse is true, then qemuDomainSnapshotPrepare already
     * ensured that the new files exist, and it was up to the user to
     * create them correctly.  */
    for (i = 0; i < snap->def->ndisks && !reuse; i++) {
        snapdisk = &(snap->def->disks[i]);
        defdisk = snap->def->dom->disks[snapdisk->index];
        if (snapdisk->snapshot != VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL)
            continue;

        if (!snapdisk->format)
            snapdisk->format = VIR_STORAGE_FILE_QCOW2;

        /* creates cmd line args: qemu-img create -f qcow2 -o */
        if (!(cmd = virCommandNewArgList(qemuImgPath,
                                         "create",
                                         "-f",
                                         virStorageFileFormatTypeToString(snapdisk->format),
                                         "-o",
                                         NULL)))
            goto cleanup;

        if (defdisk->format > 0) {
            /* adds cmd line arg: backing_file=/path/to/backing/file,backing_fmd=format */
            virCommandAddArgFormat(cmd, "backing_file=%s,backing_fmt=%s",
                                   defdisk->src,
                                   virStorageFileFormatTypeToString(defdisk->format));
        } else {
11553
            if (!cfg->allowDiskFormatProbing) {
11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown image format of '%s' and "
                                 "format probing is disabled"),
                               defdisk->src);
                goto cleanup;
            }

            /* adds cmd line arg: backing_file=/path/to/backing/file */
            virCommandAddArgFormat(cmd, "backing_file=%s", defdisk->src);
        }

        /* adds cmd line args: /path/to/target/file */
        virCommandAddArg(cmd, snapdisk->file);

        /* If the target does not exist, we're going to create it possibly */
        if (!virFileExists(snapdisk->file))
            ignore_value(virBitmapSetBit(created, i));

        if (virCommandRun(cmd, NULL) < 0)
            goto cleanup;

        virCommandFree(cmd);
        cmd = NULL;
    }

    /* update disk definitions */
    for (i = 0; i < snap->def->ndisks; i++) {
        snapdisk = &(snap->def->disks[i]);
        defdisk = vm->def->disks[snapdisk->index];

        if (snapdisk->snapshot == VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL) {
            VIR_FREE(defdisk->src);
11586
            if (VIR_STRDUP(defdisk->src, snapdisk->file) < 0) {
11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599
                /* we cannot rollback here in a sane way */
                goto cleanup;
            }
            defdisk->format = snapdisk->format;
        }
    }

    ret = 0;

cleanup:
    virCommandFree(cmd);

    /* unlink images if creation has failed */
11600
    if (ret < 0 && created) {
11601 11602 11603 11604 11605 11606 11607 11608 11609
        ssize_t bit = -1;
        while ((bit = virBitmapNextSetBit(created, bit)) >= 0) {
            snapdisk = &(snap->def->disks[bit]);
            if (unlink(snapdisk->file) < 0)
                VIR_WARN("Failed to remove snapshot image '%s'",
                         snapdisk->file);
        }
    }
    virBitmapFree(created);
11610
    virObjectUnref(cfg);
11611 11612 11613 11614

    return ret;
}

11615

11616 11617
/* The domain is expected to be locked and active. */
static int
11618
qemuDomainSnapshotCreateActiveInternal(virConnectPtr conn,
11619
                                       virQEMUDriverPtr driver,
11620 11621 11622
                                       virDomainObjPtr *vmptr,
                                       virDomainSnapshotObjPtr snap,
                                       unsigned int flags)
11623 11624 11625
{
    virDomainObjPtr vm = *vmptr;
    qemuDomainObjPrivatePtr priv = vm->privateData;
11626
    virDomainEventPtr event = NULL;
11627 11628
    bool resume = false;
    int ret = -1;
11629

11630
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
11631 11632
        return -1;

11633
    if (!virDomainObjIsActive(vm)) {
11634 11635
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
11636 11637 11638
        goto endjob;
    }

J
Jiri Denemark 已提交
11639
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
11640 11641 11642 11643
        /* 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.
         */
11644 11645
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_NONE) < 0)
11646 11647 11648 11649
            goto cleanup;

        resume = true;
        if (!virDomainObjIsActive(vm)) {
11650 11651
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("guest unexpectedly quit"));
11652 11653 11654 11655
            goto cleanup;
        }
    }

11656
    qemuDomainObjEnterMonitor(driver, vm);
11657
    ret = qemuMonitorCreateSnapshot(priv->mon, snap->def->name);
11658
    qemuDomainObjExitMonitor(driver, vm);
11659 11660 11661 11662 11663 11664
    if (ret < 0)
        goto cleanup;

    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT) {
        event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT);
11665
        qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT, 0);
11666 11667 11668 11669 11670 11671 11672
        virDomainAuditStop(vm, "from-snapshot");
        /* We already filtered the _HALT flag for persistent domains
         * only, so this end job never drops the last reference.  */
        ignore_value(qemuDomainObjEndJob(driver, vm));
        resume = false;
        vm = NULL;
    }
11673

11674 11675
cleanup:
    if (resume && virDomainObjIsActive(vm) &&
J
Jiri Denemark 已提交
11676
        qemuProcessStartCPUs(driver, vm, conn,
11677
                             VIR_DOMAIN_RUNNING_UNPAUSED,
11678 11679 11680 11681 11682 11683 11684 11685
                             QEMU_ASYNC_JOB_NONE) < 0) {
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_API_ERROR);
        if (virGetLastError() == NULL) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("resuming after snapshot failed"));
        }
11686 11687
    }

11688
endjob:
11689
    if (vm && qemuDomainObjEndJob(driver, vm) == 0) {
11690 11691
        /* Only possible if a transient vm quit while our locks were down,
         * in which case we don't want to save snapshot metadata.  */
11692
        *vmptr = NULL;
11693 11694
        ret = -1;
    }
11695

11696 11697 11698
    if (event)
        qemuDomainEventQueue(driver, event);

11699 11700 11701
    return ret;
}

11702
static int
E
Eric Blake 已提交
11703 11704
qemuDomainSnapshotPrepare(virDomainObjPtr vm, virDomainSnapshotDefPtr def,
                          unsigned int *flags)
11705 11706 11707 11708 11709
{
    int ret = -1;
    int i;
    bool active = virDomainObjIsActive(vm);
    struct stat st;
11710
    bool reuse = (*flags & VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT) != 0;
11711
    bool atomic = (*flags & VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC) != 0;
11712
    bool found_internal = false;
11713 11714
    int external = 0;
    qemuDomainObjPrivatePtr priv = vm->privateData;
11715

E
Eric Blake 已提交
11716
    if (def->state == VIR_DOMAIN_DISK_SNAPSHOT &&
11717
        reuse && !virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_TRANSACTION)) {
11718 11719
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("reuse is not supported with this QEMU binary"));
11720 11721 11722
        goto cleanup;
    }

11723 11724
    for (i = 0; i < def->ndisks; i++) {
        virDomainSnapshotDiskDefPtr disk = &def->disks[i];
E
Eric Blake 已提交
11725
        virDomainDiskDefPtr dom_disk = vm->def->disks[i];
11726 11727

        switch (disk->snapshot) {
E
Eric Blake 已提交
11728
        case VIR_DOMAIN_SNAPSHOT_LOCATION_INTERNAL:
E
Eric Blake 已提交
11729 11730 11731 11732 11733
            if (def->state != VIR_DOMAIN_DISK_SNAPSHOT &&
                dom_disk->type == VIR_DOMAIN_DISK_TYPE_NETWORK &&
                (dom_disk->protocol == VIR_DOMAIN_DISK_PROTOCOL_SHEEPDOG ||
                 dom_disk->protocol == VIR_DOMAIN_DISK_PROTOCOL_RBD)) {
                break;
11734
            }
11735 11736
            if (vm->def->disks[i]->format > 0 &&
                vm->def->disks[i]->format != VIR_STORAGE_FILE_QCOW2) {
11737 11738 11739 11740
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("internal snapshot for disk %s unsupported "
                                 "for storage type %s"),
                               disk->name,
11741 11742
                               virStorageFileFormatTypeToString(
                                   vm->def->disks[i]->format));
11743 11744
                goto cleanup;
            }
E
Eric Blake 已提交
11745 11746 11747 11748 11749 11750 11751
            if (def->state == VIR_DOMAIN_DISK_SNAPSHOT && active) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("active qemu domains require external disk "
                                 "snapshots; disk %s requested internal"),
                               disk->name);
                goto cleanup;
            }
11752
            found_internal = true;
11753 11754
            break;

E
Eric Blake 已提交
11755
        case VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL:
11756 11757 11758 11759
            if (!disk->format) {
                disk->format = VIR_STORAGE_FILE_QCOW2;
            } else if (disk->format != VIR_STORAGE_FILE_QCOW2 &&
                       disk->format != VIR_STORAGE_FILE_QED) {
11760 11761 11762
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("external snapshot format for disk %s "
                                 "is unsupported: %s"),
11763 11764
                               disk->name,
                               virStorageFileFormatTypeToString(disk->format));
11765 11766 11767 11768 11769 11770 11771 11772
                goto cleanup;
            }
            if (stat(disk->file, &st) < 0) {
                if (errno != ENOENT) {
                    virReportSystemError(errno,
                                         _("unable to stat for disk %s: %s"),
                                         disk->name, disk->file);
                    goto cleanup;
11773 11774 11775 11776 11777
                } else if (reuse) {
                    virReportSystemError(errno,
                                         _("missing existing file for disk %s: %s"),
                                         disk->name, disk->file);
                    goto cleanup;
11778
                }
11779
            } else if (!S_ISBLK(st.st_mode) && st.st_size && !reuse) {
11780 11781 11782 11783
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("external snapshot file for disk %s already "
                                 "exists and is not a block device: %s"),
                               disk->name, disk->file);
11784 11785
                goto cleanup;
            }
11786
            external++;
11787 11788
            break;

E
Eric Blake 已提交
11789
        case VIR_DOMAIN_SNAPSHOT_LOCATION_NONE:
11790 11791
            break;

E
Eric Blake 已提交
11792
        case VIR_DOMAIN_SNAPSHOT_LOCATION_DEFAULT:
11793
        default:
11794 11795
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("unexpected code path"));
11796 11797 11798 11799
            goto cleanup;
        }
    }

11800 11801 11802
    /* internal snapshot requires a disk image to store the memory image to */
    if (def->memory == VIR_DOMAIN_SNAPSHOT_LOCATION_INTERNAL &&
        !found_internal) {
11803
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
11804
                       _("internal checkpoints require at least "
11805
                         "one disk to be selected for snapshot"));
11806 11807
        goto cleanup;
    }
11808

11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830
    /* disk snapshot requires at least one disk */
    if (def->state == VIR_DOMAIN_DISK_SNAPSHOT && !external) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("disk-only snapshots require at least "
                         "one disk to be selected for snapshot"));
        goto cleanup;
    }

    /* For now, we don't allow mixing internal and external disks.
     * XXX technically, we could mix internal and external disks for
     * offline snapshots */
    if (found_internal && external) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("mixing internal and external snapshots is not "
                         "supported yet"));
        goto cleanup;
    }

    /* Alter flags to let later users know what we learned.  */
    if (external && !active)
        *flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY;

E
Eric Blake 已提交
11831
    if (def->state != VIR_DOMAIN_DISK_SNAPSHOT && active) {
11832
        if (external == 1 ||
11833
            virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_TRANSACTION)) {
11834 11835
            *flags |= VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC;
        } else if (atomic && external > 1) {
11836 11837 11838
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("atomic live snapshot of multiple disks "
                             "is unsupported"));
11839 11840 11841
            goto cleanup;
        }
    }
11842 11843 11844 11845 11846 11847 11848 11849 11850

    ret = 0;

cleanup:
    return ret;
}

/* The domain is expected to hold monitor lock.  */
static int
11851
qemuDomainSnapshotCreateSingleDiskActive(virQEMUDriverPtr driver,
11852
                                         virDomainObjPtr vm,
11853
                                         virDomainSnapshotDiskDefPtr snap,
11854
                                         virDomainDiskDefPtr disk,
11855
                                         virDomainDiskDefPtr persistDisk,
11856 11857
                                         virJSONValuePtr actions,
                                         bool reuse)
11858 11859 11860 11861
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *device = NULL;
    char *source = NULL;
11862 11863
    int format = snap->format;
    const char *formatStr = NULL;
11864
    char *persistSource = NULL;
11865
    int ret = -1;
11866 11867
    int fd = -1;
    bool need_unlink = false;
11868

E
Eric Blake 已提交
11869
    if (snap->snapshot != VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL) {
11870 11871
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected code path"));
11872 11873 11874 11875
        return -1;
    }

    if (virAsprintf(&device, "drive-%s", disk->info.alias) < 0 ||
11876 11877
        VIR_STRDUP(source, snap->file) < 0 ||
        (persistDisk && VIR_STRDUP(persistSource, source) < 0)) {
11878 11879 11880 11881
        virReportOOMError();
        goto cleanup;
    }

11882 11883
    /* create the stub file and set selinux labels; manipulate disk in
     * place, in a way that can be reverted on failure. */
11884 11885 11886 11887 11888 11889 11890
    if (!reuse) {
        fd = qemuOpenFile(driver, source, O_WRONLY | O_TRUNC | O_CREAT,
                          &need_unlink, NULL);
        if (fd < 0)
            goto cleanup;
        VIR_FORCE_CLOSE(fd);
    }
11891

11892 11893 11894 11895 11896 11897 11898 11899
    /* XXX Here, we know we are about to alter disk->backingChain if
     * successful, so we nuke the existing chain so that future
     * commands will recompute it.  Better would be storing the chain
     * ourselves rather than reprobing, but this requires modifying
     * domain_conf and our XML to fully track the chain across
     * libvirtd restarts.  */
    virStorageFileFreeMetadata(disk->backingChain);
    disk->backingChain = NULL;
11900

11901
    if (qemuDomainPrepareDiskChainElement(driver, vm, disk, source,
11902
                                          VIR_DISK_CHAIN_READ_WRITE) < 0) {
11903
        qemuDomainPrepareDiskChainElement(driver, vm, disk, source,
11904
                                          VIR_DISK_CHAIN_NO_ACCESS);
11905 11906 11907 11908
        goto cleanup;
    }

    /* create the actual snapshot */
11909 11910
    if (snap->format)
        formatStr = virStorageFileFormatTypeToString(snap->format);
11911
    ret = qemuMonitorDiskSnapshot(priv->mon, actions, device, source,
11912
                                  formatStr, reuse);
11913 11914 11915 11916 11917
    virDomainAuditDisk(vm, disk->src, source, "snapshot", ret >= 0);
    if (ret < 0)
        goto cleanup;

    /* Update vm in place to match changes.  */
11918
    need_unlink = false;
11919 11920 11921
    VIR_FREE(disk->src);
    disk->src = source;
    source = NULL;
11922
    disk->format = format;
11923 11924 11925 11926
    if (persistDisk) {
        VIR_FREE(persistDisk->src);
        persistDisk->src = persistSource;
        persistSource = NULL;
11927
        persistDisk->format = format;
11928
    }
11929 11930

cleanup:
11931 11932
    if (need_unlink && unlink(source))
        VIR_WARN("unable to unlink just-created %s", source);
11933 11934
    VIR_FREE(device);
    VIR_FREE(source);
11935
    VIR_FREE(persistSource);
11936 11937 11938
    return ret;
}

11939 11940 11941 11942
/* The domain is expected to hold monitor lock.  This is the
 * counterpart to qemuDomainSnapshotCreateSingleDiskActive, called
 * only on a failed transaction. */
static void
11943
qemuDomainSnapshotUndoSingleDiskActive(virQEMUDriverPtr driver,
11944 11945 11946 11947 11948 11949 11950 11951 11952 11953
                                       virDomainObjPtr vm,
                                       virDomainDiskDefPtr origdisk,
                                       virDomainDiskDefPtr disk,
                                       virDomainDiskDefPtr persistDisk,
                                       bool need_unlink)
{
    char *source = NULL;
    char *persistSource = NULL;
    struct stat st;

11954 11955
    if (VIR_STRDUP(source, origdisk->src) < 0 ||
        (persistDisk && VIR_STRDUP(persistSource, source) < 0))
11956 11957
        goto cleanup;

11958
    qemuDomainPrepareDiskChainElement(driver, vm, disk, disk->src,
11959
                                      VIR_DISK_CHAIN_NO_ACCESS);
11960
    if (need_unlink && stat(disk->src, &st) == 0 &&
11961
        S_ISREG(st.st_mode) && unlink(disk->src) < 0)
11962 11963 11964 11965 11966 11967
        VIR_WARN("Unable to remove just-created %s", disk->src);

    /* Update vm in place to match changes.  */
    VIR_FREE(disk->src);
    disk->src = source;
    source = NULL;
11968
    disk->format = origdisk->format;
11969 11970 11971 11972
    if (persistDisk) {
        VIR_FREE(persistDisk->src);
        persistDisk->src = persistSource;
        persistSource = NULL;
11973
        persistDisk->format = origdisk->format;
11974 11975 11976 11977 11978 11979 11980
    }

cleanup:
    VIR_FREE(source);
    VIR_FREE(persistSource);
}

11981 11982
/* The domain is expected to be locked and active. */
static int
11983
qemuDomainSnapshotCreateDiskActive(virQEMUDriverPtr driver,
11984
                                   virDomainObjPtr vm,
11985
                                   virDomainSnapshotObjPtr snap,
11986 11987
                                   unsigned int flags,
                                   enum qemuDomainAsyncJob asyncJob)
11988
{
11989 11990
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virJSONValuePtr actions = NULL;
11991 11992
    int ret = -1;
    int i;
11993
    bool persist = false;
11994
    bool reuse = (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT) != 0;
11995
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
11996

11997
    if (!virDomainObjIsActive(vm)) {
11998 11999
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
12000
        goto cleanup;
12001 12002
    }

12003
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_TRANSACTION)) {
12004
        if (!(actions = virJSONValueNewArray())) {
12005 12006 12007
            virReportOOMError();
            goto cleanup;
        }
12008
    } else if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DISK_SNAPSHOT)) {
12009 12010 12011 12012
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("live disk snapshot not supported with this "
                         "QEMU binary"));
        goto cleanup;
12013
    }
12014 12015

    /* No way to roll back if first disk succeeds but later disks
12016
     * fail, unless we have transaction support.
E
Eric Blake 已提交
12017
     * Based on earlier qemuDomainSnapshotPrepare, all
12018 12019
     * disks in this list are now either SNAPSHOT_NO, or
     * SNAPSHOT_EXTERNAL with a valid file name and qcow2 format.  */
12020 12021 12022
    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
        goto cleanup;

12023
    for (i = 0; i < snap->def->ndisks; i++) {
12024 12025
        virDomainDiskDefPtr persistDisk = NULL;

E
Eric Blake 已提交
12026
        if (snap->def->disks[i].snapshot == VIR_DOMAIN_SNAPSHOT_LOCATION_NONE)
12027
            continue;
12028 12029 12030 12031 12032 12033 12034 12035 12036
        if (vm->newDef) {
            int indx = virDomainDiskIndexByName(vm->newDef,
                                                vm->def->disks[i]->dst,
                                                false);
            if (indx >= 0) {
                persistDisk = vm->newDef->disks[indx];
                persist = true;
            }
        }
12037

12038
        ret = qemuDomainSnapshotCreateSingleDiskActive(driver, vm,
12039
                                                       &snap->def->disks[i],
12040
                                                       vm->def->disks[i],
12041 12042
                                                       persistDisk, actions,
                                                       reuse);
12043 12044 12045
        if (ret < 0)
            break;
    }
12046 12047 12048
    if (actions) {
        if (ret == 0)
            ret = qemuMonitorTransaction(priv->mon, actions);
E
Eric Blake 已提交
12049
        virJSONValueFree(actions);
12050 12051 12052 12053 12054 12055
        if (ret < 0) {
            /* Transaction failed; undo the changes to vm.  */
            bool need_unlink = !(flags & VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT);
            while (--i >= 0) {
                virDomainDiskDefPtr persistDisk = NULL;

E
Eric Blake 已提交
12056 12057
                if (snap->def->disks[i].snapshot ==
                    VIR_DOMAIN_SNAPSHOT_LOCATION_NONE)
12058 12059 12060 12061 12062 12063 12064 12065 12066
                    continue;
                if (vm->newDef) {
                    int indx = virDomainDiskIndexByName(vm->newDef,
                                                        vm->def->disks[i]->dst,
                                                        false);
                    if (indx >= 0)
                        persistDisk = vm->newDef->disks[indx];
                }

12067
                qemuDomainSnapshotUndoSingleDiskActive(driver, vm,
12068 12069 12070 12071 12072 12073 12074
                                                       snap->def->dom->disks[i],
                                                       vm->def->disks[i],
                                                       persistDisk,
                                                       need_unlink);
            }
        }
    }
12075
    qemuDomainObjExitMonitor(driver, vm);
12076 12077 12078

cleanup:

12079
    if (ret == 0 || !virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_TRANSACTION)) {
12080
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0 ||
12081
            (persist && virDomainSaveConfig(cfg->configDir, vm->newDef) < 0))
12082 12083
            ret = -1;
    }
12084
    virObjectUnref(cfg);
12085 12086 12087 12088 12089 12090 12091

    return ret;
}


static int
qemuDomainSnapshotCreateActiveExternal(virConnectPtr conn,
12092
                                       virQEMUDriverPtr driver,
12093 12094 12095 12096 12097 12098 12099 12100 12101 12102
                                       virDomainObjPtr *vmptr,
                                       virDomainSnapshotObjPtr snap,
                                       unsigned int flags)
{
    bool resume = false;
    int ret = -1;
    virDomainObjPtr vm = *vmptr;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *xml = NULL;
    bool memory = snap->def->memory == VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL;
12103
    bool memory_unlink = false;
12104
    bool atomic = !!(flags & VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC);
12105
    bool transaction = virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_TRANSACTION);
12106
    int thaw = 0; /* 1 if freeze succeeded, -1 if freeze failed */
12107
    bool pmsuspended = false;
12108

P
Peter Krempa 已提交
12109
    if (qemuDomainObjBeginAsyncJob(driver, vm, QEMU_ASYNC_JOB_SNAPSHOT) < 0)
12110 12111
        goto cleanup;

12112 12113 12114 12115 12116
    /* If quiesce was requested, then issue a freeze command, and a
     * counterpart thaw command, no matter what.  The command will
     * fail if the guest is paused or the guest agent is not
     * running.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) {
12117
        if (qemuDomainSnapshotFSFreeze(vm) < 0) {
12118 12119 12120 12121 12122 12123 12124 12125
            /* helper reported the error */
            thaw = -1;
            goto endjob;
        } else {
            thaw = 1;
        }
    }

12126 12127 12128 12129 12130
    /* We need to track what state the guest is in, since taking the
     * snapshot may alter that state and we must restore it later.  */
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PMSUSPENDED) {
        pmsuspended = true;
    } else if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159
        resume = true;

        /* For external checkpoints (those with memory), the guest
         * must pause (either by libvirt up front, or by qemu after
         * _LIVE converges).  For disk-only snapshots with multiple
         * disks, libvirt must pause externally to get all snapshots
         * to be at the same point in time, unless qemu supports
         * transactions.  For a single disk, snapshot is atomic
         * without requiring a pause.  Thanks to
         * qemuDomainSnapshotPrepare, if we got to this point, the
         * atomic flag now says whether we need to pause, and a
         * capability bit says whether to use transaction.
         */
        if ((memory && !(flags & VIR_DOMAIN_SNAPSHOT_CREATE_LIVE)) ||
            (!memory && atomic && !transaction)) {
            if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SNAPSHOT,
                                    QEMU_ASYNC_JOB_SNAPSHOT) < 0)
                goto endjob;

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

    /* do the memory snapshot if necessary */
    if (memory) {
12160
        /* check if migration is possible */
12161
        if (!qemuMigrationIsAllowed(driver, vm, vm->def, false, false))
12162 12163
            goto endjob;

12164 12165 12166 12167 12168 12169 12170 12171 12172
        /* allow the migration job to be cancelled or the domain to be paused */
        qemuDomainObjSetAsyncJobMask(vm, DEFAULT_JOB_MASK |
                                     JOB_MASK(QEMU_JOB_SUSPEND) |
                                     JOB_MASK(QEMU_JOB_MIGRATION_OP));

        if (!(xml = qemuDomainDefFormatLive(driver, vm->def, true, false)))
            goto endjob;

        if ((ret = qemuDomainSaveMemory(driver, vm, snap->def->file,
12173
                                        xml, QEMU_SAVE_FORMAT_RAW,
12174 12175 12176 12177
                                        resume, 0,
                                        QEMU_ASYNC_JOB_SNAPSHOT)) < 0)
            goto endjob;

12178 12179 12180
        /* the memory image was created, remove it on errors */
        memory_unlink = true;

12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196
        /* forbid any further manipulation */
        qemuDomainObjSetAsyncJobMask(vm, DEFAULT_JOB_MASK);
    }

    /* now the domain is now paused if:
     * - if a memory snapshot was requested
     * - an atomic snapshot was requested AND
     *   qemu does not support transactions
     *
     * Next we snapshot the disks.
     */
    if ((ret = qemuDomainSnapshotCreateDiskActive(driver, vm, snap, flags,
                                                  QEMU_ASYNC_JOB_SNAPSHOT)) < 0)
        goto endjob;

    /* the snapshot is complete now */
12197 12198 12199 12200 12201
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT) {
        virDomainEventPtr event;

        event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT);
12202
        qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT, 0);
12203 12204 12205
        virDomainAuditStop(vm, "from-snapshot");
        /* We already filtered the _HALT flag for persistent domains
         * only, so this end job never drops the last reference.  */
12206
        ignore_value(qemuDomainObjEndAsyncJob(driver, vm));
12207
        resume = false;
E
Eric Blake 已提交
12208
        thaw = 0;
12209 12210 12211
        vm = NULL;
        if (event)
            qemuDomainEventQueue(driver, event);
12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223
    } else if (memory && pmsuspended) {
        /* qemu 1.3 is unable to save a domain in pm-suspended (S3)
         * state; so we must emit an event stating that it was
         * converted to paused.  */
        virDomainEventPtr event;

        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED,
                             VIR_DOMAIN_PAUSED_FROM_SNAPSHOT);
        event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_FROM_SNAPSHOT);
        if (event)
            qemuDomainEventQueue(driver, event);
12224 12225
    }

12226
    ret = 0;
12227 12228

endjob:
12229 12230 12231
    if (resume && vm && virDomainObjIsActive(vm) &&
        qemuProcessStartCPUs(driver, vm, conn,
                             VIR_DOMAIN_RUNNING_UNPAUSED,
12232
                             QEMU_ASYNC_JOB_SNAPSHOT) < 0) {
12233 12234 12235 12236 12237 12238 12239 12240 12241 12242
        virDomainEventPtr event = NULL;
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_API_ERROR);
        if (event)
            qemuDomainEventQueue(driver, event);
        if (virGetLastError() == NULL) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("resuming after snapshot failed"));
        }
12243

12244 12245
        ret = -1;
        goto cleanup;
12246
    }
E
Eric Blake 已提交
12247
    if (vm && thaw != 0 &&
12248
        qemuDomainSnapshotFSThaw(vm, thaw > 0) < 0) {
E
Eric Blake 已提交
12249 12250 12251 12252
        /* helper reported the error, if it was needed */
        if (thaw > 0)
            ret = -1;
    }
12253
    if (vm && !qemuDomainObjEndAsyncJob(driver, vm)) {
12254
        /* Only possible if a transient vm quit while our locks were down,
12255 12256
         * in which case we don't want to save snapshot metadata.
         */
12257 12258
        *vmptr = NULL;
        ret = -1;
12259 12260
    }

12261 12262
cleanup:
    VIR_FREE(xml);
12263 12264
    if (memory_unlink && ret < 0)
        unlink(snap->def->file);
12265

12266 12267 12268
    return ret;
}

12269

12270 12271 12272 12273
static virDomainSnapshotPtr
qemuDomainSnapshotCreateXML(virDomainPtr domain,
                            const char *xmlDesc,
                            unsigned int flags)
C
Chris Lalancette 已提交
12274
{
12275
    virQEMUDriverPtr driver = domain->conn->privateData;
C
Chris Lalancette 已提交
12276
    virDomainObjPtr vm = NULL;
12277
    char *xml = NULL;
C
Chris Lalancette 已提交
12278 12279 12280
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
12281
    virDomainSnapshotDefPtr def = NULL;
12282
    bool update_current = true;
12283
    unsigned int parse_flags = VIR_DOMAIN_SNAPSHOT_PARSE_DISKS;
12284
    virDomainSnapshotObjPtr other = NULL;
12285 12286
    int align_location = VIR_DOMAIN_SNAPSHOT_LOCATION_INTERNAL;
    int align_match = true;
12287
    virQEMUDriverConfigPtr cfg = NULL;
12288
    virCapsPtr caps = NULL;
C
Chris Lalancette 已提交
12289

12290 12291
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE |
                  VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT |
12292
                  VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA |
12293
                  VIR_DOMAIN_SNAPSHOT_CREATE_HALT |
12294
                  VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY |
12295
                  VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT |
12296
                  VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE |
12297 12298
                  VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC |
                  VIR_DOMAIN_SNAPSHOT_CREATE_LIVE, NULL);
12299 12300 12301

    if ((flags & VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) &&
        !(flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY)) {
12302 12303
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("quiesce requires disk-only"));
12304 12305
        return NULL;
    }
12306 12307 12308 12309 12310 12311 12312

    if (((flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) &&
         !(flags & VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT)) ||
        (flags & VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA))
        update_current = false;
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE)
        parse_flags |= VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE;
12313

C
Chris Lalancette 已提交
12314
    virUUIDFormat(domain->uuid, uuidstr);
12315 12316

    if (!(vm = qemuDomObjFromDomain(domain)))
C
Chris Lalancette 已提交
12317 12318
        goto cleanup;

12319 12320
    cfg = virQEMUDriverGetConfig(driver);

12321 12322 12323
    if (virDomainSnapshotCreateXMLEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

12324 12325 12326
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

12327
    if (qemuProcessAutoDestroyActive(driver, vm)) {
12328 12329
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is marked for auto destroy"));
12330 12331
        goto cleanup;
    }
E
Eric Blake 已提交
12332 12333 12334 12335 12336 12337
    if (virDomainHasDiskMirror(vm)) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE, "%s",
                       _("domain has active block copy job"));
        goto cleanup;
    }

12338
    if (!vm->persistent && (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT)) {
12339 12340
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot halt after transient domain snapshot"));
12341 12342
        goto cleanup;
    }
12343 12344 12345
    if ((flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) ||
        !virDomainObjIsActive(vm))
        parse_flags |= VIR_DOMAIN_SNAPSHOT_PARSE_OFFLINE;
12346

12347
    if (!(def = virDomainSnapshotDefParseString(xmlDesc, caps, driver->xmlopt,
12348 12349
                                                QEMU_EXPECTED_VIRT_TYPES,
                                                parse_flags)))
C
Chris Lalancette 已提交
12350 12351
        goto cleanup;

12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369
    /* reject snapshot names containing slashes or starting with dot as
     * snapshot definitions are saved in files named by the snapshot name */
    if (!(flags & VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA)) {
        if (strchr(def->name, '/')) {
            virReportError(VIR_ERR_XML_DETAIL,
                           _("invalid snapshot name '%s': "
                             "name can't contain '/'"),
                           def->name);
            goto cleanup;
        }

        if (def->name[0] == '.') {
            virReportError(VIR_ERR_XML_DETAIL,
                           _("invalid snapshot name '%s': "
                             "name can't start with '.'"),
                           def->name);
            goto cleanup;
        }
12370 12371
    }

12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382
    /* reject the VIR_DOMAIN_SNAPSHOT_CREATE_LIVE flag where not supported */
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_LIVE &&
        (!virDomainObjIsActive(vm) ||
         def->memory != VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL ||
         flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE)) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("live snapshot creation is supported only "
                         "with external checkpoints"));
        goto cleanup;
    }

12383 12384 12385 12386
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) {
        /* Prevent circular chains */
        if (def->parent) {
            if (STREQ(def->name, def->parent)) {
12387 12388 12389
                virReportError(VIR_ERR_INVALID_ARG,
                               _("cannot set snapshot %s as its own parent"),
                               def->name);
12390 12391
                goto cleanup;
            }
12392
            other = virDomainSnapshotFindByName(vm->snapshots, def->parent);
12393
            if (!other) {
12394 12395 12396
                virReportError(VIR_ERR_INVALID_ARG,
                               _("parent %s for snapshot %s not found"),
                               def->parent, def->name);
12397 12398 12399 12400
                goto cleanup;
            }
            while (other->def->parent) {
                if (STREQ(other->def->parent, def->name)) {
12401 12402 12403
                    virReportError(VIR_ERR_INVALID_ARG,
                                   _("parent %s would create cycle to %s"),
                                   other->def->name, def->name);
12404 12405
                    goto cleanup;
                }
12406
                other = virDomainSnapshotFindByName(vm->snapshots,
12407 12408 12409 12410 12411 12412 12413 12414 12415 12416
                                                    other->def->parent);
                if (!other) {
                    VIR_WARN("snapshots are inconsistent for %s",
                             vm->def->name);
                    break;
                }
            }
        }

        /* Check that any replacement is compatible */
12417 12418 12419 12420 12421 12422 12423 12424 12425
        if ((flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) &&
            def->state != VIR_DOMAIN_DISK_SNAPSHOT) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("disk-only flag for snapshot %s requires "
                             "disk-snapshot state"),
                           def->name);
            goto cleanup;

        }
12426

12427 12428
        if (def->dom &&
            memcmp(def->dom->uuid, domain->uuid, VIR_UUID_BUFLEN)) {
12429 12430 12431
            virReportError(VIR_ERR_INVALID_ARG,
                           _("definition for snapshot %s must use uuid %s"),
                           def->name, uuidstr);
12432 12433
            goto cleanup;
        }
12434

12435
        other = virDomainSnapshotFindByName(vm->snapshots, def->name);
12436 12437 12438 12439 12440
        if (other) {
            if ((other->def->state == VIR_DOMAIN_RUNNING ||
                 other->def->state == VIR_DOMAIN_PAUSED) !=
                (def->state == VIR_DOMAIN_RUNNING ||
                 def->state == VIR_DOMAIN_PAUSED)) {
12441 12442 12443 12444
                virReportError(VIR_ERR_INVALID_ARG,
                               _("cannot change between online and offline "
                                 "snapshot state in snapshot %s"),
                               def->name);
12445 12446
                goto cleanup;
            }
12447

12448 12449
            if ((other->def->state == VIR_DOMAIN_DISK_SNAPSHOT) !=
                (def->state == VIR_DOMAIN_DISK_SNAPSHOT)) {
12450 12451 12452 12453
                virReportError(VIR_ERR_INVALID_ARG,
                               _("cannot change between disk snapshot and "
                                 "system checkpoint in snapshot %s"),
                               def->name);
12454 12455
                goto cleanup;
            }
12456

12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467
            if (other->def->dom) {
                if (def->dom) {
                    if (!virDomainDefCheckABIStability(other->def->dom,
                                                       def->dom))
                        goto cleanup;
                } else {
                    /* Transfer the domain def */
                    def->dom = other->def->dom;
                    other->def->dom = NULL;
                }
            }
12468

12469 12470
            if (def->dom) {
                if (def->state == VIR_DOMAIN_DISK_SNAPSHOT ||
12471
                    virDomainSnapshotDefIsExternal(def)) {
12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486
                    align_location = VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL;
                    align_match = false;
                }

                if (virDomainSnapshotAlignDisks(def, align_location,
                                                align_match) < 0) {
                    /* revert stealing of the snapshot domain definition */
                    if (def->dom && !other->def->dom) {
                        other->def->dom = def->dom;
                        def->dom = NULL;
                    }
                    goto cleanup;
                }
            }

12487 12488 12489 12490
            if (other == vm->current_snapshot) {
                update_current = true;
                vm->current_snapshot = NULL;
            }
12491

12492 12493
            /* Drop and rebuild the parent relationship, but keep all
             * child relations by reusing snap.  */
12494
            virDomainSnapshotDropParent(other);
12495
            virDomainSnapshotDefFree(other->def);
12496 12497
            other->def = def;
            def = NULL;
12498
            snap = other;
12499 12500 12501 12502 12503 12504 12505 12506 12507 12508
        } else {
            if (def->dom) {
                if (def->state == VIR_DOMAIN_DISK_SNAPSHOT ||
                    def->memory == VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL) {
                    align_location = VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL;
                    align_match = false;
                }
                if (virDomainSnapshotAlignDisks(def, align_location,
                                                align_match) < 0)
                    goto cleanup;
12509
            }
12510
        }
12511 12512 12513
    } else {
        /* Easiest way to clone inactive portion of vm->def is via
         * conversion in and back out of xml.  */
12514
        if (!(xml = qemuDomainDefFormatLive(driver, vm->def, true, true)) ||
12515
            !(def->dom = virDomainDefParseString(xml, caps, driver->xmlopt,
12516 12517 12518 12519
                                                 QEMU_EXPECTED_VIRT_TYPES,
                                                 VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

12520
        if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) {
12521 12522
            align_location = VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL;
            align_match = false;
12523 12524 12525 12526
            if (virDomainObjIsActive(vm))
                def->state = VIR_DOMAIN_DISK_SNAPSHOT;
            else
                def->state = VIR_DOMAIN_SHUTOFF;
12527
            def->memory = VIR_DOMAIN_SNAPSHOT_LOCATION_NONE;
12528 12529 12530 12531
        } else if (def->memory == VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL) {
            def->state = virDomainObjGetState(vm, NULL);
            align_location = VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL;
            align_match = false;
12532 12533
        } else {
            def->state = virDomainObjGetState(vm, NULL);
12534 12535 12536
            def->memory = (def->state == VIR_DOMAIN_SHUTOFF ?
                           VIR_DOMAIN_SNAPSHOT_LOCATION_NONE :
                           VIR_DOMAIN_SNAPSHOT_LOCATION_INTERNAL);
12537
        }
E
Eric Blake 已提交
12538 12539 12540 12541
        if (virDomainSnapshotAlignDisks(def, align_location,
                                        align_match) < 0 ||
            qemuDomainSnapshotPrepare(vm, def, &flags) < 0)
            goto cleanup;
12542 12543
    }

12544 12545 12546 12547 12548 12549
    if (!snap) {
        if (!(snap = virDomainSnapshotAssignDef(vm->snapshots, def)))
            goto cleanup;

        def = NULL;
    }
C
Chris Lalancette 已提交
12550

12551 12552
    if (update_current)
        snap->def->current = true;
12553
    if (vm->current_snapshot) {
12554 12555
        if (!(flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) &&
            VIR_STRDUP(snap->def->parent, vm->current_snapshot->def->name) < 0)
12556 12557
                goto cleanup;
        if (update_current) {
12558 12559
            vm->current_snapshot->def->current = false;
            if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
12560
                                                cfg->snapshotDir) < 0)
12561 12562 12563
                goto cleanup;
            vm->current_snapshot = NULL;
        }
12564
    }
12565

C
Chris Lalancette 已提交
12566
    /* actually do the snapshot */
12567 12568
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) {
        /* XXX Should we validate that the redefined snapshot even
12569 12570
         * makes sense, such as checking that qemu-img recognizes the
         * snapshot name in at least one of the domain's disks?  */
12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583
    } else if (virDomainObjIsActive(vm)) {
        if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY ||
            snap->def->memory == VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL) {
            /* external checkpoint or disk snapshot */
            if (qemuDomainSnapshotCreateActiveExternal(domain->conn, driver,
                                                       &vm, snap, flags) < 0)
                goto cleanup;
        } else {
            /* internal checkpoint */
            if (qemuDomainSnapshotCreateActiveInternal(domain->conn, driver,
                                                       &vm, snap, flags) < 0)
                goto cleanup;
        }
E
Eric Blake 已提交
12584
    } else {
12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597
        /* inactive; qemuDomainSnapshotPrepare guaranteed that we
         * aren't mixing internal and external, and altered flags to
         * contain DISK_ONLY if there is an external disk.  */
        if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) {
            bool reuse = !!(flags & VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT);

            if (qemuDomainSnapshotCreateInactiveExternal(driver, vm, snap,
                                                         reuse) < 0)
                goto cleanup;
        } else {
            if (qemuDomainSnapshotCreateInactiveInternal(driver, vm, snap) < 0)
                goto cleanup;
        }
C
Chris Lalancette 已提交
12598 12599
    }

12600
    /* If we fail after this point, there's not a whole lot we can
C
Chris Lalancette 已提交
12601 12602 12603 12604 12605 12606
     * do; we've successfully taken the snapshot, and we are now running
     * on it, so we have to go forward the best we can
     */
    snapshot = virGetDomainSnapshot(domain, snap->def->name);

cleanup:
12607
    if (vm) {
12608
        if (snapshot && !(flags & VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA)) {
12609
            if (qemuDomainSnapshotWriteMetadata(vm, snap,
12610
                                                cfg->snapshotDir) < 0) {
12611 12612 12613 12614 12615 12616 12617 12618
                /* if writing of metadata fails, error out rather than trying
                 * to silently carry on  without completing the snapshot */
                virDomainSnapshotFree(snapshot);
                snapshot = NULL;
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unable to save metadata for snapshot %s"),
                               snap->def->name);
                virDomainSnapshotObjListRemove(vm->snapshots, snap);
12619 12620 12621
            } else {
                if (update_current)
                    vm->current_snapshot = snap;
12622
                other = virDomainSnapshotFindByName(vm->snapshots,
12623 12624 12625 12626 12627
                                                    snap->def->parent);
                snap->parent = other;
                other->nchildren++;
                snap->sibling = other->first_child;
                other->first_child = snap;
12628
            }
12629
        } else if (snap) {
12630
            virDomainSnapshotObjListRemove(vm->snapshots, snap);
12631
        }
12632
        virObjectUnlock(vm);
12633 12634
    }
    virDomainSnapshotDefFree(def);
12635
    VIR_FREE(xml);
12636
    virObjectUnref(caps);
12637
    virObjectUnref(cfg);
C
Chris Lalancette 已提交
12638 12639 12640 12641 12642
    return snapshot;
}

static int qemuDomainSnapshotListNames(virDomainPtr domain, char **names,
                                       int nameslen,
12643
                                       unsigned int flags)
C
Chris Lalancette 已提交
12644 12645 12646 12647
{
    virDomainObjPtr vm = NULL;
    int n = -1;

12648
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
12649
                  VIR_DOMAIN_SNAPSHOT_FILTERS_ALL, -1);
12650

12651
    if (!(vm = qemuDomObjFromDomain(domain)))
C
Chris Lalancette 已提交
12652 12653
        goto cleanup;

12654 12655 12656
    if (virDomainSnapshotListNamesEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

12657
    n = virDomainSnapshotObjListGetNames(vm->snapshots, NULL, names, nameslen,
12658
                                         flags);
C
Chris Lalancette 已提交
12659 12660 12661

cleanup:
    if (vm)
12662
        virObjectUnlock(vm);
C
Chris Lalancette 已提交
12663 12664 12665 12666
    return n;
}

static int qemuDomainSnapshotNum(virDomainPtr domain,
12667
                                 unsigned int flags)
C
Chris Lalancette 已提交
12668 12669 12670 12671
{
    virDomainObjPtr vm = NULL;
    int n = -1;

12672
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
12673
                  VIR_DOMAIN_SNAPSHOT_FILTERS_ALL, -1);
12674

12675
    if (!(vm = qemuDomObjFromDomain(domain)))
C
Chris Lalancette 已提交
12676 12677
        goto cleanup;

12678 12679 12680
    if (virDomainSnapshotNumEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

12681
    n = virDomainSnapshotObjListNum(vm->snapshots, NULL, flags);
C
Chris Lalancette 已提交
12682 12683 12684

cleanup:
    if (vm)
12685
        virObjectUnlock(vm);
C
Chris Lalancette 已提交
12686 12687 12688
    return n;
}

12689 12690 12691 12692 12693 12694 12695 12696 12697 12698
static int
qemuDomainListAllSnapshots(virDomainPtr domain, virDomainSnapshotPtr **snaps,
                           unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int n = -1;

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
                  VIR_DOMAIN_SNAPSHOT_FILTERS_ALL, -1);

12699
    if (!(vm = qemuDomObjFromDomain(domain)))
12700 12701
        goto cleanup;

12702 12703 12704
    if (virDomainListAllSnapshotsEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

12705
    n = virDomainListSnapshots(vm->snapshots, NULL, domain, snaps, flags);
12706 12707 12708

cleanup:
    if (vm)
12709
        virObjectUnlock(vm);
12710 12711 12712
    return n;
}

12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723
static int
qemuDomainSnapshotListChildrenNames(virDomainSnapshotPtr snapshot,
                                    char **names,
                                    int nameslen,
                                    unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    int n = -1;

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
12724
                  VIR_DOMAIN_SNAPSHOT_FILTERS_ALL, -1);
12725

12726
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
12727 12728
        goto cleanup;

12729 12730 12731
    if (virDomainSnapshotListChildrenNamesEnsureACL(snapshot->domain->conn, vm->def) < 0)
        goto cleanup;

12732
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
12733 12734
        goto cleanup;

12735
    n = virDomainSnapshotObjListGetNames(vm->snapshots, snap, names, nameslen,
12736
                                         flags);
12737 12738 12739

cleanup:
    if (vm)
12740
        virObjectUnlock(vm);
12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752
    return n;
}

static int
qemuDomainSnapshotNumChildren(virDomainSnapshotPtr snapshot,
                              unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    int n = -1;

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
12753
                  VIR_DOMAIN_SNAPSHOT_FILTERS_ALL, -1);
12754

12755
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
12756 12757
        goto cleanup;

12758 12759 12760
    if (virDomainSnapshotNumChildrenEnsureACL(snapshot->domain->conn, vm->def) < 0)
        goto cleanup;

12761
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
12762 12763
        goto cleanup;

12764
    n = virDomainSnapshotObjListNum(vm->snapshots, snap, flags);
12765 12766 12767

cleanup:
    if (vm)
12768
        virObjectUnlock(vm);
12769 12770 12771
    return n;
}

12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783
static int
qemuDomainSnapshotListAllChildren(virDomainSnapshotPtr snapshot,
                                  virDomainSnapshotPtr **snaps,
                                  unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    int n = -1;

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
                  VIR_DOMAIN_SNAPSHOT_FILTERS_ALL, -1);

12784
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
12785 12786
        goto cleanup;

12787 12788 12789
    if (virDomainSnapshotListAllChildrenEnsureACL(snapshot->domain->conn, vm->def) < 0)
        goto cleanup;

12790
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
12791 12792
        goto cleanup;

12793
    n = virDomainListSnapshots(vm->snapshots, snap, snapshot->domain, snaps,
12794 12795 12796 12797
                               flags);

cleanup:
    if (vm)
12798
        virObjectUnlock(vm);
12799 12800 12801
    return n;
}

C
Chris Lalancette 已提交
12802 12803
static virDomainSnapshotPtr qemuDomainSnapshotLookupByName(virDomainPtr domain,
                                                           const char *name,
12804
                                                           unsigned int flags)
C
Chris Lalancette 已提交
12805 12806 12807 12808 12809
{
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;

12810 12811
    virCheckFlags(0, NULL);

12812
    if (!(vm = qemuDomObjFromDomain(domain)))
C
Chris Lalancette 已提交
12813 12814
        goto cleanup;

12815 12816 12817
    if (virDomainSnapshotLookupByNameEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

12818
    if (!(snap = qemuSnapObjFromName(vm, name)))
C
Chris Lalancette 已提交
12819 12820 12821 12822 12823 12824
        goto cleanup;

    snapshot = virGetDomainSnapshot(domain, snap->def->name);

cleanup:
    if (vm)
12825
        virObjectUnlock(vm);
C
Chris Lalancette 已提交
12826 12827 12828 12829
    return snapshot;
}

static int qemuDomainHasCurrentSnapshot(virDomainPtr domain,
12830
                                        unsigned int flags)
C
Chris Lalancette 已提交
12831 12832 12833 12834
{
    virDomainObjPtr vm;
    int ret = -1;

12835 12836
    virCheckFlags(0, -1);

12837
    if (!(vm = qemuDomObjFromDomain(domain)))
C
Chris Lalancette 已提交
12838 12839
        goto cleanup;

12840 12841 12842
    if (virDomainHasCurrentSnapshotEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

C
Chris Lalancette 已提交
12843 12844 12845 12846
    ret = (vm->current_snapshot != NULL);

cleanup:
    if (vm)
12847
        virObjectUnlock(vm);
C
Chris Lalancette 已提交
12848 12849 12850
    return ret;
}

12851 12852 12853 12854 12855 12856 12857 12858 12859 12860
static virDomainSnapshotPtr
qemuDomainSnapshotGetParent(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
{
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr parent = NULL;

    virCheckFlags(0, NULL);

12861
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
12862 12863
        goto cleanup;

12864 12865 12866
    if (virDomainSnapshotGetParentEnsureACL(snapshot->domain->conn, vm->def) < 0)
        goto cleanup;

12867
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
12868 12869 12870
        goto cleanup;

    if (!snap->def->parent) {
12871 12872 12873
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snap->def->name);
12874 12875 12876 12877 12878 12879 12880
        goto cleanup;
    }

    parent = virGetDomainSnapshot(snapshot->domain, snap->def->parent);

cleanup:
    if (vm)
12881
        virObjectUnlock(vm);
12882 12883 12884
    return parent;
}

C
Chris Lalancette 已提交
12885
static virDomainSnapshotPtr qemuDomainSnapshotCurrent(virDomainPtr domain,
12886
                                                      unsigned int flags)
C
Chris Lalancette 已提交
12887 12888 12889 12890
{
    virDomainObjPtr vm;
    virDomainSnapshotPtr snapshot = NULL;

12891 12892
    virCheckFlags(0, NULL);

12893
    if (!(vm = qemuDomObjFromDomain(domain)))
C
Chris Lalancette 已提交
12894 12895
        goto cleanup;

12896 12897 12898
    if (virDomainSnapshotCurrentEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

C
Chris Lalancette 已提交
12899
    if (!vm->current_snapshot) {
12900 12901
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT, "%s",
                       _("the domain does not have a current snapshot"));
C
Chris Lalancette 已提交
12902 12903 12904 12905 12906 12907 12908
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, vm->current_snapshot->def->name);

cleanup:
    if (vm)
12909
        virObjectUnlock(vm);
C
Chris Lalancette 已提交
12910 12911 12912
    return snapshot;
}

12913 12914
static char *qemuDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                                          unsigned int flags)
C
Chris Lalancette 已提交
12915 12916 12917 12918 12919 12920
{
    virDomainObjPtr vm = NULL;
    char *xml = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

12921
    virCheckFlags(VIR_DOMAIN_XML_SECURE, NULL);
12922

12923
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
C
Chris Lalancette 已提交
12924 12925
        goto cleanup;

12926 12927 12928
    if (virDomainSnapshotGetXMLDescEnsureACL(snapshot->domain->conn, vm->def) < 0)
        goto cleanup;

12929
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
C
Chris Lalancette 已提交
12930
        goto cleanup;
12931 12932

    virUUIDFormat(snapshot->domain->uuid, uuidstr);
C
Chris Lalancette 已提交
12933

12934
    xml = virDomainSnapshotDefFormat(uuidstr, snap->def, flags, 0);
C
Chris Lalancette 已提交
12935 12936 12937

cleanup:
    if (vm)
12938
        virObjectUnlock(vm);
C
Chris Lalancette 已提交
12939 12940 12941
    return xml;
}

12942 12943 12944 12945 12946 12947 12948 12949 12950 12951
static int
qemuDomainSnapshotIsCurrent(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;
    virDomainSnapshotObjPtr snap = NULL;

    virCheckFlags(0, -1);

12952
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
12953 12954
        goto cleanup;

12955 12956 12957
    if (virDomainSnapshotIsCurrentEnsureACL(snapshot->domain->conn, vm->def) < 0)
        goto cleanup;

12958
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
12959 12960 12961 12962 12963 12964 12965
        goto cleanup;

    ret = (vm->current_snapshot &&
           STREQ(snapshot->name, vm->current_snapshot->def->name));

cleanup:
    if (vm)
12966
        virObjectUnlock(vm);
12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980
    return ret;
}


static int
qemuDomainSnapshotHasMetadata(virDomainSnapshotPtr snapshot,
                              unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;
    virDomainSnapshotObjPtr snap = NULL;

    virCheckFlags(0, -1);

12981
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
12982 12983
        goto cleanup;

12984 12985 12986
    if (virDomainSnapshotHasMetadataEnsureACL(snapshot->domain->conn, vm->def) < 0)
        goto cleanup;

12987
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
12988 12989 12990 12991 12992 12993 12994 12995 12996
        goto cleanup;

    /* XXX Someday, we should recognize internal snapshots in qcow2
     * images that are not tied to a libvirt snapshot; if we ever do
     * that, then we would have a reason to return 0 here.  */
    ret = 1;

cleanup:
    if (vm)
12997
        virObjectUnlock(vm);
12998 12999 13000
    return ret;
}

13001 13002
/* The domain is expected to be locked and inactive. */
static int
13003
qemuDomainSnapshotRevertInactive(virQEMUDriverPtr driver,
E
Eric Blake 已提交
13004
                                 virDomainObjPtr vm,
13005 13006 13007
                                 virDomainSnapshotObjPtr snap)
{
    /* Try all disks, but report failure if we skipped any.  */
E
Eric Blake 已提交
13008
    int ret = qemuDomainSnapshotForEachQcow2(driver, vm, snap, "-a", true);
13009 13010 13011
    return ret > 0 ? -1 : ret;
}

C
Chris Lalancette 已提交
13012
static int qemuDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
13013
                                      unsigned int flags)
C
Chris Lalancette 已提交
13014
{
13015
    virQEMUDriverPtr driver = snapshot->domain->conn->privateData;
C
Chris Lalancette 已提交
13016 13017 13018 13019
    virDomainObjPtr vm = NULL;
    int ret = -1;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainEventPtr event = NULL;
13020
    virDomainEventPtr event2 = NULL;
13021
    int detail;
C
Chris Lalancette 已提交
13022 13023
    qemuDomainObjPrivatePtr priv;
    int rc;
13024
    virDomainDefPtr config = NULL;
13025
    virQEMUDriverConfigPtr cfg = NULL;
13026
    virCapsPtr caps = NULL;
C
Chris Lalancette 已提交
13027

13028
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING |
13029 13030
                  VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED |
                  VIR_DOMAIN_SNAPSHOT_REVERT_FORCE, -1);
13031

13032 13033 13034 13035 13036 13037 13038 13039 13040 13041
    /* We have the following transitions, which create the following events:
     * 1. inactive -> inactive: none
     * 2. inactive -> running:  EVENT_STARTED
     * 3. inactive -> paused:   EVENT_STARTED, EVENT_PAUSED
     * 4. running  -> inactive: EVENT_STOPPED
     * 5. running  -> running:  none
     * 6. running  -> paused:   EVENT_PAUSED
     * 7. paused   -> inactive: EVENT_STOPPED
     * 8. paused   -> running:  EVENT_RESUMED
     * 9. paused   -> paused:   none
13042 13043
     * Also, several transitions occur even if we fail partway through,
     * and use of FORCE can cause multiple transitions.
13044 13045
     */

13046 13047
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
        return -1;
13048 13049 13050

    cfg = virQEMUDriverGetConfig(driver);

13051 13052 13053
    if (virDomainRevertToSnapshotEnsureACL(snapshot->domain->conn, vm->def) < 0)
        goto cleanup;

13054 13055 13056
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

E
Eric Blake 已提交
13057 13058 13059 13060 13061
    if (virDomainHasDiskMirror(vm)) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE, "%s",
                       _("domain has active block copy job"));
        goto cleanup;
    }
C
Chris Lalancette 已提交
13062

13063
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
C
Chris Lalancette 已提交
13064 13065
        goto cleanup;

13066 13067 13068 13069 13070
    if (!vm->persistent &&
        snap->def->state != VIR_DOMAIN_RUNNING &&
        snap->def->state != VIR_DOMAIN_PAUSED &&
        (flags & (VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING |
                  VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED)) == 0) {
13071 13072 13073
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("transient domain needs to request run or pause "
                         "to revert to inactive snapshot"));
13074 13075
        goto cleanup;
    }
13076
    if (snap->def->state == VIR_DOMAIN_DISK_SNAPSHOT) {
13077 13078 13079
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("revert to external disk snapshot not supported "
                         "yet"));
13080 13081
        goto cleanup;
    }
13082 13083
    if (!(flags & VIR_DOMAIN_SNAPSHOT_REVERT_FORCE)) {
        if (!snap->def->dom) {
13084 13085 13086
            virReportError(VIR_ERR_SNAPSHOT_REVERT_RISKY,
                           _("snapshot '%s' lacks domain '%s' rollback info"),
                           snap->def->name, vm->def->name);
13087 13088 13089 13090 13091 13092 13093
            goto cleanup;
        }
        if (virDomainObjIsActive(vm) &&
            !(snap->def->state == VIR_DOMAIN_RUNNING
              || snap->def->state == VIR_DOMAIN_PAUSED) &&
            (flags & (VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING |
                      VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED))) {
13094 13095
            virReportError(VIR_ERR_SNAPSHOT_REVERT_RISKY, "%s",
                           _("must respawn qemu to start inactive snapshot"));
13096 13097 13098 13099
            goto cleanup;
        }
    }

13100

13101 13102 13103
    if (vm->current_snapshot) {
        vm->current_snapshot->def->current = false;
        if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
13104
                                            cfg->snapshotDir) < 0)
13105 13106 13107 13108 13109 13110
            goto cleanup;
        vm->current_snapshot = NULL;
        /* XXX Should we restore vm->current_snapshot after this point
         * in the failure cases where we know there was no change?  */
    }

13111
    /* Prepare to copy the snapshot inactive xml as the config of this
13112
     * domain.
13113 13114 13115
     *
     * XXX Should domain snapshots track live xml rather
     * than inactive xml?  */
13116
    snap->def->current = true;
13117
    if (snap->def->dom) {
13118
        config = virDomainDefCopy(snap->def->dom, caps, driver->xmlopt, true);
13119 13120 13121
        if (!config)
            goto cleanup;
    }
C
Chris Lalancette 已提交
13122

13123
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
C
Chris Lalancette 已提交
13124 13125 13126 13127
        goto cleanup;

    if (snap->def->state == VIR_DOMAIN_RUNNING
        || snap->def->state == VIR_DOMAIN_PAUSED) {
13128 13129 13130 13131 13132 13133 13134 13135 13136
        /* Transitions 2, 3, 5, 6, 8, 9 */
        bool was_running = false;
        bool was_stopped = false;

        /* When using the loadvm monitor command, qemu does not know
         * whether to pause or run the reverted domain, and just stays
         * in the same state as before the monitor command, whether
         * that is paused or running.  We always pause before loadvm,
         * to have finer control.  */
C
Chris Lalancette 已提交
13137
        if (virDomainObjIsActive(vm)) {
13138
            /* Transitions 5, 6, 8, 9 */
13139 13140
            /* Check for ABI compatibility.  */
            if (config && !virDomainDefCheckABIStability(vm->def, config)) {
13141 13142 13143 13144 13145
                virErrorPtr err = virGetLastError();

                if (!(flags & VIR_DOMAIN_SNAPSHOT_REVERT_FORCE)) {
                    /* Re-spawn error using correct category. */
                    if (err->code == VIR_ERR_CONFIG_UNSUPPORTED)
13146 13147
                        virReportError(VIR_ERR_SNAPSHOT_REVERT_RISKY, "%s",
                                       err->str2);
13148 13149 13150
                    goto endjob;
                }
                virResetError(err);
13151 13152
                qemuProcessStop(driver, vm,
                                VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT, 0);
13153 13154 13155 13156 13157 13158 13159 13160
                virDomainAuditStop(vm, "from-snapshot");
                detail = VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT;
                event = virDomainEventNewFromObj(vm,
                                                 VIR_DOMAIN_EVENT_STOPPED,
                                                 detail);
                if (event)
                    qemuDomainEventQueue(driver, event);
                goto load;
13161 13162
            }

C
Chris Lalancette 已提交
13163
            priv = vm->privateData;
13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178
            if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
                /* Transitions 5, 6 */
                was_running = true;
                if (qemuProcessStopCPUs(driver, vm,
                                        VIR_DOMAIN_PAUSED_FROM_SNAPSHOT,
                                        QEMU_ASYNC_JOB_NONE) < 0)
                    goto endjob;
                /* Create an event now in case the restore fails, so
                 * that user will be alerted that they are now paused.
                 * If restore later succeeds, we might replace this. */
                detail = VIR_DOMAIN_EVENT_SUSPENDED_FROM_SNAPSHOT;
                event = virDomainEventNewFromObj(vm,
                                                 VIR_DOMAIN_EVENT_SUSPENDED,
                                                 detail);
                if (!virDomainObjIsActive(vm)) {
13179 13180
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("guest unexpectedly quit"));
13181 13182 13183
                    goto endjob;
                }
            }
13184
            qemuDomainObjEnterMonitor(driver, vm);
C
Chris Lalancette 已提交
13185
            rc = qemuMonitorLoadSnapshot(priv->mon, snap->def->name);
13186
            qemuDomainObjExitMonitor(driver, vm);
13187 13188 13189
            if (rc < 0) {
                /* XXX resume domain if it was running before the
                 * failed loadvm attempt? */
13190
                goto endjob;
13191
            }
13192
            if (config)
13193
                virDomainObjAssignDef(vm, config, false, NULL);
E
Eric Blake 已提交
13194
        } else {
13195
            /* Transitions 2, 3 */
13196
        load:
13197
            was_stopped = true;
13198
            if (config)
13199
                virDomainObjAssignDef(vm, config, false, NULL);
13200

13201 13202 13203 13204
            rc = qemuProcessStart(snapshot->domain->conn,
                                  driver, vm, NULL, -1, NULL, snap,
                                  VIR_NETDEV_VPORT_PROFILE_OP_CREATE,
                                  VIR_QEMU_PROCESS_START_PAUSED);
13205
            virDomainAuditStart(vm, "from-snapshot", rc >= 0);
13206 13207 13208 13209
            detail = VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT;
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STARTED,
                                             detail);
C
Chris Lalancette 已提交
13210
            if (rc < 0)
13211
                goto endjob;
C
Chris Lalancette 已提交
13212 13213
        }

13214
        /* Touch up domain state.  */
13215 13216 13217
        if (!(flags & VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING) &&
            (snap->def->state == VIR_DOMAIN_PAUSED ||
             (flags & VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED))) {
13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230
            /* Transitions 3, 6, 9 */
            virDomainObjSetState(vm, VIR_DOMAIN_PAUSED,
                                 VIR_DOMAIN_PAUSED_FROM_SNAPSHOT);
            if (was_stopped) {
                /* Transition 3, use event as-is and add event2 */
                detail = VIR_DOMAIN_EVENT_SUSPENDED_FROM_SNAPSHOT;
                event2 = virDomainEventNewFromObj(vm,
                                                  VIR_DOMAIN_EVENT_SUSPENDED,
                                                  detail);
            } /* else transition 6 and 9 use event as-is */
        } else {
            /* Transitions 2, 5, 8 */
            if (!virDomainObjIsActive(vm)) {
13231 13232
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("guest unexpectedly quit"));
13233 13234 13235 13236 13237
                goto endjob;
            }
            rc = qemuProcessStartCPUs(driver, vm, snapshot->domain->conn,
                                      VIR_DOMAIN_RUNNING_FROM_SNAPSHOT,
                                      QEMU_ASYNC_JOB_NONE);
H
Hu Tao 已提交
13238
            if (rc < 0)
13239
                goto endjob;
13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254
            virDomainEventFree(event);
            event = NULL;
            if (was_stopped) {
                /* Transition 2 */
                detail = VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT;
                event = virDomainEventNewFromObj(vm,
                                                 VIR_DOMAIN_EVENT_STARTED,
                                                 detail);
            } else if (was_running) {
                /* Transition 8 */
                detail = VIR_DOMAIN_EVENT_RESUMED;
                event = virDomainEventNewFromObj(vm,
                                                 VIR_DOMAIN_EVENT_RESUMED,
                                                 detail);
            }
C
Chris Lalancette 已提交
13255
        }
E
Eric Blake 已提交
13256
    } else {
13257
        /* Transitions 1, 4, 7 */
13258 13259 13260
        /* Newer qemu -loadvm refuses to revert to the state of a snapshot
         * created by qemu-img snapshot -c.  If the domain is running, we
         * must take it offline; then do the revert using qemu-img.
C
Chris Lalancette 已提交
13261 13262 13263
         */

        if (virDomainObjIsActive(vm)) {
13264
            /* Transitions 4, 7 */
13265
            qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT, 0);
13266
            virDomainAuditStop(vm, "from-snapshot");
13267
            detail = VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT;
C
Chris Lalancette 已提交
13268 13269
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STOPPED,
13270
                                             detail);
13271 13272
        }

E
Eric Blake 已提交
13273
        if (qemuDomainSnapshotRevertInactive(driver, vm, snap) < 0) {
13274
            if (!vm->persistent) {
13275
                if (qemuDomainObjEndJob(driver, vm) > 0)
13276
                    qemuDomainRemoveInactive(driver, vm);
13277
                vm = NULL;
13278
                goto cleanup;
13279
            }
13280
            goto endjob;
C
Chris Lalancette 已提交
13281
        }
13282
        if (config)
13283
            virDomainObjAssignDef(vm, config, false, NULL);
13284

13285 13286 13287 13288
        if (flags & (VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING |
                     VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED)) {
            /* Flush first event, now do transition 2 or 3 */
            bool paused = (flags & VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED) != 0;
13289 13290 13291
            unsigned int start_flags = 0;

            start_flags |= paused ? VIR_QEMU_PROCESS_START_PAUSED : 0;
13292 13293 13294

            if (event)
                qemuDomainEventQueue(driver, event);
13295 13296 13297 13298
            rc = qemuProcessStart(snapshot->domain->conn,
                                  driver, vm, NULL, -1, NULL, NULL,
                                  VIR_NETDEV_VPORT_PROFILE_OP_CREATE,
                                  start_flags);
13299 13300 13301 13302
            virDomainAuditStart(vm, "from-snapshot", rc >= 0);
            if (rc < 0) {
                if (!vm->persistent) {
                    if (qemuDomainObjEndJob(driver, vm) > 0)
13303
                        qemuDomainRemoveInactive(driver, vm);
13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319
                    vm = NULL;
                    goto cleanup;
                }
                goto endjob;
            }
            detail = VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT;
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STARTED,
                                             detail);
            if (paused) {
                detail = VIR_DOMAIN_EVENT_SUSPENDED_FROM_SNAPSHOT;
                event2 = virDomainEventNewFromObj(vm,
                                                  VIR_DOMAIN_EVENT_SUSPENDED,
                                                  detail);
            }
        }
C
Chris Lalancette 已提交
13320 13321 13322 13323
    }

    ret = 0;

13324
endjob:
13325
    if (vm && qemuDomainObjEndJob(driver, vm) == 0)
C
Chris Lalancette 已提交
13326 13327
        vm = NULL;

13328
cleanup:
13329 13330
    if (vm && ret == 0) {
        if (qemuDomainSnapshotWriteMetadata(vm, snap,
13331
                                            cfg->snapshotDir) < 0)
13332 13333 13334 13335 13336 13337
            ret = -1;
        else
            vm->current_snapshot = snap;
    } else if (snap) {
        snap->def->current = false;
    }
13338
    if (event) {
C
Chris Lalancette 已提交
13339
        qemuDomainEventQueue(driver, event);
13340 13341 13342
        if (event2)
            qemuDomainEventQueue(driver, event2);
    }
C
Chris Lalancette 已提交
13343
    if (vm)
13344
        virObjectUnlock(vm);
13345
    virObjectUnref(caps);
13346
    virObjectUnref(cfg);
C
Chris Lalancette 已提交
13347 13348 13349 13350

    return ret;
}

13351 13352 13353 13354

typedef struct _virQEMUSnapReparent virQEMUSnapReparent;
typedef virQEMUSnapReparent *virQEMUSnapReparentPtr;
struct _virQEMUSnapReparent {
13355
    virQEMUDriverConfigPtr cfg;
13356
    virDomainSnapshotObjPtr parent;
13357 13358
    virDomainObjPtr vm;
    int err;
13359
    virDomainSnapshotObjPtr last;
13360 13361 13362 13363
};

static void
qemuDomainSnapshotReparentChildren(void *payload,
13364
                                   const void *name ATTRIBUTE_UNUSED,
13365 13366 13367
                                   void *data)
{
    virDomainSnapshotObjPtr snap = payload;
13368
    virQEMUSnapReparentPtr rep = data;
13369 13370 13371 13372 13373

    if (rep->err < 0) {
        return;
    }

13374
    VIR_FREE(snap->def->parent);
13375
    snap->parent = rep->parent;
13376

13377 13378 13379 13380
    if (rep->parent->def &&
        VIR_STRDUP(snap->def->parent, rep->parent->def->name) < 0) {
        rep->err = -1;
        return;
13381
    }
13382

13383 13384 13385
    if (!snap->sibling)
        rep->last = snap;

13386
    rep->err = qemuDomainSnapshotWriteMetadata(rep->vm, snap,
13387
                                               rep->cfg->snapshotDir);
13388 13389
}

13390

C
Chris Lalancette 已提交
13391 13392 13393
static int qemuDomainSnapshotDelete(virDomainSnapshotPtr snapshot,
                                    unsigned int flags)
{
13394
    virQEMUDriverPtr driver = snapshot->domain->conn->privateData;
C
Chris Lalancette 已提交
13395 13396 13397
    virDomainObjPtr vm = NULL;
    int ret = -1;
    virDomainSnapshotObjPtr snap = NULL;
13398 13399
    virQEMUSnapRemove rem;
    virQEMUSnapReparent rep;
13400
    bool metadata_only = !!(flags & VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY);
13401
    int external = 0;
13402
    virQEMUDriverConfigPtr cfg = NULL;
C
Chris Lalancette 已提交
13403

13404
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
13405 13406
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY |
                  VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY, -1);
13407

13408 13409
    if (!(vm = qemuDomObjFromSnapshot(snapshot)))
        return -1;
C
Chris Lalancette 已提交
13410

13411
    cfg = virQEMUDriverGetConfig(driver);
13412 13413 13414 13415

    if (virDomainSnapshotDeleteEnsureACL(snapshot->domain->conn, vm->def) < 0)
        goto cleanup;

13416
    if (!(snap = qemuSnapObjFromSnapshot(vm, snapshot)))
C
Chris Lalancette 已提交
13417 13418
        goto cleanup;

13419
    if (!metadata_only) {
13420
        if (!(flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY) &&
13421
            virDomainSnapshotIsExternal(snap))
13422 13423
            external++;
        if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN)
E
Eric Blake 已提交
13424
            virDomainSnapshotForEachDescendant(snap,
13425 13426 13427
                                               qemuDomainSnapshotCountExternal,
                                               &external);
        if (external) {
13428 13429 13430
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("deletion of %d external disk snapshots not "
                             "supported yet"), external);
13431 13432 13433 13434
            goto cleanup;
        }
    }

13435
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
13436 13437
        goto cleanup;

13438 13439
    if (flags & (VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                 VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY)) {
C
Chris Lalancette 已提交
13440 13441
        rem.driver = driver;
        rem.vm = vm;
13442
        rem.metadata_only = metadata_only;
C
Chris Lalancette 已提交
13443
        rem.err = 0;
13444
        rem.current = false;
E
Eric Blake 已提交
13445
        virDomainSnapshotForEachDescendant(snap,
E
Eric Blake 已提交
13446
                                           qemuDomainSnapshotDiscardAll,
13447
                                           &rem);
C
Chris Lalancette 已提交
13448
        if (rem.err < 0)
13449
            goto endjob;
13450 13451 13452 13453
        if (rem.current) {
            if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY) {
                snap->def->current = true;
                if (qemuDomainSnapshotWriteMetadata(vm, snap,
13454
                                                    cfg->snapshotDir) < 0) {
13455 13456 13457
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("failed to set snapshot '%s' as current"),
                                   snap->def->name);
13458 13459 13460 13461
                    snap->def->current = false;
                    goto endjob;
                }
            }
13462
            vm->current_snapshot = snap;
13463
        }
13464
    } else if (snap->nchildren) {
13465
        rep.cfg = cfg;
13466
        rep.parent = snap->parent;
13467 13468
        rep.vm = vm;
        rep.err = 0;
13469
        rep.last = NULL;
E
Eric Blake 已提交
13470
        virDomainSnapshotForEachChild(snap,
13471 13472
                                      qemuDomainSnapshotReparentChildren,
                                      &rep);
13473 13474
        if (rep.err < 0)
            goto endjob;
13475
        /* Can't modify siblings during ForEachChild, so do it now.  */
13476 13477 13478
        snap->parent->nchildren += snap->nchildren;
        rep.last->sibling = snap->parent->first_child;
        snap->parent->first_child = snap->first_child;
C
Chris Lalancette 已提交
13479 13480
    }

13481 13482 13483
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY) {
        snap->nchildren = 0;
        snap->first_child = NULL;
13484
        ret = 0;
13485
    } else {
13486
        virDomainSnapshotDropParent(snap);
13487
        ret = qemuDomainSnapshotDiscard(driver, vm, snap, true, metadata_only);
13488
    }
C
Chris Lalancette 已提交
13489

13490
endjob:
13491
    if (qemuDomainObjEndJob(driver, vm) == 0)
13492 13493
        vm = NULL;

C
Chris Lalancette 已提交
13494 13495
cleanup:
    if (vm)
13496
        virObjectUnlock(vm);
13497
    virObjectUnref(cfg);
C
Chris Lalancette 已提交
13498 13499
    return ret;
}
13500

13501 13502
static int qemuDomainQemuMonitorCommand(virDomainPtr domain, const char *cmd,
                                        char **result, unsigned int flags)
13503
{
13504
    virQEMUDriverPtr driver = domain->conn->privateData;
13505 13506 13507
    virDomainObjPtr vm = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;
13508
    bool hmp;
13509

13510
    virCheckFlags(VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP, -1);
13511

13512
    if (!(vm = qemuDomObjFromDomain(domain)))
13513 13514
        goto cleanup;

13515 13516 13517
    if (virDomainQemuMonitorCommandEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

13518
    if (!virDomainObjIsActive(vm)) {
13519 13520
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
13521
        goto cleanup;
13522
    }
13523

13524
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
13525 13526 13527
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
13528 13529
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain is not running"));
13530 13531 13532
        goto endjob;
    }

13533 13534
    priv = vm->privateData;

13535
    qemuDomainObjTaint(driver, vm, VIR_DOMAIN_TAINT_CUSTOM_MONITOR, -1);
13536

13537 13538
    hmp = !!(flags & VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP);

13539
    qemuDomainObjEnterMonitor(driver, vm);
13540
    ret = qemuMonitorArbitraryCommand(priv->mon, cmd, result, hmp);
13541
    qemuDomainObjExitMonitor(driver, vm);
13542 13543

endjob:
13544
    if (qemuDomainObjEndJob(driver, vm) == 0) {
13545 13546 13547 13548 13549
        vm = NULL;
    }

cleanup:
    if (vm)
13550
        virObjectUnlock(vm);
13551 13552 13553
    return ret;
}

13554

13555 13556 13557
static virDomainPtr qemuDomainQemuAttach(virConnectPtr conn,
                                         unsigned int pid_value,
                                         unsigned int flags)
13558
{
13559
    virQEMUDriverPtr driver = conn->privateData;
13560 13561 13562 13563 13564
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    virDomainPtr dom = NULL;
    virDomainChrSourceDefPtr monConfig = NULL;
    bool monJSON = false;
13565
    pid_t pid = pid_value;
13566
    char *pidfile = NULL;
13567
    virQEMUCapsPtr qemuCaps = NULL;
13568
    virCapsPtr caps = NULL;
13569 13570 13571

    virCheckFlags(0, NULL);

13572 13573 13574
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

13575
    if (!(def = qemuParseCommandLinePid(caps, driver->xmlopt, pid,
13576 13577 13578
                                        &pidfile, &monConfig, &monJSON)))
        goto cleanup;

13579 13580 13581
    if (virDomainQemuAttachEnsureACL(conn, def) < 0)
        goto cleanup;

13582
    if (!monConfig) {
13583 13584
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("No monitor connection for pid %u"), pid_value);
13585 13586 13587
        goto cleanup;
    }
    if (monConfig->type != VIR_DOMAIN_CHR_TYPE_UNIX) {
13588 13589 13590 13591 13592
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Cannot connect to monitor connection of type '%s' "
                         "for pid %u"),
                       virDomainChrTypeToString(monConfig->type),
                       pid_value);
13593 13594 13595 13596
        goto cleanup;
    }

    if (!(def->name) &&
13597
        virAsprintf(&def->name, "attach-pid-%u", pid_value) < 0) {
13598 13599 13600 13601
        virReportOOMError();
        goto cleanup;
    }

13602
    if (!(qemuCaps = virQEMUCapsCacheLookup(driver->qemuCapsCache, def->emulator)))
13603 13604
        goto cleanup;

13605
    if (qemuCanonicalizeMachine(def, qemuCaps) < 0)
13606 13607
        goto cleanup;

13608
    if (qemuDomainAssignAddresses(def, qemuCaps, NULL) < 0)
13609 13610
        goto cleanup;

13611
    if (!(vm = virDomainObjListAdd(driver->domains, def,
13612
                                   driver->xmlopt,
13613 13614 13615
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
13616 13617 13618 13619
        goto cleanup;

    def = NULL;

13620
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634
        goto cleanup;

    if (qemuProcessAttach(conn, driver, vm, pid,
                          pidfile, monConfig, monJSON) < 0) {
        monConfig = NULL;
        goto endjob;
    }

    monConfig = NULL;

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

endjob:
13635
    if (qemuDomainObjEndJob(driver, vm) == 0) {
13636 13637 13638 13639 13640 13641
        vm = NULL;
        goto cleanup;
    }

cleanup:
    virDomainDefFree(def);
13642
    virObjectUnref(qemuCaps);
13643 13644
    virDomainChrSourceDefFree(monConfig);
    if (vm)
13645
        virObjectUnlock(vm);
13646
    VIR_FREE(pidfile);
13647
    virObjectUnref(caps);
13648 13649 13650 13651
    return dom;
}


13652 13653
static int
qemuDomainOpenConsole(virDomainPtr dom,
13654
                      const char *dev_name,
13655 13656 13657 13658 13659 13660 13661
                      virStreamPtr st,
                      unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;
    int i;
    virDomainChrDefPtr chr = NULL;
13662
    qemuDomainObjPrivatePtr priv;
13663

13664 13665
    virCheckFlags(VIR_DOMAIN_CONSOLE_SAFE |
                  VIR_DOMAIN_CONSOLE_FORCE, -1);
13666

13667
    if (!(vm = qemuDomObjFromDomain(dom)))
13668 13669
        goto cleanup;

13670 13671 13672
    if (virDomainOpenConsoleEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

13673
    if (!virDomainObjIsActive(vm)) {
13674 13675
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
13676 13677 13678
        goto cleanup;
    }

13679 13680
    priv = vm->privateData;

13681
    if (dev_name) {
13682
        for (i = 0; !chr && i < vm->def->nconsoles; i++) {
13683 13684 13685 13686
            if (vm->def->consoles[i]->info.alias &&
                STREQ(dev_name, vm->def->consoles[i]->info.alias))
                chr = vm->def->consoles[i];
        }
13687
        for (i = 0; !chr && i < vm->def->nserials; i++) {
13688
            if (STREQ(dev_name, vm->def->serials[i]->info.alias))
13689 13690
                chr = vm->def->serials[i];
        }
13691
        for (i = 0; !chr && i < vm->def->nparallels; i++) {
13692
            if (STREQ(dev_name, vm->def->parallels[i]->info.alias))
13693 13694 13695
                chr = vm->def->parallels[i];
        }
    } else {
13696 13697
        if (vm->def->nconsoles)
            chr = vm->def->consoles[0];
13698 13699 13700 13701 13702
        else if (vm->def->nserials)
            chr = vm->def->serials[0];
    }

    if (!chr) {
13703 13704 13705
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot find character device %s"),
                       NULLSTR(dev_name));
13706 13707 13708
        goto cleanup;
    }

13709
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
13710 13711 13712
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("character device %s is not using a PTY"),
                       NULLSTR(dev_name));
13713 13714 13715
        goto cleanup;
    }

13716
    /* handle mutually exclusive access to console devices */
13717
    ret = virChrdevOpen(priv->devs,
13718
                        &chr->source,
13719 13720
                        st,
                        (flags & VIR_DOMAIN_CONSOLE_FORCE) != 0);
13721 13722

    if (ret == 1) {
13723 13724
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Active console session exists for this domain"));
13725 13726
        ret = -1;
    }
13727 13728 13729

cleanup:
    if (vm)
13730
        virObjectUnlock(vm);
13731 13732 13733
    return ret;
}

13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750
static int
qemuDomainOpenChannel(virDomainPtr dom,
                      const char *name,
                      virStreamPtr st,
                      unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;
    int i;
    virDomainChrDefPtr chr = NULL;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(VIR_DOMAIN_CHANNEL_FORCE, -1);

    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;

13751 13752 13753
    if (virDomainOpenChannelEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

13754 13755 13756 13757 13758 13759 13760 13761 13762
    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
        goto cleanup;
    }

    priv = vm->privateData;

    if (name) {
13763
        for (i = 0; !chr && i < vm->def->nchannels; i++) {
13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804
            if (STREQ(name, vm->def->channels[i]->info.alias))
                chr = vm->def->channels[i];

            if (vm->def->channels[i]->targetType == \
                VIR_DOMAIN_CHR_CHANNEL_TARGET_TYPE_VIRTIO &&
                STREQ(name, vm->def->channels[i]->target.name))
                chr = vm->def->channels[i];
        }
    } else {
        if (vm->def->nchannels)
            chr = vm->def->channels[0];
    }

    if (!chr) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot find channel %s"),
                       NULLSTR(name));
        goto cleanup;
    }

    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_UNIX) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("channel %s is not using a UNIX socket"),
                       NULLSTR(name));
        goto cleanup;
    }

    /* handle mutually exclusive access to channel devices */
    ret = virChrdevOpen(priv->devs,
                        &chr->source,
                        st,
                        (flags & VIR_DOMAIN_CHANNEL_FORCE) != 0);

    if (ret == 1) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Active channel stream exists for this domain"));
        ret = -1;
    }

cleanup:
    if (vm)
13805
        virObjectUnlock(vm);
13806 13807 13808
    return ret;
}

E
Eric Blake 已提交
13809
static char *
E
Eric Blake 已提交
13810
qemuDiskPathToAlias(virDomainObjPtr vm, const char *path, int *idx)
E
Eric Blake 已提交
13811
{
13812 13813
    int i;
    char *ret = NULL;
13814
    virDomainDiskDefPtr disk;
13815

13816 13817 13818
    i = virDomainDiskIndexByName(vm->def, path, true);
    if (i < 0)
        goto cleanup;
13819

13820
    disk = vm->def->disks[i];
E
Eric Blake 已提交
13821 13822
    if (idx)
        *idx = i;
13823

13824 13825 13826 13827
    if (disk->src) {
        if (virAsprintf(&ret, "drive-%s", disk->info.alias) < 0) {
            virReportOOMError();
            return NULL;
13828 13829 13830
        }
    }

13831
cleanup:
13832
    if (!ret) {
13833 13834
        virReportError(VIR_ERR_INVALID_ARG,
                       "%s", _("No device found for specified path"));
13835 13836 13837 13838
    }
    return ret;
}

13839 13840 13841 13842
/* Called while holding the VM job lock, to implement a block job
 * abort with pivot; this updates the VM definition as appropriate, on
 * either success or failure.  */
static int
E
Eric Blake 已提交
13843
qemuDomainBlockPivot(virConnectPtr conn,
13844
                     virQEMUDriverPtr driver, virDomainObjPtr vm,
13845 13846 13847 13848 13849 13850
                     const char *device, virDomainDiskDefPtr disk)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virDomainBlockJobInfo info;
    const char *format = virStorageFileFormatTypeToString(disk->mirrorFormat);
E
Eric Blake 已提交
13851
    bool resume = false;
13852 13853 13854
    char *oldsrc = NULL;
    int oldformat;
    virStorageFileMetadataPtr oldchain = NULL;
13855
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
13856 13857 13858

    /* Probe the status, if needed.  */
    if (!disk->mirroring) {
13859
        qemuDomainObjEnterMonitor(driver, vm);
13860 13861
        ret = qemuMonitorBlockJob(priv->mon, device, NULL, 0, &info,
                                  BLOCK_JOB_INFO, true);
13862
        qemuDomainObjExitMonitor(driver, vm);
13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881
        if (ret < 0)
            goto cleanup;
        if (!virDomainObjIsActive(vm)) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("domain is not running"));
            goto cleanup;
        }
        if (ret == 1 && info.cur == info.end &&
            info.type == VIR_DOMAIN_BLOCK_JOB_TYPE_COPY)
            disk->mirroring = true;
    }

    if (!disk->mirroring) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE,
                       _("disk '%s' not ready for pivot yet"),
                       disk->dst);
        goto cleanup;
    }

E
Eric Blake 已提交
13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904
    /* If we are using the older 'drive-reopen', we want to make sure
     * that management apps can tell whether the command succeeded,
     * even if libvirtd is restarted at the wrong time.  To accomplish
     * that, we pause the guest before drive-reopen, and resume it
     * only when we know the outcome; if libvirtd restarts, then
     * management will see the guest still paused, and know that no
     * guest I/O has caused the source and mirror to diverge.  XXX
     * With the newer 'block-job-complete', we need to use a
     * persistent bitmap to make things safe; so for now, we just
     * blindly pause the guest.  */
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
        if (qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_SAVE,
                                QEMU_ASYNC_JOB_NONE) < 0)
            goto cleanup;

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

13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923
    /* We previously labeled only the top-level image; but if the
     * image includes a relative backing file, the pivot may result in
     * qemu needing to open the entire backing chain, so we need to
     * label the entire chain.  This action is safe even if the
     * backing chain has already been labeled; but only necessary when
     * we know for sure that there is a backing chain.  */
    oldsrc = disk->src;
    oldformat = disk->format;
    oldchain = disk->backingChain;
    disk->src = disk->mirror;
    disk->format = disk->mirrorFormat;
    disk->backingChain = NULL;
    if (qemuDomainDetermineDiskChain(driver, disk, false) < 0) {
        disk->src = oldsrc;
        disk->format = oldformat;
        disk->backingChain = oldchain;
        goto cleanup;
    }
    if (disk->mirrorFormat && disk->mirrorFormat != VIR_STORAGE_FILE_RAW &&
13924
        (virDomainLockDiskAttach(driver->lockManager, cfg->uri,
13925
                                 vm, disk) < 0 ||
13926
         qemuSetupDiskCgroup(vm, disk) < 0 ||
13927 13928 13929 13930 13931 13932 13933 13934
         virSecurityManagerSetImageLabel(driver->securityManager, vm->def,
                                         disk) < 0)) {
        disk->src = oldsrc;
        disk->format = oldformat;
        disk->backingChain = oldchain;
        goto cleanup;
    }

13935
    /* Attempt the pivot.  */
13936
    qemuDomainObjEnterMonitor(driver, vm);
13937
    ret = qemuMonitorDrivePivot(priv->mon, device, disk->mirror, format);
13938
    qemuDomainObjExitMonitor(driver, vm);
13939 13940 13941 13942 13943 13944 13945 13946 13947

    if (ret == 0) {
        /* XXX We want to revoke security labels and disk lease, as
         * well as audit that revocation, before dropping the original
         * source.  But it gets tricky if both source and mirror share
         * common backing files (we want to only revoke the non-shared
         * portion of the chain, and is made more difficult by the
         * fact that we aren't tracking the full chain ourselves; so
         * for now, we leak the access to the original.  */
13948 13949
        VIR_FREE(oldsrc);
        virStorageFileFreeMetadata(oldchain);
13950 13951 13952 13953 13954 13955 13956 13957 13958 13959
        disk->mirror = NULL;
    } else {
        /* On failure, qemu abandons the mirror, and reverts back to
         * the source disk (RHEL 6.3 has a bug where the revert could
         * cause catastrophic failure in qemu, but we don't need to
         * worry about it here as it is not an upstream qemu problem.  */
        /* XXX should we be parsing the exact qemu error, or calling
         * 'query-block', to see what state we really got left in
         * before killing the mirroring job?  And just as on the
         * success case, there's security labeling to worry about.  */
13960 13961 13962 13963
        disk->src = oldsrc;
        disk->format = oldformat;
        virStorageFileFreeMetadata(disk->backingChain);
        disk->backingChain = oldchain;
13964 13965
        VIR_FREE(disk->mirror);
    }
13966 13967
    disk->mirrorFormat = VIR_STORAGE_FILE_NONE;
    disk->mirroring = false;
13968 13969

cleanup:
E
Eric Blake 已提交
13970 13971 13972
    if (resume && virDomainObjIsActive(vm) &&
        qemuProcessStartCPUs(driver, vm, conn,
                             VIR_DOMAIN_RUNNING_UNPAUSED,
13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983
                             QEMU_ASYNC_JOB_NONE) < 0) {
        virDomainEventPtr event = NULL;
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_API_ERROR);
        if (event)
            qemuDomainEventQueue(driver, event);
        if (virGetLastError() == NULL) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("resuming after drive-reopen failed"));
        }
E
Eric Blake 已提交
13984
    }
13985
    virObjectUnref(cfg);
13986 13987 13988
    return ret;
}

13989
static int
13990 13991 13992
qemuDomainBlockJobImpl(virDomainObjPtr vm,
                       virConnectPtr conn,
                       const char *path, const char *base,
13993
                       unsigned long bandwidth, virDomainBlockJobInfoPtr info,
13994
                       int mode, unsigned int flags)
13995
{
13996
    virQEMUDriverPtr driver = conn->privateData;
13997
    qemuDomainObjPrivatePtr priv;
E
Eric Blake 已提交
13998
    char *device = NULL;
13999
    int ret = -1;
14000
    bool async = false;
14001 14002 14003
    virDomainEventPtr event = NULL;
    int idx;
    virDomainDiskDefPtr disk;
14004

14005
    if (!virDomainObjIsActive(vm)) {
14006 14007
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain is not running"));
14008 14009 14010
        goto cleanup;
    }

14011
    priv = vm->privateData;
14012
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKJOB_ASYNC)) {
14013
        async = true;
14014
    } else if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKJOB_SYNC)) {
14015 14016
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("block jobs not supported with this QEMU binary"));
14017 14018
        goto cleanup;
    } else if (base) {
14019 14020 14021
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("partial block pull not supported with this "
                         "QEMU binary"));
14022
        goto cleanup;
14023
    } else if (mode == BLOCK_JOB_PULL && bandwidth) {
14024 14025 14026
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("setting bandwidth at start of block pull not "
                         "supported with this QEMU binary"));
14027
        goto cleanup;
14028
    }
14029

14030 14031
    device = qemuDiskPathToAlias(vm, path, &idx);
    if (!device)
14032
        goto cleanup;
14033
    disk = vm->def->disks[idx];
14034

E
Eric Blake 已提交
14035 14036 14037 14038 14039 14040
    if (mode == BLOCK_JOB_PULL && disk->mirror) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE,
                       _("disk '%s' already in active block copy job"),
                       disk->dst);
        goto cleanup;
    }
14041 14042 14043 14044 14045 14046 14047 14048
    if (mode == BLOCK_JOB_ABORT &&
        (flags & VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT) &&
        !(async && disk->mirror)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("pivot of disk '%s' requires an active copy job"),
                       disk->dst);
        goto cleanup;
    }
E
Eric Blake 已提交
14049

14050
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
14051
        goto cleanup;
14052 14053

    if (!virDomainObjIsActive(vm)) {
14054 14055
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain is not running"));
14056 14057 14058
        goto endjob;
    }

14059 14060
    if (disk->mirror && mode == BLOCK_JOB_ABORT &&
        (flags & VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT)) {
14061
        ret = qemuDomainBlockPivot(conn, driver, vm, device, disk);
14062 14063 14064
        goto endjob;
    }

14065
    qemuDomainObjEnterMonitor(driver, vm);
14066
    /* XXX - libvirt should really be tracking the backing file chain
14067 14068
     * itself, and validating that base is on the chain, rather than
     * relying on qemu to do this.  */
14069 14070
    ret = qemuMonitorBlockJob(priv->mon, device, base, bandwidth, info, mode,
                              async);
14071
    qemuDomainObjExitMonitor(driver, vm);
14072 14073 14074
    if (ret < 0)
        goto endjob;

14075 14076 14077 14078 14079 14080
    /* Snoop block copy operations, so future cancel operations can
     * avoid checking if pivot is safe.  */
    if (mode == BLOCK_JOB_INFO && ret == 1 && disk->mirror &&
        info->cur == info->end && info->type == VIR_DOMAIN_BLOCK_JOB_TYPE_COPY)
        disk->mirroring = true;

14081 14082 14083 14084 14085 14086 14087 14088 14089
    /* A successful block job cancelation stops any mirroring.  */
    if (mode == BLOCK_JOB_ABORT && disk->mirror) {
        /* XXX We should also revoke security labels and disk lease on
         * the mirror, and audit that fact, before dropping things.  */
        VIR_FREE(disk->mirror);
        disk->mirrorFormat = VIR_STORAGE_FILE_NONE;
        disk->mirroring = false;
    }

14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108
    /* With synchronous block cancel, we must synthesize an event, and
     * we silently ignore the ABORT_ASYNC flag.  With asynchronous
     * block cancel, the event will come from qemu, but without the
     * ABORT_ASYNC flag, we must block to guarantee synchronous
     * operation.  We do the waiting while still holding the VM job,
     * to prevent newly scheduled block jobs from confusing us.  */
    if (mode == BLOCK_JOB_ABORT) {
        if (!async) {
            int type = VIR_DOMAIN_BLOCK_JOB_TYPE_PULL;
            int status = VIR_DOMAIN_BLOCK_JOB_CANCELED;
            event = virDomainEventBlockJobNewFromObj(vm, disk->src, type,
                                                     status);
        } else if (!(flags & VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC)) {
            while (1) {
                /* Poll every 50ms */
                static struct timespec ts = { .tv_sec = 0,
                                              .tv_nsec = 50 * 1000 * 1000ull };
                virDomainBlockJobInfo dummy;

14109
                qemuDomainObjEnterMonitor(driver, vm);
14110 14111
                ret = qemuMonitorBlockJob(priv->mon, device, NULL, 0, &dummy,
                                          BLOCK_JOB_INFO, async);
14112
                qemuDomainObjExitMonitor(driver, vm);
14113 14114 14115 14116

                if (ret <= 0)
                    break;

14117
                virObjectUnlock(vm);
14118 14119 14120

                nanosleep(&ts, NULL);

14121
                virObjectLock(vm);
14122 14123

                if (!virDomainObjIsActive(vm)) {
14124 14125
                    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                   _("domain is not running"));
14126 14127 14128 14129 14130 14131
                    ret = -1;
                    break;
                }
            }
        }
    }
14132 14133

endjob:
14134 14135 14136 14137 14138 14139 14140 14141
    if (qemuDomainObjEndJob(driver, vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

cleanup:
    VIR_FREE(device);
    if (vm)
14142
        virObjectUnlock(vm);
14143 14144
    if (event)
        qemuDomainEventQueue(driver, event);
14145 14146 14147 14148 14149 14150
    return ret;
}

static int
qemuDomainBlockJobAbort(virDomainPtr dom, const char *path, unsigned int flags)
{
14151 14152
    virDomainObjPtr vm;

14153 14154
    virCheckFlags(VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC |
                  VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT, -1);
14155 14156 14157 14158 14159 14160 14161 14162 14163 14164

    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;

    if (virDomainBlockJobAbortEnsureACL(dom->conn, vm->def) < 0) {
        virObjectUnlock(vm);
        return -1;
    }

    return qemuDomainBlockJobImpl(vm, dom->conn, path, NULL, 0, NULL, BLOCK_JOB_ABORT,
14165
                                  flags);
14166 14167 14168 14169 14170 14171
}

static int
qemuDomainGetBlockJobInfo(virDomainPtr dom, const char *path,
                           virDomainBlockJobInfoPtr info, unsigned int flags)
{
14172
    virDomainObjPtr vm;
14173
    virCheckFlags(0, -1);
14174 14175 14176 14177 14178 14179 14180 14181 14182 14183

    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;

    if (virDomainGetBlockJobInfoEnsureACL(dom->conn, vm->def) < 0) {
        virObjectUnlock(vm);
        return -1;
    }

    return qemuDomainBlockJobImpl(vm, dom->conn, path, NULL, 0, info, BLOCK_JOB_INFO,
14184
                                  flags);
14185 14186 14187 14188 14189 14190
}

static int
qemuDomainBlockJobSetSpeed(virDomainPtr dom, const char *path,
                           unsigned long bandwidth, unsigned int flags)
{
14191
    virDomainObjPtr vm;
14192
    virCheckFlags(0, -1);
14193 14194 14195 14196 14197 14198 14199 14200 14201 14202

    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;

    if (virDomainBlockJobSetSpeedEnsureACL(dom->conn, vm->def) < 0) {
        virObjectUnlock(vm);
        return -1;
    }

    return qemuDomainBlockJobImpl(vm, dom->conn, path, NULL, bandwidth, NULL,
14203
                                  BLOCK_JOB_SPEED, flags);
14204 14205
}

14206
static int
14207 14208 14209
qemuDomainBlockCopy(virDomainObjPtr vm,
                    virConnectPtr conn,
                    const char *path,
14210 14211 14212
                    const char *dest, const char *format,
                    unsigned long bandwidth, unsigned int flags)
{
14213
    virQEMUDriverPtr driver = conn->privateData;
14214 14215 14216 14217 14218
    qemuDomainObjPrivatePtr priv;
    char *device = NULL;
    virDomainDiskDefPtr disk;
    int ret = -1;
    int idx;
14219
    struct stat st;
14220 14221
    bool need_unlink = false;
    char *mirror = NULL;
14222
    virQEMUDriverConfigPtr cfg = NULL;
14223 14224

    /* Preliminaries: find the disk we are editing, sanity checks */
14225 14226
    virCheckFlags(VIR_DOMAIN_BLOCK_REBASE_SHALLOW |
                  VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT, -1);
14227 14228

    priv = vm->privateData;
14229
    cfg = virQEMUDriverGetConfig(driver);
14230

14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248
    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain is not running"));
        goto cleanup;
    }

    device = qemuDiskPathToAlias(vm, path, &idx);
    if (!device) {
        goto cleanup;
    }
    disk = vm->def->disks[idx];
    if (disk->mirror) {
        virReportError(VIR_ERR_BLOCK_COPY_ACTIVE,
                       _("disk '%s' already in active block copy job"),
                       disk->dst);
        goto cleanup;
    }

14249 14250
    if (!(virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DRIVE_MIRROR) &&
          virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKJOB_ASYNC))) {
14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("block copy is not supported with this QEMU binary"));
        goto cleanup;
    }
    if (vm->persistent) {
        /* XXX if qemu ever lets us start a new domain with mirroring
         * already active, we can relax this; but for now, the risk of
         * 'managedsave' due to libvirt-guests means we can't risk
         * this on persistent domains.  */
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain is not transient"));
        goto cleanup;
    }

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

    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain is not running"));
        goto endjob;
    }
    if (qemuDomainDetermineDiskChain(driver, disk, false) < 0)
        goto endjob;

    if ((flags & VIR_DOMAIN_BLOCK_REBASE_SHALLOW) &&
        STREQ_NULLABLE(format, "raw") &&
        disk->backingChain->backingStore) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("disk '%s' has backing file, so raw shallow copy "
                         "is not possible"),
                       disk->dst);
        goto endjob;
    }

    /* Prepare the destination file.  */
14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306
    if (stat(dest, &st) < 0) {
        if (errno != ENOENT) {
            virReportSystemError(errno, _("unable to stat for disk %s: %s"),
                                 disk->dst, dest);
            goto endjob;
        } else if (flags & VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT) {
            virReportSystemError(errno,
                                 _("missing destination file for disk %s: %s"),
                                 disk->dst, dest);
            goto endjob;
        }
    } else if (!S_ISBLK(st.st_mode) && st.st_size &&
               !(flags & VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT)) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("external destination file for disk %s already "
                         "exists and is not a block device: %s"),
                       disk->dst, dest);
        goto endjob;
    }

14307 14308 14309 14310 14311 14312 14313
    if (!(flags & VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT)) {
        int fd = qemuOpenFile(driver, dest, O_WRONLY | O_TRUNC | O_CREAT,
                              &need_unlink, NULL);
        if (fd < 0)
            goto endjob;
        VIR_FORCE_CLOSE(fd);
        if (!format)
14314
            disk->mirrorFormat = disk->format;
14315
    } else if (format) {
14316 14317 14318 14319 14320 14321
        disk->mirrorFormat = virStorageFileFormatTypeFromString(format);
        if (disk->mirrorFormat <= 0) {
            virReportError(VIR_ERR_INVALID_ARG, _("unrecognized format '%s'"),
                           format);
            goto endjob;
        }
14322 14323 14324 14325 14326
    } else {
        /* If the user passed the REUSE_EXT flag, then either they
         * also passed the RAW flag (and format is non-NULL), or it is
         * safe for us to probe the format from the file that we will
         * be using.  */
14327 14328
        disk->mirrorFormat = virStorageFileProbeFormat(dest, cfg->user,
                                                       cfg->group);
14329 14330 14331
    }
    if (!format && disk->mirrorFormat > 0)
        format = virStorageFileFormatTypeToString(disk->mirrorFormat);
14332
    if (VIR_STRDUP(mirror, dest) < 0)
14333 14334
        goto endjob;

14335
    if (qemuDomainPrepareDiskChainElement(driver, vm, disk, dest,
14336
                                          VIR_DISK_CHAIN_READ_WRITE) < 0) {
14337
        qemuDomainPrepareDiskChainElement(driver, vm, disk, dest,
14338 14339 14340 14341
                                          VIR_DISK_CHAIN_NO_ACCESS);
        goto endjob;
    }

14342 14343 14344 14345
    /* Actually start the mirroring */
    qemuDomainObjEnterMonitor(driver, vm);
    ret = qemuMonitorDriveMirror(priv->mon, device, dest, format, bandwidth,
                                 flags);
14346
    virDomainAuditDisk(vm, NULL, dest, "mirror", ret >= 0);
14347
    qemuDomainObjExitMonitor(driver, vm);
14348
    if (ret < 0) {
14349
        qemuDomainPrepareDiskChainElement(driver, vm, disk, dest,
14350 14351 14352 14353 14354 14355 14356 14357
                                          VIR_DISK_CHAIN_NO_ACCESS);
        goto endjob;
    }

    /* Update vm in place to match changes.  */
    need_unlink = false;
    disk->mirror = mirror;
    mirror = NULL;
14358 14359

endjob:
14360 14361 14362
    if (need_unlink && unlink(dest))
        VIR_WARN("unable to unlink just-created %s", dest);
    if (ret < 0)
14363
        disk->mirrorFormat = VIR_STORAGE_FILE_NONE;
14364
    VIR_FREE(mirror);
14365 14366 14367 14368 14369 14370 14371 14372
    if (qemuDomainObjEndJob(driver, vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

cleanup:
    VIR_FREE(device);
    if (vm)
14373
        virObjectUnlock(vm);
14374
    virObjectUnref(cfg);
14375 14376 14377
    return ret;
}

14378
static int
14379 14380
qemuDomainBlockRebase(virDomainPtr dom, const char *path, const char *base,
                      unsigned long bandwidth, unsigned int flags)
14381
{
14382 14383
    virDomainObjPtr vm;

14384
    virCheckFlags(VIR_DOMAIN_BLOCK_REBASE_SHALLOW |
14385
                  VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT |
14386 14387 14388
                  VIR_DOMAIN_BLOCK_REBASE_COPY |
                  VIR_DOMAIN_BLOCK_REBASE_COPY_RAW, -1);

14389 14390 14391 14392 14393 14394 14395 14396
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;

    if (virDomainBlockRebaseEnsureACL(dom->conn, vm->def) < 0) {
        virObjectUnlock(vm);
        return -1;
    }

14397 14398 14399 14400 14401 14402
    if (flags & VIR_DOMAIN_BLOCK_REBASE_COPY) {
        const char *format = NULL;
        if (flags & VIR_DOMAIN_BLOCK_REBASE_COPY_RAW)
            format = "raw";
        flags &= ~(VIR_DOMAIN_BLOCK_REBASE_COPY |
                   VIR_DOMAIN_BLOCK_REBASE_COPY_RAW);
14403
        return qemuDomainBlockCopy(vm, dom->conn, path, base, format, bandwidth, flags);
14404 14405
    }

14406
    return qemuDomainBlockJobImpl(vm, dom->conn, path, base, bandwidth, NULL,
14407
                                  BLOCK_JOB_PULL, flags);
14408
}
14409

14410 14411 14412 14413
static int
qemuDomainBlockPull(virDomainPtr dom, const char *path, unsigned long bandwidth,
                    unsigned int flags)
{
14414
    virDomainObjPtr vm;
14415
    virCheckFlags(0, -1);
14416 14417 14418 14419 14420 14421 14422 14423 14424 14425

    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;

    if (virDomainBlockPullEnsureACL(dom->conn, vm->def) < 0) {
        virObjectUnlock(vm);
        return -1;
    }

    return qemuDomainBlockJobImpl(vm, dom->conn, path, NULL, bandwidth, NULL,
14426
                                  BLOCK_JOB_PULL, flags);
14427 14428
}

14429 14430 14431 14432 14433 14434

static int
qemuDomainBlockCommit(virDomainPtr dom, const char *path, const char *base,
                      const char *top, unsigned long bandwidth,
                      unsigned int flags)
{
14435
    virQEMUDriverPtr driver = dom->conn->privateData;
14436 14437 14438 14439 14440
    qemuDomainObjPrivatePtr priv;
    virDomainObjPtr vm = NULL;
    char *device = NULL;
    int ret = -1;
    int idx;
E
Eric Blake 已提交
14441
    virDomainDiskDefPtr disk = NULL;
14442 14443 14444 14445
    const char *top_canon = NULL;
    virStorageFileMetadataPtr top_meta = NULL;
    const char *top_parent = NULL;
    const char *base_canon = NULL;
E
Eric Blake 已提交
14446
    bool clean_access = false;
14447

14448
    virCheckFlags(VIR_DOMAIN_BLOCK_COMMIT_SHALLOW, -1);
14449 14450 14451 14452 14453

    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;
    priv = vm->privateData;

14454 14455 14456
    if (virDomainBlockCommitEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

14457 14458 14459 14460 14461 14462 14463 14464
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
        goto endjob;
    }
14465
    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCK_COMMIT)) {
14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("online commit not supported with this QEMU binary"));
        goto endjob;
    }

    device = qemuDiskPathToAlias(vm, path, &idx);
    if (!device)
        goto endjob;
    disk = vm->def->disks[idx];

    if (!disk->src) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("disk %s has no source file to be committed"),
                       disk->dst);
        goto endjob;
    }
14482 14483
    if (qemuDomainDetermineDiskChain(driver, disk, false) < 0)
        goto endjob;
14484

14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523
    if (!top) {
        top_canon = disk->src;
        top_meta = disk->backingChain;
    } else if (!(top_canon = virStorageFileChainLookup(disk->backingChain,
                                                       disk->src,
                                                       top, &top_meta,
                                                       &top_parent))) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("could not find top '%s' in chain for '%s'"),
                       top, path);
        goto endjob;
    }
    if (!top_meta || !top_meta->backingStore) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("top '%s' in chain for '%s' has no backing file"),
                       top, path);
        goto endjob;
    }
    if (!base && (flags & VIR_DOMAIN_BLOCK_COMMIT_SHALLOW)) {
        base_canon = top_meta->backingStore;
    } else if (!(base_canon = virStorageFileChainLookup(top_meta, top_canon,
                                                        base, NULL, NULL))) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("could not find base '%s' below '%s' in chain "
                         "for '%s'"),
                       base ? base : "(default)", top_canon, path);
        goto endjob;
    }
    /* Note that this code exploits the fact that
     * virStorageFileChainLookup guarantees a simple pointer
     * comparison will work, rather than needing full-blown STREQ.  */
    if ((flags & VIR_DOMAIN_BLOCK_COMMIT_SHALLOW) &&
        base_canon != top_meta->backingStore) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("base '%s' is not immediately below '%s' in chain "
                         "for '%s'"),
                       base, top_canon, path);
        goto endjob;
    }
14524

14525 14526 14527 14528 14529 14530 14531
    /* For the commit to succeed, we must allow qemu to open both the
     * 'base' image and the parent of 'top' as read/write; 'top' might
     * not have a parent, or might already be read-write.  XXX It
     * would also be nice to revert 'base' to read-only, as well as
     * revoke access to files removed from the chain, when the commit
     * operation succeeds, but doing that requires tracking the
     * operation in XML across libvirtd restarts.  */
E
Eric Blake 已提交
14532
    clean_access = true;
14533
    if (qemuDomainPrepareDiskChainElement(driver, vm, disk, base_canon,
14534 14535
                                          VIR_DISK_CHAIN_READ_WRITE) < 0 ||
        (top_parent && top_parent != disk->src &&
14536
         qemuDomainPrepareDiskChainElement(driver, vm, disk,
14537 14538 14539 14540 14541
                                           top_parent,
                                           VIR_DISK_CHAIN_READ_WRITE) < 0))
        goto endjob;

    /* Start the commit operation.  */
14542
    qemuDomainObjEnterMonitor(driver, vm);
14543 14544
    ret = qemuMonitorBlockCommit(priv->mon, device, top_canon, base_canon,
                                 bandwidth);
14545 14546 14547
    qemuDomainObjExitMonitor(driver, vm);

endjob:
E
Eric Blake 已提交
14548
    if (ret < 0 && clean_access) {
14549
        /* Revert access to read-only, if possible.  */
14550
        qemuDomainPrepareDiskChainElement(driver, vm, disk, base_canon,
14551 14552
                                          VIR_DISK_CHAIN_READ_ONLY);
        if (top_parent && top_parent != disk->src)
14553
            qemuDomainPrepareDiskChainElement(driver, vm, disk,
14554 14555 14556
                                              top_parent,
                                              VIR_DISK_CHAIN_READ_ONLY);
    }
14557 14558 14559 14560 14561 14562 14563 14564
    if (qemuDomainObjEndJob(driver, vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

cleanup:
    VIR_FREE(device);
    if (vm)
14565
        virObjectUnlock(vm);
14566 14567 14568
    return ret;
}

14569 14570 14571 14572 14573 14574
static int
qemuDomainOpenGraphics(virDomainPtr dom,
                       unsigned int idx,
                       int fd,
                       unsigned int flags)
{
14575
    virQEMUDriverPtr driver = dom->conn->privateData;
14576 14577 14578 14579 14580 14581 14582
    virDomainObjPtr vm = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;
    const char *protocol;

    virCheckFlags(VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH, -1);

14583 14584
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
14585

14586 14587 14588
    if (virDomainOpenGraphicsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

14589
    if (!virDomainObjIsActive(vm)) {
14590 14591
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
14592 14593 14594 14595 14596 14597
        goto cleanup;
    }

    priv = vm->privateData;

    if (idx >= vm->def->ngraphics) {
14598 14599
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No graphics backend with index %d"), idx);
14600 14601 14602 14603 14604 14605 14606 14607 14608 14609
        goto cleanup;
    }
    switch (vm->def->graphics[idx]->type) {
    case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
        protocol = "vnc";
        break;
    case VIR_DOMAIN_GRAPHICS_TYPE_SPICE:
        protocol = "spice";
        break;
    default:
14610 14611 14612
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Can only open VNC or SPICE graphics backends, not %s"),
                       virDomainGraphicsTypeToString(vm->def->graphics[idx]->type));
14613 14614 14615
        goto cleanup;
    }

14616
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
14617
        goto cleanup;
14618
    qemuDomainObjEnterMonitor(driver, vm);
14619 14620
    ret = qemuMonitorOpenGraphics(priv->mon, protocol, fd, "graphicsfd",
                                  (flags & VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH) != 0);
14621
    qemuDomainObjExitMonitor(driver, vm);
14622 14623 14624 14625 14626 14627 14628
    if (qemuDomainObjEndJob(driver, vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

cleanup:
    if (vm)
14629
        virObjectUnlock(vm);
14630 14631 14632
    return ret;
}

14633 14634 14635 14636 14637 14638 14639
static int
qemuDomainSetBlockIoTune(virDomainPtr dom,
                         const char *disk,
                         virTypedParameterPtr params,
                         int nparams,
                         unsigned int flags)
{
14640
    virQEMUDriverPtr driver = dom->conn->privateData;
14641 14642 14643 14644
    virDomainObjPtr vm = NULL;
    qemuDomainObjPrivatePtr priv;
    virDomainDefPtr persistentDef = NULL;
    virDomainBlockIoTuneInfo info;
E
Eric Blake 已提交
14645
    virDomainBlockIoTuneInfo *oldinfo;
14646 14647 14648 14649
    const char *device = NULL;
    int ret = -1;
    int i;
    int idx = -1;
E
Eric Blake 已提交
14650 14651
    bool set_bytes = false;
    bool set_iops = false;
14652
    virQEMUDriverConfigPtr cfg = NULL;
14653
    virCapsPtr caps = NULL;
14654 14655 14656

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_BYTES_SEC,
                               VIR_TYPED_PARAM_ULLONG,
                               VIR_DOMAIN_BLOCK_IOTUNE_READ_BYTES_SEC,
                               VIR_TYPED_PARAM_ULLONG,
                               VIR_DOMAIN_BLOCK_IOTUNE_WRITE_BYTES_SEC,
                               VIR_TYPED_PARAM_ULLONG,
                               VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_IOPS_SEC,
                               VIR_TYPED_PARAM_ULLONG,
                               VIR_DOMAIN_BLOCK_IOTUNE_READ_IOPS_SEC,
                               VIR_TYPED_PARAM_ULLONG,
                               VIR_DOMAIN_BLOCK_IOTUNE_WRITE_IOPS_SEC,
                               VIR_TYPED_PARAM_ULLONG,
                               NULL) < 0)
14671
        return -1;
14672 14673 14674

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

14675 14676 14677
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;

14678 14679 14680
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;

14681
    priv = vm->privateData;
14682 14683
    cfg = virQEMUDriverGetConfig(driver);

14684 14685 14686
    if (virDomainSetBlockIoTuneEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

14687
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
14688
        goto endjob;
14689

14690 14691
    if (!(device = qemuDiskPathToAlias(vm, disk, &idx)))
        goto endjob;
14692

14693
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
14694
                                        &persistentDef) < 0)
14695 14696 14697 14698 14699
        goto endjob;

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

14700 14701 14702 14703 14704 14705 14706
        if (param->value.ul > LLONG_MAX) {
            virReportError(VIR_ERR_OVERFLOW,
                           _("block I/O throttle limit value must"
                             " be less than %llu"), LLONG_MAX);
            goto endjob;
        }

14707 14708
        if (STREQ(param->field, VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_BYTES_SEC)) {
            info.total_bytes_sec = param->value.ul;
E
Eric Blake 已提交
14709
            set_bytes = true;
14710 14711 14712
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_READ_BYTES_SEC)) {
            info.read_bytes_sec = param->value.ul;
E
Eric Blake 已提交
14713
            set_bytes = true;
14714 14715 14716
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_WRITE_BYTES_SEC)) {
            info.write_bytes_sec = param->value.ul;
E
Eric Blake 已提交
14717
            set_bytes = true;
14718 14719 14720
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_IOPS_SEC)) {
            info.total_iops_sec = param->value.ul;
E
Eric Blake 已提交
14721
            set_iops = true;
14722 14723 14724
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_READ_IOPS_SEC)) {
            info.read_iops_sec = param->value.ul;
E
Eric Blake 已提交
14725
            set_iops = true;
14726 14727 14728
        } else if (STREQ(param->field,
                         VIR_DOMAIN_BLOCK_IOTUNE_WRITE_IOPS_SEC)) {
            info.write_iops_sec = param->value.ul;
E
Eric Blake 已提交
14729
            set_iops = true;
14730 14731 14732 14733 14734
        }
    }

    if ((info.total_bytes_sec && info.read_bytes_sec) ||
        (info.total_bytes_sec && info.write_bytes_sec)) {
14735 14736
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("total and read/write of bytes_sec cannot be set at the same time"));
14737 14738 14739 14740 14741
        goto endjob;
    }

    if ((info.total_iops_sec && info.read_iops_sec) ||
        (info.total_iops_sec && info.write_iops_sec)) {
14742 14743
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("total and read/write of iops_sec cannot be set at the same time"));
14744 14745 14746 14747
        goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
14748 14749 14750 14751 14752 14753 14754
        if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_DRIVE_IOTUNE)) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("block I/O throttling not supported with this "
                         "QEMU binary"));
            goto endjob;
        }

E
Eric Blake 已提交
14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768
        /* If the user didn't specify bytes limits, inherit previous
         * values; likewise if the user didn't specify iops
         * limits.  */
        oldinfo = &vm->def->disks[idx]->blkdeviotune;
        if (!set_bytes) {
            info.total_bytes_sec = oldinfo->total_bytes_sec;
            info.read_bytes_sec = oldinfo->read_bytes_sec;
            info.write_bytes_sec = oldinfo->write_bytes_sec;
        }
        if (!set_iops) {
            info.total_iops_sec = oldinfo->total_iops_sec;
            info.read_iops_sec = oldinfo->read_iops_sec;
            info.write_iops_sec = oldinfo->write_iops_sec;
        }
14769
        qemuDomainObjEnterMonitor(driver, vm);
14770
        ret = qemuMonitorSetBlockIoThrottle(priv->mon, device, &info);
14771
        qemuDomainObjExitMonitor(driver, vm);
L
Lei Li 已提交
14772 14773
        if (ret < 0)
            goto endjob;
14774
        vm->def->disks[idx]->blkdeviotune = info;
14775 14776 14777
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
14778
        sa_assert(persistentDef);
E
Eric Blake 已提交
14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789
        oldinfo = &persistentDef->disks[idx]->blkdeviotune;
        if (!set_bytes) {
            info.total_bytes_sec = oldinfo->total_bytes_sec;
            info.read_bytes_sec = oldinfo->read_bytes_sec;
            info.write_bytes_sec = oldinfo->write_bytes_sec;
        }
        if (!set_iops) {
            info.total_iops_sec = oldinfo->total_iops_sec;
            info.read_iops_sec = oldinfo->read_iops_sec;
            info.write_iops_sec = oldinfo->write_iops_sec;
        }
14790
        persistentDef->disks[idx]->blkdeviotune = info;
14791
        ret = virDomainSaveConfig(cfg->configDir, persistentDef);
14792
        if (ret < 0) {
14793
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
14794 14795 14796 14797 14798 14799
                           _("Write to config file failed"));
            goto endjob;
        }
    }

endjob:
14800
    if (!qemuDomainObjEndJob(driver, vm))
14801 14802 14803 14804 14805
        vm = NULL;

cleanup:
    VIR_FREE(device);
    if (vm)
14806
        virObjectUnlock(vm);
14807
    virObjectUnref(caps);
14808
    virObjectUnref(cfg);
14809 14810 14811 14812 14813 14814 14815 14816 14817 14818
    return ret;
}

static int
qemuDomainGetBlockIoTune(virDomainPtr dom,
                         const char *disk,
                         virTypedParameterPtr params,
                         int *nparams,
                         unsigned int flags)
{
14819
    virQEMUDriverPtr driver = dom->conn->privateData;
14820 14821 14822 14823 14824 14825 14826
    virDomainObjPtr vm = NULL;
    qemuDomainObjPrivatePtr priv;
    virDomainDefPtr persistentDef = NULL;
    virDomainBlockIoTuneInfo reply;
    const char *device = NULL;
    int ret = -1;
    int i;
14827
    virCapsPtr caps = NULL;
14828 14829 14830 14831 14832 14833 14834 14835

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);

    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

14836 14837
    if (!(vm = qemuDomObjFromDomain(dom)))
        return -1;
14838

14839 14840 14841
    if (virDomainGetBlockIoTuneEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

14842 14843 14844
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

14845 14846 14847 14848 14849 14850 14851
    if ((*nparams) == 0) {
        /* Current number of parameters supported by QEMU Block I/O Throttling */
        *nparams = QEMU_NB_BLOCK_IO_TUNE_PARAM;
        ret = 0;
        goto cleanup;
    }

E
Eric Blake 已提交
14852
    device = qemuDiskPathToAlias(vm, disk, NULL);
14853 14854 14855 14856 14857

    if (!device) {
        goto cleanup;
    }

14858
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
14859 14860
        goto cleanup;

14861
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
14862
                                        &persistentDef) < 0)
14863 14864 14865 14866
        goto endjob;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        priv = vm->privateData;
14867
        qemuDomainObjEnterMonitor(driver, vm);
14868
        ret = qemuMonitorGetBlockIoThrottle(priv->mon, device, &reply);
14869
        qemuDomainObjExitMonitor(driver, vm);
14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883
        if (ret < 0)
            goto endjob;
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        int idx = virDomainDiskIndexByName(vm->def, disk, true);
        if (idx < 0)
            goto endjob;
        reply = persistentDef->disks[idx]->blkdeviotune;
    }

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

14884
        switch (i) {
14885
        case 0:
14886 14887 14888 14889
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_BYTES_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.total_bytes_sec) < 0)
14890 14891 14892
                goto endjob;
            break;
        case 1:
14893 14894 14895 14896
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_READ_BYTES_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.read_bytes_sec) < 0)
14897 14898 14899
                goto endjob;
            break;
        case 2:
14900 14901 14902 14903
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_WRITE_BYTES_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.write_bytes_sec) < 0)
14904 14905 14906
                goto endjob;
            break;
        case 3:
14907 14908 14909 14910
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_TOTAL_IOPS_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.total_iops_sec) < 0)
14911 14912 14913
                goto endjob;
            break;
        case 4:
14914 14915 14916 14917
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_READ_IOPS_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.read_iops_sec) < 0)
14918 14919 14920
                goto endjob;
            break;
        case 5:
14921 14922 14923 14924
            if (virTypedParameterAssign(param,
                                        VIR_DOMAIN_BLOCK_IOTUNE_WRITE_IOPS_SEC,
                                        VIR_TYPED_PARAM_ULLONG,
                                        reply.write_iops_sec) < 0)
14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942
                goto endjob;
            break;
        default:
            break;
        }
    }

    if (*nparams > QEMU_NB_BLOCK_IO_TUNE_PARAM)
        *nparams = QEMU_NB_BLOCK_IO_TUNE_PARAM;
    ret = 0;

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

cleanup:
    VIR_FREE(device);
    if (vm)
14943
        virObjectUnlock(vm);
14944
    virObjectUnref(caps);
14945 14946
    return ret;
}
14947

14948 14949 14950 14951 14952 14953
static int
qemuDomainGetDiskErrors(virDomainPtr dom,
                        virDomainDiskErrorPtr errors,
                        unsigned int nerrors,
                        unsigned int flags)
{
14954
    virQEMUDriverPtr driver = dom->conn->privateData;
14955 14956 14957 14958 14959 14960 14961 14962 14963
    virDomainObjPtr vm = NULL;
    qemuDomainObjPrivatePtr priv;
    virHashTablePtr table = NULL;
    int ret = -1;
    int i;
    int n = 0;

    virCheckFlags(0, -1);

14964
    if (!(vm = qemuDomObjFromDomain(dom)))
14965 14966 14967 14968
        goto cleanup;

    priv = vm->privateData;

14969 14970 14971
    if (virDomainGetDiskErrorsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

14972 14973 14974 14975
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_QUERY) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
14976 14977
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000
        goto endjob;
    }

    if (!errors) {
        ret = vm->def->ndisks;
        goto endjob;
    }

    qemuDomainObjEnterMonitor(driver, vm);
    table = qemuMonitorGetBlockInfo(priv->mon);
    qemuDomainObjExitMonitor(driver, vm);
    if (!table)
        goto endjob;

    for (i = n = 0; i < vm->def->ndisks; i++) {
        struct qemuDomainDiskInfo *info;
        virDomainDiskDefPtr disk = vm->def->disks[i];

        if ((info = virHashLookup(table, disk->info.alias)) &&
            info->io_status != VIR_DOMAIN_DISK_ERROR_NONE) {
            if (n == nerrors)
                break;

15001
            if (VIR_STRDUP(errors[n].disk, disk->dst) < 0)
15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015
                goto endjob;
            errors[n].error = info->io_status;
            n++;
        }
    }

    ret = n;

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

cleanup:
    if (vm)
15016
        virObjectUnlock(vm);
15017 15018 15019 15020 15021 15022 15023 15024
    virHashFree(table);
    if (ret < 0) {
        for (i = 0; i < n; i++)
            VIR_FREE(errors[i].disk);
    }
    return ret;
}

15025 15026 15027 15028 15029 15030 15031 15032
static int
qemuDomainSetMetadata(virDomainPtr dom,
                      int type,
                      const char *metadata,
                      const char *key ATTRIBUTE_UNUSED,
                      const char *uri ATTRIBUTE_UNUSED,
                      unsigned int flags)
{
15033
    virQEMUDriverPtr driver = dom->conn->privateData;
15034 15035 15036
    virDomainObjPtr vm;
    virDomainDefPtr persistentDef;
    int ret = -1;
15037
    virQEMUDriverConfigPtr cfg = NULL;
15038
    virCapsPtr caps = NULL;
15039 15040 15041 15042

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

15043
    if (!(vm = qemuDomObjFromDomain(dom)))
15044 15045
        goto cleanup;

15046 15047
    cfg = virQEMUDriverGetConfig(driver);

15048 15049 15050
    if (virDomainSetMetadataEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

15051 15052 15053
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

15054
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags,
15055 15056 15057 15058 15059 15060 15061
                                        &persistentDef) < 0)
        goto cleanup;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        switch ((virDomainMetadataType) type) {
        case VIR_DOMAIN_METADATA_DESCRIPTION:
            VIR_FREE(vm->def->description);
15062 15063
            if (VIR_STRDUP(vm->def->description, metadata) < 0)
                goto cleanup;
15064 15065 15066
            break;
        case VIR_DOMAIN_METADATA_TITLE:
            VIR_FREE(vm->def->title);
15067 15068
            if (VIR_STRDUP(vm->def->title, metadata) < 0)
                goto cleanup;
15069 15070
            break;
        case VIR_DOMAIN_METADATA_ELEMENT:
15071
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
15072
                           _("QEmu driver does not support modifying "
15073
                             "<metadata> element"));
15074 15075 15076
            goto cleanup;
            break;
        default:
15077 15078
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("unknown metadata type"));
15079 15080 15081 15082 15083 15084 15085 15086 15087
            goto cleanup;
            break;
        }
    }

    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        switch ((virDomainMetadataType) type) {
        case VIR_DOMAIN_METADATA_DESCRIPTION:
            VIR_FREE(persistentDef->description);
15088 15089
            if (VIR_STRDUP(persistentDef->description, metadata) < 0)
                goto cleanup;
15090 15091 15092
            break;
        case VIR_DOMAIN_METADATA_TITLE:
            VIR_FREE(persistentDef->title);
15093 15094
            if (VIR_STRDUP(persistentDef->title, metadata) < 0)
                goto cleanup;
15095 15096
            break;
        case VIR_DOMAIN_METADATA_ELEMENT:
15097
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
15098
                           _("QEMU driver does not support "
15099
                             "<metadata> element"));
15100 15101
            goto cleanup;
         default:
15102 15103
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("unknown metadata type"));
15104 15105 15106 15107
            goto cleanup;
            break;
        }

15108
        if (virDomainSaveConfig(cfg->configDir, persistentDef) < 0)
15109 15110 15111 15112 15113 15114 15115
            goto cleanup;
    }

    ret = 0;

cleanup:
    if (vm)
15116
        virObjectUnlock(vm);
15117
    virObjectUnref(caps);
15118
    virObjectUnref(cfg);
15119 15120 15121 15122 15123 15124 15125 15126 15127
    return ret;
}

static char *
qemuDomainGetMetadata(virDomainPtr dom,
                      int type,
                      const char *uri ATTRIBUTE_UNUSED,
                      unsigned int flags)
{
15128
    virQEMUDriverPtr driver = dom->conn->privateData;
15129 15130 15131 15132
    virDomainObjPtr vm;
    virDomainDefPtr def;
    char *ret = NULL;
    char *field = NULL;
15133
    virCapsPtr caps = NULL;
15134 15135 15136 15137

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, NULL);

15138
    if (!(vm = qemuDomObjFromDomain(dom)))
15139 15140
        goto cleanup;

15141 15142 15143
    if (virDomainGetMetadataEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

15144 15145 15146
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

15147
    if (virDomainLiveConfigHelperMethod(caps, driver->xmlopt, vm, &flags, &def) < 0)
15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161
        goto cleanup;

    /* use correct domain definition according to flags */
    if (flags & VIR_DOMAIN_AFFECT_LIVE)
        def = vm->def;

    switch ((virDomainMetadataType) type) {
    case VIR_DOMAIN_METADATA_DESCRIPTION:
        field = def->description;
        break;
    case VIR_DOMAIN_METADATA_TITLE:
        field = def->title;
        break;
    case VIR_DOMAIN_METADATA_ELEMENT:
15162
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
15163
                       _("QEMU driver does not support "
15164
                         "<metadata> element"));
15165 15166 15167
        goto cleanup;
        break;
    default:
15168 15169
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("unknown metadata type"));
15170 15171 15172 15173 15174
        goto cleanup;
        break;
    }

    if (!field) {
15175 15176
        virReportError(VIR_ERR_NO_DOMAIN_METADATA, "%s",
                       _("Requested metadata element is not present"));
15177 15178 15179
        goto cleanup;
    }

15180
    ignore_value(VIR_STRDUP(ret, field));
15181 15182 15183

cleanup:
    if (vm)
15184
        virObjectUnlock(vm);
15185
    virObjectUnref(caps);
15186 15187 15188
    return ret;
}

15189 15190
/* qemuDomainGetCPUStats() with start_cpu == -1 */
static int
15191
qemuDomainGetTotalcpuStats(virDomainObjPtr vm,
15192 15193 15194 15195 15196
                           virTypedParameterPtr params,
                           int nparams)
{
    unsigned long long cpu_time;
    int ret;
15197
    qemuDomainObjPrivatePtr priv = vm->privateData;
15198 15199

    if (nparams == 0) /* return supported number of params */
E
Eric Blake 已提交
15200
        return QEMU_NB_TOTAL_CPU_STAT_PARAM;
15201
    /* entry 0 is cputime */
15202
    ret = virCgroupGetCpuacctUsage(priv->cgroup, &cpu_time);
15203 15204 15205 15206 15207
    if (ret < 0) {
        virReportSystemError(-ret, "%s", _("unable to get cpu account"));
        return -1;
    }

E
Eric Blake 已提交
15208 15209 15210 15211 15212 15213 15214 15215
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_CPU_STATS_CPUTIME,
                                VIR_TYPED_PARAM_ULLONG, cpu_time) < 0)
        return -1;

    if (nparams > 1) {
        unsigned long long user;
        unsigned long long sys;

15216
        ret = virCgroupGetCpuacctStat(priv->cgroup, &user, &sys);
E
Eric Blake 已提交
15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236
        if (ret < 0) {
            virReportSystemError(-ret, "%s", _("unable to get cpu account"));
            return -1;
        }

        if (virTypedParameterAssign(&params[1],
                                    VIR_DOMAIN_CPU_STATS_USERTIME,
                                    VIR_TYPED_PARAM_ULLONG, user) < 0)
            return -1;
        if (nparams > 2 &&
            virTypedParameterAssign(&params[2],
                                    VIR_DOMAIN_CPU_STATS_SYSTEMTIME,
                                    VIR_TYPED_PARAM_ULLONG, sys) < 0)
            return -1;

        if (nparams > QEMU_NB_TOTAL_CPU_STAT_PARAM)
            nparams = QEMU_NB_TOTAL_CPU_STAT_PARAM;
    }

    return nparams;
15237 15238
}

15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253
/* This function gets the sums of cpu time consumed by all vcpus.
 * For example, if there are 4 physical cpus, and 2 vcpus in a domain,
 * then for each vcpu, the cpuacct.usage_percpu looks like this:
 *   t0 t1 t2 t3
 * and we have 2 groups of such data:
 *   v\p   0   1   2   3
 *   0   t00 t01 t02 t03
 *   1   t10 t11 t12 t13
 * for each pcpu, the sum is cpu time consumed by all vcpus.
 *   s0 = t00 + t10
 *   s1 = t01 + t11
 *   s2 = t02 + t12
 *   s3 = t03 + t13
 */
static int
15254
getSumVcpuPercpuStats(virDomainObjPtr vm,
15255 15256 15257 15258 15259 15260
                      unsigned long long *sum_cpu_time,
                      unsigned int num)
{
    int ret = -1;
    int i;
    char *buf = NULL;
15261
    qemuDomainObjPrivatePtr priv = vm->privateData;
15262 15263
    virCgroupPtr group_vcpu = NULL;

15264
    for (i = 0; i < priv->nvcpupids; i++) {
15265 15266 15267 15268
        char *pos;
        unsigned long long tmp;
        int j;

15269
        if (virCgroupNewVcpu(priv->cgroup, i, false, &group_vcpu) < 0) {
15270 15271
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("error accessing cgroup cpuacct for vcpu"));
15272 15273 15274
            goto cleanup;
        }

15275
        if (virCgroupGetCpuacctPercpuUsage(group_vcpu, &buf) < 0)
15276 15277 15278 15279 15280
            goto cleanup;

        pos = buf;
        for (j = 0; j < num; j++) {
            if (virStrToLong_ull(pos, &pos, 10, &tmp) < 0) {
15281 15282
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cpuacct parse error"));
15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298
                goto cleanup;
            }
            sum_cpu_time[j] += tmp;
        }

        virCgroupFree(&group_vcpu);
        VIR_FREE(buf);
    }

    ret = 0;
cleanup:
    virCgroupFree(&group_vcpu);
    VIR_FREE(buf);
    return ret;
}

15299
static int
15300
qemuDomainGetPercpuStats(virDomainObjPtr vm,
15301 15302 15303 15304 15305 15306
                         virTypedParameterPtr params,
                         unsigned int nparams,
                         int start_cpu,
                         unsigned int ncpus)
{
    int rv = -1;
15307
    int i, id, max_id;
15308 15309
    char *pos;
    char *buf = NULL;
15310 15311 15312 15313
    unsigned long long *sum_cpu_time = NULL;
    unsigned long long *sum_cpu_pos;
    unsigned int n = 0;
    qemuDomainObjPrivatePtr priv = vm->privateData;
15314 15315
    virTypedParameterPtr ent;
    int param_idx;
15316
    unsigned long long cpu_time;
15317 15318 15319

    /* return the number of supported params */
    if (nparams == 0 && ncpus != 0)
15320
        return QEMU_NB_PER_CPU_STAT_PARAM;
15321

15322 15323 15324
    /* To parse account file, we need to know how many cpus are present.  */
    max_id = nodeGetCPUCount();
    if (max_id < 0)
15325 15326 15327
        return rv;

    if (ncpus == 0) { /* returns max cpu ID */
15328
        rv = max_id;
15329 15330 15331 15332
        goto cleanup;
    }

    if (start_cpu > max_id) {
15333 15334 15335
        virReportError(VIR_ERR_INVALID_ARG,
                       _("start_cpu %d larger than maximum of %d"),
                       start_cpu, max_id);
15336 15337 15338 15339
        goto cleanup;
    }

    /* we get percpu cputime accounting info. */
15340
    if (virCgroupGetCpuacctPercpuUsage(priv->cgroup, &buf))
15341 15342
        goto cleanup;
    pos = buf;
15343
    memset(params, 0, nparams * ncpus);
15344

15345 15346 15347
    /* return percpu cputime in index 0 */
    param_idx = 0;

15348
    /* number of cpus to compute */
15349 15350 15351
    if (start_cpu >= max_id - ncpus)
        id = max_id - 1;
    else
15352
        id = start_cpu + ncpus - 1;
15353

15354
    for (i = 0; i <= id; i++) {
15355
        if (virStrToLong_ull(pos, &pos, 10, &cpu_time) < 0) {
15356
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
15357
                           _("cpuacct parse error"));
15358
            goto cleanup;
15359 15360
        } else {
            n++;
15361 15362 15363
        }
        if (i < start_cpu)
            continue;
15364
        ent = &params[(i - start_cpu) * nparams + param_idx];
E
Eric Blake 已提交
15365 15366 15367
        if (virTypedParameterAssign(ent, VIR_DOMAIN_CPU_STATS_CPUTIME,
                                    VIR_TYPED_PARAM_ULLONG, cpu_time) < 0)
            goto cleanup;
15368
    }
15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379

    /* return percpu vcputime in index 1 */
    if (++param_idx >= nparams) {
        rv = nparams;
        goto cleanup;
    }

    if (VIR_ALLOC_N(sum_cpu_time, n) < 0) {
        virReportOOMError();
        goto cleanup;
    }
15380
    if (getSumVcpuPercpuStats(vm, sum_cpu_time, n) < 0)
15381 15382 15383
        goto cleanup;

    sum_cpu_pos = sum_cpu_time;
15384
    for (i = 0; i <= id; i++) {
15385
        cpu_time = *(sum_cpu_pos++);
15386 15387 15388 15389 15390 15391 15392 15393 15394 15395
        if (i < start_cpu)
            continue;
        if (virTypedParameterAssign(&params[(i - start_cpu) * nparams +
                                            param_idx],
                                    VIR_DOMAIN_CPU_STATS_VCPUTIME,
                                    VIR_TYPED_PARAM_ULLONG,
                                    cpu_time) < 0)
            goto cleanup;
    }

15396 15397
    rv = param_idx + 1;
cleanup:
15398
    VIR_FREE(sum_cpu_time);
15399 15400 15401 15402 15403 15404 15405
    VIR_FREE(buf);
    return rv;
}


static int
qemuDomainGetCPUStats(virDomainPtr domain,
15406 15407 15408 15409 15410
                      virTypedParameterPtr params,
                      unsigned int nparams,
                      int start_cpu,
                      unsigned int ncpus,
                      unsigned int flags)
15411 15412 15413 15414
{
    virDomainObjPtr vm = NULL;
    int ret = -1;
    bool isActive;
15415
    qemuDomainObjPrivatePtr priv;
15416 15417 15418

    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

15419 15420
    if (!(vm = qemuDomObjFromDomain(domain)))
        return -1;
15421

15422 15423
    priv = vm->privateData;

15424 15425 15426
    if (virDomainGetCPUStatsEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

15427 15428
    isActive = virDomainObjIsActive(vm);
    if (!isActive) {
15429 15430
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain is not running"));
15431 15432 15433
        goto cleanup;
    }

15434
    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUACCT)) {
15435 15436
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cgroup CPUACCT controller is not mounted"));
15437 15438 15439 15440
        goto cleanup;
    }

    if (start_cpu == -1)
15441
        ret = qemuDomainGetTotalcpuStats(vm, params, nparams);
15442
    else
15443
        ret = qemuDomainGetPercpuStats(vm, params, nparams,
15444 15445 15446
                                       start_cpu, ncpus);
cleanup:
    if (vm)
15447
        virObjectUnlock(vm);
15448 15449 15450
    return ret;
}

15451 15452 15453 15454 15455 15456
static int
qemuDomainPMSuspendForDuration(virDomainPtr dom,
                               unsigned int target,
                               unsigned long long duration,
                               unsigned int flags)
{
15457
    virQEMUDriverPtr driver = dom->conn->privateData;
15458 15459 15460 15461 15462 15463 15464
    qemuDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

    if (duration) {
15465 15466
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("Duration not supported. Use 0 for now"));
15467 15468 15469 15470 15471 15472
        return -1;
    }

    if (!(target == VIR_NODE_SUSPEND_TARGET_MEM ||
          target == VIR_NODE_SUSPEND_TARGET_DISK ||
          target == VIR_NODE_SUSPEND_TARGET_HYBRID)) {
15473 15474 15475
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unknown suspend target: %u"),
                       target);
15476 15477 15478
        return -1;
    }

15479
    if (!(vm = qemuDomObjFromDomain(dom)))
15480 15481 15482 15483
        goto cleanup;

    priv = vm->privateData;

15484 15485 15486
    if (virDomainPMSuspendForDurationEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

15487
    if (!virDomainObjIsActive(vm)) {
15488 15489
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
15490 15491 15492
        goto cleanup;
    }

15493
    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_WAKEUP) &&
15494 15495
        (target == VIR_NODE_SUSPEND_TARGET_MEM ||
         target == VIR_NODE_SUSPEND_TARGET_HYBRID)) {
15496 15497 15498
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("Unable to suspend domain due to "
                         "missing system_wakeup monitor command"));
O
Osier Yang 已提交
15499
        goto cleanup;
15500 15501
    }

15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518
    if (vm->def->pm.s3 || vm->def->pm.s4) {
        if (vm->def->pm.s3 == VIR_DOMAIN_PM_STATE_DISABLED &&
            (target == VIR_NODE_SUSPEND_TARGET_MEM ||
             target == VIR_NODE_SUSPEND_TARGET_HYBRID)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("S3 state is disabled for this domain"));
            goto cleanup;
        }

        if (vm->def->pm.s4 == VIR_DOMAIN_PM_STATE_DISABLED &&
            target == VIR_NODE_SUSPEND_TARGET_DISK) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("S4 state is disabled for this domain"));
            goto cleanup;
        }
    }

15519
    if (priv->agentError) {
15520 15521 15522
        virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                       _("QEMU guest agent is not "
                         "available due to an error"));
15523 15524 15525 15526
        goto cleanup;
    }

    if (!priv->agent) {
15527 15528
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("QEMU guest agent is not configured"));
15529 15530 15531 15532 15533 15534 15535
        goto cleanup;
    }

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

    if (!virDomainObjIsActive(vm)) {
15536 15537
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
15538 15539 15540
        goto endjob;
    }

15541
    qemuDomainObjEnterAgent(vm);
15542
    ret = qemuAgentSuspend(priv->agent, target);
15543
    qemuDomainObjExitAgent(vm);
15544 15545 15546 15547 15548 15549 15550

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

cleanup:
    if (vm)
15551
        virObjectUnlock(vm);
15552 15553 15554
    return ret;
}

15555 15556 15557 15558
static int
qemuDomainPMWakeup(virDomainPtr dom,
                   unsigned int flags)
{
15559
    virQEMUDriverPtr driver = dom->conn->privateData;
15560 15561 15562 15563 15564 15565
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, -1);

15566
    if (!(vm = qemuDomObjFromDomain(dom)))
15567 15568
        goto cleanup;

15569 15570 15571
    if (virDomainPMWakeupEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

15572 15573 15574 15575
    if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
15576 15577
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
15578 15579 15580 15581 15582
        goto endjob;
    }

    priv = vm->privateData;

15583
    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_WAKEUP)) {
15584 15585 15586
       virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                      _("Unable to wake up domain due to "
                        "missing system_wakeup monitor command"));
15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599
       goto endjob;
    }

    qemuDomainObjEnterMonitor(driver, vm);
    ret = qemuMonitorSystemWakeup(priv->mon);
    qemuDomainObjExitMonitor(driver, vm);

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

cleanup:
    if (vm)
15600
        virObjectUnlock(vm);
15601 15602 15603
    return ret;
}

15604
static int
15605 15606 15607
qemuConnectListAllDomains(virConnectPtr conn,
                          virDomainPtr **domains,
                          unsigned int flags)
15608
{
15609
    virQEMUDriverPtr driver = conn->privateData;
15610 15611
    int ret = -1;

O
Osier Yang 已提交
15612
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
15613

15614 15615 15616
    if (virConnectListAllDomainsEnsureACL(conn) < 0)
        goto cleanup;

15617
    ret = virDomainObjListExport(driver->domains, conn, domains, flags);
15618

15619
cleanup:
15620 15621 15622
    return ret;
}

M
MATSUDA Daiki 已提交
15623
static char *
15624 15625 15626 15627
qemuDomainQemuAgentCommand(virDomainPtr domain,
                           const char *cmd,
                           int timeout,
                           unsigned int flags)
M
MATSUDA Daiki 已提交
15628
{
15629
    virQEMUDriverPtr driver = domain->conn->privateData;
M
MATSUDA Daiki 已提交
15630 15631 15632 15633 15634 15635 15636
    virDomainObjPtr vm;
    int ret = -1;
    char *result = NULL;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, NULL);

15637
    if (!(vm = qemuDomObjFromDomain(domain)))
M
MATSUDA Daiki 已提交
15638 15639 15640 15641
        goto cleanup;

    priv = vm->privateData;

15642 15643 15644
    if (virDomainQemuAgentCommandEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;

M
MATSUDA Daiki 已提交
15645 15646 15647 15648 15649 15650 15651
    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
        goto cleanup;
    }

    if (priv->agentError) {
15652 15653 15654
        virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                       _("QEMU guest agent is not "
                         "available due to an error"));
M
MATSUDA Daiki 已提交
15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672
        goto cleanup;
    }

    if (!priv->agent) {
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("QEMU guest agent is not configured"));
        goto cleanup;
    }

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

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

15673
    qemuDomainObjEnterAgent(vm);
M
MATSUDA Daiki 已提交
15674
    ret = qemuAgentArbitraryCommand(priv->agent, cmd, &result, timeout);
15675
    qemuDomainObjExitAgent(vm);
15676 15677
    if (ret < 0)
        VIR_FREE(result);
M
MATSUDA Daiki 已提交
15678 15679

endjob:
15680
    if (qemuDomainObjEndJob(driver, vm) == 0)
M
MATSUDA Daiki 已提交
15681 15682 15683 15684
        vm = NULL;

cleanup:
    if (vm)
15685
        virObjectUnlock(vm);
M
MATSUDA Daiki 已提交
15686 15687 15688
    return result;
}

M
Michal Privoznik 已提交
15689 15690 15691 15692 15693 15694
static int
qemuDomainFSTrim(virDomainPtr dom,
                 const char *mountPoint,
                 unsigned long long minimum,
                 unsigned int flags)
{
15695
    virQEMUDriverPtr driver = dom->conn->privateData;
M
Michal Privoznik 已提交
15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, -1);

    if (mountPoint) {
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("Specifying mount point "
                         "is not supported for now"));
        return -1;
    }

    if (!(vm = qemuDomObjFromDomain(dom)))
        goto cleanup;

    priv = vm->privateData;

15714 15715 15716
    if (virDomainFSTrimEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

M
Michal Privoznik 已提交
15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744
    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
        goto cleanup;
    }

    if (!priv->agent) {
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("QEMU guest agent is not configured"));
        goto cleanup;
    }

    if (priv->agentError) {
        virReportError(VIR_ERR_AGENT_UNRESPONSIVE, "%s",
                       _("QEMU guest agent is not "
                         "available due to an error"));
        goto cleanup;
    }

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

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

15745
    qemuDomainObjEnterAgent(vm);
M
Michal Privoznik 已提交
15746
    ret = qemuAgentFSTrim(priv->agent, minimum);
15747
    qemuDomainObjExitAgent(vm);
M
Michal Privoznik 已提交
15748 15749 15750 15751 15752 15753 15754

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

cleanup:
    if (vm)
15755
        virObjectUnlock(vm);
M
Michal Privoznik 已提交
15756 15757 15758
    return ret;
}

15759 15760

static int
15761
qemuNodeGetInfo(virConnectPtr conn,
15762 15763
                virNodeInfoPtr nodeinfo)
{
15764 15765 15766
    if (virNodeGetInfoEnsureACL(conn) < 0)
        return -1;

15767 15768 15769 15770 15771
    return nodeGetInfo(nodeinfo);
}


static int
15772
qemuNodeGetCPUStats(virConnectPtr conn,
15773 15774 15775 15776 15777
                    int cpuNum,
                    virNodeCPUStatsPtr params,
                    int *nparams,
                    unsigned int flags)
{
15778 15779 15780
    if (virNodeGetCPUStatsEnsureACL(conn) < 0)
        return -1;

15781 15782 15783 15784 15785
    return nodeGetCPUStats(cpuNum, params, nparams, flags);
}


static int
15786
qemuNodeGetMemoryStats(virConnectPtr conn,
15787 15788 15789 15790 15791
                       int cellNum,
                       virNodeMemoryStatsPtr params,
                       int *nparams,
                       unsigned int flags)
{
15792 15793 15794
    if (virNodeGetMemoryStatsEnsureACL(conn) < 0)
        return -1;

15795 15796 15797 15798 15799
    return nodeGetMemoryStats(cellNum, params, nparams, flags);
}


static int
15800
qemuNodeGetCellsFreeMemory(virConnectPtr conn,
15801 15802 15803 15804
                           unsigned long long *freeMems,
                           int startCell,
                           int maxCells)
{
15805 15806 15807
    if (virNodeGetCellsFreeMemoryEnsureACL(conn) < 0)
        return -1;

15808 15809 15810 15811 15812
    return nodeGetCellsFreeMemory(freeMems, startCell, maxCells);
}


static unsigned long long
15813
qemuNodeGetFreeMemory(virConnectPtr conn)
15814
{
15815 15816 15817
    if (virNodeGetFreeMemoryEnsureACL(conn) < 0)
        return 0;

15818 15819 15820 15821 15822
    return nodeGetFreeMemory();
}


static int
15823
qemuNodeGetMemoryParameters(virConnectPtr conn,
15824 15825 15826 15827
                            virTypedParameterPtr params,
                            int *nparams,
                            unsigned int flags)
{
15828 15829 15830
    if (virNodeGetMemoryParametersEnsureACL(conn) < 0)
        return -1;

15831 15832 15833 15834 15835
    return nodeGetMemoryParameters(params, nparams, flags);
}


static int
15836
qemuNodeSetMemoryParameters(virConnectPtr conn,
15837 15838 15839 15840
                            virTypedParameterPtr params,
                            int nparams,
                            unsigned int flags)
{
15841 15842 15843
    if (virNodeSetMemoryParametersEnsureACL(conn) < 0)
        return -1;

15844 15845 15846 15847 15848
    return nodeSetMemoryParameters(params, nparams, flags);
}


static int
15849
qemuNodeGetCPUMap(virConnectPtr conn,
15850 15851 15852 15853
                  unsigned char **cpumap,
                  unsigned int *online,
                  unsigned int flags)
{
15854 15855 15856
    if (virNodeGetCPUMapEnsureACL(conn) < 0)
        return -1;

15857 15858 15859
    return nodeGetCPUMap(cpumap, online, flags);
}

15860 15861

static int
15862
qemuNodeSuspendForDuration(virConnectPtr conn,
15863 15864 15865 15866
                           unsigned int target,
                           unsigned long long duration,
                           unsigned int flags)
{
15867 15868 15869
    if (virNodeSuspendForDurationEnsureACL(conn) < 0)
        return -1;

15870 15871 15872 15873
    return nodeSuspendForDuration(target, duration, flags);
}


15874
static virDriver qemuDriver = {
15875
    .no = VIR_DRV_QEMU,
15876
    .name = QEMU_DRIVER_NAME,
15877 15878 15879 15880 15881
    .connectOpen = qemuConnectOpen, /* 0.2.0 */
    .connectClose = qemuConnectClose, /* 0.2.0 */
    .connectSupportsFeature = qemuConnectSupportsFeature, /* 0.5.0 */
    .connectGetType = qemuConnectGetType, /* 0.2.0 */
    .connectGetVersion = qemuConnectGetVersion, /* 0.2.0 */
15882
    .connectGetHostname = qemuConnectGetHostname, /* 0.3.3 */
15883 15884
    .connectGetSysinfo = qemuConnectGetSysinfo, /* 0.8.8 */
    .connectGetMaxVcpus = qemuConnectGetMaxVcpus, /* 0.2.1 */
15885
    .nodeGetInfo = qemuNodeGetInfo, /* 0.2.0 */
15886 15887 15888 15889 15890
    .connectGetCapabilities = qemuConnectGetCapabilities, /* 0.2.1 */
    .connectListDomains = qemuConnectListDomains, /* 0.2.0 */
    .connectNumOfDomains = qemuConnectNumOfDomains, /* 0.2.0 */
    .connectListAllDomains = qemuConnectListAllDomains, /* 0.9.13 */
    .domainCreateXML = qemuDomainCreateXML, /* 0.2.0 */
15891 15892 15893 15894 15895
    .domainLookupByID = qemuDomainLookupByID, /* 0.2.0 */
    .domainLookupByUUID = qemuDomainLookupByUUID, /* 0.2.0 */
    .domainLookupByName = qemuDomainLookupByName, /* 0.2.0 */
    .domainSuspend = qemuDomainSuspend, /* 0.2.0 */
    .domainResume = qemuDomainResume, /* 0.2.0 */
15896
    .domainShutdown = qemuDomainShutdown, /* 0.2.0 */
15897
    .domainShutdownFlags = qemuDomainShutdownFlags, /* 0.9.10 */
15898
    .domainReboot = qemuDomainReboot, /* 0.9.3 */
15899
    .domainReset = qemuDomainReset, /* 0.9.7 */
15900 15901
    .domainDestroy = qemuDomainDestroy, /* 0.2.0 */
    .domainDestroyFlags = qemuDomainDestroyFlags, /* 0.9.4 */
15902
    .domainGetOSType = qemuDomainGetOSType, /* 0.2.2 */
15903
    .domainGetMaxMemory = qemuDomainGetMaxMemory, /* 0.4.2 */
15904 15905 15906
    .domainSetMaxMemory = qemuDomainSetMaxMemory, /* 0.4.2 */
    .domainSetMemory = qemuDomainSetMemory, /* 0.4.2 */
    .domainSetMemoryFlags = qemuDomainSetMemoryFlags, /* 0.9.0 */
15907 15908 15909 15910
    .domainSetMemoryParameters = qemuDomainSetMemoryParameters, /* 0.8.5 */
    .domainGetMemoryParameters = qemuDomainGetMemoryParameters, /* 0.8.5 */
    .domainSetBlkioParameters = qemuDomainSetBlkioParameters, /* 0.9.0 */
    .domainGetBlkioParameters = qemuDomainGetBlkioParameters, /* 0.9.0 */
15911
    .domainGetInfo = qemuDomainGetInfo, /* 0.2.0 */
15912
    .domainGetState = qemuDomainGetState, /* 0.9.2 */
15913
    .domainGetControlInfo = qemuDomainGetControlInfo, /* 0.9.3 */
15914 15915
    .domainSave = qemuDomainSave, /* 0.2.0 */
    .domainSaveFlags = qemuDomainSaveFlags, /* 0.9.4 */
15916
    .domainRestore = qemuDomainRestore, /* 0.2.0 */
15917
    .domainRestoreFlags = qemuDomainRestoreFlags, /* 0.9.4 */
15918 15919
    .domainSaveImageGetXMLDesc = qemuDomainSaveImageGetXMLDesc, /* 0.9.4 */
    .domainSaveImageDefineXML = qemuDomainSaveImageDefineXML, /* 0.9.4 */
15920
    .domainCoreDump = qemuDomainCoreDump, /* 0.7.0 */
15921
    .domainScreenshot = qemuDomainScreenshot, /* 0.9.2 */
15922 15923
    .domainSetVcpus = qemuDomainSetVcpus, /* 0.4.4 */
    .domainSetVcpusFlags = qemuDomainSetVcpusFlags, /* 0.8.5 */
15924 15925 15926 15927 15928 15929 15930 15931 15932
    .domainGetVcpusFlags = qemuDomainGetVcpusFlags, /* 0.8.5 */
    .domainPinVcpu = qemuDomainPinVcpu, /* 0.4.4 */
    .domainPinVcpuFlags = qemuDomainPinVcpuFlags, /* 0.9.3 */
    .domainGetVcpuPinInfo = qemuDomainGetVcpuPinInfo, /* 0.9.3 */
    .domainPinEmulator = qemuDomainPinEmulator, /* 0.10.0 */
    .domainGetEmulatorPinInfo = qemuDomainGetEmulatorPinInfo, /* 0.10.0 */
    .domainGetVcpus = qemuDomainGetVcpus, /* 0.4.4 */
    .domainGetMaxVcpus = qemuDomainGetMaxVcpus, /* 0.4.4 */
    .domainGetSecurityLabel = qemuDomainGetSecurityLabel, /* 0.6.1 */
M
Marcelo Cerri 已提交
15933
    .domainGetSecurityLabelList = qemuDomainGetSecurityLabelList, /* 0.10.0 */
15934
    .nodeGetSecurityModel = qemuNodeGetSecurityModel, /* 0.6.1 */
15935
    .domainGetXMLDesc = qemuDomainGetXMLDesc, /* 0.2.0 */
15936 15937 15938 15939 15940 15941 15942
    .connectDomainXMLFromNative = qemuConnectDomainXMLFromNative, /* 0.6.4 */
    .connectDomainXMLToNative = qemuConnectDomainXMLToNative, /* 0.6.4 */
    .connectListDefinedDomains = qemuConnectListDefinedDomains, /* 0.2.0 */
    .connectNumOfDefinedDomains = qemuConnectNumOfDefinedDomains, /* 0.2.0 */
    .domainCreate = qemuDomainCreate, /* 0.2.0 */
    .domainCreateWithFlags = qemuDomainCreateWithFlags, /* 0.8.2 */
    .domainDefineXML = qemuDomainDefineXML, /* 0.2.0 */
15943
    .domainUndefine = qemuDomainUndefine, /* 0.2.0 */
15944
    .domainUndefineFlags = qemuDomainUndefineFlags, /* 0.9.4 */
15945 15946 15947 15948 15949
    .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 */
15950 15951
    .domainGetAutostart = qemuDomainGetAutostart, /* 0.2.1 */
    .domainSetAutostart = qemuDomainSetAutostart, /* 0.2.1 */
15952 15953 15954 15955 15956
    .domainGetSchedulerType = qemuDomainGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = qemuDomainGetSchedulerParameters, /* 0.7.0 */
    .domainGetSchedulerParametersFlags = qemuDomainGetSchedulerParametersFlags, /* 0.9.2 */
    .domainSetSchedulerParameters = qemuDomainSetSchedulerParameters, /* 0.7.0 */
    .domainSetSchedulerParametersFlags = qemuDomainSetSchedulerParametersFlags, /* 0.9.2 */
15957
    .domainMigratePerform = qemuDomainMigratePerform, /* 0.5.0 */
15958
    .domainBlockResize = qemuDomainBlockResize, /* 0.9.8 */
15959 15960
    .domainBlockStats = qemuDomainBlockStats, /* 0.4.1 */
    .domainBlockStatsFlags = qemuDomainBlockStatsFlags, /* 0.9.5 */
15961 15962 15963 15964
    .domainInterfaceStats = qemuDomainInterfaceStats, /* 0.4.1 */
    .domainMemoryStats = qemuDomainMemoryStats, /* 0.7.5 */
    .domainBlockPeek = qemuDomainBlockPeek, /* 0.4.4 */
    .domainMemoryPeek = qemuDomainMemoryPeek, /* 0.4.4 */
15965
    .domainGetBlockInfo = qemuDomainGetBlockInfo, /* 0.8.1 */
15966 15967 15968 15969
    .nodeGetCPUStats = qemuNodeGetCPUStats, /* 0.9.3 */
    .nodeGetMemoryStats = qemuNodeGetMemoryStats, /* 0.9.3 */
    .nodeGetCellsFreeMemory = qemuNodeGetCellsFreeMemory, /* 0.4.4 */
    .nodeGetFreeMemory = qemuNodeGetFreeMemory, /* 0.4.4 */
15970 15971
    .connectDomainEventRegister = qemuConnectDomainEventRegister, /* 0.5.0 */
    .connectDomainEventDeregister = qemuConnectDomainEventDeregister, /* 0.5.0 */
15972 15973 15974
    .domainMigratePrepare2 = qemuDomainMigratePrepare2, /* 0.5.0 */
    .domainMigrateFinish2 = qemuDomainMigrateFinish2, /* 0.5.0 */
    .nodeDeviceDettach = qemuNodeDeviceDettach, /* 0.6.1 */
15975
    .nodeDeviceDetachFlags = qemuNodeDeviceDetachFlags, /* 1.0.5 */
15976 15977 15978
    .nodeDeviceReAttach = qemuNodeDeviceReAttach, /* 0.6.1 */
    .nodeDeviceReset = qemuNodeDeviceReset, /* 0.6.1 */
    .domainMigratePrepareTunnel = qemuDomainMigratePrepareTunnel, /* 0.7.2 */
15979 15980
    .connectIsEncrypted = qemuConnectIsEncrypted, /* 0.7.3 */
    .connectIsSecure = qemuConnectIsSecure, /* 0.7.3 */
15981 15982 15983
    .domainIsActive = qemuDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = qemuDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = qemuDomainIsUpdated, /* 0.8.6 */
15984 15985
    .connectCompareCPU = qemuConnectCompareCPU, /* 0.7.5 */
    .connectBaselineCPU = qemuConnectBaselineCPU, /* 0.7.7 */
15986
    .domainGetJobInfo = qemuDomainGetJobInfo, /* 0.7.7 */
15987
    .domainGetJobStats = qemuDomainGetJobStats, /* 1.0.3 */
15988 15989
    .domainAbortJob = qemuDomainAbortJob, /* 0.7.7 */
    .domainMigrateSetMaxDowntime = qemuDomainMigrateSetMaxDowntime, /* 0.8.0 */
15990 15991
    .domainMigrateGetCompressionCache = qemuDomainMigrateGetCompressionCache, /* 1.0.3 */
    .domainMigrateSetCompressionCache = qemuDomainMigrateSetCompressionCache, /* 1.0.3 */
15992
    .domainMigrateSetMaxSpeed = qemuDomainMigrateSetMaxSpeed, /* 0.9.0 */
15993
    .domainMigrateGetMaxSpeed = qemuDomainMigrateGetMaxSpeed, /* 0.9.5 */
15994 15995
    .connectDomainEventRegisterAny = qemuConnectDomainEventRegisterAny, /* 0.8.0 */
    .connectDomainEventDeregisterAny = qemuConnectDomainEventDeregisterAny, /* 0.8.0 */
15996 15997 15998 15999 16000 16001 16002
    .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 */
16003
    .domainListAllSnapshots = qemuDomainListAllSnapshots, /* 0.9.13 */
16004 16005
    .domainSnapshotNumChildren = qemuDomainSnapshotNumChildren, /* 0.9.7 */
    .domainSnapshotListChildrenNames = qemuDomainSnapshotListChildrenNames, /* 0.9.7 */
16006
    .domainSnapshotListAllChildren = qemuDomainSnapshotListAllChildren, /* 0.9.13 */
16007 16008
    .domainSnapshotLookupByName = qemuDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = qemuDomainHasCurrentSnapshot, /* 0.8.0 */
16009
    .domainSnapshotGetParent = qemuDomainSnapshotGetParent, /* 0.9.7 */
16010
    .domainSnapshotCurrent = qemuDomainSnapshotCurrent, /* 0.8.0 */
16011 16012
    .domainSnapshotIsCurrent = qemuDomainSnapshotIsCurrent, /* 0.9.13 */
    .domainSnapshotHasMetadata = qemuDomainSnapshotHasMetadata, /* 0.9.13 */
16013 16014
    .domainRevertToSnapshot = qemuDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = qemuDomainSnapshotDelete, /* 0.8.0 */
16015 16016 16017
    .domainQemuMonitorCommand = qemuDomainQemuMonitorCommand, /* 0.8.3 */
    .domainQemuAttach = qemuDomainQemuAttach, /* 0.9.4 */
    .domainQemuAgentCommand = qemuDomainQemuAgentCommand, /* 0.10.0 */
16018
    .domainOpenConsole = qemuDomainOpenConsole, /* 0.8.6 */
16019
    .domainOpenGraphics = qemuDomainOpenGraphics, /* 0.9.7 */
16020
    .domainInjectNMI = qemuDomainInjectNMI, /* 0.9.2 */
16021 16022 16023 16024 16025 16026
    .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 */
16027
    .domainSendKey = qemuDomainSendKey, /* 0.9.4 */
16028 16029 16030 16031
    .domainBlockJobAbort = qemuDomainBlockJobAbort, /* 0.9.4 */
    .domainGetBlockJobInfo = qemuDomainGetBlockJobInfo, /* 0.9.4 */
    .domainBlockJobSetSpeed = qemuDomainBlockJobSetSpeed, /* 0.9.4 */
    .domainBlockPull = qemuDomainBlockPull, /* 0.9.4 */
16032
    .domainBlockRebase = qemuDomainBlockRebase, /* 0.9.10 */
16033
    .domainBlockCommit = qemuDomainBlockCommit, /* 1.0.0 */
16034
    .connectIsAlive = qemuConnectIsAlive, /* 0.9.8 */
16035
    .nodeSuspendForDuration = qemuNodeSuspendForDuration, /* 0.9.8 */
16036 16037
    .domainSetBlockIoTune = qemuDomainSetBlockIoTune, /* 0.9.8 */
    .domainGetBlockIoTune = qemuDomainGetBlockIoTune, /* 0.9.8 */
16038 16039
    .domainSetNumaParameters = qemuDomainSetNumaParameters, /* 0.9.9 */
    .domainGetNumaParameters = qemuDomainGetNumaParameters, /* 0.9.9 */
16040 16041
    .domainGetInterfaceParameters = qemuDomainGetInterfaceParameters, /* 0.9.9 */
    .domainSetInterfaceParameters = qemuDomainSetInterfaceParameters, /* 0.9.9 */
16042
    .domainGetDiskErrors = qemuDomainGetDiskErrors, /* 0.9.10 */
16043 16044
    .domainSetMetadata = qemuDomainSetMetadata, /* 0.9.10 */
    .domainGetMetadata = qemuDomainGetMetadata, /* 0.9.10 */
16045
    .domainPMSuspendForDuration = qemuDomainPMSuspendForDuration, /* 0.9.11 */
16046
    .domainPMWakeup = qemuDomainPMWakeup, /* 0.9.11 */
16047
    .domainGetCPUStats = qemuDomainGetCPUStats, /* 0.9.11 */
16048 16049 16050
    .nodeGetMemoryParameters = qemuNodeGetMemoryParameters, /* 0.10.2 */
    .nodeSetMemoryParameters = qemuNodeSetMemoryParameters, /* 0.10.2 */
    .nodeGetCPUMap = qemuNodeGetCPUMap, /* 1.0.0 */
M
Michal Privoznik 已提交
16051
    .domainFSTrim = qemuDomainFSTrim, /* 1.0.1 */
16052
    .domainOpenChannel = qemuDomainOpenChannel, /* 1.0.2 */
16053 16054 16055 16056 16057 16058
    .domainMigrateBegin3Params = qemuDomainMigrateBegin3Params, /* 1.1.0 */
    .domainMigratePrepare3Params = qemuDomainMigratePrepare3Params, /* 1.1.0 */
    .domainMigratePrepareTunnel3Params = qemuDomainMigratePrepareTunnel3Params, /* 1.1.0 */
    .domainMigratePerform3Params = qemuDomainMigratePerform3Params, /* 1.1.0 */
    .domainMigrateFinish3Params = qemuDomainMigrateFinish3Params, /* 1.1.0 */
    .domainMigrateConfirm3Params = qemuDomainMigrateConfirm3Params, /* 1.1.0 */
16059 16060 16061
};


16062
static virStateDriver qemuStateDriver = {
16063
    .name = "QEMU",
16064 16065 16066 16067
    .stateInitialize = qemuStateInitialize,
    .stateCleanup = qemuStateCleanup,
    .stateReload = qemuStateReload,
    .stateStop = qemuStateStop,
16068
};
16069

16070
int qemuRegister(void) {
16071 16072 16073 16074
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
    return 0;
}